Add a filter-by-from/to-chunk in ExitManager::List.
[UnsignedByte.git] / src / Sqlite3 / sqlite3.c
blobe7cc2f17f14f16b4c21f1023c29b47e444440950
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.4.0. By combining all the individual C code files into this
4 ** single large file, the entire code can be compiled as a one translation
5 ** unit. This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately. Performance improvements
7 ** of 5% are more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
9 **
10 ** This file is all you need to compile SQLite. To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library. (If you do not have
13 ** the "sqlite3.h" header file at hand, you will find a copy in the first
14 ** 2679 lines past this header comment.) Additional code files may be
15 ** needed if you want a wrapper to interface SQLite with your choice of
16 ** programming language. The code for the "sqlite3" command-line shell
17 ** is also in a separate file. This file contains only code for the core
18 ** SQLite library.
20 ** This amalgamation was generated on 2007-06-18 17:44:42 UTC.
22 #define SQLITE_AMALGAMATION 1
23 /************** Begin file sqlite3.h *****************************************/
25 ** 2001 September 15
27 ** The author disclaims copyright to this source code. In place of
28 ** a legal notice, here is a blessing:
30 ** May you do good and not evil.
31 ** May you find forgiveness for yourself and forgive others.
32 ** May you share freely, never taking more than you give.
34 *************************************************************************
35 ** This header file defines the interface that the SQLite library
36 ** presents to client programs. If a C-function, structure, datatype,
37 ** or constant definition does not appear in this file, then it is
38 ** not a published API of SQLite, is subject to change without
39 ** notice, and should not be referenced by programs that use SQLite.
41 ** Some of the definitions that are in this file are marked as
42 ** "experimental". Experimental interfaces are normally new
43 ** features recently added to SQLite. We do not anticipate changes
44 ** to experimental interfaces but reserve to make minor changes if
45 ** experience from use "in the wild" suggest such changes are prudent.
47 ** The official C-language API documentation for SQLite is derived
48 ** from comments in this file. This file is the authoritative source
49 ** on how SQLite interfaces are suppose to operate.
51 ** The name of this file under configuration management is "sqlite.h.in".
52 ** The makefile makes some minor changes to this file (such as inserting
53 ** the version number) and changes its name to "sqlite3.h" as
54 ** part of the build process.
56 ** @(#) $Id: sqlite.h.in,v 1.212 2007/06/14 20:57:19 drh Exp $
58 #ifndef _SQLITE3_H_
59 #define _SQLITE3_H_
60 #include <stdarg.h> /* Needed for the definition of va_list */
63 ** Make sure we can call this stuff from C++.
65 #if 0
66 extern "C" {
67 #endif
70 ** Make sure these symbols where not defined by some previous header
71 ** file.
73 #ifdef SQLITE_VERSION
74 # undef SQLITE_VERSION
75 #endif
76 #ifdef SQLITE_VERSION_NUMBER
77 # undef SQLITE_VERSION_NUMBER
78 #endif
81 ** CAPI3REF: Compile-Time Library Version Numbers
83 ** The version of the SQLite library is contained in the sqlite3.h
84 ** header file in a #define named SQLITE_VERSION. The SQLITE_VERSION
85 ** macro resolves to a string constant.
87 ** The format of the version string is "X.Y.Z", where
88 ** X is the major version number, Y is the minor version number and Z
89 ** is the release number. The X.Y.Z might be followed by "alpha" or "beta".
90 ** For example "3.1.1beta".
92 ** The X value is always 3 in SQLite. The X value only changes when
93 ** backwards compatibility is broken and we intend to never break
94 ** backwards compatibility. The Y value only changes when
95 ** there are major feature enhancements that are forwards compatible
96 ** but not backwards compatible. The Z value is incremented with
97 ** each release but resets back to 0 when Y is incremented.
99 ** The SQLITE_VERSION_NUMBER is an integer with the value
100 ** (X*1000000 + Y*1000 + Z). For example, for version "3.1.1beta",
101 ** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using
102 ** version 3.1.1 or greater at compile time, programs may use the test
103 ** (SQLITE_VERSION_NUMBER>=3001001).
105 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
107 #define SQLITE_VERSION "3.4.0"
108 #define SQLITE_VERSION_NUMBER 3004000
111 ** CAPI3REF: Run-Time Library Version Numbers
113 ** These routines return values equivalent to the header constants
114 ** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER]. The values returned
115 ** by this routines should only be different from the header values
116 ** if you compile your program using an sqlite3.h header from a
117 ** different version of SQLite that the version of the library you
118 ** link against.
120 ** The sqlite3_version[] string constant contains the text of the
121 ** [SQLITE_VERSION] string. The sqlite3_libversion() function returns
122 ** a poiner to the sqlite3_version[] string constant. The function
123 ** is provided for DLL users who can only access functions and not
124 ** constants within the DLL.
126 extern const char sqlite3_version[];
127 const char *sqlite3_libversion(void);
128 int sqlite3_libversion_number(void);
131 ** CAPI3REF: Database Connection Handle
133 ** Each open SQLite database is represented by pointer to an instance of the
134 ** opaque structure named "sqlite3". It is useful to think of an sqlite3
135 ** pointer as an object. The [sqlite3_open] interface is its constructor
136 ** and [sqlite3_close] is its destructor. There are many other interfaces
137 ** (such as [sqlite3_prepare_v2], [sqlite3_create_function], and
138 ** [sqlite3_busy_timeout] to name but three) that are methods on this
139 ** object.
141 typedef struct sqlite3 sqlite3;
145 ** CAPI3REF: 64-Bit Integer Types
147 ** Some compilers do not support the "long long" datatype. So we have
148 ** to do compiler-specific typedefs for 64-bit signed and unsigned integers.
150 ** Many SQLite interface functions require a 64-bit integer arguments.
151 ** Those interfaces are declared using this typedef.
153 #ifdef SQLITE_INT64_TYPE
154 typedef SQLITE_INT64_TYPE sqlite_int64;
155 typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
156 #elif defined(_MSC_VER) || defined(__BORLANDC__)
157 typedef __int64 sqlite_int64;
158 typedef unsigned __int64 sqlite_uint64;
159 #else
160 typedef long long int sqlite_int64;
161 typedef unsigned long long int sqlite_uint64;
162 #endif
165 ** If compiling for a processor that lacks floating point support,
166 ** substitute integer for floating-point
168 #ifdef SQLITE_OMIT_FLOATING_POINT
169 # define double sqlite_int64
170 #endif
173 ** CAPI3REF: Closing A Database Connection
175 ** Call this function with a pointer to a structure that was previously
176 ** returned from [sqlite3_open()] and the corresponding database will by
177 ** closed.
179 ** All SQL statements prepared using [sqlite3_prepare_v2()] or
180 ** [sqlite3_prepare16_v2()] must be destroyed using [sqlite3_finalize()]
181 ** before this routine is called. Otherwise, SQLITE_BUSY is returned and the
182 ** database connection remains open.
184 int sqlite3_close(sqlite3 *);
187 ** The type for a callback function.
188 ** This is legacy and deprecated. It is included for historical
189 ** compatibility and is not documented.
191 typedef int (*sqlite3_callback)(void*,int,char**, char**);
194 ** CAPI3REF: One-Step Query Execution Interface
196 ** This interface is used to do a one-time evaluatation of zero
197 ** or more SQL statements. UTF-8 text of the SQL statements to
198 ** be evaluted is passed in as the second parameter. The statements
199 ** are prepared one by one using [sqlite3_prepare()], evaluated
200 ** using [sqlite3_step()], then destroyed using [sqlite3_finalize()].
202 ** If one or more of the SQL statements are queries, then
203 ** the callback function specified by the 3rd parameter is
204 ** invoked once for each row of the query result. This callback
205 ** should normally return 0. If the callback returns a non-zero
206 ** value then the query is aborted, all subsequent SQL statements
207 ** are skipped and the sqlite3_exec() function returns the SQLITE_ABORT.
209 ** The 4th parameter to this interface is an arbitrary pointer that is
210 ** passed through to the callback function as its first parameter.
212 ** The 2nd parameter to the callback function is the number of
213 ** columns in the query result. The 3rd parameter to the callback
214 ** is an array of strings holding the values for each column
215 ** as extracted using [sqlite3_column_text()].
216 ** The 4th parameter to the callback is an array of strings
217 ** obtained using [sqlite3_column_name()] and holding
218 ** the names of each column.
220 ** The callback function may be NULL, even for queries. A NULL
221 ** callback is not an error. It just means that no callback
222 ** will be invoked.
224 ** If an error occurs while parsing or evaluating the SQL (but
225 ** not while executing the callback) then an appropriate error
226 ** message is written into memory obtained from [sqlite3_malloc()] and
227 ** *errmsg is made to point to that message. The calling function
228 ** is responsible for freeing the memory that holds the error
229 ** message. Use [sqlite3_free()] for this. If errmsg==NULL,
230 ** then no error message is ever written.
232 ** The return value is is SQLITE_OK if there are no errors and
233 ** some other [SQLITE_OK | return code] if there is an error.
234 ** The particular return value depends on the type of error.
237 int sqlite3_exec(
238 sqlite3*, /* An open database */
239 const char *sql, /* SQL to be evaluted */
240 int (*callback)(void*,int,char**,char**), /* Callback function */
241 void *, /* 1st argument to callback */
242 char **errmsg /* Error msg written here */
246 ** CAPI3REF: Result Codes
247 ** KEYWORDS: SQLITE_OK
249 ** Many SQLite functions return an integer result code from the set shown
250 ** above in order to indicates success or failure.
252 ** The result codes above are the only ones returned by SQLite in its
253 ** default configuration. However, the [sqlite3_extended_result_codes()]
254 ** API can be used to set a database connectoin to return more detailed
255 ** result codes.
257 ** See also: [SQLITE_IOERR_READ | extended result codes]
260 #define SQLITE_OK 0 /* Successful result */
261 /* beginning-of-error-codes */
262 #define SQLITE_ERROR 1 /* SQL error or missing database */
263 #define SQLITE_INTERNAL 2 /* NOT USED. Internal logic error in SQLite */
264 #define SQLITE_PERM 3 /* Access permission denied */
265 #define SQLITE_ABORT 4 /* Callback routine requested an abort */
266 #define SQLITE_BUSY 5 /* The database file is locked */
267 #define SQLITE_LOCKED 6 /* A table in the database is locked */
268 #define SQLITE_NOMEM 7 /* A malloc() failed */
269 #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
270 #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
271 #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
272 #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
273 #define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */
274 #define SQLITE_FULL 13 /* Insertion failed because database is full */
275 #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
276 #define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */
277 #define SQLITE_EMPTY 16 /* Database is empty */
278 #define SQLITE_SCHEMA 17 /* The database schema changed */
279 #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
280 #define SQLITE_CONSTRAINT 19 /* Abort due to contraint violation */
281 #define SQLITE_MISMATCH 20 /* Data type mismatch */
282 #define SQLITE_MISUSE 21 /* Library used incorrectly */
283 #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
284 #define SQLITE_AUTH 23 /* Authorization denied */
285 #define SQLITE_FORMAT 24 /* Auxiliary database format error */
286 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
287 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
288 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
289 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
290 /* end-of-error-codes */
293 ** CAPI3REF: Extended Result Codes
295 ** In its default configuration, SQLite API routines return one of 26 integer
296 ** result codes described at result-codes. However, experience has shown that
297 ** many of these result codes are too course-grained. They do not provide as
298 ** much information about problems as users might like. In an effort to
299 ** address this, newer versions of SQLite (version 3.3.8 and later) include
300 ** support for additional result codes that provide more detailed information
301 ** about errors. The extended result codes are enabled (or disabled) for
302 ** each database
303 ** connection using the [sqlite3_extended_result_codes()] API.
305 ** Some of the available extended result codes are listed above.
306 ** We expect the number of extended result codes will be expand
307 ** over time. Software that uses extended result codes should expect
308 ** to see new result codes in future releases of SQLite.
310 ** The symbolic name for an extended result code always contains a related
311 ** primary result code as a prefix. Primary result codes contain a single
312 ** "_" character. Extended result codes contain two or more "_" characters.
313 ** The numeric value of an extended result code can be converted to its
314 ** corresponding primary result code by masking off the lower 8 bytes.
316 ** The SQLITE_OK result code will never be extended. It will always
317 ** be exactly zero.
319 #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
320 #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
321 #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
322 #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
323 #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
324 #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
325 #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
326 #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
327 #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
328 #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
329 #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
332 ** CAPI3REF: Enable Or Disable Extended Result Codes
334 ** This routine enables or disables the
335 ** [SQLITE_IOERR_READ | extended result codes] feature.
336 ** By default, SQLite API routines return one of only 26 integer
337 ** [SQLITE_OK | result codes]. When extended result codes
338 ** are enabled by this routine, the repetoire of result codes can be
339 ** much larger and can (hopefully) provide more detailed information
340 ** about the cause of an error.
342 ** The second argument is a boolean value that turns extended result
343 ** codes on and off. Extended result codes are off by default for
344 ** backwards compatibility with older versions of SQLite.
346 int sqlite3_extended_result_codes(sqlite3*, int onoff);
349 ** CAPI3REF: Last Insert Rowid
351 ** Each entry in an SQLite table has a unique 64-bit signed integer key
352 ** called the "rowid". The rowid is always available as an undeclared
353 ** column named ROWID, OID, or _ROWID_. If the table has a column of
354 ** type INTEGER PRIMARY KEY then that column is another an alias for the
355 ** rowid.
357 ** This routine returns the rowid of the most recent INSERT into
358 ** the database from the database connection given in the first
359 ** argument. If no inserts have ever occurred on this database
360 ** connection, zero is returned.
362 ** If an INSERT occurs within a trigger, then the rowid of the
363 ** inserted row is returned by this routine as long as the trigger
364 ** is running. But once the trigger terminates, the value returned
365 ** by this routine reverts to the last value inserted before the
366 ** trigger fired.
368 sqlite_int64 sqlite3_last_insert_rowid(sqlite3*);
371 ** CAPI3REF: Count The Number Of Rows Modified
373 ** This function returns the number of database rows that were changed
374 ** (or inserted or deleted) by the most recent SQL statement. Only
375 ** changes that are directly specified by the INSERT, UPDATE, or
376 ** DELETE statement are counted. Auxiliary changes caused by
377 ** triggers are not counted. Use the [sqlite3_total_changes()] function
378 ** to find the total number of changes including changes caused by triggers.
380 ** Within the body of a trigger, the sqlite3_changes() interface can be
381 ** called to find the number of
382 ** changes in the most recently completed INSERT, UPDATE, or DELETE
383 ** statement within the body of the trigger.
385 ** All changes are counted, even if they were later undone by a
386 ** ROLLBACK or ABORT. Except, changes associated with creating and
387 ** dropping tables are not counted.
389 ** If a callback invokes [sqlite3_exec()] or [sqlite3_step()] recursively,
390 ** then the changes in the inner, recursive call are counted together
391 ** with the changes in the outer call.
393 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
394 ** by dropping and recreating the table. (This is much faster than going
395 ** through and deleting individual elements form the table.) Because of
396 ** this optimization, the change count for "DELETE FROM table" will be
397 ** zero regardless of the number of elements that were originally in the
398 ** table. To get an accurate count of the number of rows deleted, use
399 ** "DELETE FROM table WHERE 1" instead.
401 int sqlite3_changes(sqlite3*);
404 ** CAPI3REF: Total Number Of Rows Modified
406 ** This function returns the number of database rows that have been
407 ** modified by INSERT, UPDATE or DELETE statements since the database handle
408 ** was opened. This includes UPDATE, INSERT and DELETE statements executed
409 ** as part of trigger programs. All changes are counted as soon as the
410 ** statement that makes them is completed (when the statement handle is
411 ** passed to [sqlite3_reset()] or [sqlite_finalise()]).
413 ** See also the [sqlite3_change()] interface.
415 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
416 ** by dropping and recreating the table. (This is much faster than going
417 ** through and deleting individual elements form the table.) Because of
418 ** this optimization, the change count for "DELETE FROM table" will be
419 ** zero regardless of the number of elements that were originally in the
420 ** table. To get an accurate count of the number of rows deleted, use
421 ** "DELETE FROM table WHERE 1" instead.
423 int sqlite3_total_changes(sqlite3*);
426 ** CAPI3REF: Interrupt A Long-Running Query
428 ** This function causes any pending database operation to abort and
429 ** return at its earliest opportunity. This routine is typically
430 ** called in response to a user action such as pressing "Cancel"
431 ** or Ctrl-C where the user wants a long query operation to halt
432 ** immediately.
434 ** It is safe to call this routine from a thread different from the
435 ** thread that is currently running the database operation.
437 ** The SQL operation that is interrupted will return [SQLITE_INTERRUPT].
438 ** If an interrupted operation was an update that is inside an
439 ** explicit transaction, then the entire transaction will be rolled
440 ** back automatically.
442 void sqlite3_interrupt(sqlite3*);
445 ** CAPI3REF: Determine If An SQL Statement Is Complete
447 ** These functions return true if the given input string comprises
448 ** one or more complete SQL statements. For the sqlite3_complete() call,
449 ** the parameter must be a nul-terminated UTF-8 string. For
450 ** sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string
451 ** is required.
453 ** These routines are useful for command-line input to determine if the
454 ** currently entered text forms one or more complete SQL statements or
455 ** if additional input is needed before sending the statements into
456 ** SQLite for parsing. The algorithm is simple. If the
457 ** last token other than spaces and comments is a semicolon, then return
458 ** true. Actually, the algorithm is a little more complicated than that
459 ** in order to deal with triggers, but the basic idea is the same: the
460 ** statement is not complete unless it ends in a semicolon.
462 int sqlite3_complete(const char *sql);
463 int sqlite3_complete16(const void *sql);
466 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
468 ** This routine identifies a callback function that might be invoked
469 ** whenever an attempt is made to open a database table
470 ** that another thread or process has locked.
471 ** If the busy callback is NULL, then [SQLITE_BUSY]
472 ** (or sometimes [SQLITE_IOERR_BLOCKED])
473 ** is returned immediately upon encountering the lock.
474 ** If the busy callback is not NULL, then the
475 ** callback will be invoked with two arguments. The
476 ** first argument to the handler is a copy of the void* pointer which
477 ** is the third argument to this routine. The second argument to
478 ** the handler is the number of times that the busy handler has
479 ** been invoked for this locking event. If the
480 ** busy callback returns 0, then no additional attempts are made to
481 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
482 ** If the callback returns non-zero, then another attempt is made to open the
483 ** database for reading and the cycle repeats.
485 ** The presence of a busy handler does not guarantee that
486 ** it will be invoked when there is lock contention.
487 ** If SQLite determines that invoking the busy handler could result in
488 ** a deadlock, it will return [SQLITE_BUSY] instead.
489 ** Consider a scenario where one process is holding a read lock that
490 ** it is trying to promote to a reserved lock and
491 ** a second process is holding a reserved lock that it is trying
492 ** to promote to an exclusive lock. The first process cannot proceed
493 ** because it is blocked by the second and the second process cannot
494 ** proceed because it is blocked by the first. If both processes
495 ** invoke the busy handlers, neither will make any progress. Therefore,
496 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
497 ** will induce the first process to release its read lock and allow
498 ** the second process to proceed.
500 ** The default busy callback is NULL.
502 ** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] when
503 ** SQLite is in the middle of a large transaction where all the
504 ** changes will not fit into the in-memory cache. SQLite will
505 ** already hold a RESERVED lock on the database file, but it needs
506 ** to promote this lock to EXCLUSIVE so that it can spill cache
507 ** pages into the database file without harm to concurrent
508 ** readers. If it is unable to promote the lock, then the in-memory
509 ** cache will be left in an inconsistent state and so the error
510 ** code is promoted from the relatively benign [SQLITE_BUSY] to
511 ** the more severe [SQLITE_IOERR_BLOCKED]. This error code promotion
512 ** forces an automatic rollback of the changes. See the
513 ** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError">
514 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
515 ** this is important.
517 ** Sqlite is re-entrant, so the busy handler may start a new query.
518 ** (It is not clear why anyone would every want to do this, but it
519 ** is allowed, in theory.) But the busy handler may not close the
520 ** database. Closing the database from a busy handler will delete
521 ** data structures out from under the executing query and will
522 ** probably result in a segmentation fault or other runtime error.
524 ** There can only be a single busy handler defined for each database
525 ** connection. Setting a new busy handler clears any previous one.
526 ** Note that calling [sqlite3_busy_timeout()] will also set or clear
527 ** the busy handler.
529 int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
532 ** CAPI3REF: Set A Busy Timeout
534 ** This routine sets a busy handler that sleeps for a while when a
535 ** table is locked. The handler will sleep multiple times until
536 ** at least "ms" milliseconds of sleeping have been done. After
537 ** "ms" milliseconds of sleeping, the handler returns 0 which
538 ** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
540 ** Calling this routine with an argument less than or equal to zero
541 ** turns off all busy handlers.
543 ** There can only be a single busy handler for a particular database
544 ** connection. If another busy handler was defined
545 ** (using [sqlite3_busy_handler()]) prior to calling
546 ** this routine, that other busy handler is cleared.
548 int sqlite3_busy_timeout(sqlite3*, int ms);
551 ** CAPI3REF: Convenience Routines For Running Queries
553 ** This next routine is a convenience wrapper around [sqlite3_exec()].
554 ** Instead of invoking a user-supplied callback for each row of the
555 ** result, this routine remembers each row of the result in memory
556 ** obtained from [sqlite3_malloc()], then returns all of the result after the
557 ** query has finished.
559 ** As an example, suppose the query result where this table:
561 ** <pre>
562 ** Name | Age
563 ** -----------------------
564 ** Alice | 43
565 ** Bob | 28
566 ** Cindy | 21
567 ** </pre>
569 ** If the 3rd argument were &azResult then after the function returns
570 ** azResult will contain the following data:
572 ** <pre>
573 ** azResult[0] = "Name";
574 ** azResult[1] = "Age";
575 ** azResult[2] = "Alice";
576 ** azResult[3] = "43";
577 ** azResult[4] = "Bob";
578 ** azResult[5] = "28";
579 ** azResult[6] = "Cindy";
580 ** azResult[7] = "21";
581 ** </pre>
583 ** Notice that there is an extra row of data containing the column
584 ** headers. But the *nrow return value is still 3. *ncolumn is
585 ** set to 2. In general, the number of values inserted into azResult
586 ** will be ((*nrow) + 1)*(*ncolumn).
588 ** After the calling function has finished using the result, it should
589 ** pass the result data pointer to sqlite3_free_table() in order to
590 ** release the memory that was malloc-ed. Because of the way the
591 ** [sqlite3_malloc()] happens, the calling function must not try to call
592 ** [sqlite3_free()] directly. Only [sqlite3_free_table()] is able to release
593 ** the memory properly and safely.
595 ** The return value of this routine is the same as from [sqlite3_exec()].
597 int sqlite3_get_table(
598 sqlite3*, /* An open database */
599 const char *sql, /* SQL to be executed */
600 char ***resultp, /* Result written to a char *[] that this points to */
601 int *nrow, /* Number of result rows written here */
602 int *ncolumn, /* Number of result columns written here */
603 char **errmsg /* Error msg written here */
605 void sqlite3_free_table(char **result);
608 ** CAPI3REF: Formatted String Printing Functions
610 ** These routines are workalikes of the "printf()" family of functions
611 ** from the standard C library.
613 ** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
614 ** results into memory obtained from [sqlite_malloc()].
615 ** The strings returned by these two routines should be
616 ** released by [sqlite3_free()]. Both routines return a
617 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
618 ** memory to hold the resulting string.
620 ** In sqlite3_snprintf() routine is similar to "snprintf()" from
621 ** the standard C library. The result is written into the
622 ** buffer supplied as the second parameter whose size is given by
623 ** the first parameter. Note that the order of the
624 ** first two parameters is reversed from snprintf(). This is an
625 ** historical accident that cannot be fixed without breaking
626 ** backwards compatibility. Note also that sqlite3_snprintf()
627 ** returns a pointer to its buffer instead of the number of
628 ** characters actually written into the buffer. We admit that
629 ** the number of characters written would be a more useful return
630 ** value but we cannot change the implementation of sqlite3_snprintf()
631 ** now without breaking compatibility.
633 ** As long as the buffer size is greater than zero, sqlite3_snprintf()
634 ** guarantees that the buffer is always zero-terminated. The first
635 ** parameter "n" is the total size of the buffer, including space for
636 ** the zero terminator. So the longest string that can be completely
637 ** written will be n-1 characters.
639 ** These routines all implement some additional formatting
640 ** options that are useful for constructing SQL statements.
641 ** All of the usual printf formatting options apply. In addition, there
642 ** is are "%q" and "%Q" options.
644 ** The %q option works like %s in that it substitutes a null-terminated
645 ** string from the argument list. But %q also doubles every '\'' character.
646 ** %q is designed for use inside a string literal. By doubling each '\''
647 ** character it escapes that character and allows it to be inserted into
648 ** the string.
650 ** For example, so some string variable contains text as follows:
652 ** <blockquote><pre>
653 ** char *zText = "It's a happy day!";
654 ** </pre></blockquote>
656 ** One can use this text in an SQL statement as follows:
658 ** <blockquote><pre>
659 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
660 ** sqlite3_exec(db, zSQL, 0, 0, 0);
661 ** sqlite3_free(zSQL);
662 ** </pre></blockquote>
664 ** Because the %q format string is used, the '\'' character in zText
665 ** is escaped and the SQL generated is as follows:
667 ** <blockquote><pre>
668 ** INSERT INTO table1 VALUES('It''s a happy day!')
669 ** </pre></blockquote>
671 ** This is correct. Had we used %s instead of %q, the generated SQL
672 ** would have looked like this:
674 ** <blockquote><pre>
675 ** INSERT INTO table1 VALUES('It's a happy day!');
676 ** </pre></blockquote>
678 ** This second example is an SQL syntax error. As a general rule you
679 ** should always use %q instead of %s when inserting text into a string
680 ** literal.
682 ** The %Q option works like %q except it also adds single quotes around
683 ** the outside of the total string. Or if the parameter in the argument
684 ** list is a NULL pointer, %Q substitutes the text "NULL" (without single
685 ** quotes) in place of the %Q option. So, for example, one could say:
687 ** <blockquote><pre>
688 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
689 ** sqlite3_exec(db, zSQL, 0, 0, 0);
690 ** sqlite3_free(zSQL);
691 ** </pre></blockquote>
693 ** The code above will render a correct SQL statement in the zSQL
694 ** variable even if the zText variable is a NULL pointer.
696 char *sqlite3_mprintf(const char*,...);
697 char *sqlite3_vmprintf(const char*, va_list);
698 char *sqlite3_snprintf(int,char*,const char*, ...);
701 ** CAPI3REF: Memory Allocation Functions
703 ** SQLite uses its own memory allocator. On some installations, this
704 ** memory allocator is identical to the standard malloc()/realloc()/free()
705 ** and can be used interchangable. On others, the implementations are
706 ** different. For maximum portability, it is best not to mix calls
707 ** to the standard malloc/realloc/free with the sqlite versions.
709 void *sqlite3_malloc(int);
710 void *sqlite3_realloc(void*, int);
711 void sqlite3_free(void*);
714 ** CAPI3REF: Compile-Time Authorization Callbacks
716 ** This routine registers a authorizer callback with the SQLite library.
717 ** The authorizer callback is invoked as SQL statements are being compiled
718 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
719 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. At various
720 ** points during the compilation process, as logic is being created
721 ** to perform various actions, the authorizer callback is invoked to
722 ** see if those actions are allowed. The authorizer callback should
723 ** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the
724 ** specific action but allow the SQL statement to continue to be
725 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
726 ** rejected with an error.
728 ** Depending on the action, the [SQLITE_IGNORE] and [SQLITE_DENY] return
729 ** codes might mean something different or they might mean the same
730 ** thing. If the action is, for example, to perform a delete opertion,
731 ** then [SQLITE_IGNORE] and [SQLITE_DENY] both cause the statement compilation
732 ** to fail with an error. But if the action is to read a specific column
733 ** from a specific table, then [SQLITE_DENY] will cause the entire
734 ** statement to fail but [SQLITE_IGNORE] will cause a NULL value to be
735 ** read instead of the actual column value.
737 ** The first parameter to the authorizer callback is a copy of
738 ** the third parameter to the sqlite3_set_authorizer() interface.
739 ** The second parameter to the callback is an integer
740 ** [SQLITE_COPY | action code] that specifies the particular action
741 ** to be authorized. The available action codes are
742 ** [SQLITE_COPY | documented separately]. The third through sixth
743 ** parameters to the callback are strings that contain additional
744 ** details about the action to be authorized.
746 ** An authorizer is used when preparing SQL statements from an untrusted
747 ** source, to ensure that the SQL statements do not try to access data
748 ** that they are not allowed to see, or that they do not try to
749 ** execute malicious statements that damage the database. For
750 ** example, an application may allow a user to enter arbitrary
751 ** SQL queries for evaluation by a database. But the application does
752 ** not want the user to be able to make arbitrary changes to the
753 ** database. An authorizer could then be put in place while the
754 ** user-entered SQL is being prepared that disallows everything
755 ** except SELECT statements.
757 ** Only a single authorizer can be in place on a database connection
758 ** at a time. Each call to sqlite3_set_authorizer overrides the
759 ** previous call. A NULL authorizer means that no authorization
760 ** callback is invoked. The default authorizer is NULL.
762 ** Note that the authorizer callback is invoked only during
763 ** [sqlite3_prepare()] or its variants. Authorization is not
764 ** performed during statement evaluation in [sqlite3_step()].
766 int sqlite3_set_authorizer(
767 sqlite3*,
768 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
769 void *pUserData
773 ** CAPI3REF: Authorizer Return Codes
775 ** The [sqlite3_set_authorizer | authorizer callback function] must
776 ** return either [SQLITE_OK] or one of these two constants in order
777 ** to signal SQLite whether or not the action is permitted. See the
778 ** [sqlite3_set_authorizer | authorizer documentation] for additional
779 ** information.
781 #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
782 #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
785 ** CAPI3REF: Authorizer Action Codes
787 ** The [sqlite3_set_authorizer()] interface registers a callback function
788 ** that is invoked to authorizer certain SQL statement actions. The
789 ** second parameter to the callback is an integer code that specifies
790 ** what action is being authorized. These are the integer action codes that
791 ** the authorizer callback may be passed.
793 ** These action code values signify what kind of operation is to be
794 ** authorized. The 3rd and 4th parameters to the authorization callback
795 ** function will be parameters or NULL depending on which of these
796 ** codes is used as the second parameter. The 5th parameter to the
797 ** authorizer callback is the name of the database ("main", "temp",
798 ** etc.) if applicable. The 6th parameter to the authorizer callback
799 ** is the name of the inner-most trigger or view that is responsible for
800 ** the access attempt or NULL if this access attempt is directly from
801 ** top-level SQL code.
803 /******************************************* 3rd ************ 4th ***********/
804 #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
805 #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
806 #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
807 #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
808 #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
809 #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
810 #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
811 #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
812 #define SQLITE_DELETE 9 /* Table Name NULL */
813 #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
814 #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
815 #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
816 #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
817 #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
818 #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
819 #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
820 #define SQLITE_DROP_VIEW 17 /* View Name NULL */
821 #define SQLITE_INSERT 18 /* Table Name NULL */
822 #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
823 #define SQLITE_READ 20 /* Table Name Column Name */
824 #define SQLITE_SELECT 21 /* NULL NULL */
825 #define SQLITE_TRANSACTION 22 /* NULL NULL */
826 #define SQLITE_UPDATE 23 /* Table Name Column Name */
827 #define SQLITE_ATTACH 24 /* Filename NULL */
828 #define SQLITE_DETACH 25 /* Database Name NULL */
829 #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
830 #define SQLITE_REINDEX 27 /* Index Name NULL */
831 #define SQLITE_ANALYZE 28 /* Table Name NULL */
832 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
833 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
834 #define SQLITE_FUNCTION 31 /* Function Name NULL */
835 #define SQLITE_COPY 0 /* No longer used */
838 ** CAPI3REF: Tracing And Profiling Functions
840 ** These routines register callback functions that can be used for
841 ** tracing and profiling the execution of SQL statements.
842 ** The callback function registered by sqlite3_trace() is invoked
843 ** at the first [sqlite3_step()] for the evaluation of an SQL statement.
844 ** The callback function registered by sqlite3_profile() is invoked
845 ** as each SQL statement finishes and includes
846 ** information on how long that statement ran.
848 ** The sqlite3_profile() API is currently considered experimental and
849 ** is subject to change.
851 void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
852 void *sqlite3_profile(sqlite3*,
853 void(*xProfile)(void*,const char*,sqlite_uint64), void*);
856 ** CAPI3REF: Query Progress Callbacks
858 ** This routine configures a callback function - the progress callback - that
859 ** is invoked periodically during long running calls to [sqlite3_exec()],
860 ** [sqlite3_step()] and [sqlite3_get_table()]. An example use for this
861 ** interface is to keep a GUI updated during a large query.
863 ** The progress callback is invoked once for every N virtual machine opcodes,
864 ** where N is the second argument to this function. The progress callback
865 ** itself is identified by the third argument to this function. The fourth
866 ** argument to this function is a void pointer passed to the progress callback
867 ** function each time it is invoked.
869 ** If a call to [sqlite3_exec()], [sqlite3_step()], or [sqlite3_get_table()]
870 ** results in fewer than N opcodes being executed, then the progress
871 ** callback is never invoked.
873 ** Only a single progress callback function may be registered for each
874 ** open database connection. Every call to sqlite3_progress_handler()
875 ** overwrites the results of the previous call.
876 ** To remove the progress callback altogether, pass NULL as the third
877 ** argument to this function.
879 ** If the progress callback returns a result other than 0, then the current
880 ** query is immediately terminated and any database changes rolled back.
881 ** The containing [sqlite3_exec()], [sqlite3_step()], or
882 ** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. This feature
883 ** can be used, for example, to implement the "Cancel" button on a
884 ** progress dialog box in a GUI.
886 void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
889 ** CAPI3REF: Opening A New Database Connection
891 ** Open the sqlite database file "filename". The "filename" is UTF-8
892 ** encoded for sqlite3_open() and UTF-16 encoded in the native byte order
893 ** for sqlite3_open16(). An [sqlite3*] handle is returned in *ppDb, even
894 ** if an error occurs. If the database is opened (or created) successfully,
895 ** then SQLITE_OK is returned. Otherwise an error code is returned. The
896 ** sqlite3_errmsg() or sqlite3_errmsg16() routines can be used to obtain
897 ** an English language description of the error.
899 ** If the database file does not exist, then a new database will be created
900 ** as needed. The default encoding for the database will be UTF-8 if
901 ** sqlite3_open() is called and UTF-16 if sqlite3_open16 is used.
903 ** Whether or not an error occurs when it is opened, resources associated
904 ** with the [sqlite3*] handle should be released by passing it to
905 ** sqlite3_close() when it is no longer required.
907 ** Note to windows users: The encoding used for the filename argument
908 ** of sqlite3_open() must be UTF-8, not whatever codepage is currently
909 ** defined. Filenames containing international characters must be converted
910 ** to UTF-8 prior to passing them into sqlite3_open().
912 int sqlite3_open(
913 const char *filename, /* Database filename (UTF-8) */
914 sqlite3 **ppDb /* OUT: SQLite db handle */
916 int sqlite3_open16(
917 const void *filename, /* Database filename (UTF-16) */
918 sqlite3 **ppDb /* OUT: SQLite db handle */
922 ** CAPI3REF: Error Codes And Messages
924 ** The sqlite3_errcode() interface returns the numeric
925 ** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code]
926 ** for the most recent failed sqlite3_* API call associated
927 ** with [sqlite3] handle 'db'. If a prior API call failed but the
928 ** most recent API call succeeded, the return value from sqlite3_errcode()
929 ** is undefined.
931 ** The sqlite3_errmsg() and sqlite3_errmsg16() return English-langauge
932 ** text that describes the error, as either UTF8 or UTF16 respectively.
933 ** Memory to hold the error message string is managed internally. The
934 ** string may be overwritten or deallocated by subsequent calls to SQLite
935 ** interface functions.
937 ** Calls to many sqlite3_* functions set the error code and string returned
938 ** by [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()]
939 ** (overwriting the previous values). Note that calls to [sqlite3_errcode()],
940 ** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the
941 ** results of future invocations. Calls to API routines that do not return
942 ** an error code (examples: [sqlite3_data_count()] or [sqlite3_mprintf()]) do
943 ** not change the error code returned by this routine.
945 ** Assuming no other intervening sqlite3_* API calls are made, the error
946 ** code returned by this function is associated with the same error as
947 ** the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()].
949 int sqlite3_errcode(sqlite3 *db);
950 const char *sqlite3_errmsg(sqlite3*);
951 const void *sqlite3_errmsg16(sqlite3*);
954 ** CAPI3REF: SQL Statement Object
956 ** Instance of this object represent single SQL statements. This
957 ** is variously known as a "prepared statement" or a
958 ** "compiled SQL statement" or simply as a "statement".
960 ** The life of a statement object goes something like this:
962 ** <ol>
963 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
964 ** function.
965 ** <li> Bind values to host parameters using
966 ** [sqlite3_bind_blob | sqlite3_bind_* interfaces].
967 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
968 ** <li> Reset the statement using [sqlite3_reset()] then go back
969 ** to step 2. Do this zero or more times.
970 ** <li> Destroy the object using [sqlite3_finalize()].
971 ** </ol>
973 ** Refer to documentation on individual methods above for additional
974 ** information.
976 typedef struct sqlite3_stmt sqlite3_stmt;
979 ** CAPI3REF: Compiling An SQL Statement
981 ** To execute an SQL query, it must first be compiled into a byte-code
982 ** program using one of these routines.
984 ** The first argument "db" is an [sqlite3 | SQLite database handle]
985 ** obtained from a prior call to [sqlite3_open()] or [sqlite3_open16()].
986 ** The second argument "zSql" is the statement to be compiled, encoded
987 ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
988 ** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
989 ** use UTF-16. If the next argument, "nBytes", is less
990 ** than zero, then zSql is read up to the first zero terminator. If
991 ** "nBytes" is not less than zero, then it is the length of the string zSql
992 ** in bytes (not characters).
994 ** *pzTail is made to point to the first byte past the end of the first
995 ** SQL statement in zSql. This routine only compiles the first statement
996 ** in zSql, so *pzTail is left pointing to what remains uncompiled.
998 ** *ppStmt is left pointing to a compiled
999 ** [sqlite3_stmt | SQL statement structure] that can be
1000 ** executed using [sqlite3_step()]. Or if there is an error, *ppStmt may be
1001 ** set to NULL. If the input text contained no SQL (if the input is and
1002 ** empty string or a comment) then *ppStmt is set to NULL. The calling
1003 ** procedure is responsible for deleting the compiled SQL statement
1004 ** using [sqlite3_finalize()] after it has finished with it.
1006 ** On success, [SQLITE_OK] is returned. Otherwise an
1007 ** [SQLITE_ERROR | error code] is returned.
1009 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
1010 ** recommended for all new programs. The two older interfaces are retained
1011 ** for backwards compatibility, but their use is discouraged.
1012 ** In the "v2" interfaces, the prepared statement
1013 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
1014 ** original SQL text. This causes the [sqlite3_step()] interface to
1015 ** behave a differently in two ways:
1017 ** <ol>
1018 ** <li>
1019 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
1020 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
1021 ** statement and try to run it again. If the schema has changed in a way
1022 ** that makes the statement no longer valid, [sqlite3_step()] will still
1023 ** return [SQLITE_SCHEMA]. But unlike the legacy behavior, [SQLITE_SCHEMA] is
1024 ** now a fatal error. Calling [sqlite3_prepare_v2()] again will not make the
1025 ** error go away. Note: use [sqlite3_errmsg()] to find the text of the parsing
1026 ** error that results in an [SQLITE_SCHEMA] return.
1027 ** </li>
1029 ** <li>
1030 ** When an error occurs,
1031 ** [sqlite3_step()] will return one of the detailed
1032 ** [SQLITE_ERROR | result codes] or
1033 ** [SQLITE_IOERR_READ | extended result codes] such as directly.
1034 ** The legacy behavior was that [sqlite3_step()] would only return a generic
1035 ** [SQLITE_ERROR] result code and you would have to make a second call to
1036 ** [sqlite3_reset()] in order to find the underlying cause of the problem.
1037 ** With the "v2" prepare interfaces, the underlying reason for the error is
1038 ** returned immediately.
1039 ** </li>
1040 ** </ol>
1042 int sqlite3_prepare(
1043 sqlite3 *db, /* Database handle */
1044 const char *zSql, /* SQL statement, UTF-8 encoded */
1045 int nBytes, /* Length of zSql in bytes. */
1046 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
1047 const char **pzTail /* OUT: Pointer to unused portion of zSql */
1049 int sqlite3_prepare_v2(
1050 sqlite3 *db, /* Database handle */
1051 const char *zSql, /* SQL statement, UTF-8 encoded */
1052 int nBytes, /* Length of zSql in bytes. */
1053 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
1054 const char **pzTail /* OUT: Pointer to unused portion of zSql */
1056 int sqlite3_prepare16(
1057 sqlite3 *db, /* Database handle */
1058 const void *zSql, /* SQL statement, UTF-16 encoded */
1059 int nBytes, /* Length of zSql in bytes. */
1060 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
1061 const void **pzTail /* OUT: Pointer to unused portion of zSql */
1063 int sqlite3_prepare16_v2(
1064 sqlite3 *db, /* Database handle */
1065 const void *zSql, /* SQL statement, UTF-16 encoded */
1066 int nBytes, /* Length of zSql in bytes. */
1067 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
1068 const void **pzTail /* OUT: Pointer to unused portion of zSql */
1072 ** CAPI3REF: Dynamically Typed Value Object
1074 ** SQLite uses dynamic typing for the values it stores. Values can
1075 ** be integers, floating point values, strings, BLOBs, or NULL. When
1076 ** passing around values internally, each value is represented as
1077 ** an instance of the sqlite3_value object.
1079 typedef struct Mem sqlite3_value;
1082 ** CAPI3REF: SQL Function Context Object
1084 ** The context in which an SQL function executes is stored in an
1085 ** sqlite3_context object. A pointer to such an object is the
1086 ** first parameter to user-defined SQL functions.
1088 typedef struct sqlite3_context sqlite3_context;
1091 ** CAPI3REF: Binding Values To Prepared Statements
1093 ** In the SQL strings input to [sqlite3_prepare_v2()] and its variants,
1094 ** one or more literals can be replace by a parameter in one of these
1095 ** forms:
1097 ** <ul>
1098 ** <li> ?
1099 ** <li> ?NNN
1100 ** <li> :AAA
1101 ** <li> @AAA
1102 ** <li> $VVV
1103 ** </ul>
1105 ** In the parameter forms shown above NNN is an integer literal,
1106 ** AAA is an alphanumeric identifier and VVV is a variable name according
1107 ** to the syntax rules of the TCL programming language.
1108 ** The values of these parameters (also called "host parameter names")
1109 ** can be set using the sqlite3_bind_*() routines defined here.
1111 ** The first argument to the sqlite3_bind_*() routines always is a pointer
1112 ** to the [sqlite3_stmt] object returned from [sqlite3_prepare_v2()] or
1113 ** its variants. The second
1114 ** argument is the index of the parameter to be set. The first parameter has
1115 ** an index of 1. When the same named parameter is used more than once, second
1116 ** and subsequent
1117 ** occurrences have the same index as the first occurrence. The index for
1118 ** named parameters can be looked up using the
1119 ** [sqlite3_bind_parameter_name()] API if desired. The index for "?NNN"
1120 ** parametes is the value of NNN.
1121 ** The NNN value must be between 1 and the compile-time
1122 ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999).
1123 ** See <a href="limits.html">limits.html</a> for additional information.
1125 ** The third argument is the value to bind to the parameter.
1127 ** In those
1128 ** routines that have a fourth argument, its value is the number of bytes
1129 ** in the parameter. To be clear: the value is the number of bytes in the
1130 ** string, not the number of characters. The number
1131 ** of bytes does not include the zero-terminator at the end of strings.
1132 ** If the fourth parameter is negative, the length of the string is
1133 ** number of bytes up to the first zero terminator.
1135 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
1136 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
1137 ** text after SQLite has finished with it. If the fifth argument is the
1138 ** special value [SQLITE_STATIC], then the library assumes that the information
1139 ** is in static, unmanaged space and does not need to be freed. If the
1140 ** fifth argument has the value [SQLITE_TRANSIENT], then SQLite makes its
1141 ** own private copy of the data immediately, before the sqlite3_bind_*()
1142 ** routine returns.
1144 ** The sqlite3_bind_zeroblob() routine binds a BLOB of length n that
1145 ** is filled with zeros. A zeroblob uses a fixed amount of memory
1146 ** (just an integer to hold it size) while it is being processed.
1147 ** Zeroblobs are intended to serve as place-holders for BLOBs whose
1148 ** content is later written using
1149 ** [sqlite3_blob_open | increment BLOB I/O] routines.
1151 ** The sqlite3_bind_*() routines must be called after
1152 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
1153 ** before [sqlite3_step()].
1154 ** Bindings are not cleared by the [sqlite3_reset()] routine.
1155 ** Unbound parameters are interpreted as NULL.
1157 ** These routines return [SQLITE_OK] on success or an error code if
1158 ** anything goes wrong. [SQLITE_RANGE] is returned if the parameter
1159 ** index is out of range. [SQLITE_NOMEM] is returned if malloc fails.
1160 ** [SQLITE_MISUSE] is returned if these routines are called on a virtual
1161 ** machine that is the wrong state or which has already been finalized.
1163 int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
1164 int sqlite3_bind_double(sqlite3_stmt*, int, double);
1165 int sqlite3_bind_int(sqlite3_stmt*, int, int);
1166 int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite_int64);
1167 int sqlite3_bind_null(sqlite3_stmt*, int);
1168 int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
1169 int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
1170 int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
1171 int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
1174 ** CAPI3REF: Number Of Host Parameters
1176 ** Return the largest host parameter index in the precompiled statement given
1177 ** as the argument. When the host parameters are of the forms like ":AAA"
1178 ** or "?", then they are assigned sequential increasing numbers beginning
1179 ** with one, so the value returned is the number of parameters. However
1180 ** if the same host parameter name is used multiple times, each occurrance
1181 ** is given the same number, so the value returned in that case is the number
1182 ** of unique host parameter names. If host parameters of the form "?NNN"
1183 ** are used (where NNN is an integer) then there might be gaps in the
1184 ** numbering and the value returned by this interface is the index of the
1185 ** host parameter with the largest index value.
1187 int sqlite3_bind_parameter_count(sqlite3_stmt*);
1190 ** CAPI3REF: Name Of A Host Parameter
1192 ** This routine returns a pointer to the name of the n-th parameter in a
1193 ** [sqlite3_stmt | prepared statement].
1194 ** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name
1195 ** which is the string ":AAA" or "@AAA" or "$VVV".
1196 ** In other words, the initial ":" or "$" or "@"
1197 ** is included as part of the name.
1198 ** Parameters of the form "?" or "?NNN" have no name.
1200 ** The first bound parameter has an index of 1, not 0.
1202 ** If the value n is out of range or if the n-th parameter is nameless,
1203 ** then NULL is returned. The returned string is always in the
1204 ** UTF-8 encoding even if the named parameter was originally specified
1205 ** as UTF-16 in [sqlite3_prepare16()] or [sqlite3_prepare16_v2()].
1207 const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
1210 ** CAPI3REF: Index Of A Parameter With A Given Name
1212 ** This routine returns the index of a host parameter with the given name.
1213 ** The name must match exactly. If no parameter with the given name is
1214 ** found, return 0. Parameter names must be UTF8.
1216 int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
1219 ** CAPI3REF: Reset All Bindings On A Prepared Statement
1221 ** Contrary to the intuition of many, [sqlite3_reset()] does not
1222 ** reset the [sqlite3_bind_blob | bindings] on a
1223 ** [sqlite3_stmt | prepared statement]. Use this routine to
1224 ** reset all host parameters to NULL.
1226 int sqlite3_clear_bindings(sqlite3_stmt*);
1229 ** CAPI3REF: Number Of Columns In A Result Set
1231 ** Return the number of columns in the result set returned by the
1232 ** [sqlite3_stmt | compiled SQL statement]. This routine returns 0
1233 ** if pStmt is an SQL statement that does not return data (for
1234 ** example an UPDATE).
1236 int sqlite3_column_count(sqlite3_stmt *pStmt);
1239 ** CAPI3REF: Column Names In A Result Set
1241 ** These routines return the name assigned to a particular column
1242 ** in the result set of a SELECT statement. The sqlite3_column_name()
1243 ** interface returns a pointer to a UTF8 string and sqlite3_column_name16()
1244 ** returns a pointer to a UTF16 string. The first parameter is the
1245 ** [sqlite_stmt | prepared statement] that implements the SELECT statement.
1246 ** The second parameter is the column number. The left-most column is
1247 ** number 0.
1249 ** The returned string pointer is valid until either the
1250 ** [sqlite_stmt | prepared statement] is destroyed by [sqlite3_finalize()]
1251 ** or until the next call sqlite3_column_name() or sqlite3_column_name16()
1252 ** on the same column.
1254 const char *sqlite3_column_name(sqlite3_stmt*, int N);
1255 const void *sqlite3_column_name16(sqlite3_stmt*, int N);
1258 ** CAPI3REF: Source Of Data In A Query Result
1260 ** These routines provide a means to determine what column of what
1261 ** table in which database a result of a SELECT statement comes from.
1262 ** The name of the database or table or column can be returned as
1263 ** either a UTF8 or UTF16 string. The returned string is valid until
1264 ** the [sqlite3_stmt | prepared statement] is destroyed using
1265 ** [sqlite3_finalize()] or until the same information is requested
1266 ** again about the same column.
1268 ** The first argument to the following calls is a
1269 ** [sqlite3_stmt | compiled SQL statement].
1270 ** These functions return information about the Nth column returned by
1271 ** the statement, where N is the second function argument.
1273 ** If the Nth column returned by the statement is an expression
1274 ** or subquery and is not a column value, then all of these functions
1275 ** return NULL. Otherwise, they return the
1276 ** name of the attached database, table and column that query result
1277 ** column was extracted from.
1279 ** As with all other SQLite APIs, those postfixed with "16" return UTF-16
1280 ** encoded strings, the other functions return UTF-8.
1282 ** These APIs are only available if the library was compiled with the
1283 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
1285 const char *sqlite3_column_database_name(sqlite3_stmt*,int);
1286 const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
1287 const char *sqlite3_column_table_name(sqlite3_stmt*,int);
1288 const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
1289 const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
1290 const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
1293 ** CAPI3REF: Declared Datatype Of A Query Result
1295 ** The first parameter is a [sqlite3_stmt | compiled SQL statement].
1296 ** If this statement is a SELECT statement and the Nth column of the
1297 ** returned result set of that SELECT is a table column (not an
1298 ** expression or subquery) then the declared type of the table
1299 ** column is returned. If the Nth column of the result set is an
1300 ** expression or subquery, then a NULL pointer is returned.
1301 ** The returned string is always UTF-8 encoded. For example, in
1302 ** the database schema:
1304 ** CREATE TABLE t1(c1 VARIANT);
1306 ** And the following statement compiled:
1308 ** SELECT c1 + 1, c1 FROM t1;
1310 ** Then this routine would return the string "VARIANT" for the second
1311 ** result column (i==1), and a NULL pointer for the first result column
1312 ** (i==0).
1314 ** SQLite uses dynamic run-time typing. So just because a column
1315 ** is declared to contain a particular type does not mean that the
1316 ** data stored in that column is of the declared type. SQLite is
1317 ** strongly typed, but the typing is dynamic not static. Type
1318 ** is associated with individual values, not with the containers
1319 ** used to hold those values.
1321 const char *sqlite3_column_decltype(sqlite3_stmt *, int i);
1322 const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
1325 ** CAPI3REF: Evaluate An SQL Statement
1327 ** After an [sqlite3_stmt | SQL statement] has been prepared with a call
1328 ** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of
1329 ** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()],
1330 ** then this function must be called one or more times to evaluate the
1331 ** statement.
1333 ** The details of the behavior of this sqlite3_step() interface depend
1334 ** on whether the statement was prepared using the newer "v2" interface
1335 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
1336 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
1337 ** new "v2" interface is recommended for new applications but the legacy
1338 ** interface will continue to be supported.
1340 ** In the lagacy interface, the return value will be either [SQLITE_BUSY],
1341 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
1342 ** With the "v2" interface, any of the other [SQLITE_OK | result code]
1343 ** or [SQLITE_IOERR_READ | extended result code] might be returned as
1344 ** well.
1346 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
1347 ** database locks it needs to do its job. If the statement is a COMMIT
1348 ** or occurs outside of an explicit transaction, then you can retry the
1349 ** statement. If the statement is not a COMMIT and occurs within a
1350 ** explicit transaction then you should rollback the transaction before
1351 ** continuing.
1353 ** [SQLITE_DONE] means that the statement has finished executing
1354 ** successfully. sqlite3_step() should not be called again on this virtual
1355 ** machine without first calling [sqlite3_reset()] to reset the virtual
1356 ** machine back to its initial state.
1358 ** If the SQL statement being executed returns any data, then
1359 ** [SQLITE_ROW] is returned each time a new row of data is ready
1360 ** for processing by the caller. The values may be accessed using
1361 ** the [sqlite3_column_int | column access functions].
1362 ** sqlite3_step() is called again to retrieve the next row of data.
1364 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
1365 ** violation) has occurred. sqlite3_step() should not be called again on
1366 ** the VM. More information may be found by calling [sqlite3_errmsg()].
1367 ** With the legacy interface, a more specific error code (example:
1368 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
1369 ** can be obtained by calling [sqlite3_reset()] on the
1370 ** [sqlite_stmt | prepared statement]. In the "v2" interface,
1371 ** the more specific error code is returned directly by sqlite3_step().
1373 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
1374 ** Perhaps it was called on a [sqlite_stmt | prepared statement] that has
1375 ** already been [sqlite3_finalize | finalized] or on one that had
1376 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
1377 ** be the case that the same database connection is being used by two or
1378 ** more threads at the same moment in time.
1380 ** <b>Goofy Interface Alert:</b>
1381 ** In the legacy interface,
1382 ** the sqlite3_step() API always returns a generic error code,
1383 ** [SQLITE_ERROR], following any error other than [SQLITE_BUSY]
1384 ** and [SQLITE_MISUSE]. You must call [sqlite3_reset()] or
1385 ** [sqlite3_finalize()] in order to find one of the specific
1386 ** [SQLITE_ERROR | result codes] that better describes the error.
1387 ** We admit that this is a goofy design. The problem has been fixed
1388 ** with the "v2" interface. If you prepare all of your SQL statements
1389 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
1390 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the
1391 ** more specific [SQLITE_ERROR | result codes] are returned directly
1392 ** by sqlite3_step(). The use of the "v2" interface is recommended.
1394 int sqlite3_step(sqlite3_stmt*);
1397 ** CAPI3REF:
1399 ** Return the number of values in the current row of the result set.
1401 ** After a call to [sqlite3_step()] that returns [SQLITE_ROW], this routine
1402 ** will return the same value as the [sqlite3_column_count()] function.
1403 ** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or
1404 ** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been
1405 ** called on the [sqlite_stmt | prepared statement] for the first time,
1406 ** this routine returns zero.
1408 int sqlite3_data_count(sqlite3_stmt *pStmt);
1411 ** CAPI3REF: Fundamental Datatypes
1413 ** Every value in SQLite has one of five fundamental datatypes:
1415 ** <ul>
1416 ** <li> 64-bit signed integer
1417 ** <li> 64-bit IEEE floating point number
1418 ** <li> string
1419 ** <li> BLOB
1420 ** <li> NULL
1421 ** </ul>
1423 ** These constants are codes for each of those types.
1425 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
1426 ** for a completely different meaning. Software that links against both
1427 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not
1428 ** SQLITE_TEXT.
1430 #define SQLITE_INTEGER 1
1431 #define SQLITE_FLOAT 2
1432 #define SQLITE_BLOB 4
1433 #define SQLITE_NULL 5
1434 #ifdef SQLITE_TEXT
1435 # undef SQLITE_TEXT
1436 #else
1437 # define SQLITE_TEXT 3
1438 #endif
1439 #define SQLITE3_TEXT 3
1442 ** CAPI3REF: Results Values From A Query
1444 ** These routines return information about the information
1445 ** in a single column of the current result row of a query. In every
1446 ** case the first argument is a pointer to the
1447 ** [sqlite3_stmt | SQL statement] that is being
1448 ** evaluate (the [sqlite_stmt*] that was returned from
1449 ** [sqlite3_prepare_v2()] or one of its variants) and
1450 ** the second argument is the index of the column for which information
1451 ** should be returned. The left-most column has an index of 0.
1453 ** If the SQL statement is not currently point to a valid row, or if the
1454 ** the column index is out of range, the result is undefined.
1456 ** The sqlite3_column_type() routine returns
1457 ** [SQLITE_INTEGER | datatype code] for the initial data type
1458 ** of the result column. The returned value is one of [SQLITE_INTEGER],
1459 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
1460 ** returned by sqlite3_column_type() is only meaningful if no type
1461 ** conversions have occurred as described below. After a type conversion,
1462 ** the value returned by sqlite3_column_type() is undefined. Future
1463 ** versions of SQLite may change the behavior of sqlite3_column_type()
1464 ** following a type conversion.
1466 *** The sqlite3_column_nm
1468 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
1469 ** routine returns the number of bytes in that BLOB or string.
1470 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
1471 ** the string to UTF-8 and then returns the number of bytes.
1472 ** If the result is a numeric value then sqlite3_column_bytes() uses
1473 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
1474 ** the number of bytes in that string.
1475 ** The value returned does not include the zero terminator at the end
1476 ** of the string. For clarity: the value returned is the number of
1477 ** bytes in the string, not the number of characters.
1479 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
1480 ** but leaves the result in UTF-16 instead of UTF-8.
1481 ** The zero terminator is not included in this count.
1483 ** These routines attempt to convert the value where appropriate. For
1484 ** example, if the internal representation is FLOAT and a text result
1485 ** is requested, [sqlite3_snprintf()] is used internally to do the conversion
1486 ** automatically. The following table details the conversions that
1487 ** are applied:
1489 ** <blockquote>
1490 ** <table border="1">
1491 ** <tr><th> Internal <th> Requested <th>
1492 ** <tr><th> Type <th> Type <th> Conversion
1494 ** <tr><td> NULL <td> INTEGER <td> Result is 0
1495 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
1496 ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
1497 ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
1498 ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
1499 ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
1500 ** <tr><td> INTEGER <td> BLOB <td> Same as for INTEGER->TEXT
1501 ** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
1502 ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
1503 ** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
1504 ** <tr><td> TEXT <td> INTEGER <td> Use atoi()
1505 ** <tr><td> TEXT <td> FLOAT <td> Use atof()
1506 ** <tr><td> TEXT <td> BLOB <td> No change
1507 ** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
1508 ** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
1509 ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
1510 ** </table>
1511 ** </blockquote>
1513 ** The table above makes reference to standard C library functions atoi()
1514 ** and atof(). SQLite does not really use these functions. It has its
1515 ** on equavalent internal routines. The atoi() and atof() names are
1516 ** used in the table for brevity and because they are familiar to most
1517 ** C programmers.
1519 ** Note that when type conversions occur, pointers returned by prior
1520 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
1521 ** sqlite3_column_text16() may be invalidated.
1522 ** Type conversions and pointer invalidations might occur
1523 ** in the following cases:
1525 ** <ul>
1526 ** <li><p> The initial content is a BLOB and sqlite3_column_text()
1527 ** or sqlite3_column_text16() is called. A zero-terminator might
1528 ** need to be added to the string.</p></li>
1530 ** <li><p> The initial content is UTF-8 text and sqlite3_column_bytes16() or
1531 ** sqlite3_column_text16() is called. The content must be converted
1532 ** to UTF-16.</p></li>
1534 ** <li><p> The initial content is UTF-16 text and sqlite3_column_bytes() or
1535 ** sqlite3_column_text() is called. The content must be converted
1536 ** to UTF-8.</p></li>
1537 ** </ul>
1539 ** Conversions between UTF-16be and UTF-16le are always done in place and do
1540 ** not invalidate a prior pointer, though of course the content of the buffer
1541 ** that the prior pointer points to will have been modified. Other kinds
1542 ** of conversion are done in place when it is possible, but sometime it is
1543 ** not possible and in those cases prior pointers are invalidated.
1545 ** The safest and easiest to remember policy is to invoke these routines
1546 ** in one of the following ways:
1548 ** <ul>
1549 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
1550 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
1551 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
1552 ** </ul>
1554 ** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(),
1555 ** or sqlite3_column_text16() first to force the result into the desired
1556 ** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to
1557 ** find the size of the result. Do not mix call to sqlite3_column_text() or
1558 ** sqlite3_column_blob() with calls to sqlite3_column_bytes16(). And do not
1559 ** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes().
1561 const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
1562 int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
1563 int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
1564 double sqlite3_column_double(sqlite3_stmt*, int iCol);
1565 int sqlite3_column_int(sqlite3_stmt*, int iCol);
1566 sqlite_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
1567 const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
1568 const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
1569 int sqlite3_column_type(sqlite3_stmt*, int iCol);
1570 sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
1573 ** CAPI3REF: Destroy A Prepared Statement Object
1575 ** The sqlite3_finalize() function is called to delete a
1576 ** [sqlite3_stmt | compiled SQL statement]. If the statement was
1577 ** executed successfully, or not executed at all, then SQLITE_OK is returned.
1578 ** If execution of the statement failed then an
1579 ** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code]
1580 ** is returned.
1582 ** This routine can be called at any point during the execution of the
1583 ** [sqlite3_stmt | virtual machine]. If the virtual machine has not
1584 ** completed execution when this routine is called, that is like
1585 ** encountering an error or an interrupt. (See [sqlite3_interrupt()].)
1586 ** Incomplete updates may be rolled back and transactions cancelled,
1587 ** depending on the circumstances, and the
1588 ** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT].
1590 int sqlite3_finalize(sqlite3_stmt *pStmt);
1593 ** CAPI3REF: Reset A Prepared Statement Object
1595 ** The sqlite3_reset() function is called to reset a
1596 ** [sqlite_stmt | compiled SQL statement] object.
1597 ** back to it's initial state, ready to be re-executed.
1598 ** Any SQL statement variables that had values bound to them using
1599 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
1600 ** Use [sqlite3_clear_bindings()] to reset the bindings.
1602 int sqlite3_reset(sqlite3_stmt *pStmt);
1605 ** CAPI3REF: Create Or Redefine SQL Functions
1607 ** The following two functions are used to add SQL functions or aggregates
1608 ** or to redefine the behavior of existing SQL functions or aggregates. The
1609 ** difference only between the two is that the second parameter, the
1610 ** name of the (scalar) function or aggregate, is encoded in UTF-8 for
1611 ** sqlite3_create_function() and UTF-16 for sqlite3_create_function16().
1613 ** The first argument is the [sqlite3 | database handle] that holds the
1614 ** SQL function or aggregate is to be added or redefined. If a single
1615 ** program uses more than one database handle internally, then SQL
1616 ** functions or aggregates must be added individually to each database
1617 ** handle with which they will be used.
1619 ** The second parameter is the name of the SQL function to be created
1620 ** or redefined.
1621 ** The length of the name is limited to 255 bytes, exclusive of the
1622 ** zero-terminator. Note that the name length limit is in bytes, not
1623 ** characters. Any attempt to create a function with a longer name
1624 ** will result in an SQLITE_ERROR error.
1626 ** The third parameter is the number of arguments that the SQL function or
1627 ** aggregate takes. If this parameter is negative, then the SQL function or
1628 ** aggregate may take any number of arguments.
1630 ** The fourth parameter, eTextRep, specifies what
1631 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
1632 ** its parameters. Any SQL function implementation should be able to work
1633 ** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
1634 ** more efficient with one encoding than another. It is allowed to
1635 ** invoke sqlite_create_function() or sqlite3_create_function16() multiple
1636 ** times with the same function but with different values of eTextRep.
1637 ** When multiple implementations of the same function are available, SQLite
1638 ** will pick the one that involves the least amount of data conversion.
1639 ** If there is only a single implementation which does not care what
1640 ** text encoding is used, then the fourth argument should be
1641 ** [SQLITE_ANY].
1643 ** The fifth parameter is an arbitrary pointer. The implementation
1644 ** of the function can gain access to this pointer using
1645 ** [sqlite_user_data()].
1647 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
1648 ** pointers to C-language functions that implement the SQL
1649 ** function or aggregate. A scalar SQL function requires an implementation of
1650 ** the xFunc callback only, NULL pointers should be passed as the xStep
1651 ** and xFinal parameters. An aggregate SQL function requires an implementation
1652 ** of xStep and xFinal and NULL should be passed for xFunc. To delete an
1653 ** existing SQL function or aggregate, pass NULL for all three function
1654 ** callback.
1656 ** It is permitted to register multiple implementations of the same
1657 ** functions with the same name but with either differing numbers of
1658 ** arguments or differing perferred text encodings. SQLite will use
1659 ** the implementation most closely matches the way in which the
1660 ** SQL function is used.
1662 int sqlite3_create_function(
1663 sqlite3 *,
1664 const char *zFunctionName,
1665 int nArg,
1666 int eTextRep,
1667 void*,
1668 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
1669 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
1670 void (*xFinal)(sqlite3_context*)
1672 int sqlite3_create_function16(
1673 sqlite3*,
1674 const void *zFunctionName,
1675 int nArg,
1676 int eTextRep,
1677 void*,
1678 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
1679 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
1680 void (*xFinal)(sqlite3_context*)
1684 ** CAPI3REF: Text Encodings
1686 ** These constant define integer codes that represent the various
1687 ** text encodings supported by SQLite.
1689 #define SQLITE_UTF8 1
1690 #define SQLITE_UTF16LE 2
1691 #define SQLITE_UTF16BE 3
1692 #define SQLITE_UTF16 4 /* Use native byte order */
1693 #define SQLITE_ANY 5 /* sqlite3_create_function only */
1694 #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
1697 ** CAPI3REF: Obsolete Functions
1699 ** These functions are all now obsolete. In order to maintain
1700 ** backwards compatibility with older code, we continue to support
1701 ** these functions. However, new development projects should avoid
1702 ** the use of these functions. To help encourage people to avoid
1703 ** using these functions, we are not going to tell you want they do.
1705 int sqlite3_aggregate_count(sqlite3_context*);
1706 int sqlite3_expired(sqlite3_stmt*);
1707 int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
1708 int sqlite3_global_recover(void);
1712 ** CAPI3REF: Obtaining SQL Function Parameter Values
1714 ** The C-language implementation of SQL functions and aggregates uses
1715 ** this set of interface routines to access the parameter values on
1716 ** the function or aggregate.
1718 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
1719 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
1720 ** define callbacks that implement the SQL functions and aggregates.
1721 ** The 4th parameter to these callbacks is an array of pointers to
1722 ** [sqlite3_value] objects. There is one [sqlite3_value] object for
1723 ** each parameter to the SQL function. These routines are used to
1724 ** extract values from the [sqlite3_value] objects.
1726 ** These routines work just like the corresponding
1727 ** [sqlite3_column_blob | sqlite3_column_* routines] except that
1728 ** these routines take a single [sqlite3_value*] pointer instead
1729 ** of an [sqlite3_stmt*] pointer and an integer column number.
1731 ** The sqlite3_value_text16() interface extracts a UTF16 string
1732 ** in the native byte-order of the host machine. The
1733 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
1734 ** extract UTF16 strings as big-endian and little-endian respectively.
1736 ** The sqlite3_value_numeric_type() interface attempts to apply
1737 ** numeric affinity to the value. This means that an attempt is
1738 ** made to convert the value to an integer or floating point. If
1739 ** such a conversion is possible without loss of information (in order
1740 ** words if the value is original a string that looks like a number)
1741 ** then it is done. Otherwise no conversion occurs. The
1742 ** [SQLITE_INTEGER | datatype] after conversion is returned.
1744 ** Please pay particular attention to the fact that the pointer that
1745 ** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or
1746 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
1747 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite_value_text()],
1748 ** or [sqlite3_value_text16()].
1750 const void *sqlite3_value_blob(sqlite3_value*);
1751 int sqlite3_value_bytes(sqlite3_value*);
1752 int sqlite3_value_bytes16(sqlite3_value*);
1753 double sqlite3_value_double(sqlite3_value*);
1754 int sqlite3_value_int(sqlite3_value*);
1755 sqlite_int64 sqlite3_value_int64(sqlite3_value*);
1756 const unsigned char *sqlite3_value_text(sqlite3_value*);
1757 const void *sqlite3_value_text16(sqlite3_value*);
1758 const void *sqlite3_value_text16le(sqlite3_value*);
1759 const void *sqlite3_value_text16be(sqlite3_value*);
1760 int sqlite3_value_type(sqlite3_value*);
1761 int sqlite3_value_numeric_type(sqlite3_value*);
1764 ** CAPI3REF: Obtain Aggregate Function Context
1766 ** The implementation of aggregate SQL functions use this routine to allocate
1767 ** a structure for storing their state. The first time this routine
1768 ** is called for a particular aggregate, a new structure of size nBytes
1769 ** is allocated, zeroed, and returned. On subsequent calls (for the
1770 ** same aggregate instance) the same buffer is returned. The implementation
1771 ** of the aggregate can use the returned buffer to accumulate data.
1773 ** The buffer allocated is freed automatically by SQLite whan the aggregate
1774 ** query concludes.
1776 ** The first parameter should be a copy of the
1777 ** [sqlite3_context | SQL function context] that is the first
1778 ** parameter to the callback routine that implements the aggregate
1779 ** function.
1781 void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
1784 ** CAPI3REF: User Data For Functions
1786 ** The pUserData parameter to the [sqlite3_create_function()]
1787 ** and [sqlite3_create_function16()] routines
1788 ** used to register user functions is available to
1789 ** the implementation of the function using this call.
1791 void *sqlite3_user_data(sqlite3_context*);
1794 ** CAPI3REF: Function Auxiliary Data
1796 ** The following two functions may be used by scalar SQL functions to
1797 ** associate meta-data with argument values. If the same value is passed to
1798 ** multiple invocations of the same SQL function during query execution, under
1799 ** some circumstances the associated meta-data may be preserved. This may
1800 ** be used, for example, to add a regular-expression matching scalar
1801 ** function. The compiled version of the regular expression is stored as
1802 ** meta-data associated with the SQL value passed as the regular expression
1803 ** pattern. The compiled regular expression can be reused on multiple
1804 ** invocations of the same function so that the original pattern string
1805 ** does not need to be recompiled on each invocation.
1807 ** The sqlite3_get_auxdata() interface returns a pointer to the meta-data
1808 ** associated with the Nth argument value to the current SQL function
1809 ** call, where N is the second parameter. If no meta-data has been set for
1810 ** that value, then a NULL pointer is returned.
1812 ** The sqlite3_set_auxdata() is used to associate meta-data with an SQL
1813 ** function argument. The third parameter is a pointer to the meta-data
1814 ** to be associated with the Nth user function argument value. The fourth
1815 ** parameter specifies a destructor that will be called on the meta-
1816 ** data pointer to release it when it is no longer required. If the
1817 ** destructor is NULL, it is not invoked.
1819 ** In practice, meta-data is preserved between function calls for
1820 ** expressions that are constant at compile time. This includes literal
1821 ** values and SQL variables.
1823 void *sqlite3_get_auxdata(sqlite3_context*, int);
1824 void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*));
1828 ** CAPI3REF: Constants Defining Special Destructor Behavior
1830 ** These are special value for the destructor that is passed in as the
1831 ** final argument to routines like [sqlite3_result_blob()]. If the destructor
1832 ** argument is SQLITE_STATIC, it means that the content pointer is constant
1833 ** and will never change. It does not need to be destroyed. The
1834 ** SQLITE_TRANSIENT value means that the content will likely change in
1835 ** the near future and that SQLite should make its own private copy of
1836 ** the content before returning.
1838 ** The typedef is necessary to work around problems in certain
1839 ** C++ compilers. See ticket #2191.
1841 typedef void (*sqlite3_destructor_type)(void*);
1842 #define SQLITE_STATIC ((sqlite3_destructor_type)0)
1843 #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
1846 ** CAPI3REF: Setting The Result Of An SQL Function
1848 ** These routines are used by the xFunc or xFinal callbacks that
1849 ** implement SQL functions and aggregates. See
1850 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
1851 ** for additional information.
1853 ** These functions work very much like the
1854 ** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used
1855 ** to bind values to host parameters in prepared statements.
1856 ** Refer to the
1857 ** [sqlite3_bind_blob | sqlite3_bind_* documentation] for
1858 ** additional information.
1860 ** The sqlite3_result_error() and sqlite3_result_error16() functions
1861 ** cause the implemented SQL function to throw an exception. The
1862 ** parameter to sqlite3_result_error() or sqlite3_result_error16()
1863 ** is the text of an error message.
1865 ** The sqlite3_result_toobig() cause the function implementation
1866 ** to throw and error indicating that a string or BLOB is to long
1867 ** to represent.
1869 void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
1870 void sqlite3_result_double(sqlite3_context*, double);
1871 void sqlite3_result_error(sqlite3_context*, const char*, int);
1872 void sqlite3_result_error16(sqlite3_context*, const void*, int);
1873 void sqlite3_result_error_toobig(sqlite3_context*);
1874 void sqlite3_result_int(sqlite3_context*, int);
1875 void sqlite3_result_int64(sqlite3_context*, sqlite_int64);
1876 void sqlite3_result_null(sqlite3_context*);
1877 void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
1878 void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
1879 void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
1880 void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
1881 void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
1882 void sqlite3_result_zeroblob(sqlite3_context*, int n);
1885 ** CAPI3REF: Define New Collating Sequences
1887 ** These functions are used to add new collation sequences to the
1888 ** [sqlite3*] handle specified as the first argument.
1890 ** The name of the new collation sequence is specified as a UTF-8 string
1891 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
1892 ** and a UTF-16 string for sqlite3_create_collation16(). In all cases
1893 ** the name is passed as the second function argument.
1895 ** The third argument must be one of the constants [SQLITE_UTF8],
1896 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
1897 ** routine expects to be passed pointers to strings encoded using UTF-8,
1898 ** UTF-16 little-endian or UTF-16 big-endian respectively.
1900 ** A pointer to the user supplied routine must be passed as the fifth
1901 ** argument. If it is NULL, this is the same as deleting the collation
1902 ** sequence (so that SQLite cannot call it anymore). Each time the user
1903 ** supplied function is invoked, it is passed a copy of the void* passed as
1904 ** the fourth argument to sqlite3_create_collation() or
1905 ** sqlite3_create_collation16() as its first parameter.
1907 ** The remaining arguments to the user-supplied routine are two strings,
1908 ** each represented by a [length, data] pair and encoded in the encoding
1909 ** that was passed as the third argument when the collation sequence was
1910 ** registered. The user routine should return negative, zero or positive if
1911 ** the first string is less than, equal to, or greater than the second
1912 ** string. i.e. (STRING1 - STRING2).
1914 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
1915 ** excapt that it takes an extra argument which is a destructor for
1916 ** the collation. The destructor is called when the collation is
1917 ** destroyed and is passed a copy of the fourth parameter void* pointer
1918 ** of the sqlite3_create_collation_v2(). Collations are destroyed when
1919 ** they are overridden by later calls to the collation creation functions
1920 ** or when the [sqlite3*] database handle is closed using [sqlite3_close()].
1922 ** The sqlite3_create_collation_v2() interface is experimental and
1923 ** subject to change in future releases. The other collation creation
1924 ** functions are stable.
1926 int sqlite3_create_collation(
1927 sqlite3*,
1928 const char *zName,
1929 int eTextRep,
1930 void*,
1931 int(*xCompare)(void*,int,const void*,int,const void*)
1933 int sqlite3_create_collation_v2(
1934 sqlite3*,
1935 const char *zName,
1936 int eTextRep,
1937 void*,
1938 int(*xCompare)(void*,int,const void*,int,const void*),
1939 void(*xDestroy)(void*)
1941 int sqlite3_create_collation16(
1942 sqlite3*,
1943 const char *zName,
1944 int eTextRep,
1945 void*,
1946 int(*xCompare)(void*,int,const void*,int,const void*)
1950 ** CAPI3REF: Collation Needed Callbacks
1952 ** To avoid having to register all collation sequences before a database
1953 ** can be used, a single callback function may be registered with the
1954 ** database handle to be called whenever an undefined collation sequence is
1955 ** required.
1957 ** If the function is registered using the sqlite3_collation_needed() API,
1958 ** then it is passed the names of undefined collation sequences as strings
1959 ** encoded in UTF-8. If sqlite3_collation_needed16() is used, the names
1960 ** are passed as UTF-16 in machine native byte order. A call to either
1961 ** function replaces any existing callback.
1963 ** When the callback is invoked, the first argument passed is a copy
1964 ** of the second argument to sqlite3_collation_needed() or
1965 ** sqlite3_collation_needed16(). The second argument is the database
1966 ** handle. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], or
1967 ** [SQLITE_UTF16LE], indicating the most desirable form of the collation
1968 ** sequence function required. The fourth parameter is the name of the
1969 ** required collation sequence.
1971 ** The callback function should register the desired collation using
1972 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
1973 ** [sqlite3_create_collation_v2()].
1975 int sqlite3_collation_needed(
1976 sqlite3*,
1977 void*,
1978 void(*)(void*,sqlite3*,int eTextRep,const char*)
1980 int sqlite3_collation_needed16(
1981 sqlite3*,
1982 void*,
1983 void(*)(void*,sqlite3*,int eTextRep,const void*)
1987 ** Specify the key for an encrypted database. This routine should be
1988 ** called right after sqlite3_open().
1990 ** The code to implement this API is not available in the public release
1991 ** of SQLite.
1993 int sqlite3_key(
1994 sqlite3 *db, /* Database to be rekeyed */
1995 const void *pKey, int nKey /* The key */
1999 ** Change the key on an open database. If the current database is not
2000 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
2001 ** database is decrypted.
2003 ** The code to implement this API is not available in the public release
2004 ** of SQLite.
2006 int sqlite3_rekey(
2007 sqlite3 *db, /* Database to be rekeyed */
2008 const void *pKey, int nKey /* The new key */
2012 ** CAPI3REF: Suspend Execution For A Short Time
2014 ** This function causes the current thread to suspect execution
2015 ** a number of milliseconds specified in its parameter.
2017 ** If the operating system does not support sleep requests with
2018 ** millisecond time resolution, then the time will be rounded up to
2019 ** the nearest second. The number of milliseconds of sleep actually
2020 ** requested from the operating system is returned.
2022 int sqlite3_sleep(int);
2025 ** CAPI3REF: Name Of The Folder Holding Temporary Files
2027 ** If this global variable is made to point to a string which is
2028 ** the name of a folder (a.ka. directory), then all temporary files
2029 ** created by SQLite will be placed in that directory. If this variable
2030 ** is NULL pointer, then SQLite does a search for an appropriate temporary
2031 ** file directory.
2033 ** Once [sqlite3_open()] has been called, changing this variable will
2034 ** invalidate the current temporary database, if any. Generally speaking,
2035 ** it is not safe to invoke this routine after [sqlite3_open()] has
2036 ** been called.
2038 extern char *sqlite3_temp_directory;
2041 ** CAPI3REF: Test To See If The Databse Is In Auto-Commit Mode
2043 ** Test to see whether or not the database connection is in autocommit
2044 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
2045 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
2046 ** by the next COMMIT or ROLLBACK.
2048 int sqlite3_get_autocommit(sqlite3*);
2051 ** CAPI3REF: Find The Database Handle Associated With A Prepared Statement
2053 ** Return the [sqlite3*] database handle to which a
2054 ** [sqlite3_stmt | prepared statement] belongs.
2055 ** This is the same database handle that was
2056 ** the first argument to the [sqlite3_prepare_v2()] or its variants
2057 ** that was used to create the statement in the first place.
2059 sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
2063 ** CAPI3REF: Commit And Rollback Notification Callbacks
2065 ** These routines
2066 ** register callback functions to be invoked whenever a transaction
2067 ** is committed or rolled back. The pArg argument is passed through
2068 ** to the callback. If the callback on a commit hook function
2069 ** returns non-zero, then the commit is converted into a rollback.
2071 ** If another function was previously registered, its pArg value is returned.
2072 ** Otherwise NULL is returned.
2074 ** Registering a NULL function disables the callback.
2076 ** For the purposes of this API, a transaction is said to have been
2077 ** rolled back if an explicit "ROLLBACK" statement is executed, or
2078 ** an error or constraint causes an implicit rollback to occur. The
2079 ** callback is not invoked if a transaction is automatically rolled
2080 ** back because the database connection is closed.
2082 ** These are experimental interfaces and are subject to change.
2084 void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
2085 void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
2088 ** CAPI3REF: Data Change Notification Callbacks
2090 ** Register a callback function with the database connection identified by the
2091 ** first argument to be invoked whenever a row is updated, inserted or deleted.
2092 ** Any callback set by a previous call to this function for the same
2093 ** database connection is overridden.
2095 ** The second argument is a pointer to the function to invoke when a
2096 ** row is updated, inserted or deleted. The first argument to the callback is
2097 ** a copy of the third argument to sqlite3_update_hook(). The second callback
2098 ** argument is one of SQLITE_INSERT, SQLITE_DELETE or SQLITE_UPDATE, depending
2099 ** on the operation that caused the callback to be invoked. The third and
2100 ** fourth arguments to the callback contain pointers to the database and
2101 ** table name containing the affected row. The final callback parameter is
2102 ** the rowid of the row. In the case of an update, this is the rowid after
2103 ** the update takes place.
2105 ** The update hook is not invoked when internal system tables are
2106 ** modified (i.e. sqlite_master and sqlite_sequence).
2108 ** If another function was previously registered, its pArg value is returned.
2109 ** Otherwise NULL is returned.
2111 void *sqlite3_update_hook(
2112 sqlite3*,
2113 void(*)(void *,int ,char const *,char const *,sqlite_int64),
2114 void*
2118 ** CAPI3REF: Enable Or Disable Shared Pager Cache
2120 ** This routine enables or disables the sharing of the database cache
2121 ** and schema data structures between connections to the same database.
2122 ** Sharing is enabled if the argument is true and disabled if the argument
2123 ** is false.
2125 ** Cache sharing is enabled and disabled on a thread-by-thread basis.
2126 ** Each call to this routine enables or disables cache sharing only for
2127 ** connections created in the same thread in which this routine is called.
2128 ** There is no mechanism for sharing cache between database connections
2129 ** running in different threads.
2131 ** Sharing must be disabled prior to shutting down a thread or else
2132 ** the thread will leak memory. Call this routine with an argument of
2133 ** 0 to turn off sharing. Or use the sqlite3_thread_cleanup() API.
2135 ** This routine must not be called when any database connections
2136 ** are active in the current thread. Enabling or disabling shared
2137 ** cache while there are active database connections will result
2138 ** in memory corruption.
2140 ** When the shared cache is enabled, the
2141 ** following routines must always be called from the same thread:
2142 ** [sqlite3_open()], [sqlite3_prepare_v2()], [sqlite3_step()],
2143 ** [sqlite3_reset()], [sqlite3_finalize()], and [sqlite3_close()].
2144 ** This is due to the fact that the shared cache makes use of
2145 ** thread-specific storage so that it will be available for sharing
2146 ** with other connections.
2148 ** Virtual tables cannot be used with a shared cache. When shared
2149 ** cache is enabled, the sqlite3_create_module() API used to register
2150 ** virtual tables will always return an error.
2152 ** This routine returns [SQLITE_OK] if shared cache was
2153 ** enabled or disabled successfully. An [SQLITE_ERROR | error code]
2154 ** is returned otherwise.
2156 ** Shared cache is disabled by default for backward compatibility.
2158 int sqlite3_enable_shared_cache(int);
2161 ** CAPI3REF: Attempt To Free Heap Memory
2163 ** Attempt to free N bytes of heap memory by deallocating non-essential
2164 ** memory allocations held by the database library (example: memory
2165 ** used to cache database pages to improve performance).
2167 ** This function is not a part of standard builds. It is only created
2168 ** if SQLite is compiled with the SQLITE_ENABLE_MEMORY_MANAGEMENT macro.
2170 int sqlite3_release_memory(int);
2173 ** CAPI3REF: Impose A Limit On Heap Size
2175 ** Place a "soft" limit on the amount of heap memory that may be allocated by
2176 ** SQLite within the current thread. If an internal allocation is requested
2177 ** that would exceed the specified limit, [sqlite3_release_memory()] is invoked
2178 ** one or more times to free up some space before the allocation is made.
2180 ** The limit is called "soft", because if [sqlite3_release_memory()] cannot free
2181 ** sufficient memory to prevent the limit from being exceeded, the memory is
2182 ** allocated anyway and the current operation proceeds.
2184 ** Prior to shutting down a thread sqlite3_soft_heap_limit() must be set to
2185 ** zero (the default) or else the thread will leak memory. Alternatively, use
2186 ** the [sqlite3_thread_cleanup()] API.
2188 ** A negative or zero value for N means that there is no soft heap limit and
2189 ** [sqlite3_release_memory()] will only be called when memory is exhaused.
2190 ** The default value for the soft heap limit is zero.
2192 ** SQLite makes a best effort to honor the soft heap limit. But if it
2193 ** is unable to reduce memory usage below the soft limit, execution will
2194 ** continue without error or notification. This is why the limit is
2195 ** called a "soft" limit. It is advisory only.
2197 ** This function is only available if the library was compiled with the
2198 ** SQLITE_ENABLE_MEMORY_MANAGEMENT option set.
2199 ** memory-management has been enabled.
2201 void sqlite3_soft_heap_limit(int);
2204 ** CAPI3REF: Clean Up Thread Local Storage
2206 ** This routine makes sure that all thread-local storage has been
2207 ** deallocated for the current thread.
2209 ** This routine is not technically necessary. All thread-local storage
2210 ** will be automatically deallocated once memory-management and
2211 ** shared-cache are disabled and the soft heap limit has been set
2212 ** to zero. This routine is provided as a convenience for users who
2213 ** want to make absolutely sure they have not forgotten something
2214 ** prior to killing off a thread.
2216 void sqlite3_thread_cleanup(void);
2219 ** CAPI3REF: Extract Metadata About A Column Of A Table
2221 ** This routine
2222 ** returns meta-data about a specific column of a specific database
2223 ** table accessible using the connection handle passed as the first function
2224 ** argument.
2226 ** The column is identified by the second, third and fourth parameters to
2227 ** this function. The second parameter is either the name of the database
2228 ** (i.e. "main", "temp" or an attached database) containing the specified
2229 ** table or NULL. If it is NULL, then all attached databases are searched
2230 ** for the table using the same algorithm as the database engine uses to
2231 ** resolve unqualified table references.
2233 ** The third and fourth parameters to this function are the table and column
2234 ** name of the desired column, respectively. Neither of these parameters
2235 ** may be NULL.
2237 ** Meta information is returned by writing to the memory locations passed as
2238 ** the 5th and subsequent parameters to this function. Any of these
2239 ** arguments may be NULL, in which case the corresponding element of meta
2240 ** information is ommitted.
2242 ** <pre>
2243 ** Parameter Output Type Description
2244 ** -----------------------------------
2246 ** 5th const char* Data type
2247 ** 6th const char* Name of the default collation sequence
2248 ** 7th int True if the column has a NOT NULL constraint
2249 ** 8th int True if the column is part of the PRIMARY KEY
2250 ** 9th int True if the column is AUTOINCREMENT
2251 ** </pre>
2254 ** The memory pointed to by the character pointers returned for the
2255 ** declaration type and collation sequence is valid only until the next
2256 ** call to any sqlite API function.
2258 ** If the specified table is actually a view, then an error is returned.
2260 ** If the specified column is "rowid", "oid" or "_rowid_" and an
2261 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output
2262 ** parameters are set for the explicitly declared column. If there is no
2263 ** explicitly declared IPK column, then the output parameters are set as
2264 ** follows:
2266 ** <pre>
2267 ** data type: "INTEGER"
2268 ** collation sequence: "BINARY"
2269 ** not null: 0
2270 ** primary key: 1
2271 ** auto increment: 0
2272 ** </pre>
2274 ** This function may load one or more schemas from database files. If an
2275 ** error occurs during this process, or if the requested table or column
2276 ** cannot be found, an SQLITE error code is returned and an error message
2277 ** left in the database handle (to be retrieved using sqlite3_errmsg()).
2279 ** This API is only available if the library was compiled with the
2280 ** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
2282 int sqlite3_table_column_metadata(
2283 sqlite3 *db, /* Connection handle */
2284 const char *zDbName, /* Database name or NULL */
2285 const char *zTableName, /* Table name */
2286 const char *zColumnName, /* Column name */
2287 char const **pzDataType, /* OUTPUT: Declared data type */
2288 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
2289 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
2290 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
2291 int *pAutoinc /* OUTPUT: True if colums is auto-increment */
2295 ** CAPI3REF: Load An Extension
2297 ** Attempt to load an SQLite extension library contained in the file
2298 ** zFile. The entry point is zProc. zProc may be 0 in which case the
2299 ** name of the entry point defaults to "sqlite3_extension_init".
2301 ** Return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
2303 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
2304 ** error message text. The calling function should free this memory
2305 ** by calling [sqlite3_free()].
2307 ** Extension loading must be enabled using [sqlite3_enable_load_extension()]
2308 ** prior to calling this API or an error will be returned.
2310 int sqlite3_load_extension(
2311 sqlite3 *db, /* Load the extension into this database connection */
2312 const char *zFile, /* Name of the shared library containing extension */
2313 const char *zProc, /* Entry point. Derived from zFile if 0 */
2314 char **pzErrMsg /* Put error message here if not 0 */
2318 ** CAPI3REF: Enable Or Disable Extension Loading
2320 ** So as not to open security holes in older applications that are
2321 ** unprepared to deal with extension loading, and as a means of disabling
2322 ** extension loading while evaluating user-entered SQL, the following
2323 ** API is provided to turn the [sqlite3_load_extension()] mechanism on and
2324 ** off. It is off by default. See ticket #1863.
2326 ** Call this routine with onoff==1 to turn extension loading on
2327 ** and call it with onoff==0 to turn it back off again.
2329 int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
2332 ** CAPI3REF: Make Arrangements To Automatically Load An Extension
2334 ** Register an extension entry point that is automatically invoked
2335 ** whenever a new database connection is opened using
2336 ** [sqlite3_open()] or [sqlite3_open16()].
2338 ** This API can be invoked at program startup in order to register
2339 ** one or more statically linked extensions that will be available
2340 ** to all new database connections.
2342 ** Duplicate extensions are detected so calling this routine multiple
2343 ** times with the same extension is harmless.
2345 ** This routine stores a pointer to the extension in an array
2346 ** that is obtained from malloc(). If you run a memory leak
2347 ** checker on your program and it reports a leak because of this
2348 ** array, then invoke [sqlite3_automatic_extension_reset()] prior
2349 ** to shutdown to free the memory.
2351 ** Automatic extensions apply across all threads.
2353 ** This interface is experimental and is subject to change or
2354 ** removal in future releases of SQLite.
2356 int sqlite3_auto_extension(void *xEntryPoint);
2360 ** CAPI3REF: Reset Automatic Extension Loading
2362 ** Disable all previously registered automatic extensions. This
2363 ** routine undoes the effect of all prior [sqlite3_automatic_extension()]
2364 ** calls.
2366 ** This call disabled automatic extensions in all threads.
2368 ** This interface is experimental and is subject to change or
2369 ** removal in future releases of SQLite.
2371 void sqlite3_reset_auto_extension(void);
2375 ****** EXPERIMENTAL - subject to change without notice **************
2377 ** The interface to the virtual-table mechanism is currently considered
2378 ** to be experimental. The interface might change in incompatible ways.
2379 ** If this is a problem for you, do not use the interface at this time.
2381 ** When the virtual-table mechanism stablizes, we will declare the
2382 ** interface fixed, support it indefinitely, and remove this comment.
2386 ** Structures used by the virtual table interface
2388 typedef struct sqlite3_vtab sqlite3_vtab;
2389 typedef struct sqlite3_index_info sqlite3_index_info;
2390 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
2391 typedef struct sqlite3_module sqlite3_module;
2394 ** A module is a class of virtual tables. Each module is defined
2395 ** by an instance of the following structure. This structure consists
2396 ** mostly of methods for the module.
2398 struct sqlite3_module {
2399 int iVersion;
2400 int (*xCreate)(sqlite3*, void *pAux,
2401 int argc, const char *const*argv,
2402 sqlite3_vtab **ppVTab, char**);
2403 int (*xConnect)(sqlite3*, void *pAux,
2404 int argc, const char *const*argv,
2405 sqlite3_vtab **ppVTab, char**);
2406 int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
2407 int (*xDisconnect)(sqlite3_vtab *pVTab);
2408 int (*xDestroy)(sqlite3_vtab *pVTab);
2409 int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
2410 int (*xClose)(sqlite3_vtab_cursor*);
2411 int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
2412 int argc, sqlite3_value **argv);
2413 int (*xNext)(sqlite3_vtab_cursor*);
2414 int (*xEof)(sqlite3_vtab_cursor*);
2415 int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
2416 int (*xRowid)(sqlite3_vtab_cursor*, sqlite_int64 *pRowid);
2417 int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite_int64 *);
2418 int (*xBegin)(sqlite3_vtab *pVTab);
2419 int (*xSync)(sqlite3_vtab *pVTab);
2420 int (*xCommit)(sqlite3_vtab *pVTab);
2421 int (*xRollback)(sqlite3_vtab *pVTab);
2422 int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
2423 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
2424 void **ppArg);
2428 ** The sqlite3_index_info structure and its substructures is used to
2429 ** pass information into and receive the reply from the xBestIndex
2430 ** method of an sqlite3_module. The fields under **Inputs** are the
2431 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
2432 ** results into the **Outputs** fields.
2434 ** The aConstraint[] array records WHERE clause constraints of the
2435 ** form:
2437 ** column OP expr
2439 ** Where OP is =, <, <=, >, or >=. The particular operator is stored
2440 ** in aConstraint[].op. The index of the column is stored in
2441 ** aConstraint[].iColumn. aConstraint[].usable is TRUE if the
2442 ** expr on the right-hand side can be evaluated (and thus the constraint
2443 ** is usable) and false if it cannot.
2445 ** The optimizer automatically inverts terms of the form "expr OP column"
2446 ** and makes other simplificatinos to the WHERE clause in an attempt to
2447 ** get as many WHERE clause terms into the form shown above as possible.
2448 ** The aConstraint[] array only reports WHERE clause terms in the correct
2449 ** form that refer to the particular virtual table being queried.
2451 ** Information about the ORDER BY clause is stored in aOrderBy[].
2452 ** Each term of aOrderBy records a column of the ORDER BY clause.
2454 ** The xBestIndex method must fill aConstraintUsage[] with information
2455 ** about what parameters to pass to xFilter. If argvIndex>0 then
2456 ** the right-hand side of the corresponding aConstraint[] is evaluated
2457 ** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit
2458 ** is true, then the constraint is assumed to be fully handled by the
2459 ** virtual table and is not checked again by SQLite.
2461 ** The idxNum and idxPtr values are recorded and passed into xFilter.
2462 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
2464 ** The orderByConsumed means that output from xFilter will occur in
2465 ** the correct order to satisfy the ORDER BY clause so that no separate
2466 ** sorting step is required.
2468 ** The estimatedCost value is an estimate of the cost of doing the
2469 ** particular lookup. A full scan of a table with N entries should have
2470 ** a cost of N. A binary search of a table of N entries should have a
2471 ** cost of approximately log(N).
2473 struct sqlite3_index_info {
2474 /* Inputs */
2475 const int nConstraint; /* Number of entries in aConstraint */
2476 const struct sqlite3_index_constraint {
2477 int iColumn; /* Column on left-hand side of constraint */
2478 unsigned char op; /* Constraint operator */
2479 unsigned char usable; /* True if this constraint is usable */
2480 int iTermOffset; /* Used internally - xBestIndex should ignore */
2481 } *const aConstraint; /* Table of WHERE clause constraints */
2482 const int nOrderBy; /* Number of terms in the ORDER BY clause */
2483 const struct sqlite3_index_orderby {
2484 int iColumn; /* Column number */
2485 unsigned char desc; /* True for DESC. False for ASC. */
2486 } *const aOrderBy; /* The ORDER BY clause */
2488 /* Outputs */
2489 struct sqlite3_index_constraint_usage {
2490 int argvIndex; /* if >0, constraint is part of argv to xFilter */
2491 unsigned char omit; /* Do not code a test for this constraint */
2492 } *const aConstraintUsage;
2493 int idxNum; /* Number used to identify the index */
2494 char *idxStr; /* String, possibly obtained from sqlite3_malloc */
2495 int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
2496 int orderByConsumed; /* True if output is already ordered */
2497 double estimatedCost; /* Estimated cost of using this index */
2499 #define SQLITE_INDEX_CONSTRAINT_EQ 2
2500 #define SQLITE_INDEX_CONSTRAINT_GT 4
2501 #define SQLITE_INDEX_CONSTRAINT_LE 8
2502 #define SQLITE_INDEX_CONSTRAINT_LT 16
2503 #define SQLITE_INDEX_CONSTRAINT_GE 32
2504 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
2507 ** This routine is used to register a new module name with an SQLite
2508 ** connection. Module names must be registered before creating new
2509 ** virtual tables on the module, or before using preexisting virtual
2510 ** tables of the module.
2512 int sqlite3_create_module(
2513 sqlite3 *db, /* SQLite connection to register module with */
2514 const char *zName, /* Name of the module */
2515 const sqlite3_module *, /* Methods for the module */
2516 void * /* Client data for xCreate/xConnect */
2520 ** Every module implementation uses a subclass of the following structure
2521 ** to describe a particular instance of the module. Each subclass will
2522 ** be taylored to the specific needs of the module implementation. The
2523 ** purpose of this superclass is to define certain fields that are common
2524 ** to all module implementations.
2526 ** Virtual tables methods can set an error message by assigning a
2527 ** string obtained from sqlite3_mprintf() to zErrMsg. The method should
2528 ** take care that any prior string is freed by a call to sqlite3_free()
2529 ** prior to assigning a new string to zErrMsg. After the error message
2530 ** is delivered up to the client application, the string will be automatically
2531 ** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note
2532 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
2533 ** since virtual tables are commonly implemented in loadable extensions which
2534 ** do not have access to sqlite3MPrintf() or sqlite3Free().
2536 struct sqlite3_vtab {
2537 const sqlite3_module *pModule; /* The module for this virtual table */
2538 int nRef; /* Used internally */
2539 char *zErrMsg; /* Error message from sqlite3_mprintf() */
2540 /* Virtual table implementations will typically add additional fields */
2543 /* Every module implementation uses a subclass of the following structure
2544 ** to describe cursors that point into the virtual table and are used
2545 ** to loop through the virtual table. Cursors are created using the
2546 ** xOpen method of the module. Each module implementation will define
2547 ** the content of a cursor structure to suit its own needs.
2549 ** This superclass exists in order to define fields of the cursor that
2550 ** are common to all implementations.
2552 struct sqlite3_vtab_cursor {
2553 sqlite3_vtab *pVtab; /* Virtual table of this cursor */
2554 /* Virtual table implementations will typically add additional fields */
2558 ** The xCreate and xConnect methods of a module use the following API
2559 ** to declare the format (the names and datatypes of the columns) of
2560 ** the virtual tables they implement.
2562 int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
2565 ** Virtual tables can provide alternative implementations of functions
2566 ** using the xFindFunction method. But global versions of those functions
2567 ** must exist in order to be overloaded.
2569 ** This API makes sure a global version of a function with a particular
2570 ** name and number of parameters exists. If no such function exists
2571 ** before this API is called, a new function is created. The implementation
2572 ** of the new function always causes an exception to be thrown. So
2573 ** the new function is not good for anything by itself. Its only
2574 ** purpose is to be a place-holder function that can be overloaded
2575 ** by virtual tables.
2577 ** This API should be considered part of the virtual table interface,
2578 ** which is experimental and subject to change.
2580 int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
2583 ** The interface to the virtual-table mechanism defined above (back up
2584 ** to a comment remarkably similar to this one) is currently considered
2585 ** to be experimental. The interface might change in incompatible ways.
2586 ** If this is a problem for you, do not use the interface at this time.
2588 ** When the virtual-table mechanism stablizes, we will declare the
2589 ** interface fixed, support it indefinitely, and remove this comment.
2591 ****** EXPERIMENTAL - subject to change without notice **************
2595 ** CAPI3REF: A Handle To An Open BLOB
2597 ** An instance of the following opaque structure is used to
2598 ** represent an blob-handle. A blob-handle is created by
2599 ** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()].
2600 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
2601 ** can be used to read or write small subsections of the blob.
2602 ** The [sqltie3_blob_size()] interface returns the size of the
2603 ** blob in bytes.
2605 typedef struct sqlite3_blob sqlite3_blob;
2608 ** CAPI3REF: Open A BLOB For Incremental I/O
2610 ** Open a handle to the blob located in row iRow,, column zColumn,
2611 ** table zTable in database zDb. i.e. the same blob that would
2612 ** be selected by:
2614 ** <pre>
2615 ** SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
2616 ** </pre>
2618 ** If the flags parameter is non-zero, the blob is opened for
2619 ** read and write access. If it is zero, the blob is opened for read
2620 ** access.
2622 ** On success, [SQLITE_OK] is returned and the new
2623 ** [sqlite3_blob | blob handle] is written to *ppBlob.
2624 ** Otherwise an error code is returned and
2625 ** any value written to *ppBlob should not be used by the caller.
2626 ** This function sets the database-handle error code and message
2627 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
2629 int sqlite3_blob_open(
2630 sqlite3*,
2631 const char *zDb,
2632 const char *zTable,
2633 const char *zColumn,
2634 sqlite_int64 iRow,
2635 int flags,
2636 sqlite3_blob **ppBlob
2640 ** CAPI3REF: Close A BLOB Handle
2642 ** Close an open [sqlite3_blob | blob handle].
2644 int sqlite3_blob_close(sqlite3_blob *);
2647 ** CAPI3REF: Return The Size Of An Open BLOB
2649 ** Return the size in bytes of the blob accessible via the open
2650 ** [sqlite3_blob | blob-handle] passed as an argument.
2652 int sqlite3_blob_bytes(sqlite3_blob *);
2655 ** CAPI3REF: Read Data From A BLOB Incrementally
2657 ** This function is used to read data from an open
2658 ** [sqlite3_blob | blob-handle] into a caller supplied buffer.
2659 ** n bytes of data are copied into buffer
2660 ** z from the open blob, starting at offset iOffset.
2662 ** On success, SQLITE_OK is returned. Otherwise, an
2663 ** [SQLITE_ERROR | SQLite error code] or an
2664 ** [SQLITE_IOERR_READ | extended error code] is returned.
2666 int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset);
2669 ** CAPI3REF: Write Data Into A BLOB Incrementally
2671 ** This function is used to write data into an open
2672 ** [sqlite3_blob | blob-handle] from a user supplied buffer.
2673 ** n bytes of data are copied from the buffer
2674 ** pointed to by z into the open blob, starting at offset iOffset.
2676 ** If the [sqlite3_blob | blob-handle] passed as the first argument
2677 ** was not opened for writing (the flags parameter to [sqlite3_blob_open()]
2678 *** was zero), this function returns [SQLITE_READONLY].
2680 ** This function may only modify the contents of the blob, it is
2681 ** not possible to increase the size of a blob using this API. If
2682 ** offset iOffset is less than n bytes from the end of the blob,
2683 ** [SQLITE_ERROR] is returned and no data is written.
2685 ** On success, SQLITE_OK is returned. Otherwise, an
2686 ** [SQLITE_ERROR | SQLite error code] or an
2687 ** [SQLITE_IOERR_READ | extended error code] is returned.
2689 int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
2692 ** Undo the hack that converts floating point types to integer for
2693 ** builds on processors without floating point support.
2695 #ifdef SQLITE_OMIT_FLOATING_POINT
2696 # undef double
2697 #endif
2699 #if 0
2700 } /* End of the 'extern "C"' block */
2701 #endif
2702 #endif
2704 /************** End of sqlite3.h *********************************************/
2705 /************** Begin file date.c ********************************************/
2707 ** 2003 October 31
2709 ** The author disclaims copyright to this source code. In place of
2710 ** a legal notice, here is a blessing:
2712 ** May you do good and not evil.
2713 ** May you find forgiveness for yourself and forgive others.
2714 ** May you share freely, never taking more than you give.
2716 *************************************************************************
2717 ** This file contains the C functions that implement date and time
2718 ** functions for SQLite.
2720 ** There is only one exported symbol in this file - the function
2721 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
2722 ** All other code has file scope.
2724 ** $Id: date.c,v 1.66 2007/05/08 21:56:00 drh Exp $
2726 ** SQLite processes all times and dates as Julian Day numbers. The
2727 ** dates and times are stored as the number of days since noon
2728 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
2729 ** calendar system.
2731 ** 1970-01-01 00:00:00 is JD 2440587.5
2732 ** 2000-01-01 00:00:00 is JD 2451544.5
2734 ** This implemention requires years to be expressed as a 4-digit number
2735 ** which means that only dates between 0000-01-01 and 9999-12-31 can
2736 ** be represented, even though julian day numbers allow a much wider
2737 ** range of dates.
2739 ** The Gregorian calendar system is used for all dates and times,
2740 ** even those that predate the Gregorian calendar. Historians usually
2741 ** use the Julian calendar for dates prior to 1582-10-15 and for some
2742 ** dates afterwards, depending on locale. Beware of this difference.
2744 ** The conversion algorithms are implemented based on descriptions
2745 ** in the following text:
2747 ** Jean Meeus
2748 ** Astronomical Algorithms, 2nd Edition, 1998
2749 ** ISBM 0-943396-61-1
2750 ** Willmann-Bell, Inc
2751 ** Richmond, Virginia (USA)
2753 /************** Include sqliteInt.h in the middle of date.c ******************/
2754 /************** Begin file sqliteInt.h ***************************************/
2756 ** 2001 September 15
2758 ** The author disclaims copyright to this source code. In place of
2759 ** a legal notice, here is a blessing:
2761 ** May you do good and not evil.
2762 ** May you find forgiveness for yourself and forgive others.
2763 ** May you share freely, never taking more than you give.
2765 *************************************************************************
2766 ** Internal interface definitions for SQLite.
2768 ** @(#) $Id: sqliteInt.h,v 1.572 2007/06/10 22:57:33 drh Exp $
2770 #ifndef _SQLITEINT_H_
2771 #define _SQLITEINT_H_
2772 /************** Include limits.h in the middle of sqliteInt.h ****************/
2773 /************** Begin file limits.h ******************************************/
2775 ** 2007 May 7
2777 ** The author disclaims copyright to this source code. In place of
2778 ** a legal notice, here is a blessing:
2780 ** May you do good and not evil.
2781 ** May you find forgiveness for yourself and forgive others.
2782 ** May you share freely, never taking more than you give.
2784 *************************************************************************
2786 ** This file defines various limits of what SQLite can process.
2788 ** @(#) $Id: limits.h,v 1.9 2007/06/09 09:53:51 drh Exp $
2792 ** The maximum length of a TEXT or BLOB in bytes. This also
2793 ** limits the size of a row in a table or index.
2795 ** The hard limit is the ability of a 32-bit signed integer
2796 ** to count the size: 2^31-1 or 2147483647.
2798 #ifndef SQLITE_MAX_LENGTH
2799 # define SQLITE_MAX_LENGTH 1000000000
2800 #endif
2803 ** This is the maximum number of
2805 ** * Columns in a table
2806 ** * Columns in an index
2807 ** * Columns in a view
2808 ** * Terms in the SET clause of an UPDATE statement
2809 ** * Terms in the result set of a SELECT statement
2810 ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
2811 ** * Terms in the VALUES clause of an INSERT statement
2813 ** The hard upper limit here is 32676. Most database people will
2814 ** tell you that in a well-normalized database, you usually should
2815 ** not have more than a dozen or so columns in any table. And if
2816 ** that is the case, there is no point in having more than a few
2817 ** dozen values in any of the other situations described above.
2819 #ifndef SQLITE_MAX_COLUMN
2820 # define SQLITE_MAX_COLUMN 2000
2821 #endif
2824 ** The maximum length of a single SQL statement in bytes.
2825 ** The hard limit here is the same as SQLITE_MAX_LENGTH.
2827 #ifndef SQLITE_MAX_SQL_LENGTH
2828 # define SQLITE_MAX_SQL_LENGTH 1000000
2829 #endif
2832 ** The maximum depth of an expression tree. This is limited to
2833 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
2834 ** want to place more severe limits on the complexity of an
2835 ** expression. A value of 0 (the default) means do not enforce
2836 ** any limitation on expression tree depth.
2838 #ifndef SQLITE_MAX_EXPR_DEPTH
2839 # define SQLITE_MAX_EXPR_DEPTH 1000
2840 #endif
2843 ** The maximum number of terms in a compound SELECT statement.
2844 ** The code generator for compound SELECT statements does one
2845 ** level of recursion for each term. A stack overflow can result
2846 ** if the number of terms is too large. In practice, most SQL
2847 ** never has more than 3 or 4 terms. Use a value of 0 to disable
2848 ** any limit on the number of terms in a compount SELECT.
2850 #ifndef SQLITE_MAX_COMPOUND_SELECT
2851 # define SQLITE_MAX_COMPOUND_SELECT 500
2852 #endif
2855 ** The maximum number of opcodes in a VDBE program.
2856 ** Not currently enforced.
2858 #ifndef SQLITE_MAX_VDBE_OP
2859 # define SQLITE_MAX_VDBE_OP 25000
2860 #endif
2863 ** The maximum number of arguments to an SQL function.
2865 #ifndef SQLITE_MAX_FUNCTION_ARG
2866 # define SQLITE_MAX_FUNCTION_ARG 100
2867 #endif
2870 ** The maximum number of in-memory pages to use for the main database
2871 ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
2873 #ifndef SQLITE_DEFAULT_CACHE_SIZE
2874 # define SQLITE_DEFAULT_CACHE_SIZE 2000
2875 #endif
2876 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
2877 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
2878 #endif
2881 ** The maximum number of attached databases. This must be at least 2
2882 ** in order to support the main database file (0) and the file used to
2883 ** hold temporary tables (1). And it must be less than 32 because
2884 ** we use a bitmask of databases with a u32 in places (for example
2885 ** the Parse.cookieMask field).
2887 #ifndef SQLITE_MAX_ATTACHED
2888 # define SQLITE_MAX_ATTACHED 10
2889 #endif
2893 ** The maximum value of a ?nnn wildcard that the parser will accept.
2895 #ifndef SQLITE_MAX_VARIABLE_NUMBER
2896 # define SQLITE_MAX_VARIABLE_NUMBER 999
2897 #endif
2900 ** The default size of a database page.
2902 #ifndef SQLITE_DEFAULT_PAGE_SIZE
2903 # define SQLITE_DEFAULT_PAGE_SIZE 1024
2904 #endif
2906 /* Maximum page size. The upper bound on this value is 32768. This a limit
2907 ** imposed by the necessity of storing the value in a 2-byte unsigned integer
2908 ** and the fact that the page size must be a power of 2.
2910 #ifndef SQLITE_MAX_PAGE_SIZE
2911 # define SQLITE_MAX_PAGE_SIZE 32768
2912 #endif
2915 ** Maximum number of pages in one database file.
2917 ** This is really just the default value for the max_page_count pragma.
2918 ** This value can be lowered (or raised) at run-time using that the
2919 ** max_page_count macro.
2921 #ifndef SQLITE_MAX_PAGE_COUNT
2922 # define SQLITE_MAX_PAGE_COUNT 1073741823
2923 #endif
2926 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
2927 ** operator.
2929 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
2930 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
2931 #endif
2933 /************** End of limits.h **********************************************/
2934 /************** Continuing where we left off in sqliteInt.h ******************/
2937 #if defined(SQLITE_TCL) || defined(TCLSH)
2938 # include <tcl.h>
2939 #endif
2942 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
2943 ** Setting NDEBUG makes the code smaller and run faster. So the following
2944 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
2945 ** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out
2946 ** feature.
2948 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
2949 # define NDEBUG 1
2950 #endif
2953 ** These #defines should enable >2GB file support on Posix if the
2954 ** underlying operating system supports it. If the OS lacks
2955 ** large file support, or if the OS is windows, these should be no-ops.
2957 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
2958 ** on the compiler command line. This is necessary if you are compiling
2959 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
2960 ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
2961 ** without this option, LFS is enable. But LFS does not exist in the kernel
2962 ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
2963 ** portability you should omit LFS.
2965 ** Similar is true for MacOS. LFS is only supported on MacOS 9 and later.
2967 #ifndef SQLITE_DISABLE_LFS
2968 # define _LARGE_FILE 1
2969 # ifndef _FILE_OFFSET_BITS
2970 # define _FILE_OFFSET_BITS 64
2971 # endif
2972 # define _LARGEFILE_SOURCE 1
2973 #endif
2975 /************** Include hash.h in the middle of sqliteInt.h ******************/
2976 /************** Begin file hash.h ********************************************/
2978 ** 2001 September 22
2980 ** The author disclaims copyright to this source code. In place of
2981 ** a legal notice, here is a blessing:
2983 ** May you do good and not evil.
2984 ** May you find forgiveness for yourself and forgive others.
2985 ** May you share freely, never taking more than you give.
2987 *************************************************************************
2988 ** This is the header file for the generic hash-table implemenation
2989 ** used in SQLite.
2991 ** $Id: hash.h,v 1.9 2006/02/14 10:48:39 danielk1977 Exp $
2993 #ifndef _SQLITE_HASH_H_
2994 #define _SQLITE_HASH_H_
2996 /* Forward declarations of structures. */
2997 typedef struct Hash Hash;
2998 typedef struct HashElem HashElem;
3000 /* A complete hash table is an instance of the following structure.
3001 ** The internals of this structure are intended to be opaque -- client
3002 ** code should not attempt to access or modify the fields of this structure
3003 ** directly. Change this structure only by using the routines below.
3004 ** However, many of the "procedures" and "functions" for modifying and
3005 ** accessing this structure are really macros, so we can't really make
3006 ** this structure opaque.
3008 struct Hash {
3009 char keyClass; /* SQLITE_HASH_INT, _POINTER, _STRING, _BINARY */
3010 char copyKey; /* True if copy of key made on insert */
3011 int count; /* Number of entries in this table */
3012 HashElem *first; /* The first element of the array */
3013 void *(*xMalloc)(int); /* malloc() function to use */
3014 void (*xFree)(void *); /* free() function to use */
3015 int htsize; /* Number of buckets in the hash table */
3016 struct _ht { /* the hash table */
3017 int count; /* Number of entries with this hash */
3018 HashElem *chain; /* Pointer to first entry with this hash */
3019 } *ht;
3022 /* Each element in the hash table is an instance of the following
3023 ** structure. All elements are stored on a single doubly-linked list.
3025 ** Again, this structure is intended to be opaque, but it can't really
3026 ** be opaque because it is used by macros.
3028 struct HashElem {
3029 HashElem *next, *prev; /* Next and previous elements in the table */
3030 void *data; /* Data associated with this element */
3031 void *pKey; int nKey; /* Key associated with this element */
3035 ** There are 4 different modes of operation for a hash table:
3037 ** SQLITE_HASH_INT nKey is used as the key and pKey is ignored.
3039 ** SQLITE_HASH_POINTER pKey is used as the key and nKey is ignored.
3041 ** SQLITE_HASH_STRING pKey points to a string that is nKey bytes long
3042 ** (including the null-terminator, if any). Case
3043 ** is ignored in comparisons.
3045 ** SQLITE_HASH_BINARY pKey points to binary data nKey bytes long.
3046 ** memcmp() is used to compare keys.
3048 ** A copy of the key is made for SQLITE_HASH_STRING and SQLITE_HASH_BINARY
3049 ** if the copyKey parameter to HashInit is 1.
3051 /* #define SQLITE_HASH_INT 1 // NOT USED */
3052 /* #define SQLITE_HASH_POINTER 2 // NOT USED */
3053 #define SQLITE_HASH_STRING 3
3054 #define SQLITE_HASH_BINARY 4
3057 ** Access routines. To delete, insert a NULL pointer.
3059 static void sqlite3HashInit(Hash*, int keytype, int copyKey);
3060 static void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
3061 static void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
3062 static void sqlite3HashClear(Hash*);
3065 ** Macros for looping over all elements of a hash table. The idiom is
3066 ** like this:
3068 ** Hash h;
3069 ** HashElem *p;
3070 ** ...
3071 ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
3072 ** SomeStructure *pData = sqliteHashData(p);
3073 ** // do something with pData
3074 ** }
3076 #define sqliteHashFirst(H) ((H)->first)
3077 #define sqliteHashNext(E) ((E)->next)
3078 #define sqliteHashData(E) ((E)->data)
3079 #define sqliteHashKey(E) ((E)->pKey)
3080 #define sqliteHashKeysize(E) ((E)->nKey)
3083 ** Number of entries in a hash table
3085 #define sqliteHashCount(H) ((H)->count)
3087 #endif /* _SQLITE_HASH_H_ */
3089 /************** End of hash.h ************************************************/
3090 /************** Continuing where we left off in sqliteInt.h ******************/
3091 /************** Include parse.h in the middle of sqliteInt.h *****************/
3092 /************** Begin file parse.h *******************************************/
3093 #define TK_SEMI 1
3094 #define TK_EXPLAIN 2
3095 #define TK_QUERY 3
3096 #define TK_PLAN 4
3097 #define TK_BEGIN 5
3098 #define TK_TRANSACTION 6
3099 #define TK_DEFERRED 7
3100 #define TK_IMMEDIATE 8
3101 #define TK_EXCLUSIVE 9
3102 #define TK_COMMIT 10
3103 #define TK_END 11
3104 #define TK_ROLLBACK 12
3105 #define TK_CREATE 13
3106 #define TK_TABLE 14
3107 #define TK_IF 15
3108 #define TK_NOT 16
3109 #define TK_EXISTS 17
3110 #define TK_TEMP 18
3111 #define TK_LP 19
3112 #define TK_RP 20
3113 #define TK_AS 21
3114 #define TK_COMMA 22
3115 #define TK_ID 23
3116 #define TK_ABORT 24
3117 #define TK_AFTER 25
3118 #define TK_ANALYZE 26
3119 #define TK_ASC 27
3120 #define TK_ATTACH 28
3121 #define TK_BEFORE 29
3122 #define TK_CASCADE 30
3123 #define TK_CAST 31
3124 #define TK_CONFLICT 32
3125 #define TK_DATABASE 33
3126 #define TK_DESC 34
3127 #define TK_DETACH 35
3128 #define TK_EACH 36
3129 #define TK_FAIL 37
3130 #define TK_FOR 38
3131 #define TK_IGNORE 39
3132 #define TK_INITIALLY 40
3133 #define TK_INSTEAD 41
3134 #define TK_LIKE_KW 42
3135 #define TK_MATCH 43
3136 #define TK_KEY 44
3137 #define TK_OF 45
3138 #define TK_OFFSET 46
3139 #define TK_PRAGMA 47
3140 #define TK_RAISE 48
3141 #define TK_REPLACE 49
3142 #define TK_RESTRICT 50
3143 #define TK_ROW 51
3144 #define TK_TRIGGER 52
3145 #define TK_VACUUM 53
3146 #define TK_VIEW 54
3147 #define TK_VIRTUAL 55
3148 #define TK_REINDEX 56
3149 #define TK_RENAME 57
3150 #define TK_CTIME_KW 58
3151 #define TK_ANY 59
3152 #define TK_OR 60
3153 #define TK_AND 61
3154 #define TK_IS 62
3155 #define TK_BETWEEN 63
3156 #define TK_IN 64
3157 #define TK_ISNULL 65
3158 #define TK_NOTNULL 66
3159 #define TK_NE 67
3160 #define TK_EQ 68
3161 #define TK_GT 69
3162 #define TK_LE 70
3163 #define TK_LT 71
3164 #define TK_GE 72
3165 #define TK_ESCAPE 73
3166 #define TK_BITAND 74
3167 #define TK_BITOR 75
3168 #define TK_LSHIFT 76
3169 #define TK_RSHIFT 77
3170 #define TK_PLUS 78
3171 #define TK_MINUS 79
3172 #define TK_STAR 80
3173 #define TK_SLASH 81
3174 #define TK_REM 82
3175 #define TK_CONCAT 83
3176 #define TK_COLLATE 84
3177 #define TK_UMINUS 85
3178 #define TK_UPLUS 86
3179 #define TK_BITNOT 87
3180 #define TK_STRING 88
3181 #define TK_JOIN_KW 89
3182 #define TK_CONSTRAINT 90
3183 #define TK_DEFAULT 91
3184 #define TK_NULL 92
3185 #define TK_PRIMARY 93
3186 #define TK_UNIQUE 94
3187 #define TK_CHECK 95
3188 #define TK_REFERENCES 96
3189 #define TK_AUTOINCR 97
3190 #define TK_ON 98
3191 #define TK_DELETE 99
3192 #define TK_UPDATE 100
3193 #define TK_INSERT 101
3194 #define TK_SET 102
3195 #define TK_DEFERRABLE 103
3196 #define TK_FOREIGN 104
3197 #define TK_DROP 105
3198 #define TK_UNION 106
3199 #define TK_ALL 107
3200 #define TK_EXCEPT 108
3201 #define TK_INTERSECT 109
3202 #define TK_SELECT 110
3203 #define TK_DISTINCT 111
3204 #define TK_DOT 112
3205 #define TK_FROM 113
3206 #define TK_JOIN 114
3207 #define TK_USING 115
3208 #define TK_ORDER 116
3209 #define TK_BY 117
3210 #define TK_GROUP 118
3211 #define TK_HAVING 119
3212 #define TK_LIMIT 120
3213 #define TK_WHERE 121
3214 #define TK_INTO 122
3215 #define TK_VALUES 123
3216 #define TK_INTEGER 124
3217 #define TK_FLOAT 125
3218 #define TK_BLOB 126
3219 #define TK_REGISTER 127
3220 #define TK_VARIABLE 128
3221 #define TK_CASE 129
3222 #define TK_WHEN 130
3223 #define TK_THEN 131
3224 #define TK_ELSE 132
3225 #define TK_INDEX 133
3226 #define TK_ALTER 134
3227 #define TK_TO 135
3228 #define TK_ADD 136
3229 #define TK_COLUMNKW 137
3230 #define TK_TO_TEXT 138
3231 #define TK_TO_BLOB 139
3232 #define TK_TO_NUMERIC 140
3233 #define TK_TO_INT 141
3234 #define TK_TO_REAL 142
3235 #define TK_END_OF_FILE 143
3236 #define TK_ILLEGAL 144
3237 #define TK_SPACE 145
3238 #define TK_UNCLOSED_STRING 146
3239 #define TK_COMMENT 147
3240 #define TK_FUNCTION 148
3241 #define TK_COLUMN 149
3242 #define TK_AGG_FUNCTION 150
3243 #define TK_AGG_COLUMN 151
3244 #define TK_CONST_FUNC 152
3246 /************** End of parse.h ***********************************************/
3247 /************** Continuing where we left off in sqliteInt.h ******************/
3248 #include <stdio.h>
3249 #include <stdlib.h>
3250 #include <string.h>
3251 #include <assert.h>
3252 #include <stddef.h>
3254 #if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
3255 # define isnan(X) ((X)!=(X))
3256 #endif
3259 ** If compiling for a processor that lacks floating point support,
3260 ** substitute integer for floating-point
3262 #ifdef SQLITE_OMIT_FLOATING_POINT
3263 # define double sqlite_int64
3264 # define LONGDOUBLE_TYPE sqlite_int64
3265 # ifndef SQLITE_BIG_DBL
3266 # define SQLITE_BIG_DBL (0x7fffffffffffffff)
3267 # endif
3268 # define SQLITE_OMIT_DATETIME_FUNCS 1
3269 # define SQLITE_OMIT_TRACE 1
3270 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
3271 #endif
3272 #ifndef SQLITE_BIG_DBL
3273 # define SQLITE_BIG_DBL (1e99)
3274 #endif
3277 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
3278 ** afterward. Having this macro allows us to cause the C compiler
3279 ** to omit code used by TEMP tables without messy #ifndef statements.
3281 #ifdef SQLITE_OMIT_TEMPDB
3282 #define OMIT_TEMPDB 1
3283 #else
3284 #define OMIT_TEMPDB 0
3285 #endif
3288 ** If the following macro is set to 1, then NULL values are considered
3289 ** distinct when determining whether or not two entries are the same
3290 ** in a UNIQUE index. This is the way PostgreSQL, Oracle, DB2, MySQL,
3291 ** OCELOT, and Firebird all work. The SQL92 spec explicitly says this
3292 ** is the way things are suppose to work.
3294 ** If the following macro is set to 0, the NULLs are indistinct for
3295 ** a UNIQUE index. In this mode, you can only have a single NULL entry
3296 ** for a column declared UNIQUE. This is the way Informix and SQL Server
3297 ** work.
3299 #define NULL_DISTINCT_FOR_UNIQUE 1
3302 ** The "file format" number is an integer that is incremented whenever
3303 ** the VDBE-level file format changes. The following macros define the
3304 ** the default file format for new databases and the maximum file format
3305 ** that the library can read.
3307 #define SQLITE_MAX_FILE_FORMAT 4
3308 #ifndef SQLITE_DEFAULT_FILE_FORMAT
3309 # define SQLITE_DEFAULT_FILE_FORMAT 1
3310 #endif
3313 ** Provide a default value for TEMP_STORE in case it is not specified
3314 ** on the command-line
3316 #ifndef TEMP_STORE
3317 # define TEMP_STORE 1
3318 #endif
3321 ** GCC does not define the offsetof() macro so we'll have to do it
3322 ** ourselves.
3324 #ifndef offsetof
3325 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
3326 #endif
3329 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
3330 ** not, there are still machines out there that use EBCDIC.)
3332 #if 'A' == '\301'
3333 # define SQLITE_EBCDIC 1
3334 #else
3335 # define SQLITE_ASCII 1
3336 #endif
3339 ** Integers of known sizes. These typedefs might change for architectures
3340 ** where the sizes very. Preprocessor macros are available so that the
3341 ** types can be conveniently redefined at compile-type. Like this:
3343 ** cc '-DUINTPTR_TYPE=long long int' ...
3345 #ifndef UINT32_TYPE
3346 # define UINT32_TYPE unsigned int
3347 #endif
3348 #ifndef UINT16_TYPE
3349 # define UINT16_TYPE unsigned short int
3350 #endif
3351 #ifndef INT16_TYPE
3352 # define INT16_TYPE short int
3353 #endif
3354 #ifndef UINT8_TYPE
3355 # define UINT8_TYPE unsigned char
3356 #endif
3357 #ifndef INT8_TYPE
3358 # define INT8_TYPE signed char
3359 #endif
3360 #ifndef LONGDOUBLE_TYPE
3361 # define LONGDOUBLE_TYPE long double
3362 #endif
3363 typedef sqlite_int64 i64; /* 8-byte signed integer */
3364 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
3365 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
3366 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
3367 typedef INT16_TYPE i16; /* 2-byte signed integer */
3368 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
3369 typedef UINT8_TYPE i8; /* 1-byte signed integer */
3372 ** Macros to determine whether the machine is big or little endian,
3373 ** evaluated at runtime.
3375 extern const int sqlite3one;
3376 #if defined(i386) || defined(__i386__) || defined(_M_IX86)
3377 # define SQLITE_BIGENDIAN 0
3378 # define SQLITE_LITTLEENDIAN 1
3379 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
3380 #else
3381 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
3382 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
3383 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
3384 #endif
3387 ** An instance of the following structure is used to store the busy-handler
3388 ** callback for a given sqlite handle.
3390 ** The sqlite.busyHandler member of the sqlite struct contains the busy
3391 ** callback for the database handle. Each pager opened via the sqlite
3392 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
3393 ** callback is currently invoked only from within pager.c.
3395 typedef struct BusyHandler BusyHandler;
3396 struct BusyHandler {
3397 int (*xFunc)(void *,int); /* The busy callback */
3398 void *pArg; /* First arg to busy callback */
3399 int nBusy; /* Incremented with each busy call */
3403 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
3404 ** "BusyHandler typedefs.
3406 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
3407 /************** Begin file vdbe.h ********************************************/
3409 ** 2001 September 15
3411 ** The author disclaims copyright to this source code. In place of
3412 ** a legal notice, here is a blessing:
3414 ** May you do good and not evil.
3415 ** May you find forgiveness for yourself and forgive others.
3416 ** May you share freely, never taking more than you give.
3418 *************************************************************************
3419 ** Header file for the Virtual DataBase Engine (VDBE)
3421 ** This header defines the interface to the virtual database engine
3422 ** or VDBE. The VDBE implements an abstract machine that runs a
3423 ** simple program to access and modify the underlying database.
3425 ** $Id: vdbe.h,v 1.110 2007/05/08 21:45:28 drh Exp $
3427 #ifndef _SQLITE_VDBE_H_
3428 #define _SQLITE_VDBE_H_
3431 ** A single VDBE is an opaque structure named "Vdbe". Only routines
3432 ** in the source file sqliteVdbe.c are allowed to see the insides
3433 ** of this structure.
3435 typedef struct Vdbe Vdbe;
3438 ** A single instruction of the virtual machine has an opcode
3439 ** and as many as three operands. The instruction is recorded
3440 ** as an instance of the following structure:
3442 struct VdbeOp {
3443 u8 opcode; /* What operation to perform */
3444 int p1; /* First operand */
3445 int p2; /* Second parameter (often the jump destination) */
3446 char *p3; /* Third parameter */
3447 int p3type; /* One of the P3_xxx constants defined below */
3448 #ifdef VDBE_PROFILE
3449 int cnt; /* Number of times this instruction was executed */
3450 long long cycles; /* Total time spend executing this instruction */
3451 #endif
3453 typedef struct VdbeOp VdbeOp;
3456 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
3457 ** it takes up less space.
3459 struct VdbeOpList {
3460 u8 opcode; /* What operation to perform */
3461 signed char p1; /* First operand */
3462 short int p2; /* Second parameter (often the jump destination) */
3463 char *p3; /* Third parameter */
3465 typedef struct VdbeOpList VdbeOpList;
3468 ** Allowed values of VdbeOp.p3type
3470 #define P3_NOTUSED 0 /* The P3 parameter is not used */
3471 #define P3_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
3472 #define P3_STATIC (-2) /* Pointer to a static string */
3473 #define P3_COLLSEQ (-4) /* P3 is a pointer to a CollSeq structure */
3474 #define P3_FUNCDEF (-5) /* P3 is a pointer to a FuncDef structure */
3475 #define P3_KEYINFO (-6) /* P3 is a pointer to a KeyInfo structure */
3476 #define P3_VDBEFUNC (-7) /* P3 is a pointer to a VdbeFunc structure */
3477 #define P3_MEM (-8) /* P3 is a pointer to a Mem* structure */
3478 #define P3_TRANSIENT (-9) /* P3 is a pointer to a transient string */
3479 #define P3_VTAB (-10) /* P3 is a pointer to an sqlite3_vtab structure */
3480 #define P3_MPRINTF (-11) /* P3 is a string obtained from sqlite3_mprintf() */
3482 /* When adding a P3 argument using P3_KEYINFO, a copy of the KeyInfo structure
3483 ** is made. That copy is freed when the Vdbe is finalized. But if the
3484 ** argument is P3_KEYINFO_HANDOFF, the passed in pointer is used. It still
3485 ** gets freed when the Vdbe is finalized so it still should be obtained
3486 ** from a single sqliteMalloc(). But no copy is made and the calling
3487 ** function should *not* try to free the KeyInfo.
3489 #define P3_KEYINFO_HANDOFF (-9)
3492 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
3493 ** number of columns of data returned by the statement.
3495 #define COLNAME_NAME 0
3496 #define COLNAME_DECLTYPE 1
3497 #define COLNAME_DATABASE 2
3498 #define COLNAME_TABLE 3
3499 #define COLNAME_COLUMN 4
3500 #define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
3503 ** The following macro converts a relative address in the p2 field
3504 ** of a VdbeOp structure into a negative number so that
3505 ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
3506 ** the macro again restores the address.
3508 #define ADDR(X) (-1-(X))
3511 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
3512 ** header file that defines a number for each opcode used by the VDBE.
3514 /************** Include opcodes.h in the middle of vdbe.h ********************/
3515 /************** Begin file opcodes.h *****************************************/
3516 /* Automatically generated. Do not edit */
3517 /* See the mkopcodeh.awk script for details */
3518 #define OP_MemLoad 1
3519 #define OP_VNext 2
3520 #define OP_HexBlob 126 /* same as TK_BLOB */
3521 #define OP_Column 3
3522 #define OP_SetCookie 4
3523 #define OP_IfMemPos 5
3524 #define OP_Real 125 /* same as TK_FLOAT */
3525 #define OP_Sequence 6
3526 #define OP_MoveGt 7
3527 #define OP_Ge 72 /* same as TK_GE */
3528 #define OP_RowKey 8
3529 #define OP_Eq 68 /* same as TK_EQ */
3530 #define OP_OpenWrite 9
3531 #define OP_NotNull 66 /* same as TK_NOTNULL */
3532 #define OP_If 10
3533 #define OP_ToInt 141 /* same as TK_TO_INT */
3534 #define OP_String8 88 /* same as TK_STRING */
3535 #define OP_Pop 11
3536 #define OP_VRowid 12
3537 #define OP_CollSeq 13
3538 #define OP_OpenRead 14
3539 #define OP_Expire 15
3540 #define OP_AutoCommit 17
3541 #define OP_Gt 69 /* same as TK_GT */
3542 #define OP_IntegrityCk 18
3543 #define OP_Sort 19
3544 #define OP_Function 20
3545 #define OP_And 61 /* same as TK_AND */
3546 #define OP_Subtract 79 /* same as TK_MINUS */
3547 #define OP_Noop 21
3548 #define OP_Return 22
3549 #define OP_Remainder 82 /* same as TK_REM */
3550 #define OP_NewRowid 23
3551 #define OP_Multiply 80 /* same as TK_STAR */
3552 #define OP_IfMemNeg 24
3553 #define OP_Variable 25
3554 #define OP_String 26
3555 #define OP_RealAffinity 27
3556 #define OP_ParseSchema 28
3557 #define OP_VOpen 29
3558 #define OP_Close 30
3559 #define OP_CreateIndex 31
3560 #define OP_IsUnique 32
3561 #define OP_NotFound 33
3562 #define OP_Int64 34
3563 #define OP_MustBeInt 35
3564 #define OP_Halt 36
3565 #define OP_Rowid 37
3566 #define OP_IdxLT 38
3567 #define OP_AddImm 39
3568 #define OP_Statement 40
3569 #define OP_RowData 41
3570 #define OP_MemMax 42
3571 #define OP_Push 43
3572 #define OP_Or 60 /* same as TK_OR */
3573 #define OP_NotExists 44
3574 #define OP_MemIncr 45
3575 #define OP_Gosub 46
3576 #define OP_Divide 81 /* same as TK_SLASH */
3577 #define OP_Integer 47
3578 #define OP_ToNumeric 140 /* same as TK_TO_NUMERIC*/
3579 #define OP_MemInt 48
3580 #define OP_Prev 49
3581 #define OP_Concat 83 /* same as TK_CONCAT */
3582 #define OP_BitAnd 74 /* same as TK_BITAND */
3583 #define OP_VColumn 50
3584 #define OP_CreateTable 51
3585 #define OP_Last 52
3586 #define OP_IsNull 65 /* same as TK_ISNULL */
3587 #define OP_IncrVacuum 53
3588 #define OP_IdxRowid 54
3589 #define OP_MakeIdxRec 55
3590 #define OP_ShiftRight 77 /* same as TK_RSHIFT */
3591 #define OP_ResetCount 56
3592 #define OP_FifoWrite 57
3593 #define OP_Callback 58
3594 #define OP_ContextPush 59
3595 #define OP_DropTrigger 62
3596 #define OP_DropIndex 63
3597 #define OP_IdxGE 64
3598 #define OP_IdxDelete 73
3599 #define OP_Vacuum 84
3600 #define OP_MoveLe 86
3601 #define OP_IfNot 89
3602 #define OP_DropTable 90
3603 #define OP_MakeRecord 91
3604 #define OP_ToBlob 139 /* same as TK_TO_BLOB */
3605 #define OP_Delete 92
3606 #define OP_AggFinal 93
3607 #define OP_ShiftLeft 76 /* same as TK_LSHIFT */
3608 #define OP_Dup 94
3609 #define OP_Goto 95
3610 #define OP_TableLock 96
3611 #define OP_FifoRead 97
3612 #define OP_Clear 98
3613 #define OP_IdxGT 99
3614 #define OP_MoveLt 100
3615 #define OP_Le 70 /* same as TK_LE */
3616 #define OP_VerifyCookie 101
3617 #define OP_AggStep 102
3618 #define OP_Pull 103
3619 #define OP_ToText 138 /* same as TK_TO_TEXT */
3620 #define OP_Not 16 /* same as TK_NOT */
3621 #define OP_ToReal 142 /* same as TK_TO_REAL */
3622 #define OP_SetNumColumns 104
3623 #define OP_AbsValue 105
3624 #define OP_Transaction 106
3625 #define OP_VFilter 107
3626 #define OP_Negative 85 /* same as TK_UMINUS */
3627 #define OP_Ne 67 /* same as TK_NE */
3628 #define OP_VDestroy 108
3629 #define OP_ContextPop 109
3630 #define OP_BitOr 75 /* same as TK_BITOR */
3631 #define OP_Next 110
3632 #define OP_IdxInsert 111
3633 #define OP_Distinct 112
3634 #define OP_Lt 71 /* same as TK_LT */
3635 #define OP_Insert 113
3636 #define OP_Destroy 114
3637 #define OP_ReadCookie 115
3638 #define OP_ForceInt 116
3639 #define OP_LoadAnalysis 117
3640 #define OP_Explain 118
3641 #define OP_IfMemZero 119
3642 #define OP_OpenPseudo 120
3643 #define OP_OpenEphemeral 121
3644 #define OP_Null 122
3645 #define OP_Blob 123
3646 #define OP_Add 78 /* same as TK_PLUS */
3647 #define OP_MemStore 124
3648 #define OP_Rewind 127
3649 #define OP_MoveGe 128
3650 #define OP_VBegin 129
3651 #define OP_VUpdate 130
3652 #define OP_BitNot 87 /* same as TK_BITNOT */
3653 #define OP_VCreate 131
3654 #define OP_MemMove 132
3655 #define OP_MemNull 133
3656 #define OP_Found 134
3657 #define OP_NullRow 135
3659 /* The following opcode values are never used */
3660 #define OP_NotUsed_136 136
3661 #define OP_NotUsed_137 137
3663 /* Opcodes that are guaranteed to never push a value onto the stack
3664 ** contain a 1 their corresponding position of the following mask
3665 ** set. See the opcodeNoPush() function in vdbeaux.c */
3666 #define NOPUSH_MASK_0 0xeeb4
3667 #define NOPUSH_MASK_1 0x796b
3668 #define NOPUSH_MASK_2 0x7ddb
3669 #define NOPUSH_MASK_3 0xff32
3670 #define NOPUSH_MASK_4 0xffff
3671 #define NOPUSH_MASK_5 0xb6f7
3672 #define NOPUSH_MASK_6 0xfdfd
3673 #define NOPUSH_MASK_7 0x93b3
3674 #define NOPUSH_MASK_8 0x7ccf
3675 #define NOPUSH_MASK_9 0x0000
3677 /************** End of opcodes.h *********************************************/
3678 /************** Continuing where we left off in vdbe.h ***********************/
3681 ** Prototypes for the VDBE interface. See comments on the implementation
3682 ** for a description of what each of these routines does.
3684 static Vdbe *sqlite3VdbeCreate(sqlite3*);
3685 static int sqlite3VdbeAddOp(Vdbe*,int,int,int);
3686 static int sqlite3VdbeOp3(Vdbe*,int,int,int,const char *zP3,int);
3687 static int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
3688 static void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
3689 static void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
3690 static void sqlite3VdbeJumpHere(Vdbe*, int addr);
3691 static void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
3692 static void sqlite3VdbeChangeP3(Vdbe*, int addr, const char *zP1, int N);
3693 static VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
3694 static int sqlite3VdbeMakeLabel(Vdbe*);
3695 static void sqlite3VdbeDelete(Vdbe*);
3696 static void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
3697 static int sqlite3VdbeFinalize(Vdbe*);
3698 static void sqlite3VdbeResolveLabel(Vdbe*, int);
3699 static int sqlite3VdbeCurrentAddr(Vdbe*);
3700 #ifdef SQLITE_DEBUG
3701 static void sqlite3VdbeTrace(Vdbe*,FILE*);
3702 #endif
3703 static void sqlite3VdbeResetStepResult(Vdbe*);
3704 static int sqlite3VdbeReset(Vdbe*);
3705 static void sqlite3VdbeSetNumCols(Vdbe*,int);
3706 static int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, int);
3707 static void sqlite3VdbeCountChanges(Vdbe*);
3708 static sqlite3 *sqlite3VdbeDb(Vdbe*);
3709 static void sqlite3VdbeSetSql(Vdbe*, const char *z, int n);
3710 static const char *sqlite3VdbeGetSql(Vdbe*);
3711 static void sqlite3VdbeSwap(Vdbe*,Vdbe*);
3713 #ifndef NDEBUG
3714 static void sqlite3VdbeComment(Vdbe*, const char*, ...);
3715 # define VdbeComment(X) sqlite3VdbeComment X
3716 #else
3717 # define VdbeComment(X)
3718 #endif
3720 #endif
3722 /************** End of vdbe.h ************************************************/
3723 /************** Continuing where we left off in sqliteInt.h ******************/
3724 /************** Include btree.h in the middle of sqliteInt.h *****************/
3725 /************** Begin file btree.h *******************************************/
3727 ** 2001 September 15
3729 ** The author disclaims copyright to this source code. In place of
3730 ** a legal notice, here is a blessing:
3732 ** May you do good and not evil.
3733 ** May you find forgiveness for yourself and forgive others.
3734 ** May you share freely, never taking more than you give.
3736 *************************************************************************
3737 ** This header file defines the interface that the sqlite B-Tree file
3738 ** subsystem. See comments in the source code for a detailed description
3739 ** of what each interface routine does.
3741 ** @(#) $Id: btree.h,v 1.82 2007/05/08 21:45:27 drh Exp $
3743 #ifndef _BTREE_H_
3744 #define _BTREE_H_
3746 /* TODO: This definition is just included so other modules compile. It
3747 ** needs to be revisited.
3749 #define SQLITE_N_BTREE_META 10
3752 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
3753 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
3755 #ifndef SQLITE_DEFAULT_AUTOVACUUM
3756 #define SQLITE_DEFAULT_AUTOVACUUM 0
3757 #endif
3759 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
3760 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
3761 #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
3764 ** Forward declarations of structure
3766 typedef struct Btree Btree;
3767 typedef struct BtCursor BtCursor;
3768 typedef struct BtShared BtShared;
3771 static int sqlite3BtreeOpen(
3772 const char *zFilename, /* Name of database file to open */
3773 sqlite3 *db, /* Associated database connection */
3774 Btree **, /* Return open Btree* here */
3775 int flags /* Flags */
3778 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
3779 ** following values.
3781 ** NOTE: These values must match the corresponding PAGER_ values in
3782 ** pager.h.
3784 #define BTREE_OMIT_JOURNAL 1 /* Do not use journal. No argument */
3785 #define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
3786 #define BTREE_MEMORY 4 /* In-memory DB. No argument */
3788 static int sqlite3BtreeClose(Btree*);
3789 static int sqlite3BtreeSetBusyHandler(Btree*,BusyHandler*);
3790 static int sqlite3BtreeSetCacheSize(Btree*,int);
3791 static int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
3792 static int sqlite3BtreeSyncDisabled(Btree*);
3793 static int sqlite3BtreeSetPageSize(Btree*,int,int);
3794 static int sqlite3BtreeGetPageSize(Btree*);
3795 static int sqlite3BtreeMaxPageCount(Btree*,int);
3796 static int sqlite3BtreeGetReserve(Btree*);
3797 static int sqlite3BtreeSetAutoVacuum(Btree *, int);
3798 static int sqlite3BtreeGetAutoVacuum(Btree *);
3799 static int sqlite3BtreeBeginTrans(Btree*,int);
3800 static int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
3801 static int sqlite3BtreeCommitPhaseTwo(Btree*);
3802 static int sqlite3BtreeCommit(Btree*);
3803 static int sqlite3BtreeRollback(Btree*);
3804 static int sqlite3BtreeBeginStmt(Btree*);
3805 static int sqlite3BtreeCommitStmt(Btree*);
3806 static int sqlite3BtreeRollbackStmt(Btree*);
3807 static int sqlite3BtreeCreateTable(Btree*, int*, int flags);
3808 static int sqlite3BtreeIsInTrans(Btree*);
3809 static int sqlite3BtreeIsInStmt(Btree*);
3810 static int sqlite3BtreeIsInReadTrans(Btree*);
3811 static void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
3812 static int sqlite3BtreeSchemaLocked(Btree *);
3813 static int sqlite3BtreeLockTable(Btree *, int, u8);
3815 static const char *sqlite3BtreeGetFilename(Btree *);
3816 static const char *sqlite3BtreeGetDirname(Btree *);
3817 static const char *sqlite3BtreeGetJournalname(Btree *);
3818 static int sqlite3BtreeCopyFile(Btree *, Btree *);
3820 static int sqlite3BtreeIncrVacuum(Btree *);
3822 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
3823 ** of the following flags:
3825 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
3826 #define BTREE_ZERODATA 2 /* Table has keys only - no data */
3827 #define BTREE_LEAFDATA 4 /* Data stored in leaves only. Implies INTKEY */
3829 static int sqlite3BtreeDropTable(Btree*, int, int*);
3830 static int sqlite3BtreeClearTable(Btree*, int);
3831 static int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
3832 static int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
3834 static int sqlite3BtreeCursor(
3835 Btree*, /* BTree containing table to open */
3836 int iTable, /* Index of root page */
3837 int wrFlag, /* 1 for writing. 0 for read-only */
3838 int(*)(void*,int,const void*,int,const void*), /* Key comparison function */
3839 void*, /* First argument to compare function */
3840 BtCursor **ppCursor /* Returned cursor */
3843 static int sqlite3BtreeCloseCursor(BtCursor*);
3844 static int sqlite3BtreeMoveto(BtCursor*,const void *pKey,i64 nKey,int bias,int *pRes);
3845 static int sqlite3BtreeDelete(BtCursor*);
3846 static int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
3847 const void *pData, int nData,
3848 int nZero, int bias);
3849 static int sqlite3BtreeFirst(BtCursor*, int *pRes);
3850 static int sqlite3BtreeLast(BtCursor*, int *pRes);
3851 static int sqlite3BtreeNext(BtCursor*, int *pRes);
3852 static int sqlite3BtreeEof(BtCursor*);
3853 static int sqlite3BtreeFlags(BtCursor*);
3854 static int sqlite3BtreePrevious(BtCursor*, int *pRes);
3855 static int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
3856 static int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
3857 static const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
3858 static const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
3859 static int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
3860 static int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
3862 static char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
3863 static struct Pager *sqlite3BtreePager(Btree*);
3865 static int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
3866 static void sqlite3BtreeCacheOverflow(BtCursor *);
3868 #ifdef SQLITE_TEST
3869 static int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
3870 static void sqlite3BtreeCursorList(Btree*);
3871 static int sqlite3BtreePageDump(Btree*, int, int recursive);
3872 #endif
3874 #endif /* _BTREE_H_ */
3876 /************** End of btree.h ***********************************************/
3877 /************** Continuing where we left off in sqliteInt.h ******************/
3878 /************** Include pager.h in the middle of sqliteInt.h *****************/
3879 /************** Begin file pager.h *******************************************/
3881 ** 2001 September 15
3883 ** The author disclaims copyright to this source code. In place of
3884 ** a legal notice, here is a blessing:
3886 ** May you do good and not evil.
3887 ** May you find forgiveness for yourself and forgive others.
3888 ** May you share freely, never taking more than you give.
3890 *************************************************************************
3891 ** This header file defines the interface that the sqlite page cache
3892 ** subsystem. The page cache subsystem reads and writes a file a page
3893 ** at a time and provides a journal for rollback.
3895 ** @(#) $Id: pager.h,v 1.61 2007/05/08 21:45:28 drh Exp $
3898 #ifndef _PAGER_H_
3899 #define _PAGER_H_
3902 ** The type used to represent a page number. The first page in a file
3903 ** is called page 1. 0 is used to represent "not a page".
3905 typedef unsigned int Pgno;
3908 ** Each open file is managed by a separate instance of the "Pager" structure.
3910 typedef struct Pager Pager;
3913 ** Handle type for pages.
3915 typedef struct PgHdr DbPage;
3918 ** Allowed values for the flags parameter to sqlite3PagerOpen().
3920 ** NOTE: This values must match the corresponding BTREE_ values in btree.h.
3922 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
3923 #define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */
3926 ** Valid values for the second argument to sqlite3PagerLockingMode().
3928 #define PAGER_LOCKINGMODE_QUERY -1
3929 #define PAGER_LOCKINGMODE_NORMAL 0
3930 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
3933 ** See source code comments for a detailed description of the following
3934 ** routines:
3936 static int sqlite3PagerOpen(Pager **ppPager, const char *zFilename,
3937 int nExtra, int flags);
3938 static void sqlite3PagerSetBusyhandler(Pager*, BusyHandler *pBusyHandler);
3939 static void sqlite3PagerSetDestructor(Pager*, void(*)(DbPage*,int));
3940 static void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*,int));
3941 static int sqlite3PagerSetPagesize(Pager*, int);
3942 static int sqlite3PagerMaxPageCount(Pager*, int);
3943 static int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
3944 static void sqlite3PagerSetCachesize(Pager*, int);
3945 static int sqlite3PagerClose(Pager *pPager);
3946 static int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
3947 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
3948 static DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
3949 static int sqlite3PagerRef(DbPage*);
3950 static int sqlite3PagerUnref(DbPage*);
3951 static int sqlite3PagerWrite(DbPage*);
3952 static int sqlite3PagerOverwrite(Pager *pPager, Pgno pgno, void*);
3953 static int sqlite3PagerPagecount(Pager*);
3954 static int sqlite3PagerTruncate(Pager*,Pgno);
3955 static int sqlite3PagerBegin(DbPage*, int exFlag);
3956 static int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, Pgno);
3957 static int sqlite3PagerCommitPhaseTwo(Pager*);
3958 static int sqlite3PagerRollback(Pager*);
3959 static int sqlite3PagerIsreadonly(Pager*);
3960 static int sqlite3PagerStmtBegin(Pager*);
3961 static int sqlite3PagerStmtCommit(Pager*);
3962 static int sqlite3PagerStmtRollback(Pager*);
3963 static void sqlite3PagerDontRollback(DbPage*);
3964 static void sqlite3PagerDontWrite(DbPage*);
3965 static int sqlite3PagerRefcount(Pager*);
3966 static void sqlite3PagerSetSafetyLevel(Pager*,int,int);
3967 static const char *sqlite3PagerFilename(Pager*);
3968 static const char *sqlite3PagerDirname(Pager*);
3969 static const char *sqlite3PagerJournalname(Pager*);
3970 static int sqlite3PagerNosync(Pager*);
3971 static int sqlite3PagerMovepage(Pager*,DbPage*,Pgno);
3972 static void *sqlite3PagerGetData(DbPage *);
3973 static void *sqlite3PagerGetExtra(DbPage *);
3974 static int sqlite3PagerLockingMode(Pager *, int);
3976 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
3977 static int sqlite3PagerReleaseMemory(int);
3978 #endif
3980 #ifdef SQLITE_HAS_CODEC
3981 static void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
3982 #endif
3984 #if !defined(NDEBUG) || defined(SQLITE_TEST)
3985 static Pgno sqlite3PagerPagenumber(DbPage*);
3986 static int sqlite3PagerIswriteable(DbPage*);
3987 #endif
3989 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
3990 static int sqlite3PagerLockstate(Pager*);
3991 #endif
3993 #ifdef SQLITE_TEST
3994 static int *sqlite3PagerStats(Pager*);
3995 static void sqlite3PagerRefdump(Pager*);
3996 int pager3_refinfo_enable;
3997 #endif
3999 #ifdef SQLITE_TEST
4000 void disable_simulated_io_errors(void);
4001 void enable_simulated_io_errors(void);
4002 #else
4003 # define disable_simulated_io_errors()
4004 # define enable_simulated_io_errors()
4005 #endif
4007 #endif /* _PAGER_H_ */
4009 /************** End of pager.h ***********************************************/
4010 /************** Continuing where we left off in sqliteInt.h ******************/
4012 #ifdef SQLITE_MEMDEBUG
4014 ** The following global variables are used for testing and debugging
4015 ** only. They only work if SQLITE_MEMDEBUG is defined.
4017 extern int sqlite3_nMalloc; /* Number of sqliteMalloc() calls */
4018 extern int sqlite3_nFree; /* Number of sqliteFree() calls */
4019 extern int sqlite3_iMallocFail; /* Fail sqliteMalloc() after this many calls */
4020 extern int sqlite3_iMallocReset; /* Set iMallocFail to this when it reaches 0 */
4022 extern void *sqlite3_pFirst; /* Pointer to linked list of allocations */
4023 extern int sqlite3_nMaxAlloc; /* High water mark of ThreadData.nAlloc */
4024 extern int sqlite3_mallocDisallowed; /* assert() in sqlite3Malloc() if set */
4025 extern int sqlite3_isFail; /* True if all malloc calls should fail */
4026 extern const char *sqlite3_zFile; /* Filename to associate debug info with */
4027 extern int sqlite3_iLine; /* Line number for debug info */
4029 #define ENTER_MALLOC (sqlite3_zFile = __FILE__, sqlite3_iLine = __LINE__)
4030 #define sqliteMalloc(x) (ENTER_MALLOC, sqlite3Malloc(x,1))
4031 #define sqliteMallocRaw(x) (ENTER_MALLOC, sqlite3MallocRaw(x,1))
4032 #define sqliteRealloc(x,y) (ENTER_MALLOC, sqlite3Realloc(x,y))
4033 #define sqliteStrDup(x) (ENTER_MALLOC, sqlite3StrDup(x))
4034 #define sqliteStrNDup(x,y) (ENTER_MALLOC, sqlite3StrNDup(x,y))
4035 #define sqliteReallocOrFree(x,y) (ENTER_MALLOC, sqlite3ReallocOrFree(x,y))
4037 #else
4039 #define ENTER_MALLOC 0
4040 #define sqliteMalloc(x) sqlite3Malloc(x,1)
4041 #define sqliteMallocRaw(x) sqlite3MallocRaw(x,1)
4042 #define sqliteRealloc(x,y) sqlite3Realloc(x,y)
4043 #define sqliteStrDup(x) sqlite3StrDup(x)
4044 #define sqliteStrNDup(x,y) sqlite3StrNDup(x,y)
4045 #define sqliteReallocOrFree(x,y) sqlite3ReallocOrFree(x,y)
4047 #endif
4049 /* Variable sqlite3_mallocHasFailed is set to true after a malloc()
4050 ** failure occurs.
4052 ** The sqlite3MallocFailed() macro returns true if a malloc has failed
4053 ** in this thread since the last call to sqlite3ApiExit(), or false
4054 ** otherwise.
4056 extern int sqlite3_mallocHasFailed;
4057 #define sqlite3MallocFailed() (sqlite3_mallocHasFailed && sqlite3OsInMutex(1))
4059 #define sqliteFree(x) sqlite3FreeX(x)
4060 #define sqliteAllocSize(x) sqlite3AllocSize(x)
4063 ** An instance of this structure might be allocated to store information
4064 ** specific to a single thread.
4066 struct ThreadData {
4067 int dummy; /* So that this structure is never empty */
4069 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
4070 int nSoftHeapLimit; /* Suggested max mem allocation. No limit if <0 */
4071 int nAlloc; /* Number of bytes currently allocated */
4072 Pager *pPager; /* Linked list of all pagers in this thread */
4073 #endif
4075 #ifndef SQLITE_OMIT_SHARED_CACHE
4076 u8 useSharedData; /* True if shared pagers and schemas are enabled */
4077 BtShared *pBtree; /* Linked list of all currently open BTrees */
4078 #endif
4082 ** Name of the master database table. The master database table
4083 ** is a special table that holds the names and attributes of all
4084 ** user tables and indices.
4086 #define MASTER_NAME "sqlite_master"
4087 #define TEMP_MASTER_NAME "sqlite_temp_master"
4090 ** The root-page of the master database table.
4092 #define MASTER_ROOT 1
4095 ** The name of the schema table.
4097 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
4100 ** A convenience macro that returns the number of elements in
4101 ** an array.
4103 #define ArraySize(X) (sizeof(X)/sizeof(X[0]))
4106 ** Forward references to structures
4108 typedef struct AggInfo AggInfo;
4109 typedef struct AuthContext AuthContext;
4110 typedef struct CollSeq CollSeq;
4111 typedef struct Column Column;
4112 typedef struct Db Db;
4113 typedef struct Schema Schema;
4114 typedef struct Expr Expr;
4115 typedef struct ExprList ExprList;
4116 typedef struct FKey FKey;
4117 typedef struct FuncDef FuncDef;
4118 typedef struct IdList IdList;
4119 typedef struct Index Index;
4120 typedef struct KeyClass KeyClass;
4121 typedef struct KeyInfo KeyInfo;
4122 typedef struct Module Module;
4123 typedef struct NameContext NameContext;
4124 typedef struct Parse Parse;
4125 typedef struct Select Select;
4126 typedef struct SrcList SrcList;
4127 typedef struct ThreadData ThreadData;
4128 typedef struct Table Table;
4129 typedef struct TableLock TableLock;
4130 typedef struct Token Token;
4131 typedef struct TriggerStack TriggerStack;
4132 typedef struct TriggerStep TriggerStep;
4133 typedef struct Trigger Trigger;
4134 typedef struct WhereInfo WhereInfo;
4135 typedef struct WhereLevel WhereLevel;
4137 /************** Include os.h in the middle of sqliteInt.h ********************/
4138 /************** Begin file os.h **********************************************/
4140 ** 2001 September 16
4142 ** The author disclaims copyright to this source code. In place of
4143 ** a legal notice, here is a blessing:
4145 ** May you do good and not evil.
4146 ** May you find forgiveness for yourself and forgive others.
4147 ** May you share freely, never taking more than you give.
4149 ******************************************************************************
4151 ** This header file (together with is companion C source-code file
4152 ** "os.c") attempt to abstract the underlying operating system so that
4153 ** the SQLite library will work on both POSIX and windows systems.
4155 #ifndef _SQLITE_OS_H_
4156 #define _SQLITE_OS_H_
4159 ** Figure out if we are dealing with Unix, Windows, or some other
4160 ** operating system.
4162 #if defined(OS_OTHER)
4163 # if OS_OTHER==1
4164 # undef OS_UNIX
4165 # define OS_UNIX 0
4166 # undef OS_WIN
4167 # define OS_WIN 0
4168 # undef OS_OS2
4169 # define OS_OS2 0
4170 # else
4171 # undef OS_OTHER
4172 # endif
4173 #endif
4174 #if !defined(OS_UNIX) && !defined(OS_OTHER)
4175 # define OS_OTHER 0
4176 # ifndef OS_WIN
4177 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
4178 # define OS_WIN 1
4179 # define OS_UNIX 0
4180 # define OS_OS2 0
4181 # elif defined(_EMX_) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
4182 # define OS_WIN 0
4183 # define OS_UNIX 0
4184 # define OS_OS2 1
4185 # else
4186 # define OS_WIN 0
4187 # define OS_UNIX 1
4188 # define OS_OS2 0
4189 # endif
4190 # else
4191 # define OS_UNIX 0
4192 # define OS_OS2 0
4193 # endif
4194 #else
4195 # ifndef OS_WIN
4196 # define OS_WIN 0
4197 # endif
4198 #endif
4202 ** Define the maximum size of a temporary filename
4204 #if OS_WIN
4205 # include <windows.h>
4206 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
4207 #elif OS_OS2
4208 # define INCL_DOSDATETIME
4209 # define INCL_DOSFILEMGR
4210 # define INCL_DOSERRORS
4211 # define INCL_DOSMISC
4212 # define INCL_DOSPROCESS
4213 # include <os2.h>
4214 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
4215 #else
4216 # define SQLITE_TEMPNAME_SIZE 200
4217 #endif
4219 /* If the SET_FULLSYNC macro is not defined above, then make it
4220 ** a no-op
4222 #ifndef SET_FULLSYNC
4223 # define SET_FULLSYNC(x,y)
4224 #endif
4227 ** The default size of a disk sector
4229 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
4230 # define SQLITE_DEFAULT_SECTOR_SIZE 512
4231 #endif
4234 ** Temporary files are named starting with this prefix followed by 16 random
4235 ** alphanumeric characters, and no file extension. They are stored in the
4236 ** OS's standard temporary file directory, and are deleted prior to exit.
4237 ** If sqlite is being embedded in another program, you may wish to change the
4238 ** prefix to reflect your program's name, so that if your program exits
4239 ** prematurely, old temporary files can be easily identified. This can be done
4240 ** using -DTEMP_FILE_PREFIX=myprefix_ on the compiler command line.
4242 ** 2006-10-31: The default prefix used to be "sqlite_". But then
4243 ** Mcafee started using SQLite in their anti-virus product and it
4244 ** started putting files with the "sqlite" name in the c:/temp folder.
4245 ** This annoyed many windows users. Those users would then do a
4246 ** Google search for "sqlite", find the telephone numbers of the
4247 ** developers and call to wake them up at night and complain.
4248 ** For this reason, the default name prefix is changed to be "sqlite"
4249 ** spelled backwards. So the temp files are still identified, but
4250 ** anybody smart enough to figure out the code is also likely smart
4251 ** enough to know that calling the developer will not help get rid
4252 ** of the file.
4254 #ifndef TEMP_FILE_PREFIX
4255 # define TEMP_FILE_PREFIX "etilqs_"
4256 #endif
4259 ** Define the interfaces for Unix, Windows, and OS/2.
4261 #if OS_UNIX
4262 #define sqlite3OsOpenReadWrite sqlite3UnixOpenReadWrite
4263 #define sqlite3OsOpenExclusive sqlite3UnixOpenExclusive
4264 #define sqlite3OsOpenReadOnly sqlite3UnixOpenReadOnly
4265 #define sqlite3OsDelete sqlite3UnixDelete
4266 #define sqlite3OsFileExists sqlite3UnixFileExists
4267 #define sqlite3OsFullPathname sqlite3UnixFullPathname
4268 #define sqlite3OsIsDirWritable sqlite3UnixIsDirWritable
4269 #define sqlite3OsSyncDirectory sqlite3UnixSyncDirectory
4270 #define sqlite3OsTempFileName sqlite3UnixTempFileName
4271 #define sqlite3OsRandomSeed sqlite3UnixRandomSeed
4272 #define sqlite3OsSleep sqlite3UnixSleep
4273 #define sqlite3OsCurrentTime sqlite3UnixCurrentTime
4274 #define sqlite3OsEnterMutex sqlite3UnixEnterMutex
4275 #define sqlite3OsLeaveMutex sqlite3UnixLeaveMutex
4276 #define sqlite3OsInMutex sqlite3UnixInMutex
4277 #define sqlite3OsThreadSpecificData sqlite3UnixThreadSpecificData
4278 #define sqlite3OsMalloc sqlite3GenericMalloc
4279 #define sqlite3OsRealloc sqlite3GenericRealloc
4280 #define sqlite3OsFree sqlite3GenericFree
4281 #define sqlite3OsAllocationSize sqlite3GenericAllocationSize
4282 #define sqlite3OsDlopen sqlite3UnixDlopen
4283 #define sqlite3OsDlsym sqlite3UnixDlsym
4284 #define sqlite3OsDlclose sqlite3UnixDlclose
4285 #endif
4286 #if OS_WIN
4287 #define sqlite3OsOpenReadWrite sqlite3WinOpenReadWrite
4288 #define sqlite3OsOpenExclusive sqlite3WinOpenExclusive
4289 #define sqlite3OsOpenReadOnly sqlite3WinOpenReadOnly
4290 #define sqlite3OsDelete sqlite3WinDelete
4291 #define sqlite3OsFileExists sqlite3WinFileExists
4292 #define sqlite3OsFullPathname sqlite3WinFullPathname
4293 #define sqlite3OsIsDirWritable sqlite3WinIsDirWritable
4294 #define sqlite3OsSyncDirectory sqlite3WinSyncDirectory
4295 #define sqlite3OsTempFileName sqlite3WinTempFileName
4296 #define sqlite3OsRandomSeed sqlite3WinRandomSeed
4297 #define sqlite3OsSleep sqlite3WinSleep
4298 #define sqlite3OsCurrentTime sqlite3WinCurrentTime
4299 #define sqlite3OsEnterMutex sqlite3WinEnterMutex
4300 #define sqlite3OsLeaveMutex sqlite3WinLeaveMutex
4301 #define sqlite3OsInMutex sqlite3WinInMutex
4302 #define sqlite3OsThreadSpecificData sqlite3WinThreadSpecificData
4303 #define sqlite3OsMalloc sqlite3GenericMalloc
4304 #define sqlite3OsRealloc sqlite3GenericRealloc
4305 #define sqlite3OsFree sqlite3GenericFree
4306 #define sqlite3OsAllocationSize sqlite3GenericAllocationSize
4307 #define sqlite3OsDlopen sqlite3WinDlopen
4308 #define sqlite3OsDlsym sqlite3WinDlsym
4309 #define sqlite3OsDlclose sqlite3WinDlclose
4310 #endif
4311 #if OS_OS2
4312 #define sqlite3OsOpenReadWrite sqlite3Os2OpenReadWrite
4313 #define sqlite3OsOpenExclusive sqlite3Os2OpenExclusive
4314 #define sqlite3OsOpenReadOnly sqlite3Os2OpenReadOnly
4315 #define sqlite3OsDelete sqlite3Os2Delete
4316 #define sqlite3OsFileExists sqlite3Os2FileExists
4317 #define sqlite3OsFullPathname sqlite3Os2FullPathname
4318 #define sqlite3OsIsDirWritable sqlite3Os2IsDirWritable
4319 #define sqlite3OsSyncDirectory sqlite3Os2SyncDirectory
4320 #define sqlite3OsTempFileName sqlite3Os2TempFileName
4321 #define sqlite3OsRandomSeed sqlite3Os2RandomSeed
4322 #define sqlite3OsSleep sqlite3Os2Sleep
4323 #define sqlite3OsCurrentTime sqlite3Os2CurrentTime
4324 #define sqlite3OsEnterMutex sqlite3Os2EnterMutex
4325 #define sqlite3OsLeaveMutex sqlite3Os2LeaveMutex
4326 #define sqlite3OsInMutex sqlite3Os2InMutex
4327 #define sqlite3OsThreadSpecificData sqlite3Os2ThreadSpecificData
4328 #define sqlite3OsMalloc sqlite3GenericMalloc
4329 #define sqlite3OsRealloc sqlite3GenericRealloc
4330 #define sqlite3OsFree sqlite3GenericFree
4331 #define sqlite3OsAllocationSize sqlite3GenericAllocationSize
4332 #define sqlite3OsDlopen sqlite3Os2Dlopen
4333 #define sqlite3OsDlsym sqlite3Os2Dlsym
4334 #define sqlite3OsDlclose sqlite3Os2Dlclose
4335 #endif
4341 ** If using an alternative OS interface, then we must have an "os_other.h"
4342 ** header file available for that interface. Presumably the "os_other.h"
4343 ** header file contains #defines similar to those above.
4345 #if OS_OTHER
4346 # include "os_other.h"
4347 #endif
4352 ** Forward declarations
4354 typedef struct OsFile OsFile;
4355 typedef struct IoMethod IoMethod;
4358 ** An instance of the following structure contains pointers to all
4359 ** methods on an OsFile object.
4361 struct IoMethod {
4362 int (*xClose)(OsFile**);
4363 int (*xOpenDirectory)(OsFile*, const char*);
4364 int (*xRead)(OsFile*, void*, int amt);
4365 int (*xWrite)(OsFile*, const void*, int amt);
4366 int (*xSeek)(OsFile*, i64 offset);
4367 int (*xTruncate)(OsFile*, i64 size);
4368 int (*xSync)(OsFile*, int);
4369 void (*xSetFullSync)(OsFile *id, int setting);
4370 int (*xFileHandle)(OsFile *id);
4371 int (*xFileSize)(OsFile*, i64 *pSize);
4372 int (*xLock)(OsFile*, int);
4373 int (*xUnlock)(OsFile*, int);
4374 int (*xLockState)(OsFile *id);
4375 int (*xCheckReservedLock)(OsFile *id);
4376 int (*xSectorSize)(OsFile *id);
4380 ** The OsFile object describes an open disk file in an OS-dependent way.
4381 ** The version of OsFile defined here is a generic version. Each OS
4382 ** implementation defines its own subclass of this structure that contains
4383 ** additional information needed to handle file I/O. But the pMethod
4384 ** entry (pointing to the virtual function table) always occurs first
4385 ** so that we can always find the appropriate methods.
4387 struct OsFile {
4388 IoMethod const *pMethod;
4392 ** The following values may be passed as the second argument to
4393 ** sqlite3OsLock(). The various locks exhibit the following semantics:
4395 ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
4396 ** RESERVED: A single process may hold a RESERVED lock on a file at
4397 ** any time. Other processes may hold and obtain new SHARED locks.
4398 ** PENDING: A single process may hold a PENDING lock on a file at
4399 ** any one time. Existing SHARED locks may persist, but no new
4400 ** SHARED locks may be obtained by other processes.
4401 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
4403 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
4404 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
4405 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
4406 ** sqlite3OsLock().
4408 #define NO_LOCK 0
4409 #define SHARED_LOCK 1
4410 #define RESERVED_LOCK 2
4411 #define PENDING_LOCK 3
4412 #define EXCLUSIVE_LOCK 4
4415 ** File Locking Notes: (Mostly about windows but also some info for Unix)
4417 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
4418 ** those functions are not available. So we use only LockFile() and
4419 ** UnlockFile().
4421 ** LockFile() prevents not just writing but also reading by other processes.
4422 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
4423 ** byte out of a specific range of bytes. The lock byte is obtained at
4424 ** random so two separate readers can probably access the file at the
4425 ** same time, unless they are unlucky and choose the same lock byte.
4426 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
4427 ** There can only be one writer. A RESERVED_LOCK is obtained by locking
4428 ** a single byte of the file that is designated as the reserved lock byte.
4429 ** A PENDING_LOCK is obtained by locking a designated byte different from
4430 ** the RESERVED_LOCK byte.
4432 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
4433 ** which means we can use reader/writer locks. When reader/writer locks
4434 ** are used, the lock is placed on the same range of bytes that is used
4435 ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
4436 ** will support two or more Win95 readers or two or more WinNT readers.
4437 ** But a single Win95 reader will lock out all WinNT readers and a single
4438 ** WinNT reader will lock out all other Win95 readers.
4440 ** The following #defines specify the range of bytes used for locking.
4441 ** SHARED_SIZE is the number of bytes available in the pool from which
4442 ** a random byte is selected for a shared lock. The pool of bytes for
4443 ** shared locks begins at SHARED_FIRST.
4445 ** These #defines are available in sqlite_aux.h so that adaptors for
4446 ** connecting SQLite to other operating systems can use the same byte
4447 ** ranges for locking. In particular, the same locking strategy and
4448 ** byte ranges are used for Unix. This leaves open the possiblity of having
4449 ** clients on win95, winNT, and unix all talking to the same shared file
4450 ** and all locking correctly. To do so would require that samba (or whatever
4451 ** tool is being used for file sharing) implements locks correctly between
4452 ** windows and unix. I'm guessing that isn't likely to happen, but by
4453 ** using the same locking range we are at least open to the possibility.
4455 ** Locking in windows is manditory. For this reason, we cannot store
4456 ** actual data in the bytes used for locking. The pager never allocates
4457 ** the pages involved in locking therefore. SHARED_SIZE is selected so
4458 ** that all locks will fit on a single page even at the minimum page size.
4459 ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
4460 ** is set high so that we don't have to allocate an unused page except
4461 ** for very large databases. But one should test the page skipping logic
4462 ** by setting PENDING_BYTE low and running the entire regression suite.
4464 ** Changing the value of PENDING_BYTE results in a subtly incompatible
4465 ** file format. Depending on how it is changed, you might not notice
4466 ** the incompatibility right away, even running a full regression test.
4467 ** The default location of PENDING_BYTE is the first byte past the
4468 ** 1GB boundary.
4471 #ifndef SQLITE_TEST
4472 #define PENDING_BYTE 0x40000000 /* First byte past the 1GB boundary */
4473 #else
4474 extern unsigned int sqlite3_pending_byte;
4475 #define PENDING_BYTE sqlite3_pending_byte
4476 #endif
4478 #define RESERVED_BYTE (PENDING_BYTE+1)
4479 #define SHARED_FIRST (PENDING_BYTE+2)
4480 #define SHARED_SIZE 510
4483 ** Prototypes for operating system interface routines.
4485 static int sqlite3OsClose(OsFile**);
4486 static int sqlite3OsOpenDirectory(OsFile*, const char*);
4487 static int sqlite3OsRead(OsFile*, void*, int amt);
4488 static int sqlite3OsWrite(OsFile*, const void*, int amt);
4489 static int sqlite3OsSeek(OsFile*, i64 offset);
4490 static int sqlite3OsTruncate(OsFile*, i64 size);
4491 static int sqlite3OsSync(OsFile*, int);
4492 static void sqlite3OsSetFullSync(OsFile *id, int setting);
4493 static int sqlite3OsFileSize(OsFile*, i64 *pSize);
4494 static int sqlite3OsLock(OsFile*, int);
4495 static int sqlite3OsUnlock(OsFile*, int);
4496 static int sqlite3OsCheckReservedLock(OsFile *id);
4497 static int sqlite3OsOpenReadWrite(const char*, OsFile**, int*);
4498 static int sqlite3OsOpenExclusive(const char*, OsFile**, int);
4499 static int sqlite3OsOpenReadOnly(const char*, OsFile**);
4500 static int sqlite3OsDelete(const char*);
4501 static int sqlite3OsFileExists(const char*);
4502 static char *sqlite3OsFullPathname(const char*);
4503 static int sqlite3OsIsDirWritable(char*);
4504 static int sqlite3OsSyncDirectory(const char*);
4505 static int sqlite3OsSectorSize(OsFile *id);
4506 static int sqlite3OsTempFileName(char*);
4507 static int sqlite3OsRandomSeed(char*);
4508 static int sqlite3OsSleep(int ms);
4509 static int sqlite3OsCurrentTime(double*);
4510 static void sqlite3OsEnterMutex(void);
4511 static void sqlite3OsLeaveMutex(void);
4512 static int sqlite3OsInMutex(int);
4513 static ThreadData *sqlite3OsThreadSpecificData(int);
4514 static void *sqlite3OsMalloc(int);
4515 static void *sqlite3OsRealloc(void *, int);
4516 static void sqlite3OsFree(void *);
4517 static int sqlite3OsAllocationSize(void *);
4518 static void *sqlite3OsDlopen(const char*);
4519 static void *sqlite3OsDlsym(void*, const char*);
4520 static int sqlite3OsDlclose(void*);
4522 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
4523 static int sqlite3OsFileHandle(OsFile *id);
4524 static int sqlite3OsLockState(OsFile *id);
4525 #endif
4528 ** If the SQLITE_ENABLE_REDEF_IO macro is defined, then the OS-layer
4529 ** interface routines are not called directly but are invoked using
4530 ** pointers to functions. This allows the implementation of various
4531 ** OS-layer interface routines to be modified at run-time. There are
4532 ** obscure but legitimate reasons for wanting to do this. But for
4533 ** most users, a direct call to the underlying interface is preferable
4534 ** so the the redefinable I/O interface is turned off by default.
4536 #ifdef SQLITE_ENABLE_REDEF_IO
4539 ** When redefinable I/O is enabled, a single global instance of the
4540 ** following structure holds pointers to the routines that SQLite
4541 ** uses to talk with the underlying operating system. Modify this
4542 ** structure (before using any SQLite API!) to accomodate perculiar
4543 ** operating system interfaces or behaviors.
4545 struct sqlite3OsVtbl {
4546 int (*xOpenReadWrite)(const char*, OsFile**, int*);
4547 int (*xOpenExclusive)(const char*, OsFile**, int);
4548 int (*xOpenReadOnly)(const char*, OsFile**);
4550 int (*xDelete)(const char*);
4551 int (*xFileExists)(const char*);
4552 char *(*xFullPathname)(const char*);
4553 int (*xIsDirWritable)(char*);
4554 int (*xSyncDirectory)(const char*);
4555 int (*xTempFileName)(char*);
4557 int (*xRandomSeed)(char*);
4558 int (*xSleep)(int ms);
4559 int (*xCurrentTime)(double*);
4561 void (*xEnterMutex)(void);
4562 void (*xLeaveMutex)(void);
4563 int (*xInMutex)(int);
4564 ThreadData *(*xThreadSpecificData)(int);
4566 void *(*xMalloc)(int);
4567 void *(*xRealloc)(void *, int);
4568 void (*xFree)(void *);
4569 int (*xAllocationSize)(void *);
4571 void *(*xDlopen)(const char*);
4572 void *(*xDlsym)(void*, const char*);
4573 int (*xDlclose)(void*);
4576 /* Macro used to comment out routines that do not exists when there is
4577 ** no disk I/O or extension loading
4579 #ifdef SQLITE_OMIT_DISKIO
4580 # define IF_DISKIO(X) 0
4581 #else
4582 # define IF_DISKIO(X) X
4583 #endif
4584 #ifdef SQLITE_OMIT_LOAD_EXTENSION
4585 # define IF_DLOPEN(X) 0
4586 #else
4587 # define IF_DLOPEN(X) X
4588 #endif
4591 #if defined(_SQLITE_OS_C_) || defined(SQLITE_AMALGAMATION)
4593 ** The os.c file implements the global virtual function table.
4594 ** We have to put this file here because the initializers
4595 ** (ex: sqlite3OsRandomSeed) are macros that are about to be
4596 ** redefined.
4598 struct sqlite3OsVtbl sqlite3Os = {
4599 IF_DISKIO( sqlite3OsOpenReadWrite ),
4600 IF_DISKIO( sqlite3OsOpenExclusive ),
4601 IF_DISKIO( sqlite3OsOpenReadOnly ),
4602 IF_DISKIO( sqlite3OsDelete ),
4603 IF_DISKIO( sqlite3OsFileExists ),
4604 IF_DISKIO( sqlite3OsFullPathname ),
4605 IF_DISKIO( sqlite3OsIsDirWritable ),
4606 IF_DISKIO( sqlite3OsSyncDirectory ),
4607 IF_DISKIO( sqlite3OsTempFileName ),
4608 sqlite3OsRandomSeed,
4609 sqlite3OsSleep,
4610 sqlite3OsCurrentTime,
4611 sqlite3OsEnterMutex,
4612 sqlite3OsLeaveMutex,
4613 sqlite3OsInMutex,
4614 sqlite3OsThreadSpecificData,
4615 sqlite3OsMalloc,
4616 sqlite3OsRealloc,
4617 sqlite3OsFree,
4618 sqlite3OsAllocationSize,
4619 IF_DLOPEN( sqlite3OsDlopen ),
4620 IF_DLOPEN( sqlite3OsDlsym ),
4621 IF_DLOPEN( sqlite3OsDlclose ),
4623 #else
4625 ** Files other than os.c just reference the global virtual function table.
4627 extern struct sqlite3OsVtbl sqlite3Os;
4628 #endif /* _SQLITE_OS_C_ */
4631 /* This additional API routine is available with redefinable I/O */
4632 struct sqlite3OsVtbl *sqlite3_os_switch(void);
4636 ** Redefine the OS interface to go through the virtual function table
4637 ** rather than calling routines directly.
4639 #undef sqlite3OsOpenReadWrite
4640 #undef sqlite3OsOpenExclusive
4641 #undef sqlite3OsOpenReadOnly
4642 #undef sqlite3OsDelete
4643 #undef sqlite3OsFileExists
4644 #undef sqlite3OsFullPathname
4645 #undef sqlite3OsIsDirWritable
4646 #undef sqlite3OsSyncDirectory
4647 #undef sqlite3OsTempFileName
4648 #undef sqlite3OsRandomSeed
4649 #undef sqlite3OsSleep
4650 #undef sqlite3OsCurrentTime
4651 #undef sqlite3OsEnterMutex
4652 #undef sqlite3OsLeaveMutex
4653 #undef sqlite3OsInMutex
4654 #undef sqlite3OsThreadSpecificData
4655 #undef sqlite3OsMalloc
4656 #undef sqlite3OsRealloc
4657 #undef sqlite3OsFree
4658 #undef sqlite3OsAllocationSize
4659 #define sqlite3OsOpenReadWrite sqlite3Os.xOpenReadWrite
4660 #define sqlite3OsOpenExclusive sqlite3Os.xOpenExclusive
4661 #define sqlite3OsOpenReadOnly sqlite3Os.xOpenReadOnly
4662 #define sqlite3OsDelete sqlite3Os.xDelete
4663 #define sqlite3OsFileExists sqlite3Os.xFileExists
4664 #define sqlite3OsFullPathname sqlite3Os.xFullPathname
4665 #define sqlite3OsIsDirWritable sqlite3Os.xIsDirWritable
4666 #define sqlite3OsSyncDirectory sqlite3Os.xSyncDirectory
4667 #define sqlite3OsTempFileName sqlite3Os.xTempFileName
4668 #define sqlite3OsRandomSeed sqlite3Os.xRandomSeed
4669 #define sqlite3OsSleep sqlite3Os.xSleep
4670 #define sqlite3OsCurrentTime sqlite3Os.xCurrentTime
4671 #define sqlite3OsEnterMutex sqlite3Os.xEnterMutex
4672 #define sqlite3OsLeaveMutex sqlite3Os.xLeaveMutex
4673 #define sqlite3OsInMutex sqlite3Os.xInMutex
4674 #define sqlite3OsThreadSpecificData sqlite3Os.xThreadSpecificData
4675 #define sqlite3OsMalloc sqlite3Os.xMalloc
4676 #define sqlite3OsRealloc sqlite3Os.xRealloc
4677 #define sqlite3OsFree sqlite3Os.xFree
4678 #define sqlite3OsAllocationSize sqlite3Os.xAllocationSize
4680 #endif /* SQLITE_ENABLE_REDEF_IO */
4682 #endif /* _SQLITE_OS_H_ */
4684 /************** End of os.h **************************************************/
4685 /************** Continuing where we left off in sqliteInt.h ******************/
4688 ** Each database file to be accessed by the system is an instance
4689 ** of the following structure. There are normally two of these structures
4690 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
4691 ** aDb[1] is the database file used to hold temporary tables. Additional
4692 ** databases may be attached.
4694 struct Db {
4695 char *zName; /* Name of this database */
4696 Btree *pBt; /* The B*Tree structure for this database file */
4697 u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
4698 u8 safety_level; /* How aggressive at synching data to disk */
4699 void *pAux; /* Auxiliary data. Usually NULL */
4700 void (*xFreeAux)(void*); /* Routine to free pAux */
4701 Schema *pSchema; /* Pointer to database schema (possibly shared) */
4705 ** An instance of the following structure stores a database schema.
4707 ** If there are no virtual tables configured in this schema, the
4708 ** Schema.db variable is set to NULL. After the first virtual table
4709 ** has been added, it is set to point to the database connection
4710 ** used to create the connection. Once a virtual table has been
4711 ** added to the Schema structure and the Schema.db variable populated,
4712 ** only that database connection may use the Schema to prepare
4713 ** statements.
4715 struct Schema {
4716 int schema_cookie; /* Database schema version number for this file */
4717 Hash tblHash; /* All tables indexed by name */
4718 Hash idxHash; /* All (named) indices indexed by name */
4719 Hash trigHash; /* All triggers indexed by name */
4720 Hash aFKey; /* Foreign keys indexed by to-table */
4721 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
4722 u8 file_format; /* Schema format version for this file */
4723 u8 enc; /* Text encoding used by this database */
4724 u16 flags; /* Flags associated with this schema */
4725 int cache_size; /* Number of pages to use in the cache */
4726 #ifndef SQLITE_OMIT_VIRTUALTABLE
4727 sqlite3 *db; /* "Owner" connection. See comment above */
4728 #endif
4732 ** These macros can be used to test, set, or clear bits in the
4733 ** Db.flags field.
4735 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
4736 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
4737 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
4738 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
4741 ** Allowed values for the DB.flags field.
4743 ** The DB_SchemaLoaded flag is set after the database schema has been
4744 ** read into internal hash tables.
4746 ** DB_UnresetViews means that one or more views have column names that
4747 ** have been filled out. If the schema changes, these column names might
4748 ** changes and so the view will need to be reset.
4750 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
4751 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
4752 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
4756 ** Each database is an instance of the following structure.
4758 ** The sqlite.lastRowid records the last insert rowid generated by an
4759 ** insert statement. Inserts on views do not affect its value. Each
4760 ** trigger has its own context, so that lastRowid can be updated inside
4761 ** triggers as usual. The previous value will be restored once the trigger
4762 ** exits. Upon entering a before or instead of trigger, lastRowid is no
4763 ** longer (since after version 2.8.12) reset to -1.
4765 ** The sqlite.nChange does not count changes within triggers and keeps no
4766 ** context. It is reset at start of sqlite3_exec.
4767 ** The sqlite.lsChange represents the number of changes made by the last
4768 ** insert, update, or delete statement. It remains constant throughout the
4769 ** length of a statement and is then updated by OP_SetCounts. It keeps a
4770 ** context stack just like lastRowid so that the count of changes
4771 ** within a trigger is not seen outside the trigger. Changes to views do not
4772 ** affect the value of lsChange.
4773 ** The sqlite.csChange keeps track of the number of current changes (since
4774 ** the last statement) and is used to update sqlite_lsChange.
4776 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
4777 ** store the most recent error code and, if applicable, string. The
4778 ** internal function sqlite3Error() is used to set these variables
4779 ** consistently.
4781 struct sqlite3 {
4782 int nDb; /* Number of backends currently in use */
4783 Db *aDb; /* All backends */
4784 int flags; /* Miscellanous flags. See below */
4785 int errCode; /* Most recent error code (SQLITE_*) */
4786 int errMask; /* & result codes with this before returning */
4787 u8 autoCommit; /* The auto-commit flag. */
4788 u8 temp_store; /* 1: file 2: memory 0: default */
4789 int nTable; /* Number of tables in the database */
4790 CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
4791 i64 lastRowid; /* ROWID of most recent insert (see above) */
4792 i64 priorNewRowid; /* Last randomly generated ROWID */
4793 int magic; /* Magic number for detect library misuse */
4794 int nChange; /* Value returned by sqlite3_changes() */
4795 int nTotalChange; /* Value returned by sqlite3_total_changes() */
4796 struct sqlite3InitInfo { /* Information used during initialization */
4797 int iDb; /* When back is being initialized */
4798 int newTnum; /* Rootpage of table being initialized */
4799 u8 busy; /* TRUE if currently initializing */
4800 } init;
4801 int nExtension; /* Number of loaded extensions */
4802 void **aExtension; /* Array of shared libraray handles */
4803 struct Vdbe *pVdbe; /* List of active virtual machines */
4804 int activeVdbeCnt; /* Number of vdbes currently executing */
4805 void (*xTrace)(void*,const char*); /* Trace function */
4806 void *pTraceArg; /* Argument to the trace function */
4807 void (*xProfile)(void*,const char*,u64); /* Profiling function */
4808 void *pProfileArg; /* Argument to profile function */
4809 void *pCommitArg; /* Argument to xCommitCallback() */
4810 int (*xCommitCallback)(void*); /* Invoked at every commit. */
4811 void *pRollbackArg; /* Argument to xRollbackCallback() */
4812 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
4813 void *pUpdateArg;
4814 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
4815 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
4816 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
4817 void *pCollNeededArg;
4818 sqlite3_value *pErr; /* Most recent error message */
4819 char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
4820 char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
4821 union {
4822 int isInterrupted; /* True if sqlite3_interrupt has been called */
4823 double notUsed1; /* Spacer */
4824 } u1;
4825 #ifndef SQLITE_OMIT_AUTHORIZATION
4826 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
4827 /* Access authorization function */
4828 void *pAuthArg; /* 1st argument to the access auth function */
4829 #endif
4830 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
4831 int (*xProgress)(void *); /* The progress callback */
4832 void *pProgressArg; /* Argument to the progress callback */
4833 int nProgressOps; /* Number of opcodes for progress callback */
4834 #endif
4835 #ifndef SQLITE_OMIT_VIRTUALTABLE
4836 Hash aModule; /* populated by sqlite3_create_module() */
4837 Table *pVTab; /* vtab with active Connect/Create method */
4838 sqlite3_vtab **aVTrans; /* Virtual tables with open transactions */
4839 int nVTrans; /* Allocated size of aVTrans */
4840 #endif
4841 Hash aFunc; /* All functions that can be in SQL exprs */
4842 Hash aCollSeq; /* All collating sequences */
4843 BusyHandler busyHandler; /* Busy callback */
4844 int busyTimeout; /* Busy handler timeout, in msec */
4845 Db aDbStatic[2]; /* Static space for the 2 default backends */
4846 #ifdef SQLITE_SSE
4847 sqlite3_stmt *pFetch; /* Used by SSE to fetch stored statements */
4848 #endif
4849 u8 dfltLockMode; /* Default locking-mode for attached dbs */
4853 ** A macro to discover the encoding of a database.
4855 #define ENC(db) ((db)->aDb[0].pSchema->enc)
4858 ** Possible values for the sqlite.flags and or Db.flags fields.
4860 ** On sqlite.flags, the SQLITE_InTrans value means that we have
4861 ** executed a BEGIN. On Db.flags, SQLITE_InTrans means a statement
4862 ** transaction is active on that particular database file.
4864 #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
4865 #define SQLITE_InTrans 0x00000008 /* True if in a transaction */
4866 #define SQLITE_InternChanges 0x00000010 /* Uncommitted Hash table changes */
4867 #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
4868 #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
4869 #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
4870 /* DELETE, or UPDATE and return */
4871 /* the count using a callback. */
4872 #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
4873 /* result set is empty */
4874 #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
4875 #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
4876 #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
4877 #define SQLITE_NoReadlock 0x00001000 /* Readlocks are omitted when
4878 ** accessing read-only databases */
4879 #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
4880 #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
4881 #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
4882 #define SQLITE_FullFSync 0x00010000 /* Use full fsync on the backend */
4883 #define SQLITE_LoadExtension 0x00020000 /* Enable load_extension */
4885 #define SQLITE_RecoveryMode 0x00040000 /* Ignore schema errors */
4888 ** Possible values for the sqlite.magic field.
4889 ** The numbers are obtained at random and have no special meaning, other
4890 ** than being distinct from one another.
4892 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
4893 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
4894 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
4895 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
4898 ** Each SQL function is defined by an instance of the following
4899 ** structure. A pointer to this structure is stored in the sqlite.aFunc
4900 ** hash table. When multiple functions have the same name, the hash table
4901 ** points to a linked list of these structures.
4903 struct FuncDef {
4904 i16 nArg; /* Number of arguments. -1 means unlimited */
4905 u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
4906 u8 needCollSeq; /* True if sqlite3GetFuncCollSeq() might be called */
4907 u8 flags; /* Some combination of SQLITE_FUNC_* */
4908 void *pUserData; /* User data parameter */
4909 FuncDef *pNext; /* Next function with same name */
4910 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
4911 void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
4912 void (*xFinalize)(sqlite3_context*); /* Aggregate finializer */
4913 char zName[1]; /* SQL name of the function. MUST BE LAST */
4917 ** Each SQLite module (virtual table definition) is defined by an
4918 ** instance of the following structure, stored in the sqlite3.aModule
4919 ** hash table.
4921 struct Module {
4922 const sqlite3_module *pModule; /* Callback pointers */
4923 const char *zName; /* Name passed to create_module() */
4924 void *pAux; /* pAux passed to create_module() */
4928 ** Possible values for FuncDef.flags
4930 #define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
4931 #define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
4932 #define SQLITE_FUNC_EPHEM 0x04 /* Ephermeral. Delete with VDBE */
4935 ** information about each column of an SQL table is held in an instance
4936 ** of this structure.
4938 struct Column {
4939 char *zName; /* Name of this column */
4940 Expr *pDflt; /* Default value of this column */
4941 char *zType; /* Data type for this column */
4942 char *zColl; /* Collating sequence. If NULL, use the default */
4943 u8 notNull; /* True if there is a NOT NULL constraint */
4944 u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */
4945 char affinity; /* One of the SQLITE_AFF_... values */
4949 ** A "Collating Sequence" is defined by an instance of the following
4950 ** structure. Conceptually, a collating sequence consists of a name and
4951 ** a comparison routine that defines the order of that sequence.
4953 ** There may two seperate implementations of the collation function, one
4954 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
4955 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
4956 ** native byte order. When a collation sequence is invoked, SQLite selects
4957 ** the version that will require the least expensive encoding
4958 ** translations, if any.
4960 ** The CollSeq.pUser member variable is an extra parameter that passed in
4961 ** as the first argument to the UTF-8 comparison function, xCmp.
4962 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
4963 ** xCmp16.
4965 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
4966 ** collating sequence is undefined. Indices built on an undefined
4967 ** collating sequence may not be read or written.
4969 struct CollSeq {
4970 char *zName; /* Name of the collating sequence, UTF-8 encoded */
4971 u8 enc; /* Text encoding handled by xCmp() */
4972 u8 type; /* One of the SQLITE_COLL_... values below */
4973 void *pUser; /* First argument to xCmp() */
4974 int (*xCmp)(void*,int, const void*, int, const void*);
4975 void (*xDel)(void*); /* Destructor for pUser */
4979 ** Allowed values of CollSeq flags:
4981 #define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */
4982 #define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */
4983 #define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */
4984 #define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */
4987 ** A sort order can be either ASC or DESC.
4989 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
4990 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
4993 ** Column affinity types.
4995 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
4996 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
4997 ** the speed a little by number the values consecutively.
4999 ** But rather than start with 0 or 1, we begin with 'a'. That way,
5000 ** when multiple affinity types are concatenated into a string and
5001 ** used as the P3 operand, they will be more readable.
5003 ** Note also that the numeric types are grouped together so that testing
5004 ** for a numeric type is a single comparison.
5006 #define SQLITE_AFF_TEXT 'a'
5007 #define SQLITE_AFF_NONE 'b'
5008 #define SQLITE_AFF_NUMERIC 'c'
5009 #define SQLITE_AFF_INTEGER 'd'
5010 #define SQLITE_AFF_REAL 'e'
5012 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
5015 ** Each SQL table is represented in memory by an instance of the
5016 ** following structure.
5018 ** Table.zName is the name of the table. The case of the original
5019 ** CREATE TABLE statement is stored, but case is not significant for
5020 ** comparisons.
5022 ** Table.nCol is the number of columns in this table. Table.aCol is a
5023 ** pointer to an array of Column structures, one for each column.
5025 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
5026 ** the column that is that key. Otherwise Table.iPKey is negative. Note
5027 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
5028 ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
5029 ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
5030 ** is generated for each row of the table. Table.hasPrimKey is true if
5031 ** the table has any PRIMARY KEY, INTEGER or otherwise.
5033 ** Table.tnum is the page number for the root BTree page of the table in the
5034 ** database file. If Table.iDb is the index of the database table backend
5035 ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
5036 ** holds temporary tables and indices. If Table.isEphem
5037 ** is true, then the table is stored in a file that is automatically deleted
5038 ** when the VDBE cursor to the table is closed. In this case Table.tnum
5039 ** refers VDBE cursor number that holds the table open, not to the root
5040 ** page number. Transient tables are used to hold the results of a
5041 ** sub-query that appears instead of a real table name in the FROM clause
5042 ** of a SELECT statement.
5044 struct Table {
5045 char *zName; /* Name of the table */
5046 int nCol; /* Number of columns in this table */
5047 Column *aCol; /* Information about each column */
5048 int iPKey; /* If not less then 0, use aCol[iPKey] as the primary key */
5049 Index *pIndex; /* List of SQL indexes on this table. */
5050 int tnum; /* Root BTree node for this table (see note above) */
5051 Select *pSelect; /* NULL for tables. Points to definition if a view. */
5052 int nRef; /* Number of pointers to this Table */
5053 Trigger *pTrigger; /* List of SQL triggers on this table */
5054 FKey *pFKey; /* Linked list of all foreign keys in this table */
5055 char *zColAff; /* String defining the affinity of each column */
5056 #ifndef SQLITE_OMIT_CHECK
5057 Expr *pCheck; /* The AND of all CHECK constraints */
5058 #endif
5059 #ifndef SQLITE_OMIT_ALTERTABLE
5060 int addColOffset; /* Offset in CREATE TABLE statement to add a new column */
5061 #endif
5062 u8 readOnly; /* True if this table should not be written by the user */
5063 u8 isEphem; /* True if created using OP_OpenEphermeral */
5064 u8 hasPrimKey; /* True if there exists a primary key */
5065 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
5066 u8 autoInc; /* True if the integer primary key is autoincrement */
5067 #ifndef SQLITE_OMIT_VIRTUALTABLE
5068 u8 isVirtual; /* True if this is a virtual table */
5069 u8 isCommit; /* True once the CREATE TABLE has been committed */
5070 Module *pMod; /* Pointer to the implementation of the module */
5071 sqlite3_vtab *pVtab; /* Pointer to the module instance */
5072 int nModuleArg; /* Number of arguments to the module */
5073 char **azModuleArg; /* Text of all module args. [0] is module name */
5074 #endif
5075 Schema *pSchema;
5079 ** Test to see whether or not a table is a virtual table. This is
5080 ** done as a macro so that it will be optimized out when virtual
5081 ** table support is omitted from the build.
5083 #ifndef SQLITE_OMIT_VIRTUALTABLE
5084 # define IsVirtual(X) ((X)->isVirtual)
5085 #else
5086 # define IsVirtual(X) 0
5087 #endif
5090 ** Each foreign key constraint is an instance of the following structure.
5092 ** A foreign key is associated with two tables. The "from" table is
5093 ** the table that contains the REFERENCES clause that creates the foreign
5094 ** key. The "to" table is the table that is named in the REFERENCES clause.
5095 ** Consider this example:
5097 ** CREATE TABLE ex1(
5098 ** a INTEGER PRIMARY KEY,
5099 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
5100 ** );
5102 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
5104 ** Each REFERENCES clause generates an instance of the following structure
5105 ** which is attached to the from-table. The to-table need not exist when
5106 ** the from-table is created. The existance of the to-table is not checked
5107 ** until an attempt is made to insert data into the from-table.
5109 ** The sqlite.aFKey hash table stores pointers to this structure
5110 ** given the name of a to-table. For each to-table, all foreign keys
5111 ** associated with that table are on a linked list using the FKey.pNextTo
5112 ** field.
5114 struct FKey {
5115 Table *pFrom; /* The table that constains the REFERENCES clause */
5116 FKey *pNextFrom; /* Next foreign key in pFrom */
5117 char *zTo; /* Name of table that the key points to */
5118 FKey *pNextTo; /* Next foreign key that points to zTo */
5119 int nCol; /* Number of columns in this key */
5120 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
5121 int iFrom; /* Index of column in pFrom */
5122 char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
5123 } *aCol; /* One entry for each of nCol column s */
5124 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
5125 u8 updateConf; /* How to resolve conflicts that occur on UPDATE */
5126 u8 deleteConf; /* How to resolve conflicts that occur on DELETE */
5127 u8 insertConf; /* How to resolve conflicts that occur on INSERT */
5131 ** SQLite supports many different ways to resolve a contraint
5132 ** error. ROLLBACK processing means that a constraint violation
5133 ** causes the operation in process to fail and for the current transaction
5134 ** to be rolled back. ABORT processing means the operation in process
5135 ** fails and any prior changes from that one operation are backed out,
5136 ** but the transaction is not rolled back. FAIL processing means that
5137 ** the operation in progress stops and returns an error code. But prior
5138 ** changes due to the same operation are not backed out and no rollback
5139 ** occurs. IGNORE means that the particular row that caused the constraint
5140 ** error is not inserted or updated. Processing continues and no error
5141 ** is returned. REPLACE means that preexisting database rows that caused
5142 ** a UNIQUE constraint violation are removed so that the new insert or
5143 ** update can proceed. Processing continues and no error is reported.
5145 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
5146 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
5147 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
5148 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
5149 ** referenced table row is propagated into the row that holds the
5150 ** foreign key.
5152 ** The following symbolic values are used to record which type
5153 ** of action to take.
5155 #define OE_None 0 /* There is no constraint to check */
5156 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
5157 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
5158 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
5159 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
5160 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
5162 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
5163 #define OE_SetNull 7 /* Set the foreign key value to NULL */
5164 #define OE_SetDflt 8 /* Set the foreign key value to its default */
5165 #define OE_Cascade 9 /* Cascade the changes */
5167 #define OE_Default 99 /* Do whatever the default action is */
5171 ** An instance of the following structure is passed as the first
5172 ** argument to sqlite3VdbeKeyCompare and is used to control the
5173 ** comparison of the two index keys.
5175 ** If the KeyInfo.incrKey value is true and the comparison would
5176 ** otherwise be equal, then return a result as if the second key
5177 ** were larger.
5179 struct KeyInfo {
5180 u8 enc; /* Text encoding - one of the TEXT_Utf* values */
5181 u8 incrKey; /* Increase 2nd key by epsilon before comparison */
5182 int nField; /* Number of entries in aColl[] */
5183 u8 *aSortOrder; /* If defined an aSortOrder[i] is true, sort DESC */
5184 CollSeq *aColl[1]; /* Collating sequence for each term of the key */
5188 ** Each SQL index is represented in memory by an
5189 ** instance of the following structure.
5191 ** The columns of the table that are to be indexed are described
5192 ** by the aiColumn[] field of this structure. For example, suppose
5193 ** we have the following table and index:
5195 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
5196 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
5198 ** In the Table structure describing Ex1, nCol==3 because there are
5199 ** three columns in the table. In the Index structure describing
5200 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
5201 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
5202 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
5203 ** The second column to be indexed (c1) has an index of 0 in
5204 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
5206 ** The Index.onError field determines whether or not the indexed columns
5207 ** must be unique and what to do if they are not. When Index.onError=OE_None,
5208 ** it means this is not a unique index. Otherwise it is a unique index
5209 ** and the value of Index.onError indicate the which conflict resolution
5210 ** algorithm to employ whenever an attempt is made to insert a non-unique
5211 ** element.
5213 struct Index {
5214 char *zName; /* Name of this index */
5215 int nColumn; /* Number of columns in the table used by this index */
5216 int *aiColumn; /* Which columns are used by this index. 1st is 0 */
5217 unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
5218 Table *pTable; /* The SQL table being indexed */
5219 int tnum; /* Page containing root of this index in database file */
5220 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
5221 u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
5222 char *zColAff; /* String defining the affinity of each column */
5223 Index *pNext; /* The next index associated with the same table */
5224 Schema *pSchema; /* Schema containing this index */
5225 u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */
5226 char **azColl; /* Array of collation sequence names for index */
5230 ** Each token coming out of the lexer is an instance of
5231 ** this structure. Tokens are also used as part of an expression.
5233 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
5234 ** may contain random values. Do not make any assuptions about Token.dyn
5235 ** and Token.n when Token.z==0.
5237 struct Token {
5238 const unsigned char *z; /* Text of the token. Not NULL-terminated! */
5239 unsigned dyn : 1; /* True for malloced memory, false for static */
5240 unsigned n : 31; /* Number of characters in this token */
5244 ** An instance of this structure contains information needed to generate
5245 ** code for a SELECT that contains aggregate functions.
5247 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
5248 ** pointer to this structure. The Expr.iColumn field is the index in
5249 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
5250 ** code for that node.
5252 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
5253 ** original Select structure that describes the SELECT statement. These
5254 ** fields do not need to be freed when deallocating the AggInfo structure.
5256 struct AggInfo {
5257 u8 directMode; /* Direct rendering mode means take data directly
5258 ** from source tables rather than from accumulators */
5259 u8 useSortingIdx; /* In direct mode, reference the sorting index rather
5260 ** than the source table */
5261 int sortingIdx; /* Cursor number of the sorting index */
5262 ExprList *pGroupBy; /* The group by clause */
5263 int nSortingColumn; /* Number of columns in the sorting index */
5264 struct AggInfo_col { /* For each column used in source tables */
5265 Table *pTab; /* Source table */
5266 int iTable; /* Cursor number of the source table */
5267 int iColumn; /* Column number within the source table */
5268 int iSorterColumn; /* Column number in the sorting index */
5269 int iMem; /* Memory location that acts as accumulator */
5270 Expr *pExpr; /* The original expression */
5271 } *aCol;
5272 int nColumn; /* Number of used entries in aCol[] */
5273 int nColumnAlloc; /* Number of slots allocated for aCol[] */
5274 int nAccumulator; /* Number of columns that show through to the output.
5275 ** Additional columns are used only as parameters to
5276 ** aggregate functions */
5277 struct AggInfo_func { /* For each aggregate function */
5278 Expr *pExpr; /* Expression encoding the function */
5279 FuncDef *pFunc; /* The aggregate function implementation */
5280 int iMem; /* Memory location that acts as accumulator */
5281 int iDistinct; /* Ephermeral table used to enforce DISTINCT */
5282 } *aFunc;
5283 int nFunc; /* Number of entries in aFunc[] */
5284 int nFuncAlloc; /* Number of slots allocated for aFunc[] */
5288 ** Each node of an expression in the parse tree is an instance
5289 ** of this structure.
5291 ** Expr.op is the opcode. The integer parser token codes are reused
5292 ** as opcodes here. For example, the parser defines TK_GE to be an integer
5293 ** code representing the ">=" operator. This same integer code is reused
5294 ** to represent the greater-than-or-equal-to operator in the expression
5295 ** tree.
5297 ** Expr.pRight and Expr.pLeft are subexpressions. Expr.pList is a list
5298 ** of argument if the expression is a function.
5300 ** Expr.token is the operator token for this node. For some expressions
5301 ** that have subexpressions, Expr.token can be the complete text that gave
5302 ** rise to the Expr. In the latter case, the token is marked as being
5303 ** a compound token.
5305 ** An expression of the form ID or ID.ID refers to a column in a table.
5306 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
5307 ** the integer cursor number of a VDBE cursor pointing to that table and
5308 ** Expr.iColumn is the column number for the specific column. If the
5309 ** expression is used as a result in an aggregate SELECT, then the
5310 ** value is also stored in the Expr.iAgg column in the aggregate so that
5311 ** it can be accessed after all aggregates are computed.
5313 ** If the expression is a function, the Expr.iTable is an integer code
5314 ** representing which function. If the expression is an unbound variable
5315 ** marker (a question mark character '?' in the original SQL) then the
5316 ** Expr.iTable holds the index number for that variable.
5318 ** If the expression is a subquery then Expr.iColumn holds an integer
5319 ** register number containing the result of the subquery. If the
5320 ** subquery gives a constant result, then iTable is -1. If the subquery
5321 ** gives a different answer at different times during statement processing
5322 ** then iTable is the address of a subroutine that computes the subquery.
5324 ** The Expr.pSelect field points to a SELECT statement. The SELECT might
5325 ** be the right operand of an IN operator. Or, if a scalar SELECT appears
5326 ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
5327 ** operand.
5329 ** If the Expr is of type OP_Column, and the table it is selecting from
5330 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
5331 ** corresponding table definition.
5333 struct Expr {
5334 u8 op; /* Operation performed by this node */
5335 char affinity; /* The affinity of the column or 0 if not a column */
5336 u16 flags; /* Various flags. See below */
5337 CollSeq *pColl; /* The collation type of the column or 0 */
5338 Expr *pLeft, *pRight; /* Left and right subnodes */
5339 ExprList *pList; /* A list of expressions used as function arguments
5340 ** or in "<expr> IN (<expr-list)" */
5341 Token token; /* An operand token */
5342 Token span; /* Complete text of the expression */
5343 int iTable, iColumn; /* When op==TK_COLUMN, then this expr node means the
5344 ** iColumn-th field of the iTable-th table. */
5345 AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
5346 int iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
5347 int iRightJoinTable; /* If EP_FromJoin, the right table of the join */
5348 Select *pSelect; /* When the expression is a sub-select. Also the
5349 ** right side of "<expr> IN (<select>)" */
5350 Table *pTab; /* Table for OP_Column expressions. */
5351 Schema *pSchema;
5352 #if SQLITE_MAX_EXPR_DEPTH>0
5353 int nHeight; /* Height of the tree headed by this node */
5354 #endif
5358 ** The following are the meanings of bits in the Expr.flags field.
5360 #define EP_FromJoin 0x01 /* Originated in ON or USING clause of a join */
5361 #define EP_Agg 0x02 /* Contains one or more aggregate functions */
5362 #define EP_Resolved 0x04 /* IDs have been resolved to COLUMNs */
5363 #define EP_Error 0x08 /* Expression contains one or more errors */
5364 #define EP_Distinct 0x10 /* Aggregate function with DISTINCT keyword */
5365 #define EP_VarSelect 0x20 /* pSelect is correlated, not constant */
5366 #define EP_Dequoted 0x40 /* True if the string has been dequoted */
5367 #define EP_InfixFunc 0x80 /* True for an infix function: LIKE, GLOB, etc */
5368 #define EP_ExpCollate 0x100 /* Collating sequence specified explicitly */
5371 ** These macros can be used to test, set, or clear bits in the
5372 ** Expr.flags field.
5374 #define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
5375 #define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
5376 #define ExprSetProperty(E,P) (E)->flags|=(P)
5377 #define ExprClearProperty(E,P) (E)->flags&=~(P)
5380 ** A list of expressions. Each expression may optionally have a
5381 ** name. An expr/name combination can be used in several ways, such
5382 ** as the list of "expr AS ID" fields following a "SELECT" or in the
5383 ** list of "ID = expr" items in an UPDATE. A list of expressions can
5384 ** also be used as the argument to a function, in which case the a.zName
5385 ** field is not used.
5387 struct ExprList {
5388 int nExpr; /* Number of expressions on the list */
5389 int nAlloc; /* Number of entries allocated below */
5390 int iECursor; /* VDBE Cursor associated with this ExprList */
5391 struct ExprList_item {
5392 Expr *pExpr; /* The list of expressions */
5393 char *zName; /* Token associated with this expression */
5394 u8 sortOrder; /* 1 for DESC or 0 for ASC */
5395 u8 isAgg; /* True if this is an aggregate like count(*) */
5396 u8 done; /* A flag to indicate when processing is finished */
5397 } *a; /* One entry for each expression */
5401 ** An instance of this structure can hold a simple list of identifiers,
5402 ** such as the list "a,b,c" in the following statements:
5404 ** INSERT INTO t(a,b,c) VALUES ...;
5405 ** CREATE INDEX idx ON t(a,b,c);
5406 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
5408 ** The IdList.a.idx field is used when the IdList represents the list of
5409 ** column names after a table name in an INSERT statement. In the statement
5411 ** INSERT INTO t(a,b,c) ...
5413 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
5415 struct IdList {
5416 struct IdList_item {
5417 char *zName; /* Name of the identifier */
5418 int idx; /* Index in some Table.aCol[] of a column named zName */
5419 } *a;
5420 int nId; /* Number of identifiers on the list */
5421 int nAlloc; /* Number of entries allocated for a[] below */
5425 ** The bitmask datatype defined below is used for various optimizations.
5427 ** Changing this from a 64-bit to a 32-bit type limits the number of
5428 ** tables in a join to 32 instead of 64. But it also reduces the size
5429 ** of the library by 738 bytes on ix86.
5431 typedef u64 Bitmask;
5434 ** The following structure describes the FROM clause of a SELECT statement.
5435 ** Each table or subquery in the FROM clause is a separate element of
5436 ** the SrcList.a[] array.
5438 ** With the addition of multiple database support, the following structure
5439 ** can also be used to describe a particular table such as the table that
5440 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
5441 ** such a table must be a simple name: ID. But in SQLite, the table can
5442 ** now be identified by a database name, a dot, then the table name: ID.ID.
5444 ** The jointype starts out showing the join type between the current table
5445 ** and the next table on the list. The parser builds the list this way.
5446 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
5447 ** jointype expresses the join between the table and the previous table.
5449 struct SrcList {
5450 i16 nSrc; /* Number of tables or subqueries in the FROM clause */
5451 i16 nAlloc; /* Number of entries allocated in a[] below */
5452 struct SrcList_item {
5453 char *zDatabase; /* Name of database holding this table */
5454 char *zName; /* Name of the table */
5455 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
5456 Table *pTab; /* An SQL table corresponding to zName */
5457 Select *pSelect; /* A SELECT statement used in place of a table name */
5458 u8 isPopulated; /* Temporary table associated with SELECT is populated */
5459 u8 jointype; /* Type of join between this able and the previous */
5460 int iCursor; /* The VDBE cursor number used to access this table */
5461 Expr *pOn; /* The ON clause of a join */
5462 IdList *pUsing; /* The USING clause of a join */
5463 Bitmask colUsed; /* Bit N (1<<N) set if column N or pTab is used */
5464 } a[1]; /* One entry for each identifier on the list */
5468 ** Permitted values of the SrcList.a.jointype field
5470 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
5471 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
5472 #define JT_NATURAL 0x0004 /* True for a "natural" join */
5473 #define JT_LEFT 0x0008 /* Left outer join */
5474 #define JT_RIGHT 0x0010 /* Right outer join */
5475 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
5476 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
5479 ** For each nested loop in a WHERE clause implementation, the WhereInfo
5480 ** structure contains a single instance of this structure. This structure
5481 ** is intended to be private the the where.c module and should not be
5482 ** access or modified by other modules.
5484 ** The pIdxInfo and pBestIdx fields are used to help pick the best
5485 ** index on a virtual table. The pIdxInfo pointer contains indexing
5486 ** information for the i-th table in the FROM clause before reordering.
5487 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
5488 ** The pBestIdx pointer is a copy of pIdxInfo for the i-th table after
5489 ** FROM clause ordering. This is a little confusing so I will repeat
5490 ** it in different words. WhereInfo.a[i].pIdxInfo is index information
5491 ** for WhereInfo.pTabList.a[i]. WhereInfo.a[i].pBestInfo is the
5492 ** index information for the i-th loop of the join. pBestInfo is always
5493 ** either NULL or a copy of some pIdxInfo. So for cleanup it is
5494 ** sufficient to free all of the pIdxInfo pointers.
5497 struct WhereLevel {
5498 int iFrom; /* Which entry in the FROM clause */
5499 int flags; /* Flags associated with this level */
5500 int iMem; /* First memory cell used by this level */
5501 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
5502 Index *pIdx; /* Index used. NULL if no index */
5503 int iTabCur; /* The VDBE cursor used to access the table */
5504 int iIdxCur; /* The VDBE cursor used to acesss pIdx */
5505 int brk; /* Jump here to break out of the loop */
5506 int nxt; /* Jump here to start the next IN combination */
5507 int cont; /* Jump here to continue with the next loop cycle */
5508 int top; /* First instruction of interior of the loop */
5509 int op, p1, p2; /* Opcode used to terminate the loop */
5510 int nEq; /* Number of == or IN constraints on this loop */
5511 int nIn; /* Number of IN operators constraining this loop */
5512 struct InLoop {
5513 int iCur; /* The VDBE cursor used by this IN operator */
5514 int topAddr; /* Top of the IN loop */
5515 } *aInLoop; /* Information about each nested IN operator */
5516 sqlite3_index_info *pBestIdx; /* Index information for this level */
5518 /* The following field is really not part of the current level. But
5519 ** we need a place to cache index information for each table in the
5520 ** FROM clause and the WhereLevel structure is a convenient place.
5522 sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
5526 ** The WHERE clause processing routine has two halves. The
5527 ** first part does the start of the WHERE loop and the second
5528 ** half does the tail of the WHERE loop. An instance of
5529 ** this structure is returned by the first half and passed
5530 ** into the second half to give some continuity.
5532 struct WhereInfo {
5533 Parse *pParse;
5534 SrcList *pTabList; /* List of tables in the join */
5535 int iTop; /* The very beginning of the WHERE loop */
5536 int iContinue; /* Jump here to continue with next record */
5537 int iBreak; /* Jump here to break out of the loop */
5538 int nLevel; /* Number of nested loop */
5539 sqlite3_index_info **apInfo; /* Array of pointers to index info structures */
5540 WhereLevel a[1]; /* Information about each nest loop in the WHERE */
5544 ** A NameContext defines a context in which to resolve table and column
5545 ** names. The context consists of a list of tables (the pSrcList) field and
5546 ** a list of named expression (pEList). The named expression list may
5547 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
5548 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
5549 ** pEList corresponds to the result set of a SELECT and is NULL for
5550 ** other statements.
5552 ** NameContexts can be nested. When resolving names, the inner-most
5553 ** context is searched first. If no match is found, the next outer
5554 ** context is checked. If there is still no match, the next context
5555 ** is checked. This process continues until either a match is found
5556 ** or all contexts are check. When a match is found, the nRef member of
5557 ** the context containing the match is incremented.
5559 ** Each subquery gets a new NameContext. The pNext field points to the
5560 ** NameContext in the parent query. Thus the process of scanning the
5561 ** NameContext list corresponds to searching through successively outer
5562 ** subqueries looking for a match.
5564 struct NameContext {
5565 Parse *pParse; /* The parser */
5566 SrcList *pSrcList; /* One or more tables used to resolve names */
5567 ExprList *pEList; /* Optional list of named expressions */
5568 int nRef; /* Number of names resolved by this context */
5569 int nErr; /* Number of errors encountered while resolving names */
5570 u8 allowAgg; /* Aggregate functions allowed here */
5571 u8 hasAgg; /* True if aggregates are seen */
5572 u8 isCheck; /* True if resolving names in a CHECK constraint */
5573 int nDepth; /* Depth of subquery recursion. 1 for no recursion */
5574 AggInfo *pAggInfo; /* Information about aggregates at this level */
5575 NameContext *pNext; /* Next outer name context. NULL for outermost */
5579 ** An instance of the following structure contains all information
5580 ** needed to generate code for a single SELECT statement.
5582 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
5583 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
5584 ** limit and nOffset to the value of the offset (or 0 if there is not
5585 ** offset). But later on, nLimit and nOffset become the memory locations
5586 ** in the VDBE that record the limit and offset counters.
5588 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
5589 ** These addresses must be stored so that we can go back and fill in
5590 ** the P3_KEYINFO and P2 parameters later. Neither the KeyInfo nor
5591 ** the number of columns in P2 can be computed at the same time
5592 ** as the OP_OpenEphm instruction is coded because not
5593 ** enough information about the compound query is known at that point.
5594 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
5595 ** for the result set. The KeyInfo for addrOpenTran[2] contains collating
5596 ** sequences for the ORDER BY clause.
5598 struct Select {
5599 ExprList *pEList; /* The fields of the result */
5600 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
5601 u8 isDistinct; /* True if the DISTINCT keyword is present */
5602 u8 isResolved; /* True once sqlite3SelectResolve() has run. */
5603 u8 isAgg; /* True if this is an aggregate query */
5604 u8 usesEphm; /* True if uses an OpenEphemeral opcode */
5605 u8 disallowOrderBy; /* Do not allow an ORDER BY to be attached if TRUE */
5606 char affinity; /* MakeRecord with this affinity for SRT_Set */
5607 SrcList *pSrc; /* The FROM clause */
5608 Expr *pWhere; /* The WHERE clause */
5609 ExprList *pGroupBy; /* The GROUP BY clause */
5610 Expr *pHaving; /* The HAVING clause */
5611 ExprList *pOrderBy; /* The ORDER BY clause */
5612 Select *pPrior; /* Prior select in a compound select statement */
5613 Select *pRightmost; /* Right-most select in a compound select statement */
5614 Expr *pLimit; /* LIMIT expression. NULL means not used. */
5615 Expr *pOffset; /* OFFSET expression. NULL means not used. */
5616 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
5617 int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
5621 ** The results of a select can be distributed in several ways.
5623 #define SRT_Union 1 /* Store result as keys in an index */
5624 #define SRT_Except 2 /* Remove result from a UNION index */
5625 #define SRT_Discard 3 /* Do not save the results anywhere */
5627 /* The ORDER BY clause is ignored for all of the above */
5628 #define IgnorableOrderby(X) (X<=SRT_Discard)
5630 #define SRT_Callback 4 /* Invoke a callback with each row of result */
5631 #define SRT_Mem 5 /* Store result in a memory cell */
5632 #define SRT_Set 6 /* Store non-null results as keys in an index */
5633 #define SRT_Table 7 /* Store result as data with an automatic rowid */
5634 #define SRT_EphemTab 8 /* Create transient tab and store like SRT_Table */
5635 #define SRT_Subroutine 9 /* Call a subroutine to handle results */
5636 #define SRT_Exists 10 /* Store 1 if the result is not empty */
5639 ** An SQL parser context. A copy of this structure is passed through
5640 ** the parser and down into all the parser action routine in order to
5641 ** carry around information that is global to the entire parse.
5643 ** The structure is divided into two parts. When the parser and code
5644 ** generate call themselves recursively, the first part of the structure
5645 ** is constant but the second part is reset at the beginning and end of
5646 ** each recursion.
5648 ** The nTableLock and aTableLock variables are only used if the shared-cache
5649 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
5650 ** used to store the set of table-locks required by the statement being
5651 ** compiled. Function sqlite3TableLock() is used to add entries to the
5652 ** list.
5654 struct Parse {
5655 sqlite3 *db; /* The main database structure */
5656 int rc; /* Return code from execution */
5657 char *zErrMsg; /* An error message */
5658 Vdbe *pVdbe; /* An engine for executing database bytecode */
5659 u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
5660 u8 nameClash; /* A permanent table name clashes with temp table name */
5661 u8 checkSchema; /* Causes schema cookie check after an error */
5662 u8 nested; /* Number of nested calls to the parser/code generator */
5663 u8 parseError; /* True after a parsing error. Ticket #1794 */
5664 int nErr; /* Number of errors seen */
5665 int nTab; /* Number of previously allocated VDBE cursors */
5666 int nMem; /* Number of memory cells used so far */
5667 int nSet; /* Number of sets used so far */
5668 int ckOffset; /* Stack offset to data used by CHECK constraints */
5669 u32 writeMask; /* Start a write transaction on these databases */
5670 u32 cookieMask; /* Bitmask of schema verified databases */
5671 int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
5672 int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
5673 #ifndef SQLITE_OMIT_SHARED_CACHE
5674 int nTableLock; /* Number of locks in aTableLock */
5675 TableLock *aTableLock; /* Required table locks for shared-cache mode */
5676 #endif
5678 /* Above is constant between recursions. Below is reset before and after
5679 ** each recursion */
5681 int nVar; /* Number of '?' variables seen in the SQL so far */
5682 int nVarExpr; /* Number of used slots in apVarExpr[] */
5683 int nVarExprAlloc; /* Number of allocated slots in apVarExpr[] */
5684 Expr **apVarExpr; /* Pointers to :aaa and $aaaa wildcard expressions */
5685 u8 explain; /* True if the EXPLAIN flag is found on the query */
5686 Token sErrToken; /* The token at which the error occurred */
5687 Token sNameToken; /* Token with unqualified schema object name */
5688 Token sLastToken; /* The last token parsed */
5689 const char *zSql; /* All SQL text */
5690 const char *zTail; /* All SQL text past the last semicolon parsed */
5691 Table *pNewTable; /* A table being constructed by CREATE TABLE */
5692 Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
5693 TriggerStack *trigStack; /* Trigger actions being coded */
5694 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
5695 #ifndef SQLITE_OMIT_VIRTUALTABLE
5696 Token sArg; /* Complete text of a module argument */
5697 u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
5698 Table *pVirtualLock; /* Require virtual table lock on this table */
5699 #endif
5700 #if SQLITE_MAX_EXPR_DEPTH>0
5701 int nHeight; /* Expression tree height of current sub-select */
5702 #endif
5705 #ifdef SQLITE_OMIT_VIRTUALTABLE
5706 #define IN_DECLARE_VTAB 0
5707 #else
5708 #define IN_DECLARE_VTAB (pParse->declareVtab)
5709 #endif
5712 ** An instance of the following structure can be declared on a stack and used
5713 ** to save the Parse.zAuthContext value so that it can be restored later.
5715 struct AuthContext {
5716 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
5717 Parse *pParse; /* The Parse structure */
5721 ** Bitfield flags for P2 value in OP_Insert and OP_Delete
5723 #define OPFLAG_NCHANGE 1 /* Set to update db->nChange */
5724 #define OPFLAG_LASTROWID 2 /* Set to update db->lastRowid */
5725 #define OPFLAG_ISUPDATE 4 /* This OP_Insert is an sql UPDATE */
5726 #define OPFLAG_APPEND 8 /* This is likely to be an append */
5729 * Each trigger present in the database schema is stored as an instance of
5730 * struct Trigger.
5732 * Pointers to instances of struct Trigger are stored in two ways.
5733 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
5734 * database). This allows Trigger structures to be retrieved by name.
5735 * 2. All triggers associated with a single table form a linked list, using the
5736 * pNext member of struct Trigger. A pointer to the first element of the
5737 * linked list is stored as the "pTrigger" member of the associated
5738 * struct Table.
5740 * The "step_list" member points to the first element of a linked list
5741 * containing the SQL statements specified as the trigger program.
5743 struct Trigger {
5744 char *name; /* The name of the trigger */
5745 char *table; /* The table or view to which the trigger applies */
5746 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
5747 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
5748 Expr *pWhen; /* The WHEN clause of the expresion (may be NULL) */
5749 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
5750 the <column-list> is stored here */
5751 Token nameToken; /* Token containing zName. Use during parsing only */
5752 Schema *pSchema; /* Schema containing the trigger */
5753 Schema *pTabSchema; /* Schema containing the table */
5754 TriggerStep *step_list; /* Link list of trigger program steps */
5755 Trigger *pNext; /* Next trigger associated with the table */
5759 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
5760 ** determine which.
5762 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
5763 ** In that cases, the constants below can be ORed together.
5765 #define TRIGGER_BEFORE 1
5766 #define TRIGGER_AFTER 2
5769 * An instance of struct TriggerStep is used to store a single SQL statement
5770 * that is a part of a trigger-program.
5772 * Instances of struct TriggerStep are stored in a singly linked list (linked
5773 * using the "pNext" member) referenced by the "step_list" member of the
5774 * associated struct Trigger instance. The first element of the linked list is
5775 * the first step of the trigger-program.
5777 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
5778 * "SELECT" statement. The meanings of the other members is determined by the
5779 * value of "op" as follows:
5781 * (op == TK_INSERT)
5782 * orconf -> stores the ON CONFLICT algorithm
5783 * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
5784 * this stores a pointer to the SELECT statement. Otherwise NULL.
5785 * target -> A token holding the name of the table to insert into.
5786 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
5787 * this stores values to be inserted. Otherwise NULL.
5788 * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
5789 * statement, then this stores the column-names to be
5790 * inserted into.
5792 * (op == TK_DELETE)
5793 * target -> A token holding the name of the table to delete from.
5794 * pWhere -> The WHERE clause of the DELETE statement if one is specified.
5795 * Otherwise NULL.
5797 * (op == TK_UPDATE)
5798 * target -> A token holding the name of the table to update rows of.
5799 * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
5800 * Otherwise NULL.
5801 * pExprList -> A list of the columns to update and the expressions to update
5802 * them to. See sqlite3Update() documentation of "pChanges"
5803 * argument.
5806 struct TriggerStep {
5807 int op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
5808 int orconf; /* OE_Rollback etc. */
5809 Trigger *pTrig; /* The trigger that this step is a part of */
5811 Select *pSelect; /* Valid for SELECT and sometimes
5812 INSERT steps (when pExprList == 0) */
5813 Token target; /* Valid for DELETE, UPDATE, INSERT steps */
5814 Expr *pWhere; /* Valid for DELETE, UPDATE steps */
5815 ExprList *pExprList; /* Valid for UPDATE statements and sometimes
5816 INSERT steps (when pSelect == 0) */
5817 IdList *pIdList; /* Valid for INSERT statements only */
5818 TriggerStep *pNext; /* Next in the link-list */
5819 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
5823 * An instance of struct TriggerStack stores information required during code
5824 * generation of a single trigger program. While the trigger program is being
5825 * coded, its associated TriggerStack instance is pointed to by the
5826 * "pTriggerStack" member of the Parse structure.
5828 * The pTab member points to the table that triggers are being coded on. The
5829 * newIdx member contains the index of the vdbe cursor that points at the temp
5830 * table that stores the new.* references. If new.* references are not valid
5831 * for the trigger being coded (for example an ON DELETE trigger), then newIdx
5832 * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
5834 * The ON CONFLICT policy to be used for the trigger program steps is stored
5835 * as the orconf member. If this is OE_Default, then the ON CONFLICT clause
5836 * specified for individual triggers steps is used.
5838 * struct TriggerStack has a "pNext" member, to allow linked lists to be
5839 * constructed. When coding nested triggers (triggers fired by other triggers)
5840 * each nested trigger stores its parent trigger's TriggerStack as the "pNext"
5841 * pointer. Once the nested trigger has been coded, the pNext value is restored
5842 * to the pTriggerStack member of the Parse stucture and coding of the parent
5843 * trigger continues.
5845 * Before a nested trigger is coded, the linked list pointed to by the
5846 * pTriggerStack is scanned to ensure that the trigger is not about to be coded
5847 * recursively. If this condition is detected, the nested trigger is not coded.
5849 struct TriggerStack {
5850 Table *pTab; /* Table that triggers are currently being coded on */
5851 int newIdx; /* Index of vdbe cursor to "new" temp table */
5852 int oldIdx; /* Index of vdbe cursor to "old" temp table */
5853 int orconf; /* Current orconf policy */
5854 int ignoreJump; /* where to jump to for a RAISE(IGNORE) */
5855 Trigger *pTrigger; /* The trigger currently being coded */
5856 TriggerStack *pNext; /* Next trigger down on the trigger stack */
5860 ** The following structure contains information used by the sqliteFix...
5861 ** routines as they walk the parse tree to make database references
5862 ** explicit.
5864 typedef struct DbFixer DbFixer;
5865 struct DbFixer {
5866 Parse *pParse; /* The parsing context. Error messages written here */
5867 const char *zDb; /* Make sure all objects are contained in this database */
5868 const char *zType; /* Type of the container - used for error messages */
5869 const Token *pName; /* Name of the container - used for error messages */
5873 ** A pointer to this structure is used to communicate information
5874 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
5876 typedef struct {
5877 sqlite3 *db; /* The database being initialized */
5878 int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
5879 char **pzErrMsg; /* Error message stored here */
5880 int rc; /* Result code stored here */
5881 } InitData;
5884 * This global flag is set for performance testing of triggers. When it is set
5885 * SQLite will perform the overhead of building new and old trigger references
5886 * even when no triggers exist
5888 extern int sqlite3_always_code_trigger_setup;
5891 ** A lookup table used by the SQLITE_READ_UTF8 macro. The definition
5892 ** is in utf.c.
5894 extern const unsigned char sqlite3UtfTrans1[];
5897 ** Macros for reading UTF8 characters.
5899 ** SQLITE_READ_UTF8(x,c) reads a single UTF8 value out of x and writes
5900 ** that value into c. The type of x must be unsigned char*. The type
5901 ** of c must be unsigned int.
5903 ** SQLITE_SKIP_UTF8(x) advances x forward by one character. The type of
5904 ** x must be unsigned char*.
5906 ** Notes On Invalid UTF-8:
5908 ** * These macros never allow a 7-bit character (0x00 through 0x7f) to
5909 ** be encoded as a multi-byte character. Any multi-byte character that
5910 ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
5912 ** * These macros never allow a UTF16 surrogate value to be encoded.
5913 ** If a multi-byte character attempts to encode a value between
5914 ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
5916 ** * Bytes in the range of 0x80 through 0xbf which occur as the first
5917 ** byte of a character are interpreted as single-byte characters
5918 ** and rendered as themselves even though they are technically
5919 ** invalid characters.
5921 ** * These routines accept an infinite number of different UTF8 encodings
5922 ** for unicode values 0x80 and greater. They do not change over-length
5923 ** encodings to 0xfffd as some systems recommend.
5926 #define SQLITE_READ_UTF8(zIn, c) { \
5927 c = *(zIn++); \
5928 if( c>=0xc0 ){ \
5929 c = sqlite3UtfTrans1[c-0xc0]; \
5930 while( (*zIn & 0xc0)==0x80 ){ \
5931 c = (c<<6) + (0x3f & *(zIn++)); \
5933 if( c<0x80 \
5934 || (c&0xFFFFF800)==0xD800 \
5935 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
5938 #define SQLITE_SKIP_UTF8(zIn) { \
5939 if( (*(zIn++))>=0xc0 ){ \
5940 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
5948 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
5949 ** builds) or a function call (for debugging). If it is a function call,
5950 ** it allows the operator to set a breakpoint at the spot where database
5951 ** corruption is first detected.
5953 #ifdef SQLITE_DEBUG
5954 static int sqlite3Corrupt(void);
5955 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
5956 #else
5957 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
5958 #endif
5961 ** Internal function prototypes
5963 static int sqlite3StrICmp(const char *, const char *);
5964 static int sqlite3StrNICmp(const char *, const char *, int);
5965 static int sqlite3IsNumber(const char*, int*, u8);
5967 static void *sqlite3Malloc(int,int);
5968 static void *sqlite3MallocRaw(int,int);
5969 static void *sqlite3Realloc(void*,int);
5970 static char *sqlite3StrDup(const char*);
5971 static char *sqlite3StrNDup(const char*, int);
5972 # define sqlite3CheckMemory(a,b)
5973 static void *sqlite3ReallocOrFree(void*,int);
5974 static void sqlite3FreeX(void*);
5975 static void *sqlite3MallocX(int);
5976 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
5977 static int sqlite3AllocSize(void *);
5978 #endif
5980 static char *sqlite3MPrintf(const char*, ...);
5981 static char *sqlite3VMPrintf(const char*, va_list);
5982 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
5983 static void sqlite3DebugPrintf(const char*, ...);
5984 static void *sqlite3TextToPtr(const char*);
5985 #endif
5986 static void sqlite3SetString(char **, ...);
5987 static void sqlite3ErrorMsg(Parse*, const char*, ...);
5988 static void sqlite3ErrorClear(Parse*);
5989 static void sqlite3Dequote(char*);
5990 static void sqlite3DequoteExpr(Expr*);
5991 static int sqlite3KeywordCode(const unsigned char*, int);
5992 static int sqlite3RunParser(Parse*, const char*, char **);
5993 static void sqlite3FinishCoding(Parse*);
5994 static Expr *sqlite3Expr(int, Expr*, Expr*, const Token*);
5995 static Expr *sqlite3ExprOrFree(int, Expr*, Expr*, const Token*);
5996 static Expr *sqlite3RegisterExpr(Parse*,Token*);
5997 static Expr *sqlite3ExprAnd(Expr*, Expr*);
5998 static void sqlite3ExprSpan(Expr*,Token*,Token*);
5999 static Expr *sqlite3ExprFunction(ExprList*, Token*);
6000 static void sqlite3ExprAssignVarNumber(Parse*, Expr*);
6001 static void sqlite3ExprDelete(Expr*);
6002 static ExprList *sqlite3ExprListAppend(ExprList*,Expr*,Token*);
6003 static void sqlite3ExprListDelete(ExprList*);
6004 static int sqlite3Init(sqlite3*, char**);
6005 static int sqlite3InitCallback(void*, int, char**, char**);
6006 static void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
6007 static void sqlite3ResetInternalSchema(sqlite3*, int);
6008 static void sqlite3BeginParse(Parse*,int);
6009 static void sqlite3CommitInternalChanges(sqlite3*);
6010 static Table *sqlite3ResultSetOfSelect(Parse*,char*,Select*);
6011 static void sqlite3OpenMasterTable(Parse *, int);
6012 static void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
6013 static void sqlite3AddColumn(Parse*,Token*);
6014 static void sqlite3AddNotNull(Parse*, int);
6015 static void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
6016 static void sqlite3AddCheckConstraint(Parse*, Expr*);
6017 static void sqlite3AddColumnType(Parse*,Token*);
6018 static void sqlite3AddDefaultValue(Parse*,Expr*);
6019 static void sqlite3AddCollateType(Parse*, const char*, int);
6020 static void sqlite3EndTable(Parse*,Token*,Token*,Select*);
6022 static void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
6024 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
6025 static int sqlite3ViewGetColumnNames(Parse*,Table*);
6026 #else
6027 # define sqlite3ViewGetColumnNames(A,B) 0
6028 #endif
6030 static void sqlite3DropTable(Parse*, SrcList*, int, int);
6031 static void sqlite3DeleteTable(Table*);
6032 static void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
6033 static void *sqlite3ArrayAllocate(void*,int,int,int*,int*,int*);
6034 static IdList *sqlite3IdListAppend(IdList*, Token*);
6035 static int sqlite3IdListIndex(IdList*,const char*);
6036 static SrcList *sqlite3SrcListAppend(SrcList*, Token*, Token*);
6037 static SrcList *sqlite3SrcListAppendFromTerm(SrcList*, Token*, Token*, Token*,
6038 Select*, Expr*, IdList*);
6039 static void sqlite3SrcListShiftJoinType(SrcList*);
6040 static void sqlite3SrcListAssignCursors(Parse*, SrcList*);
6041 static void sqlite3IdListDelete(IdList*);
6042 static void sqlite3SrcListDelete(SrcList*);
6043 static void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
6044 Token*, int, int);
6045 static void sqlite3DropIndex(Parse*, SrcList*, int);
6046 static int sqlite3Select(Parse*, Select*, int, int, Select*, int, int*, char *aff);
6047 static Select *sqlite3SelectNew(ExprList*,SrcList*,Expr*,ExprList*,Expr*,ExprList*,
6048 int,Expr*,Expr*);
6049 static void sqlite3SelectDelete(Select*);
6050 static Table *sqlite3SrcListLookup(Parse*, SrcList*);
6051 static int sqlite3IsReadOnly(Parse*, Table*, int);
6052 static void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
6053 static void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
6054 static void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
6055 static WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**);
6056 static void sqlite3WhereEnd(WhereInfo*);
6057 static void sqlite3ExprCodeGetColumn(Vdbe*, Table*, int, int);
6058 static void sqlite3ExprCode(Parse*, Expr*);
6059 static void sqlite3ExprCodeAndCache(Parse*, Expr*);
6060 static int sqlite3ExprCodeExprList(Parse*, ExprList*);
6061 static void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
6062 static void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
6063 static Table *sqlite3FindTable(sqlite3*,const char*, const char*);
6064 static Table *sqlite3LocateTable(Parse*,const char*, const char*);
6065 static Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
6066 static void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
6067 static void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
6068 static void sqlite3Vacuum(Parse*);
6069 static int sqlite3RunVacuum(char**, sqlite3*);
6070 static char *sqlite3NameFromToken(Token*);
6071 static int sqlite3ExprCompare(Expr*, Expr*);
6072 int sqliteFuncId(Token*);
6073 static int sqlite3ExprResolveNames(NameContext *, Expr *);
6074 static int sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
6075 static int sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
6076 static Vdbe *sqlite3GetVdbe(Parse*);
6077 static Expr *sqlite3CreateIdExpr(const char*);
6078 static void sqlite3Randomness(int, void*);
6079 static void sqlite3RollbackAll(sqlite3*);
6080 static void sqlite3CodeVerifySchema(Parse*, int);
6081 static void sqlite3BeginTransaction(Parse*, int);
6082 static void sqlite3CommitTransaction(Parse*);
6083 static void sqlite3RollbackTransaction(Parse*);
6084 static int sqlite3ExprIsConstant(Expr*);
6085 static int sqlite3ExprIsConstantNotJoin(Expr*);
6086 static int sqlite3ExprIsConstantOrFunction(Expr*);
6087 static int sqlite3ExprIsInteger(Expr*, int*);
6088 static int sqlite3IsRowid(const char*);
6089 static void sqlite3GenerateRowDelete(sqlite3*, Vdbe*, Table*, int, int);
6090 static void sqlite3GenerateRowIndexDelete(Vdbe*, Table*, int, char*);
6091 static void sqlite3GenerateIndexKey(Vdbe*, Index*, int);
6092 static void sqlite3GenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int);
6093 static void sqlite3CompleteInsertion(Parse*, Table*, int, char*, int, int, int, int);
6094 static void sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
6095 static void sqlite3BeginWriteOperation(Parse*, int, int);
6096 static Expr *sqlite3ExprDup(Expr*);
6097 static void sqlite3TokenCopy(Token*, Token*);
6098 static ExprList *sqlite3ExprListDup(ExprList*);
6099 static SrcList *sqlite3SrcListDup(SrcList*);
6100 static IdList *sqlite3IdListDup(IdList*);
6101 static Select *sqlite3SelectDup(Select*);
6102 static FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
6103 static void sqlite3RegisterBuiltinFunctions(sqlite3*);
6104 static void sqlite3RegisterDateTimeFunctions(sqlite3*);
6105 static int sqlite3SafetyOn(sqlite3*);
6106 static int sqlite3SafetyOff(sqlite3*);
6107 static int sqlite3SafetyCheck(sqlite3*);
6108 static void sqlite3ChangeCookie(sqlite3*, Vdbe*, int);
6110 #ifndef SQLITE_OMIT_TRIGGER
6111 static void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
6112 Expr*,int, int);
6113 static void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
6114 static void sqlite3DropTrigger(Parse*, SrcList*, int);
6115 static void sqlite3DropTriggerPtr(Parse*, Trigger*);
6116 static int sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
6117 static int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int,
6118 int, int);
6119 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
6120 static void sqlite3DeleteTriggerStep(TriggerStep*);
6121 static TriggerStep *sqlite3TriggerSelectStep(Select*);
6122 static TriggerStep *sqlite3TriggerInsertStep(Token*, IdList*, ExprList*,Select*,int);
6123 static TriggerStep *sqlite3TriggerUpdateStep(Token*, ExprList*, Expr*, int);
6124 static TriggerStep *sqlite3TriggerDeleteStep(Token*, Expr*);
6125 static void sqlite3DeleteTrigger(Trigger*);
6126 static void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
6127 #else
6128 # define sqlite3TriggersExist(A,B,C,D,E,F) 0
6129 # define sqlite3DeleteTrigger(A)
6130 # define sqlite3DropTriggerPtr(A,B)
6131 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
6132 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) 0
6133 #endif
6135 static int sqlite3JoinType(Parse*, Token*, Token*, Token*);
6136 static void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
6137 static void sqlite3DeferForeignKey(Parse*, int);
6138 #ifndef SQLITE_OMIT_AUTHORIZATION
6139 static void sqlite3AuthRead(Parse*,Expr*,SrcList*);
6140 static int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
6141 static void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
6142 static void sqlite3AuthContextPop(AuthContext*);
6143 #else
6144 # define sqlite3AuthRead(a,b,c)
6145 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
6146 # define sqlite3AuthContextPush(a,b,c)
6147 # define sqlite3AuthContextPop(a) ((void)(a))
6148 #endif
6149 static void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
6150 static void sqlite3Detach(Parse*, Expr*);
6151 static int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
6152 int omitJournal, int nCache, Btree **ppBtree);
6153 static int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
6154 static int sqlite3FixSrcList(DbFixer*, SrcList*);
6155 static int sqlite3FixSelect(DbFixer*, Select*);
6156 static int sqlite3FixExpr(DbFixer*, Expr*);
6157 static int sqlite3FixExprList(DbFixer*, ExprList*);
6158 static int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
6159 static int sqlite3AtoF(const char *z, double*);
6160 char *sqlite3_snprintf(int,char*,const char*,...);
6161 static int sqlite3GetInt32(const char *, int*);
6162 static int sqlite3FitsIn64Bits(const char *);
6163 static int sqlite3Utf16ByteLen(const void *pData, int nChar);
6164 static int sqlite3Utf8CharLen(const char *pData, int nByte);
6165 static u32 sqlite3ReadUtf8(const unsigned char *);
6166 static int sqlite3PutVarint(unsigned char *, u64);
6167 static int sqlite3GetVarint(const unsigned char *, u64 *);
6168 static int sqlite3GetVarint32(const unsigned char *, u32 *);
6169 static int sqlite3VarintLen(u64 v);
6170 static void sqlite3IndexAffinityStr(Vdbe *, Index *);
6171 static void sqlite3TableAffinityStr(Vdbe *, Table *);
6172 static char sqlite3CompareAffinity(Expr *pExpr, char aff2);
6173 static int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
6174 static char sqlite3ExprAffinity(Expr *pExpr);
6175 static int sqlite3Atoi64(const char*, i64*);
6176 static void sqlite3Error(sqlite3*, int, const char*,...);
6177 static void *sqlite3HexToBlob(const char *z);
6178 static int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
6179 static const char *sqlite3ErrStr(int);
6180 static int sqlite3ReadSchema(Parse *pParse);
6181 static CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
6182 static CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
6183 static CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
6184 static Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
6185 static int sqlite3CheckCollSeq(Parse *, CollSeq *);
6186 static int sqlite3CheckObjectName(Parse *, const char *);
6187 static void sqlite3VdbeSetChanges(sqlite3 *, int);
6188 static void sqlite3Utf16Substr(sqlite3_context *,int,sqlite3_value **);
6190 static const void *sqlite3ValueText(sqlite3_value*, u8);
6191 static int sqlite3ValueBytes(sqlite3_value*, u8);
6192 static void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, void(*)(void*));
6193 static void sqlite3ValueFree(sqlite3_value*);
6194 static sqlite3_value *sqlite3ValueNew(void);
6195 static char *sqlite3Utf16to8(const void*, int);
6196 static int sqlite3ValueFromExpr(Expr *, u8, u8, sqlite3_value **);
6197 static void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
6198 extern const unsigned char sqlite3UpperToLower[];
6199 static void sqlite3RootPageMoved(Db*, int, int);
6200 static void sqlite3Reindex(Parse*, Token*, Token*);
6201 static void sqlite3AlterFunctions(sqlite3*);
6202 static void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
6203 static int sqlite3GetToken(const unsigned char *, int *);
6204 static void sqlite3NestedParse(Parse*, const char*, ...);
6205 static void sqlite3ExpirePreparedStatements(sqlite3*);
6206 static void sqlite3CodeSubselect(Parse *, Expr *);
6207 static int sqlite3SelectResolve(Parse *, Select *, NameContext *);
6208 static void sqlite3ColumnDefault(Vdbe *, Table *, int);
6209 static void sqlite3AlterFinishAddColumn(Parse *, Token *);
6210 static void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
6211 static CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
6212 static char sqlite3AffinityType(const Token*);
6213 static void sqlite3Analyze(Parse*, Token*, Token*);
6214 static int sqlite3InvokeBusyHandler(BusyHandler*);
6215 static int sqlite3FindDb(sqlite3*, Token*);
6216 static int sqlite3AnalysisLoad(sqlite3*,int iDB);
6217 static void sqlite3DefaultRowEst(Index*);
6218 static void sqlite3RegisterLikeFunctions(sqlite3*, int);
6219 static int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
6220 static ThreadData *sqlite3ThreadData(void);
6221 static const ThreadData *sqlite3ThreadDataReadOnly(void);
6222 static void sqlite3ReleaseThreadData(void);
6223 static void sqlite3AttachFunctions(sqlite3 *);
6224 static void sqlite3MinimumFileFormat(Parse*, int, int);
6225 static void sqlite3SchemaFree(void *);
6226 static Schema *sqlite3SchemaGet(Btree *);
6227 static int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
6228 static KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
6229 static int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
6230 void (*)(sqlite3_context*,int,sqlite3_value **),
6231 void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
6232 static int sqlite3ApiExit(sqlite3 *db, int);
6233 static void sqlite3FailedMalloc(void);
6234 static void sqlite3AbortOtherActiveVdbes(sqlite3 *, Vdbe *);
6235 static int sqlite3OpenTempDatabase(Parse *);
6237 #ifndef SQLITE_OMIT_LOAD_EXTENSION
6238 static void sqlite3CloseExtensions(sqlite3*);
6239 static int sqlite3AutoLoadExtensions(sqlite3*);
6240 #else
6241 # define sqlite3CloseExtensions(X)
6242 # define sqlite3AutoLoadExtensions(X) SQLITE_OK
6243 #endif
6245 #ifndef SQLITE_OMIT_SHARED_CACHE
6246 static void sqlite3TableLock(Parse *, int, int, u8, const char *);
6247 #else
6248 #define sqlite3TableLock(v,w,x,y,z)
6249 #endif
6251 #ifdef SQLITE_TEST
6252 static int sqlite3Utf8To8(unsigned char*);
6253 #endif
6255 #ifdef SQLITE_MEMDEBUG
6256 static void sqlite3MallocDisallow(void);
6257 static void sqlite3MallocAllow(void);
6258 static int sqlite3TestMallocFail(void);
6259 #else
6260 #define sqlite3TestMallocFail() 0
6261 #define sqlite3MallocDisallow()
6262 #define sqlite3MallocAllow()
6263 #endif
6265 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
6266 static void *sqlite3ThreadSafeMalloc(int);
6267 static void sqlite3ThreadSafeFree(void *);
6268 #else
6269 #define sqlite3ThreadSafeMalloc sqlite3MallocX
6270 #define sqlite3ThreadSafeFree sqlite3FreeX
6271 #endif
6273 #ifdef SQLITE_OMIT_VIRTUALTABLE
6274 # define sqlite3VtabClear(X)
6275 # define sqlite3VtabSync(X,Y) (Y)
6276 # define sqlite3VtabRollback(X)
6277 # define sqlite3VtabCommit(X)
6278 #else
6279 static void sqlite3VtabClear(Table*);
6280 static int sqlite3VtabSync(sqlite3 *db, int rc);
6281 static int sqlite3VtabRollback(sqlite3 *db);
6282 static int sqlite3VtabCommit(sqlite3 *db);
6283 #endif
6284 static void sqlite3VtabLock(sqlite3_vtab*);
6285 static void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
6286 static void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
6287 static void sqlite3VtabFinishParse(Parse*, Token*);
6288 static void sqlite3VtabArgInit(Parse*);
6289 static void sqlite3VtabArgExtend(Parse*, Token*);
6290 static int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
6291 static int sqlite3VtabCallConnect(Parse*, Table*);
6292 static int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
6293 static int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
6294 static FuncDef *sqlite3VtabOverloadFunction(FuncDef*, int nArg, Expr*);
6295 static void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
6296 static int sqlite3Reprepare(Vdbe*);
6297 static void sqlite3ExprListCheckLength(Parse*, ExprList*, int, const char*);
6298 CollSeq* sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
6300 #if SQLITE_MAX_EXPR_DEPTH>0
6301 static void sqlite3ExprSetHeight(Expr *);
6302 static int sqlite3SelectExprHeight(Select *);
6303 #else
6304 #define sqlite3ExprSetHeight(x)
6305 #endif
6307 static u32 sqlite3Get2byte(const u8*);
6308 static u32 sqlite3Get4byte(const u8*);
6309 static void sqlite3Put2byte(u8*, u32);
6310 static void sqlite3Put4byte(u8*, u32);
6312 #ifdef SQLITE_SSE
6313 #include "sseInt.h"
6314 #endif
6316 #ifdef SQLITE_DEBUG
6317 static void sqlite3ParserTrace(FILE*, char *);
6318 #endif
6321 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
6322 ** sqlite3_io_trace is a pointer to a printf-like routine used to
6323 ** print I/O tracing messages.
6325 #ifdef SQLITE_ENABLE_IOTRACE
6326 # define IOTRACE(A) if( sqlite3_io_trace ){ sqlite3_io_trace A; }
6327 static void sqlite3VdbeIOTraceSql(Vdbe*);
6328 #else
6329 # define IOTRACE(A)
6330 # define sqlite3VdbeIOTraceSql(X)
6331 #endif
6332 extern void (*sqlite3_io_trace)(const char*,...);
6334 #endif
6336 /************** End of sqliteInt.h *******************************************/
6337 /************** Continuing where we left off in date.c ***********************/
6338 #include <ctype.h>
6339 #include <time.h>
6341 #ifndef SQLITE_OMIT_DATETIME_FUNCS
6344 ** A structure for holding a single date and time.
6346 typedef struct DateTime DateTime;
6347 struct DateTime {
6348 double rJD; /* The julian day number */
6349 int Y, M, D; /* Year, month, and day */
6350 int h, m; /* Hour and minutes */
6351 int tz; /* Timezone offset in minutes */
6352 double s; /* Seconds */
6353 char validYMD; /* True if Y,M,D are valid */
6354 char validHMS; /* True if h,m,s are valid */
6355 char validJD; /* True if rJD is valid */
6356 char validTZ; /* True if tz is valid */
6361 ** Convert zDate into one or more integers. Additional arguments
6362 ** come in groups of 5 as follows:
6364 ** N number of digits in the integer
6365 ** min minimum allowed value of the integer
6366 ** max maximum allowed value of the integer
6367 ** nextC first character after the integer
6368 ** pVal where to write the integers value.
6370 ** Conversions continue until one with nextC==0 is encountered.
6371 ** The function returns the number of successful conversions.
6373 static int getDigits(const char *zDate, ...){
6374 va_list ap;
6375 int val;
6376 int N;
6377 int min;
6378 int max;
6379 int nextC;
6380 int *pVal;
6381 int cnt = 0;
6382 va_start(ap, zDate);
6384 N = va_arg(ap, int);
6385 min = va_arg(ap, int);
6386 max = va_arg(ap, int);
6387 nextC = va_arg(ap, int);
6388 pVal = va_arg(ap, int*);
6389 val = 0;
6390 while( N-- ){
6391 if( !isdigit(*(u8*)zDate) ){
6392 goto end_getDigits;
6394 val = val*10 + *zDate - '0';
6395 zDate++;
6397 if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
6398 goto end_getDigits;
6400 *pVal = val;
6401 zDate++;
6402 cnt++;
6403 }while( nextC );
6404 end_getDigits:
6405 va_end(ap);
6406 return cnt;
6410 ** Read text from z[] and convert into a floating point number. Return
6411 ** the number of digits converted.
6413 #define getValue sqlite3AtoF
6416 ** Parse a timezone extension on the end of a date-time.
6417 ** The extension is of the form:
6419 ** (+/-)HH:MM
6421 ** If the parse is successful, write the number of minutes
6422 ** of change in *pnMin and return 0. If a parser error occurs,
6423 ** return 0.
6425 ** A missing specifier is not considered an error.
6427 static int parseTimezone(const char *zDate, DateTime *p){
6428 int sgn = 0;
6429 int nHr, nMn;
6430 while( isspace(*(u8*)zDate) ){ zDate++; }
6431 p->tz = 0;
6432 if( *zDate=='-' ){
6433 sgn = -1;
6434 }else if( *zDate=='+' ){
6435 sgn = +1;
6436 }else{
6437 return *zDate!=0;
6439 zDate++;
6440 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
6441 return 1;
6443 zDate += 5;
6444 p->tz = sgn*(nMn + nHr*60);
6445 while( isspace(*(u8*)zDate) ){ zDate++; }
6446 return *zDate!=0;
6450 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
6451 ** The HH, MM, and SS must each be exactly 2 digits. The
6452 ** fractional seconds FFFF can be one or more digits.
6454 ** Return 1 if there is a parsing error and 0 on success.
6456 static int parseHhMmSs(const char *zDate, DateTime *p){
6457 int h, m, s;
6458 double ms = 0.0;
6459 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
6460 return 1;
6462 zDate += 5;
6463 if( *zDate==':' ){
6464 zDate++;
6465 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
6466 return 1;
6468 zDate += 2;
6469 if( *zDate=='.' && isdigit((u8)zDate[1]) ){
6470 double rScale = 1.0;
6471 zDate++;
6472 while( isdigit(*(u8*)zDate) ){
6473 ms = ms*10.0 + *zDate - '0';
6474 rScale *= 10.0;
6475 zDate++;
6477 ms /= rScale;
6479 }else{
6480 s = 0;
6482 p->validJD = 0;
6483 p->validHMS = 1;
6484 p->h = h;
6485 p->m = m;
6486 p->s = s + ms;
6487 if( parseTimezone(zDate, p) ) return 1;
6488 p->validTZ = p->tz!=0;
6489 return 0;
6493 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
6494 ** that the YYYY-MM-DD is according to the Gregorian calendar.
6496 ** Reference: Meeus page 61
6498 static void computeJD(DateTime *p){
6499 int Y, M, D, A, B, X1, X2;
6501 if( p->validJD ) return;
6502 if( p->validYMD ){
6503 Y = p->Y;
6504 M = p->M;
6505 D = p->D;
6506 }else{
6507 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
6508 M = 1;
6509 D = 1;
6511 if( M<=2 ){
6512 Y--;
6513 M += 12;
6515 A = Y/100;
6516 B = 2 - A + (A/4);
6517 X1 = 365.25*(Y+4716);
6518 X2 = 30.6001*(M+1);
6519 p->rJD = X1 + X2 + D + B - 1524.5;
6520 p->validJD = 1;
6521 if( p->validHMS ){
6522 p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
6523 if( p->validTZ ){
6524 p->rJD -= p->tz*60/86400.0;
6525 p->validYMD = 0;
6526 p->validHMS = 0;
6527 p->validTZ = 0;
6533 ** Parse dates of the form
6535 ** YYYY-MM-DD HH:MM:SS.FFF
6536 ** YYYY-MM-DD HH:MM:SS
6537 ** YYYY-MM-DD HH:MM
6538 ** YYYY-MM-DD
6540 ** Write the result into the DateTime structure and return 0
6541 ** on success and 1 if the input string is not a well-formed
6542 ** date.
6544 static int parseYyyyMmDd(const char *zDate, DateTime *p){
6545 int Y, M, D, neg;
6547 if( zDate[0]=='-' ){
6548 zDate++;
6549 neg = 1;
6550 }else{
6551 neg = 0;
6553 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
6554 return 1;
6556 zDate += 10;
6557 while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
6558 if( parseHhMmSs(zDate, p)==0 ){
6559 /* We got the time */
6560 }else if( *zDate==0 ){
6561 p->validHMS = 0;
6562 }else{
6563 return 1;
6565 p->validJD = 0;
6566 p->validYMD = 1;
6567 p->Y = neg ? -Y : Y;
6568 p->M = M;
6569 p->D = D;
6570 if( p->validTZ ){
6571 computeJD(p);
6573 return 0;
6577 ** Attempt to parse the given string into a Julian Day Number. Return
6578 ** the number of errors.
6580 ** The following are acceptable forms for the input string:
6582 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
6583 ** DDDD.DD
6584 ** now
6586 ** In the first form, the +/-HH:MM is always optional. The fractional
6587 ** seconds extension (the ".FFF") is optional. The seconds portion
6588 ** (":SS.FFF") is option. The year and date can be omitted as long
6589 ** as there is a time string. The time string can be omitted as long
6590 ** as there is a year and date.
6592 static int parseDateOrTime(const char *zDate, DateTime *p){
6593 memset(p, 0, sizeof(*p));
6594 if( parseYyyyMmDd(zDate,p)==0 ){
6595 return 0;
6596 }else if( parseHhMmSs(zDate, p)==0 ){
6597 return 0;
6598 }else if( sqlite3StrICmp(zDate,"now")==0){
6599 double r;
6600 sqlite3OsCurrentTime(&r);
6601 p->rJD = r;
6602 p->validJD = 1;
6603 return 0;
6604 }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
6605 getValue(zDate, &p->rJD);
6606 p->validJD = 1;
6607 return 0;
6609 return 1;
6613 ** Compute the Year, Month, and Day from the julian day number.
6615 static void computeYMD(DateTime *p){
6616 int Z, A, B, C, D, E, X1;
6617 if( p->validYMD ) return;
6618 if( !p->validJD ){
6619 p->Y = 2000;
6620 p->M = 1;
6621 p->D = 1;
6622 }else{
6623 Z = p->rJD + 0.5;
6624 A = (Z - 1867216.25)/36524.25;
6625 A = Z + 1 + A - (A/4);
6626 B = A + 1524;
6627 C = (B - 122.1)/365.25;
6628 D = 365.25*C;
6629 E = (B-D)/30.6001;
6630 X1 = 30.6001*E;
6631 p->D = B - D - X1;
6632 p->M = E<14 ? E-1 : E-13;
6633 p->Y = p->M>2 ? C - 4716 : C - 4715;
6635 p->validYMD = 1;
6639 ** Compute the Hour, Minute, and Seconds from the julian day number.
6641 static void computeHMS(DateTime *p){
6642 int Z, s;
6643 if( p->validHMS ) return;
6644 computeJD(p);
6645 Z = p->rJD + 0.5;
6646 s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
6647 p->s = 0.001*s;
6648 s = p->s;
6649 p->s -= s;
6650 p->h = s/3600;
6651 s -= p->h*3600;
6652 p->m = s/60;
6653 p->s += s - p->m*60;
6654 p->validHMS = 1;
6658 ** Compute both YMD and HMS
6660 static void computeYMD_HMS(DateTime *p){
6661 computeYMD(p);
6662 computeHMS(p);
6666 ** Clear the YMD and HMS and the TZ
6668 static void clearYMD_HMS_TZ(DateTime *p){
6669 p->validYMD = 0;
6670 p->validHMS = 0;
6671 p->validTZ = 0;
6675 ** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
6676 ** for the time value p where p is in UTC.
6678 static double localtimeOffset(DateTime *p){
6679 DateTime x, y;
6680 time_t t;
6681 x = *p;
6682 computeYMD_HMS(&x);
6683 if( x.Y<1971 || x.Y>=2038 ){
6684 x.Y = 2000;
6685 x.M = 1;
6686 x.D = 1;
6687 x.h = 0;
6688 x.m = 0;
6689 x.s = 0.0;
6690 } else {
6691 int s = x.s + 0.5;
6692 x.s = s;
6694 x.tz = 0;
6695 x.validJD = 0;
6696 computeJD(&x);
6697 t = (x.rJD-2440587.5)*86400.0 + 0.5;
6698 #ifdef HAVE_LOCALTIME_R
6700 struct tm sLocal;
6701 localtime_r(&t, &sLocal);
6702 y.Y = sLocal.tm_year + 1900;
6703 y.M = sLocal.tm_mon + 1;
6704 y.D = sLocal.tm_mday;
6705 y.h = sLocal.tm_hour;
6706 y.m = sLocal.tm_min;
6707 y.s = sLocal.tm_sec;
6709 #else
6711 struct tm *pTm;
6712 sqlite3OsEnterMutex();
6713 pTm = localtime(&t);
6714 y.Y = pTm->tm_year + 1900;
6715 y.M = pTm->tm_mon + 1;
6716 y.D = pTm->tm_mday;
6717 y.h = pTm->tm_hour;
6718 y.m = pTm->tm_min;
6719 y.s = pTm->tm_sec;
6720 sqlite3OsLeaveMutex();
6722 #endif
6723 y.validYMD = 1;
6724 y.validHMS = 1;
6725 y.validJD = 0;
6726 y.validTZ = 0;
6727 computeJD(&y);
6728 return y.rJD - x.rJD;
6732 ** Process a modifier to a date-time stamp. The modifiers are
6733 ** as follows:
6735 ** NNN days
6736 ** NNN hours
6737 ** NNN minutes
6738 ** NNN.NNNN seconds
6739 ** NNN months
6740 ** NNN years
6741 ** start of month
6742 ** start of year
6743 ** start of week
6744 ** start of day
6745 ** weekday N
6746 ** unixepoch
6747 ** localtime
6748 ** utc
6750 ** Return 0 on success and 1 if there is any kind of error.
6752 static int parseModifier(const char *zMod, DateTime *p){
6753 int rc = 1;
6754 int n;
6755 double r;
6756 char *z, zBuf[30];
6757 z = zBuf;
6758 for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
6759 z[n] = tolower(zMod[n]);
6761 z[n] = 0;
6762 switch( z[0] ){
6763 case 'l': {
6764 /* localtime
6766 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
6767 ** show local time.
6769 if( strcmp(z, "localtime")==0 ){
6770 computeJD(p);
6771 p->rJD += localtimeOffset(p);
6772 clearYMD_HMS_TZ(p);
6773 rc = 0;
6775 break;
6777 case 'u': {
6779 ** unixepoch
6781 ** Treat the current value of p->rJD as the number of
6782 ** seconds since 1970. Convert to a real julian day number.
6784 if( strcmp(z, "unixepoch")==0 && p->validJD ){
6785 p->rJD = p->rJD/86400.0 + 2440587.5;
6786 clearYMD_HMS_TZ(p);
6787 rc = 0;
6788 }else if( strcmp(z, "utc")==0 ){
6789 double c1;
6790 computeJD(p);
6791 c1 = localtimeOffset(p);
6792 p->rJD -= c1;
6793 clearYMD_HMS_TZ(p);
6794 p->rJD += c1 - localtimeOffset(p);
6795 rc = 0;
6797 break;
6799 case 'w': {
6801 ** weekday N
6803 ** Move the date to the same time on the next occurrence of
6804 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
6805 ** date is already on the appropriate weekday, this is a no-op.
6807 if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
6808 && (n=r)==r && n>=0 && r<7 ){
6809 int Z;
6810 computeYMD_HMS(p);
6811 p->validTZ = 0;
6812 p->validJD = 0;
6813 computeJD(p);
6814 Z = p->rJD + 1.5;
6815 Z %= 7;
6816 if( Z>n ) Z -= 7;
6817 p->rJD += n - Z;
6818 clearYMD_HMS_TZ(p);
6819 rc = 0;
6821 break;
6823 case 's': {
6825 ** start of TTTTT
6827 ** Move the date backwards to the beginning of the current day,
6828 ** or month or year.
6830 if( strncmp(z, "start of ", 9)!=0 ) break;
6831 z += 9;
6832 computeYMD(p);
6833 p->validHMS = 1;
6834 p->h = p->m = 0;
6835 p->s = 0.0;
6836 p->validTZ = 0;
6837 p->validJD = 0;
6838 if( strcmp(z,"month")==0 ){
6839 p->D = 1;
6840 rc = 0;
6841 }else if( strcmp(z,"year")==0 ){
6842 computeYMD(p);
6843 p->M = 1;
6844 p->D = 1;
6845 rc = 0;
6846 }else if( strcmp(z,"day")==0 ){
6847 rc = 0;
6849 break;
6851 case '+':
6852 case '-':
6853 case '0':
6854 case '1':
6855 case '2':
6856 case '3':
6857 case '4':
6858 case '5':
6859 case '6':
6860 case '7':
6861 case '8':
6862 case '9': {
6863 n = getValue(z, &r);
6864 assert( n>=1 );
6865 if( z[n]==':' ){
6866 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
6867 ** specified number of hours, minutes, seconds, and fractional seconds
6868 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
6869 ** omitted.
6871 const char *z2 = z;
6872 DateTime tx;
6873 int day;
6874 if( !isdigit(*(u8*)z2) ) z2++;
6875 memset(&tx, 0, sizeof(tx));
6876 if( parseHhMmSs(z2, &tx) ) break;
6877 computeJD(&tx);
6878 tx.rJD -= 0.5;
6879 day = (int)tx.rJD;
6880 tx.rJD -= day;
6881 if( z[0]=='-' ) tx.rJD = -tx.rJD;
6882 computeJD(p);
6883 clearYMD_HMS_TZ(p);
6884 p->rJD += tx.rJD;
6885 rc = 0;
6886 break;
6888 z += n;
6889 while( isspace(*(u8*)z) ) z++;
6890 n = strlen(z);
6891 if( n>10 || n<3 ) break;
6892 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
6893 computeJD(p);
6894 rc = 0;
6895 if( n==3 && strcmp(z,"day")==0 ){
6896 p->rJD += r;
6897 }else if( n==4 && strcmp(z,"hour")==0 ){
6898 p->rJD += r/24.0;
6899 }else if( n==6 && strcmp(z,"minute")==0 ){
6900 p->rJD += r/(24.0*60.0);
6901 }else if( n==6 && strcmp(z,"second")==0 ){
6902 p->rJD += r/(24.0*60.0*60.0);
6903 }else if( n==5 && strcmp(z,"month")==0 ){
6904 int x, y;
6905 computeYMD_HMS(p);
6906 p->M += r;
6907 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
6908 p->Y += x;
6909 p->M -= x*12;
6910 p->validJD = 0;
6911 computeJD(p);
6912 y = r;
6913 if( y!=r ){
6914 p->rJD += (r - y)*30.0;
6916 }else if( n==4 && strcmp(z,"year")==0 ){
6917 computeYMD_HMS(p);
6918 p->Y += r;
6919 p->validJD = 0;
6920 computeJD(p);
6921 }else{
6922 rc = 1;
6924 clearYMD_HMS_TZ(p);
6925 break;
6927 default: {
6928 break;
6931 return rc;
6935 ** Process time function arguments. argv[0] is a date-time stamp.
6936 ** argv[1] and following are modifiers. Parse them all and write
6937 ** the resulting time into the DateTime structure p. Return 0
6938 ** on success and 1 if there are any errors.
6940 static int isDate(int argc, sqlite3_value **argv, DateTime *p){
6941 int i;
6942 const unsigned char *z;
6943 if( argc==0 ) return 1;
6944 if( (z = sqlite3_value_text(argv[0]))==0 || parseDateOrTime((char*)z, p) ){
6945 return 1;
6947 for(i=1; i<argc; i++){
6948 if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
6949 return 1;
6952 return 0;
6957 ** The following routines implement the various date and time functions
6958 ** of SQLite.
6962 ** julianday( TIMESTRING, MOD, MOD, ...)
6964 ** Return the julian day number of the date specified in the arguments
6966 static void juliandayFunc(
6967 sqlite3_context *context,
6968 int argc,
6969 sqlite3_value **argv
6971 DateTime x;
6972 if( isDate(argc, argv, &x)==0 ){
6973 computeJD(&x);
6974 sqlite3_result_double(context, x.rJD);
6979 ** datetime( TIMESTRING, MOD, MOD, ...)
6981 ** Return YYYY-MM-DD HH:MM:SS
6983 static void datetimeFunc(
6984 sqlite3_context *context,
6985 int argc,
6986 sqlite3_value **argv
6988 DateTime x;
6989 if( isDate(argc, argv, &x)==0 ){
6990 char zBuf[100];
6991 computeYMD_HMS(&x);
6992 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
6993 x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
6994 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
6999 ** time( TIMESTRING, MOD, MOD, ...)
7001 ** Return HH:MM:SS
7003 static void timeFunc(
7004 sqlite3_context *context,
7005 int argc,
7006 sqlite3_value **argv
7008 DateTime x;
7009 if( isDate(argc, argv, &x)==0 ){
7010 char zBuf[100];
7011 computeHMS(&x);
7012 sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
7013 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
7018 ** date( TIMESTRING, MOD, MOD, ...)
7020 ** Return YYYY-MM-DD
7022 static void dateFunc(
7023 sqlite3_context *context,
7024 int argc,
7025 sqlite3_value **argv
7027 DateTime x;
7028 if( isDate(argc, argv, &x)==0 ){
7029 char zBuf[100];
7030 computeYMD(&x);
7031 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
7032 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
7037 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
7039 ** Return a string described by FORMAT. Conversions as follows:
7041 ** %d day of month
7042 ** %f ** fractional seconds SS.SSS
7043 ** %H hour 00-24
7044 ** %j day of year 000-366
7045 ** %J ** Julian day number
7046 ** %m month 01-12
7047 ** %M minute 00-59
7048 ** %s seconds since 1970-01-01
7049 ** %S seconds 00-59
7050 ** %w day of week 0-6 sunday==0
7051 ** %W week of year 00-53
7052 ** %Y year 0000-9999
7053 ** %% %
7055 static void strftimeFunc(
7056 sqlite3_context *context,
7057 int argc,
7058 sqlite3_value **argv
7060 DateTime x;
7061 u64 n;
7062 int i, j;
7063 char *z;
7064 const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
7065 char zBuf[100];
7066 if( zFmt==0 || isDate(argc-1, argv+1, &x) ) return;
7067 for(i=0, n=1; zFmt[i]; i++, n++){
7068 if( zFmt[i]=='%' ){
7069 switch( zFmt[i+1] ){
7070 case 'd':
7071 case 'H':
7072 case 'm':
7073 case 'M':
7074 case 'S':
7075 case 'W':
7076 n++;
7077 /* fall thru */
7078 case 'w':
7079 case '%':
7080 break;
7081 case 'f':
7082 n += 8;
7083 break;
7084 case 'j':
7085 n += 3;
7086 break;
7087 case 'Y':
7088 n += 8;
7089 break;
7090 case 's':
7091 case 'J':
7092 n += 50;
7093 break;
7094 default:
7095 return; /* ERROR. return a NULL */
7097 i++;
7100 if( n<sizeof(zBuf) ){
7101 z = zBuf;
7102 }else if( n>SQLITE_MAX_LENGTH ){
7103 sqlite3_result_error_toobig(context);
7104 return;
7105 }else{
7106 z = sqliteMalloc( n );
7107 if( z==0 ) return;
7109 computeJD(&x);
7110 computeYMD_HMS(&x);
7111 for(i=j=0; zFmt[i]; i++){
7112 if( zFmt[i]!='%' ){
7113 z[j++] = zFmt[i];
7114 }else{
7115 i++;
7116 switch( zFmt[i] ){
7117 case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
7118 case 'f': {
7119 double s = x.s;
7120 if( s>59.999 ) s = 59.999;
7121 sqlite3_snprintf(7, &z[j],"%06.3f", s);
7122 j += strlen(&z[j]);
7123 break;
7125 case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
7126 case 'W': /* Fall thru */
7127 case 'j': {
7128 int nDay; /* Number of days since 1st day of year */
7129 DateTime y = x;
7130 y.validJD = 0;
7131 y.M = 1;
7132 y.D = 1;
7133 computeJD(&y);
7134 nDay = x.rJD - y.rJD + 0.5;
7135 if( zFmt[i]=='W' ){
7136 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
7137 wd = ((int)(x.rJD+0.5)) % 7;
7138 sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
7139 j += 2;
7140 }else{
7141 sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
7142 j += 3;
7144 break;
7146 case 'J': {
7147 sqlite3_snprintf(20, &z[j],"%.16g",x.rJD);
7148 j+=strlen(&z[j]);
7149 break;
7151 case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
7152 case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
7153 case 's': {
7154 sqlite3_snprintf(30,&z[j],"%d",
7155 (int)((x.rJD-2440587.5)*86400.0 + 0.5));
7156 j += strlen(&z[j]);
7157 break;
7159 case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
7160 case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
7161 case 'Y': sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
7162 case '%': z[j++] = '%'; break;
7166 z[j] = 0;
7167 sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
7168 if( z!=zBuf ){
7169 sqliteFree(z);
7174 ** current_time()
7176 ** This function returns the same value as time('now').
7178 static void ctimeFunc(
7179 sqlite3_context *context,
7180 int argc,
7181 sqlite3_value **argv
7183 sqlite3_value *pVal = sqlite3ValueNew();
7184 if( pVal ){
7185 sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
7186 timeFunc(context, 1, &pVal);
7187 sqlite3ValueFree(pVal);
7192 ** current_date()
7194 ** This function returns the same value as date('now').
7196 static void cdateFunc(
7197 sqlite3_context *context,
7198 int argc,
7199 sqlite3_value **argv
7201 sqlite3_value *pVal = sqlite3ValueNew();
7202 if( pVal ){
7203 sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
7204 dateFunc(context, 1, &pVal);
7205 sqlite3ValueFree(pVal);
7210 ** current_timestamp()
7212 ** This function returns the same value as datetime('now').
7214 static void ctimestampFunc(
7215 sqlite3_context *context,
7216 int argc,
7217 sqlite3_value **argv
7219 sqlite3_value *pVal = sqlite3ValueNew();
7220 if( pVal ){
7221 sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC);
7222 datetimeFunc(context, 1, &pVal);
7223 sqlite3ValueFree(pVal);
7226 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
7228 #ifdef SQLITE_OMIT_DATETIME_FUNCS
7230 ** If the library is compiled to omit the full-scale date and time
7231 ** handling (to get a smaller binary), the following minimal version
7232 ** of the functions current_time(), current_date() and current_timestamp()
7233 ** are included instead. This is to support column declarations that
7234 ** include "DEFAULT CURRENT_TIME" etc.
7236 ** This function uses the C-library functions time(), gmtime()
7237 ** and strftime(). The format string to pass to strftime() is supplied
7238 ** as the user-data for the function.
7240 static void currentTimeFunc(
7241 sqlite3_context *context,
7242 int argc,
7243 sqlite3_value **argv
7245 time_t t;
7246 char *zFormat = (char *)sqlite3_user_data(context);
7247 char zBuf[20];
7249 time(&t);
7250 #ifdef SQLITE_TEST
7252 extern int sqlite3_current_time; /* See os_XXX.c */
7253 if( sqlite3_current_time ){
7254 t = sqlite3_current_time;
7257 #endif
7259 #ifdef HAVE_GMTIME_R
7261 struct tm sNow;
7262 gmtime_r(&t, &sNow);
7263 strftime(zBuf, 20, zFormat, &sNow);
7265 #else
7267 struct tm *pTm;
7268 sqlite3OsEnterMutex();
7269 pTm = gmtime(&t);
7270 strftime(zBuf, 20, zFormat, pTm);
7271 sqlite3OsLeaveMutex();
7273 #endif
7275 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
7277 #endif
7280 ** This function registered all of the above C functions as SQL
7281 ** functions. This should be the only routine in this file with
7282 ** external linkage.
7284 static void sqlite3RegisterDateTimeFunctions(sqlite3 *db){
7285 #ifndef SQLITE_OMIT_DATETIME_FUNCS
7286 static const struct {
7287 char *zName;
7288 int nArg;
7289 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
7290 } aFuncs[] = {
7291 { "julianday", -1, juliandayFunc },
7292 { "date", -1, dateFunc },
7293 { "time", -1, timeFunc },
7294 { "datetime", -1, datetimeFunc },
7295 { "strftime", -1, strftimeFunc },
7296 { "current_time", 0, ctimeFunc },
7297 { "current_timestamp", 0, ctimestampFunc },
7298 { "current_date", 0, cdateFunc },
7300 int i;
7302 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
7303 sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
7304 SQLITE_UTF8, 0, aFuncs[i].xFunc, 0, 0);
7306 #else
7307 static const struct {
7308 char *zName;
7309 char *zFormat;
7310 } aFuncs[] = {
7311 { "current_time", "%H:%M:%S" },
7312 { "current_date", "%Y-%m-%d" },
7313 { "current_timestamp", "%Y-%m-%d %H:%M:%S" }
7315 int i;
7317 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
7318 sqlite3CreateFunc(db, aFuncs[i].zName, 0, SQLITE_UTF8,
7319 aFuncs[i].zFormat, currentTimeFunc, 0, 0);
7321 #endif
7324 /************** End of date.c ************************************************/
7325 /************** Begin file os.c **********************************************/
7327 ** 2005 November 29
7329 ** The author disclaims copyright to this source code. In place of
7330 ** a legal notice, here is a blessing:
7332 ** May you do good and not evil.
7333 ** May you find forgiveness for yourself and forgive others.
7334 ** May you share freely, never taking more than you give.
7336 ******************************************************************************
7338 ** This file contains OS interface code that is common to all
7339 ** architectures.
7341 #define _SQLITE_OS_C_ 1
7342 #undef _SQLITE_OS_C_
7345 ** The following routines are convenience wrappers around methods
7346 ** of the OsFile object. This is mostly just syntactic sugar. All
7347 ** of this would be completely automatic if SQLite were coded using
7348 ** C++ instead of plain old C.
7350 static int sqlite3OsClose(OsFile **pId){
7351 OsFile *id;
7352 if( pId!=0 && (id = *pId)!=0 ){
7353 return id->pMethod->xClose(pId);
7354 }else{
7355 return SQLITE_OK;
7358 static int sqlite3OsOpenDirectory(OsFile *id, const char *zName){
7359 return id->pMethod->xOpenDirectory(id, zName);
7361 static int sqlite3OsRead(OsFile *id, void *pBuf, int amt){
7362 return id->pMethod->xRead(id, pBuf, amt);
7364 static int sqlite3OsWrite(OsFile *id, const void *pBuf, int amt){
7365 return id->pMethod->xWrite(id, pBuf, amt);
7367 static int sqlite3OsSeek(OsFile *id, i64 offset){
7368 return id->pMethod->xSeek(id, offset);
7370 static int sqlite3OsTruncate(OsFile *id, i64 size){
7371 return id->pMethod->xTruncate(id, size);
7373 static int sqlite3OsSync(OsFile *id, int fullsync){
7374 return id->pMethod->xSync(id, fullsync);
7376 static void sqlite3OsSetFullSync(OsFile *id, int value){
7377 id->pMethod->xSetFullSync(id, value);
7379 static int sqlite3OsFileSize(OsFile *id, i64 *pSize){
7380 return id->pMethod->xFileSize(id, pSize);
7382 static int sqlite3OsLock(OsFile *id, int lockType){
7383 return id->pMethod->xLock(id, lockType);
7385 static int sqlite3OsUnlock(OsFile *id, int lockType){
7386 return id->pMethod->xUnlock(id, lockType);
7388 static int sqlite3OsCheckReservedLock(OsFile *id){
7389 return id->pMethod->xCheckReservedLock(id);
7391 static int sqlite3OsSectorSize(OsFile *id){
7392 int (*xSectorSize)(OsFile*) = id->pMethod->xSectorSize;
7393 return xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE;
7396 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
7397 /* These methods are currently only used for testing and debugging. */
7398 int sqlite3OsFileHandle(OsFile *id){
7399 return id->pMethod->xFileHandle(id);
7401 int sqlite3OsLockState(OsFile *id){
7402 return id->pMethod->xLockState(id);
7404 #endif
7406 #ifdef SQLITE_ENABLE_REDEF_IO
7408 ** A function to return a pointer to the virtual function table.
7409 ** This routine really does not accomplish very much since the
7410 ** virtual function table is a global variable and anybody who
7411 ** can call this function can just as easily access the variable
7412 ** for themselves. Nevertheless, we include this routine for
7413 ** backwards compatibility with an earlier redefinable I/O
7414 ** interface design.
7416 struct sqlite3OsVtbl *sqlite3_os_switch(void){
7417 return &sqlite3Os;
7419 #endif
7421 /************** End of os.c **************************************************/
7422 /************** Begin file malloc.c ******************************************/
7424 ** 2001 September 15
7426 ** The author disclaims copyright to this source code. In place of
7427 ** a legal notice, here is a blessing:
7429 ** May you do good and not evil.
7430 ** May you find forgiveness for yourself and forgive others.
7431 ** May you share freely, never taking more than you give.
7433 *************************************************************************
7434 ** Memory allocation functions used throughout sqlite.
7437 ** $Id: malloc.c,v 1.3 2007/06/15 20:29:20 drh Exp $
7441 ** MALLOC WRAPPER ARCHITECTURE
7443 ** The sqlite code accesses dynamic memory allocation/deallocation by invoking
7444 ** the following six APIs (which may be implemented as macros).
7446 ** sqlite3Malloc()
7447 ** sqlite3MallocRaw()
7448 ** sqlite3Realloc()
7449 ** sqlite3ReallocOrFree()
7450 ** sqlite3Free()
7451 ** sqlite3AllocSize()
7453 ** The function sqlite3FreeX performs the same task as sqlite3Free and is
7454 ** guaranteed to be a real function. The same holds for sqlite3MallocX
7456 ** The above APIs are implemented in terms of the functions provided in the
7457 ** operating-system interface. The OS interface is never accessed directly
7458 ** by code outside of this file.
7460 ** sqlite3OsMalloc()
7461 ** sqlite3OsRealloc()
7462 ** sqlite3OsFree()
7463 ** sqlite3OsAllocationSize()
7465 ** Functions sqlite3MallocRaw() and sqlite3Realloc() may invoke
7466 ** sqlite3_release_memory() if a call to sqlite3OsMalloc() or
7467 ** sqlite3OsRealloc() fails (or if the soft-heap-limit for the thread is
7468 ** exceeded). Function sqlite3Malloc() usually invokes
7469 ** sqlite3MallocRaw().
7471 ** MALLOC TEST WRAPPER ARCHITECTURE
7473 ** The test wrapper provides extra test facilities to ensure the library
7474 ** does not leak memory and handles the failure of the underlying OS level
7475 ** allocation system correctly. It is only present if the library is
7476 ** compiled with the SQLITE_MEMDEBUG macro set.
7478 ** * Guardposts to detect overwrites.
7479 ** * Ability to cause a specific Malloc() or Realloc() to fail.
7480 ** * Audit outstanding memory allocations (i.e check for leaks).
7483 #define MAX(x,y) ((x)>(y)?(x):(y))
7485 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
7487 ** Set the soft heap-size limit for the current thread. Passing a negative
7488 ** value indicates no limit.
7490 void sqlite3_soft_heap_limit(int n){
7491 ThreadData *pTd = sqlite3ThreadData();
7492 if( pTd ){
7493 pTd->nSoftHeapLimit = n;
7495 sqlite3ReleaseThreadData();
7499 ** Release memory held by SQLite instances created by the current thread.
7501 int sqlite3_release_memory(int n){
7502 return sqlite3PagerReleaseMemory(n);
7504 #else
7505 /* If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, then define a version
7506 ** of sqlite3_release_memory() to be used by other code in this file.
7507 ** This is done for no better reason than to reduce the number of
7508 ** pre-processor #ifndef statements.
7510 #define sqlite3_release_memory(x) 0 /* 0 == no memory freed */
7511 #endif
7513 #ifdef SQLITE_MEMDEBUG
7514 /*--------------------------------------------------------------------------
7515 ** Begin code for memory allocation system test layer.
7517 ** Memory debugging is turned on by defining the SQLITE_MEMDEBUG macro.
7519 ** SQLITE_MEMDEBUG==1 -> Fence-posting only (thread safe)
7520 ** SQLITE_MEMDEBUG==2 -> Fence-posting + linked list of allocations (not ts)
7521 ** SQLITE_MEMDEBUG==3 -> Above + backtraces (not thread safe, req. glibc)
7524 /* Figure out whether or not to store backtrace() information for each malloc.
7525 ** The backtrace() function is only used if SQLITE_MEMDEBUG is set to 2 or
7526 ** greater and glibc is in use. If we don't want to use backtrace(), then just
7527 ** define it as an empty macro and set the amount of space reserved to 0.
7529 #if defined(__GLIBC__) && SQLITE_MEMDEBUG>2
7530 extern int backtrace(void **, int);
7531 #define TESTALLOC_STACKSIZE 128
7532 #define TESTALLOC_STACKFRAMES ((TESTALLOC_STACKSIZE-8)/sizeof(void*))
7533 #else
7534 #define backtrace(x, y)
7535 #define TESTALLOC_STACKSIZE 0
7536 #define TESTALLOC_STACKFRAMES 0
7537 #endif
7540 ** Number of 32-bit guard words. This should probably be a multiple of
7541 ** 2 since on 64-bit machines we want the value returned by sqliteMalloc()
7542 ** to be 8-byte aligned.
7544 #ifndef TESTALLOC_NGUARD
7545 # define TESTALLOC_NGUARD 2
7546 #endif
7549 ** Size reserved for storing file-name along with each malloc()ed blob.
7551 #define TESTALLOC_FILESIZE 64
7554 ** Size reserved for storing the user string. Each time a Malloc() or Realloc()
7555 ** call succeeds, up to TESTALLOC_USERSIZE bytes of the string pointed to by
7556 ** sqlite3_malloc_id are stored along with the other test system metadata.
7558 #define TESTALLOC_USERSIZE 64
7559 const char *sqlite3_malloc_id = 0;
7562 ** Blocks used by the test layer have the following format:
7564 ** <sizeof(void *) pNext pointer>
7565 ** <sizeof(void *) pPrev pointer>
7566 ** <TESTALLOC_NGUARD 32-bit guard words>
7567 ** <The application level allocation>
7568 ** <TESTALLOC_NGUARD 32-bit guard words>
7569 ** <32-bit line number>
7570 ** <TESTALLOC_FILESIZE bytes containing null-terminated file name>
7571 ** <TESTALLOC_STACKSIZE bytes of backtrace() output>
7574 #define TESTALLOC_OFFSET_GUARD1(p) (sizeof(void *) * 2)
7575 #define TESTALLOC_OFFSET_DATA(p) ( \
7576 TESTALLOC_OFFSET_GUARD1(p) + sizeof(u32) * TESTALLOC_NGUARD \
7578 #define TESTALLOC_OFFSET_GUARD2(p) ( \
7579 TESTALLOC_OFFSET_DATA(p) + sqlite3OsAllocationSize(p) - TESTALLOC_OVERHEAD \
7581 #define TESTALLOC_OFFSET_LINENUMBER(p) ( \
7582 TESTALLOC_OFFSET_GUARD2(p) + sizeof(u32) * TESTALLOC_NGUARD \
7584 #define TESTALLOC_OFFSET_FILENAME(p) ( \
7585 TESTALLOC_OFFSET_LINENUMBER(p) + sizeof(u32) \
7587 #define TESTALLOC_OFFSET_USER(p) ( \
7588 TESTALLOC_OFFSET_FILENAME(p) + TESTALLOC_FILESIZE \
7590 #define TESTALLOC_OFFSET_STACK(p) ( \
7591 TESTALLOC_OFFSET_USER(p) + TESTALLOC_USERSIZE + 8 - \
7592 (TESTALLOC_OFFSET_USER(p) % 8) \
7595 #define TESTALLOC_OVERHEAD ( \
7596 sizeof(void *)*2 + /* pPrev and pNext pointers */ \
7597 TESTALLOC_NGUARD*sizeof(u32)*2 + /* Guard words */ \
7598 sizeof(u32) + TESTALLOC_FILESIZE + /* File and line number */ \
7599 TESTALLOC_USERSIZE + /* User string */ \
7600 TESTALLOC_STACKSIZE /* backtrace() stack */ \
7605 ** For keeping track of the number of mallocs and frees. This
7606 ** is used to check for memory leaks. The iMallocFail and iMallocReset
7607 ** values are used to simulate malloc() failures during testing in
7608 ** order to verify that the library correctly handles an out-of-memory
7609 ** condition.
7611 int sqlite3_nMalloc; /* Number of sqliteMalloc() calls */
7612 int sqlite3_nFree; /* Number of sqliteFree() calls */
7613 int sqlite3_memUsed; /* TODO Total memory obtained from malloc */
7614 int sqlite3_memMax; /* TODO Mem usage high-water mark */
7615 int sqlite3_iMallocFail; /* Fail sqliteMalloc() after this many calls */
7616 int sqlite3_iMallocReset = -1; /* When iMallocFail reaches 0, set to this */
7618 void *sqlite3_pFirst = 0; /* Pointer to linked list of allocations */
7619 int sqlite3_nMaxAlloc = 0; /* High water mark of ThreadData.nAlloc */
7620 int sqlite3_mallocDisallowed = 0; /* assert() in sqlite3Malloc() if set */
7621 int sqlite3_isFail = 0; /* True if all malloc calls should fail */
7622 const char *sqlite3_zFile = 0; /* Filename to associate debug info with */
7623 int sqlite3_iLine = 0; /* Line number for debug info */
7624 int sqlite3_mallocfail_trace = 0; /* Print a msg on malloc fail if true */
7627 ** Check for a simulated memory allocation failure. Return true if
7628 ** the failure should be simulated. Return false to proceed as normal.
7630 static int sqlite3TestMallocFail(){
7631 if( sqlite3_isFail ){
7632 return 1;
7634 if( sqlite3_iMallocFail>=0 ){
7635 sqlite3_iMallocFail--;
7636 if( sqlite3_iMallocFail==0 ){
7637 sqlite3_iMallocFail = sqlite3_iMallocReset;
7638 sqlite3_isFail = 1;
7639 if( sqlite3_mallocfail_trace ){
7640 sqlite3DebugPrintf("###_malloc_fails_###\n");
7642 return 1;
7645 return 0;
7649 ** The argument is a pointer returned by sqlite3OsMalloc() or xRealloc().
7650 ** assert() that the first and last (TESTALLOC_NGUARD*4) bytes are set to the
7651 ** values set by the applyGuards() function.
7653 static void checkGuards(u32 *p)
7655 int i;
7656 char *zAlloc = (char *)p;
7657 char *z;
7659 /* First set of guard words */
7660 z = &zAlloc[TESTALLOC_OFFSET_GUARD1(p)];
7661 for(i=0; i<TESTALLOC_NGUARD; i++){
7662 assert(((u32 *)z)[i]==0xdead1122);
7665 /* Second set of guard words */
7666 z = &zAlloc[TESTALLOC_OFFSET_GUARD2(p)];
7667 for(i=0; i<TESTALLOC_NGUARD; i++){
7668 u32 guard = 0;
7669 memcpy(&guard, &z[i*sizeof(u32)], sizeof(u32));
7670 assert(guard==0xdead3344);
7675 ** The argument is a pointer returned by sqlite3OsMalloc() or Realloc(). The
7676 ** first and last (TESTALLOC_NGUARD*4) bytes are set to known values for use as
7677 ** guard-posts.
7679 static void applyGuards(u32 *p)
7681 int i;
7682 char *z;
7683 char *zAlloc = (char *)p;
7685 /* First set of guard words */
7686 z = &zAlloc[TESTALLOC_OFFSET_GUARD1(p)];
7687 for(i=0; i<TESTALLOC_NGUARD; i++){
7688 ((u32 *)z)[i] = 0xdead1122;
7691 /* Second set of guard words */
7692 z = &zAlloc[TESTALLOC_OFFSET_GUARD2(p)];
7693 for(i=0; i<TESTALLOC_NGUARD; i++){
7694 static const int guard = 0xdead3344;
7695 memcpy(&z[i*sizeof(u32)], &guard, sizeof(u32));
7698 /* Line number */
7699 z = &((char *)z)[TESTALLOC_NGUARD*sizeof(u32)]; /* Guard words */
7700 z = &zAlloc[TESTALLOC_OFFSET_LINENUMBER(p)];
7701 memcpy(z, &sqlite3_iLine, sizeof(u32));
7703 /* File name */
7704 z = &zAlloc[TESTALLOC_OFFSET_FILENAME(p)];
7705 strncpy(z, sqlite3_zFile, TESTALLOC_FILESIZE);
7706 z[TESTALLOC_FILESIZE - 1] = '\0';
7708 /* User string */
7709 z = &zAlloc[TESTALLOC_OFFSET_USER(p)];
7710 z[0] = 0;
7711 if( sqlite3_malloc_id ){
7712 strncpy(z, sqlite3_malloc_id, TESTALLOC_USERSIZE);
7713 z[TESTALLOC_USERSIZE-1] = 0;
7716 /* backtrace() stack */
7717 z = &zAlloc[TESTALLOC_OFFSET_STACK(p)];
7718 backtrace((void **)z, TESTALLOC_STACKFRAMES);
7720 /* Sanity check to make sure checkGuards() is working */
7721 checkGuards(p);
7725 ** The argument is a malloc()ed pointer as returned by the test-wrapper.
7726 ** Return a pointer to the Os level allocation.
7728 static void *getOsPointer(void *p)
7730 char *z = (char *)p;
7731 return (void *)(&z[-1 * TESTALLOC_OFFSET_DATA(p)]);
7735 #if SQLITE_MEMDEBUG>1
7737 ** The argument points to an Os level allocation. Link it into the threads list
7738 ** of allocations.
7740 static void linkAlloc(void *p){
7741 void **pp = (void **)p;
7742 pp[0] = 0;
7743 pp[1] = sqlite3_pFirst;
7744 if( sqlite3_pFirst ){
7745 ((void **)sqlite3_pFirst)[0] = p;
7747 sqlite3_pFirst = p;
7751 ** The argument points to an Os level allocation. Unlinke it from the threads
7752 ** list of allocations.
7754 static void unlinkAlloc(void *p)
7756 void **pp = (void **)p;
7757 if( p==sqlite3_pFirst ){
7758 assert(!pp[0]);
7759 assert(!pp[1] || ((void **)(pp[1]))[0]==p);
7760 sqlite3_pFirst = pp[1];
7761 if( sqlite3_pFirst ){
7762 ((void **)sqlite3_pFirst)[0] = 0;
7764 }else{
7765 void **pprev = pp[0];
7766 void **pnext = pp[1];
7767 assert(pprev);
7768 assert(pprev[1]==p);
7769 pprev[1] = (void *)pnext;
7770 if( pnext ){
7771 assert(pnext[0]==p);
7772 pnext[0] = (void *)pprev;
7778 ** Pointer p is a pointer to an OS level allocation that has just been
7779 ** realloc()ed. Set the list pointers that point to this entry to it's new
7780 ** location.
7782 static void relinkAlloc(void *p)
7784 void **pp = (void **)p;
7785 if( pp[0] ){
7786 ((void **)(pp[0]))[1] = p;
7787 }else{
7788 sqlite3_pFirst = p;
7790 if( pp[1] ){
7791 ((void **)(pp[1]))[0] = p;
7794 #else
7795 #define linkAlloc(x)
7796 #define relinkAlloc(x)
7797 #define unlinkAlloc(x)
7798 #endif
7801 ** This function sets the result of the Tcl interpreter passed as an argument
7802 ** to a list containing an entry for each currently outstanding call made to
7803 ** sqliteMalloc and friends by the current thread. Each list entry is itself a
7804 ** list, consisting of the following (in order):
7806 ** * The number of bytes allocated
7807 ** * The __FILE__ macro at the time of the sqliteMalloc() call.
7808 ** * The __LINE__ macro ...
7809 ** * The value of the sqlite3_malloc_id variable ...
7810 ** * The output of backtrace() (if available) ...
7812 ** Todo: We could have a version of this function that outputs to stdout,
7813 ** to debug memory leaks when Tcl is not available.
7815 #if defined(TCLSH) && defined(SQLITE_DEBUG) && SQLITE_MEMDEBUG>1
7816 static int sqlite3OutstandingMallocs(Tcl_Interp *interp){
7817 void *p;
7818 Tcl_Obj *pRes = Tcl_NewObj();
7819 Tcl_IncrRefCount(pRes);
7822 for(p=sqlite3_pFirst; p; p=((void **)p)[1]){
7823 Tcl_Obj *pEntry = Tcl_NewObj();
7824 Tcl_Obj *pStack = Tcl_NewObj();
7825 char *z;
7826 u32 iLine;
7827 int nBytes = sqlite3OsAllocationSize(p) - TESTALLOC_OVERHEAD;
7828 char *zAlloc = (char *)p;
7829 int i;
7831 Tcl_ListObjAppendElement(0, pEntry, Tcl_NewIntObj(nBytes));
7833 z = &zAlloc[TESTALLOC_OFFSET_FILENAME(p)];
7834 Tcl_ListObjAppendElement(0, pEntry, Tcl_NewStringObj(z, -1));
7836 z = &zAlloc[TESTALLOC_OFFSET_LINENUMBER(p)];
7837 memcpy(&iLine, z, sizeof(u32));
7838 Tcl_ListObjAppendElement(0, pEntry, Tcl_NewIntObj(iLine));
7840 z = &zAlloc[TESTALLOC_OFFSET_USER(p)];
7841 Tcl_ListObjAppendElement(0, pEntry, Tcl_NewStringObj(z, -1));
7843 z = &zAlloc[TESTALLOC_OFFSET_STACK(p)];
7844 for(i=0; i<TESTALLOC_STACKFRAMES; i++){
7845 char zHex[128];
7846 sqlite3_snprintf(sizeof(zHex), zHex, "%p", ((void **)z)[i]);
7847 Tcl_ListObjAppendElement(0, pStack, Tcl_NewStringObj(zHex, -1));
7850 Tcl_ListObjAppendElement(0, pEntry, pStack);
7851 Tcl_ListObjAppendElement(0, pRes, pEntry);
7854 Tcl_ResetResult(interp);
7855 Tcl_SetObjResult(interp, pRes);
7856 Tcl_DecrRefCount(pRes);
7857 return TCL_OK;
7859 #endif
7862 ** This is the test layer's wrapper around sqlite3OsMalloc().
7864 static void * OSMALLOC(int n){
7865 sqlite3OsEnterMutex();
7866 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
7867 sqlite3_nMaxAlloc =
7868 MAX(sqlite3_nMaxAlloc, sqlite3ThreadDataReadOnly()->nAlloc);
7869 #endif
7870 assert( !sqlite3_mallocDisallowed );
7871 if( !sqlite3TestMallocFail() ){
7872 u32 *p;
7873 p = (u32 *)sqlite3OsMalloc(n + TESTALLOC_OVERHEAD);
7874 assert(p);
7875 sqlite3_nMalloc++;
7876 applyGuards(p);
7877 linkAlloc(p);
7878 sqlite3OsLeaveMutex();
7879 return (void *)(&p[TESTALLOC_NGUARD + 2*sizeof(void *)/sizeof(u32)]);
7881 sqlite3OsLeaveMutex();
7882 return 0;
7885 static int OSSIZEOF(void *p){
7886 if( p ){
7887 u32 *pOs = (u32 *)getOsPointer(p);
7888 return sqlite3OsAllocationSize(pOs) - TESTALLOC_OVERHEAD;
7890 return 0;
7894 ** This is the test layer's wrapper around sqlite3OsFree(). The argument is a
7895 ** pointer to the space allocated for the application to use.
7897 static void OSFREE(void *pFree){
7898 u32 *p; /* Pointer to the OS-layer allocation */
7899 sqlite3OsEnterMutex();
7900 p = (u32 *)getOsPointer(pFree);
7901 checkGuards(p);
7902 unlinkAlloc(p);
7903 memset(pFree, 0x55, OSSIZEOF(pFree));
7904 sqlite3OsFree(p);
7905 sqlite3_nFree++;
7906 sqlite3OsLeaveMutex();
7910 ** This is the test layer's wrapper around sqlite3OsRealloc().
7912 static void * OSREALLOC(void *pRealloc, int n){
7913 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
7914 sqlite3_nMaxAlloc =
7915 MAX(sqlite3_nMaxAlloc, sqlite3ThreadDataReadOnly()->nAlloc);
7916 #endif
7917 assert( !sqlite3_mallocDisallowed );
7918 if( !sqlite3TestMallocFail() ){
7919 u32 *p = (u32 *)getOsPointer(pRealloc);
7920 checkGuards(p);
7921 p = sqlite3OsRealloc(p, n + TESTALLOC_OVERHEAD);
7922 applyGuards(p);
7923 relinkAlloc(p);
7924 return (void *)(&p[TESTALLOC_NGUARD + 2*sizeof(void *)/sizeof(u32)]);
7926 return 0;
7929 static void OSMALLOC_FAILED(){
7930 sqlite3_isFail = 0;
7933 #else
7934 /* Define macros to call the sqlite3OsXXX interface directly if
7935 ** the SQLITE_MEMDEBUG macro is not defined.
7937 #define OSMALLOC(x) sqlite3OsMalloc(x)
7938 #define OSREALLOC(x,y) sqlite3OsRealloc(x,y)
7939 #define OSFREE(x) sqlite3OsFree(x)
7940 #define OSSIZEOF(x) sqlite3OsAllocationSize(x)
7941 #define OSMALLOC_FAILED()
7943 #endif /* SQLITE_MEMDEBUG */
7945 ** End code for memory allocation system test layer.
7946 **--------------------------------------------------------------------------*/
7949 ** This routine is called when we are about to allocate n additional bytes
7950 ** of memory. If the new allocation will put is over the soft allocation
7951 ** limit, then invoke sqlite3_release_memory() to try to release some
7952 ** memory before continuing with the allocation.
7954 ** This routine also makes sure that the thread-specific-data (TSD) has
7955 ** be allocated. If it has not and can not be allocated, then return
7956 ** false. The updateMemoryUsedCount() routine below will deallocate
7957 ** the TSD if it ought to be.
7959 ** If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, this routine is
7960 ** a no-op
7962 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
7963 static int enforceSoftLimit(int n){
7964 ThreadData *pTsd = sqlite3ThreadData();
7965 if( pTsd==0 ){
7966 return 0;
7968 assert( pTsd->nAlloc>=0 );
7969 if( n>0 && pTsd->nSoftHeapLimit>0 ){
7970 while( pTsd->nAlloc+n>pTsd->nSoftHeapLimit && sqlite3_release_memory(n) ){}
7972 return 1;
7974 #else
7975 # define enforceSoftLimit(X) 1
7976 #endif
7979 ** Update the count of total outstanding memory that is held in
7980 ** thread-specific-data (TSD). If after this update the TSD is
7981 ** no longer being used, then deallocate it.
7983 ** If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, this routine is
7984 ** a no-op
7986 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
7987 static void updateMemoryUsedCount(int n){
7988 ThreadData *pTsd = sqlite3ThreadData();
7989 if( pTsd ){
7990 pTsd->nAlloc += n;
7991 assert( pTsd->nAlloc>=0 );
7992 if( pTsd->nAlloc==0 && pTsd->nSoftHeapLimit==0 ){
7993 sqlite3ReleaseThreadData();
7997 #else
7998 #define updateMemoryUsedCount(x) /* no-op */
7999 #endif
8002 ** Allocate and return N bytes of uninitialised memory by calling
8003 ** sqlite3OsMalloc(). If the Malloc() call fails, attempt to free memory
8004 ** by calling sqlite3_release_memory().
8006 static void *sqlite3MallocRaw(int n, int doMemManage){
8007 void *p = 0;
8008 if( n>0 && !sqlite3MallocFailed() && (!doMemManage || enforceSoftLimit(n)) ){
8009 while( (p = OSMALLOC(n))==0 && sqlite3_release_memory(n) ){}
8010 if( !p ){
8011 sqlite3FailedMalloc();
8012 OSMALLOC_FAILED();
8013 }else if( doMemManage ){
8014 updateMemoryUsedCount(OSSIZEOF(p));
8017 return p;
8021 ** Resize the allocation at p to n bytes by calling sqlite3OsRealloc(). The
8022 ** pointer to the new allocation is returned. If the Realloc() call fails,
8023 ** attempt to free memory by calling sqlite3_release_memory().
8025 static void *sqlite3Realloc(void *p, int n){
8026 if( sqlite3MallocFailed() ){
8027 return 0;
8030 if( !p ){
8031 return sqlite3Malloc(n, 1);
8032 }else{
8033 void *np = 0;
8034 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8035 int origSize = OSSIZEOF(p);
8036 #endif
8037 if( enforceSoftLimit(n - origSize) ){
8038 while( (np = OSREALLOC(p, n))==0 && sqlite3_release_memory(n) ){}
8039 if( !np ){
8040 sqlite3FailedMalloc();
8041 OSMALLOC_FAILED();
8042 }else{
8043 updateMemoryUsedCount(OSSIZEOF(np) - origSize);
8046 return np;
8051 ** Free the memory pointed to by p. p must be either a NULL pointer or a
8052 ** value returned by a previous call to sqlite3Malloc() or sqlite3Realloc().
8054 static void sqlite3FreeX(void *p){
8055 if( p ){
8056 updateMemoryUsedCount(0 - OSSIZEOF(p));
8057 OSFREE(p);
8062 ** A version of sqliteMalloc() that is always a function, not a macro.
8063 ** Currently, this is used only to alloc to allocate the parser engine.
8065 static void *sqlite3MallocX(int n){
8066 return sqliteMalloc(n);
8070 ** sqlite3Malloc
8071 ** sqlite3ReallocOrFree
8073 ** These two are implemented as wrappers around sqlite3MallocRaw(),
8074 ** sqlite3Realloc() and sqlite3Free().
8076 static void *sqlite3Malloc(int n, int doMemManage){
8077 void *p = sqlite3MallocRaw(n, doMemManage);
8078 if( p ){
8079 memset(p, 0, n);
8081 return p;
8083 static void *sqlite3ReallocOrFree(void *p, int n){
8084 void *pNew;
8085 pNew = sqlite3Realloc(p, n);
8086 if( !pNew ){
8087 sqlite3FreeX(p);
8089 return pNew;
8093 ** sqlite3ThreadSafeMalloc() and sqlite3ThreadSafeFree() are used in those
8094 ** rare scenarios where sqlite may allocate memory in one thread and free
8095 ** it in another. They are exactly the same as sqlite3Malloc() and
8096 ** sqlite3Free() except that:
8098 ** * The allocated memory is not included in any calculations with
8099 ** respect to the soft-heap-limit, and
8101 ** * sqlite3ThreadSafeMalloc() must be matched with ThreadSafeFree(),
8102 ** not sqlite3Free(). Calling sqlite3Free() on memory obtained from
8103 ** ThreadSafeMalloc() will cause an error somewhere down the line.
8105 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8106 static void *sqlite3ThreadSafeMalloc(int n){
8107 (void)ENTER_MALLOC;
8108 return sqlite3Malloc(n, 0);
8110 static void sqlite3ThreadSafeFree(void *p){
8111 (void)ENTER_MALLOC;
8112 if( p ){
8113 OSFREE(p);
8116 #endif
8120 ** Return the number of bytes allocated at location p. p must be either
8121 ** a NULL pointer (in which case 0 is returned) or a pointer returned by
8122 ** sqlite3Malloc(), sqlite3Realloc() or sqlite3ReallocOrFree().
8124 ** The number of bytes allocated does not include any overhead inserted by
8125 ** any malloc() wrapper functions that may be called. So the value returned
8126 ** is the number of bytes that were available to SQLite using pointer p,
8127 ** regardless of how much memory was actually allocated.
8129 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8130 static int sqlite3AllocSize(void *p){
8131 return OSSIZEOF(p);
8133 #endif
8136 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
8137 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
8138 ** is because when memory debugging is turned on, these two functions are
8139 ** called via macros that record the current file and line number in the
8140 ** ThreadData structure.
8142 static char *sqlite3StrDup(const char *z){
8143 char *zNew;
8144 int n;
8145 if( z==0 ) return 0;
8146 n = strlen(z)+1;
8147 zNew = sqlite3MallocRaw(n, 1);
8148 if( zNew ) memcpy(zNew, z, n);
8149 return zNew;
8151 static char *sqlite3StrNDup(const char *z, int n){
8152 char *zNew;
8153 if( z==0 ) return 0;
8154 zNew = sqlite3MallocRaw(n+1, 1);
8155 if( zNew ){
8156 memcpy(zNew, z, n);
8157 zNew[n] = 0;
8159 return zNew;
8163 ** Create a string from the 2nd and subsequent arguments (up to the
8164 ** first NULL argument), store the string in memory obtained from
8165 ** sqliteMalloc() and make the pointer indicated by the 1st argument
8166 ** point to that string. The 1st argument must either be NULL or
8167 ** point to memory obtained from sqliteMalloc().
8169 static void sqlite3SetString(char **pz, ...){
8170 va_list ap;
8171 int nByte;
8172 const char *z;
8173 char *zResult;
8175 assert( pz!=0 );
8176 nByte = 1;
8177 va_start(ap, pz);
8178 while( (z = va_arg(ap, const char*))!=0 ){
8179 nByte += strlen(z);
8181 va_end(ap);
8182 sqliteFree(*pz);
8183 *pz = zResult = sqliteMallocRaw( nByte );
8184 if( zResult==0 ){
8185 return;
8187 *zResult = 0;
8188 va_start(ap, pz);
8189 while( (z = va_arg(ap, const char*))!=0 ){
8190 int n = strlen(z);
8191 memcpy(zResult, z, n);
8192 zResult += n;
8194 zResult[0] = 0;
8195 va_end(ap);
8200 ** This function must be called before exiting any API function (i.e.
8201 ** returning control to the user) that has called sqlite3Malloc or
8202 ** sqlite3Realloc.
8204 ** The returned value is normally a copy of the second argument to this
8205 ** function. However, if a malloc() failure has occured since the previous
8206 ** invocation SQLITE_NOMEM is returned instead.
8208 ** If the first argument, db, is not NULL and a malloc() error has occured,
8209 ** then the connection error-code (the value returned by sqlite3_errcode())
8210 ** is set to SQLITE_NOMEM.
8212 int sqlite3_mallocHasFailed = 0;
8213 static int sqlite3ApiExit(sqlite3* db, int rc){
8214 if( sqlite3MallocFailed() ){
8215 sqlite3_mallocHasFailed = 0;
8216 sqlite3OsLeaveMutex();
8217 sqlite3Error(db, SQLITE_NOMEM, 0);
8218 rc = SQLITE_NOMEM;
8220 return rc & (db ? db->errMask : 0xff);
8224 ** Set the "malloc has failed" condition to true for this thread.
8226 static void sqlite3FailedMalloc(){
8227 if( !sqlite3MallocFailed() ){
8228 sqlite3OsEnterMutex();
8229 assert( sqlite3_mallocHasFailed==0 );
8230 sqlite3_mallocHasFailed = 1;
8234 #ifdef SQLITE_MEMDEBUG
8236 ** This function sets a flag in the thread-specific-data structure that will
8237 ** cause an assert to fail if sqliteMalloc() or sqliteRealloc() is called.
8239 static void sqlite3MallocDisallow(){
8240 assert( sqlite3_mallocDisallowed>=0 );
8241 sqlite3_mallocDisallowed++;
8245 ** This function clears the flag set in the thread-specific-data structure set
8246 ** by sqlite3MallocDisallow().
8248 static void sqlite3MallocAllow(){
8249 assert( sqlite3_mallocDisallowed>0 );
8250 sqlite3_mallocDisallowed--;
8252 #endif
8254 /************** End of malloc.c **********************************************/
8255 /************** Begin file printf.c ******************************************/
8257 ** The "printf" code that follows dates from the 1980's. It is in
8258 ** the public domain. The original comments are included here for
8259 ** completeness. They are very out-of-date but might be useful as
8260 ** an historical reference. Most of the "enhancements" have been backed
8261 ** out so that the functionality is now the same as standard printf().
8263 **************************************************************************
8265 ** The following modules is an enhanced replacement for the "printf" subroutines
8266 ** found in the standard C library. The following enhancements are
8267 ** supported:
8269 ** + Additional functions. The standard set of "printf" functions
8270 ** includes printf, fprintf, sprintf, vprintf, vfprintf, and
8271 ** vsprintf. This module adds the following:
8273 ** * snprintf -- Works like sprintf, but has an extra argument
8274 ** which is the size of the buffer written to.
8276 ** * mprintf -- Similar to sprintf. Writes output to memory
8277 ** obtained from malloc.
8279 ** * xprintf -- Calls a function to dispose of output.
8281 ** * nprintf -- No output, but returns the number of characters
8282 ** that would have been output by printf.
8284 ** * A v- version (ex: vsnprintf) of every function is also
8285 ** supplied.
8287 ** + A few extensions to the formatting notation are supported:
8289 ** * The "=" flag (similar to "-") causes the output to be
8290 ** be centered in the appropriately sized field.
8292 ** * The %b field outputs an integer in binary notation.
8294 ** * The %c field now accepts a precision. The character output
8295 ** is repeated by the number of times the precision specifies.
8297 ** * The %' field works like %c, but takes as its character the
8298 ** next character of the format string, instead of the next
8299 ** argument. For example, printf("%.78'-") prints 78 minus
8300 ** signs, the same as printf("%.78c",'-').
8302 ** + When compiled using GCC on a SPARC, this version of printf is
8303 ** faster than the library printf for SUN OS 4.1.
8305 ** + All functions are fully reentrant.
8308 #include <math.h>
8311 ** Conversion types fall into various categories as defined by the
8312 ** following enumeration.
8314 #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
8315 #define etFLOAT 2 /* Floating point. %f */
8316 #define etEXP 3 /* Exponentional notation. %e and %E */
8317 #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
8318 #define etSIZE 5 /* Return number of characters processed so far. %n */
8319 #define etSTRING 6 /* Strings. %s */
8320 #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
8321 #define etPERCENT 8 /* Percent symbol. %% */
8322 #define etCHARX 9 /* Characters. %c */
8323 /* The rest are extensions, not normally found in printf() */
8324 #define etCHARLIT 10 /* Literal characters. %' */
8325 #define etSQLESCAPE 11 /* Strings with '\'' doubled. %q */
8326 #define etSQLESCAPE2 12 /* Strings with '\'' doubled and enclosed in '',
8327 NULL pointers replaced by SQL NULL. %Q */
8328 #define etTOKEN 13 /* a pointer to a Token structure */
8329 #define etSRCLIST 14 /* a pointer to a SrcList */
8330 #define etPOINTER 15 /* The %p conversion */
8334 ** An "etByte" is an 8-bit unsigned value.
8336 typedef unsigned char etByte;
8339 ** Each builtin conversion character (ex: the 'd' in "%d") is described
8340 ** by an instance of the following structure
8342 typedef struct et_info { /* Information about each format field */
8343 char fmttype; /* The format field code letter */
8344 etByte base; /* The base for radix conversion */
8345 etByte flags; /* One or more of FLAG_ constants below */
8346 etByte type; /* Conversion paradigm */
8347 etByte charset; /* Offset into aDigits[] of the digits string */
8348 etByte prefix; /* Offset into aPrefix[] of the prefix string */
8349 } et_info;
8352 ** Allowed values for et_info.flags
8354 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
8355 #define FLAG_INTERN 2 /* True if for internal use only */
8356 #define FLAG_STRING 4 /* Allow infinity precision */
8360 ** The following table is searched linearly, so it is good to put the
8361 ** most frequently used conversion types first.
8363 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
8364 static const char aPrefix[] = "-x0\000X0";
8365 static const et_info fmtinfo[] = {
8366 { 'd', 10, 1, etRADIX, 0, 0 },
8367 { 's', 0, 4, etSTRING, 0, 0 },
8368 { 'g', 0, 1, etGENERIC, 30, 0 },
8369 { 'z', 0, 6, etDYNSTRING, 0, 0 },
8370 { 'q', 0, 4, etSQLESCAPE, 0, 0 },
8371 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
8372 { 'c', 0, 0, etCHARX, 0, 0 },
8373 { 'o', 8, 0, etRADIX, 0, 2 },
8374 { 'u', 10, 0, etRADIX, 0, 0 },
8375 { 'x', 16, 0, etRADIX, 16, 1 },
8376 { 'X', 16, 0, etRADIX, 0, 4 },
8377 #ifndef SQLITE_OMIT_FLOATING_POINT
8378 { 'f', 0, 1, etFLOAT, 0, 0 },
8379 { 'e', 0, 1, etEXP, 30, 0 },
8380 { 'E', 0, 1, etEXP, 14, 0 },
8381 { 'G', 0, 1, etGENERIC, 14, 0 },
8382 #endif
8383 { 'i', 10, 1, etRADIX, 0, 0 },
8384 { 'n', 0, 0, etSIZE, 0, 0 },
8385 { '%', 0, 0, etPERCENT, 0, 0 },
8386 { 'p', 16, 0, etPOINTER, 0, 1 },
8387 { 'T', 0, 2, etTOKEN, 0, 0 },
8388 { 'S', 0, 2, etSRCLIST, 0, 0 },
8390 #define etNINFO (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
8393 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
8394 ** conversions will work.
8396 #ifndef SQLITE_OMIT_FLOATING_POINT
8398 ** "*val" is a double such that 0.1 <= *val < 10.0
8399 ** Return the ascii code for the leading digit of *val, then
8400 ** multiply "*val" by 10.0 to renormalize.
8402 ** Example:
8403 ** input: *val = 3.14159
8404 ** output: *val = 1.4159 function return = '3'
8406 ** The counter *cnt is incremented each time. After counter exceeds
8407 ** 16 (the number of significant digits in a 64-bit float) '0' is
8408 ** always returned.
8410 static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
8411 int digit;
8412 LONGDOUBLE_TYPE d;
8413 if( (*cnt)++ >= 16 ) return '0';
8414 digit = (int)*val;
8415 d = digit;
8416 digit += '0';
8417 *val = (*val - d)*10.0;
8418 return digit;
8420 #endif /* SQLITE_OMIT_FLOATING_POINT */
8423 ** On machines with a small stack size, you can redefine the
8424 ** SQLITE_PRINT_BUF_SIZE to be less than 350. But beware - for
8425 ** smaller values some %f conversions may go into an infinite loop.
8427 #ifndef SQLITE_PRINT_BUF_SIZE
8428 # define SQLITE_PRINT_BUF_SIZE 350
8429 #endif
8430 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
8433 ** The root program. All variations call this core.
8435 ** INPUTS:
8436 ** func This is a pointer to a function taking three arguments
8437 ** 1. A pointer to anything. Same as the "arg" parameter.
8438 ** 2. A pointer to the list of characters to be output
8439 ** (Note, this list is NOT null terminated.)
8440 ** 3. An integer number of characters to be output.
8441 ** (Note: This number might be zero.)
8443 ** arg This is the pointer to anything which will be passed as the
8444 ** first argument to "func". Use it for whatever you like.
8446 ** fmt This is the format string, as in the usual print.
8448 ** ap This is a pointer to a list of arguments. Same as in
8449 ** vfprint.
8451 ** OUTPUTS:
8452 ** The return value is the total number of characters sent to
8453 ** the function "func". Returns -1 on a error.
8455 ** Note that the order in which automatic variables are declared below
8456 ** seems to make a big difference in determining how fast this beast
8457 ** will run.
8459 static int vxprintf(
8460 void (*func)(void*,const char*,int), /* Consumer of text */
8461 void *arg, /* First argument to the consumer */
8462 int useExtended, /* Allow extended %-conversions */
8463 const char *fmt, /* Format string */
8464 va_list ap /* arguments */
8466 int c; /* Next character in the format string */
8467 char *bufpt; /* Pointer to the conversion buffer */
8468 int precision; /* Precision of the current field */
8469 int length; /* Length of the field */
8470 int idx; /* A general purpose loop counter */
8471 int count; /* Total number of characters output */
8472 int width; /* Width of the current field */
8473 etByte flag_leftjustify; /* True if "-" flag is present */
8474 etByte flag_plussign; /* True if "+" flag is present */
8475 etByte flag_blanksign; /* True if " " flag is present */
8476 etByte flag_alternateform; /* True if "#" flag is present */
8477 etByte flag_altform2; /* True if "!" flag is present */
8478 etByte flag_zeropad; /* True if field width constant starts with zero */
8479 etByte flag_long; /* True if "l" flag is present */
8480 etByte flag_longlong; /* True if the "ll" flag is present */
8481 etByte done; /* Loop termination flag */
8482 sqlite_uint64 longvalue; /* Value for integer types */
8483 LONGDOUBLE_TYPE realvalue; /* Value for real types */
8484 const et_info *infop; /* Pointer to the appropriate info structure */
8485 char buf[etBUFSIZE]; /* Conversion buffer */
8486 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
8487 etByte errorflag = 0; /* True if an error is encountered */
8488 etByte xtype; /* Conversion paradigm */
8489 char *zExtra; /* Extra memory used for etTCLESCAPE conversions */
8490 static const char spaces[] =
8491 " ";
8492 #define etSPACESIZE (sizeof(spaces)-1)
8493 #ifndef SQLITE_OMIT_FLOATING_POINT
8494 int exp, e2; /* exponent of real numbers */
8495 double rounder; /* Used for rounding floating point values */
8496 etByte flag_dp; /* True if decimal point should be shown */
8497 etByte flag_rtz; /* True if trailing zeros should be removed */
8498 etByte flag_exp; /* True to force display of the exponent */
8499 int nsd; /* Number of significant digits returned */
8500 #endif
8502 func(arg,"",0);
8503 count = length = 0;
8504 bufpt = 0;
8505 for(; (c=(*fmt))!=0; ++fmt){
8506 if( c!='%' ){
8507 int amt;
8508 bufpt = (char *)fmt;
8509 amt = 1;
8510 while( (c=(*++fmt))!='%' && c!=0 ) amt++;
8511 (*func)(arg,bufpt,amt);
8512 count += amt;
8513 if( c==0 ) break;
8515 if( (c=(*++fmt))==0 ){
8516 errorflag = 1;
8517 (*func)(arg,"%",1);
8518 count++;
8519 break;
8521 /* Find out what flags are present */
8522 flag_leftjustify = flag_plussign = flag_blanksign =
8523 flag_alternateform = flag_altform2 = flag_zeropad = 0;
8524 done = 0;
8526 switch( c ){
8527 case '-': flag_leftjustify = 1; break;
8528 case '+': flag_plussign = 1; break;
8529 case ' ': flag_blanksign = 1; break;
8530 case '#': flag_alternateform = 1; break;
8531 case '!': flag_altform2 = 1; break;
8532 case '0': flag_zeropad = 1; break;
8533 default: done = 1; break;
8535 }while( !done && (c=(*++fmt))!=0 );
8536 /* Get the field width */
8537 width = 0;
8538 if( c=='*' ){
8539 width = va_arg(ap,int);
8540 if( width<0 ){
8541 flag_leftjustify = 1;
8542 width = -width;
8544 c = *++fmt;
8545 }else{
8546 while( c>='0' && c<='9' ){
8547 width = width*10 + c - '0';
8548 c = *++fmt;
8551 if( width > etBUFSIZE-10 ){
8552 width = etBUFSIZE-10;
8554 /* Get the precision */
8555 if( c=='.' ){
8556 precision = 0;
8557 c = *++fmt;
8558 if( c=='*' ){
8559 precision = va_arg(ap,int);
8560 if( precision<0 ) precision = -precision;
8561 c = *++fmt;
8562 }else{
8563 while( c>='0' && c<='9' ){
8564 precision = precision*10 + c - '0';
8565 c = *++fmt;
8568 }else{
8569 precision = -1;
8571 /* Get the conversion type modifier */
8572 if( c=='l' ){
8573 flag_long = 1;
8574 c = *++fmt;
8575 if( c=='l' ){
8576 flag_longlong = 1;
8577 c = *++fmt;
8578 }else{
8579 flag_longlong = 0;
8581 }else{
8582 flag_long = flag_longlong = 0;
8584 /* Fetch the info entry for the field */
8585 infop = 0;
8586 for(idx=0; idx<etNINFO; idx++){
8587 if( c==fmtinfo[idx].fmttype ){
8588 infop = &fmtinfo[idx];
8589 if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
8590 xtype = infop->type;
8591 }else{
8592 return -1;
8594 break;
8597 zExtra = 0;
8598 if( infop==0 ){
8599 return -1;
8603 /* Limit the precision to prevent overflowing buf[] during conversion */
8604 if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
8605 precision = etBUFSIZE-40;
8609 ** At this point, variables are initialized as follows:
8611 ** flag_alternateform TRUE if a '#' is present.
8612 ** flag_altform2 TRUE if a '!' is present.
8613 ** flag_plussign TRUE if a '+' is present.
8614 ** flag_leftjustify TRUE if a '-' is present or if the
8615 ** field width was negative.
8616 ** flag_zeropad TRUE if the width began with 0.
8617 ** flag_long TRUE if the letter 'l' (ell) prefixed
8618 ** the conversion character.
8619 ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
8620 ** the conversion character.
8621 ** flag_blanksign TRUE if a ' ' is present.
8622 ** width The specified field width. This is
8623 ** always non-negative. Zero is the default.
8624 ** precision The specified precision. The default
8625 ** is -1.
8626 ** xtype The class of the conversion.
8627 ** infop Pointer to the appropriate info struct.
8629 switch( xtype ){
8630 case etPOINTER:
8631 flag_longlong = sizeof(char*)==sizeof(i64);
8632 flag_long = sizeof(char*)==sizeof(long int);
8633 /* Fall through into the next case */
8634 case etRADIX:
8635 if( infop->flags & FLAG_SIGNED ){
8636 i64 v;
8637 if( flag_longlong ) v = va_arg(ap,i64);
8638 else if( flag_long ) v = va_arg(ap,long int);
8639 else v = va_arg(ap,int);
8640 if( v<0 ){
8641 longvalue = -v;
8642 prefix = '-';
8643 }else{
8644 longvalue = v;
8645 if( flag_plussign ) prefix = '+';
8646 else if( flag_blanksign ) prefix = ' ';
8647 else prefix = 0;
8649 }else{
8650 if( flag_longlong ) longvalue = va_arg(ap,u64);
8651 else if( flag_long ) longvalue = va_arg(ap,unsigned long int);
8652 else longvalue = va_arg(ap,unsigned int);
8653 prefix = 0;
8655 if( longvalue==0 ) flag_alternateform = 0;
8656 if( flag_zeropad && precision<width-(prefix!=0) ){
8657 precision = width-(prefix!=0);
8659 bufpt = &buf[etBUFSIZE-1];
8661 register const char *cset; /* Use registers for speed */
8662 register int base;
8663 cset = &aDigits[infop->charset];
8664 base = infop->base;
8665 do{ /* Convert to ascii */
8666 *(--bufpt) = cset[longvalue%base];
8667 longvalue = longvalue/base;
8668 }while( longvalue>0 );
8670 length = &buf[etBUFSIZE-1]-bufpt;
8671 for(idx=precision-length; idx>0; idx--){
8672 *(--bufpt) = '0'; /* Zero pad */
8674 if( prefix ) *(--bufpt) = prefix; /* Add sign */
8675 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
8676 const char *pre;
8677 char x;
8678 pre = &aPrefix[infop->prefix];
8679 if( *bufpt!=pre[0] ){
8680 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
8683 length = &buf[etBUFSIZE-1]-bufpt;
8684 break;
8685 case etFLOAT:
8686 case etEXP:
8687 case etGENERIC:
8688 realvalue = va_arg(ap,double);
8689 #ifndef SQLITE_OMIT_FLOATING_POINT
8690 if( precision<0 ) precision = 6; /* Set default precision */
8691 if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
8692 if( realvalue<0.0 ){
8693 realvalue = -realvalue;
8694 prefix = '-';
8695 }else{
8696 if( flag_plussign ) prefix = '+';
8697 else if( flag_blanksign ) prefix = ' ';
8698 else prefix = 0;
8700 if( xtype==etGENERIC && precision>0 ) precision--;
8701 #if 0
8702 /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
8703 for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
8704 #else
8705 /* It makes more sense to use 0.5 */
8706 for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
8707 #endif
8708 if( xtype==etFLOAT ) realvalue += rounder;
8709 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
8710 exp = 0;
8711 if( isnan(realvalue) ){
8712 bufpt = "NaN";
8713 length = 3;
8714 break;
8716 if( realvalue>0.0 ){
8717 while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
8718 while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
8719 while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
8720 while( realvalue<1e-8 && exp>=-350 ){ realvalue *= 1e8; exp-=8; }
8721 while( realvalue<1.0 && exp>=-350 ){ realvalue *= 10.0; exp--; }
8722 if( exp>350 || exp<-350 ){
8723 if( prefix=='-' ){
8724 bufpt = "-Inf";
8725 }else if( prefix=='+' ){
8726 bufpt = "+Inf";
8727 }else{
8728 bufpt = "Inf";
8730 length = strlen(bufpt);
8731 break;
8734 bufpt = buf;
8736 ** If the field type is etGENERIC, then convert to either etEXP
8737 ** or etFLOAT, as appropriate.
8739 flag_exp = xtype==etEXP;
8740 if( xtype!=etFLOAT ){
8741 realvalue += rounder;
8742 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
8744 if( xtype==etGENERIC ){
8745 flag_rtz = !flag_alternateform;
8746 if( exp<-4 || exp>precision ){
8747 xtype = etEXP;
8748 }else{
8749 precision = precision - exp;
8750 xtype = etFLOAT;
8752 }else{
8753 flag_rtz = 0;
8755 if( xtype==etEXP ){
8756 e2 = 0;
8757 }else{
8758 e2 = exp;
8760 nsd = 0;
8761 flag_dp = (precision>0) | flag_alternateform | flag_altform2;
8762 /* The sign in front of the number */
8763 if( prefix ){
8764 *(bufpt++) = prefix;
8766 /* Digits prior to the decimal point */
8767 if( e2<0 ){
8768 *(bufpt++) = '0';
8769 }else{
8770 for(; e2>=0; e2--){
8771 *(bufpt++) = et_getdigit(&realvalue,&nsd);
8774 /* The decimal point */
8775 if( flag_dp ){
8776 *(bufpt++) = '.';
8778 /* "0" digits after the decimal point but before the first
8779 ** significant digit of the number */
8780 for(e2++; e2<0 && precision>0; precision--, e2++){
8781 *(bufpt++) = '0';
8783 /* Significant digits after the decimal point */
8784 while( (precision--)>0 ){
8785 *(bufpt++) = et_getdigit(&realvalue,&nsd);
8787 /* Remove trailing zeros and the "." if no digits follow the "." */
8788 if( flag_rtz && flag_dp ){
8789 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
8790 assert( bufpt>buf );
8791 if( bufpt[-1]=='.' ){
8792 if( flag_altform2 ){
8793 *(bufpt++) = '0';
8794 }else{
8795 *(--bufpt) = 0;
8799 /* Add the "eNNN" suffix */
8800 if( flag_exp || (xtype==etEXP && exp) ){
8801 *(bufpt++) = aDigits[infop->charset];
8802 if( exp<0 ){
8803 *(bufpt++) = '-'; exp = -exp;
8804 }else{
8805 *(bufpt++) = '+';
8807 if( exp>=100 ){
8808 *(bufpt++) = (exp/100)+'0'; /* 100's digit */
8809 exp %= 100;
8811 *(bufpt++) = exp/10+'0'; /* 10's digit */
8812 *(bufpt++) = exp%10+'0'; /* 1's digit */
8814 *bufpt = 0;
8816 /* The converted number is in buf[] and zero terminated. Output it.
8817 ** Note that the number is in the usual order, not reversed as with
8818 ** integer conversions. */
8819 length = bufpt-buf;
8820 bufpt = buf;
8822 /* Special case: Add leading zeros if the flag_zeropad flag is
8823 ** set and we are not left justified */
8824 if( flag_zeropad && !flag_leftjustify && length < width){
8825 int i;
8826 int nPad = width - length;
8827 for(i=width; i>=nPad; i--){
8828 bufpt[i] = bufpt[i-nPad];
8830 i = prefix!=0;
8831 while( nPad-- ) bufpt[i++] = '0';
8832 length = width;
8834 #endif
8835 break;
8836 case etSIZE:
8837 *(va_arg(ap,int*)) = count;
8838 length = width = 0;
8839 break;
8840 case etPERCENT:
8841 buf[0] = '%';
8842 bufpt = buf;
8843 length = 1;
8844 break;
8845 case etCHARLIT:
8846 case etCHARX:
8847 c = buf[0] = (xtype==etCHARX ? va_arg(ap,int) : *++fmt);
8848 if( precision>=0 ){
8849 for(idx=1; idx<precision; idx++) buf[idx] = c;
8850 length = precision;
8851 }else{
8852 length =1;
8854 bufpt = buf;
8855 break;
8856 case etSTRING:
8857 case etDYNSTRING:
8858 bufpt = va_arg(ap,char*);
8859 if( bufpt==0 ){
8860 bufpt = "";
8861 }else if( xtype==etDYNSTRING ){
8862 zExtra = bufpt;
8864 length = strlen(bufpt);
8865 if( precision>=0 && precision<length ) length = precision;
8866 break;
8867 case etSQLESCAPE:
8868 case etSQLESCAPE2: {
8869 int i, j, n, ch, isnull;
8870 int needQuote;
8871 char *escarg = va_arg(ap,char*);
8872 isnull = escarg==0;
8873 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
8874 for(i=n=0; (ch=escarg[i])!=0; i++){
8875 if( ch=='\'' ) n++;
8877 needQuote = !isnull && xtype==etSQLESCAPE2;
8878 n += i + 1 + needQuote*2;
8879 if( n>etBUFSIZE ){
8880 bufpt = zExtra = sqliteMalloc( n );
8881 if( bufpt==0 ) return -1;
8882 }else{
8883 bufpt = buf;
8885 j = 0;
8886 if( needQuote ) bufpt[j++] = '\'';
8887 for(i=0; (ch=escarg[i])!=0; i++){
8888 bufpt[j++] = ch;
8889 if( ch=='\'' ) bufpt[j++] = ch;
8891 if( needQuote ) bufpt[j++] = '\'';
8892 bufpt[j] = 0;
8893 length = j;
8894 /* The precision is ignored on %q and %Q */
8895 /* if( precision>=0 && precision<length ) length = precision; */
8896 break;
8898 case etTOKEN: {
8899 Token *pToken = va_arg(ap, Token*);
8900 if( pToken && pToken->z ){
8901 (*func)(arg, (char*)pToken->z, pToken->n);
8903 length = width = 0;
8904 break;
8906 case etSRCLIST: {
8907 SrcList *pSrc = va_arg(ap, SrcList*);
8908 int k = va_arg(ap, int);
8909 struct SrcList_item *pItem = &pSrc->a[k];
8910 assert( k>=0 && k<pSrc->nSrc );
8911 if( pItem->zDatabase && pItem->zDatabase[0] ){
8912 (*func)(arg, pItem->zDatabase, strlen(pItem->zDatabase));
8913 (*func)(arg, ".", 1);
8915 (*func)(arg, pItem->zName, strlen(pItem->zName));
8916 length = width = 0;
8917 break;
8919 }/* End switch over the format type */
8921 ** The text of the conversion is pointed to by "bufpt" and is
8922 ** "length" characters long. The field width is "width". Do
8923 ** the output.
8925 if( !flag_leftjustify ){
8926 register int nspace;
8927 nspace = width-length;
8928 if( nspace>0 ){
8929 count += nspace;
8930 while( nspace>=etSPACESIZE ){
8931 (*func)(arg,spaces,etSPACESIZE);
8932 nspace -= etSPACESIZE;
8934 if( nspace>0 ) (*func)(arg,spaces,nspace);
8937 if( length>0 ){
8938 (*func)(arg,bufpt,length);
8939 count += length;
8941 if( flag_leftjustify ){
8942 register int nspace;
8943 nspace = width-length;
8944 if( nspace>0 ){
8945 count += nspace;
8946 while( nspace>=etSPACESIZE ){
8947 (*func)(arg,spaces,etSPACESIZE);
8948 nspace -= etSPACESIZE;
8950 if( nspace>0 ) (*func)(arg,spaces,nspace);
8953 if( zExtra ){
8954 sqliteFree(zExtra);
8956 }/* End for loop over the format string */
8957 return errorflag ? -1 : count;
8958 } /* End of function */
8961 /* This structure is used to store state information about the
8962 ** write to memory that is currently in progress.
8964 struct sgMprintf {
8965 char *zBase; /* A base allocation */
8966 char *zText; /* The string collected so far */
8967 int nChar; /* Length of the string so far */
8968 int nTotal; /* Output size if unconstrained */
8969 int nAlloc; /* Amount of space allocated in zText */
8970 void *(*xRealloc)(void*,int); /* Function used to realloc memory */
8974 ** This function implements the callback from vxprintf.
8976 ** This routine add nNewChar characters of text in zNewText to
8977 ** the sgMprintf structure pointed to by "arg".
8979 static void mout(void *arg, const char *zNewText, int nNewChar){
8980 struct sgMprintf *pM = (struct sgMprintf*)arg;
8981 pM->nTotal += nNewChar;
8982 if( pM->nChar + nNewChar + 1 > pM->nAlloc ){
8983 if( pM->xRealloc==0 ){
8984 nNewChar = pM->nAlloc - pM->nChar - 1;
8985 }else{
8986 int nAlloc = pM->nChar + nNewChar*2 + 1;
8987 if( pM->zText==pM->zBase ){
8988 pM->zText = pM->xRealloc(0, nAlloc);
8989 if( pM->zText && pM->nChar ){
8990 memcpy(pM->zText, pM->zBase, pM->nChar);
8992 }else{
8993 char *zNew;
8994 zNew = pM->xRealloc(pM->zText, nAlloc);
8995 if( zNew ){
8996 pM->zText = zNew;
8997 }else{
8998 return;
9001 pM->nAlloc = nAlloc;
9004 if( pM->zText ){
9005 if( nNewChar>0 ){
9006 memcpy(&pM->zText[pM->nChar], zNewText, nNewChar);
9007 pM->nChar += nNewChar;
9009 pM->zText[pM->nChar] = 0;
9014 ** This routine is a wrapper around xprintf() that invokes mout() as
9015 ** the consumer.
9017 static char *base_vprintf(
9018 void *(*xRealloc)(void*,int), /* Routine to realloc memory. May be NULL */
9019 int useInternal, /* Use internal %-conversions if true */
9020 char *zInitBuf, /* Initially write here, before mallocing */
9021 int nInitBuf, /* Size of zInitBuf[] */
9022 const char *zFormat, /* format string */
9023 va_list ap /* arguments */
9025 struct sgMprintf sM;
9026 sM.zBase = sM.zText = zInitBuf;
9027 sM.nChar = sM.nTotal = 0;
9028 sM.nAlloc = nInitBuf;
9029 sM.xRealloc = xRealloc;
9030 vxprintf(mout, &sM, useInternal, zFormat, ap);
9031 if( xRealloc ){
9032 if( sM.zText==sM.zBase ){
9033 sM.zText = xRealloc(0, sM.nChar+1);
9034 if( sM.zText ){
9035 memcpy(sM.zText, sM.zBase, sM.nChar+1);
9037 }else if( sM.nAlloc>sM.nChar+10 ){
9038 char *zNew = xRealloc(sM.zText, sM.nChar+1);
9039 if( zNew ){
9040 sM.zText = zNew;
9044 return sM.zText;
9048 ** Realloc that is a real function, not a macro.
9050 static void *printf_realloc(void *old, int size){
9051 return sqliteRealloc(old,size);
9055 ** Print into memory obtained from sqliteMalloc(). Use the internal
9056 ** %-conversion extensions.
9058 static char *sqlite3VMPrintf(const char *zFormat, va_list ap){
9059 char zBase[SQLITE_PRINT_BUF_SIZE];
9060 return base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
9064 ** Print into memory obtained from sqliteMalloc(). Use the internal
9065 ** %-conversion extensions.
9067 static char *sqlite3MPrintf(const char *zFormat, ...){
9068 va_list ap;
9069 char *z;
9070 char zBase[SQLITE_PRINT_BUF_SIZE];
9071 va_start(ap, zFormat);
9072 z = base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
9073 va_end(ap);
9074 return z;
9078 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
9079 ** %-conversion extensions.
9081 char *sqlite3_vmprintf(const char *zFormat, va_list ap){
9082 char zBase[SQLITE_PRINT_BUF_SIZE];
9083 return base_vprintf(sqlite3_realloc, 0, zBase, sizeof(zBase), zFormat, ap);
9087 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
9088 ** %-conversion extensions.
9090 char *sqlite3_mprintf(const char *zFormat, ...){
9091 va_list ap;
9092 char *z;
9093 va_start(ap, zFormat);
9094 z = sqlite3_vmprintf(zFormat, ap);
9095 va_end(ap);
9096 return z;
9100 ** sqlite3_snprintf() works like snprintf() except that it ignores the
9101 ** current locale settings. This is important for SQLite because we
9102 ** are not able to use a "," as the decimal point in place of "." as
9103 ** specified by some locales.
9105 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
9106 char *z;
9107 va_list ap;
9109 if( n<=0 ){
9110 return zBuf;
9112 zBuf[0] = 0;
9113 va_start(ap,zFormat);
9114 z = base_vprintf(0, 0, zBuf, n, zFormat, ap);
9115 va_end(ap);
9116 return z;
9119 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) || defined(SQLITE_MEMDEBUG)
9121 ** A version of printf() that understands %lld. Used for debugging.
9122 ** The printf() built into some versions of windows does not understand %lld
9123 ** and segfaults if you give it a long long int.
9125 static void sqlite3DebugPrintf(const char *zFormat, ...){
9126 extern int getpid(void);
9127 va_list ap;
9128 char zBuf[500];
9129 va_start(ap, zFormat);
9130 base_vprintf(0, 0, zBuf, sizeof(zBuf), zFormat, ap);
9131 va_end(ap);
9132 fprintf(stdout,"%s", zBuf);
9133 fflush(stdout);
9135 #endif
9137 /************** End of printf.c **********************************************/
9138 /************** Begin file random.c ******************************************/
9140 ** 2001 September 15
9142 ** The author disclaims copyright to this source code. In place of
9143 ** a legal notice, here is a blessing:
9145 ** May you do good and not evil.
9146 ** May you find forgiveness for yourself and forgive others.
9147 ** May you share freely, never taking more than you give.
9149 *************************************************************************
9150 ** This file contains code to implement a pseudo-random number
9151 ** generator (PRNG) for SQLite.
9153 ** Random numbers are used by some of the database backends in order
9154 ** to generate random integer keys for tables or random filenames.
9156 ** $Id: random.c,v 1.16 2007/01/05 14:38:56 drh Exp $
9161 ** Get a single 8-bit random value from the RC4 PRNG. The Mutex
9162 ** must be held while executing this routine.
9164 ** Why not just use a library random generator like lrand48() for this?
9165 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
9166 ** good source of random numbers. The lrand48() library function may
9167 ** well be good enough. But maybe not. Or maybe lrand48() has some
9168 ** subtle problems on some systems that could cause problems. It is hard
9169 ** to know. To minimize the risk of problems due to bad lrand48()
9170 ** implementations, SQLite uses this random number generator based
9171 ** on RC4, which we know works very well.
9173 ** (Later): Actually, OP_NewRowid does not depend on a good source of
9174 ** randomness any more. But we will leave this code in all the same.
9176 static int randomByte(void){
9177 unsigned char t;
9179 /* All threads share a single random number generator.
9180 ** This structure is the current state of the generator.
9182 static struct {
9183 unsigned char isInit; /* True if initialized */
9184 unsigned char i, j; /* State variables */
9185 unsigned char s[256]; /* State variables */
9186 } prng;
9188 /* Initialize the state of the random number generator once,
9189 ** the first time this routine is called. The seed value does
9190 ** not need to contain a lot of randomness since we are not
9191 ** trying to do secure encryption or anything like that...
9193 ** Nothing in this file or anywhere else in SQLite does any kind of
9194 ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
9195 ** number generator) not as an encryption device.
9197 if( !prng.isInit ){
9198 int i;
9199 char k[256];
9200 prng.j = 0;
9201 prng.i = 0;
9202 sqlite3OsRandomSeed(k);
9203 for(i=0; i<256; i++){
9204 prng.s[i] = i;
9206 for(i=0; i<256; i++){
9207 prng.j += prng.s[i] + k[i];
9208 t = prng.s[prng.j];
9209 prng.s[prng.j] = prng.s[i];
9210 prng.s[i] = t;
9212 prng.isInit = 1;
9215 /* Generate and return single random byte
9217 prng.i++;
9218 t = prng.s[prng.i];
9219 prng.j += t;
9220 prng.s[prng.i] = prng.s[prng.j];
9221 prng.s[prng.j] = t;
9222 t += prng.s[prng.i];
9223 return prng.s[t];
9227 ** Return N random bytes.
9229 static void sqlite3Randomness(int N, void *pBuf){
9230 unsigned char *zBuf = pBuf;
9231 sqlite3OsEnterMutex();
9232 while( N-- ){
9233 *(zBuf++) = randomByte();
9235 sqlite3OsLeaveMutex();
9238 /************** End of random.c **********************************************/
9239 /************** Begin file utf.c *********************************************/
9241 ** 2004 April 13
9243 ** The author disclaims copyright to this source code. In place of
9244 ** a legal notice, here is a blessing:
9246 ** May you do good and not evil.
9247 ** May you find forgiveness for yourself and forgive others.
9248 ** May you share freely, never taking more than you give.
9250 *************************************************************************
9251 ** This file contains routines used to translate between UTF-8,
9252 ** UTF-16, UTF-16BE, and UTF-16LE.
9254 ** $Id: utf.c,v 1.51 2007/05/23 16:23:09 danielk1977 Exp $
9256 ** Notes on UTF-8:
9258 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
9259 ** 0xxxxxxx 00000000 00000000 0xxxxxxx
9260 ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
9261 ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
9262 ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
9265 ** Notes on UTF-16: (with wwww+1==uuuuu)
9267 ** Word-0 Word-1 Value
9268 ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
9269 ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
9272 ** BOM or Byte Order Mark:
9273 ** 0xff 0xfe little-endian utf-16 follows
9274 ** 0xfe 0xff big-endian utf-16 follows
9277 /************** Include vdbeInt.h in the middle of utf.c *********************/
9278 /************** Begin file vdbeInt.h *****************************************/
9280 ** 2003 September 6
9282 ** The author disclaims copyright to this source code. In place of
9283 ** a legal notice, here is a blessing:
9285 ** May you do good and not evil.
9286 ** May you find forgiveness for yourself and forgive others.
9287 ** May you share freely, never taking more than you give.
9289 *************************************************************************
9290 ** This is the header file for information that is private to the
9291 ** VDBE. This information used to all be at the top of the single
9292 ** source code file "vdbe.c". When that file became too big (over
9293 ** 6000 lines long) it was split up into several smaller files and
9294 ** this header information was factored out.
9296 #ifndef _VDBEINT_H_
9297 #define _VDBEINT_H_
9300 ** intToKey() and keyToInt() used to transform the rowid. But with
9301 ** the latest versions of the design they are no-ops.
9303 #define keyToInt(X) (X)
9304 #define intToKey(X) (X)
9307 ** The makefile scans the vdbe.c source file and creates the following
9308 ** array of string constants which are the names of all VDBE opcodes. This
9309 ** array is defined in a separate source code file named opcode.c which is
9310 ** automatically generated by the makefile.
9312 extern const char *const sqlite3OpcodeNames[];
9315 ** SQL is translated into a sequence of instructions to be
9316 ** executed by a virtual machine. Each instruction is an instance
9317 ** of the following structure.
9319 typedef struct VdbeOp Op;
9322 ** Boolean values
9324 typedef unsigned char Bool;
9327 ** A cursor is a pointer into a single BTree within a database file.
9328 ** The cursor can seek to a BTree entry with a particular key, or
9329 ** loop over all entries of the Btree. You can also insert new BTree
9330 ** entries or retrieve the key or data from the entry that the cursor
9331 ** is currently pointing to.
9333 ** Every cursor that the virtual machine has open is represented by an
9334 ** instance of the following structure.
9336 ** If the Cursor.isTriggerRow flag is set it means that this cursor is
9337 ** really a single row that represents the NEW or OLD pseudo-table of
9338 ** a row trigger. The data for the row is stored in Cursor.pData and
9339 ** the rowid is in Cursor.iKey.
9341 struct Cursor {
9342 BtCursor *pCursor; /* The cursor structure of the backend */
9343 int iDb; /* Index of cursor database in db->aDb[] (or -1) */
9344 i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
9345 i64 nextRowid; /* Next rowid returned by OP_NewRowid */
9346 Bool zeroed; /* True if zeroed out and ready for reuse */
9347 Bool rowidIsValid; /* True if lastRowid is valid */
9348 Bool atFirst; /* True if pointing to first entry */
9349 Bool useRandomRowid; /* Generate new record numbers semi-randomly */
9350 Bool nullRow; /* True if pointing to a row with no data */
9351 Bool nextRowidValid; /* True if the nextRowid field is valid */
9352 Bool pseudoTable; /* This is a NEW or OLD pseudo-tables of a trigger */
9353 Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
9354 Bool isTable; /* True if a table requiring integer keys */
9355 Bool isIndex; /* True if an index containing keys only - no data */
9356 u8 bogusIncrKey; /* Something for pIncrKey to point to if pKeyInfo==0 */
9357 i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
9358 Btree *pBt; /* Separate file holding temporary table */
9359 int nData; /* Number of bytes in pData */
9360 char *pData; /* Data for a NEW or OLD pseudo-table */
9361 i64 iKey; /* Key for the NEW or OLD pseudo-table row */
9362 u8 *pIncrKey; /* Pointer to pKeyInfo->incrKey */
9363 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
9364 int nField; /* Number of fields in the header */
9365 i64 seqCount; /* Sequence counter */
9366 sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
9367 const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
9369 /* Cached information about the header for the data record that the
9370 ** cursor is currently pointing to. Only valid if cacheValid is true.
9371 ** aRow might point to (ephemeral) data for the current row, or it might
9372 ** be NULL.
9374 int cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
9375 int payloadSize; /* Total number of bytes in the record */
9376 u32 *aType; /* Type values for all entries in the record */
9377 u32 *aOffset; /* Cached offsets to the start of each columns data */
9378 u8 *aRow; /* Data for the current row, if all on one page */
9380 typedef struct Cursor Cursor;
9383 ** Number of bytes of string storage space available to each stack
9384 ** layer without having to malloc. NBFS is short for Number of Bytes
9385 ** For Strings.
9387 #define NBFS 32
9390 ** A value for Cursor.cacheValid that means the cache is always invalid.
9392 #define CACHE_STALE 0
9395 ** Internally, the vdbe manipulates nearly all SQL values as Mem
9396 ** structures. Each Mem struct may cache multiple representations (string,
9397 ** integer etc.) of the same value. A value (and therefore Mem structure)
9398 ** has the following properties:
9400 ** Each value has a manifest type. The manifest type of the value stored
9401 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
9402 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
9403 ** SQLITE_BLOB.
9405 struct Mem {
9406 union {
9407 i64 i; /* Integer value. Or FuncDef* when flags==MEM_Agg */
9408 FuncDef *pDef; /* Used only when flags==MEM_Agg */
9409 } u;
9410 double r; /* Real value */
9411 char *z; /* String or BLOB value */
9412 int n; /* Number of characters in string value, including '\0' */
9413 u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
9414 u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
9415 u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
9416 void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
9417 char zShort[NBFS]; /* Space for short strings */
9419 typedef struct Mem Mem;
9421 /* One or more of the following flags are set to indicate the validOK
9422 ** representations of the value stored in the Mem struct.
9424 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
9425 ** No other flags may be set in this case.
9427 ** If the MEM_Str flag is set then Mem.z points at a string representation.
9428 ** Usually this is encoded in the same unicode encoding as the main
9429 ** database (see below for exceptions). If the MEM_Term flag is also
9430 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
9431 ** flags may coexist with the MEM_Str flag.
9433 ** Multiple of these values can appear in Mem.flags. But only one
9434 ** at a time can appear in Mem.type.
9436 #define MEM_Null 0x0001 /* Value is NULL */
9437 #define MEM_Str 0x0002 /* Value is a string */
9438 #define MEM_Int 0x0004 /* Value is an integer */
9439 #define MEM_Real 0x0008 /* Value is a real number */
9440 #define MEM_Blob 0x0010 /* Value is a BLOB */
9442 /* Whenever Mem contains a valid string or blob representation, one of
9443 ** the following flags must be set to determine the memory management
9444 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
9445 ** string is \000 or \u0000 terminated
9447 #define MEM_Term 0x0020 /* String rep is nul terminated */
9448 #define MEM_Dyn 0x0040 /* Need to call sqliteFree() on Mem.z */
9449 #define MEM_Static 0x0080 /* Mem.z points to a static string */
9450 #define MEM_Ephem 0x0100 /* Mem.z points to an ephemeral string */
9451 #define MEM_Short 0x0200 /* Mem.z points to Mem.zShort */
9452 #define MEM_Agg 0x0400 /* Mem.z points to an agg function context */
9453 #define MEM_Zero 0x0800 /* Mem.i contains count of 0s appended to blob */
9455 #ifdef SQLITE_OMIT_INCRBLOB
9456 #undef MEM_Zero
9457 #define MEM_Zero 0x0000
9458 #endif
9461 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
9462 ** additional information about auxiliary information bound to arguments
9463 ** of the function. This is used to implement the sqlite3_get_auxdata()
9464 ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
9465 ** that can be associated with a constant argument to a function. This
9466 ** allows functions such as "regexp" to compile their constant regular
9467 ** expression argument once and reused the compiled code for multiple
9468 ** invocations.
9470 struct VdbeFunc {
9471 FuncDef *pFunc; /* The definition of the function */
9472 int nAux; /* Number of entries allocated for apAux[] */
9473 struct AuxData {
9474 void *pAux; /* Aux data for the i-th argument */
9475 void (*xDelete)(void *); /* Destructor for the aux data */
9476 } apAux[1]; /* One slot for each function argument */
9478 typedef struct VdbeFunc VdbeFunc;
9481 ** The "context" argument for a installable function. A pointer to an
9482 ** instance of this structure is the first argument to the routines used
9483 ** implement the SQL functions.
9485 ** There is a typedef for this structure in sqlite.h. So all routines,
9486 ** even the public interface to SQLite, can use a pointer to this structure.
9487 ** But this file is the only place where the internal details of this
9488 ** structure are known.
9490 ** This structure is defined inside of vdbeInt.h because it uses substructures
9491 ** (Mem) which are only defined there.
9493 struct sqlite3_context {
9494 FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
9495 VdbeFunc *pVdbeFunc; /* Auxilary data, if created. */
9496 Mem s; /* The return value is stored here */
9497 Mem *pMem; /* Memory cell used to store aggregate context */
9498 u8 isError; /* Set to true for an error */
9499 CollSeq *pColl; /* Collating sequence */
9503 ** A Set structure is used for quick testing to see if a value
9504 ** is part of a small set. Sets are used to implement code like
9505 ** this:
9506 ** x.y IN ('hi','hoo','hum')
9508 typedef struct Set Set;
9509 struct Set {
9510 Hash hash; /* A set is just a hash table */
9511 HashElem *prev; /* Previously accessed hash elemen */
9515 ** A FifoPage structure holds a single page of valves. Pages are arranged
9516 ** in a list.
9518 typedef struct FifoPage FifoPage;
9519 struct FifoPage {
9520 int nSlot; /* Number of entries aSlot[] */
9521 int iWrite; /* Push the next value into this entry in aSlot[] */
9522 int iRead; /* Read the next value from this entry in aSlot[] */
9523 FifoPage *pNext; /* Next page in the fifo */
9524 i64 aSlot[1]; /* One or more slots for rowid values */
9528 ** The Fifo structure is typedef-ed in vdbeInt.h. But the implementation
9529 ** of that structure is private to this file.
9531 ** The Fifo structure describes the entire fifo.
9533 typedef struct Fifo Fifo;
9534 struct Fifo {
9535 int nEntry; /* Total number of entries */
9536 FifoPage *pFirst; /* First page on the list */
9537 FifoPage *pLast; /* Last page on the list */
9541 ** A Context stores the last insert rowid, the last statement change count,
9542 ** and the current statement change count (i.e. changes since last statement).
9543 ** The current keylist is also stored in the context.
9544 ** Elements of Context structure type make up the ContextStack, which is
9545 ** updated by the ContextPush and ContextPop opcodes (used by triggers).
9546 ** The context is pushed before executing a trigger a popped when the
9547 ** trigger finishes.
9549 typedef struct Context Context;
9550 struct Context {
9551 i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
9552 int nChange; /* Statement changes (Vdbe.nChanges) */
9553 Fifo sFifo; /* Records that will participate in a DELETE or UPDATE */
9557 ** An instance of the virtual machine. This structure contains the complete
9558 ** state of the virtual machine.
9560 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
9561 ** is really a pointer to an instance of this structure.
9563 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
9564 ** any virtual table method invocations made by the vdbe program. It is
9565 ** set to 2 for xDestroy method calls and 1 for all other methods. This
9566 ** variable is used for two purposes: to allow xDestroy methods to execute
9567 ** "DROP TABLE" statements and to prevent some nasty side effects of
9568 ** malloc failure when SQLite is invoked recursively by a virtual table
9569 ** method function.
9571 struct Vdbe {
9572 sqlite3 *db; /* The whole database */
9573 Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
9574 int nOp; /* Number of instructions in the program */
9575 int nOpAlloc; /* Number of slots allocated for aOp[] */
9576 Op *aOp; /* Space to hold the virtual machine's program */
9577 int nLabel; /* Number of labels used */
9578 int nLabelAlloc; /* Number of slots allocated in aLabel[] */
9579 int *aLabel; /* Space to hold the labels */
9580 Mem *aStack; /* The operand stack, except string values */
9581 Mem *pTos; /* Top entry in the operand stack */
9582 Mem **apArg; /* Arguments to currently executing user function */
9583 Mem *aColName; /* Column names to return */
9584 int nCursor; /* Number of slots in apCsr[] */
9585 Cursor **apCsr; /* One element of this array for each open cursor */
9586 int nVar; /* Number of entries in aVar[] */
9587 Mem *aVar; /* Values for the OP_Variable opcode. */
9588 char **azVar; /* Name of variables */
9589 int okVar; /* True if azVar[] has been initialized */
9590 int magic; /* Magic number for sanity checking */
9591 int nMem; /* Number of memory locations currently allocated */
9592 Mem *aMem; /* The memory locations */
9593 int nCallback; /* Number of callbacks invoked so far */
9594 int cacheCtr; /* Cursor row cache generation counter */
9595 Fifo sFifo; /* A list of ROWIDs */
9596 int contextStackTop; /* Index of top element in the context stack */
9597 int contextStackDepth; /* The size of the "context" stack */
9598 Context *contextStack; /* Stack used by opcodes ContextPush & ContextPop*/
9599 int pc; /* The program counter */
9600 int rc; /* Value to return */
9601 unsigned uniqueCnt; /* Used by OP_MakeRecord when P2!=0 */
9602 int errorAction; /* Recovery action to do in case of an error */
9603 int inTempTrans; /* True if temp database is transactioned */
9604 int returnStack[100]; /* Return address stack for OP_Gosub & OP_Return */
9605 int returnDepth; /* Next unused element in returnStack[] */
9606 int nResColumn; /* Number of columns in one row of the result set */
9607 char **azResColumn; /* Values for one row of result */
9608 int popStack; /* Pop the stack this much on entry to VdbeExec() */
9609 char *zErrMsg; /* Error message written here */
9610 u8 resOnStack; /* True if there are result values on the stack */
9611 u8 explain; /* True if EXPLAIN present on SQL command */
9612 u8 changeCntOn; /* True to update the change-counter */
9613 u8 aborted; /* True if ROLLBACK in another VM causes an abort */
9614 u8 expired; /* True if the VM needs to be recompiled */
9615 u8 minWriteFileFormat; /* Minimum file format for writable database files */
9616 u8 inVtabMethod; /* See comments above */
9617 int nChange; /* Number of db changes made since last reset */
9618 i64 startTime; /* Time when query started - used for profiling */
9619 int nSql; /* Number of bytes in zSql */
9620 char *zSql; /* Text of the SQL statement that generated this */
9621 #ifdef SQLITE_DEBUG
9622 FILE *trace; /* Write an execution trace here, if not NULL */
9623 #endif
9624 #ifdef SQLITE_SSE
9625 int fetchId; /* Statement number used by sqlite3_fetch_statement */
9626 int lru; /* Counter used for LRU cache replacement */
9627 #endif
9631 ** The following are allowed values for Vdbe.magic
9633 #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
9634 #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
9635 #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
9636 #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
9639 ** Function prototypes
9641 static void sqlite3VdbeFreeCursor(Vdbe *, Cursor*);
9642 void sqliteVdbePopStack(Vdbe*,int);
9643 static int sqlite3VdbeCursorMoveto(Cursor*);
9644 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
9645 static void sqlite3VdbePrintOp(FILE*, int, Op*);
9646 #endif
9647 static int sqlite3VdbeSerialTypeLen(u32);
9648 static u32 sqlite3VdbeSerialType(Mem*, int);
9649 static int sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
9650 static int sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
9651 static void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
9653 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
9654 static int sqlite3VdbeIdxKeyCompare(Cursor*, int , const unsigned char*, int*);
9655 static int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
9656 static int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
9657 static int sqlite3VdbeRecordCompare(void*,int,const void*,int, const void*);
9658 static int sqlite3VdbeIdxRowidLen(const u8*);
9659 static int sqlite3VdbeExec(Vdbe*);
9660 static int sqlite3VdbeList(Vdbe*);
9661 static int sqlite3VdbeHalt(Vdbe*);
9662 static int sqlite3VdbeChangeEncoding(Mem *, int);
9663 static int sqlite3VdbeMemTooBig(Mem*);
9664 static int sqlite3VdbeMemCopy(Mem*, const Mem*);
9665 static void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
9666 static int sqlite3VdbeMemMove(Mem*, Mem*);
9667 static int sqlite3VdbeMemNulTerminate(Mem*);
9668 static int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
9669 static void sqlite3VdbeMemSetInt64(Mem*, i64);
9670 static void sqlite3VdbeMemSetDouble(Mem*, double);
9671 static void sqlite3VdbeMemSetNull(Mem*);
9672 static void sqlite3VdbeMemSetZeroBlob(Mem*,int);
9673 static int sqlite3VdbeMemMakeWriteable(Mem*);
9674 static int sqlite3VdbeMemDynamicify(Mem*);
9675 static int sqlite3VdbeMemStringify(Mem*, int);
9676 static i64 sqlite3VdbeIntValue(Mem*);
9677 static int sqlite3VdbeMemIntegerify(Mem*);
9678 static double sqlite3VdbeRealValue(Mem*);
9679 static void sqlite3VdbeIntegerAffinity(Mem*);
9680 static int sqlite3VdbeMemRealify(Mem*);
9681 static int sqlite3VdbeMemNumerify(Mem*);
9682 static int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
9683 static void sqlite3VdbeMemRelease(Mem *p);
9684 static int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
9685 #ifndef NDEBUG
9686 static void sqlite3VdbeMemSanity(Mem*);
9687 static int sqlite3VdbeOpcodeNoPush(u8);
9688 #endif
9689 static int sqlite3VdbeMemTranslate(Mem*, u8);
9690 #ifdef SQLITE_DEBUG
9691 static void sqlite3VdbePrintSql(Vdbe*);
9692 static void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
9693 #endif
9694 static int sqlite3VdbeMemHandleBom(Mem *pMem);
9695 static void sqlite3VdbeFifoInit(Fifo*);
9696 static int sqlite3VdbeFifoPush(Fifo*, i64);
9697 static int sqlite3VdbeFifoPop(Fifo*, i64*);
9698 static void sqlite3VdbeFifoClear(Fifo*);
9700 #ifndef SQLITE_OMIT_INCRBLOB
9701 static int sqlite3VdbeMemExpandBlob(Mem *);
9702 #else
9703 #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
9704 #endif
9706 #endif /* !defined(_VDBEINT_H_) */
9708 /************** End of vdbeInt.h *********************************************/
9709 /************** Continuing where we left off in utf.c ************************/
9712 ** The following constant value is used by the SQLITE_BIGENDIAN and
9713 ** SQLITE_LITTLEENDIAN macros.
9715 const int sqlite3one = 1;
9718 ** This lookup table is used to help decode the first byte of
9719 ** a multi-byte UTF8 character.
9721 const unsigned char sqlite3UtfTrans1[] = {
9722 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
9723 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
9724 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
9725 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
9726 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
9727 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
9728 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
9729 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
9732 #define WRITE_UTF8(zOut, c) { \
9733 if( c<0x00080 ){ \
9734 *zOut++ = (c&0xFF); \
9736 else if( c<0x00800 ){ \
9737 *zOut++ = 0xC0 + ((c>>6)&0x1F); \
9738 *zOut++ = 0x80 + (c & 0x3F); \
9740 else if( c<0x10000 ){ \
9741 *zOut++ = 0xE0 + ((c>>12)&0x0F); \
9742 *zOut++ = 0x80 + ((c>>6) & 0x3F); \
9743 *zOut++ = 0x80 + (c & 0x3F); \
9744 }else{ \
9745 *zOut++ = 0xF0 + ((c>>18) & 0x07); \
9746 *zOut++ = 0x80 + ((c>>12) & 0x3F); \
9747 *zOut++ = 0x80 + ((c>>6) & 0x3F); \
9748 *zOut++ = 0x80 + (c & 0x3F); \
9752 #define WRITE_UTF16LE(zOut, c) { \
9753 if( c<=0xFFFF ){ \
9754 *zOut++ = (c&0x00FF); \
9755 *zOut++ = ((c>>8)&0x00FF); \
9756 }else{ \
9757 *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
9758 *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03)); \
9759 *zOut++ = (c&0x00FF); \
9760 *zOut++ = (0x00DC + ((c>>8)&0x03)); \
9764 #define WRITE_UTF16BE(zOut, c) { \
9765 if( c<=0xFFFF ){ \
9766 *zOut++ = ((c>>8)&0x00FF); \
9767 *zOut++ = (c&0x00FF); \
9768 }else{ \
9769 *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03)); \
9770 *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
9771 *zOut++ = (0x00DC + ((c>>8)&0x03)); \
9772 *zOut++ = (c&0x00FF); \
9776 #define READ_UTF16LE(zIn, c){ \
9777 c = (*zIn++); \
9778 c += ((*zIn++)<<8); \
9779 if( c>=0xD800 && c<0xE000 ){ \
9780 int c2 = (*zIn++); \
9781 c2 += ((*zIn++)<<8); \
9782 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
9783 if( (c & 0xFFFF0000)==0 ) c = 0xFFFD; \
9787 #define READ_UTF16BE(zIn, c){ \
9788 c = ((*zIn++)<<8); \
9789 c += (*zIn++); \
9790 if( c>=0xD800 && c<0xE000 ){ \
9791 int c2 = ((*zIn++)<<8); \
9792 c2 += (*zIn++); \
9793 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
9794 if( (c & 0xFFFF0000)==0 ) c = 0xFFFD; \
9799 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
9800 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
9802 /* #define TRANSLATE_TRACE 1 */
9804 #ifndef SQLITE_OMIT_UTF16
9806 ** This routine transforms the internal text encoding used by pMem to
9807 ** desiredEnc. It is an error if the string is already of the desired
9808 ** encoding, or if *pMem does not contain a string value.
9810 static int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
9811 unsigned char zShort[NBFS]; /* Temporary short output buffer */
9812 int len; /* Maximum length of output string in bytes */
9813 unsigned char *zOut; /* Output buffer */
9814 unsigned char *zIn; /* Input iterator */
9815 unsigned char *zTerm; /* End of input */
9816 unsigned char *z; /* Output iterator */
9817 unsigned int c;
9819 assert( pMem->flags&MEM_Str );
9820 assert( pMem->enc!=desiredEnc );
9821 assert( pMem->enc!=0 );
9822 assert( pMem->n>=0 );
9824 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
9826 char zBuf[100];
9827 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
9828 fprintf(stderr, "INPUT: %s\n", zBuf);
9830 #endif
9832 /* If the translation is between UTF-16 little and big endian, then
9833 ** all that is required is to swap the byte order. This case is handled
9834 ** differently from the others.
9836 if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
9837 u8 temp;
9838 int rc;
9839 rc = sqlite3VdbeMemMakeWriteable(pMem);
9840 if( rc!=SQLITE_OK ){
9841 assert( rc==SQLITE_NOMEM );
9842 return SQLITE_NOMEM;
9844 zIn = (u8*)pMem->z;
9845 zTerm = &zIn[pMem->n];
9846 while( zIn<zTerm ){
9847 temp = *zIn;
9848 *zIn = *(zIn+1);
9849 zIn++;
9850 *zIn++ = temp;
9852 pMem->enc = desiredEnc;
9853 goto translate_out;
9856 /* Set len to the maximum number of bytes required in the output buffer. */
9857 if( desiredEnc==SQLITE_UTF8 ){
9858 /* When converting from UTF-16, the maximum growth results from
9859 ** translating a 2-byte character to a 4-byte UTF-8 character.
9860 ** A single byte is required for the output string
9861 ** nul-terminator.
9863 len = pMem->n * 2 + 1;
9864 }else{
9865 /* When converting from UTF-8 to UTF-16 the maximum growth is caused
9866 ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
9867 ** character. Two bytes are required in the output buffer for the
9868 ** nul-terminator.
9870 len = pMem->n * 2 + 2;
9873 /* Set zIn to point at the start of the input buffer and zTerm to point 1
9874 ** byte past the end.
9876 ** Variable zOut is set to point at the output buffer. This may be space
9877 ** obtained from malloc(), or Mem.zShort, if it large enough and not in
9878 ** use, or the zShort array on the stack (see above).
9880 zIn = (u8*)pMem->z;
9881 zTerm = &zIn[pMem->n];
9882 if( len>NBFS ){
9883 zOut = sqliteMallocRaw(len);
9884 if( !zOut ) return SQLITE_NOMEM;
9885 }else{
9886 zOut = zShort;
9888 z = zOut;
9890 if( pMem->enc==SQLITE_UTF8 ){
9891 unsigned int iExtra = 0xD800;
9893 if( 0==(pMem->flags&MEM_Term) && zTerm>zIn && (zTerm[-1]&0x80) ){
9894 /* This UTF8 string is not nul-terminated, and the last byte is
9895 ** not a character in the ascii range (codpoints 0..127). This
9896 ** means the SQLITE_READ_UTF8() macro might read past the end
9897 ** of the allocated buffer.
9899 ** There are four possibilities:
9901 ** 1. The last byte is the first byte of a non-ASCII character,
9903 ** 2. The final N bytes of the input string are continuation bytes
9904 ** and immediately preceding them is the first byte of a
9905 ** non-ASCII character.
9907 ** 3. The final N bytes of the input string are continuation bytes
9908 ** and immediately preceding them is a byte that encodes a
9909 ** character in the ASCII range.
9911 ** 4. The entire string consists of continuation characters.
9913 ** Cases (3) and (4) require no special handling. The SQLITE_READ_UTF8()
9914 ** macro will not overread the buffer in these cases.
9916 unsigned char *zExtra = &zTerm[-1];
9917 while( zExtra>zIn && (zExtra[0]&0xC0)==0x80 ){
9918 zExtra--;
9921 if( (zExtra[0]&0xC0)==0xC0 ){
9922 /* Make a copy of the last character encoding in the input string.
9923 ** Then make sure it is nul-terminated and use SQLITE_READ_UTF8()
9924 ** to decode the codepoint. Store the codepoint in variable iExtra,
9925 ** it will be appended to the output string later.
9927 unsigned char *zFree = 0;
9928 unsigned char zBuf[16];
9929 int nExtra = (pMem->n+zIn-zExtra);
9930 zTerm = zExtra;
9931 if( nExtra>15 ){
9932 zExtra = sqliteMallocRaw(nExtra+1);
9933 if( !zExtra ){
9934 return SQLITE_NOMEM;
9936 zFree = zExtra;
9937 }else{
9938 zExtra = zBuf;
9940 memcpy(zExtra, zTerm, nExtra);
9941 zExtra[nExtra] = '\0';
9942 SQLITE_READ_UTF8(zExtra, iExtra);
9943 sqliteFree(zFree);
9947 if( desiredEnc==SQLITE_UTF16LE ){
9948 /* UTF-8 -> UTF-16 Little-endian */
9949 while( zIn<zTerm ){
9950 SQLITE_READ_UTF8(zIn, c);
9951 WRITE_UTF16LE(z, c);
9953 if( iExtra!=0xD800 ){
9954 WRITE_UTF16LE(z, iExtra);
9956 }else{
9957 assert( desiredEnc==SQLITE_UTF16BE );
9958 /* UTF-8 -> UTF-16 Big-endian */
9959 while( zIn<zTerm ){
9960 SQLITE_READ_UTF8(zIn, c);
9961 WRITE_UTF16BE(z, c);
9963 if( iExtra!=0xD800 ){
9964 WRITE_UTF16BE(z, iExtra);
9967 pMem->n = z - zOut;
9968 *z++ = 0;
9969 }else{
9970 assert( desiredEnc==SQLITE_UTF8 );
9971 if( pMem->enc==SQLITE_UTF16LE ){
9972 /* UTF-16 Little-endian -> UTF-8 */
9973 while( zIn<zTerm ){
9974 READ_UTF16LE(zIn, c);
9975 WRITE_UTF8(z, c);
9977 }else{
9978 /* UTF-16 Little-endian -> UTF-8 */
9979 while( zIn<zTerm ){
9980 READ_UTF16BE(zIn, c);
9981 WRITE_UTF8(z, c);
9984 pMem->n = z - zOut;
9986 *z = 0;
9987 assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
9989 sqlite3VdbeMemRelease(pMem);
9990 pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
9991 pMem->enc = desiredEnc;
9992 if( zOut==zShort ){
9993 memcpy(pMem->zShort, zOut, len);
9994 zOut = (u8*)pMem->zShort;
9995 pMem->flags |= (MEM_Term|MEM_Short);
9996 }else{
9997 pMem->flags |= (MEM_Term|MEM_Dyn);
9999 pMem->z = (char*)zOut;
10001 translate_out:
10002 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
10004 char zBuf[100];
10005 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
10006 fprintf(stderr, "OUTPUT: %s\n", zBuf);
10008 #endif
10009 return SQLITE_OK;
10013 ** This routine checks for a byte-order mark at the beginning of the
10014 ** UTF-16 string stored in *pMem. If one is present, it is removed and
10015 ** the encoding of the Mem adjusted. This routine does not do any
10016 ** byte-swapping, it just sets Mem.enc appropriately.
10018 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
10019 ** changed by this function.
10021 static int sqlite3VdbeMemHandleBom(Mem *pMem){
10022 int rc = SQLITE_OK;
10023 u8 bom = 0;
10025 if( pMem->n<0 || pMem->n>1 ){
10026 u8 b1 = *(u8 *)pMem->z;
10027 u8 b2 = *(((u8 *)pMem->z) + 1);
10028 if( b1==0xFE && b2==0xFF ){
10029 bom = SQLITE_UTF16BE;
10031 if( b1==0xFF && b2==0xFE ){
10032 bom = SQLITE_UTF16LE;
10036 if( bom ){
10037 /* This function is called as soon as a string is stored in a Mem*,
10038 ** from within sqlite3VdbeMemSetStr(). At that point it is not possible
10039 ** for the string to be stored in Mem.zShort, or for it to be stored
10040 ** in dynamic memory with no destructor.
10042 assert( !(pMem->flags&MEM_Short) );
10043 assert( !(pMem->flags&MEM_Dyn) || pMem->xDel );
10044 if( pMem->flags & MEM_Dyn ){
10045 void (*xDel)(void*) = pMem->xDel;
10046 char *z = pMem->z;
10047 pMem->z = 0;
10048 pMem->xDel = 0;
10049 rc = sqlite3VdbeMemSetStr(pMem, &z[2], pMem->n-2, bom, SQLITE_TRANSIENT);
10050 xDel(z);
10051 }else{
10052 rc = sqlite3VdbeMemSetStr(pMem, &pMem->z[2], pMem->n-2, bom,
10053 SQLITE_TRANSIENT);
10056 return rc;
10058 #endif /* SQLITE_OMIT_UTF16 */
10061 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
10062 ** return the number of unicode characters in pZ up to (but not including)
10063 ** the first 0x00 byte. If nByte is not less than zero, return the
10064 ** number of unicode characters in the first nByte of pZ (or up to
10065 ** the first 0x00, whichever comes first).
10067 static int sqlite3Utf8CharLen(const char *zIn, int nByte){
10068 int r = 0;
10069 const u8 *z = (const u8*)zIn;
10070 const u8 *zTerm;
10071 if( nByte>=0 ){
10072 zTerm = &z[nByte];
10073 }else{
10074 zTerm = (const u8*)(-1);
10076 assert( z<=zTerm );
10077 while( *z!=0 && z<zTerm ){
10078 SQLITE_SKIP_UTF8(z);
10079 r++;
10081 return r;
10084 #ifndef SQLITE_OMIT_UTF16
10086 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
10087 ** Memory to hold the UTF-8 string is obtained from malloc and must be
10088 ** freed by the calling function.
10090 ** NULL is returned if there is an allocation error.
10092 static char *sqlite3Utf16to8(const void *z, int nByte){
10093 Mem m;
10094 memset(&m, 0, sizeof(m));
10095 sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
10096 sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
10097 assert( (m.flags & MEM_Term)!=0 || sqlite3MallocFailed() );
10098 assert( (m.flags & MEM_Str)!=0 || sqlite3MallocFailed() );
10099 return (m.flags & MEM_Dyn)!=0 ? m.z : sqliteStrDup(m.z);
10103 ** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
10104 ** return the number of bytes up to (but not including), the first pair
10105 ** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
10106 ** then return the number of bytes in the first nChar unicode characters
10107 ** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
10109 static int sqlite3Utf16ByteLen(const void *zIn, int nChar){
10110 unsigned int c = 1;
10111 char const *z = zIn;
10112 int n = 0;
10113 if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
10114 /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
10115 ** and in other parts of this file means that at one branch will
10116 ** not be covered by coverage testing on any single host. But coverage
10117 ** will be complete if the tests are run on both a little-endian and
10118 ** big-endian host. Because both the UTF16NATIVE and SQLITE_UTF16BE
10119 ** macros are constant at compile time the compiler can determine
10120 ** which branch will be followed. It is therefore assumed that no runtime
10121 ** penalty is paid for this "if" statement.
10123 while( c && ((nChar<0) || n<nChar) ){
10124 READ_UTF16BE(z, c);
10125 n++;
10127 }else{
10128 while( c && ((nChar<0) || n<nChar) ){
10129 READ_UTF16LE(z, c);
10130 n++;
10133 return (z-(char const *)zIn)-((c==0)?2:0);
10136 #if defined(SQLITE_TEST)
10138 ** Translate UTF-8 to UTF-8.
10140 ** This has the effect of making sure that the string is well-formed
10141 ** UTF-8. Miscoded characters are removed.
10143 ** The translation is done in-place (since it is impossible for the
10144 ** correct UTF-8 encoding to be longer than a malformed encoding).
10146 static int sqlite3Utf8To8(unsigned char *zIn){
10147 unsigned char *zOut = zIn;
10148 unsigned char *zStart = zIn;
10149 int c;
10151 while(1){
10152 SQLITE_READ_UTF8(zIn, c);
10153 if( c==0 ) break;
10154 if( c!=0xfffd ){
10155 WRITE_UTF8(zOut, c);
10158 *zOut = 0;
10159 return zOut - zStart;
10161 #endif
10163 #if defined(SQLITE_TEST)
10165 ** This routine is called from the TCL test function "translate_selftest".
10166 ** It checks that the primitives for serializing and deserializing
10167 ** characters in each encoding are inverses of each other.
10169 static void sqlite3UtfSelfTest(){
10170 unsigned int i, t;
10171 unsigned char zBuf[20];
10172 unsigned char *z;
10173 int n;
10174 unsigned int c;
10176 for(i=0; i<0x00110000; i++){
10177 z = zBuf;
10178 WRITE_UTF8(z, i);
10179 n = z-zBuf;
10180 z[0] = 0;
10181 z = zBuf;
10182 SQLITE_READ_UTF8(z, c);
10183 t = i;
10184 if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
10185 if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
10186 assert( c==t );
10187 assert( (z-zBuf)==n );
10189 for(i=0; i<0x00110000; i++){
10190 if( i>=0xD800 && i<0xE000 ) continue;
10191 z = zBuf;
10192 WRITE_UTF16LE(z, i);
10193 n = z-zBuf;
10194 z[0] = 0;
10195 z = zBuf;
10196 READ_UTF16LE(z, c);
10197 assert( c==i );
10198 assert( (z-zBuf)==n );
10200 for(i=0; i<0x00110000; i++){
10201 if( i>=0xD800 && i<0xE000 ) continue;
10202 z = zBuf;
10203 WRITE_UTF16BE(z, i);
10204 n = z-zBuf;
10205 z[0] = 0;
10206 z = zBuf;
10207 READ_UTF16BE(z, c);
10208 assert( c==i );
10209 assert( (z-zBuf)==n );
10212 #endif /* SQLITE_TEST */
10213 #endif /* SQLITE_OMIT_UTF16 */
10215 /************** End of utf.c *************************************************/
10216 /************** Begin file util.c ********************************************/
10218 ** 2001 September 15
10220 ** The author disclaims copyright to this source code. In place of
10221 ** a legal notice, here is a blessing:
10223 ** May you do good and not evil.
10224 ** May you find forgiveness for yourself and forgive others.
10225 ** May you share freely, never taking more than you give.
10227 *************************************************************************
10228 ** Utility functions used throughout sqlite.
10230 ** This file contains functions for allocating memory, comparing
10231 ** strings, and stuff like that.
10233 ** $Id: util.c,v 1.205 2007/05/16 17:50:46 danielk1977 Exp $
10238 ** Set the most recent error code and error string for the sqlite
10239 ** handle "db". The error code is set to "err_code".
10241 ** If it is not NULL, string zFormat specifies the format of the
10242 ** error string in the style of the printf functions: The following
10243 ** format characters are allowed:
10245 ** %s Insert a string
10246 ** %z A string that should be freed after use
10247 ** %d Insert an integer
10248 ** %T Insert a token
10249 ** %S Insert the first element of a SrcList
10251 ** zFormat and any string tokens that follow it are assumed to be
10252 ** encoded in UTF-8.
10254 ** To clear the most recent error for sqlite handle "db", sqlite3Error
10255 ** should be called with err_code set to SQLITE_OK and zFormat set
10256 ** to NULL.
10258 static void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
10259 if( db && (db->pErr || (db->pErr = sqlite3ValueNew())!=0) ){
10260 db->errCode = err_code;
10261 if( zFormat ){
10262 char *z;
10263 va_list ap;
10264 va_start(ap, zFormat);
10265 z = sqlite3VMPrintf(zFormat, ap);
10266 va_end(ap);
10267 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, sqlite3FreeX);
10268 }else{
10269 sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
10275 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
10276 ** The following formatting characters are allowed:
10278 ** %s Insert a string
10279 ** %z A string that should be freed after use
10280 ** %d Insert an integer
10281 ** %T Insert a token
10282 ** %S Insert the first element of a SrcList
10284 ** This function should be used to report any error that occurs whilst
10285 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
10286 ** last thing the sqlite3_prepare() function does is copy the error
10287 ** stored by this function into the database handle using sqlite3Error().
10288 ** Function sqlite3Error() should be used during statement execution
10289 ** (sqlite3_step() etc.).
10291 static void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
10292 va_list ap;
10293 pParse->nErr++;
10294 sqliteFree(pParse->zErrMsg);
10295 va_start(ap, zFormat);
10296 pParse->zErrMsg = sqlite3VMPrintf(zFormat, ap);
10297 va_end(ap);
10298 if( pParse->rc==SQLITE_OK ){
10299 pParse->rc = SQLITE_ERROR;
10304 ** Clear the error message in pParse, if any
10306 static void sqlite3ErrorClear(Parse *pParse){
10307 sqliteFree(pParse->zErrMsg);
10308 pParse->zErrMsg = 0;
10309 pParse->nErr = 0;
10313 ** Convert an SQL-style quoted string into a normal string by removing
10314 ** the quote characters. The conversion is done in-place. If the
10315 ** input does not begin with a quote character, then this routine
10316 ** is a no-op.
10318 ** 2002-Feb-14: This routine is extended to remove MS-Access style
10319 ** brackets from around identifers. For example: "[a-b-c]" becomes
10320 ** "a-b-c".
10322 static void sqlite3Dequote(char *z){
10323 int quote;
10324 int i, j;
10325 if( z==0 ) return;
10326 quote = z[0];
10327 switch( quote ){
10328 case '\'': break;
10329 case '"': break;
10330 case '`': break; /* For MySQL compatibility */
10331 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
10332 default: return;
10334 for(i=1, j=0; z[i]; i++){
10335 if( z[i]==quote ){
10336 if( z[i+1]==quote ){
10337 z[j++] = quote;
10338 i++;
10339 }else{
10340 z[j++] = 0;
10341 break;
10343 }else{
10344 z[j++] = z[i];
10349 /* An array to map all upper-case characters into their corresponding
10350 ** lower-case character.
10352 const unsigned char sqlite3UpperToLower[] = {
10353 #ifdef SQLITE_ASCII
10354 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
10355 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
10356 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
10357 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
10358 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
10359 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
10360 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
10361 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
10362 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
10363 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
10364 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
10365 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
10366 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
10367 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
10368 252,253,254,255
10369 #endif
10370 #ifdef SQLITE_EBCDIC
10371 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
10372 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
10373 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
10374 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
10375 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
10376 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
10377 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
10378 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
10379 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
10380 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
10381 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
10382 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
10383 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
10384 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
10385 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
10386 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
10387 #endif
10389 #define UpperToLower sqlite3UpperToLower
10392 ** Some systems have stricmp(). Others have strcasecmp(). Because
10393 ** there is no consistency, we will define our own.
10395 static int sqlite3StrICmp(const char *zLeft, const char *zRight){
10396 register unsigned char *a, *b;
10397 a = (unsigned char *)zLeft;
10398 b = (unsigned char *)zRight;
10399 while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
10400 return UpperToLower[*a] - UpperToLower[*b];
10402 static int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
10403 register unsigned char *a, *b;
10404 a = (unsigned char *)zLeft;
10405 b = (unsigned char *)zRight;
10406 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
10407 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
10411 ** Return TRUE if z is a pure numeric string. Return FALSE if the
10412 ** string contains any character which is not part of a number. If
10413 ** the string is numeric and contains the '.' character, set *realnum
10414 ** to TRUE (otherwise FALSE).
10416 ** An empty string is considered non-numeric.
10418 static int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
10419 int incr = (enc==SQLITE_UTF8?1:2);
10420 if( enc==SQLITE_UTF16BE ) z++;
10421 if( *z=='-' || *z=='+' ) z += incr;
10422 if( !isdigit(*(u8*)z) ){
10423 return 0;
10425 z += incr;
10426 if( realnum ) *realnum = 0;
10427 while( isdigit(*(u8*)z) ){ z += incr; }
10428 if( *z=='.' ){
10429 z += incr;
10430 if( !isdigit(*(u8*)z) ) return 0;
10431 while( isdigit(*(u8*)z) ){ z += incr; }
10432 if( realnum ) *realnum = 1;
10434 if( *z=='e' || *z=='E' ){
10435 z += incr;
10436 if( *z=='+' || *z=='-' ) z += incr;
10437 if( !isdigit(*(u8*)z) ) return 0;
10438 while( isdigit(*(u8*)z) ){ z += incr; }
10439 if( realnum ) *realnum = 1;
10441 return *z==0;
10445 ** The string z[] is an ascii representation of a real number.
10446 ** Convert this string to a double.
10448 ** This routine assumes that z[] really is a valid number. If it
10449 ** is not, the result is undefined.
10451 ** This routine is used instead of the library atof() function because
10452 ** the library atof() might want to use "," as the decimal point instead
10453 ** of "." depending on how locale is set. But that would cause problems
10454 ** for SQL. So this routine always uses "." regardless of locale.
10456 static int sqlite3AtoF(const char *z, double *pResult){
10457 #ifndef SQLITE_OMIT_FLOATING_POINT
10458 int sign = 1;
10459 const char *zBegin = z;
10460 LONGDOUBLE_TYPE v1 = 0.0;
10461 while( isspace(*(u8*)z) ) z++;
10462 if( *z=='-' ){
10463 sign = -1;
10464 z++;
10465 }else if( *z=='+' ){
10466 z++;
10468 while( isdigit(*(u8*)z) ){
10469 v1 = v1*10.0 + (*z - '0');
10470 z++;
10472 if( *z=='.' ){
10473 LONGDOUBLE_TYPE divisor = 1.0;
10474 z++;
10475 while( isdigit(*(u8*)z) ){
10476 v1 = v1*10.0 + (*z - '0');
10477 divisor *= 10.0;
10478 z++;
10480 v1 /= divisor;
10482 if( *z=='e' || *z=='E' ){
10483 int esign = 1;
10484 int eval = 0;
10485 LONGDOUBLE_TYPE scale = 1.0;
10486 z++;
10487 if( *z=='-' ){
10488 esign = -1;
10489 z++;
10490 }else if( *z=='+' ){
10491 z++;
10493 while( isdigit(*(u8*)z) ){
10494 eval = eval*10 + *z - '0';
10495 z++;
10497 while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
10498 while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
10499 while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
10500 while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
10501 if( esign<0 ){
10502 v1 /= scale;
10503 }else{
10504 v1 *= scale;
10507 *pResult = sign<0 ? -v1 : v1;
10508 return z - zBegin;
10509 #else
10510 return sqlite3Atoi64(z, pResult);
10511 #endif /* SQLITE_OMIT_FLOATING_POINT */
10515 ** Return TRUE if zNum is a 64-bit signed integer and write
10516 ** the value of the integer into *pNum. If zNum is not an integer
10517 ** or is an integer that is too large to be expressed with 64 bits,
10518 ** then return false. If n>0 and the integer is string is not
10519 ** exactly n bytes long, return false.
10521 ** When this routine was originally written it dealt with only
10522 ** 32-bit numbers. At that time, it was much faster than the
10523 ** atoi() library routine in RedHat 7.2.
10525 static int sqlite3Atoi64(const char *zNum, i64 *pNum){
10526 i64 v = 0;
10527 int neg;
10528 int i, c;
10529 while( isspace(*(u8*)zNum) ) zNum++;
10530 if( *zNum=='-' ){
10531 neg = 1;
10532 zNum++;
10533 }else if( *zNum=='+' ){
10534 neg = 0;
10535 zNum++;
10536 }else{
10537 neg = 0;
10539 for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
10540 v = v*10 + c - '0';
10542 *pNum = neg ? -v : v;
10543 return c==0 && i>0 &&
10544 (i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0));
10548 ** The string zNum represents an integer. There might be some other
10549 ** information following the integer too, but that part is ignored.
10550 ** If the integer that the prefix of zNum represents will fit in a
10551 ** 32-bit signed integer, return TRUE. Otherwise return FALSE.
10553 ** This routine returns FALSE for the string -2147483648 even that
10554 ** that number will in fact fit in a 32-bit integer. But positive
10555 ** 2147483648 will not fit in 32 bits. So it seems safer to return
10556 ** false.
10558 static int sqlite3FitsIn32Bits(const char *zNum){
10559 int i, c;
10560 if( *zNum=='-' || *zNum=='+' ) zNum++;
10561 for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
10562 return i<10 || (i==10 && memcmp(zNum,"2147483647",10)<=0);
10566 ** If zNum represents an integer that will fit in 32-bits, then set
10567 ** *pValue to that integer and return true. Otherwise return false.
10569 static int sqlite3GetInt32(const char *zNum, int *pValue){
10570 if( sqlite3FitsIn32Bits(zNum) ){
10571 *pValue = atoi(zNum);
10572 return 1;
10574 return 0;
10578 ** The string zNum represents an integer. There might be some other
10579 ** information following the integer too, but that part is ignored.
10580 ** If the integer that the prefix of zNum represents will fit in a
10581 ** 64-bit signed integer, return TRUE. Otherwise return FALSE.
10583 ** This routine returns FALSE for the string -9223372036854775808 even that
10584 ** that number will, in theory fit in a 64-bit integer. Positive
10585 ** 9223373036854775808 will not fit in 64 bits. So it seems safer to return
10586 ** false.
10588 static int sqlite3FitsIn64Bits(const char *zNum){
10589 int i, c;
10590 if( *zNum=='-' || *zNum=='+' ) zNum++;
10591 for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
10592 return i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0);
10597 ** Check to make sure we have a valid db pointer. This test is not
10598 ** foolproof but it does provide some measure of protection against
10599 ** misuse of the interface such as passing in db pointers that are
10600 ** NULL or which have been previously closed. If this routine returns
10601 ** TRUE it means that the db pointer is invalid and should not be
10602 ** dereferenced for any reason. The calling function should invoke
10603 ** SQLITE_MISUSE immediately.
10605 static int sqlite3SafetyCheck(sqlite3 *db){
10606 int magic;
10607 if( db==0 ) return 1;
10608 magic = db->magic;
10609 if( magic!=SQLITE_MAGIC_CLOSED &&
10610 magic!=SQLITE_MAGIC_OPEN &&
10611 magic!=SQLITE_MAGIC_BUSY ) return 1;
10612 return 0;
10616 ** The variable-length integer encoding is as follows:
10618 ** KEY:
10619 ** A = 0xxxxxxx 7 bits of data and one flag bit
10620 ** B = 1xxxxxxx 7 bits of data and one flag bit
10621 ** C = xxxxxxxx 8 bits of data
10623 ** 7 bits - A
10624 ** 14 bits - BA
10625 ** 21 bits - BBA
10626 ** 28 bits - BBBA
10627 ** 35 bits - BBBBA
10628 ** 42 bits - BBBBBA
10629 ** 49 bits - BBBBBBA
10630 ** 56 bits - BBBBBBBA
10631 ** 64 bits - BBBBBBBBC
10635 ** Write a 64-bit variable-length integer to memory starting at p[0].
10636 ** The length of data write will be between 1 and 9 bytes. The number
10637 ** of bytes written is returned.
10639 ** A variable-length integer consists of the lower 7 bits of each byte
10640 ** for all bytes that have the 8th bit set and one byte with the 8th
10641 ** bit clear. Except, if we get to the 9th byte, it stores the full
10642 ** 8 bits and is the last byte.
10644 static int sqlite3PutVarint(unsigned char *p, u64 v){
10645 int i, j, n;
10646 u8 buf[10];
10647 if( v & (((u64)0xff000000)<<32) ){
10648 p[8] = v;
10649 v >>= 8;
10650 for(i=7; i>=0; i--){
10651 p[i] = (v & 0x7f) | 0x80;
10652 v >>= 7;
10654 return 9;
10656 n = 0;
10658 buf[n++] = (v & 0x7f) | 0x80;
10659 v >>= 7;
10660 }while( v!=0 );
10661 buf[0] &= 0x7f;
10662 assert( n<=9 );
10663 for(i=0, j=n-1; j>=0; j--, i++){
10664 p[i] = buf[j];
10666 return n;
10670 ** Read a 64-bit variable-length integer from memory starting at p[0].
10671 ** Return the number of bytes read. The value is stored in *v.
10673 static int sqlite3GetVarint(const unsigned char *p, u64 *v){
10674 u32 x;
10675 u64 x64;
10676 int n;
10677 unsigned char c;
10678 if( ((c = p[0]) & 0x80)==0 ){
10679 *v = c;
10680 return 1;
10682 x = c & 0x7f;
10683 if( ((c = p[1]) & 0x80)==0 ){
10684 *v = (x<<7) | c;
10685 return 2;
10687 x = (x<<7) | (c&0x7f);
10688 if( ((c = p[2]) & 0x80)==0 ){
10689 *v = (x<<7) | c;
10690 return 3;
10692 x = (x<<7) | (c&0x7f);
10693 if( ((c = p[3]) & 0x80)==0 ){
10694 *v = (x<<7) | c;
10695 return 4;
10697 x64 = (x<<7) | (c&0x7f);
10698 n = 4;
10700 c = p[n++];
10701 if( n==9 ){
10702 x64 = (x64<<8) | c;
10703 break;
10705 x64 = (x64<<7) | (c&0x7f);
10706 }while( (c & 0x80)!=0 );
10707 *v = x64;
10708 return n;
10712 ** Read a 32-bit variable-length integer from memory starting at p[0].
10713 ** Return the number of bytes read. The value is stored in *v.
10715 static int sqlite3GetVarint32(const unsigned char *p, u32 *v){
10716 u32 x;
10717 int n;
10718 unsigned char c;
10719 if( ((signed char*)p)[0]>=0 ){
10720 *v = p[0];
10721 return 1;
10723 x = p[0] & 0x7f;
10724 if( ((signed char*)p)[1]>=0 ){
10725 *v = (x<<7) | p[1];
10726 return 2;
10728 x = (x<<7) | (p[1] & 0x7f);
10729 n = 2;
10731 x = (x<<7) | ((c = p[n++])&0x7f);
10732 }while( (c & 0x80)!=0 && n<9 );
10733 *v = x;
10734 return n;
10738 ** Return the number of bytes that will be needed to store the given
10739 ** 64-bit integer.
10741 static int sqlite3VarintLen(u64 v){
10742 int i = 0;
10744 i++;
10745 v >>= 7;
10746 }while( v!=0 && i<9 );
10747 return i;
10752 ** Read or write a four-byte big-endian integer value.
10754 static u32 sqlite3Get4byte(const u8 *p){
10755 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
10757 static void sqlite3Put4byte(unsigned char *p, u32 v){
10758 p[0] = v>>24;
10759 p[1] = v>>16;
10760 p[2] = v>>8;
10761 p[3] = v;
10766 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC) \
10767 || defined(SQLITE_TEST)
10769 ** Translate a single byte of Hex into an integer.
10771 static int hexToInt(int h){
10772 if( h>='0' && h<='9' ){
10773 return h - '0';
10774 }else if( h>='a' && h<='f' ){
10775 return h - 'a' + 10;
10776 }else{
10777 assert( h>='A' && h<='F' );
10778 return h - 'A' + 10;
10781 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC || SQLITE_TEST */
10783 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
10785 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
10786 ** value. Return a pointer to its binary value. Space to hold the
10787 ** binary value has been obtained from malloc and must be freed by
10788 ** the calling routine.
10790 static void *sqlite3HexToBlob(const char *z){
10791 char *zBlob;
10792 int i;
10793 int n = strlen(z);
10794 if( n%2 ) return 0;
10796 zBlob = (char *)sqliteMalloc(n/2);
10797 if( zBlob ){
10798 for(i=0; i<n; i+=2){
10799 zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
10802 return zBlob;
10804 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
10808 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
10809 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
10810 ** when this routine is called.
10812 ** This routine is called when entering an SQLite API. The SQLITE_MAGIC_OPEN
10813 ** value indicates that the database connection passed into the API is
10814 ** open and is not being used by another thread. By changing the value
10815 ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
10816 ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
10817 ** when the API exits.
10819 ** This routine is a attempt to detect if two threads use the
10820 ** same sqlite* pointer at the same time. There is a race
10821 ** condition so it is possible that the error is not detected.
10822 ** But usually the problem will be seen. The result will be an
10823 ** error which can be used to debug the application that is
10824 ** using SQLite incorrectly.
10826 ** Ticket #202: If db->magic is not a valid open value, take care not
10827 ** to modify the db structure at all. It could be that db is a stale
10828 ** pointer. In other words, it could be that there has been a prior
10829 ** call to sqlite3_close(db) and db has been deallocated. And we do
10830 ** not want to write into deallocated memory.
10832 static int sqlite3SafetyOn(sqlite3 *db){
10833 if( db->magic==SQLITE_MAGIC_OPEN ){
10834 db->magic = SQLITE_MAGIC_BUSY;
10835 return 0;
10836 }else if( db->magic==SQLITE_MAGIC_BUSY ){
10837 db->magic = SQLITE_MAGIC_ERROR;
10838 db->u1.isInterrupted = 1;
10840 return 1;
10844 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
10845 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
10846 ** when this routine is called.
10848 static int sqlite3SafetyOff(sqlite3 *db){
10849 if( db->magic==SQLITE_MAGIC_BUSY ){
10850 db->magic = SQLITE_MAGIC_OPEN;
10851 return 0;
10852 }else {
10853 db->magic = SQLITE_MAGIC_ERROR;
10854 db->u1.isInterrupted = 1;
10855 return 1;
10860 ** Return a pointer to the ThreadData associated with the calling thread.
10862 static ThreadData *sqlite3ThreadData(){
10863 ThreadData *p = (ThreadData*)sqlite3OsThreadSpecificData(1);
10864 if( !p ){
10865 sqlite3FailedMalloc();
10867 return p;
10871 ** Return a pointer to the ThreadData associated with the calling thread.
10872 ** If no ThreadData has been allocated to this thread yet, return a pointer
10873 ** to a substitute ThreadData structure that is all zeros.
10875 static const ThreadData *sqlite3ThreadDataReadOnly(){
10876 static const ThreadData zeroData = {0}; /* Initializer to silence warnings
10877 ** from broken compilers */
10878 const ThreadData *pTd = sqlite3OsThreadSpecificData(0);
10879 return pTd ? pTd : &zeroData;
10883 ** Check to see if the ThreadData for this thread is all zero. If it
10884 ** is, then deallocate it.
10886 static void sqlite3ReleaseThreadData(){
10887 sqlite3OsThreadSpecificData(-1);
10890 /************** End of util.c ************************************************/
10891 /************** Begin file hash.c ********************************************/
10893 ** 2001 September 22
10895 ** The author disclaims copyright to this source code. In place of
10896 ** a legal notice, here is a blessing:
10898 ** May you do good and not evil.
10899 ** May you find forgiveness for yourself and forgive others.
10900 ** May you share freely, never taking more than you give.
10902 *************************************************************************
10903 ** This is the implementation of generic hash-tables
10904 ** used in SQLite.
10906 ** $Id: hash.c,v 1.19 2007/03/31 03:59:24 drh Exp $
10909 /* Turn bulk memory into a hash table object by initializing the
10910 ** fields of the Hash structure.
10912 ** "pNew" is a pointer to the hash table that is to be initialized.
10913 ** keyClass is one of the constants SQLITE_HASH_INT, SQLITE_HASH_POINTER,
10914 ** SQLITE_HASH_BINARY, or SQLITE_HASH_STRING. The value of keyClass
10915 ** determines what kind of key the hash table will use. "copyKey" is
10916 ** true if the hash table should make its own private copy of keys and
10917 ** false if it should just use the supplied pointer. CopyKey only makes
10918 ** sense for SQLITE_HASH_STRING and SQLITE_HASH_BINARY and is ignored
10919 ** for other key classes.
10921 static void sqlite3HashInit(Hash *pNew, int keyClass, int copyKey){
10922 assert( pNew!=0 );
10923 assert( keyClass>=SQLITE_HASH_STRING && keyClass<=SQLITE_HASH_BINARY );
10924 pNew->keyClass = keyClass;
10925 #if 0
10926 if( keyClass==SQLITE_HASH_POINTER || keyClass==SQLITE_HASH_INT ) copyKey = 0;
10927 #endif
10928 pNew->copyKey = copyKey;
10929 pNew->first = 0;
10930 pNew->count = 0;
10931 pNew->htsize = 0;
10932 pNew->ht = 0;
10933 pNew->xMalloc = sqlite3MallocX;
10934 pNew->xFree = sqlite3FreeX;
10937 /* Remove all entries from a hash table. Reclaim all memory.
10938 ** Call this routine to delete a hash table or to reset a hash table
10939 ** to the empty state.
10941 static void sqlite3HashClear(Hash *pH){
10942 HashElem *elem; /* For looping over all elements of the table */
10944 assert( pH!=0 );
10945 elem = pH->first;
10946 pH->first = 0;
10947 if( pH->ht ) pH->xFree(pH->ht);
10948 pH->ht = 0;
10949 pH->htsize = 0;
10950 while( elem ){
10951 HashElem *next_elem = elem->next;
10952 if( pH->copyKey && elem->pKey ){
10953 pH->xFree(elem->pKey);
10955 pH->xFree(elem);
10956 elem = next_elem;
10958 pH->count = 0;
10961 #if 0 /* NOT USED */
10963 ** Hash and comparison functions when the mode is SQLITE_HASH_INT
10965 static int intHash(const void *pKey, int nKey){
10966 return nKey ^ (nKey<<8) ^ (nKey>>8);
10968 static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){
10969 return n2 - n1;
10971 #endif
10973 #if 0 /* NOT USED */
10975 ** Hash and comparison functions when the mode is SQLITE_HASH_POINTER
10977 static int ptrHash(const void *pKey, int nKey){
10978 uptr x = Addr(pKey);
10979 return x ^ (x<<8) ^ (x>>8);
10981 static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
10982 if( pKey1==pKey2 ) return 0;
10983 if( pKey1<pKey2 ) return -1;
10984 return 1;
10986 #endif
10989 ** Hash and comparison functions when the mode is SQLITE_HASH_STRING
10991 static int strHash(const void *pKey, int nKey){
10992 const char *z = (const char *)pKey;
10993 int h = 0;
10994 if( nKey<=0 ) nKey = strlen(z);
10995 while( nKey > 0 ){
10996 h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
10997 nKey--;
10999 return h & 0x7fffffff;
11001 static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
11002 if( n1!=n2 ) return 1;
11003 return sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
11007 ** Hash and comparison functions when the mode is SQLITE_HASH_BINARY
11009 static int binHash(const void *pKey, int nKey){
11010 int h = 0;
11011 const char *z = (const char *)pKey;
11012 while( nKey-- > 0 ){
11013 h = (h<<3) ^ h ^ *(z++);
11015 return h & 0x7fffffff;
11017 static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
11018 if( n1!=n2 ) return 1;
11019 return memcmp(pKey1,pKey2,n1);
11023 ** Return a pointer to the appropriate hash function given the key class.
11025 ** The C syntax in this function definition may be unfamilar to some
11026 ** programmers, so we provide the following additional explanation:
11028 ** The name of the function is "hashFunction". The function takes a
11029 ** single parameter "keyClass". The return value of hashFunction()
11030 ** is a pointer to another function. Specifically, the return value
11031 ** of hashFunction() is a pointer to a function that takes two parameters
11032 ** with types "const void*" and "int" and returns an "int".
11034 static int (*hashFunction(int keyClass))(const void*,int){
11035 #if 0 /* HASH_INT and HASH_POINTER are never used */
11036 switch( keyClass ){
11037 case SQLITE_HASH_INT: return &intHash;
11038 case SQLITE_HASH_POINTER: return &ptrHash;
11039 case SQLITE_HASH_STRING: return &strHash;
11040 case SQLITE_HASH_BINARY: return &binHash;;
11041 default: break;
11043 return 0;
11044 #else
11045 if( keyClass==SQLITE_HASH_STRING ){
11046 return &strHash;
11047 }else{
11048 assert( keyClass==SQLITE_HASH_BINARY );
11049 return &binHash;
11051 #endif
11055 ** Return a pointer to the appropriate hash function given the key class.
11057 ** For help in interpreted the obscure C code in the function definition,
11058 ** see the header comment on the previous function.
11060 static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
11061 #if 0 /* HASH_INT and HASH_POINTER are never used */
11062 switch( keyClass ){
11063 case SQLITE_HASH_INT: return &intCompare;
11064 case SQLITE_HASH_POINTER: return &ptrCompare;
11065 case SQLITE_HASH_STRING: return &strCompare;
11066 case SQLITE_HASH_BINARY: return &binCompare;
11067 default: break;
11069 return 0;
11070 #else
11071 if( keyClass==SQLITE_HASH_STRING ){
11072 return &strCompare;
11073 }else{
11074 assert( keyClass==SQLITE_HASH_BINARY );
11075 return &binCompare;
11077 #endif
11080 /* Link an element into the hash table
11082 static void insertElement(
11083 Hash *pH, /* The complete hash table */
11084 struct _ht *pEntry, /* The entry into which pNew is inserted */
11085 HashElem *pNew /* The element to be inserted */
11087 HashElem *pHead; /* First element already in pEntry */
11088 pHead = pEntry->chain;
11089 if( pHead ){
11090 pNew->next = pHead;
11091 pNew->prev = pHead->prev;
11092 if( pHead->prev ){ pHead->prev->next = pNew; }
11093 else { pH->first = pNew; }
11094 pHead->prev = pNew;
11095 }else{
11096 pNew->next = pH->first;
11097 if( pH->first ){ pH->first->prev = pNew; }
11098 pNew->prev = 0;
11099 pH->first = pNew;
11101 pEntry->count++;
11102 pEntry->chain = pNew;
11106 /* Resize the hash table so that it cantains "new_size" buckets.
11107 ** "new_size" must be a power of 2. The hash table might fail
11108 ** to resize if sqliteMalloc() fails.
11110 static void rehash(Hash *pH, int new_size){
11111 struct _ht *new_ht; /* The new hash table */
11112 HashElem *elem, *next_elem; /* For looping over existing elements */
11113 int (*xHash)(const void*,int); /* The hash function */
11115 assert( (new_size & (new_size-1))==0 );
11116 new_ht = (struct _ht *)pH->xMalloc( new_size*sizeof(struct _ht) );
11117 if( new_ht==0 ) return;
11118 if( pH->ht ) pH->xFree(pH->ht);
11119 pH->ht = new_ht;
11120 pH->htsize = new_size;
11121 xHash = hashFunction(pH->keyClass);
11122 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
11123 int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
11124 next_elem = elem->next;
11125 insertElement(pH, &new_ht[h], elem);
11129 /* This function (for internal use only) locates an element in an
11130 ** hash table that matches the given key. The hash for this key has
11131 ** already been computed and is passed as the 4th parameter.
11133 static HashElem *findElementGivenHash(
11134 const Hash *pH, /* The pH to be searched */
11135 const void *pKey, /* The key we are searching for */
11136 int nKey,
11137 int h /* The hash for this key. */
11139 HashElem *elem; /* Used to loop thru the element list */
11140 int count; /* Number of elements left to test */
11141 int (*xCompare)(const void*,int,const void*,int); /* comparison function */
11143 if( pH->ht ){
11144 struct _ht *pEntry = &pH->ht[h];
11145 elem = pEntry->chain;
11146 count = pEntry->count;
11147 xCompare = compareFunction(pH->keyClass);
11148 while( count-- && elem ){
11149 if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
11150 return elem;
11152 elem = elem->next;
11155 return 0;
11158 /* Remove a single entry from the hash table given a pointer to that
11159 ** element and a hash on the element's key.
11161 static void removeElementGivenHash(
11162 Hash *pH, /* The pH containing "elem" */
11163 HashElem* elem, /* The element to be removed from the pH */
11164 int h /* Hash value for the element */
11166 struct _ht *pEntry;
11167 if( elem->prev ){
11168 elem->prev->next = elem->next;
11169 }else{
11170 pH->first = elem->next;
11172 if( elem->next ){
11173 elem->next->prev = elem->prev;
11175 pEntry = &pH->ht[h];
11176 if( pEntry->chain==elem ){
11177 pEntry->chain = elem->next;
11179 pEntry->count--;
11180 if( pEntry->count<=0 ){
11181 pEntry->chain = 0;
11183 if( pH->copyKey ){
11184 pH->xFree(elem->pKey);
11186 pH->xFree( elem );
11187 pH->count--;
11188 if( pH->count<=0 ){
11189 assert( pH->first==0 );
11190 assert( pH->count==0 );
11191 sqlite3HashClear(pH);
11195 /* Attempt to locate an element of the hash table pH with a key
11196 ** that matches pKey,nKey. Return the data for this element if it is
11197 ** found, or NULL if there is no match.
11199 static void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
11200 int h; /* A hash on key */
11201 HashElem *elem; /* The element that matches key */
11202 int (*xHash)(const void*,int); /* The hash function */
11204 if( pH==0 || pH->ht==0 ) return 0;
11205 xHash = hashFunction(pH->keyClass);
11206 assert( xHash!=0 );
11207 h = (*xHash)(pKey,nKey);
11208 assert( (pH->htsize & (pH->htsize-1))==0 );
11209 elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1));
11210 return elem ? elem->data : 0;
11213 /* Insert an element into the hash table pH. The key is pKey,nKey
11214 ** and the data is "data".
11216 ** If no element exists with a matching key, then a new
11217 ** element is created. A copy of the key is made if the copyKey
11218 ** flag is set. NULL is returned.
11220 ** If another element already exists with the same key, then the
11221 ** new data replaces the old data and the old data is returned.
11222 ** The key is not copied in this instance. If a malloc fails, then
11223 ** the new data is returned and the hash table is unchanged.
11225 ** If the "data" parameter to this function is NULL, then the
11226 ** element corresponding to "key" is removed from the hash table.
11228 static void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
11229 int hraw; /* Raw hash value of the key */
11230 int h; /* the hash of the key modulo hash table size */
11231 HashElem *elem; /* Used to loop thru the element list */
11232 HashElem *new_elem; /* New element added to the pH */
11233 int (*xHash)(const void*,int); /* The hash function */
11235 assert( pH!=0 );
11236 xHash = hashFunction(pH->keyClass);
11237 assert( xHash!=0 );
11238 hraw = (*xHash)(pKey, nKey);
11239 assert( (pH->htsize & (pH->htsize-1))==0 );
11240 h = hraw & (pH->htsize-1);
11241 elem = findElementGivenHash(pH,pKey,nKey,h);
11242 if( elem ){
11243 void *old_data = elem->data;
11244 if( data==0 ){
11245 removeElementGivenHash(pH,elem,h);
11246 }else{
11247 elem->data = data;
11249 return old_data;
11251 if( data==0 ) return 0;
11252 new_elem = (HashElem*)pH->xMalloc( sizeof(HashElem) );
11253 if( new_elem==0 ) return data;
11254 if( pH->copyKey && pKey!=0 ){
11255 new_elem->pKey = pH->xMalloc( nKey );
11256 if( new_elem->pKey==0 ){
11257 pH->xFree(new_elem);
11258 return data;
11260 memcpy((void*)new_elem->pKey, pKey, nKey);
11261 }else{
11262 new_elem->pKey = (void*)pKey;
11264 new_elem->nKey = nKey;
11265 pH->count++;
11266 if( pH->htsize==0 ){
11267 rehash(pH,8);
11268 if( pH->htsize==0 ){
11269 pH->count = 0;
11270 if( pH->copyKey ){
11271 pH->xFree(new_elem->pKey);
11273 pH->xFree(new_elem);
11274 return data;
11277 if( pH->count > pH->htsize ){
11278 rehash(pH,pH->htsize*2);
11280 assert( pH->htsize>0 );
11281 assert( (pH->htsize & (pH->htsize-1))==0 );
11282 h = hraw & (pH->htsize-1);
11283 insertElement(pH, &pH->ht[h], new_elem);
11284 new_elem->data = data;
11285 return 0;
11288 /************** End of hash.c ************************************************/
11289 /************** Begin file opcodes.c *****************************************/
11290 /* Automatically generated. Do not edit */
11291 /* See the mkopcodec.awk script for details. */
11292 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
11293 const char *const sqlite3OpcodeNames[] = { "?",
11294 /* 1 */ "MemLoad",
11295 /* 2 */ "VNext",
11296 /* 3 */ "Column",
11297 /* 4 */ "SetCookie",
11298 /* 5 */ "IfMemPos",
11299 /* 6 */ "Sequence",
11300 /* 7 */ "MoveGt",
11301 /* 8 */ "RowKey",
11302 /* 9 */ "OpenWrite",
11303 /* 10 */ "If",
11304 /* 11 */ "Pop",
11305 /* 12 */ "VRowid",
11306 /* 13 */ "CollSeq",
11307 /* 14 */ "OpenRead",
11308 /* 15 */ "Expire",
11309 /* 16 */ "Not",
11310 /* 17 */ "AutoCommit",
11311 /* 18 */ "IntegrityCk",
11312 /* 19 */ "Sort",
11313 /* 20 */ "Function",
11314 /* 21 */ "Noop",
11315 /* 22 */ "Return",
11316 /* 23 */ "NewRowid",
11317 /* 24 */ "IfMemNeg",
11318 /* 25 */ "Variable",
11319 /* 26 */ "String",
11320 /* 27 */ "RealAffinity",
11321 /* 28 */ "ParseSchema",
11322 /* 29 */ "VOpen",
11323 /* 30 */ "Close",
11324 /* 31 */ "CreateIndex",
11325 /* 32 */ "IsUnique",
11326 /* 33 */ "NotFound",
11327 /* 34 */ "Int64",
11328 /* 35 */ "MustBeInt",
11329 /* 36 */ "Halt",
11330 /* 37 */ "Rowid",
11331 /* 38 */ "IdxLT",
11332 /* 39 */ "AddImm",
11333 /* 40 */ "Statement",
11334 /* 41 */ "RowData",
11335 /* 42 */ "MemMax",
11336 /* 43 */ "Push",
11337 /* 44 */ "NotExists",
11338 /* 45 */ "MemIncr",
11339 /* 46 */ "Gosub",
11340 /* 47 */ "Integer",
11341 /* 48 */ "MemInt",
11342 /* 49 */ "Prev",
11343 /* 50 */ "VColumn",
11344 /* 51 */ "CreateTable",
11345 /* 52 */ "Last",
11346 /* 53 */ "IncrVacuum",
11347 /* 54 */ "IdxRowid",
11348 /* 55 */ "MakeIdxRec",
11349 /* 56 */ "ResetCount",
11350 /* 57 */ "FifoWrite",
11351 /* 58 */ "Callback",
11352 /* 59 */ "ContextPush",
11353 /* 60 */ "Or",
11354 /* 61 */ "And",
11355 /* 62 */ "DropTrigger",
11356 /* 63 */ "DropIndex",
11357 /* 64 */ "IdxGE",
11358 /* 65 */ "IsNull",
11359 /* 66 */ "NotNull",
11360 /* 67 */ "Ne",
11361 /* 68 */ "Eq",
11362 /* 69 */ "Gt",
11363 /* 70 */ "Le",
11364 /* 71 */ "Lt",
11365 /* 72 */ "Ge",
11366 /* 73 */ "IdxDelete",
11367 /* 74 */ "BitAnd",
11368 /* 75 */ "BitOr",
11369 /* 76 */ "ShiftLeft",
11370 /* 77 */ "ShiftRight",
11371 /* 78 */ "Add",
11372 /* 79 */ "Subtract",
11373 /* 80 */ "Multiply",
11374 /* 81 */ "Divide",
11375 /* 82 */ "Remainder",
11376 /* 83 */ "Concat",
11377 /* 84 */ "Vacuum",
11378 /* 85 */ "Negative",
11379 /* 86 */ "MoveLe",
11380 /* 87 */ "BitNot",
11381 /* 88 */ "String8",
11382 /* 89 */ "IfNot",
11383 /* 90 */ "DropTable",
11384 /* 91 */ "MakeRecord",
11385 /* 92 */ "Delete",
11386 /* 93 */ "AggFinal",
11387 /* 94 */ "Dup",
11388 /* 95 */ "Goto",
11389 /* 96 */ "TableLock",
11390 /* 97 */ "FifoRead",
11391 /* 98 */ "Clear",
11392 /* 99 */ "IdxGT",
11393 /* 100 */ "MoveLt",
11394 /* 101 */ "VerifyCookie",
11395 /* 102 */ "AggStep",
11396 /* 103 */ "Pull",
11397 /* 104 */ "SetNumColumns",
11398 /* 105 */ "AbsValue",
11399 /* 106 */ "Transaction",
11400 /* 107 */ "VFilter",
11401 /* 108 */ "VDestroy",
11402 /* 109 */ "ContextPop",
11403 /* 110 */ "Next",
11404 /* 111 */ "IdxInsert",
11405 /* 112 */ "Distinct",
11406 /* 113 */ "Insert",
11407 /* 114 */ "Destroy",
11408 /* 115 */ "ReadCookie",
11409 /* 116 */ "ForceInt",
11410 /* 117 */ "LoadAnalysis",
11411 /* 118 */ "Explain",
11412 /* 119 */ "IfMemZero",
11413 /* 120 */ "OpenPseudo",
11414 /* 121 */ "OpenEphemeral",
11415 /* 122 */ "Null",
11416 /* 123 */ "Blob",
11417 /* 124 */ "MemStore",
11418 /* 125 */ "Real",
11419 /* 126 */ "HexBlob",
11420 /* 127 */ "Rewind",
11421 /* 128 */ "MoveGe",
11422 /* 129 */ "VBegin",
11423 /* 130 */ "VUpdate",
11424 /* 131 */ "VCreate",
11425 /* 132 */ "MemMove",
11426 /* 133 */ "MemNull",
11427 /* 134 */ "Found",
11428 /* 135 */ "NullRow",
11429 /* 136 */ "NotUsed_136",
11430 /* 137 */ "NotUsed_137",
11431 /* 138 */ "ToText",
11432 /* 139 */ "ToBlob",
11433 /* 140 */ "ToNumeric",
11434 /* 141 */ "ToInt",
11435 /* 142 */ "ToReal",
11437 #endif
11439 /************** End of opcodes.c *********************************************/
11440 /************** Begin file os_os2.c ******************************************/
11442 ** 2006 Feb 14
11444 ** The author disclaims copyright to this source code. In place of
11445 ** a legal notice, here is a blessing:
11447 ** May you do good and not evil.
11448 ** May you find forgiveness for yourself and forgive others.
11449 ** May you share freely, never taking more than you give.
11451 ******************************************************************************
11453 ** This file contains code that is specific to OS/2.
11456 #if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
11457 /* os2safe.h has to be included before os2.h, needed for high mem */
11458 #include <os2safe.h>
11459 #endif
11462 #if OS_OS2
11465 ** Macros used to determine whether or not to use threads.
11467 #if defined(THREADSAFE) && THREADSAFE
11468 # define SQLITE_OS2_THREADS 1
11469 #endif
11472 ** Include code that is common to all os_*.c files
11474 /************** Include os_common.h in the middle of os_os2.c ****************/
11475 /************** Begin file os_common.h ***************************************/
11477 ** 2004 May 22
11479 ** The author disclaims copyright to this source code. In place of
11480 ** a legal notice, here is a blessing:
11482 ** May you do good and not evil.
11483 ** May you find forgiveness for yourself and forgive others.
11484 ** May you share freely, never taking more than you give.
11486 ******************************************************************************
11488 ** This file contains macros and a little bit of code that is common to
11489 ** all of the platform-specific files (os_*.c) and is #included into those
11490 ** files.
11492 ** This file should be #included by the os_*.c files only. It is not a
11493 ** general purpose header file.
11497 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
11498 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
11499 ** switch. The following code should catch this problem at compile-time.
11501 #ifdef MEMORY_DEBUG
11502 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
11503 #endif
11507 * When testing, this global variable stores the location of the
11508 * pending-byte in the database file.
11510 #ifdef SQLITE_TEST
11511 unsigned int sqlite3_pending_byte = 0x40000000;
11512 #endif
11514 int sqlite3_os_trace = 0;
11515 #ifdef SQLITE_DEBUG
11516 #define OSTRACE1(X) if( sqlite3_os_trace ) sqlite3DebugPrintf(X)
11517 #define OSTRACE2(X,Y) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y)
11518 #define OSTRACE3(X,Y,Z) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z)
11519 #define OSTRACE4(X,Y,Z,A) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A)
11520 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A,B)
11521 #define OSTRACE6(X,Y,Z,A,B,C) \
11522 if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
11523 #define OSTRACE7(X,Y,Z,A,B,C,D) \
11524 if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
11525 #else
11526 #define OSTRACE1(X)
11527 #define OSTRACE2(X,Y)
11528 #define OSTRACE3(X,Y,Z)
11529 #define OSTRACE4(X,Y,Z,A)
11530 #define OSTRACE5(X,Y,Z,A,B)
11531 #define OSTRACE6(X,Y,Z,A,B,C)
11532 #define OSTRACE7(X,Y,Z,A,B,C,D)
11533 #endif
11536 ** Macros for performance tracing. Normally turned off. Only works
11537 ** on i486 hardware.
11539 #ifdef SQLITE_PERFORMANCE_TRACE
11540 __inline__ unsigned long long int hwtime(void){
11541 unsigned long long int x;
11542 __asm__("rdtsc\n\t"
11543 "mov %%edx, %%ecx\n\t"
11544 :"=A" (x));
11545 return x;
11547 static unsigned long long int g_start;
11548 static unsigned int elapse;
11549 #define TIMER_START g_start=hwtime()
11550 #define TIMER_END elapse=hwtime()-g_start
11551 #define TIMER_ELAPSED elapse
11552 #else
11553 #define TIMER_START
11554 #define TIMER_END
11555 #define TIMER_ELAPSED 0
11556 #endif
11559 ** If we compile with the SQLITE_TEST macro set, then the following block
11560 ** of code will give us the ability to simulate a disk I/O error. This
11561 ** is used for testing the I/O recovery logic.
11563 #ifdef SQLITE_TEST
11564 int sqlite3_io_error_hit = 0;
11565 int sqlite3_io_error_pending = 0;
11566 int sqlite3_io_error_persist = 0;
11567 int sqlite3_diskfull_pending = 0;
11568 int sqlite3_diskfull = 0;
11569 #define SimulateIOError(CODE) \
11570 if( sqlite3_io_error_pending || sqlite3_io_error_hit ) \
11571 if( sqlite3_io_error_pending-- == 1 \
11572 || (sqlite3_io_error_persist && sqlite3_io_error_hit) ) \
11573 { local_ioerr(); CODE; }
11574 static void local_ioerr(){
11575 IOTRACE(("IOERR\n"));
11576 sqlite3_io_error_hit = 1;
11578 #define SimulateDiskfullError(CODE) \
11579 if( sqlite3_diskfull_pending ){ \
11580 if( sqlite3_diskfull_pending == 1 ){ \
11581 local_ioerr(); \
11582 sqlite3_diskfull = 1; \
11583 sqlite3_io_error_hit = 1; \
11584 CODE; \
11585 }else{ \
11586 sqlite3_diskfull_pending--; \
11589 #else
11590 #define SimulateIOError(A)
11591 #define SimulateDiskfullError(A)
11592 #endif
11595 ** When testing, keep a count of the number of open files.
11597 #ifdef SQLITE_TEST
11598 int sqlite3_open_file_count = 0;
11599 #define OpenCounter(X) sqlite3_open_file_count+=(X)
11600 #else
11601 #define OpenCounter(X)
11602 #endif
11605 ** sqlite3GenericMalloc
11606 ** sqlite3GenericRealloc
11607 ** sqlite3GenericOsFree
11608 ** sqlite3GenericAllocationSize
11610 ** Implementation of the os level dynamic memory allocation interface in terms
11611 ** of the standard malloc(), realloc() and free() found in many operating
11612 ** systems. No rocket science here.
11614 ** There are two versions of these four functions here. The version
11615 ** implemented here is only used if memory-management or memory-debugging is
11616 ** enabled. This version allocates an extra 8-bytes at the beginning of each
11617 ** block and stores the size of the allocation there.
11619 ** If neither memory-management or debugging is enabled, the second
11620 ** set of implementations is used instead.
11622 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || defined (SQLITE_MEMDEBUG)
11623 static void *sqlite3GenericMalloc(int n){
11624 char *p = (char *)malloc(n+8);
11625 assert(n>0);
11626 assert(sizeof(int)<=8);
11627 if( p ){
11628 *(int *)p = n;
11629 p += 8;
11631 return (void *)p;
11633 static void *sqlite3GenericRealloc(void *p, int n){
11634 char *p2 = ((char *)p - 8);
11635 assert(n>0);
11636 p2 = (char*)realloc(p2, n+8);
11637 if( p2 ){
11638 *(int *)p2 = n;
11639 p2 += 8;
11641 return (void *)p2;
11643 static void sqlite3GenericFree(void *p){
11644 assert(p);
11645 free((void *)((char *)p - 8));
11647 static int sqlite3GenericAllocationSize(void *p){
11648 return p ? *(int *)((char *)p - 8) : 0;
11650 #else
11651 static void *sqlite3GenericMalloc(int n){
11652 char *p = (char *)malloc(n);
11653 return (void *)p;
11655 static void *sqlite3GenericRealloc(void *p, int n){
11656 assert(n>0);
11657 p = realloc(p, n);
11658 return p;
11660 static void sqlite3GenericFree(void *p){
11661 assert(p);
11662 free(p);
11664 /* Never actually used, but needed for the linker */
11665 static int sqlite3GenericAllocationSize(void *p){ return 0; }
11666 #endif
11669 ** The default size of a disk sector
11671 #ifndef PAGER_SECTOR_SIZE
11672 # define PAGER_SECTOR_SIZE 512
11673 #endif
11675 /************** End of os_common.h *******************************************/
11676 /************** Continuing where we left off in os_os2.c *********************/
11679 ** The os2File structure is subclass of OsFile specific for the OS/2
11680 ** protability layer.
11682 typedef struct os2File os2File;
11683 struct os2File {
11684 IoMethod const *pMethod; /* Always the first entry */
11685 HFILE h; /* Handle for accessing the file */
11686 int delOnClose; /* True if file is to be deleted on close */
11687 char* pathToDel; /* Name of file to delete on close */
11688 unsigned char locktype; /* Type of lock currently held on this file */
11692 ** Do not include any of the File I/O interface procedures if the
11693 ** SQLITE_OMIT_DISKIO macro is defined (indicating that there database
11694 ** will be in-memory only)
11696 #ifndef SQLITE_OMIT_DISKIO
11699 ** Delete the named file
11701 static int sqlite3Os2Delete( const char *zFilename ){
11702 APIRET rc = NO_ERROR;
11704 rc = DosDelete( (PSZ)zFilename );
11705 OSTRACE2( "DELETE \"%s\"\n", zFilename );
11706 return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
11710 ** Return TRUE if the named file exists.
11712 static int sqlite3Os2FileExists( const char *zFilename ){
11713 FILESTATUS3 fsts3ConfigInfo;
11714 memset(&fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo));
11715 return DosQueryPathInfo( (PSZ)zFilename, FIL_STANDARD,
11716 &fsts3ConfigInfo, sizeof(FILESTATUS3) ) == NO_ERROR;
11719 /* Forward declaration */
11720 int allocateOs2File( os2File *pInit, OsFile **pld );
11723 ** Attempt to open a file for both reading and writing. If that
11724 ** fails, try opening it read-only. If the file does not exist,
11725 ** try to create it.
11727 ** On success, a handle for the open file is written to *id
11728 ** and *pReadonly is set to 0 if the file was opened for reading and
11729 ** writing or 1 if the file was opened read-only. The function returns
11730 ** SQLITE_OK.
11732 ** On failure, the function returns SQLITE_CANTOPEN and leaves
11733 ** *id and *pReadonly unchanged.
11735 static int sqlite3Os2OpenReadWrite(
11736 const char *zFilename,
11737 OsFile **pld,
11738 int *pReadonly
11740 os2File f;
11741 HFILE hf;
11742 ULONG ulAction;
11743 APIRET rc = NO_ERROR;
11745 assert( *pld == 0 );
11746 rc = DosOpen( (PSZ)zFilename, &hf, &ulAction, 0L,
11747 FILE_ARCHIVED | FILE_NORMAL,
11748 OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS,
11749 OPEN_FLAGS_FAIL_ON_ERROR | OPEN_FLAGS_RANDOM |
11750 OPEN_SHARE_DENYNONE | OPEN_ACCESS_READWRITE, (PEAOP2)NULL );
11751 if( rc != NO_ERROR ){
11752 rc = DosOpen( (PSZ)zFilename, &hf, &ulAction, 0L,
11753 FILE_ARCHIVED | FILE_NORMAL,
11754 OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS,
11755 OPEN_FLAGS_FAIL_ON_ERROR | OPEN_FLAGS_RANDOM |
11756 OPEN_SHARE_DENYWRITE | OPEN_ACCESS_READONLY, (PEAOP2)NULL );
11757 if( rc != NO_ERROR ){
11758 return SQLITE_CANTOPEN;
11760 *pReadonly = 1;
11762 else{
11763 *pReadonly = 0;
11765 f.h = hf;
11766 f.locktype = NO_LOCK;
11767 f.delOnClose = 0;
11768 f.pathToDel = NULL;
11769 OpenCounter(+1);
11770 OSTRACE3( "OPEN R/W %d \"%s\"\n", hf, zFilename );
11771 return allocateOs2File( &f, pld );
11776 ** Attempt to open a new file for exclusive access by this process.
11777 ** The file will be opened for both reading and writing. To avoid
11778 ** a potential security problem, we do not allow the file to have
11779 ** previously existed. Nor do we allow the file to be a symbolic
11780 ** link.
11782 ** If delFlag is true, then make arrangements to automatically delete
11783 ** the file when it is closed.
11785 ** On success, write the file handle into *id and return SQLITE_OK.
11787 ** On failure, return SQLITE_CANTOPEN.
11789 static int sqlite3Os2OpenExclusive( const char *zFilename, OsFile **pld, int delFlag ){
11790 os2File f;
11791 HFILE hf;
11792 ULONG ulAction;
11793 APIRET rc = NO_ERROR;
11795 assert( *pld == 0 );
11796 rc = DosOpen( (PSZ)zFilename, &hf, &ulAction, 0L, FILE_NORMAL,
11797 OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_REPLACE_IF_EXISTS,
11798 OPEN_FLAGS_FAIL_ON_ERROR | OPEN_FLAGS_RANDOM |
11799 OPEN_SHARE_DENYREADWRITE | OPEN_ACCESS_READWRITE, (PEAOP2)NULL );
11800 if( rc != NO_ERROR ){
11801 return SQLITE_CANTOPEN;
11804 f.h = hf;
11805 f.locktype = NO_LOCK;
11806 f.delOnClose = delFlag ? 1 : 0;
11807 f.pathToDel = delFlag ? sqlite3OsFullPathname( zFilename ) : NULL;
11808 OpenCounter( +1 );
11809 if( delFlag ) DosForceDelete( sqlite3OsFullPathname( zFilename ) );
11810 OSTRACE3( "OPEN EX %d \"%s\"\n", hf, sqlite3OsFullPathname ( zFilename ) );
11811 return allocateOs2File( &f, pld );
11815 ** Attempt to open a new file for read-only access.
11817 ** On success, write the file handle into *id and return SQLITE_OK.
11819 ** On failure, return SQLITE_CANTOPEN.
11821 static int sqlite3Os2OpenReadOnly( const char *zFilename, OsFile **pld ){
11822 os2File f;
11823 HFILE hf;
11824 ULONG ulAction;
11825 APIRET rc = NO_ERROR;
11827 assert( *pld == 0 );
11828 rc = DosOpen( (PSZ)zFilename, &hf, &ulAction, 0L,
11829 FILE_NORMAL, OPEN_ACTION_OPEN_IF_EXISTS,
11830 OPEN_FLAGS_FAIL_ON_ERROR | OPEN_FLAGS_RANDOM |
11831 OPEN_SHARE_DENYWRITE | OPEN_ACCESS_READONLY, (PEAOP2)NULL );
11832 if( rc != NO_ERROR ){
11833 return SQLITE_CANTOPEN;
11835 f.h = hf;
11836 f.locktype = NO_LOCK;
11837 f.delOnClose = 0;
11838 f.pathToDel = NULL;
11839 OpenCounter( +1 );
11840 OSTRACE3( "OPEN RO %d \"%s\"\n", hf, zFilename );
11841 return allocateOs2File( &f, pld );
11845 ** Attempt to open a file descriptor for the directory that contains a
11846 ** file. This file descriptor can be used to fsync() the directory
11847 ** in order to make sure the creation of a new file is actually written
11848 ** to disk.
11850 ** This routine is only meaningful for Unix. It is a no-op under
11851 ** OS/2 since OS/2 does not support hard links.
11853 ** On success, a handle for a previously open file is at *id is
11854 ** updated with the new directory file descriptor and SQLITE_OK is
11855 ** returned.
11857 ** On failure, the function returns SQLITE_CANTOPEN and leaves
11858 ** *id unchanged.
11860 int os2OpenDirectory(
11861 OsFile *id,
11862 const char *zDirname
11864 return SQLITE_OK;
11868 ** Create a temporary file name in zBuf. zBuf must be big enough to
11869 ** hold at least SQLITE_TEMPNAME_SIZE characters.
11871 static int sqlite3Os2TempFileName( char *zBuf ){
11872 static const unsigned char zChars[] =
11873 "abcdefghijklmnopqrstuvwxyz"
11874 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
11875 "0123456789";
11876 int i, j;
11877 PSZ zTempPath = 0;
11878 if( DosScanEnv( "TEMP", &zTempPath ) ){
11879 if( DosScanEnv( "TMP", &zTempPath ) ){
11880 if( DosScanEnv( "TMPDIR", &zTempPath ) ){
11881 ULONG ulDriveNum = 0, ulDriveMap = 0;
11882 DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
11883 sprintf( zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
11887 for(;;){
11888 sprintf( zBuf, "%s\\"TEMP_FILE_PREFIX, zTempPath );
11889 j = strlen( zBuf );
11890 sqlite3Randomness( 15, &zBuf[j] );
11891 for( i = 0; i < 15; i++, j++ ){
11892 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
11894 zBuf[j] = 0;
11895 if( !sqlite3OsFileExists( zBuf ) ) break;
11897 OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
11898 return SQLITE_OK;
11902 ** Close a file.
11904 int os2Close( OsFile **pld ){
11905 os2File *pFile;
11906 APIRET rc = NO_ERROR;
11907 if( pld && (pFile = (os2File*)*pld) != 0 ){
11908 OSTRACE2( "CLOSE %d\n", pFile->h );
11909 rc = DosClose( pFile->h );
11910 pFile->locktype = NO_LOCK;
11911 if( pFile->delOnClose != 0 ){
11912 rc = DosForceDelete( pFile->pathToDel );
11914 *pld = 0;
11915 OpenCounter( -1 );
11918 return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
11922 ** Read data from a file into a buffer. Return SQLITE_OK if all
11923 ** bytes were read successfully and SQLITE_IOERR if anything goes
11924 ** wrong.
11926 int os2Read( OsFile *id, void *pBuf, int amt ){
11927 ULONG got;
11928 assert( id!=0 );
11929 SimulateIOError( return SQLITE_IOERR );
11930 OSTRACE3( "READ %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
11931 DosRead( ((os2File*)id)->h, pBuf, amt, &got );
11932 if (got == (ULONG)amt)
11933 return SQLITE_OK;
11934 else if (got < 0)
11935 return SQLITE_IOERR_READ;
11936 else {
11937 memset(&((char*)pBuf)[got], 0, amt-got);
11938 return SQLITE_IOERR_SHORT_READ;
11943 ** Write data from a buffer into a file. Return SQLITE_OK on success
11944 ** or some other error code on failure.
11946 int os2Write( OsFile *id, const void *pBuf, int amt ){
11947 APIRET rc = NO_ERROR;
11948 ULONG wrote;
11949 assert( id!=0 );
11950 SimulateIOError( return SQLITE_IOERR );
11951 SimulateDiskfullError( return SQLITE_FULL );
11952 OSTRACE3( "WRITE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
11953 while( amt > 0 &&
11954 (rc = DosWrite( ((os2File*)id)->h, (PVOID)pBuf, amt, &wrote )) && wrote > 0 ){
11955 amt -= wrote;
11956 pBuf = &((char*)pBuf)[wrote];
11959 return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
11963 ** Move the read/write pointer in a file.
11965 int os2Seek( OsFile *id, i64 offset ){
11966 APIRET rc = NO_ERROR;
11967 ULONG filePointer = 0L;
11968 assert( id!=0 );
11969 rc = DosSetFilePtr( ((os2File*)id)->h, offset, FILE_BEGIN, &filePointer );
11970 OSTRACE3( "SEEK %d %lld\n", ((os2File*)id)->h, offset );
11971 return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
11975 ** Make sure all writes to a particular file are committed to disk.
11977 int os2Sync( OsFile *id, int dataOnly ){
11978 assert( id!=0 );
11979 OSTRACE3( "SYNC %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
11980 return DosResetBuffer( ((os2File*)id)->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
11984 ** Sync the directory zDirname. This is a no-op on operating systems other
11985 ** than UNIX.
11987 static int sqlite3Os2SyncDirectory( const char *zDirname ){
11988 SimulateIOError( return SQLITE_IOERR );
11989 return SQLITE_OK;
11993 ** Truncate an open file to a specified size
11995 int os2Truncate( OsFile *id, i64 nByte ){
11996 APIRET rc = NO_ERROR;
11997 ULONG upperBits = nByte>>32;
11998 assert( id!=0 );
11999 OSTRACE3( "TRUNCATE %d %lld\n", ((os2File*)id)->h, nByte );
12000 SimulateIOError( return SQLITE_IOERR );
12001 rc = DosSetFilePtr( ((os2File*)id)->h, nByte, FILE_BEGIN, &upperBits );
12002 if( rc != NO_ERROR ){
12003 return SQLITE_IOERR;
12005 rc = DosSetFilePtr( ((os2File*)id)->h, 0L, FILE_END, &upperBits );
12006 return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
12010 ** Determine the current size of a file in bytes
12012 int os2FileSize( OsFile *id, i64 *pSize ){
12013 APIRET rc = NO_ERROR;
12014 FILESTATUS3 fsts3FileInfo;
12015 memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
12016 assert( id!=0 );
12017 SimulateIOError( return SQLITE_IOERR );
12018 rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
12019 if( rc == NO_ERROR ){
12020 *pSize = fsts3FileInfo.cbFile;
12021 return SQLITE_OK;
12023 else{
12024 return SQLITE_IOERR;
12029 ** Acquire a reader lock.
12031 static int getReadLock( os2File *id ){
12032 FILELOCK LockArea,
12033 UnlockArea;
12034 memset(&LockArea, 0, sizeof(LockArea));
12035 memset(&UnlockArea, 0, sizeof(UnlockArea));
12036 LockArea.lOffset = SHARED_FIRST;
12037 LockArea.lRange = SHARED_SIZE;
12038 UnlockArea.lOffset = 0L;
12039 UnlockArea.lRange = 0L;
12040 return DosSetFileLocks( id->h, &UnlockArea, &LockArea, 2000L, 1L );
12044 ** Undo a readlock
12046 static int unlockReadLock( os2File *id ){
12047 FILELOCK LockArea,
12048 UnlockArea;
12049 memset(&LockArea, 0, sizeof(LockArea));
12050 memset(&UnlockArea, 0, sizeof(UnlockArea));
12051 LockArea.lOffset = 0L;
12052 LockArea.lRange = 0L;
12053 UnlockArea.lOffset = SHARED_FIRST;
12054 UnlockArea.lRange = SHARED_SIZE;
12055 return DosSetFileLocks( id->h, &UnlockArea, &LockArea, 2000L, 1L );
12058 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
12060 ** Check that a given pathname is a directory and is writable
12063 static int sqlite3Os2IsDirWritable( char *zDirname ){
12064 FILESTATUS3 fsts3ConfigInfo;
12065 APIRET rc = NO_ERROR;
12066 memset(&fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo));
12067 if( zDirname==0 ) return 0;
12068 if( strlen(zDirname)>CCHMAXPATH ) return 0;
12069 rc = DosQueryPathInfo( (PSZ)zDirname, FIL_STANDARD, &fsts3ConfigInfo, sizeof(FILESTATUS3) );
12070 if( rc != NO_ERROR ) return 0;
12071 if( (fsts3ConfigInfo.attrFile & FILE_DIRECTORY) != FILE_DIRECTORY ) return 0;
12073 return 1;
12075 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
12078 ** Lock the file with the lock specified by parameter locktype - one
12079 ** of the following:
12081 ** (1) SHARED_LOCK
12082 ** (2) RESERVED_LOCK
12083 ** (3) PENDING_LOCK
12084 ** (4) EXCLUSIVE_LOCK
12086 ** Sometimes when requesting one lock state, additional lock states
12087 ** are inserted in between. The locking might fail on one of the later
12088 ** transitions leaving the lock state different from what it started but
12089 ** still short of its goal. The following chart shows the allowed
12090 ** transitions and the inserted intermediate states:
12092 ** UNLOCKED -> SHARED
12093 ** SHARED -> RESERVED
12094 ** SHARED -> (PENDING) -> EXCLUSIVE
12095 ** RESERVED -> (PENDING) -> EXCLUSIVE
12096 ** PENDING -> EXCLUSIVE
12098 ** This routine will only increase a lock. The os2Unlock() routine
12099 ** erases all locks at once and returns us immediately to locking level 0.
12100 ** It is not possible to lower the locking level one step at a time. You
12101 ** must go straight to locking level 0.
12103 int os2Lock( OsFile *id, int locktype ){
12104 APIRET rc = SQLITE_OK; /* Return code from subroutines */
12105 APIRET res = NO_ERROR; /* Result of an OS/2 lock call */
12106 int newLocktype; /* Set id->locktype to this value before exiting */
12107 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
12108 FILELOCK LockArea,
12109 UnlockArea;
12110 os2File *pFile = (os2File*)id;
12111 memset(&LockArea, 0, sizeof(LockArea));
12112 memset(&UnlockArea, 0, sizeof(UnlockArea));
12113 assert( pFile!=0 );
12114 OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
12116 /* If there is already a lock of this type or more restrictive on the
12117 ** OsFile, do nothing. Don't use the end_lock: exit path, as
12118 ** sqlite3OsEnterMutex() hasn't been called yet.
12120 if( pFile->locktype>=locktype ){
12121 return SQLITE_OK;
12124 /* Make sure the locking sequence is correct
12126 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
12127 assert( locktype!=PENDING_LOCK );
12128 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
12130 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
12131 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
12132 ** the PENDING_LOCK byte is temporary.
12134 newLocktype = pFile->locktype;
12135 if( pFile->locktype==NO_LOCK
12136 || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
12138 int cnt = 3;
12140 LockArea.lOffset = PENDING_BYTE;
12141 LockArea.lRange = 1L;
12142 UnlockArea.lOffset = 0L;
12143 UnlockArea.lRange = 0L;
12145 while( cnt-->0 && (res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L) )!=NO_ERROR ){
12146 /* Try 3 times to get the pending lock. The pending lock might be
12147 ** held by another reader process who will release it momentarily.
12149 OSTRACE2( "could not get a PENDING lock. cnt=%d\n", cnt );
12150 DosSleep(1);
12152 gotPendingLock = res;
12155 /* Acquire a shared lock
12157 if( locktype==SHARED_LOCK && res ){
12158 assert( pFile->locktype==NO_LOCK );
12159 res = getReadLock(pFile);
12160 if( res == NO_ERROR ){
12161 newLocktype = SHARED_LOCK;
12165 /* Acquire a RESERVED lock
12167 if( locktype==RESERVED_LOCK && res ){
12168 assert( pFile->locktype==SHARED_LOCK );
12169 LockArea.lOffset = RESERVED_BYTE;
12170 LockArea.lRange = 1L;
12171 UnlockArea.lOffset = 0L;
12172 UnlockArea.lRange = 0L;
12173 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
12174 if( res == NO_ERROR ){
12175 newLocktype = RESERVED_LOCK;
12179 /* Acquire a PENDING lock
12181 if( locktype==EXCLUSIVE_LOCK && res ){
12182 newLocktype = PENDING_LOCK;
12183 gotPendingLock = 0;
12186 /* Acquire an EXCLUSIVE lock
12188 if( locktype==EXCLUSIVE_LOCK && res ){
12189 assert( pFile->locktype>=SHARED_LOCK );
12190 res = unlockReadLock(pFile);
12191 OSTRACE2( "unreadlock = %d\n", res );
12192 LockArea.lOffset = SHARED_FIRST;
12193 LockArea.lRange = SHARED_SIZE;
12194 UnlockArea.lOffset = 0L;
12195 UnlockArea.lRange = 0L;
12196 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
12197 if( res == NO_ERROR ){
12198 newLocktype = EXCLUSIVE_LOCK;
12199 }else{
12200 OSTRACE2( "error-code = %d\n", res );
12204 /* If we are holding a PENDING lock that ought to be released, then
12205 ** release it now.
12207 if( gotPendingLock && locktype==SHARED_LOCK ){
12208 LockArea.lOffset = 0L;
12209 LockArea.lRange = 0L;
12210 UnlockArea.lOffset = PENDING_BYTE;
12211 UnlockArea.lRange = 1L;
12212 DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
12215 /* Update the state of the lock has held in the file descriptor then
12216 ** return the appropriate result code.
12218 if( res == NO_ERROR ){
12219 rc = SQLITE_OK;
12220 }else{
12221 OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
12222 locktype, newLocktype );
12223 rc = SQLITE_BUSY;
12225 pFile->locktype = newLocktype;
12226 return rc;
12230 ** This routine checks if there is a RESERVED lock held on the specified
12231 ** file by this or any other process. If such a lock is held, return
12232 ** non-zero, otherwise zero.
12234 int os2CheckReservedLock( OsFile *id ){
12235 APIRET rc = NO_ERROR;
12236 os2File *pFile = (os2File*)id;
12237 assert( pFile!=0 );
12238 if( pFile->locktype>=RESERVED_LOCK ){
12239 rc = 1;
12240 OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, rc );
12241 }else{
12242 FILELOCK LockArea,
12243 UnlockArea;
12244 memset(&LockArea, 0, sizeof(LockArea));
12245 memset(&UnlockArea, 0, sizeof(UnlockArea));
12246 LockArea.lOffset = RESERVED_BYTE;
12247 LockArea.lRange = 1L;
12248 UnlockArea.lOffset = 0L;
12249 UnlockArea.lRange = 0L;
12250 rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
12251 if( rc == NO_ERROR ){
12252 LockArea.lOffset = 0L;
12253 LockArea.lRange = 0L;
12254 UnlockArea.lOffset = RESERVED_BYTE;
12255 UnlockArea.lRange = 1L;
12256 rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
12258 OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, rc );
12260 return rc;
12264 ** Lower the locking level on file descriptor id to locktype. locktype
12265 ** must be either NO_LOCK or SHARED_LOCK.
12267 ** If the locking level of the file descriptor is already at or below
12268 ** the requested locking level, this routine is a no-op.
12270 ** It is not possible for this routine to fail if the second argument
12271 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
12272 ** might return SQLITE_IOERR;
12274 int os2Unlock( OsFile *id, int locktype ){
12275 int type;
12276 APIRET rc = SQLITE_OK;
12277 os2File *pFile = (os2File*)id;
12278 FILELOCK LockArea,
12279 UnlockArea;
12280 memset(&LockArea, 0, sizeof(LockArea));
12281 memset(&UnlockArea, 0, sizeof(UnlockArea));
12282 assert( pFile!=0 );
12283 assert( locktype<=SHARED_LOCK );
12284 OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
12285 type = pFile->locktype;
12286 if( type>=EXCLUSIVE_LOCK ){
12287 LockArea.lOffset = 0L;
12288 LockArea.lRange = 0L;
12289 UnlockArea.lOffset = SHARED_FIRST;
12290 UnlockArea.lRange = SHARED_SIZE;
12291 DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
12292 if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
12293 /* This should never happen. We should always be able to
12294 ** reacquire the read lock */
12295 rc = SQLITE_IOERR;
12298 if( type>=RESERVED_LOCK ){
12299 LockArea.lOffset = 0L;
12300 LockArea.lRange = 0L;
12301 UnlockArea.lOffset = RESERVED_BYTE;
12302 UnlockArea.lRange = 1L;
12303 DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
12305 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
12306 unlockReadLock(pFile);
12308 if( type>=PENDING_LOCK ){
12309 LockArea.lOffset = 0L;
12310 LockArea.lRange = 0L;
12311 UnlockArea.lOffset = PENDING_BYTE;
12312 UnlockArea.lRange = 1L;
12313 DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 2000L, 1L );
12315 pFile->locktype = locktype;
12316 return rc;
12320 ** Turn a relative pathname into a full pathname. Return a pointer
12321 ** to the full pathname stored in space obtained from sqliteMalloc().
12322 ** The calling function is responsible for freeing this space once it
12323 ** is no longer needed.
12325 static char *sqlite3Os2FullPathname( const char *zRelative ){
12326 char *zFull = 0;
12327 if( strchr(zRelative, ':') ){
12328 sqlite3SetString( &zFull, zRelative, (char*)0 );
12329 }else{
12330 char zBuff[SQLITE_TEMPNAME_SIZE - 2] = {0};
12331 char zDrive[1] = {0};
12332 ULONG cbzFullLen = SQLITE_TEMPNAME_SIZE;
12333 ULONG ulDriveNum = 0;
12334 ULONG ulDriveMap = 0;
12335 DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
12336 DosQueryCurrentDir( 0L, zBuff, &cbzFullLen );
12337 zFull = sqliteMalloc( cbzFullLen );
12338 sprintf( zDrive, "%c", (char)('A' + ulDriveNum - 1) );
12339 sqlite3SetString( &zFull, zDrive, ":\\", zBuff, "\\", zRelative, (char*)0 );
12341 return zFull;
12345 ** The fullSync option is meaningless on os2, or correct me if I'm wrong. This is a no-op.
12346 ** From os_unix.c: Change the value of the fullsync flag in the given file descriptor.
12347 ** From os_unix.c: ((unixFile*)id)->fullSync = v;
12349 static void os2SetFullSync( OsFile *id, int v ){
12350 return;
12354 ** Return the underlying file handle for an OsFile
12356 static int os2FileHandle( OsFile *id ){
12357 return (int)((os2File*)id)->h;
12361 ** Return an integer that indices the type of lock currently held
12362 ** by this handle. (Used for testing and analysis only.)
12364 static int os2LockState( OsFile *id ){
12365 return ((os2File*)id)->locktype;
12369 ** Return the sector size in bytes of the underlying block device for
12370 ** the specified file. This is almost always 512 bytes, but may be
12371 ** larger for some devices.
12373 ** SQLite code assumes this function cannot fail. It also assumes that
12374 ** if two files are created in the same file-system directory (i.e.
12375 ** a database and it's journal file) that the sector size will be the
12376 ** same for both.
12378 static int os2SectorSize(OsFile *id){
12379 return SQLITE_DEFAULT_SECTOR_SIZE;
12383 ** This vector defines all the methods that can operate on an OsFile
12384 ** for os2.
12386 static const IoMethod sqlite3Os2IoMethod = {
12387 os2Close,
12388 os2OpenDirectory,
12389 os2Read,
12390 os2Write,
12391 os2Seek,
12392 os2Truncate,
12393 os2Sync,
12394 os2SetFullSync,
12395 os2FileHandle,
12396 os2FileSize,
12397 os2Lock,
12398 os2Unlock,
12399 os2LockState,
12400 os2CheckReservedLock,
12401 os2SectorSize,
12405 ** Allocate memory for an OsFile. Initialize the new OsFile
12406 ** to the value given in pInit and return a pointer to the new
12407 ** OsFile. If we run out of memory, close the file and return NULL.
12409 int allocateOs2File( os2File *pInit, OsFile **pld ){
12410 os2File *pNew;
12411 pNew = sqliteMalloc( sizeof(*pNew) );
12412 if( pNew==0 ){
12413 DosClose( pInit->h );
12414 *pld = 0;
12415 return SQLITE_NOMEM;
12416 }else{
12417 *pNew = *pInit;
12418 pNew->pMethod = &sqlite3Os2IoMethod;
12419 pNew->locktype = NO_LOCK;
12420 *pld = (OsFile*)pNew;
12421 OpenCounter(+1);
12422 return SQLITE_OK;
12426 #endif /* SQLITE_OMIT_DISKIO */
12427 /***************************************************************************
12428 ** Everything above deals with file I/O. Everything that follows deals
12429 ** with other miscellanous aspects of the operating system interface
12430 ****************************************************************************/
12432 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12434 ** Interfaces for opening a shared library, finding entry points
12435 ** within the shared library, and closing the shared library.
12437 static void *sqlite3Os2Dlopen(const char *zFilename){
12438 UCHAR loadErr[256];
12439 HMODULE hmod;
12440 APIRET rc;
12441 rc = DosLoadModule(loadErr, sizeof(loadErr), zFilename, &hmod);
12442 if (rc != NO_ERROR) return 0;
12443 return (void*)hmod;
12445 static void *sqlite3Os2Dlsym(void *pHandle, const char *zSymbol){
12446 PFN pfn;
12447 APIRET rc;
12448 rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
12449 if (rc != NO_ERROR) {
12450 /* if the symbol itself was not found, search again for the same
12451 * symbol with an extra underscore, that might be needed depending
12452 * on the calling convention */
12453 char _zSymbol[256] = "_";
12454 strncat(_zSymbol, zSymbol, 255);
12455 rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
12457 if (rc != NO_ERROR) return 0;
12458 return pfn;
12460 static int sqlite3Os2Dlclose(void *pHandle){
12461 return DosFreeModule((HMODULE)pHandle);
12463 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
12467 ** Get information to seed the random number generator. The seed
12468 ** is written into the buffer zBuf[256]. The calling function must
12469 ** supply a sufficiently large buffer.
12471 static int sqlite3Os2RandomSeed( char *zBuf ){
12472 /* We have to initialize zBuf to prevent valgrind from reporting
12473 ** errors. The reports issued by valgrind are incorrect - we would
12474 ** prefer that the randomness be increased by making use of the
12475 ** uninitialized space in zBuf - but valgrind errors tend to worry
12476 ** some users. Rather than argue, it seems easier just to initialize
12477 ** the whole array and silence valgrind, even if that means less randomness
12478 ** in the random seed.
12480 ** When testing, initializing zBuf[] to zero is all we do. That means
12481 ** that we always use the same random number sequence. This makes the
12482 ** tests repeatable.
12484 memset( zBuf, 0, 256 );
12485 DosGetDateTime( (PDATETIME)zBuf );
12486 return SQLITE_OK;
12490 ** Sleep for a little while. Return the amount of time slept.
12492 static int sqlite3Os2Sleep( int ms ){
12493 DosSleep( ms );
12494 return ms;
12498 ** Static variables used for thread synchronization
12500 static int inMutex = 0;
12501 #ifdef SQLITE_OS2_THREADS
12502 static ULONG mutexOwner;
12503 #endif
12506 ** The following pair of routines implement mutual exclusion for
12507 ** multi-threaded processes. Only a single thread is allowed to
12508 ** executed code that is surrounded by EnterMutex() and LeaveMutex().
12510 ** SQLite uses only a single Mutex. There is not much critical
12511 ** code and what little there is executes quickly and without blocking.
12513 static void sqlite3Os2EnterMutex(){
12514 PTIB ptib;
12515 #ifdef SQLITE_OS2_THREADS
12516 DosEnterCritSec();
12517 DosGetInfoBlocks( &ptib, NULL );
12518 mutexOwner = ptib->tib_ptib2->tib2_ultid;
12519 #endif
12520 assert( !inMutex );
12521 inMutex = 1;
12523 static void sqlite3Os2LeaveMutex(){
12524 PTIB ptib;
12525 assert( inMutex );
12526 inMutex = 0;
12527 #ifdef SQLITE_OS2_THREADS
12528 DosGetInfoBlocks( &ptib, NULL );
12529 assert( mutexOwner == ptib->tib_ptib2->tib2_ultid );
12530 DosExitCritSec();
12531 #endif
12535 ** Return TRUE if the mutex is currently held.
12537 ** If the thisThreadOnly parameter is true, return true if and only if the
12538 ** calling thread holds the mutex. If the parameter is false, return
12539 ** true if any thread holds the mutex.
12541 static int sqlite3Os2InMutex( int thisThreadOnly ){
12542 #ifdef SQLITE_OS2_THREADS
12543 PTIB ptib;
12544 DosGetInfoBlocks( &ptib, NULL );
12545 return inMutex>0 && (thisThreadOnly==0 || mutexOwner==ptib->tib_ptib2->tib2_ultid);
12546 #else
12547 return inMutex>0;
12548 #endif
12552 ** The following variable, if set to a non-zero value, becomes the result
12553 ** returned from sqlite3OsCurrentTime(). This is used for testing.
12555 #ifdef SQLITE_TEST
12556 int sqlite3_current_time = 0;
12557 #endif
12560 ** Find the current time (in Universal Coordinated Time). Write the
12561 ** current time and date as a Julian Day number into *prNow and
12562 ** return 0. Return 1 if the time and date cannot be found.
12564 static int sqlite3Os2CurrentTime( double *prNow ){
12565 double now;
12566 USHORT second, minute, hour,
12567 day, month, year;
12568 DATETIME dt;
12569 DosGetDateTime( &dt );
12570 second = (USHORT)dt.seconds;
12571 minute = (USHORT)dt.minutes + dt.timezone;
12572 hour = (USHORT)dt.hours;
12573 day = (USHORT)dt.day;
12574 month = (USHORT)dt.month;
12575 year = (USHORT)dt.year;
12577 /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
12578 http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
12579 /* Calculate the Julian days */
12580 now = day - 32076 +
12581 1461*(year + 4800 + (month - 14)/12)/4 +
12582 367*(month - 2 - (month - 14)/12*12)/12 -
12583 3*((year + 4900 + (month - 14)/12)/100)/4;
12585 /* Add the fractional hours, mins and seconds */
12586 now += (hour + 12.0)/24.0;
12587 now += minute/1440.0;
12588 now += second/86400.0;
12589 *prNow = now;
12590 #ifdef SQLITE_TEST
12591 if( sqlite3_current_time ){
12592 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
12594 #endif
12595 return 0;
12599 ** Remember the number of thread-specific-data blocks allocated.
12600 ** Use this to verify that we are not leaking thread-specific-data.
12601 ** Ticket #1601
12603 #ifdef SQLITE_TEST
12604 int sqlite3_tsd_count = 0;
12605 # define TSD_COUNTER_INCR InterlockedIncrement( &sqlite3_tsd_count )
12606 # define TSD_COUNTER_DECR InterlockedDecrement( &sqlite3_tsd_count )
12607 #else
12608 # define TSD_COUNTER_INCR /* no-op */
12609 # define TSD_COUNTER_DECR /* no-op */
12610 #endif
12613 ** If called with allocateFlag>1, then return a pointer to thread
12614 ** specific data for the current thread. Allocate and zero the
12615 ** thread-specific data if it does not already exist necessary.
12617 ** If called with allocateFlag==0, then check the current thread
12618 ** specific data. Return it if it exists. If it does not exist,
12619 ** then return NULL.
12621 ** If called with allocateFlag<0, check to see if the thread specific
12622 ** data is allocated and is all zero. If it is then deallocate it.
12623 ** Return a pointer to the thread specific data or NULL if it is
12624 ** unallocated or gets deallocated.
12626 static ThreadData *sqlite3Os2ThreadSpecificData( int allocateFlag ){
12627 static ThreadData **s_ppTsd = NULL;
12628 static const ThreadData zeroData = {0, 0, 0};
12629 ThreadData *pTsd;
12631 if( !s_ppTsd ){
12632 sqlite3OsEnterMutex();
12633 if( !s_ppTsd ){
12634 PULONG pul;
12635 APIRET rc = DosAllocThreadLocalMemory(1, &pul);
12636 if( rc != NO_ERROR ){
12637 sqlite3OsLeaveMutex();
12638 return 0;
12640 s_ppTsd = (ThreadData **)pul;
12642 sqlite3OsLeaveMutex();
12644 pTsd = *s_ppTsd;
12645 if( allocateFlag>0 ){
12646 if( !pTsd ){
12647 pTsd = sqlite3OsMalloc( sizeof(zeroData) );
12648 if( pTsd ){
12649 *pTsd = zeroData;
12650 *s_ppTsd = pTsd;
12651 TSD_COUNTER_INCR;
12654 }else if( pTsd!=0 && allocateFlag<0
12655 && memcmp( pTsd, &zeroData, sizeof(ThreadData) )==0 ){
12656 sqlite3OsFree(pTsd);
12657 *s_ppTsd = NULL;
12658 TSD_COUNTER_DECR;
12659 pTsd = 0;
12661 return pTsd;
12663 #endif /* OS_OS2 */
12665 /************** End of os_os2.c **********************************************/
12666 /************** Begin file os_unix.c *****************************************/
12668 ** 2004 May 22
12670 ** The author disclaims copyright to this source code. In place of
12671 ** a legal notice, here is a blessing:
12673 ** May you do good and not evil.
12674 ** May you find forgiveness for yourself and forgive others.
12675 ** May you share freely, never taking more than you give.
12677 ******************************************************************************
12679 ** This file contains code that is specific to Unix systems.
12681 #if OS_UNIX /* This file is used on unix only */
12683 /* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
12686 ** These #defines should enable >2GB file support on Posix if the
12687 ** underlying operating system supports it. If the OS lacks
12688 ** large file support, these should be no-ops.
12690 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
12691 ** on the compiler command line. This is necessary if you are compiling
12692 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
12693 ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
12694 ** without this option, LFS is enable. But LFS does not exist in the kernel
12695 ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
12696 ** portability you should omit LFS.
12698 #ifndef SQLITE_DISABLE_LFS
12699 # define _LARGE_FILE 1
12700 # ifndef _FILE_OFFSET_BITS
12701 # define _FILE_OFFSET_BITS 64
12702 # endif
12703 # define _LARGEFILE_SOURCE 1
12704 #endif
12707 ** standard include files.
12709 #include <sys/types.h>
12710 #include <sys/stat.h>
12711 #include <fcntl.h>
12712 #include <unistd.h>
12713 #include <sys/time.h>
12714 #include <errno.h>
12715 #ifdef SQLITE_ENABLE_LOCKING_STYLE
12716 #include <sys/ioctl.h>
12717 #include <sys/param.h>
12718 #include <sys/mount.h>
12719 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
12722 ** If we are to be thread-safe, include the pthreads header and define
12723 ** the SQLITE_UNIX_THREADS macro.
12725 #ifndef THREADSAFE
12726 # define THREADSAFE 1
12727 #endif
12728 #if THREADSAFE
12729 # include <pthread.h>
12730 # define SQLITE_UNIX_THREADS 1
12731 #endif
12734 ** Default permissions when creating a new file
12736 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
12737 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
12738 #endif
12743 ** The unixFile structure is subclass of OsFile specific for the unix
12744 ** protability layer.
12746 typedef struct unixFile unixFile;
12747 struct unixFile {
12748 IoMethod const *pMethod; /* Always the first entry */
12749 struct openCnt *pOpen; /* Info about all open fd's on this inode */
12750 struct lockInfo *pLock; /* Info about locks on this inode */
12751 #ifdef SQLITE_ENABLE_LOCKING_STYLE
12752 void *lockingContext; /* Locking style specific state */
12753 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
12754 int h; /* The file descriptor */
12755 unsigned char locktype; /* The type of lock held on this fd */
12756 unsigned char isOpen; /* True if needs to be closed */
12757 unsigned char fullSync; /* Use F_FULLSYNC if available */
12758 int dirfd; /* File descriptor for the directory */
12759 i64 offset; /* Seek offset */
12760 #ifdef SQLITE_UNIX_THREADS
12761 pthread_t tid; /* The thread that "owns" this OsFile */
12762 #endif
12766 ** Provide the ability to override some OS-layer functions during
12767 ** testing. This is used to simulate OS crashes to verify that
12768 ** commits are atomic even in the event of an OS crash.
12770 #ifdef SQLITE_CRASH_TEST
12771 extern int sqlite3CrashTestEnable;
12772 extern int sqlite3CrashOpenReadWrite(const char*, OsFile**, int*);
12773 extern int sqlite3CrashOpenExclusive(const char*, OsFile**, int);
12774 extern int sqlite3CrashOpenReadOnly(const char*, OsFile**, int);
12775 # define CRASH_TEST_OVERRIDE(X,A,B,C) \
12776 if(sqlite3CrashTestEnable){ return X(A,B,C); }
12777 #else
12778 # define CRASH_TEST_OVERRIDE(X,A,B,C) /* no-op */
12779 #endif
12783 ** Include code that is common to all os_*.c files
12785 /************** Include os_common.h in the middle of os_unix.c ***************/
12786 /************** Begin file os_common.h ***************************************/
12788 ** 2004 May 22
12790 ** The author disclaims copyright to this source code. In place of
12791 ** a legal notice, here is a blessing:
12793 ** May you do good and not evil.
12794 ** May you find forgiveness for yourself and forgive others.
12795 ** May you share freely, never taking more than you give.
12797 ******************************************************************************
12799 ** This file contains macros and a little bit of code that is common to
12800 ** all of the platform-specific files (os_*.c) and is #included into those
12801 ** files.
12803 ** This file should be #included by the os_*.c files only. It is not a
12804 ** general purpose header file.
12808 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
12809 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
12810 ** switch. The following code should catch this problem at compile-time.
12812 #ifdef MEMORY_DEBUG
12813 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
12814 #endif
12818 * When testing, this global variable stores the location of the
12819 * pending-byte in the database file.
12821 #ifdef SQLITE_TEST
12822 unsigned int sqlite3_pending_byte = 0x40000000;
12823 #endif
12825 int sqlite3_os_trace = 0;
12826 #ifdef SQLITE_DEBUG
12827 #define OSTRACE1(X) if( sqlite3_os_trace ) sqlite3DebugPrintf(X)
12828 #define OSTRACE2(X,Y) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y)
12829 #define OSTRACE3(X,Y,Z) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z)
12830 #define OSTRACE4(X,Y,Z,A) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A)
12831 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A,B)
12832 #define OSTRACE6(X,Y,Z,A,B,C) \
12833 if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
12834 #define OSTRACE7(X,Y,Z,A,B,C,D) \
12835 if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
12836 #else
12837 #define OSTRACE1(X)
12838 #define OSTRACE2(X,Y)
12839 #define OSTRACE3(X,Y,Z)
12840 #define OSTRACE4(X,Y,Z,A)
12841 #define OSTRACE5(X,Y,Z,A,B)
12842 #define OSTRACE6(X,Y,Z,A,B,C)
12843 #define OSTRACE7(X,Y,Z,A,B,C,D)
12844 #endif
12847 ** Macros for performance tracing. Normally turned off. Only works
12848 ** on i486 hardware.
12850 #ifdef SQLITE_PERFORMANCE_TRACE
12851 __inline__ unsigned long long int hwtime(void){
12852 unsigned long long int x;
12853 __asm__("rdtsc\n\t"
12854 "mov %%edx, %%ecx\n\t"
12855 :"=A" (x));
12856 return x;
12858 static unsigned long long int g_start;
12859 static unsigned int elapse;
12860 #define TIMER_START g_start=hwtime()
12861 #define TIMER_END elapse=hwtime()-g_start
12862 #define TIMER_ELAPSED elapse
12863 #else
12864 #define TIMER_START
12865 #define TIMER_END
12866 #define TIMER_ELAPSED 0
12867 #endif
12870 ** If we compile with the SQLITE_TEST macro set, then the following block
12871 ** of code will give us the ability to simulate a disk I/O error. This
12872 ** is used for testing the I/O recovery logic.
12874 #ifdef SQLITE_TEST
12875 int sqlite3_io_error_hit = 0;
12876 int sqlite3_io_error_pending = 0;
12877 int sqlite3_io_error_persist = 0;
12878 int sqlite3_diskfull_pending = 0;
12879 int sqlite3_diskfull = 0;
12880 #define SimulateIOError(CODE) \
12881 if( sqlite3_io_error_pending || sqlite3_io_error_hit ) \
12882 if( sqlite3_io_error_pending-- == 1 \
12883 || (sqlite3_io_error_persist && sqlite3_io_error_hit) ) \
12884 { local_ioerr(); CODE; }
12885 static void local_ioerr(){
12886 IOTRACE(("IOERR\n"));
12887 sqlite3_io_error_hit = 1;
12889 #define SimulateDiskfullError(CODE) \
12890 if( sqlite3_diskfull_pending ){ \
12891 if( sqlite3_diskfull_pending == 1 ){ \
12892 local_ioerr(); \
12893 sqlite3_diskfull = 1; \
12894 sqlite3_io_error_hit = 1; \
12895 CODE; \
12896 }else{ \
12897 sqlite3_diskfull_pending--; \
12900 #else
12901 #define SimulateIOError(A)
12902 #define SimulateDiskfullError(A)
12903 #endif
12906 ** When testing, keep a count of the number of open files.
12908 #ifdef SQLITE_TEST
12909 int sqlite3_open_file_count = 0;
12910 #define OpenCounter(X) sqlite3_open_file_count+=(X)
12911 #else
12912 #define OpenCounter(X)
12913 #endif
12916 ** sqlite3GenericMalloc
12917 ** sqlite3GenericRealloc
12918 ** sqlite3GenericOsFree
12919 ** sqlite3GenericAllocationSize
12921 ** Implementation of the os level dynamic memory allocation interface in terms
12922 ** of the standard malloc(), realloc() and free() found in many operating
12923 ** systems. No rocket science here.
12925 ** There are two versions of these four functions here. The version
12926 ** implemented here is only used if memory-management or memory-debugging is
12927 ** enabled. This version allocates an extra 8-bytes at the beginning of each
12928 ** block and stores the size of the allocation there.
12930 ** If neither memory-management or debugging is enabled, the second
12931 ** set of implementations is used instead.
12933 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || defined (SQLITE_MEMDEBUG)
12934 static void *sqlite3GenericMalloc(int n){
12935 char *p = (char *)malloc(n+8);
12936 assert(n>0);
12937 assert(sizeof(int)<=8);
12938 if( p ){
12939 *(int *)p = n;
12940 p += 8;
12942 return (void *)p;
12944 static void *sqlite3GenericRealloc(void *p, int n){
12945 char *p2 = ((char *)p - 8);
12946 assert(n>0);
12947 p2 = (char*)realloc(p2, n+8);
12948 if( p2 ){
12949 *(int *)p2 = n;
12950 p2 += 8;
12952 return (void *)p2;
12954 static void sqlite3GenericFree(void *p){
12955 assert(p);
12956 free((void *)((char *)p - 8));
12958 static int sqlite3GenericAllocationSize(void *p){
12959 return p ? *(int *)((char *)p - 8) : 0;
12961 #else
12962 static void *sqlite3GenericMalloc(int n){
12963 char *p = (char *)malloc(n);
12964 return (void *)p;
12966 static void *sqlite3GenericRealloc(void *p, int n){
12967 assert(n>0);
12968 p = realloc(p, n);
12969 return p;
12971 static void sqlite3GenericFree(void *p){
12972 assert(p);
12973 free(p);
12975 /* Never actually used, but needed for the linker */
12976 static int sqlite3GenericAllocationSize(void *p){ return 0; }
12977 #endif
12980 ** The default size of a disk sector
12982 #ifndef PAGER_SECTOR_SIZE
12983 # define PAGER_SECTOR_SIZE 512
12984 #endif
12986 /************** End of os_common.h *******************************************/
12987 /************** Continuing where we left off in os_unix.c ********************/
12990 ** Do not include any of the File I/O interface procedures if the
12991 ** SQLITE_OMIT_DISKIO macro is defined (indicating that the database
12992 ** will be in-memory only)
12994 #ifndef SQLITE_OMIT_DISKIO
12998 ** Define various macros that are missing from some systems.
13000 #ifndef O_LARGEFILE
13001 # define O_LARGEFILE 0
13002 #endif
13003 #ifdef SQLITE_DISABLE_LFS
13004 # undef O_LARGEFILE
13005 # define O_LARGEFILE 0
13006 #endif
13007 #ifndef O_NOFOLLOW
13008 # define O_NOFOLLOW 0
13009 #endif
13010 #ifndef O_BINARY
13011 # define O_BINARY 0
13012 #endif
13015 ** The DJGPP compiler environment looks mostly like Unix, but it
13016 ** lacks the fcntl() system call. So redefine fcntl() to be something
13017 ** that always succeeds. This means that locking does not occur under
13018 ** DJGPP. But it's DOS - what did you expect?
13020 #ifdef __DJGPP__
13021 # define fcntl(A,B,C) 0
13022 #endif
13025 ** The threadid macro resolves to the thread-id or to 0. Used for
13026 ** testing and debugging only.
13028 #ifdef SQLITE_UNIX_THREADS
13029 #define threadid pthread_self()
13030 #else
13031 #define threadid 0
13032 #endif
13035 ** Set or check the OsFile.tid field. This field is set when an OsFile
13036 ** is first opened. All subsequent uses of the OsFile verify that the
13037 ** same thread is operating on the OsFile. Some operating systems do
13038 ** not allow locks to be overridden by other threads and that restriction
13039 ** means that sqlite3* database handles cannot be moved from one thread
13040 ** to another. This logic makes sure a user does not try to do that
13041 ** by mistake.
13043 ** Version 3.3.1 (2006-01-15): OsFiles can be moved from one thread to
13044 ** another as long as we are running on a system that supports threads
13045 ** overriding each others locks (which now the most common behavior)
13046 ** or if no locks are held. But the OsFile.pLock field needs to be
13047 ** recomputed because its key includes the thread-id. See the
13048 ** transferOwnership() function below for additional information
13050 #if defined(SQLITE_UNIX_THREADS)
13051 # define SET_THREADID(X) (X)->tid = pthread_self()
13052 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
13053 !pthread_equal((X)->tid, pthread_self()))
13054 #else
13055 # define SET_THREADID(X)
13056 # define CHECK_THREADID(X) 0
13057 #endif
13060 ** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
13061 ** section 6.5.2.2 lines 483 through 490 specify that when a process
13062 ** sets or clears a lock, that operation overrides any prior locks set
13063 ** by the same process. It does not explicitly say so, but this implies
13064 ** that it overrides locks set by the same process using a different
13065 ** file descriptor. Consider this test case:
13067 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
13068 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
13070 ** Suppose ./file1 and ./file2 are really the same file (because
13071 ** one is a hard or symbolic link to the other) then if you set
13072 ** an exclusive lock on fd1, then try to get an exclusive lock
13073 ** on fd2, it works. I would have expected the second lock to
13074 ** fail since there was already a lock on the file due to fd1.
13075 ** But not so. Since both locks came from the same process, the
13076 ** second overrides the first, even though they were on different
13077 ** file descriptors opened on different file names.
13079 ** Bummer. If you ask me, this is broken. Badly broken. It means
13080 ** that we cannot use POSIX locks to synchronize file access among
13081 ** competing threads of the same process. POSIX locks will work fine
13082 ** to synchronize access for threads in separate processes, but not
13083 ** threads within the same process.
13085 ** To work around the problem, SQLite has to manage file locks internally
13086 ** on its own. Whenever a new database is opened, we have to find the
13087 ** specific inode of the database file (the inode is determined by the
13088 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
13089 ** and check for locks already existing on that inode. When locks are
13090 ** created or removed, we have to look at our own internal record of the
13091 ** locks to see if another thread has previously set a lock on that same
13092 ** inode.
13094 ** The OsFile structure for POSIX is no longer just an integer file
13095 ** descriptor. It is now a structure that holds the integer file
13096 ** descriptor and a pointer to a structure that describes the internal
13097 ** locks on the corresponding inode. There is one locking structure
13098 ** per inode, so if the same inode is opened twice, both OsFile structures
13099 ** point to the same locking structure. The locking structure keeps
13100 ** a reference count (so we will know when to delete it) and a "cnt"
13101 ** field that tells us its internal lock status. cnt==0 means the
13102 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
13103 ** cnt>0 means there are cnt shared locks on the file.
13105 ** Any attempt to lock or unlock a file first checks the locking
13106 ** structure. The fcntl() system call is only invoked to set a
13107 ** POSIX lock if the internal lock structure transitions between
13108 ** a locked and an unlocked state.
13110 ** 2004-Jan-11:
13111 ** More recent discoveries about POSIX advisory locks. (The more
13112 ** I discover, the more I realize the a POSIX advisory locks are
13113 ** an abomination.)
13115 ** If you close a file descriptor that points to a file that has locks,
13116 ** all locks on that file that are owned by the current process are
13117 ** released. To work around this problem, each OsFile structure contains
13118 ** a pointer to an openCnt structure. There is one openCnt structure
13119 ** per open inode, which means that multiple OsFiles can point to a single
13120 ** openCnt. When an attempt is made to close an OsFile, if there are
13121 ** other OsFiles open on the same inode that are holding locks, the call
13122 ** to close() the file descriptor is deferred until all of the locks clear.
13123 ** The openCnt structure keeps a list of file descriptors that need to
13124 ** be closed and that list is walked (and cleared) when the last lock
13125 ** clears.
13127 ** First, under Linux threads, because each thread has a separate
13128 ** process ID, lock operations in one thread do not override locks
13129 ** to the same file in other threads. Linux threads behave like
13130 ** separate processes in this respect. But, if you close a file
13131 ** descriptor in linux threads, all locks are cleared, even locks
13132 ** on other threads and even though the other threads have different
13133 ** process IDs. Linux threads is inconsistent in this respect.
13134 ** (I'm beginning to think that linux threads is an abomination too.)
13135 ** The consequence of this all is that the hash table for the lockInfo
13136 ** structure has to include the process id as part of its key because
13137 ** locks in different threads are treated as distinct. But the
13138 ** openCnt structure should not include the process id in its
13139 ** key because close() clears lock on all threads, not just the current
13140 ** thread. Were it not for this goofiness in linux threads, we could
13141 ** combine the lockInfo and openCnt structures into a single structure.
13143 ** 2004-Jun-28:
13144 ** On some versions of linux, threads can override each others locks.
13145 ** On others not. Sometimes you can change the behavior on the same
13146 ** system by setting the LD_ASSUME_KERNEL environment variable. The
13147 ** POSIX standard is silent as to which behavior is correct, as far
13148 ** as I can tell, so other versions of unix might show the same
13149 ** inconsistency. There is no little doubt in my mind that posix
13150 ** advisory locks and linux threads are profoundly broken.
13152 ** To work around the inconsistencies, we have to test at runtime
13153 ** whether or not threads can override each others locks. This test
13154 ** is run once, the first time any lock is attempted. A static
13155 ** variable is set to record the results of this test for future
13156 ** use.
13160 ** An instance of the following structure serves as the key used
13161 ** to locate a particular lockInfo structure given its inode.
13163 ** If threads cannot override each others locks, then we set the
13164 ** lockKey.tid field to the thread ID. If threads can override
13165 ** each others locks then tid is always set to zero. tid is omitted
13166 ** if we compile without threading support.
13168 struct lockKey {
13169 dev_t dev; /* Device number */
13170 ino_t ino; /* Inode number */
13171 #ifdef SQLITE_UNIX_THREADS
13172 pthread_t tid; /* Thread ID or zero if threads can override each other */
13173 #endif
13177 ** An instance of the following structure is allocated for each open
13178 ** inode on each thread with a different process ID. (Threads have
13179 ** different process IDs on linux, but not on most other unixes.)
13181 ** A single inode can have multiple file descriptors, so each OsFile
13182 ** structure contains a pointer to an instance of this object and this
13183 ** object keeps a count of the number of OsFiles pointing to it.
13185 struct lockInfo {
13186 struct lockKey key; /* The lookup key */
13187 int cnt; /* Number of SHARED locks held */
13188 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
13189 int nRef; /* Number of pointers to this structure */
13193 ** An instance of the following structure serves as the key used
13194 ** to locate a particular openCnt structure given its inode. This
13195 ** is the same as the lockKey except that the thread ID is omitted.
13197 struct openKey {
13198 dev_t dev; /* Device number */
13199 ino_t ino; /* Inode number */
13203 ** An instance of the following structure is allocated for each open
13204 ** inode. This structure keeps track of the number of locks on that
13205 ** inode. If a close is attempted against an inode that is holding
13206 ** locks, the close is deferred until all locks clear by adding the
13207 ** file descriptor to be closed to the pending list.
13209 struct openCnt {
13210 struct openKey key; /* The lookup key */
13211 int nRef; /* Number of pointers to this structure */
13212 int nLock; /* Number of outstanding locks */
13213 int nPending; /* Number of pending close() operations */
13214 int *aPending; /* Malloced space holding fd's awaiting a close() */
13218 ** These hash tables map inodes and file descriptors (really, lockKey and
13219 ** openKey structures) into lockInfo and openCnt structures. Access to
13220 ** these hash tables must be protected by a mutex.
13222 static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0,
13223 sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
13224 static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0,
13225 sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
13227 #ifdef SQLITE_ENABLE_LOCKING_STYLE
13229 ** The locking styles are associated with the different file locking
13230 ** capabilities supported by different file systems.
13232 ** POSIX locking style fully supports shared and exclusive byte-range locks
13233 ** ADP locking only supports exclusive byte-range locks
13234 ** FLOCK only supports a single file-global exclusive lock
13235 ** DOTLOCK isn't a true locking style, it refers to the use of a special
13236 ** file named the same as the database file with a '.lock' extension, this
13237 ** can be used on file systems that do not offer any reliable file locking
13238 ** NO locking means that no locking will be attempted, this is only used for
13239 ** read-only file systems currently
13240 ** UNSUPPORTED means that no locking will be attempted, this is only used for
13241 ** file systems that are known to be unsupported
13243 typedef enum {
13244 posixLockingStyle = 0, /* standard posix-advisory locks */
13245 afpLockingStyle, /* use afp locks */
13246 flockLockingStyle, /* use flock() */
13247 dotlockLockingStyle, /* use <file>.lock files */
13248 noLockingStyle, /* useful for read-only file system */
13249 unsupportedLockingStyle /* indicates unsupported file system */
13250 } sqlite3LockingStyle;
13251 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
13253 #ifdef SQLITE_UNIX_THREADS
13255 ** This variable records whether or not threads can override each others
13256 ** locks.
13258 ** 0: No. Threads cannot override each others locks.
13259 ** 1: Yes. Threads can override each others locks.
13260 ** -1: We don't know yet.
13262 ** On some systems, we know at compile-time if threads can override each
13263 ** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
13264 ** will be set appropriately. On other systems, we have to check at
13265 ** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
13266 ** undefined.
13268 ** This variable normally has file scope only. But during testing, we make
13269 ** it a global so that the test code can change its value in order to verify
13270 ** that the right stuff happens in either case.
13272 #ifndef SQLITE_THREAD_OVERRIDE_LOCK
13273 # define SQLITE_THREAD_OVERRIDE_LOCK -1
13274 #endif
13275 #ifdef SQLITE_TEST
13276 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
13277 #else
13278 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
13279 #endif
13282 ** This structure holds information passed into individual test
13283 ** threads by the testThreadLockingBehavior() routine.
13285 struct threadTestData {
13286 int fd; /* File to be locked */
13287 struct flock lock; /* The locking operation */
13288 int result; /* Result of the locking operation */
13291 #ifdef SQLITE_LOCK_TRACE
13293 ** Print out information about all locking operations.
13295 ** This routine is used for troubleshooting locks on multithreaded
13296 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
13297 ** command-line option on the compiler. This code is normally
13298 ** turned off.
13300 static int lockTrace(int fd, int op, struct flock *p){
13301 char *zOpName, *zType;
13302 int s;
13303 int savedErrno;
13304 if( op==F_GETLK ){
13305 zOpName = "GETLK";
13306 }else if( op==F_SETLK ){
13307 zOpName = "SETLK";
13308 }else{
13309 s = fcntl(fd, op, p);
13310 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
13311 return s;
13313 if( p->l_type==F_RDLCK ){
13314 zType = "RDLCK";
13315 }else if( p->l_type==F_WRLCK ){
13316 zType = "WRLCK";
13317 }else if( p->l_type==F_UNLCK ){
13318 zType = "UNLCK";
13319 }else{
13320 assert( 0 );
13322 assert( p->l_whence==SEEK_SET );
13323 s = fcntl(fd, op, p);
13324 savedErrno = errno;
13325 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
13326 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
13327 (int)p->l_pid, s);
13328 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
13329 struct flock l2;
13330 l2 = *p;
13331 fcntl(fd, F_GETLK, &l2);
13332 if( l2.l_type==F_RDLCK ){
13333 zType = "RDLCK";
13334 }else if( l2.l_type==F_WRLCK ){
13335 zType = "WRLCK";
13336 }else if( l2.l_type==F_UNLCK ){
13337 zType = "UNLCK";
13338 }else{
13339 assert( 0 );
13341 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
13342 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
13344 errno = savedErrno;
13345 return s;
13347 #define fcntl lockTrace
13348 #endif /* SQLITE_LOCK_TRACE */
13351 ** The testThreadLockingBehavior() routine launches two separate
13352 ** threads on this routine. This routine attempts to lock a file
13353 ** descriptor then returns. The success or failure of that attempt
13354 ** allows the testThreadLockingBehavior() procedure to determine
13355 ** whether or not threads can override each others locks.
13357 static void *threadLockingTest(void *pArg){
13358 struct threadTestData *pData = (struct threadTestData*)pArg;
13359 pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
13360 return pArg;
13364 ** This procedure attempts to determine whether or not threads
13365 ** can override each others locks then sets the
13366 ** threadsOverrideEachOthersLocks variable appropriately.
13368 static void testThreadLockingBehavior(int fd_orig){
13369 int fd;
13370 struct threadTestData d[2];
13371 pthread_t t[2];
13373 fd = dup(fd_orig);
13374 if( fd<0 ) return;
13375 memset(d, 0, sizeof(d));
13376 d[0].fd = fd;
13377 d[0].lock.l_type = F_RDLCK;
13378 d[0].lock.l_len = 1;
13379 d[0].lock.l_start = 0;
13380 d[0].lock.l_whence = SEEK_SET;
13381 d[1] = d[0];
13382 d[1].lock.l_type = F_WRLCK;
13383 pthread_create(&t[0], 0, threadLockingTest, &d[0]);
13384 pthread_create(&t[1], 0, threadLockingTest, &d[1]);
13385 pthread_join(t[0], 0);
13386 pthread_join(t[1], 0);
13387 close(fd);
13388 threadsOverrideEachOthersLocks = d[0].result==0 && d[1].result==0;
13390 #endif /* SQLITE_UNIX_THREADS */
13393 ** Release a lockInfo structure previously allocated by findLockInfo().
13395 static void releaseLockInfo(struct lockInfo *pLock){
13396 assert( sqlite3OsInMutex(1) );
13397 if (pLock == NULL)
13398 return;
13399 pLock->nRef--;
13400 if( pLock->nRef==0 ){
13401 sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
13402 sqlite3ThreadSafeFree(pLock);
13407 ** Release a openCnt structure previously allocated by findLockInfo().
13409 static void releaseOpenCnt(struct openCnt *pOpen){
13410 assert( sqlite3OsInMutex(1) );
13411 if (pOpen == NULL)
13412 return;
13413 pOpen->nRef--;
13414 if( pOpen->nRef==0 ){
13415 sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
13416 free(pOpen->aPending);
13417 sqlite3ThreadSafeFree(pOpen);
13421 #ifdef SQLITE_ENABLE_LOCKING_STYLE
13423 ** Tests a byte-range locking query to see if byte range locks are
13424 ** supported, if not we fall back to dotlockLockingStyle.
13426 static sqlite3LockingStyle sqlite3TestLockingStyle(const char *filePath,
13427 int fd) {
13428 /* test byte-range lock using fcntl */
13429 struct flock lockInfo;
13431 lockInfo.l_len = 1;
13432 lockInfo.l_start = 0;
13433 lockInfo.l_whence = SEEK_SET;
13434 lockInfo.l_type = F_RDLCK;
13436 if (fcntl(fd, F_GETLK, &lockInfo) != -1) {
13437 return posixLockingStyle;
13440 /* testing for flock can give false positives. So if if the above test
13441 ** fails, then we fall back to using dot-lock style locking.
13443 return dotlockLockingStyle;
13447 ** Examines the f_fstypename entry in the statfs structure as returned by
13448 ** stat() for the file system hosting the database file, assigns the
13449 ** appropriate locking style based on it's value. These values and
13450 ** assignments are based on Darwin/OSX behavior and have not been tested on
13451 ** other systems.
13453 static sqlite3LockingStyle sqlite3DetectLockingStyle(const char *filePath,
13454 int fd) {
13456 #ifdef SQLITE_FIXED_LOCKING_STYLE
13457 return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
13458 #else
13459 struct statfs fsInfo;
13461 if (statfs(filePath, &fsInfo) == -1)
13462 return sqlite3TestLockingStyle(filePath, fd);
13464 if (fsInfo.f_flags & MNT_RDONLY)
13465 return noLockingStyle;
13467 if( (!strcmp(fsInfo.f_fstypename, "hfs")) ||
13468 (!strcmp(fsInfo.f_fstypename, "ufs")) )
13469 return posixLockingStyle;
13471 if(!strcmp(fsInfo.f_fstypename, "afpfs"))
13472 return afpLockingStyle;
13474 if(!strcmp(fsInfo.f_fstypename, "nfs"))
13475 return sqlite3TestLockingStyle(filePath, fd);
13477 if(!strcmp(fsInfo.f_fstypename, "smbfs"))
13478 return flockLockingStyle;
13480 if(!strcmp(fsInfo.f_fstypename, "msdos"))
13481 return dotlockLockingStyle;
13483 if(!strcmp(fsInfo.f_fstypename, "webdav"))
13484 return unsupportedLockingStyle;
13486 return sqlite3TestLockingStyle(filePath, fd);
13487 #endif /* SQLITE_FIXED_LOCKING_STYLE */
13490 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
13493 ** Given a file descriptor, locate lockInfo and openCnt structures that
13494 ** describes that file descriptor. Create new ones if necessary. The
13495 ** return values might be uninitialized if an error occurs.
13497 ** Return the number of errors.
13499 static int findLockInfo(
13500 int fd, /* The file descriptor used in the key */
13501 struct lockInfo **ppLock, /* Return the lockInfo structure here */
13502 struct openCnt **ppOpen /* Return the openCnt structure here */
13504 int rc;
13505 struct lockKey key1;
13506 struct openKey key2;
13507 struct stat statbuf;
13508 struct lockInfo *pLock;
13509 struct openCnt *pOpen;
13510 rc = fstat(fd, &statbuf);
13511 if( rc!=0 ) return 1;
13513 assert( sqlite3OsInMutex(1) );
13514 memset(&key1, 0, sizeof(key1));
13515 key1.dev = statbuf.st_dev;
13516 key1.ino = statbuf.st_ino;
13517 #ifdef SQLITE_UNIX_THREADS
13518 if( threadsOverrideEachOthersLocks<0 ){
13519 testThreadLockingBehavior(fd);
13521 key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
13522 #endif
13523 memset(&key2, 0, sizeof(key2));
13524 key2.dev = statbuf.st_dev;
13525 key2.ino = statbuf.st_ino;
13526 pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
13527 if( pLock==0 ){
13528 struct lockInfo *pOld;
13529 pLock = sqlite3ThreadSafeMalloc( sizeof(*pLock) );
13530 if( pLock==0 ){
13531 rc = 1;
13532 goto exit_findlockinfo;
13534 pLock->key = key1;
13535 pLock->nRef = 1;
13536 pLock->cnt = 0;
13537 pLock->locktype = 0;
13538 pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
13539 if( pOld!=0 ){
13540 assert( pOld==pLock );
13541 sqlite3ThreadSafeFree(pLock);
13542 rc = 1;
13543 goto exit_findlockinfo;
13545 }else{
13546 pLock->nRef++;
13548 *ppLock = pLock;
13549 if( ppOpen!=0 ){
13550 pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
13551 if( pOpen==0 ){
13552 struct openCnt *pOld;
13553 pOpen = sqlite3ThreadSafeMalloc( sizeof(*pOpen) );
13554 if( pOpen==0 ){
13555 releaseLockInfo(pLock);
13556 rc = 1;
13557 goto exit_findlockinfo;
13559 pOpen->key = key2;
13560 pOpen->nRef = 1;
13561 pOpen->nLock = 0;
13562 pOpen->nPending = 0;
13563 pOpen->aPending = 0;
13564 pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
13565 if( pOld!=0 ){
13566 assert( pOld==pOpen );
13567 sqlite3ThreadSafeFree(pOpen);
13568 releaseLockInfo(pLock);
13569 rc = 1;
13570 goto exit_findlockinfo;
13572 }else{
13573 pOpen->nRef++;
13575 *ppOpen = pOpen;
13578 exit_findlockinfo:
13579 return rc;
13582 #ifdef SQLITE_DEBUG
13584 ** Helper function for printing out trace information from debugging
13585 ** binaries. This returns the string represetation of the supplied
13586 ** integer lock-type.
13588 static const char *locktypeName(int locktype){
13589 switch( locktype ){
13590 case NO_LOCK: return "NONE";
13591 case SHARED_LOCK: return "SHARED";
13592 case RESERVED_LOCK: return "RESERVED";
13593 case PENDING_LOCK: return "PENDING";
13594 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
13596 return "ERROR";
13598 #endif
13601 ** If we are currently in a different thread than the thread that the
13602 ** unixFile argument belongs to, then transfer ownership of the unixFile
13603 ** over to the current thread.
13605 ** A unixFile is only owned by a thread on systems where one thread is
13606 ** unable to override locks created by a different thread. RedHat9 is
13607 ** an example of such a system.
13609 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
13610 ** If the unixFile is locked and an ownership is wrong, then return
13611 ** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
13613 #ifdef SQLITE_UNIX_THREADS
13614 static int transferOwnership(unixFile *pFile){
13615 int rc;
13616 pthread_t hSelf;
13617 if( threadsOverrideEachOthersLocks ){
13618 /* Ownership transfers not needed on this system */
13619 return SQLITE_OK;
13621 hSelf = pthread_self();
13622 if( pthread_equal(pFile->tid, hSelf) ){
13623 /* We are still in the same thread */
13624 OSTRACE1("No-transfer, same thread\n");
13625 return SQLITE_OK;
13627 if( pFile->locktype!=NO_LOCK ){
13628 /* We cannot change ownership while we are holding a lock! */
13629 return SQLITE_MISUSE;
13631 OSTRACE4("Transfer ownership of %d from %d to %d\n",
13632 pFile->h, pFile->tid, hSelf);
13633 pFile->tid = hSelf;
13634 if (pFile->pLock != NULL) {
13635 releaseLockInfo(pFile->pLock);
13636 rc = findLockInfo(pFile->h, &pFile->pLock, 0);
13637 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
13638 locktypeName(pFile->locktype),
13639 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
13640 return rc;
13641 } else {
13642 return SQLITE_OK;
13645 #else
13646 /* On single-threaded builds, ownership transfer is a no-op */
13647 # define transferOwnership(X) SQLITE_OK
13648 #endif
13651 ** Delete the named file
13653 static int sqlite3UnixDelete(const char *zFilename){
13654 SimulateIOError(return SQLITE_IOERR_DELETE);
13655 unlink(zFilename);
13656 return SQLITE_OK;
13660 ** Return TRUE if the named file exists.
13662 static int sqlite3UnixFileExists(const char *zFilename){
13663 return access(zFilename, 0)==0;
13666 /* Forward declaration */
13667 static int allocateUnixFile(
13668 int h, /* File descriptor of the open file */
13669 OsFile **pId, /* Write the real file descriptor here */
13670 const char *zFilename, /* Name of the file being opened */
13671 int delFlag /* If true, make sure the file deletes on close */
13675 ** Attempt to open a file for both reading and writing. If that
13676 ** fails, try opening it read-only. If the file does not exist,
13677 ** try to create it.
13679 ** On success, a handle for the open file is written to *id
13680 ** and *pReadonly is set to 0 if the file was opened for reading and
13681 ** writing or 1 if the file was opened read-only. The function returns
13682 ** SQLITE_OK.
13684 ** On failure, the function returns SQLITE_CANTOPEN and leaves
13685 ** *id and *pReadonly unchanged.
13687 static int sqlite3UnixOpenReadWrite(
13688 const char *zFilename,
13689 OsFile **pId,
13690 int *pReadonly
13692 int h;
13694 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
13695 assert( 0==*pId );
13696 h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
13697 SQLITE_DEFAULT_FILE_PERMISSIONS);
13698 if( h<0 ){
13699 #ifdef EISDIR
13700 if( errno==EISDIR ){
13701 return SQLITE_CANTOPEN;
13703 #endif
13704 h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
13705 if( h<0 ){
13706 return SQLITE_CANTOPEN;
13708 *pReadonly = 1;
13709 }else{
13710 *pReadonly = 0;
13712 return allocateUnixFile(h, pId, zFilename, 0);
13717 ** Attempt to open a new file for exclusive access by this process.
13718 ** The file will be opened for both reading and writing. To avoid
13719 ** a potential security problem, we do not allow the file to have
13720 ** previously existed. Nor do we allow the file to be a symbolic
13721 ** link.
13723 ** If delFlag is true, then make arrangements to automatically delete
13724 ** the file when it is closed.
13726 ** On success, write the file handle into *id and return SQLITE_OK.
13728 ** On failure, return SQLITE_CANTOPEN.
13730 static int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
13731 int h;
13733 CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
13734 assert( 0==*pId );
13735 h = open(zFilename,
13736 O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
13737 delFlag ? 0600 : SQLITE_DEFAULT_FILE_PERMISSIONS);
13738 if( h<0 ){
13739 return SQLITE_CANTOPEN;
13741 return allocateUnixFile(h, pId, zFilename, delFlag);
13745 ** Attempt to open a new file for read-only access.
13747 ** On success, write the file handle into *id and return SQLITE_OK.
13749 ** On failure, return SQLITE_CANTOPEN.
13751 static int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
13752 int h;
13754 CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
13755 assert( 0==*pId );
13756 h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
13757 if( h<0 ){
13758 return SQLITE_CANTOPEN;
13760 return allocateUnixFile(h, pId, zFilename, 0);
13764 ** Attempt to open a file descriptor for the directory that contains a
13765 ** file. This file descriptor can be used to fsync() the directory
13766 ** in order to make sure the creation of a new file is actually written
13767 ** to disk.
13769 ** This routine is only meaningful for Unix. It is a no-op under
13770 ** windows since windows does not support hard links.
13772 ** If FULL_FSYNC is enabled, this function is not longer useful,
13773 ** a FULL_FSYNC sync applies to all pending disk operations.
13775 ** On success, a handle for a previously open file at *id is
13776 ** updated with the new directory file descriptor and SQLITE_OK is
13777 ** returned.
13779 ** On failure, the function returns SQLITE_CANTOPEN and leaves
13780 ** *id unchanged.
13782 static int unixOpenDirectory(
13783 OsFile *id,
13784 const char *zDirname
13786 unixFile *pFile = (unixFile*)id;
13787 assert( pFile!=0 );
13788 SET_THREADID(pFile);
13789 assert( pFile->dirfd<0 );
13790 pFile->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
13791 if( pFile->dirfd<0 ){
13792 return SQLITE_CANTOPEN;
13794 OSTRACE3("OPENDIR %-3d %s\n", pFile->dirfd, zDirname);
13795 return SQLITE_OK;
13799 ** Create a temporary file name in zBuf. zBuf must be big enough to
13800 ** hold at least SQLITE_TEMPNAME_SIZE characters.
13802 static int sqlite3UnixTempFileName(char *zBuf){
13803 static const char *azDirs[] = {
13805 "/var/tmp",
13806 "/usr/tmp",
13807 "/tmp",
13808 ".",
13810 static const unsigned char zChars[] =
13811 "abcdefghijklmnopqrstuvwxyz"
13812 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
13813 "0123456789";
13814 int i, j;
13815 struct stat buf;
13816 const char *zDir = ".";
13817 azDirs[0] = sqlite3_temp_directory;
13818 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
13819 if( azDirs[i]==0 ) continue;
13820 if( stat(azDirs[i], &buf) ) continue;
13821 if( !S_ISDIR(buf.st_mode) ) continue;
13822 if( access(azDirs[i], 07) ) continue;
13823 zDir = azDirs[i];
13824 break;
13827 sqlite3_snprintf(SQLITE_TEMPNAME_SIZE, zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
13828 j = strlen(zBuf);
13829 sqlite3Randomness(15, &zBuf[j]);
13830 for(i=0; i<15; i++, j++){
13831 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
13833 zBuf[j] = 0;
13834 }while( access(zBuf,0)==0 );
13835 return SQLITE_OK;
13839 ** Check that a given pathname is a directory and is writable
13842 static int sqlite3UnixIsDirWritable(char *zBuf){
13843 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
13844 struct stat buf;
13845 if( zBuf==0 ) return 0;
13846 if( zBuf[0]==0 ) return 0;
13847 if( stat(zBuf, &buf) ) return 0;
13848 if( !S_ISDIR(buf.st_mode) ) return 0;
13849 if( access(zBuf, 07) ) return 0;
13850 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
13851 return 1;
13855 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
13856 ** Return the number of bytes actually read. Update the offset.
13858 static int seekAndRead(unixFile *id, void *pBuf, int cnt){
13859 int got;
13860 i64 newOffset;
13861 TIMER_START;
13862 #if defined(USE_PREAD)
13863 got = pread(id->h, pBuf, cnt, id->offset);
13864 SimulateIOError( got = -1 );
13865 #elif defined(USE_PREAD64)
13866 got = pread64(id->h, pBuf, cnt, id->offset);
13867 SimulateIOError( got = -1 );
13868 #else
13869 newOffset = lseek(id->h, id->offset, SEEK_SET);
13870 SimulateIOError( newOffset-- );
13871 if( newOffset!=id->offset ){
13872 return -1;
13874 got = read(id->h, pBuf, cnt);
13875 #endif
13876 TIMER_END;
13877 OSTRACE5("READ %-3d %5d %7lld %d\n", id->h, got, id->offset, TIMER_ELAPSED);
13878 if( got>0 ){
13879 id->offset += got;
13881 return got;
13885 ** Read data from a file into a buffer. Return SQLITE_OK if all
13886 ** bytes were read successfully and SQLITE_IOERR if anything goes
13887 ** wrong.
13889 static int unixRead(OsFile *id, void *pBuf, int amt){
13890 int got;
13891 assert( id );
13892 got = seekAndRead((unixFile*)id, pBuf, amt);
13893 if( got==amt ){
13894 return SQLITE_OK;
13895 }else if( got<0 ){
13896 return SQLITE_IOERR_READ;
13897 }else{
13898 memset(&((char*)pBuf)[got], 0, amt-got);
13899 return SQLITE_IOERR_SHORT_READ;
13904 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
13905 ** Return the number of bytes actually read. Update the offset.
13907 static int seekAndWrite(unixFile *id, const void *pBuf, int cnt){
13908 int got;
13909 i64 newOffset;
13910 TIMER_START;
13911 #if defined(USE_PREAD)
13912 got = pwrite(id->h, pBuf, cnt, id->offset);
13913 #elif defined(USE_PREAD64)
13914 got = pwrite64(id->h, pBuf, cnt, id->offset);
13915 #else
13916 newOffset = lseek(id->h, id->offset, SEEK_SET);
13917 if( newOffset!=id->offset ){
13918 return -1;
13920 got = write(id->h, pBuf, cnt);
13921 #endif
13922 TIMER_END;
13923 OSTRACE5("WRITE %-3d %5d %7lld %d\n", id->h, got, id->offset, TIMER_ELAPSED);
13924 if( got>0 ){
13925 id->offset += got;
13927 return got;
13932 ** Write data from a buffer into a file. Return SQLITE_OK on success
13933 ** or some other error code on failure.
13935 static int unixWrite(OsFile *id, const void *pBuf, int amt){
13936 int wrote = 0;
13937 assert( id );
13938 assert( amt>0 );
13939 while( amt>0 && (wrote = seekAndWrite((unixFile*)id, pBuf, amt))>0 ){
13940 amt -= wrote;
13941 pBuf = &((char*)pBuf)[wrote];
13943 SimulateIOError(( wrote=(-1), amt=1 ));
13944 SimulateDiskfullError(( wrote=0, amt=1 ));
13945 if( amt>0 ){
13946 if( wrote<0 ){
13947 return SQLITE_IOERR_WRITE;
13948 }else{
13949 return SQLITE_FULL;
13952 return SQLITE_OK;
13956 ** Move the read/write pointer in a file.
13958 static int unixSeek(OsFile *id, i64 offset){
13959 assert( id );
13960 #ifdef SQLITE_TEST
13961 if( offset ) SimulateDiskfullError(return SQLITE_FULL);
13962 #endif
13963 ((unixFile*)id)->offset = offset;
13964 return SQLITE_OK;
13967 #ifdef SQLITE_TEST
13969 ** Count the number of fullsyncs and normal syncs. This is used to test
13970 ** that syncs and fullsyncs are occuring at the right times.
13972 int sqlite3_sync_count = 0;
13973 int sqlite3_fullsync_count = 0;
13974 #endif
13977 ** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
13978 ** Otherwise use fsync() in its place.
13980 #ifndef HAVE_FDATASYNC
13981 # define fdatasync fsync
13982 #endif
13985 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
13986 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
13987 ** only available on Mac OS X. But that could change.
13989 #ifdef F_FULLFSYNC
13990 # define HAVE_FULLFSYNC 1
13991 #else
13992 # define HAVE_FULLFSYNC 0
13993 #endif
13997 ** The fsync() system call does not work as advertised on many
13998 ** unix systems. The following procedure is an attempt to make
13999 ** it work better.
14001 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
14002 ** for testing when we want to run through the test suite quickly.
14003 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
14004 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
14005 ** or power failure will likely corrupt the database file.
14007 static int full_fsync(int fd, int fullSync, int dataOnly){
14008 int rc;
14010 /* Record the number of times that we do a normal fsync() and
14011 ** FULLSYNC. This is used during testing to verify that this procedure
14012 ** gets called with the correct arguments.
14014 #ifdef SQLITE_TEST
14015 if( fullSync ) sqlite3_fullsync_count++;
14016 sqlite3_sync_count++;
14017 #endif
14019 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
14020 ** no-op
14022 #ifdef SQLITE_NO_SYNC
14023 rc = SQLITE_OK;
14024 #else
14026 #if HAVE_FULLFSYNC
14027 if( fullSync ){
14028 rc = fcntl(fd, F_FULLFSYNC, 0);
14029 }else{
14030 rc = 1;
14032 /* If the FULLFSYNC failed, fall back to attempting an fsync().
14033 * It shouldn't be possible for fullfsync to fail on the local
14034 * file system (on OSX), so failure indicates that FULLFSYNC
14035 * isn't supported for this file system. So, attempt an fsync
14036 * and (for now) ignore the overhead of a superfluous fcntl call.
14037 * It'd be better to detect fullfsync support once and avoid
14038 * the fcntl call every time sync is called.
14040 if( rc ) rc = fsync(fd);
14042 #else
14043 if( dataOnly ){
14044 rc = fdatasync(fd);
14045 }else{
14046 rc = fsync(fd);
14048 #endif /* HAVE_FULLFSYNC */
14049 #endif /* defined(SQLITE_NO_SYNC) */
14051 return rc;
14055 ** Make sure all writes to a particular file are committed to disk.
14057 ** If dataOnly==0 then both the file itself and its metadata (file
14058 ** size, access time, etc) are synced. If dataOnly!=0 then only the
14059 ** file data is synced.
14061 ** Under Unix, also make sure that the directory entry for the file
14062 ** has been created by fsync-ing the directory that contains the file.
14063 ** If we do not do this and we encounter a power failure, the directory
14064 ** entry for the journal might not exist after we reboot. The next
14065 ** SQLite to access the file will not know that the journal exists (because
14066 ** the directory entry for the journal was never created) and the transaction
14067 ** will not roll back - possibly leading to database corruption.
14069 static int unixSync(OsFile *id, int dataOnly){
14070 int rc;
14071 unixFile *pFile = (unixFile*)id;
14072 assert( pFile );
14073 OSTRACE2("SYNC %-3d\n", pFile->h);
14074 rc = full_fsync(pFile->h, pFile->fullSync, dataOnly);
14075 SimulateIOError( rc=1 );
14076 if( rc ){
14077 return SQLITE_IOERR_FSYNC;
14079 if( pFile->dirfd>=0 ){
14080 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
14081 HAVE_FULLFSYNC, pFile->fullSync);
14082 #ifndef SQLITE_DISABLE_DIRSYNC
14083 /* The directory sync is only attempted if full_fsync is
14084 ** turned off or unavailable. If a full_fsync occurred above,
14085 ** then the directory sync is superfluous.
14087 if( (!HAVE_FULLFSYNC || !pFile->fullSync) && full_fsync(pFile->dirfd,0,0) ){
14089 ** We have received multiple reports of fsync() returning
14090 ** errors when applied to directories on certain file systems.
14091 ** A failed directory sync is not a big deal. So it seems
14092 ** better to ignore the error. Ticket #1657
14094 /* return SQLITE_IOERR; */
14096 #endif
14097 close(pFile->dirfd); /* Only need to sync once, so close the directory */
14098 pFile->dirfd = -1; /* when we are done. */
14100 return SQLITE_OK;
14104 ** Sync the directory zDirname. This is a no-op on operating systems other
14105 ** than UNIX.
14107 ** This is used to make sure the master journal file has truely been deleted
14108 ** before making changes to individual journals on a multi-database commit.
14109 ** The F_FULLFSYNC option is not needed here.
14111 static int sqlite3UnixSyncDirectory(const char *zDirname){
14112 #ifdef SQLITE_DISABLE_DIRSYNC
14113 return SQLITE_OK;
14114 #else
14115 int fd;
14116 int r;
14117 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
14118 OSTRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
14119 if( fd<0 ){
14120 return SQLITE_CANTOPEN;
14122 r = fsync(fd);
14123 close(fd);
14124 SimulateIOError( r=1 );
14125 if( r ){
14126 return SQLITE_IOERR_DIR_FSYNC;
14127 }else{
14128 return SQLITE_OK;
14130 #endif
14134 ** Truncate an open file to a specified size
14136 static int unixTruncate(OsFile *id, i64 nByte){
14137 int rc;
14138 assert( id );
14139 rc = ftruncate(((unixFile*)id)->h, nByte);
14140 SimulateIOError( rc=1 );
14141 if( rc ){
14142 return SQLITE_IOERR_TRUNCATE;
14143 }else{
14144 return SQLITE_OK;
14149 ** Determine the current size of a file in bytes
14151 static int unixFileSize(OsFile *id, i64 *pSize){
14152 int rc;
14153 struct stat buf;
14154 assert( id );
14155 rc = fstat(((unixFile*)id)->h, &buf);
14156 SimulateIOError( rc=1 );
14157 if( rc!=0 ){
14158 return SQLITE_IOERR_FSTAT;
14160 *pSize = buf.st_size;
14161 return SQLITE_OK;
14165 ** This routine checks if there is a RESERVED lock held on the specified
14166 ** file by this or any other process. If such a lock is held, return
14167 ** non-zero. If the file is unlocked or holds only SHARED locks, then
14168 ** return zero.
14170 static int unixCheckReservedLock(OsFile *id){
14171 int r = 0;
14172 unixFile *pFile = (unixFile*)id;
14174 assert( pFile );
14175 sqlite3OsEnterMutex(); /* Because pFile->pLock is shared across threads */
14177 /* Check if a thread in this process holds such a lock */
14178 if( pFile->pLock->locktype>SHARED_LOCK ){
14179 r = 1;
14182 /* Otherwise see if some other process holds it.
14184 if( !r ){
14185 struct flock lock;
14186 lock.l_whence = SEEK_SET;
14187 lock.l_start = RESERVED_BYTE;
14188 lock.l_len = 1;
14189 lock.l_type = F_WRLCK;
14190 fcntl(pFile->h, F_GETLK, &lock);
14191 if( lock.l_type!=F_UNLCK ){
14192 r = 1;
14196 sqlite3OsLeaveMutex();
14197 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
14199 return r;
14203 ** Lock the file with the lock specified by parameter locktype - one
14204 ** of the following:
14206 ** (1) SHARED_LOCK
14207 ** (2) RESERVED_LOCK
14208 ** (3) PENDING_LOCK
14209 ** (4) EXCLUSIVE_LOCK
14211 ** Sometimes when requesting one lock state, additional lock states
14212 ** are inserted in between. The locking might fail on one of the later
14213 ** transitions leaving the lock state different from what it started but
14214 ** still short of its goal. The following chart shows the allowed
14215 ** transitions and the inserted intermediate states:
14217 ** UNLOCKED -> SHARED
14218 ** SHARED -> RESERVED
14219 ** SHARED -> (PENDING) -> EXCLUSIVE
14220 ** RESERVED -> (PENDING) -> EXCLUSIVE
14221 ** PENDING -> EXCLUSIVE
14223 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
14224 ** routine to lower a locking level.
14226 static int unixLock(OsFile *id, int locktype){
14227 /* The following describes the implementation of the various locks and
14228 ** lock transitions in terms of the POSIX advisory shared and exclusive
14229 ** lock primitives (called read-locks and write-locks below, to avoid
14230 ** confusion with SQLite lock names). The algorithms are complicated
14231 ** slightly in order to be compatible with windows systems simultaneously
14232 ** accessing the same database file, in case that is ever required.
14234 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
14235 ** byte', each single bytes at well known offsets, and the 'shared byte
14236 ** range', a range of 510 bytes at a well known offset.
14238 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
14239 ** byte'. If this is successful, a random byte from the 'shared byte
14240 ** range' is read-locked and the lock on the 'pending byte' released.
14242 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
14243 ** A RESERVED lock is implemented by grabbing a write-lock on the
14244 ** 'reserved byte'.
14246 ** A process may only obtain a PENDING lock after it has obtained a
14247 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
14248 ** on the 'pending byte'. This ensures that no new SHARED locks can be
14249 ** obtained, but existing SHARED locks are allowed to persist. A process
14250 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
14251 ** This property is used by the algorithm for rolling back a journal file
14252 ** after a crash.
14254 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
14255 ** implemented by obtaining a write-lock on the entire 'shared byte
14256 ** range'. Since all other locks require a read-lock on one of the bytes
14257 ** within this range, this ensures that no other locks are held on the
14258 ** database.
14260 ** The reason a single byte cannot be used instead of the 'shared byte
14261 ** range' is that some versions of windows do not support read-locks. By
14262 ** locking a random byte from a range, concurrent SHARED locks may exist
14263 ** even if the locking primitive used is always a write-lock.
14265 int rc = SQLITE_OK;
14266 unixFile *pFile = (unixFile*)id;
14267 struct lockInfo *pLock = pFile->pLock;
14268 struct flock lock;
14269 int s;
14271 assert( pFile );
14272 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h,
14273 locktypeName(locktype), locktypeName(pFile->locktype),
14274 locktypeName(pLock->locktype), pLock->cnt , getpid());
14276 /* If there is already a lock of this type or more restrictive on the
14277 ** OsFile, do nothing. Don't use the end_lock: exit path, as
14278 ** sqlite3OsEnterMutex() hasn't been called yet.
14280 if( pFile->locktype>=locktype ){
14281 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
14282 locktypeName(locktype));
14283 return SQLITE_OK;
14286 /* Make sure the locking sequence is correct
14288 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
14289 assert( locktype!=PENDING_LOCK );
14290 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
14292 /* This mutex is needed because pFile->pLock is shared across threads
14294 sqlite3OsEnterMutex();
14296 /* Make sure the current thread owns the pFile.
14298 rc = transferOwnership(pFile);
14299 if( rc!=SQLITE_OK ){
14300 sqlite3OsLeaveMutex();
14301 return rc;
14303 pLock = pFile->pLock;
14305 /* If some thread using this PID has a lock via a different OsFile*
14306 ** handle that precludes the requested lock, return BUSY.
14308 if( (pFile->locktype!=pLock->locktype &&
14309 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
14311 rc = SQLITE_BUSY;
14312 goto end_lock;
14315 /* If a SHARED lock is requested, and some thread using this PID already
14316 ** has a SHARED or RESERVED lock, then increment reference counts and
14317 ** return SQLITE_OK.
14319 if( locktype==SHARED_LOCK &&
14320 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
14321 assert( locktype==SHARED_LOCK );
14322 assert( pFile->locktype==0 );
14323 assert( pLock->cnt>0 );
14324 pFile->locktype = SHARED_LOCK;
14325 pLock->cnt++;
14326 pFile->pOpen->nLock++;
14327 goto end_lock;
14330 lock.l_len = 1L;
14332 lock.l_whence = SEEK_SET;
14334 /* A PENDING lock is needed before acquiring a SHARED lock and before
14335 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
14336 ** be released.
14338 if( locktype==SHARED_LOCK
14339 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
14341 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
14342 lock.l_start = PENDING_BYTE;
14343 s = fcntl(pFile->h, F_SETLK, &lock);
14344 if( s==(-1) ){
14345 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
14346 goto end_lock;
14351 /* If control gets to this point, then actually go ahead and make
14352 ** operating system calls for the specified lock.
14354 if( locktype==SHARED_LOCK ){
14355 assert( pLock->cnt==0 );
14356 assert( pLock->locktype==0 );
14358 /* Now get the read-lock */
14359 lock.l_start = SHARED_FIRST;
14360 lock.l_len = SHARED_SIZE;
14361 s = fcntl(pFile->h, F_SETLK, &lock);
14363 /* Drop the temporary PENDING lock */
14364 lock.l_start = PENDING_BYTE;
14365 lock.l_len = 1L;
14366 lock.l_type = F_UNLCK;
14367 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
14368 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
14369 goto end_lock;
14371 if( s==(-1) ){
14372 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
14373 }else{
14374 pFile->locktype = SHARED_LOCK;
14375 pFile->pOpen->nLock++;
14376 pLock->cnt = 1;
14378 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
14379 /* We are trying for an exclusive lock but another thread in this
14380 ** same process is still holding a shared lock. */
14381 rc = SQLITE_BUSY;
14382 }else{
14383 /* The request was for a RESERVED or EXCLUSIVE lock. It is
14384 ** assumed that there is a SHARED or greater lock on the file
14385 ** already.
14387 assert( 0!=pFile->locktype );
14388 lock.l_type = F_WRLCK;
14389 switch( locktype ){
14390 case RESERVED_LOCK:
14391 lock.l_start = RESERVED_BYTE;
14392 break;
14393 case EXCLUSIVE_LOCK:
14394 lock.l_start = SHARED_FIRST;
14395 lock.l_len = SHARED_SIZE;
14396 break;
14397 default:
14398 assert(0);
14400 s = fcntl(pFile->h, F_SETLK, &lock);
14401 if( s==(-1) ){
14402 rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
14406 if( rc==SQLITE_OK ){
14407 pFile->locktype = locktype;
14408 pLock->locktype = locktype;
14409 }else if( locktype==EXCLUSIVE_LOCK ){
14410 pFile->locktype = PENDING_LOCK;
14411 pLock->locktype = PENDING_LOCK;
14414 end_lock:
14415 sqlite3OsLeaveMutex();
14416 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
14417 rc==SQLITE_OK ? "ok" : "failed");
14418 return rc;
14422 ** Lower the locking level on file descriptor pFile to locktype. locktype
14423 ** must be either NO_LOCK or SHARED_LOCK.
14425 ** If the locking level of the file descriptor is already at or below
14426 ** the requested locking level, this routine is a no-op.
14428 static int unixUnlock(OsFile *id, int locktype){
14429 struct lockInfo *pLock;
14430 struct flock lock;
14431 int rc = SQLITE_OK;
14432 unixFile *pFile = (unixFile*)id;
14434 assert( pFile );
14435 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
14436 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
14438 assert( locktype<=SHARED_LOCK );
14439 if( pFile->locktype<=locktype ){
14440 return SQLITE_OK;
14442 if( CHECK_THREADID(pFile) ){
14443 return SQLITE_MISUSE;
14445 sqlite3OsEnterMutex();
14446 pLock = pFile->pLock;
14447 assert( pLock->cnt!=0 );
14448 if( pFile->locktype>SHARED_LOCK ){
14449 assert( pLock->locktype==pFile->locktype );
14450 if( locktype==SHARED_LOCK ){
14451 lock.l_type = F_RDLCK;
14452 lock.l_whence = SEEK_SET;
14453 lock.l_start = SHARED_FIRST;
14454 lock.l_len = SHARED_SIZE;
14455 if( fcntl(pFile->h, F_SETLK, &lock)==(-1) ){
14456 /* This should never happen */
14457 rc = SQLITE_IOERR_RDLOCK;
14460 lock.l_type = F_UNLCK;
14461 lock.l_whence = SEEK_SET;
14462 lock.l_start = PENDING_BYTE;
14463 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
14464 if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
14465 pLock->locktype = SHARED_LOCK;
14466 }else{
14467 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
14470 if( locktype==NO_LOCK ){
14471 struct openCnt *pOpen;
14473 /* Decrement the shared lock counter. Release the lock using an
14474 ** OS call only when all threads in this same process have released
14475 ** the lock.
14477 pLock->cnt--;
14478 if( pLock->cnt==0 ){
14479 lock.l_type = F_UNLCK;
14480 lock.l_whence = SEEK_SET;
14481 lock.l_start = lock.l_len = 0L;
14482 if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
14483 pLock->locktype = NO_LOCK;
14484 }else{
14485 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
14489 /* Decrement the count of locks against this same file. When the
14490 ** count reaches zero, close any other file descriptors whose close
14491 ** was deferred because of outstanding locks.
14493 pOpen = pFile->pOpen;
14494 pOpen->nLock--;
14495 assert( pOpen->nLock>=0 );
14496 if( pOpen->nLock==0 && pOpen->nPending>0 ){
14497 int i;
14498 for(i=0; i<pOpen->nPending; i++){
14499 close(pOpen->aPending[i]);
14501 free(pOpen->aPending);
14502 pOpen->nPending = 0;
14503 pOpen->aPending = 0;
14506 sqlite3OsLeaveMutex();
14507 pFile->locktype = locktype;
14508 return rc;
14512 ** Close a file.
14514 static int unixClose(OsFile **pId){
14515 unixFile *id = (unixFile*)*pId;
14517 if( !id ) return SQLITE_OK;
14518 unixUnlock(*pId, NO_LOCK);
14519 if( id->dirfd>=0 ) close(id->dirfd);
14520 id->dirfd = -1;
14521 sqlite3OsEnterMutex();
14523 if( id->pOpen->nLock ){
14524 /* If there are outstanding locks, do not actually close the file just
14525 ** yet because that would clear those locks. Instead, add the file
14526 ** descriptor to pOpen->aPending. It will be automatically closed when
14527 ** the last lock is cleared.
14529 int *aNew;
14530 struct openCnt *pOpen = id->pOpen;
14531 aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
14532 if( aNew==0 ){
14533 /* If a malloc fails, just leak the file descriptor */
14534 }else{
14535 pOpen->aPending = aNew;
14536 pOpen->aPending[pOpen->nPending] = id->h;
14537 pOpen->nPending++;
14539 }else{
14540 /* There are no outstanding locks so we can close the file immediately */
14541 close(id->h);
14543 releaseLockInfo(id->pLock);
14544 releaseOpenCnt(id->pOpen);
14546 sqlite3OsLeaveMutex();
14547 id->isOpen = 0;
14548 OSTRACE2("CLOSE %-3d\n", id->h);
14549 OpenCounter(-1);
14550 sqlite3ThreadSafeFree(id);
14551 *pId = 0;
14552 return SQLITE_OK;
14556 #ifdef SQLITE_ENABLE_LOCKING_STYLE
14557 #pragma mark AFP Support
14560 ** The afpLockingContext structure contains all afp lock specific state
14562 typedef struct afpLockingContext afpLockingContext;
14563 struct afpLockingContext {
14564 unsigned long long sharedLockByte;
14565 char *filePath;
14568 struct ByteRangeLockPB2
14570 unsigned long long offset; /* offset to first byte to lock */
14571 unsigned long long length; /* nbr of bytes to lock */
14572 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
14573 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
14574 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
14575 int fd; /* file desc to assoc this lock with */
14578 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
14580 /* return 0 on success, 1 on failure. To match the behavior of the
14581 normal posix file locking (used in unixLock for example), we should
14582 provide 'richer' return codes - specifically to differentiate between
14583 'file busy' and 'file system error' results */
14584 static int _AFPFSSetLock(const char *path, int fd, unsigned long long offset,
14585 unsigned long long length, int setLockFlag)
14587 struct ByteRangeLockPB2 pb;
14588 int err;
14590 pb.unLockFlag = setLockFlag ? 0 : 1;
14591 pb.startEndFlag = 0;
14592 pb.offset = offset;
14593 pb.length = length;
14594 pb.fd = fd;
14595 OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n",
14596 (setLockFlag?"ON":"OFF"), fd, offset, length);
14597 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
14598 if ( err==-1 ) {
14599 OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno,
14600 strerror(errno));
14601 return 1; /* error */
14602 } else {
14603 return 0;
14608 ** This routine checks if there is a RESERVED lock held on the specified
14609 ** file by this or any other process. If such a lock is held, return
14610 ** non-zero. If the file is unlocked or holds only SHARED locks, then
14611 ** return zero.
14613 static int afpUnixCheckReservedLock(OsFile *id){
14614 int r = 0;
14615 unixFile *pFile = (unixFile*)id;
14617 assert( pFile );
14618 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
14620 /* Check if a thread in this process holds such a lock */
14621 if( pFile->locktype>SHARED_LOCK ){
14622 r = 1;
14625 /* Otherwise see if some other process holds it.
14627 if ( !r ) {
14628 /* lock the byte */
14629 int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
14630 if (failed) {
14631 /* if we failed to get the lock then someone else must have it */
14632 r = 1;
14633 } else {
14634 /* if we succeeded in taking the reserved lock, unlock it to restore
14635 ** the original state */
14636 _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
14639 OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
14641 return r;
14644 /* AFP-style locking following the behavior of unixLock, see the unixLock
14645 ** function comments for details of lock management. */
14646 static int afpUnixLock(OsFile *id, int locktype)
14648 int rc = SQLITE_OK;
14649 unixFile *pFile = (unixFile*)id;
14650 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
14651 int gotPendingLock = 0;
14653 assert( pFile );
14654 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h,
14655 locktypeName(locktype), locktypeName(pFile->locktype), getpid());
14656 /* If there is already a lock of this type or more restrictive on the
14657 ** OsFile, do nothing. Don't use the afp_end_lock: exit path, as
14658 ** sqlite3OsEnterMutex() hasn't been called yet.
14660 if( pFile->locktype>=locktype ){
14661 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h,
14662 locktypeName(locktype));
14663 return SQLITE_OK;
14666 /* Make sure the locking sequence is correct
14668 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
14669 assert( locktype!=PENDING_LOCK );
14670 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
14672 /* This mutex is needed because pFile->pLock is shared across threads
14674 sqlite3OsEnterMutex();
14676 /* Make sure the current thread owns the pFile.
14678 rc = transferOwnership(pFile);
14679 if( rc!=SQLITE_OK ){
14680 sqlite3OsLeaveMutex();
14681 return rc;
14684 /* A PENDING lock is needed before acquiring a SHARED lock and before
14685 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
14686 ** be released.
14688 if( locktype==SHARED_LOCK
14689 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
14691 int failed = _AFPFSSetLock(context->filePath, pFile->h,
14692 PENDING_BYTE, 1, 1);
14693 if (failed) {
14694 rc = SQLITE_BUSY;
14695 goto afp_end_lock;
14699 /* If control gets to this point, then actually go ahead and make
14700 ** operating system calls for the specified lock.
14702 if( locktype==SHARED_LOCK ){
14703 int lk, failed;
14704 int tries = 0;
14706 /* Now get the read-lock */
14707 /* note that the quality of the randomness doesn't matter that much */
14708 lk = random();
14709 context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
14710 failed = _AFPFSSetLock(context->filePath, pFile->h,
14711 SHARED_FIRST+context->sharedLockByte, 1, 1);
14713 /* Drop the temporary PENDING lock */
14714 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
14715 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
14716 goto afp_end_lock;
14719 if( failed ){
14720 rc = SQLITE_BUSY;
14721 } else {
14722 pFile->locktype = SHARED_LOCK;
14724 }else{
14725 /* The request was for a RESERVED or EXCLUSIVE lock. It is
14726 ** assumed that there is a SHARED or greater lock on the file
14727 ** already.
14729 int failed = 0;
14730 assert( 0!=pFile->locktype );
14731 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
14732 /* Acquire a RESERVED lock */
14733 failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
14735 if (!failed && locktype == EXCLUSIVE_LOCK) {
14736 /* Acquire an EXCLUSIVE lock */
14738 /* Remove the shared lock before trying the range. we'll need to
14739 ** reestablish the shared lock if we can't get the afpUnixUnlock
14741 if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
14742 context->sharedLockByte, 1, 0)) {
14743 /* now attemmpt to get the exclusive lock range */
14744 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
14745 SHARED_SIZE, 1);
14746 if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
14747 context->sharedLockByte, 1, 1)) {
14748 rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
14750 } else {
14751 /* */
14752 rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
14755 if( failed && rc == SQLITE_OK){
14756 rc = SQLITE_BUSY;
14760 if( rc==SQLITE_OK ){
14761 pFile->locktype = locktype;
14762 }else if( locktype==EXCLUSIVE_LOCK ){
14763 pFile->locktype = PENDING_LOCK;
14766 afp_end_lock:
14767 sqlite3OsLeaveMutex();
14768 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype),
14769 rc==SQLITE_OK ? "ok" : "failed");
14770 return rc;
14774 ** Lower the locking level on file descriptor pFile to locktype. locktype
14775 ** must be either NO_LOCK or SHARED_LOCK.
14777 ** If the locking level of the file descriptor is already at or below
14778 ** the requested locking level, this routine is a no-op.
14780 static int afpUnixUnlock(OsFile *id, int locktype) {
14781 struct flock lock;
14782 int rc = SQLITE_OK;
14783 unixFile *pFile = (unixFile*)id;
14784 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
14786 assert( pFile );
14787 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype,
14788 pFile->locktype, getpid());
14790 assert( locktype<=SHARED_LOCK );
14791 if( pFile->locktype<=locktype ){
14792 return SQLITE_OK;
14794 if( CHECK_THREADID(pFile) ){
14795 return SQLITE_MISUSE;
14797 sqlite3OsEnterMutex();
14798 if( pFile->locktype>SHARED_LOCK ){
14799 if( locktype==SHARED_LOCK ){
14800 int failed = 0;
14802 /* unlock the exclusive range - then re-establish the shared lock */
14803 if (pFile->locktype==EXCLUSIVE_LOCK) {
14804 failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST,
14805 SHARED_SIZE, 0);
14806 if (!failed) {
14807 /* successfully removed the exclusive lock */
14808 if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
14809 context->sharedLockByte, 1, 1)) {
14810 /* failed to re-establish our shared lock */
14811 rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
14813 } else {
14814 /* This should never happen - failed to unlock the exclusive range */
14815 rc = SQLITE_IOERR_UNLOCK;
14819 if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
14820 if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
14821 /* failed to release the pending lock */
14822 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
14825 if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
14826 if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
14827 /* failed to release the reserved lock */
14828 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
14832 if( locktype==NO_LOCK ){
14833 int failed = _AFPFSSetLock(context->filePath, pFile->h,
14834 SHARED_FIRST + context->sharedLockByte, 1, 0);
14835 if (failed) {
14836 rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
14839 if (rc == SQLITE_OK)
14840 pFile->locktype = locktype;
14841 sqlite3OsLeaveMutex();
14842 return rc;
14846 ** Close a file & cleanup AFP specific locking context
14848 static int afpUnixClose(OsFile **pId) {
14849 unixFile *id = (unixFile*)*pId;
14851 if( !id ) return SQLITE_OK;
14852 afpUnixUnlock(*pId, NO_LOCK);
14853 /* free the AFP locking structure */
14854 if (id->lockingContext != NULL) {
14855 if (((afpLockingContext *)id->lockingContext)->filePath != NULL)
14856 sqlite3ThreadSafeFree(((afpLockingContext*)id->lockingContext)->filePath);
14857 sqlite3ThreadSafeFree(id->lockingContext);
14860 if( id->dirfd>=0 ) close(id->dirfd);
14861 id->dirfd = -1;
14862 close(id->h);
14863 id->isOpen = 0;
14864 OSTRACE2("CLOSE %-3d\n", id->h);
14865 OpenCounter(-1);
14866 sqlite3ThreadSafeFree(id);
14867 *pId = 0;
14868 return SQLITE_OK;
14872 #pragma mark flock() style locking
14875 ** The flockLockingContext is not used
14877 typedef void flockLockingContext;
14879 static int flockUnixCheckReservedLock(OsFile *id) {
14880 unixFile *pFile = (unixFile*)id;
14882 if (pFile->locktype == RESERVED_LOCK) {
14883 return 1; /* already have a reserved lock */
14884 } else {
14885 /* attempt to get the lock */
14886 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
14887 if (!rc) {
14888 /* got the lock, unlock it */
14889 flock(pFile->h, LOCK_UN);
14890 return 0; /* no one has it reserved */
14892 return 1; /* someone else might have it reserved */
14896 static int flockUnixLock(OsFile *id, int locktype) {
14897 unixFile *pFile = (unixFile*)id;
14899 /* if we already have a lock, it is exclusive.
14900 ** Just adjust level and punt on outta here. */
14901 if (pFile->locktype > NO_LOCK) {
14902 pFile->locktype = locktype;
14903 return SQLITE_OK;
14906 /* grab an exclusive lock */
14907 int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
14908 if (rc) {
14909 /* didn't get, must be busy */
14910 return SQLITE_BUSY;
14911 } else {
14912 /* got it, set the type and return ok */
14913 pFile->locktype = locktype;
14914 return SQLITE_OK;
14918 static int flockUnixUnlock(OsFile *id, int locktype) {
14919 unixFile *pFile = (unixFile*)id;
14921 assert( locktype<=SHARED_LOCK );
14923 /* no-op if possible */
14924 if( pFile->locktype==locktype ){
14925 return SQLITE_OK;
14928 /* shared can just be set because we always have an exclusive */
14929 if (locktype==SHARED_LOCK) {
14930 pFile->locktype = locktype;
14931 return SQLITE_OK;
14934 /* no, really, unlock. */
14935 int rc = flock(pFile->h, LOCK_UN);
14936 if (rc)
14937 return SQLITE_IOERR_UNLOCK;
14938 else {
14939 pFile->locktype = NO_LOCK;
14940 return SQLITE_OK;
14945 ** Close a file.
14947 static int flockUnixClose(OsFile **pId) {
14948 unixFile *id = (unixFile*)*pId;
14950 if( !id ) return SQLITE_OK;
14951 flockUnixUnlock(*pId, NO_LOCK);
14953 if( id->dirfd>=0 ) close(id->dirfd);
14954 id->dirfd = -1;
14955 sqlite3OsEnterMutex();
14957 close(id->h);
14958 sqlite3OsLeaveMutex();
14959 id->isOpen = 0;
14960 OSTRACE2("CLOSE %-3d\n", id->h);
14961 OpenCounter(-1);
14962 sqlite3ThreadSafeFree(id);
14963 *pId = 0;
14964 return SQLITE_OK;
14967 #pragma mark Old-School .lock file based locking
14970 ** The dotlockLockingContext structure contains all dotlock (.lock) lock
14971 ** specific state
14973 typedef struct dotlockLockingContext dotlockLockingContext;
14974 struct dotlockLockingContext {
14975 char *lockPath;
14979 static int dotlockUnixCheckReservedLock(OsFile *id) {
14980 unixFile *pFile = (unixFile*)id;
14981 dotlockLockingContext *context =
14982 (dotlockLockingContext *) pFile->lockingContext;
14984 if (pFile->locktype == RESERVED_LOCK) {
14985 return 1; /* already have a reserved lock */
14986 } else {
14987 struct stat statBuf;
14988 if (lstat(context->lockPath,&statBuf) == 0)
14989 /* file exists, someone else has the lock */
14990 return 1;
14991 else
14992 /* file does not exist, we could have it if we want it */
14993 return 0;
14997 static int dotlockUnixLock(OsFile *id, int locktype) {
14998 unixFile *pFile = (unixFile*)id;
14999 dotlockLockingContext *context =
15000 (dotlockLockingContext *) pFile->lockingContext;
15002 /* if we already have a lock, it is exclusive.
15003 ** Just adjust level and punt on outta here. */
15004 if (pFile->locktype > NO_LOCK) {
15005 pFile->locktype = locktype;
15007 /* Always update the timestamp on the old file */
15008 utimes(context->lockPath,NULL);
15009 return SQLITE_OK;
15012 /* check to see if lock file already exists */
15013 struct stat statBuf;
15014 if (lstat(context->lockPath,&statBuf) == 0){
15015 return SQLITE_BUSY; /* it does, busy */
15018 /* grab an exclusive lock */
15019 int fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
15020 if (fd < 0) {
15021 /* failed to open/create the file, someone else may have stolen the lock */
15022 return SQLITE_BUSY;
15024 close(fd);
15026 /* got it, set the type and return ok */
15027 pFile->locktype = locktype;
15028 return SQLITE_OK;
15031 static int dotlockUnixUnlock(OsFile *id, int locktype) {
15032 unixFile *pFile = (unixFile*)id;
15033 dotlockLockingContext *context =
15034 (dotlockLockingContext *) pFile->lockingContext;
15036 assert( locktype<=SHARED_LOCK );
15038 /* no-op if possible */
15039 if( pFile->locktype==locktype ){
15040 return SQLITE_OK;
15043 /* shared can just be set because we always have an exclusive */
15044 if (locktype==SHARED_LOCK) {
15045 pFile->locktype = locktype;
15046 return SQLITE_OK;
15049 /* no, really, unlock. */
15050 unlink(context->lockPath);
15051 pFile->locktype = NO_LOCK;
15052 return SQLITE_OK;
15056 ** Close a file.
15058 static int dotlockUnixClose(OsFile **pId) {
15059 unixFile *id = (unixFile*)*pId;
15061 if( !id ) return SQLITE_OK;
15062 dotlockUnixUnlock(*pId, NO_LOCK);
15063 /* free the dotlock locking structure */
15064 if (id->lockingContext != NULL) {
15065 if (((dotlockLockingContext *)id->lockingContext)->lockPath != NULL)
15066 sqlite3ThreadSafeFree( ( (dotlockLockingContext *)
15067 id->lockingContext)->lockPath);
15068 sqlite3ThreadSafeFree(id->lockingContext);
15071 if( id->dirfd>=0 ) close(id->dirfd);
15072 id->dirfd = -1;
15073 sqlite3OsEnterMutex();
15075 close(id->h);
15077 sqlite3OsLeaveMutex();
15078 id->isOpen = 0;
15079 OSTRACE2("CLOSE %-3d\n", id->h);
15080 OpenCounter(-1);
15081 sqlite3ThreadSafeFree(id);
15082 *pId = 0;
15083 return SQLITE_OK;
15087 #pragma mark No locking
15090 ** The nolockLockingContext is void
15092 typedef void nolockLockingContext;
15094 static int nolockUnixCheckReservedLock(OsFile *id) {
15095 return 0;
15098 static int nolockUnixLock(OsFile *id, int locktype) {
15099 return SQLITE_OK;
15102 static int nolockUnixUnlock(OsFile *id, int locktype) {
15103 return SQLITE_OK;
15107 ** Close a file.
15109 static int nolockUnixClose(OsFile **pId) {
15110 unixFile *id = (unixFile*)*pId;
15112 if( !id ) return SQLITE_OK;
15113 if( id->dirfd>=0 ) close(id->dirfd);
15114 id->dirfd = -1;
15115 sqlite3OsEnterMutex();
15117 close(id->h);
15119 sqlite3OsLeaveMutex();
15120 id->isOpen = 0;
15121 OSTRACE2("CLOSE %-3d\n", id->h);
15122 OpenCounter(-1);
15123 sqlite3ThreadSafeFree(id);
15124 *pId = 0;
15125 return SQLITE_OK;
15128 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
15131 ** Turn a relative pathname into a full pathname. Return a pointer
15132 ** to the full pathname stored in space obtained from sqliteMalloc().
15133 ** The calling function is responsible for freeing this space once it
15134 ** is no longer needed.
15136 static char *sqlite3UnixFullPathname(const char *zRelative){
15137 char *zFull = 0;
15138 if( zRelative[0]=='/' ){
15139 sqlite3SetString(&zFull, zRelative, (char*)0);
15140 }else{
15141 char *zBuf = sqliteMalloc(5000);
15142 if( zBuf==0 ){
15143 return 0;
15145 zBuf[0] = 0;
15146 sqlite3SetString(&zFull, getcwd(zBuf, 5000), "/", zRelative,
15147 (char*)0);
15148 sqliteFree(zBuf);
15151 #if 0
15153 ** Remove "/./" path elements and convert "/A/./" path elements
15154 ** to just "/".
15156 if( zFull ){
15157 int i, j;
15158 for(i=j=0; zFull[i]; i++){
15159 if( zFull[i]=='/' ){
15160 if( zFull[i+1]=='/' ) continue;
15161 if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
15162 i += 1;
15163 continue;
15165 if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
15166 while( j>0 && zFull[j-1]!='/' ){ j--; }
15167 i += 3;
15168 continue;
15171 zFull[j++] = zFull[i];
15173 zFull[j] = 0;
15175 #endif
15177 return zFull;
15181 ** Change the value of the fullsync flag in the given file descriptor.
15183 static void unixSetFullSync(OsFile *id, int v){
15184 ((unixFile*)id)->fullSync = v;
15188 ** Return the underlying file handle for an OsFile
15190 static int unixFileHandle(OsFile *id){
15191 return ((unixFile*)id)->h;
15195 ** Return an integer that indices the type of lock currently held
15196 ** by this handle. (Used for testing and analysis only.)
15198 static int unixLockState(OsFile *id){
15199 return ((unixFile*)id)->locktype;
15203 ** Return the sector size in bytes of the underlying block device for
15204 ** the specified file. This is almost always 512 bytes, but may be
15205 ** larger for some devices.
15207 ** SQLite code assumes this function cannot fail. It also assumes that
15208 ** if two files are created in the same file-system directory (i.e.
15209 ** a database and it's journal file) that the sector size will be the
15210 ** same for both.
15212 static int unixSectorSize(OsFile *id){
15213 return SQLITE_DEFAULT_SECTOR_SIZE;
15217 ** This vector defines all the methods that can operate on an OsFile
15218 ** for unix.
15220 static const IoMethod sqlite3UnixIoMethod = {
15221 unixClose,
15222 unixOpenDirectory,
15223 unixRead,
15224 unixWrite,
15225 unixSeek,
15226 unixTruncate,
15227 unixSync,
15228 unixSetFullSync,
15229 unixFileHandle,
15230 unixFileSize,
15231 unixLock,
15232 unixUnlock,
15233 unixLockState,
15234 unixCheckReservedLock,
15235 unixSectorSize,
15238 #ifdef SQLITE_ENABLE_LOCKING_STYLE
15240 ** This vector defines all the methods that can operate on an OsFile
15241 ** for unix with AFP style file locking.
15243 static const IoMethod sqlite3AFPLockingUnixIoMethod = {
15244 afpUnixClose,
15245 unixOpenDirectory,
15246 unixRead,
15247 unixWrite,
15248 unixSeek,
15249 unixTruncate,
15250 unixSync,
15251 unixSetFullSync,
15252 unixFileHandle,
15253 unixFileSize,
15254 afpUnixLock,
15255 afpUnixUnlock,
15256 unixLockState,
15257 afpUnixCheckReservedLock,
15258 unixSectorSize,
15262 ** This vector defines all the methods that can operate on an OsFile
15263 ** for unix with flock() style file locking.
15265 static const IoMethod sqlite3FlockLockingUnixIoMethod = {
15266 flockUnixClose,
15267 unixOpenDirectory,
15268 unixRead,
15269 unixWrite,
15270 unixSeek,
15271 unixTruncate,
15272 unixSync,
15273 unixSetFullSync,
15274 unixFileHandle,
15275 unixFileSize,
15276 flockUnixLock,
15277 flockUnixUnlock,
15278 unixLockState,
15279 flockUnixCheckReservedLock,
15280 unixSectorSize,
15284 ** This vector defines all the methods that can operate on an OsFile
15285 ** for unix with dotlock style file locking.
15287 static const IoMethod sqlite3DotlockLockingUnixIoMethod = {
15288 dotlockUnixClose,
15289 unixOpenDirectory,
15290 unixRead,
15291 unixWrite,
15292 unixSeek,
15293 unixTruncate,
15294 unixSync,
15295 unixSetFullSync,
15296 unixFileHandle,
15297 unixFileSize,
15298 dotlockUnixLock,
15299 dotlockUnixUnlock,
15300 unixLockState,
15301 dotlockUnixCheckReservedLock,
15302 unixSectorSize,
15306 ** This vector defines all the methods that can operate on an OsFile
15307 ** for unix with dotlock style file locking.
15309 static const IoMethod sqlite3NolockLockingUnixIoMethod = {
15310 nolockUnixClose,
15311 unixOpenDirectory,
15312 unixRead,
15313 unixWrite,
15314 unixSeek,
15315 unixTruncate,
15316 unixSync,
15317 unixSetFullSync,
15318 unixFileHandle,
15319 unixFileSize,
15320 nolockUnixLock,
15321 nolockUnixUnlock,
15322 unixLockState,
15323 nolockUnixCheckReservedLock,
15324 unixSectorSize,
15327 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
15330 ** Allocate memory for a new unixFile and initialize that unixFile.
15331 ** Write a pointer to the new unixFile into *pId.
15332 ** If we run out of memory, close the file and return an error.
15334 #ifdef SQLITE_ENABLE_LOCKING_STYLE
15336 ** When locking extensions are enabled, the filepath and locking style
15337 ** are needed to determine the unixFile pMethod to use for locking operations.
15338 ** The locking-style specific lockingContext data structure is created
15339 ** and assigned here also.
15341 static int allocateUnixFile(
15342 int h, /* Open file descriptor of file being opened */
15343 OsFile **pId, /* Write completed initialization here */
15344 const char *zFilename, /* Name of the file being opened */
15345 int delFlag /* Delete-on-or-before-close flag */
15347 sqlite3LockingStyle lockingStyle;
15348 unixFile *pNew;
15349 unixFile f;
15350 int rc;
15352 memset(&f, 0, sizeof(f));
15353 lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
15354 if ( lockingStyle == posixLockingStyle ) {
15355 sqlite3OsEnterMutex();
15356 rc = findLockInfo(h, &f.pLock, &f.pOpen);
15357 sqlite3OsLeaveMutex();
15358 if( rc ){
15359 close(h);
15360 unlink(zFilename);
15361 return SQLITE_NOMEM;
15363 } else {
15364 /* pLock and pOpen are only used for posix advisory locking */
15365 f.pLock = NULL;
15366 f.pOpen = NULL;
15368 if( delFlag ){
15369 unlink(zFilename);
15371 f.dirfd = -1;
15372 f.h = h;
15373 SET_THREADID(&f);
15374 pNew = sqlite3ThreadSafeMalloc( sizeof(unixFile) );
15375 if( pNew==0 ){
15376 close(h);
15377 sqlite3OsEnterMutex();
15378 releaseLockInfo(f.pLock);
15379 releaseOpenCnt(f.pOpen);
15380 sqlite3OsLeaveMutex();
15381 *pId = 0;
15382 return SQLITE_NOMEM;
15383 }else{
15384 *pNew = f;
15385 switch(lockingStyle) {
15386 case afpLockingStyle: {
15387 /* afp locking uses the file path so it needs to be included in
15388 ** the afpLockingContext */
15389 int nFilename;
15390 pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
15391 pNew->lockingContext =
15392 sqlite3ThreadSafeMalloc(sizeof(afpLockingContext));
15393 nFilename = strlen(zFilename)+1;
15394 ((afpLockingContext *)pNew->lockingContext)->filePath =
15395 sqlite3ThreadSafeMalloc(nFilename);
15396 memcpy(((afpLockingContext *)pNew->lockingContext)->filePath,
15397 zFilename, nFilename);
15398 srandomdev();
15399 break;
15401 case flockLockingStyle:
15402 /* flock locking doesn't need additional lockingContext information */
15403 pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
15404 break;
15405 case dotlockLockingStyle: {
15406 /* dotlock locking uses the file path so it needs to be included in
15407 ** the dotlockLockingContext */
15408 int nFilename;
15409 pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
15410 pNew->lockingContext = sqlite3ThreadSafeMalloc(
15411 sizeof(dotlockLockingContext));
15412 nFilename = strlen(zFilename) + 6;
15413 ((dotlockLockingContext *)pNew->lockingContext)->lockPath =
15414 sqlite3ThreadSafeMalloc( nFilename );
15415 sqlite3_snprintf(nFilename,
15416 ((dotlockLockingContext *)pNew->lockingContext)->lockPath,
15417 "%s.lock", zFilename);
15418 break;
15420 case posixLockingStyle:
15421 /* posix locking doesn't need additional lockingContext information */
15422 pNew->pMethod = &sqlite3UnixIoMethod;
15423 break;
15424 case noLockingStyle:
15425 case unsupportedLockingStyle:
15426 default:
15427 pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
15429 *pId = (OsFile*)pNew;
15430 OpenCounter(+1);
15431 return SQLITE_OK;
15434 #else /* SQLITE_ENABLE_LOCKING_STYLE */
15435 static int allocateUnixFile(
15436 int h, /* Open file descriptor on file being opened */
15437 OsFile **pId, /* Write the resul unixFile structure here */
15438 const char *zFilename, /* Name of the file being opened */
15439 int delFlag /* If true, delete the file on or before closing */
15441 unixFile *pNew;
15442 unixFile f;
15443 int rc;
15445 memset(&f, 0, sizeof(f));
15446 sqlite3OsEnterMutex();
15447 rc = findLockInfo(h, &f.pLock, &f.pOpen);
15448 sqlite3OsLeaveMutex();
15449 if( delFlag ){
15450 unlink(zFilename);
15452 if( rc ){
15453 close(h);
15454 return SQLITE_NOMEM;
15456 OSTRACE3("OPEN %-3d %s\n", h, zFilename);
15457 f.dirfd = -1;
15458 f.h = h;
15459 SET_THREADID(&f);
15460 pNew = sqlite3ThreadSafeMalloc( sizeof(unixFile) );
15461 if( pNew==0 ){
15462 close(h);
15463 sqlite3OsEnterMutex();
15464 releaseLockInfo(f.pLock);
15465 releaseOpenCnt(f.pOpen);
15466 sqlite3OsLeaveMutex();
15467 *pId = 0;
15468 return SQLITE_NOMEM;
15469 }else{
15470 *pNew = f;
15471 pNew->pMethod = &sqlite3UnixIoMethod;
15472 *pId = (OsFile*)pNew;
15473 OpenCounter(+1);
15474 return SQLITE_OK;
15477 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
15479 #endif /* SQLITE_OMIT_DISKIO */
15480 /***************************************************************************
15481 ** Everything above deals with file I/O. Everything that follows deals
15482 ** with other miscellanous aspects of the operating system interface
15483 ****************************************************************************/
15486 #ifndef SQLITE_OMIT_LOAD_EXTENSION
15488 ** Interfaces for opening a shared library, finding entry points
15489 ** within the shared library, and closing the shared library.
15491 #include <dlfcn.h>
15492 static void *sqlite3UnixDlopen(const char *zFilename){
15493 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
15495 static void *sqlite3UnixDlsym(void *pHandle, const char *zSymbol){
15496 return dlsym(pHandle, zSymbol);
15498 static int sqlite3UnixDlclose(void *pHandle){
15499 return dlclose(pHandle);
15501 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
15504 ** Get information to seed the random number generator. The seed
15505 ** is written into the buffer zBuf[256]. The calling function must
15506 ** supply a sufficiently large buffer.
15508 static int sqlite3UnixRandomSeed(char *zBuf){
15509 /* We have to initialize zBuf to prevent valgrind from reporting
15510 ** errors. The reports issued by valgrind are incorrect - we would
15511 ** prefer that the randomness be increased by making use of the
15512 ** uninitialized space in zBuf - but valgrind errors tend to worry
15513 ** some users. Rather than argue, it seems easier just to initialize
15514 ** the whole array and silence valgrind, even if that means less randomness
15515 ** in the random seed.
15517 ** When testing, initializing zBuf[] to zero is all we do. That means
15518 ** that we always use the same random number sequence. This makes the
15519 ** tests repeatable.
15521 memset(zBuf, 0, 256);
15522 #if !defined(SQLITE_TEST)
15524 int pid, fd;
15525 fd = open("/dev/urandom", O_RDONLY);
15526 if( fd<0 ){
15527 time_t t;
15528 time(&t);
15529 memcpy(zBuf, &t, sizeof(t));
15530 pid = getpid();
15531 memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
15532 }else{
15533 read(fd, zBuf, 256);
15534 close(fd);
15537 #endif
15538 return SQLITE_OK;
15542 ** Sleep for a little while. Return the amount of time slept.
15543 ** The argument is the number of milliseconds we want to sleep.
15545 static int sqlite3UnixSleep(int ms){
15546 #if defined(HAVE_USLEEP) && HAVE_USLEEP
15547 usleep(ms*1000);
15548 return ms;
15549 #else
15550 sleep((ms+999)/1000);
15551 return 1000*((ms+999)/1000);
15552 #endif
15556 ** Static variables used for thread synchronization.
15558 ** inMutex the nesting depth of the recursive mutex. The thread
15559 ** holding mutexMain can read this variable at any time.
15560 ** But is must hold mutexAux to change this variable. Other
15561 ** threads must hold mutexAux to read the variable and can
15562 ** never write.
15564 ** mutexOwner The thread id of the thread holding mutexMain. Same
15565 ** access rules as for inMutex.
15567 ** mutexOwnerValid True if the value in mutexOwner is valid. The same
15568 ** access rules apply as for inMutex.
15570 ** mutexMain The main mutex. Hold this mutex in order to get exclusive
15571 ** access to SQLite data structures.
15573 ** mutexAux An auxiliary mutex needed to access variables defined above.
15575 ** Mutexes are always acquired in this order: mutexMain mutexAux. It
15576 ** is not necessary to acquire mutexMain in order to get mutexAux - just
15577 ** do not attempt to acquire them in the reverse order: mutexAux mutexMain.
15578 ** Either get the mutexes with mutexMain first or get mutexAux only.
15580 ** When running on a platform where the three variables inMutex, mutexOwner,
15581 ** and mutexOwnerValid can be set atomically, the mutexAux is not required.
15582 ** On many systems, all three are 32-bit integers and writing to a 32-bit
15583 ** integer is atomic. I think. But there are no guarantees. So it seems
15584 ** safer to protect them using mutexAux.
15586 static int inMutex = 0;
15587 #ifdef SQLITE_UNIX_THREADS
15588 static pthread_t mutexOwner; /* Thread holding mutexMain */
15589 static int mutexOwnerValid = 0; /* True if mutexOwner is valid */
15590 static pthread_mutex_t mutexMain = PTHREAD_MUTEX_INITIALIZER; /* The mutex */
15591 static pthread_mutex_t mutexAux = PTHREAD_MUTEX_INITIALIZER; /* Aux mutex */
15592 #endif
15595 ** The following pair of routine implement mutual exclusion for
15596 ** multi-threaded processes. Only a single thread is allowed to
15597 ** executed code that is surrounded by EnterMutex() and LeaveMutex().
15599 ** SQLite uses only a single Mutex. There is not much critical
15600 ** code and what little there is executes quickly and without blocking.
15602 ** As of version 3.3.2, this mutex must be recursive.
15604 static void sqlite3UnixEnterMutex(){
15605 #ifdef SQLITE_UNIX_THREADS
15606 pthread_mutex_lock(&mutexAux);
15607 if( !mutexOwnerValid || !pthread_equal(mutexOwner, pthread_self()) ){
15608 pthread_mutex_unlock(&mutexAux);
15609 pthread_mutex_lock(&mutexMain);
15610 assert( inMutex==0 );
15611 assert( !mutexOwnerValid );
15612 pthread_mutex_lock(&mutexAux);
15613 mutexOwner = pthread_self();
15614 mutexOwnerValid = 1;
15616 inMutex++;
15617 pthread_mutex_unlock(&mutexAux);
15618 #else
15619 inMutex++;
15620 #endif
15622 static void sqlite3UnixLeaveMutex(){
15623 assert( inMutex>0 );
15624 #ifdef SQLITE_UNIX_THREADS
15625 pthread_mutex_lock(&mutexAux);
15626 inMutex--;
15627 assert( pthread_equal(mutexOwner, pthread_self()) );
15628 if( inMutex==0 ){
15629 assert( mutexOwnerValid );
15630 mutexOwnerValid = 0;
15631 pthread_mutex_unlock(&mutexMain);
15633 pthread_mutex_unlock(&mutexAux);
15634 #else
15635 inMutex--;
15636 #endif
15640 ** Return TRUE if the mutex is currently held.
15642 ** If the thisThrd parameter is true, return true only if the
15643 ** calling thread holds the mutex. If the parameter is false, return
15644 ** true if any thread holds the mutex.
15646 static int sqlite3UnixInMutex(int thisThrd){
15647 #ifdef SQLITE_UNIX_THREADS
15648 int rc;
15649 pthread_mutex_lock(&mutexAux);
15650 rc = inMutex>0 && (thisThrd==0 || pthread_equal(mutexOwner,pthread_self()));
15651 pthread_mutex_unlock(&mutexAux);
15652 return rc;
15653 #else
15654 return inMutex>0;
15655 #endif
15659 ** Remember the number of thread-specific-data blocks allocated.
15660 ** Use this to verify that we are not leaking thread-specific-data.
15661 ** Ticket #1601
15663 #ifdef SQLITE_TEST
15664 int sqlite3_tsd_count = 0;
15665 # ifdef SQLITE_UNIX_THREADS
15666 static pthread_mutex_t tsd_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
15667 # define TSD_COUNTER(N) \
15668 pthread_mutex_lock(&tsd_counter_mutex); \
15669 sqlite3_tsd_count += N; \
15670 pthread_mutex_unlock(&tsd_counter_mutex);
15671 # else
15672 # define TSD_COUNTER(N) sqlite3_tsd_count += N
15673 # endif
15674 #else
15675 # define TSD_COUNTER(N) /* no-op */
15676 #endif
15679 ** If called with allocateFlag>0, then return a pointer to thread
15680 ** specific data for the current thread. Allocate and zero the
15681 ** thread-specific data if it does not already exist.
15683 ** If called with allocateFlag==0, then check the current thread
15684 ** specific data. Return it if it exists. If it does not exist,
15685 ** then return NULL.
15687 ** If called with allocateFlag<0, check to see if the thread specific
15688 ** data is allocated and is all zero. If it is then deallocate it.
15689 ** Return a pointer to the thread specific data or NULL if it is
15690 ** unallocated or gets deallocated.
15692 static ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
15693 static const ThreadData zeroData = {0}; /* Initializer to silence warnings
15694 ** from broken compilers */
15695 #ifdef SQLITE_UNIX_THREADS
15696 static pthread_key_t key;
15697 static int keyInit = 0;
15698 ThreadData *pTsd;
15700 if( !keyInit ){
15701 sqlite3OsEnterMutex();
15702 if( !keyInit ){
15703 int rc;
15704 rc = pthread_key_create(&key, 0);
15705 if( rc ){
15706 sqlite3OsLeaveMutex();
15707 return 0;
15709 keyInit = 1;
15711 sqlite3OsLeaveMutex();
15714 pTsd = pthread_getspecific(key);
15715 if( allocateFlag>0 ){
15716 if( pTsd==0 ){
15717 if( !sqlite3TestMallocFail() ){
15718 pTsd = sqlite3OsMalloc(sizeof(zeroData));
15720 #ifdef SQLITE_MEMDEBUG
15721 sqlite3_isFail = 0;
15722 #endif
15723 if( pTsd ){
15724 *pTsd = zeroData;
15725 pthread_setspecific(key, pTsd);
15726 TSD_COUNTER(+1);
15729 }else if( pTsd!=0 && allocateFlag<0
15730 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
15731 sqlite3OsFree(pTsd);
15732 pthread_setspecific(key, 0);
15733 TSD_COUNTER(-1);
15734 pTsd = 0;
15736 return pTsd;
15737 #else
15738 static ThreadData *pTsd = 0;
15739 if( allocateFlag>0 ){
15740 if( pTsd==0 ){
15741 if( !sqlite3TestMallocFail() ){
15742 pTsd = sqlite3OsMalloc( sizeof(zeroData) );
15744 #ifdef SQLITE_MEMDEBUG
15745 sqlite3_isFail = 0;
15746 #endif
15747 if( pTsd ){
15748 *pTsd = zeroData;
15749 TSD_COUNTER(+1);
15752 }else if( pTsd!=0 && allocateFlag<0
15753 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
15754 sqlite3OsFree(pTsd);
15755 TSD_COUNTER(-1);
15756 pTsd = 0;
15758 return pTsd;
15759 #endif
15763 ** The following variable, if set to a non-zero value, becomes the result
15764 ** returned from sqlite3OsCurrentTime(). This is used for testing.
15766 #ifdef SQLITE_TEST
15767 int sqlite3_current_time = 0;
15768 #endif
15771 ** Find the current time (in Universal Coordinated Time). Write the
15772 ** current time and date as a Julian Day number into *prNow and
15773 ** return 0. Return 1 if the time and date cannot be found.
15775 static int sqlite3UnixCurrentTime(double *prNow){
15776 #ifdef NO_GETTOD
15777 time_t t;
15778 time(&t);
15779 *prNow = t/86400.0 + 2440587.5;
15780 #else
15781 struct timeval sNow;
15782 gettimeofday(&sNow, 0);
15783 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
15784 #endif
15785 #ifdef SQLITE_TEST
15786 if( sqlite3_current_time ){
15787 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
15789 #endif
15790 return 0;
15793 #endif /* OS_UNIX */
15795 /************** End of os_unix.c *********************************************/
15796 /************** Begin file os_win.c ******************************************/
15798 ** 2004 May 22
15800 ** The author disclaims copyright to this source code. In place of
15801 ** a legal notice, here is a blessing:
15803 ** May you do good and not evil.
15804 ** May you find forgiveness for yourself and forgive others.
15805 ** May you share freely, never taking more than you give.
15807 ******************************************************************************
15809 ** This file contains code that is specific to windows.
15811 #if OS_WIN /* This file is used for windows only */
15813 #include <winbase.h>
15815 #ifdef __CYGWIN__
15816 # include <sys/cygwin.h>
15817 #endif
15820 ** Macros used to determine whether or not to use threads.
15822 #if defined(THREADSAFE) && THREADSAFE
15823 # define SQLITE_W32_THREADS 1
15824 #endif
15827 ** Include code that is common to all os_*.c files
15829 /************** Include os_common.h in the middle of os_win.c ****************/
15830 /************** Begin file os_common.h ***************************************/
15832 ** 2004 May 22
15834 ** The author disclaims copyright to this source code. In place of
15835 ** a legal notice, here is a blessing:
15837 ** May you do good and not evil.
15838 ** May you find forgiveness for yourself and forgive others.
15839 ** May you share freely, never taking more than you give.
15841 ******************************************************************************
15843 ** This file contains macros and a little bit of code that is common to
15844 ** all of the platform-specific files (os_*.c) and is #included into those
15845 ** files.
15847 ** This file should be #included by the os_*.c files only. It is not a
15848 ** general purpose header file.
15852 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
15853 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
15854 ** switch. The following code should catch this problem at compile-time.
15856 #ifdef MEMORY_DEBUG
15857 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
15858 #endif
15862 * When testing, this global variable stores the location of the
15863 * pending-byte in the database file.
15865 #ifdef SQLITE_TEST
15866 unsigned int sqlite3_pending_byte = 0x40000000;
15867 #endif
15869 int sqlite3_os_trace = 0;
15870 #ifdef SQLITE_DEBUG
15871 #define OSTRACE1(X) if( sqlite3_os_trace ) sqlite3DebugPrintf(X)
15872 #define OSTRACE2(X,Y) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y)
15873 #define OSTRACE3(X,Y,Z) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z)
15874 #define OSTRACE4(X,Y,Z,A) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A)
15875 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3_os_trace ) sqlite3DebugPrintf(X,Y,Z,A,B)
15876 #define OSTRACE6(X,Y,Z,A,B,C) \
15877 if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
15878 #define OSTRACE7(X,Y,Z,A,B,C,D) \
15879 if(sqlite3_os_trace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
15880 #else
15881 #define OSTRACE1(X)
15882 #define OSTRACE2(X,Y)
15883 #define OSTRACE3(X,Y,Z)
15884 #define OSTRACE4(X,Y,Z,A)
15885 #define OSTRACE5(X,Y,Z,A,B)
15886 #define OSTRACE6(X,Y,Z,A,B,C)
15887 #define OSTRACE7(X,Y,Z,A,B,C,D)
15888 #endif
15891 ** Macros for performance tracing. Normally turned off. Only works
15892 ** on i486 hardware.
15894 #ifdef SQLITE_PERFORMANCE_TRACE
15895 __inline__ unsigned long long int hwtime(void){
15896 unsigned long long int x;
15897 __asm__("rdtsc\n\t"
15898 "mov %%edx, %%ecx\n\t"
15899 :"=A" (x));
15900 return x;
15902 static unsigned long long int g_start;
15903 static unsigned int elapse;
15904 #define TIMER_START g_start=hwtime()
15905 #define TIMER_END elapse=hwtime()-g_start
15906 #define TIMER_ELAPSED elapse
15907 #else
15908 #define TIMER_START
15909 #define TIMER_END
15910 #define TIMER_ELAPSED 0
15911 #endif
15914 ** If we compile with the SQLITE_TEST macro set, then the following block
15915 ** of code will give us the ability to simulate a disk I/O error. This
15916 ** is used for testing the I/O recovery logic.
15918 #ifdef SQLITE_TEST
15919 int sqlite3_io_error_hit = 0;
15920 int sqlite3_io_error_pending = 0;
15921 int sqlite3_io_error_persist = 0;
15922 int sqlite3_diskfull_pending = 0;
15923 int sqlite3_diskfull = 0;
15924 #define SimulateIOError(CODE) \
15925 if( sqlite3_io_error_pending || sqlite3_io_error_hit ) \
15926 if( sqlite3_io_error_pending-- == 1 \
15927 || (sqlite3_io_error_persist && sqlite3_io_error_hit) ) \
15928 { local_ioerr(); CODE; }
15929 static void local_ioerr(){
15930 IOTRACE(("IOERR\n"));
15931 sqlite3_io_error_hit = 1;
15933 #define SimulateDiskfullError(CODE) \
15934 if( sqlite3_diskfull_pending ){ \
15935 if( sqlite3_diskfull_pending == 1 ){ \
15936 local_ioerr(); \
15937 sqlite3_diskfull = 1; \
15938 sqlite3_io_error_hit = 1; \
15939 CODE; \
15940 }else{ \
15941 sqlite3_diskfull_pending--; \
15944 #else
15945 #define SimulateIOError(A)
15946 #define SimulateDiskfullError(A)
15947 #endif
15950 ** When testing, keep a count of the number of open files.
15952 #ifdef SQLITE_TEST
15953 int sqlite3_open_file_count = 0;
15954 #define OpenCounter(X) sqlite3_open_file_count+=(X)
15955 #else
15956 #define OpenCounter(X)
15957 #endif
15960 ** sqlite3GenericMalloc
15961 ** sqlite3GenericRealloc
15962 ** sqlite3GenericOsFree
15963 ** sqlite3GenericAllocationSize
15965 ** Implementation of the os level dynamic memory allocation interface in terms
15966 ** of the standard malloc(), realloc() and free() found in many operating
15967 ** systems. No rocket science here.
15969 ** There are two versions of these four functions here. The version
15970 ** implemented here is only used if memory-management or memory-debugging is
15971 ** enabled. This version allocates an extra 8-bytes at the beginning of each
15972 ** block and stores the size of the allocation there.
15974 ** If neither memory-management or debugging is enabled, the second
15975 ** set of implementations is used instead.
15977 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || defined (SQLITE_MEMDEBUG)
15978 static void *sqlite3GenericMalloc(int n){
15979 char *p = (char *)malloc(n+8);
15980 assert(n>0);
15981 assert(sizeof(int)<=8);
15982 if( p ){
15983 *(int *)p = n;
15984 p += 8;
15986 return (void *)p;
15988 static void *sqlite3GenericRealloc(void *p, int n){
15989 char *p2 = ((char *)p - 8);
15990 assert(n>0);
15991 p2 = (char*)realloc(p2, n+8);
15992 if( p2 ){
15993 *(int *)p2 = n;
15994 p2 += 8;
15996 return (void *)p2;
15998 static void sqlite3GenericFree(void *p){
15999 assert(p);
16000 free((void *)((char *)p - 8));
16002 static int sqlite3GenericAllocationSize(void *p){
16003 return p ? *(int *)((char *)p - 8) : 0;
16005 #else
16006 static void *sqlite3GenericMalloc(int n){
16007 char *p = (char *)malloc(n);
16008 return (void *)p;
16010 static void *sqlite3GenericRealloc(void *p, int n){
16011 assert(n>0);
16012 p = realloc(p, n);
16013 return p;
16015 static void sqlite3GenericFree(void *p){
16016 assert(p);
16017 free(p);
16019 /* Never actually used, but needed for the linker */
16020 static int sqlite3GenericAllocationSize(void *p){ return 0; }
16021 #endif
16024 ** The default size of a disk sector
16026 #ifndef PAGER_SECTOR_SIZE
16027 # define PAGER_SECTOR_SIZE 512
16028 #endif
16030 /************** End of os_common.h *******************************************/
16031 /************** Continuing where we left off in os_win.c *********************/
16034 ** Determine if we are dealing with WindowsCE - which has a much
16035 ** reduced API.
16037 #if defined(_WIN32_WCE)
16038 # define OS_WINCE 1
16039 # define AreFileApisANSI() 1
16040 #else
16041 # define OS_WINCE 0
16042 #endif
16045 ** WinCE lacks native support for file locking so we have to fake it
16046 ** with some code of our own.
16048 #if OS_WINCE
16049 typedef struct winceLock {
16050 int nReaders; /* Number of reader locks obtained */
16051 BOOL bPending; /* Indicates a pending lock has been obtained */
16052 BOOL bReserved; /* Indicates a reserved lock has been obtained */
16053 BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
16054 } winceLock;
16055 #endif
16058 ** The winFile structure is a subclass of OsFile specific to the win32
16059 ** portability layer.
16061 typedef struct winFile winFile;
16062 struct winFile {
16063 IoMethod const *pMethod;/* Must be first */
16064 HANDLE h; /* Handle for accessing the file */
16065 unsigned char locktype; /* Type of lock currently held on this file */
16066 short sharedLockByte; /* Randomly chosen byte used as a shared lock */
16067 #if OS_WINCE
16068 WCHAR *zDeleteOnClose; /* Name of file to delete when closing */
16069 HANDLE hMutex; /* Mutex used to control access to shared lock */
16070 HANDLE hShared; /* Shared memory segment used for locking */
16071 winceLock local; /* Locks obtained by this instance of winFile */
16072 winceLock *shared; /* Global shared lock memory for the file */
16073 #endif
16078 ** Do not include any of the File I/O interface procedures if the
16079 ** SQLITE_OMIT_DISKIO macro is defined (indicating that there database
16080 ** will be in-memory only)
16082 #ifndef SQLITE_OMIT_DISKIO
16085 ** The following variable is (normally) set once and never changes
16086 ** thereafter. It records whether the operating system is Win95
16087 ** or WinNT.
16089 ** 0: Operating system unknown.
16090 ** 1: Operating system is Win95.
16091 ** 2: Operating system is WinNT.
16093 ** In order to facilitate testing on a WinNT system, the test fixture
16094 ** can manually set this value to 1 to emulate Win98 behavior.
16096 int sqlite3_os_type = 0;
16099 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
16100 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
16102 ** Here is an interesting observation: Win95, Win98, and WinME lack
16103 ** the LockFileEx() API. But we can still statically link against that
16104 ** API as long as we don't call it win running Win95/98/ME. A call to
16105 ** this routine is used to determine if the host is Win95/98/ME or
16106 ** WinNT/2K/XP so that we will know whether or not we can safely call
16107 ** the LockFileEx() API.
16109 #if OS_WINCE
16110 # define isNT() (1)
16111 #else
16112 static int isNT(void){
16113 if( sqlite3_os_type==0 ){
16114 OSVERSIONINFO sInfo;
16115 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
16116 GetVersionEx(&sInfo);
16117 sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
16119 return sqlite3_os_type==2;
16121 #endif /* OS_WINCE */
16124 ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
16126 ** Space to hold the returned string is obtained from sqliteMalloc.
16128 static WCHAR *utf8ToUnicode(const char *zFilename){
16129 int nChar;
16130 WCHAR *zWideFilename;
16132 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
16133 zWideFilename = sqliteMalloc( nChar*sizeof(zWideFilename[0]) );
16134 if( zWideFilename==0 ){
16135 return 0;
16137 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
16138 if( nChar==0 ){
16139 sqliteFree(zWideFilename);
16140 zWideFilename = 0;
16142 return zWideFilename;
16146 ** Convert microsoft unicode to UTF-8. Space to hold the returned string is
16147 ** obtained from sqliteMalloc().
16149 static char *unicodeToUtf8(const WCHAR *zWideFilename){
16150 int nByte;
16151 char *zFilename;
16153 nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
16154 zFilename = sqliteMalloc( nByte );
16155 if( zFilename==0 ){
16156 return 0;
16158 nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
16159 0, 0);
16160 if( nByte == 0 ){
16161 sqliteFree(zFilename);
16162 zFilename = 0;
16164 return zFilename;
16168 ** Convert an ansi string to microsoft unicode, based on the
16169 ** current codepage settings for file apis.
16171 ** Space to hold the returned string is obtained
16172 ** from sqliteMalloc.
16174 static WCHAR *mbcsToUnicode(const char *zFilename){
16175 int nByte;
16176 WCHAR *zMbcsFilename;
16177 int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
16179 nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
16180 zMbcsFilename = sqliteMalloc( nByte*sizeof(zMbcsFilename[0]) );
16181 if( zMbcsFilename==0 ){
16182 return 0;
16184 nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
16185 if( nByte==0 ){
16186 sqliteFree(zMbcsFilename);
16187 zMbcsFilename = 0;
16189 return zMbcsFilename;
16193 ** Convert microsoft unicode to multibyte character string, based on the
16194 ** user's Ansi codepage.
16196 ** Space to hold the returned string is obtained from
16197 ** sqliteMalloc().
16199 static char *unicodeToMbcs(const WCHAR *zWideFilename){
16200 int nByte;
16201 char *zFilename;
16202 int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
16204 nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
16205 zFilename = sqliteMalloc( nByte );
16206 if( zFilename==0 ){
16207 return 0;
16209 nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
16210 0, 0);
16211 if( nByte == 0 ){
16212 sqliteFree(zFilename);
16213 zFilename = 0;
16215 return zFilename;
16219 ** Convert multibyte character string to UTF-8. Space to hold the
16220 ** returned string is obtained from sqliteMalloc().
16222 static char *mbcsToUtf8(const char *zFilename){
16223 char *zFilenameUtf8;
16224 WCHAR *zTmpWide;
16226 zTmpWide = mbcsToUnicode(zFilename);
16227 if( zTmpWide==0 ){
16228 return 0;
16230 zFilenameUtf8 = unicodeToUtf8(zTmpWide);
16231 sqliteFree(zTmpWide);
16232 return zFilenameUtf8;
16236 ** Convert UTF-8 to multibyte character string. Space to hold the
16237 ** returned string is obtained from sqliteMalloc().
16239 static char *utf8ToMbcs(const char *zFilename){
16240 char *zFilenameMbcs;
16241 WCHAR *zTmpWide;
16243 zTmpWide = utf8ToUnicode(zFilename);
16244 if( zTmpWide==0 ){
16245 return 0;
16247 zFilenameMbcs = unicodeToMbcs(zTmpWide);
16248 sqliteFree(zTmpWide);
16249 return zFilenameMbcs;
16252 #if OS_WINCE
16253 /*************************************************************************
16254 ** This section contains code for WinCE only.
16257 ** WindowsCE does not have a localtime() function. So create a
16258 ** substitute.
16260 struct tm *__cdecl localtime(const time_t *t)
16262 static struct tm y;
16263 FILETIME uTm, lTm;
16264 SYSTEMTIME pTm;
16265 i64 t64;
16266 t64 = *t;
16267 t64 = (t64 + 11644473600)*10000000;
16268 uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
16269 uTm.dwHighDateTime= t64 >> 32;
16270 FileTimeToLocalFileTime(&uTm,&lTm);
16271 FileTimeToSystemTime(&lTm,&pTm);
16272 y.tm_year = pTm.wYear - 1900;
16273 y.tm_mon = pTm.wMonth - 1;
16274 y.tm_wday = pTm.wDayOfWeek;
16275 y.tm_mday = pTm.wDay;
16276 y.tm_hour = pTm.wHour;
16277 y.tm_min = pTm.wMinute;
16278 y.tm_sec = pTm.wSecond;
16279 return &y;
16282 /* This will never be called, but defined to make the code compile */
16283 #define GetTempPathA(a,b)
16285 #define LockFile(a,b,c,d,e) winceLockFile(&a, b, c, d, e)
16286 #define UnlockFile(a,b,c,d,e) winceUnlockFile(&a, b, c, d, e)
16287 #define LockFileEx(a,b,c,d,e,f) winceLockFileEx(&a, b, c, d, e, f)
16289 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
16292 ** Acquire a lock on the handle h
16294 static void winceMutexAcquire(HANDLE h){
16295 DWORD dwErr;
16296 do {
16297 dwErr = WaitForSingleObject(h, INFINITE);
16298 } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
16301 ** Release a lock acquired by winceMutexAcquire()
16303 #define winceMutexRelease(h) ReleaseMutex(h)
16306 ** Create the mutex and shared memory used for locking in the file
16307 ** descriptor pFile
16309 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
16310 WCHAR *zTok;
16311 WCHAR *zName = utf8ToUnicode(zFilename);
16312 BOOL bInit = TRUE;
16314 /* Initialize the local lockdata */
16315 ZeroMemory(&pFile->local, sizeof(pFile->local));
16317 /* Replace the backslashes from the filename and lowercase it
16318 ** to derive a mutex name. */
16319 zTok = CharLowerW(zName);
16320 for (;*zTok;zTok++){
16321 if (*zTok == '\\') *zTok = '_';
16324 /* Create/open the named mutex */
16325 pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
16326 if (!pFile->hMutex){
16327 sqliteFree(zName);
16328 return FALSE;
16331 /* Acquire the mutex before continuing */
16332 winceMutexAcquire(pFile->hMutex);
16334 /* Since the names of named mutexes, semaphores, file mappings etc are
16335 ** case-sensitive, take advantage of that by uppercasing the mutex name
16336 ** and using that as the shared filemapping name.
16338 CharUpperW(zName);
16339 pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
16340 PAGE_READWRITE, 0, sizeof(winceLock),
16341 zName);
16343 /* Set a flag that indicates we're the first to create the memory so it
16344 ** must be zero-initialized */
16345 if (GetLastError() == ERROR_ALREADY_EXISTS){
16346 bInit = FALSE;
16349 sqliteFree(zName);
16351 /* If we succeeded in making the shared memory handle, map it. */
16352 if (pFile->hShared){
16353 pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
16354 FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
16355 /* If mapping failed, close the shared memory handle and erase it */
16356 if (!pFile->shared){
16357 CloseHandle(pFile->hShared);
16358 pFile->hShared = NULL;
16362 /* If shared memory could not be created, then close the mutex and fail */
16363 if (pFile->hShared == NULL){
16364 winceMutexRelease(pFile->hMutex);
16365 CloseHandle(pFile->hMutex);
16366 pFile->hMutex = NULL;
16367 return FALSE;
16370 /* Initialize the shared memory if we're supposed to */
16371 if (bInit) {
16372 ZeroMemory(pFile->shared, sizeof(winceLock));
16375 winceMutexRelease(pFile->hMutex);
16376 return TRUE;
16380 ** Destroy the part of winFile that deals with wince locks
16382 static void winceDestroyLock(winFile *pFile){
16383 if (pFile->hMutex){
16384 /* Acquire the mutex */
16385 winceMutexAcquire(pFile->hMutex);
16387 /* The following blocks should probably assert in debug mode, but they
16388 are to cleanup in case any locks remained open */
16389 if (pFile->local.nReaders){
16390 pFile->shared->nReaders --;
16392 if (pFile->local.bReserved){
16393 pFile->shared->bReserved = FALSE;
16395 if (pFile->local.bPending){
16396 pFile->shared->bPending = FALSE;
16398 if (pFile->local.bExclusive){
16399 pFile->shared->bExclusive = FALSE;
16402 /* De-reference and close our copy of the shared memory handle */
16403 UnmapViewOfFile(pFile->shared);
16404 CloseHandle(pFile->hShared);
16406 if( pFile->zDeleteOnClose ){
16407 DeleteFileW(pFile->zDeleteOnClose);
16408 sqliteFree(pFile->zDeleteOnClose);
16409 pFile->zDeleteOnClose = 0;
16412 /* Done with the mutex */
16413 winceMutexRelease(pFile->hMutex);
16414 CloseHandle(pFile->hMutex);
16415 pFile->hMutex = NULL;
16420 ** An implementation of the LockFile() API of windows for wince
16422 static BOOL winceLockFile(
16423 HANDLE *phFile,
16424 DWORD dwFileOffsetLow,
16425 DWORD dwFileOffsetHigh,
16426 DWORD nNumberOfBytesToLockLow,
16427 DWORD nNumberOfBytesToLockHigh
16429 winFile *pFile = HANDLE_TO_WINFILE(phFile);
16430 BOOL bReturn = FALSE;
16432 if (!pFile->hMutex) return TRUE;
16433 winceMutexAcquire(pFile->hMutex);
16435 /* Wanting an exclusive lock? */
16436 if (dwFileOffsetLow == SHARED_FIRST
16437 && nNumberOfBytesToLockLow == SHARED_SIZE){
16438 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
16439 pFile->shared->bExclusive = TRUE;
16440 pFile->local.bExclusive = TRUE;
16441 bReturn = TRUE;
16445 /* Want a read-only lock? */
16446 else if ((dwFileOffsetLow >= SHARED_FIRST &&
16447 dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
16448 nNumberOfBytesToLockLow == 1){
16449 if (pFile->shared->bExclusive == 0){
16450 pFile->local.nReaders ++;
16451 if (pFile->local.nReaders == 1){
16452 pFile->shared->nReaders ++;
16454 bReturn = TRUE;
16458 /* Want a pending lock? */
16459 else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
16460 /* If no pending lock has been acquired, then acquire it */
16461 if (pFile->shared->bPending == 0) {
16462 pFile->shared->bPending = TRUE;
16463 pFile->local.bPending = TRUE;
16464 bReturn = TRUE;
16467 /* Want a reserved lock? */
16468 else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
16469 if (pFile->shared->bReserved == 0) {
16470 pFile->shared->bReserved = TRUE;
16471 pFile->local.bReserved = TRUE;
16472 bReturn = TRUE;
16476 winceMutexRelease(pFile->hMutex);
16477 return bReturn;
16481 ** An implementation of the UnlockFile API of windows for wince
16483 static BOOL winceUnlockFile(
16484 HANDLE *phFile,
16485 DWORD dwFileOffsetLow,
16486 DWORD dwFileOffsetHigh,
16487 DWORD nNumberOfBytesToUnlockLow,
16488 DWORD nNumberOfBytesToUnlockHigh
16490 winFile *pFile = HANDLE_TO_WINFILE(phFile);
16491 BOOL bReturn = FALSE;
16493 if (!pFile->hMutex) return TRUE;
16494 winceMutexAcquire(pFile->hMutex);
16496 /* Releasing a reader lock or an exclusive lock */
16497 if (dwFileOffsetLow >= SHARED_FIRST &&
16498 dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
16499 /* Did we have an exclusive lock? */
16500 if (pFile->local.bExclusive){
16501 pFile->local.bExclusive = FALSE;
16502 pFile->shared->bExclusive = FALSE;
16503 bReturn = TRUE;
16506 /* Did we just have a reader lock? */
16507 else if (pFile->local.nReaders){
16508 pFile->local.nReaders --;
16509 if (pFile->local.nReaders == 0)
16511 pFile->shared->nReaders --;
16513 bReturn = TRUE;
16517 /* Releasing a pending lock */
16518 else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
16519 if (pFile->local.bPending){
16520 pFile->local.bPending = FALSE;
16521 pFile->shared->bPending = FALSE;
16522 bReturn = TRUE;
16525 /* Releasing a reserved lock */
16526 else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
16527 if (pFile->local.bReserved) {
16528 pFile->local.bReserved = FALSE;
16529 pFile->shared->bReserved = FALSE;
16530 bReturn = TRUE;
16534 winceMutexRelease(pFile->hMutex);
16535 return bReturn;
16539 ** An implementation of the LockFileEx() API of windows for wince
16541 static BOOL winceLockFileEx(
16542 HANDLE *phFile,
16543 DWORD dwFlags,
16544 DWORD dwReserved,
16545 DWORD nNumberOfBytesToLockLow,
16546 DWORD nNumberOfBytesToLockHigh,
16547 LPOVERLAPPED lpOverlapped
16549 /* If the caller wants a shared read lock, forward this call
16550 ** to winceLockFile */
16551 if (lpOverlapped->Offset == SHARED_FIRST &&
16552 dwFlags == 1 &&
16553 nNumberOfBytesToLockLow == SHARED_SIZE){
16554 return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
16556 return FALSE;
16559 ** End of the special code for wince
16560 *****************************************************************************/
16561 #endif /* OS_WINCE */
16564 ** Convert a UTF-8 filename into whatever form the underlying
16565 ** operating system wants filenames in. Space to hold the result
16566 ** is obtained from sqliteMalloc and must be freed by the calling
16567 ** function.
16569 static void *convertUtf8Filename(const char *zFilename){
16570 void *zConverted = 0;
16571 if( isNT() ){
16572 zConverted = utf8ToUnicode(zFilename);
16573 }else{
16574 zConverted = utf8ToMbcs(zFilename);
16576 /* caller will handle out of memory */
16577 return zConverted;
16581 ** Delete the named file.
16583 ** Note that windows does not allow a file to be deleted if some other
16584 ** process has it open. Sometimes a virus scanner or indexing program
16585 ** will open a journal file shortly after it is created in order to do
16586 ** whatever it is it does. While this other process is holding the
16587 ** file open, we will be unable to delete it. To work around this
16588 ** problem, we delay 100 milliseconds and try to delete again. Up
16589 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
16590 ** up and returning an error.
16592 #define MX_DELETION_ATTEMPTS 3
16593 static int sqlite3WinDelete(const char *zFilename){
16594 int cnt = 0;
16595 int rc;
16596 void *zConverted = convertUtf8Filename(zFilename);
16597 if( zConverted==0 ){
16598 return SQLITE_NOMEM;
16600 SimulateIOError(return SQLITE_IOERR_DELETE);
16601 if( isNT() ){
16603 rc = DeleteFileW(zConverted);
16604 }while( rc==0 && GetFileAttributesW(zConverted)!=0xffffffff
16605 && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
16606 }else{
16607 #if OS_WINCE
16608 return SQLITE_NOMEM;
16609 #else
16611 rc = DeleteFileA(zConverted);
16612 }while( rc==0 && GetFileAttributesA(zConverted)!=0xffffffff
16613 && cnt++ < MX_DELETION_ATTEMPTS && (Sleep(100), 1) );
16614 #endif
16616 sqliteFree(zConverted);
16617 OSTRACE2("DELETE \"%s\"\n", zFilename);
16618 return rc!=0 ? SQLITE_OK : SQLITE_IOERR;
16622 ** Return TRUE if the named file exists.
16624 static int sqlite3WinFileExists(const char *zFilename){
16625 int exists = 0;
16626 void *zConverted = convertUtf8Filename(zFilename);
16627 if( zConverted==0 ){
16628 return SQLITE_NOMEM;
16630 if( isNT() ){
16631 exists = GetFileAttributesW((WCHAR*)zConverted) != 0xffffffff;
16632 }else{
16633 #if OS_WINCE
16634 return SQLITE_NOMEM;
16635 #else
16636 exists = GetFileAttributesA((char*)zConverted) != 0xffffffff;
16637 #endif
16639 sqliteFree(zConverted);
16640 return exists;
16643 /* Forward declaration */
16644 static int allocateWinFile(winFile *pInit, OsFile **pId);
16647 ** Attempt to open a file for both reading and writing. If that
16648 ** fails, try opening it read-only. If the file does not exist,
16649 ** try to create it.
16651 ** On success, a handle for the open file is written to *id
16652 ** and *pReadonly is set to 0 if the file was opened for reading and
16653 ** writing or 1 if the file was opened read-only. The function returns
16654 ** SQLITE_OK.
16656 ** On failure, the function returns SQLITE_CANTOPEN and leaves
16657 ** *id and *pReadonly unchanged.
16659 static int sqlite3WinOpenReadWrite(
16660 const char *zFilename,
16661 OsFile **pId,
16662 int *pReadonly
16664 winFile f;
16665 HANDLE h;
16666 void *zConverted = convertUtf8Filename(zFilename);
16667 if( zConverted==0 ){
16668 return SQLITE_NOMEM;
16670 assert( *pId==0 );
16672 if( isNT() ){
16673 h = CreateFileW((WCHAR*)zConverted,
16674 GENERIC_READ | GENERIC_WRITE,
16675 FILE_SHARE_READ | FILE_SHARE_WRITE,
16676 NULL,
16677 OPEN_ALWAYS,
16678 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
16679 NULL
16681 if( h==INVALID_HANDLE_VALUE ){
16682 h = CreateFileW((WCHAR*)zConverted,
16683 GENERIC_READ,
16684 FILE_SHARE_READ | FILE_SHARE_WRITE,
16685 NULL,
16686 OPEN_ALWAYS,
16687 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
16688 NULL
16690 if( h==INVALID_HANDLE_VALUE ){
16691 sqliteFree(zConverted);
16692 return SQLITE_CANTOPEN;
16694 *pReadonly = 1;
16695 }else{
16696 *pReadonly = 0;
16698 #if OS_WINCE
16699 if (!winceCreateLock(zFilename, &f)){
16700 CloseHandle(h);
16701 sqliteFree(zConverted);
16702 return SQLITE_CANTOPEN;
16704 #endif
16705 }else{
16706 #if OS_WINCE
16707 return SQLITE_NOMEM;
16708 #else
16709 h = CreateFileA((char*)zConverted,
16710 GENERIC_READ | GENERIC_WRITE,
16711 FILE_SHARE_READ | FILE_SHARE_WRITE,
16712 NULL,
16713 OPEN_ALWAYS,
16714 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
16715 NULL
16717 if( h==INVALID_HANDLE_VALUE ){
16718 h = CreateFileA((char*)zConverted,
16719 GENERIC_READ,
16720 FILE_SHARE_READ | FILE_SHARE_WRITE,
16721 NULL,
16722 OPEN_ALWAYS,
16723 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
16724 NULL
16726 if( h==INVALID_HANDLE_VALUE ){
16727 sqliteFree(zConverted);
16728 return SQLITE_CANTOPEN;
16730 *pReadonly = 1;
16731 }else{
16732 *pReadonly = 0;
16734 #endif /* OS_WINCE */
16737 sqliteFree(zConverted);
16739 f.h = h;
16740 #if OS_WINCE
16741 f.zDeleteOnClose = 0;
16742 #endif
16743 OSTRACE3("OPEN R/W %d \"%s\"\n", h, zFilename);
16744 return allocateWinFile(&f, pId);
16749 ** Attempt to open a new file for exclusive access by this process.
16750 ** The file will be opened for both reading and writing. To avoid
16751 ** a potential security problem, we do not allow the file to have
16752 ** previously existed. Nor do we allow the file to be a symbolic
16753 ** link.
16755 ** If delFlag is true, then make arrangements to automatically delete
16756 ** the file when it is closed.
16758 ** On success, write the file handle into *id and return SQLITE_OK.
16760 ** On failure, return SQLITE_CANTOPEN.
16762 ** Sometimes if we have just deleted a prior journal file, windows
16763 ** will fail to open a new one because there is a "pending delete".
16764 ** To work around this bug, we pause for 100 milliseconds and attempt
16765 ** a second open after the first one fails. The whole operation only
16766 ** fails if both open attempts are unsuccessful.
16768 static int sqlite3WinOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
16769 winFile f;
16770 HANDLE h;
16771 DWORD fileflags;
16772 void *zConverted = convertUtf8Filename(zFilename);
16773 if( zConverted==0 ){
16774 return SQLITE_NOMEM;
16776 assert( *pId == 0 );
16777 fileflags = FILE_FLAG_RANDOM_ACCESS;
16778 #if !OS_WINCE
16779 if( delFlag ){
16780 fileflags |= FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE;
16782 #endif
16783 if( isNT() ){
16784 int cnt = 0;
16786 h = CreateFileW((WCHAR*)zConverted,
16787 GENERIC_READ | GENERIC_WRITE,
16789 NULL,
16790 CREATE_ALWAYS,
16791 fileflags,
16792 NULL
16794 }while( h==INVALID_HANDLE_VALUE && cnt++ < 2 && (Sleep(100), 1) );
16795 }else{
16796 #if OS_WINCE
16797 return SQLITE_NOMEM;
16798 #else
16799 int cnt = 0;
16801 h = CreateFileA((char*)zConverted,
16802 GENERIC_READ | GENERIC_WRITE,
16804 NULL,
16805 CREATE_ALWAYS,
16806 fileflags,
16807 NULL
16809 }while( h==INVALID_HANDLE_VALUE && cnt++ < 2 && (Sleep(100), 1) );
16810 #endif /* OS_WINCE */
16812 #if OS_WINCE
16813 if( delFlag && h!=INVALID_HANDLE_VALUE ){
16814 f.zDeleteOnClose = zConverted;
16815 zConverted = 0;
16817 f.hMutex = NULL;
16818 #endif
16819 sqliteFree(zConverted);
16820 if( h==INVALID_HANDLE_VALUE ){
16821 return SQLITE_CANTOPEN;
16823 f.h = h;
16824 OSTRACE3("OPEN EX %d \"%s\"\n", h, zFilename);
16825 return allocateWinFile(&f, pId);
16829 ** Attempt to open a new file for read-only access.
16831 ** On success, write the file handle into *id and return SQLITE_OK.
16833 ** On failure, return SQLITE_CANTOPEN.
16835 static int sqlite3WinOpenReadOnly(const char *zFilename, OsFile **pId){
16836 winFile f;
16837 HANDLE h;
16838 void *zConverted = convertUtf8Filename(zFilename);
16839 if( zConverted==0 ){
16840 return SQLITE_NOMEM;
16842 assert( *pId==0 );
16843 if( isNT() ){
16844 h = CreateFileW((WCHAR*)zConverted,
16845 GENERIC_READ,
16847 NULL,
16848 OPEN_EXISTING,
16849 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
16850 NULL
16852 }else{
16853 #if OS_WINCE
16854 return SQLITE_NOMEM;
16855 #else
16856 h = CreateFileA((char*)zConverted,
16857 GENERIC_READ,
16859 NULL,
16860 OPEN_EXISTING,
16861 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
16862 NULL
16864 #endif
16866 sqliteFree(zConverted);
16867 if( h==INVALID_HANDLE_VALUE ){
16868 return SQLITE_CANTOPEN;
16870 f.h = h;
16871 #if OS_WINCE
16872 f.zDeleteOnClose = 0;
16873 f.hMutex = NULL;
16874 #endif
16875 OSTRACE3("OPEN RO %d \"%s\"\n", h, zFilename);
16876 return allocateWinFile(&f, pId);
16880 ** Attempt to open a file descriptor for the directory that contains a
16881 ** file. This file descriptor can be used to fsync() the directory
16882 ** in order to make sure the creation of a new file is actually written
16883 ** to disk.
16885 ** This routine is only meaningful for Unix. It is a no-op under
16886 ** windows since windows does not support hard links.
16888 ** On success, a handle for a previously open file is at *id is
16889 ** updated with the new directory file descriptor and SQLITE_OK is
16890 ** returned.
16892 ** On failure, the function returns SQLITE_CANTOPEN and leaves
16893 ** *id unchanged.
16895 static int winOpenDirectory(
16896 OsFile *id,
16897 const char *zDirname
16899 return SQLITE_OK;
16903 ** Create a temporary file name in zBuf. zBuf must be big enough to
16904 ** hold at least SQLITE_TEMPNAME_SIZE characters.
16906 static int sqlite3WinTempFileName(char *zBuf){
16907 static char zChars[] =
16908 "abcdefghijklmnopqrstuvwxyz"
16909 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
16910 "0123456789";
16911 int i, j;
16912 char zTempPath[SQLITE_TEMPNAME_SIZE];
16913 if( sqlite3_temp_directory ){
16914 strncpy(zTempPath, sqlite3_temp_directory, SQLITE_TEMPNAME_SIZE-30);
16915 zTempPath[SQLITE_TEMPNAME_SIZE-30] = 0;
16916 }else if( isNT() ){
16917 char *zMulti;
16918 WCHAR zWidePath[SQLITE_TEMPNAME_SIZE];
16919 GetTempPathW(SQLITE_TEMPNAME_SIZE-30, zWidePath);
16920 zMulti = unicodeToUtf8(zWidePath);
16921 if( zMulti ){
16922 strncpy(zTempPath, zMulti, SQLITE_TEMPNAME_SIZE-30);
16923 zTempPath[SQLITE_TEMPNAME_SIZE-30] = 0;
16924 sqliteFree(zMulti);
16925 }else{
16926 return SQLITE_NOMEM;
16928 }else{
16929 char *zUtf8;
16930 char zMbcsPath[SQLITE_TEMPNAME_SIZE];
16931 GetTempPathA(SQLITE_TEMPNAME_SIZE-30, zMbcsPath);
16932 zUtf8 = mbcsToUtf8(zMbcsPath);
16933 if( zUtf8 ){
16934 strncpy(zTempPath, zUtf8, SQLITE_TEMPNAME_SIZE-30);
16935 zTempPath[SQLITE_TEMPNAME_SIZE-30] = 0;
16936 sqliteFree(zUtf8);
16937 }else{
16938 return SQLITE_NOMEM;
16941 for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
16942 zTempPath[i] = 0;
16943 for(;;){
16944 sqlite3_snprintf(SQLITE_TEMPNAME_SIZE, zBuf,
16945 "%s\\"TEMP_FILE_PREFIX, zTempPath);
16946 j = strlen(zBuf);
16947 sqlite3Randomness(15, &zBuf[j]);
16948 for(i=0; i<15; i++, j++){
16949 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
16951 zBuf[j] = 0;
16952 if( !sqlite3OsFileExists(zBuf) ) break;
16954 OSTRACE2("TEMP FILENAME: %s\n", zBuf);
16955 return SQLITE_OK;
16959 ** Close a file.
16961 ** It is reported that an attempt to close a handle might sometimes
16962 ** fail. This is a very unreasonable result, but windows is notorious
16963 ** for being unreasonable so I do not doubt that it might happen. If
16964 ** the close fails, we pause for 100 milliseconds and try again. As
16965 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
16966 ** giving up and returning an error.
16968 #define MX_CLOSE_ATTEMPT 3
16969 static int winClose(OsFile **pId){
16970 winFile *pFile;
16971 int rc = 1;
16972 if( pId && (pFile = (winFile*)*pId)!=0 ){
16973 int rc, cnt = 0;
16974 OSTRACE2("CLOSE %d\n", pFile->h);
16976 rc = CloseHandle(pFile->h);
16977 }while( rc==0 && cnt++ < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
16978 #if OS_WINCE
16979 winceDestroyLock(pFile);
16980 #endif
16981 OpenCounter(-1);
16982 sqliteFree(pFile);
16983 *pId = 0;
16985 return rc ? SQLITE_OK : SQLITE_IOERR;
16989 ** Read data from a file into a buffer. Return SQLITE_OK if all
16990 ** bytes were read successfully and SQLITE_IOERR if anything goes
16991 ** wrong.
16993 static int winRead(OsFile *id, void *pBuf, int amt){
16994 DWORD got;
16995 assert( id!=0 );
16996 SimulateIOError(return SQLITE_IOERR_READ);
16997 OSTRACE3("READ %d lock=%d\n", ((winFile*)id)->h, ((winFile*)id)->locktype);
16998 if( !ReadFile(((winFile*)id)->h, pBuf, amt, &got, 0) ){
16999 return SQLITE_IOERR_READ;
17001 if( got==(DWORD)amt ){
17002 return SQLITE_OK;
17003 }else{
17004 memset(&((char*)pBuf)[got], 0, amt-got);
17005 return SQLITE_IOERR_SHORT_READ;
17010 ** Write data from a buffer into a file. Return SQLITE_OK on success
17011 ** or some other error code on failure.
17013 static int winWrite(OsFile *id, const void *pBuf, int amt){
17014 int rc = 0;
17015 DWORD wrote;
17016 assert( id!=0 );
17017 SimulateIOError(return SQLITE_IOERR_READ);
17018 SimulateDiskfullError(return SQLITE_FULL);
17019 OSTRACE3("WRITE %d lock=%d\n", ((winFile*)id)->h, ((winFile*)id)->locktype);
17020 assert( amt>0 );
17021 while( amt>0 && (rc = WriteFile(((winFile*)id)->h, pBuf, amt, &wrote, 0))!=0
17022 && wrote>0 ){
17023 amt -= wrote;
17024 pBuf = &((char*)pBuf)[wrote];
17026 if( !rc || amt>(int)wrote ){
17027 return SQLITE_FULL;
17029 return SQLITE_OK;
17033 ** Some microsoft compilers lack this definition.
17035 #ifndef INVALID_SET_FILE_POINTER
17036 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
17037 #endif
17040 ** Move the read/write pointer in a file.
17042 static int winSeek(OsFile *id, i64 offset){
17043 LONG upperBits = offset>>32;
17044 LONG lowerBits = offset & 0xffffffff;
17045 DWORD rc;
17046 assert( id!=0 );
17047 #ifdef SQLITE_TEST
17048 if( offset ) SimulateDiskfullError(return SQLITE_FULL);
17049 #endif
17050 rc = SetFilePointer(((winFile*)id)->h, lowerBits, &upperBits, FILE_BEGIN);
17051 OSTRACE3("SEEK %d %lld\n", ((winFile*)id)->h, offset);
17052 if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
17053 return SQLITE_FULL;
17055 return SQLITE_OK;
17059 ** Make sure all writes to a particular file are committed to disk.
17061 static int winSync(OsFile *id, int dataOnly){
17062 assert( id!=0 );
17063 OSTRACE3("SYNC %d lock=%d\n", ((winFile*)id)->h, ((winFile*)id)->locktype);
17064 if( FlushFileBuffers(((winFile*)id)->h) ){
17065 return SQLITE_OK;
17066 }else{
17067 return SQLITE_IOERR;
17072 ** Sync the directory zDirname. This is a no-op on operating systems other
17073 ** than UNIX.
17075 static int sqlite3WinSyncDirectory(const char *zDirname){
17076 SimulateIOError(return SQLITE_IOERR_READ);
17077 return SQLITE_OK;
17081 ** Truncate an open file to a specified size
17083 static int winTruncate(OsFile *id, i64 nByte){
17084 LONG upperBits = nByte>>32;
17085 assert( id!=0 );
17086 OSTRACE3("TRUNCATE %d %lld\n", ((winFile*)id)->h, nByte);
17087 SimulateIOError(return SQLITE_IOERR_TRUNCATE);
17088 SetFilePointer(((winFile*)id)->h, nByte, &upperBits, FILE_BEGIN);
17089 SetEndOfFile(((winFile*)id)->h);
17090 return SQLITE_OK;
17094 ** Determine the current size of a file in bytes
17096 static int winFileSize(OsFile *id, i64 *pSize){
17097 DWORD upperBits, lowerBits;
17098 assert( id!=0 );
17099 SimulateIOError(return SQLITE_IOERR_FSTAT);
17100 lowerBits = GetFileSize(((winFile*)id)->h, &upperBits);
17101 *pSize = (((i64)upperBits)<<32) + lowerBits;
17102 return SQLITE_OK;
17106 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
17108 #ifndef LOCKFILE_FAIL_IMMEDIATELY
17109 # define LOCKFILE_FAIL_IMMEDIATELY 1
17110 #endif
17113 ** Acquire a reader lock.
17114 ** Different API routines are called depending on whether or not this
17115 ** is Win95 or WinNT.
17117 static int getReadLock(winFile *id){
17118 int res;
17119 if( isNT() ){
17120 OVERLAPPED ovlp;
17121 ovlp.Offset = SHARED_FIRST;
17122 ovlp.OffsetHigh = 0;
17123 ovlp.hEvent = 0;
17124 res = LockFileEx(id->h, LOCKFILE_FAIL_IMMEDIATELY, 0, SHARED_SIZE,0,&ovlp);
17125 }else{
17126 int lk;
17127 sqlite3Randomness(sizeof(lk), &lk);
17128 id->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
17129 res = LockFile(id->h, SHARED_FIRST+id->sharedLockByte, 0, 1, 0);
17131 return res;
17135 ** Undo a readlock
17137 static int unlockReadLock(winFile *pFile){
17138 int res;
17139 if( isNT() ){
17140 res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
17141 }else{
17142 res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
17144 return res;
17147 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
17149 ** Check that a given pathname is a directory and is writable
17152 static int sqlite3WinIsDirWritable(char *zDirname){
17153 int fileAttr;
17154 void *zConverted;
17155 if( zDirname==0 ) return 0;
17156 if( !isNT() && strlen(zDirname)>MAX_PATH ) return 0;
17158 zConverted = convertUtf8Filename(zDirname);
17159 if( zConverted==0 ){
17160 return SQLITE_NOMEM;
17162 if( isNT() ){
17163 fileAttr = GetFileAttributesW((WCHAR*)zConverted);
17164 }else{
17165 #if OS_WINCE
17166 return 0;
17167 #else
17168 fileAttr = GetFileAttributesA((char*)zConverted);
17169 #endif
17171 sqliteFree(zConverted);
17172 if( fileAttr == 0xffffffff ) return 0;
17173 if( (fileAttr & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY ){
17174 return 0;
17176 return 1;
17178 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
17181 ** Lock the file with the lock specified by parameter locktype - one
17182 ** of the following:
17184 ** (1) SHARED_LOCK
17185 ** (2) RESERVED_LOCK
17186 ** (3) PENDING_LOCK
17187 ** (4) EXCLUSIVE_LOCK
17189 ** Sometimes when requesting one lock state, additional lock states
17190 ** are inserted in between. The locking might fail on one of the later
17191 ** transitions leaving the lock state different from what it started but
17192 ** still short of its goal. The following chart shows the allowed
17193 ** transitions and the inserted intermediate states:
17195 ** UNLOCKED -> SHARED
17196 ** SHARED -> RESERVED
17197 ** SHARED -> (PENDING) -> EXCLUSIVE
17198 ** RESERVED -> (PENDING) -> EXCLUSIVE
17199 ** PENDING -> EXCLUSIVE
17201 ** This routine will only increase a lock. The winUnlock() routine
17202 ** erases all locks at once and returns us immediately to locking level 0.
17203 ** It is not possible to lower the locking level one step at a time. You
17204 ** must go straight to locking level 0.
17206 static int winLock(OsFile *id, int locktype){
17207 int rc = SQLITE_OK; /* Return code from subroutines */
17208 int res = 1; /* Result of a windows lock call */
17209 int newLocktype; /* Set id->locktype to this value before exiting */
17210 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
17211 winFile *pFile = (winFile*)id;
17213 assert( pFile!=0 );
17214 OSTRACE5("LOCK %d %d was %d(%d)\n",
17215 pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
17217 /* If there is already a lock of this type or more restrictive on the
17218 ** OsFile, do nothing. Don't use the end_lock: exit path, as
17219 ** sqlite3OsEnterMutex() hasn't been called yet.
17221 if( pFile->locktype>=locktype ){
17222 return SQLITE_OK;
17225 /* Make sure the locking sequence is correct
17227 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
17228 assert( locktype!=PENDING_LOCK );
17229 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
17231 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
17232 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
17233 ** the PENDING_LOCK byte is temporary.
17235 newLocktype = pFile->locktype;
17236 if( pFile->locktype==NO_LOCK
17237 || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
17239 int cnt = 3;
17240 while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
17241 /* Try 3 times to get the pending lock. The pending lock might be
17242 ** held by another reader process who will release it momentarily.
17244 OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
17245 Sleep(1);
17247 gotPendingLock = res;
17250 /* Acquire a shared lock
17252 if( locktype==SHARED_LOCK && res ){
17253 assert( pFile->locktype==NO_LOCK );
17254 res = getReadLock(pFile);
17255 if( res ){
17256 newLocktype = SHARED_LOCK;
17260 /* Acquire a RESERVED lock
17262 if( locktype==RESERVED_LOCK && res ){
17263 assert( pFile->locktype==SHARED_LOCK );
17264 res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
17265 if( res ){
17266 newLocktype = RESERVED_LOCK;
17270 /* Acquire a PENDING lock
17272 if( locktype==EXCLUSIVE_LOCK && res ){
17273 newLocktype = PENDING_LOCK;
17274 gotPendingLock = 0;
17277 /* Acquire an EXCLUSIVE lock
17279 if( locktype==EXCLUSIVE_LOCK && res ){
17280 assert( pFile->locktype>=SHARED_LOCK );
17281 res = unlockReadLock(pFile);
17282 OSTRACE2("unreadlock = %d\n", res);
17283 res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
17284 if( res ){
17285 newLocktype = EXCLUSIVE_LOCK;
17286 }else{
17287 OSTRACE2("error-code = %d\n", GetLastError());
17288 getReadLock(pFile);
17292 /* If we are holding a PENDING lock that ought to be released, then
17293 ** release it now.
17295 if( gotPendingLock && locktype==SHARED_LOCK ){
17296 UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
17299 /* Update the state of the lock has held in the file descriptor then
17300 ** return the appropriate result code.
17302 if( res ){
17303 rc = SQLITE_OK;
17304 }else{
17305 OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
17306 locktype, newLocktype);
17307 rc = SQLITE_BUSY;
17309 pFile->locktype = newLocktype;
17310 return rc;
17314 ** This routine checks if there is a RESERVED lock held on the specified
17315 ** file by this or any other process. If such a lock is held, return
17316 ** non-zero, otherwise zero.
17318 static int winCheckReservedLock(OsFile *id){
17319 int rc;
17320 winFile *pFile = (winFile*)id;
17321 assert( pFile!=0 );
17322 if( pFile->locktype>=RESERVED_LOCK ){
17323 rc = 1;
17324 OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
17325 }else{
17326 rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
17327 if( rc ){
17328 UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
17330 rc = !rc;
17331 OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
17333 return rc;
17337 ** Lower the locking level on file descriptor id to locktype. locktype
17338 ** must be either NO_LOCK or SHARED_LOCK.
17340 ** If the locking level of the file descriptor is already at or below
17341 ** the requested locking level, this routine is a no-op.
17343 ** It is not possible for this routine to fail if the second argument
17344 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
17345 ** might return SQLITE_IOERR;
17347 static int winUnlock(OsFile *id, int locktype){
17348 int type;
17349 int rc = SQLITE_OK;
17350 winFile *pFile = (winFile*)id;
17351 assert( pFile!=0 );
17352 assert( locktype<=SHARED_LOCK );
17353 OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
17354 pFile->locktype, pFile->sharedLockByte);
17355 type = pFile->locktype;
17356 if( type>=EXCLUSIVE_LOCK ){
17357 UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
17358 if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
17359 /* This should never happen. We should always be able to
17360 ** reacquire the read lock */
17361 rc = SQLITE_IOERR_UNLOCK;
17364 if( type>=RESERVED_LOCK ){
17365 UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
17367 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
17368 unlockReadLock(pFile);
17370 if( type>=PENDING_LOCK ){
17371 UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
17373 pFile->locktype = locktype;
17374 return rc;
17378 ** Turn a relative pathname into a full pathname. Return a pointer
17379 ** to the full pathname stored in space obtained from sqliteMalloc().
17380 ** The calling function is responsible for freeing this space once it
17381 ** is no longer needed.
17383 static char *sqlite3WinFullPathname(const char *zRelative){
17384 char *zFull;
17385 #if defined(__CYGWIN__)
17386 int nByte;
17387 nByte = strlen(zRelative) + MAX_PATH + 1001;
17388 zFull = sqliteMalloc( nByte );
17389 if( zFull==0 ) return 0;
17390 if( cygwin_conv_to_full_win32_path(zRelative, zFull) ) return 0;
17391 #elif OS_WINCE
17392 /* WinCE has no concept of a relative pathname, or so I am told. */
17393 zFull = sqliteStrDup(zRelative);
17394 #else
17395 int nByte;
17396 void *zConverted;
17397 zConverted = convertUtf8Filename(zRelative);
17398 if( isNT() ){
17399 WCHAR *zTemp;
17400 nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
17401 zTemp = sqliteMalloc( nByte*sizeof(zTemp[0]) );
17402 if( zTemp==0 ){
17403 sqliteFree(zConverted);
17404 return 0;
17406 GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
17407 sqliteFree(zConverted);
17408 zFull = unicodeToUtf8(zTemp);
17409 sqliteFree(zTemp);
17410 }else{
17411 char *zTemp;
17412 nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
17413 zTemp = sqliteMalloc( nByte*sizeof(zTemp[0]) );
17414 if( zTemp==0 ){
17415 sqliteFree(zConverted);
17416 return 0;
17418 GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
17419 sqliteFree(zConverted);
17420 zFull = mbcsToUtf8(zTemp);
17421 sqliteFree(zTemp);
17423 #endif
17424 return zFull;
17428 ** The fullSync option is meaningless on windows. This is a no-op.
17430 static void winSetFullSync(OsFile *id, int v){
17431 return;
17435 ** Return the underlying file handle for an OsFile
17437 static int winFileHandle(OsFile *id){
17438 return (int)((winFile*)id)->h;
17442 ** Return an integer that indices the type of lock currently held
17443 ** by this handle. (Used for testing and analysis only.)
17445 static int winLockState(OsFile *id){
17446 return ((winFile*)id)->locktype;
17450 ** Return the sector size in bytes of the underlying block device for
17451 ** the specified file. This is almost always 512 bytes, but may be
17452 ** larger for some devices.
17454 ** SQLite code assumes this function cannot fail. It also assumes that
17455 ** if two files are created in the same file-system directory (i.e.
17456 ** a database and it's journal file) that the sector size will be the
17457 ** same for both.
17459 static int winSectorSize(OsFile *id){
17460 return SQLITE_DEFAULT_SECTOR_SIZE;
17464 ** This vector defines all the methods that can operate on an OsFile
17465 ** for win32.
17467 static const IoMethod sqlite3WinIoMethod = {
17468 winClose,
17469 winOpenDirectory,
17470 winRead,
17471 winWrite,
17472 winSeek,
17473 winTruncate,
17474 winSync,
17475 winSetFullSync,
17476 winFileHandle,
17477 winFileSize,
17478 winLock,
17479 winUnlock,
17480 winLockState,
17481 winCheckReservedLock,
17482 winSectorSize,
17486 ** Allocate memory for an OsFile. Initialize the new OsFile
17487 ** to the value given in pInit and return a pointer to the new
17488 ** OsFile. If we run out of memory, close the file and return NULL.
17490 static int allocateWinFile(winFile *pInit, OsFile **pId){
17491 winFile *pNew;
17492 pNew = sqliteMalloc( sizeof(*pNew) );
17493 if( pNew==0 ){
17494 CloseHandle(pInit->h);
17495 #if OS_WINCE
17496 sqliteFree(pInit->zDeleteOnClose);
17497 #endif
17498 *pId = 0;
17499 return SQLITE_NOMEM;
17500 }else{
17501 *pNew = *pInit;
17502 pNew->pMethod = &sqlite3WinIoMethod;
17503 pNew->locktype = NO_LOCK;
17504 pNew->sharedLockByte = 0;
17505 *pId = (OsFile*)pNew;
17506 OpenCounter(+1);
17507 return SQLITE_OK;
17512 #endif /* SQLITE_OMIT_DISKIO */
17513 /***************************************************************************
17514 ** Everything above deals with file I/O. Everything that follows deals
17515 ** with other miscellanous aspects of the operating system interface
17516 ****************************************************************************/
17518 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
17520 ** Interfaces for opening a shared library, finding entry points
17521 ** within the shared library, and closing the shared library.
17523 static void *sqlite3WinDlopen(const char *zFilename){
17524 HANDLE h;
17525 void *zConverted = convertUtf8Filename(zFilename);
17526 if( zConverted==0 ){
17527 return 0;
17529 if( isNT() ){
17530 h = LoadLibraryW((WCHAR*)zConverted);
17531 }else{
17532 #if OS_WINCE
17533 return 0;
17534 #else
17535 h = LoadLibraryA((char*)zConverted);
17536 #endif
17538 sqliteFree(zConverted);
17539 return (void*)h;
17542 static void *sqlite3WinDlsym(void *pHandle, const char *zSymbol){
17543 #if OS_WINCE
17544 /* The GetProcAddressA() routine is only available on wince. */
17545 return GetProcAddressA((HANDLE)pHandle, zSymbol);
17546 #else
17547 /* All other windows platforms expect GetProcAddress() to take
17548 ** an Ansi string regardless of the _UNICODE setting */
17549 return GetProcAddress((HANDLE)pHandle, zSymbol);
17550 #endif
17552 static int sqlite3WinDlclose(void *pHandle){
17553 return FreeLibrary((HANDLE)pHandle);
17555 #endif /* !SQLITE_OMIT_LOAD_EXTENSION */
17558 ** Get information to seed the random number generator. The seed
17559 ** is written into the buffer zBuf[256]. The calling function must
17560 ** supply a sufficiently large buffer.
17562 static int sqlite3WinRandomSeed(char *zBuf){
17563 /* We have to initialize zBuf to prevent valgrind from reporting
17564 ** errors. The reports issued by valgrind are incorrect - we would
17565 ** prefer that the randomness be increased by making use of the
17566 ** uninitialized space in zBuf - but valgrind errors tend to worry
17567 ** some users. Rather than argue, it seems easier just to initialize
17568 ** the whole array and silence valgrind, even if that means less randomness
17569 ** in the random seed.
17571 ** When testing, initializing zBuf[] to zero is all we do. That means
17572 ** that we always use the same random number sequence.* This makes the
17573 ** tests repeatable.
17575 memset(zBuf, 0, 256);
17576 GetSystemTime((LPSYSTEMTIME)zBuf);
17577 return SQLITE_OK;
17581 ** Sleep for a little while. Return the amount of time slept.
17583 static int sqlite3WinSleep(int ms){
17584 Sleep(ms);
17585 return ms;
17589 ** Static variables used for thread synchronization
17591 static int inMutex = 0;
17592 #ifdef SQLITE_W32_THREADS
17593 static DWORD mutexOwner;
17594 static CRITICAL_SECTION cs;
17595 #endif
17598 ** The following pair of routines implement mutual exclusion for
17599 ** multi-threaded processes. Only a single thread is allowed to
17600 ** executed code that is surrounded by EnterMutex() and LeaveMutex().
17602 ** SQLite uses only a single Mutex. There is not much critical
17603 ** code and what little there is executes quickly and without blocking.
17605 ** Version 3.3.1 and earlier used a simple mutex. Beginning with
17606 ** version 3.3.2, a recursive mutex is required.
17608 static void sqlite3WinEnterMutex(){
17609 #ifdef SQLITE_W32_THREADS
17610 static int isInit = 0;
17611 while( !isInit ){
17612 static long lock = 0;
17613 if( InterlockedIncrement(&lock)==1 ){
17614 InitializeCriticalSection(&cs);
17615 isInit = 1;
17616 }else{
17617 Sleep(1);
17620 EnterCriticalSection(&cs);
17621 mutexOwner = GetCurrentThreadId();
17622 #endif
17623 inMutex++;
17625 static void sqlite3WinLeaveMutex(){
17626 assert( inMutex );
17627 inMutex--;
17628 #ifdef SQLITE_W32_THREADS
17629 assert( mutexOwner==GetCurrentThreadId() );
17630 LeaveCriticalSection(&cs);
17631 #endif
17635 ** Return TRUE if the mutex is currently held.
17637 ** If the thisThreadOnly parameter is true, return true if and only if the
17638 ** calling thread holds the mutex. If the parameter is false, return
17639 ** true if any thread holds the mutex.
17641 static int sqlite3WinInMutex(int thisThreadOnly){
17642 #ifdef SQLITE_W32_THREADS
17643 return inMutex>0 && (thisThreadOnly==0 || mutexOwner==GetCurrentThreadId());
17644 #else
17645 return inMutex>0;
17646 #endif
17651 ** The following variable, if set to a non-zero value, becomes the result
17652 ** returned from sqlite3OsCurrentTime(). This is used for testing.
17654 #ifdef SQLITE_TEST
17655 int sqlite3_current_time = 0;
17656 #endif
17659 ** Find the current time (in Universal Coordinated Time). Write the
17660 ** current time and date as a Julian Day number into *prNow and
17661 ** return 0. Return 1 if the time and date cannot be found.
17663 static int sqlite3WinCurrentTime(double *prNow){
17664 FILETIME ft;
17665 /* FILETIME structure is a 64-bit value representing the number of
17666 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
17668 double now;
17669 #if OS_WINCE
17670 SYSTEMTIME time;
17671 GetSystemTime(&time);
17672 SystemTimeToFileTime(&time,&ft);
17673 #else
17674 GetSystemTimeAsFileTime( &ft );
17675 #endif
17676 now = ((double)ft.dwHighDateTime) * 4294967296.0;
17677 *prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
17678 #ifdef SQLITE_TEST
17679 if( sqlite3_current_time ){
17680 *prNow = sqlite3_current_time/86400.0 + 2440587.5;
17682 #endif
17683 return 0;
17687 ** Remember the number of thread-specific-data blocks allocated.
17688 ** Use this to verify that we are not leaking thread-specific-data.
17689 ** Ticket #1601
17691 #ifdef SQLITE_TEST
17692 int sqlite3_tsd_count = 0;
17693 # define TSD_COUNTER_INCR InterlockedIncrement(&sqlite3_tsd_count)
17694 # define TSD_COUNTER_DECR InterlockedDecrement(&sqlite3_tsd_count)
17695 #else
17696 # define TSD_COUNTER_INCR /* no-op */
17697 # define TSD_COUNTER_DECR /* no-op */
17698 #endif
17703 ** If called with allocateFlag>1, then return a pointer to thread
17704 ** specific data for the current thread. Allocate and zero the
17705 ** thread-specific data if it does not already exist necessary.
17707 ** If called with allocateFlag==0, then check the current thread
17708 ** specific data. Return it if it exists. If it does not exist,
17709 ** then return NULL.
17711 ** If called with allocateFlag<0, check to see if the thread specific
17712 ** data is allocated and is all zero. If it is then deallocate it.
17713 ** Return a pointer to the thread specific data or NULL if it is
17714 ** unallocated or gets deallocated.
17716 static ThreadData *sqlite3WinThreadSpecificData(int allocateFlag){
17717 static int key;
17718 static int keyInit = 0;
17719 static const ThreadData zeroData = {0};
17720 ThreadData *pTsd;
17722 if( !keyInit ){
17723 sqlite3OsEnterMutex();
17724 if( !keyInit ){
17725 key = TlsAlloc();
17726 if( key==0xffffffff ){
17727 sqlite3OsLeaveMutex();
17728 return 0;
17730 keyInit = 1;
17732 sqlite3OsLeaveMutex();
17734 pTsd = TlsGetValue(key);
17735 if( allocateFlag>0 ){
17736 if( !pTsd ){
17737 pTsd = sqlite3OsMalloc( sizeof(zeroData) );
17738 if( pTsd ){
17739 *pTsd = zeroData;
17740 TlsSetValue(key, pTsd);
17741 TSD_COUNTER_INCR;
17744 }else if( pTsd!=0 && allocateFlag<0
17745 && memcmp(pTsd, &zeroData, sizeof(ThreadData))==0 ){
17746 sqlite3OsFree(pTsd);
17747 TlsSetValue(key, 0);
17748 TSD_COUNTER_DECR;
17749 pTsd = 0;
17751 return pTsd;
17753 #endif /* OS_WIN */
17755 /************** End of os_win.c **********************************************/
17756 /************** Begin file pager.c *******************************************/
17758 ** 2001 September 15
17760 ** The author disclaims copyright to this source code. In place of
17761 ** a legal notice, here is a blessing:
17763 ** May you do good and not evil.
17764 ** May you find forgiveness for yourself and forgive others.
17765 ** May you share freely, never taking more than you give.
17767 *************************************************************************
17768 ** This is the implementation of the page cache subsystem or "pager".
17770 ** The pager is used to access a database disk file. It implements
17771 ** atomic commit and rollback through the use of a journal file that
17772 ** is separate from the database file. The pager also implements file
17773 ** locking to prevent two processes from writing the same database
17774 ** file simultaneously, or one process from reading the database while
17775 ** another is writing.
17777 ** @(#) $Id: pager.c,v 1.348 2007/06/18 17:25:18 drh Exp $
17779 #ifndef SQLITE_OMIT_DISKIO
17782 ** Macros for troubleshooting. Normally turned off
17784 #if 0
17785 #define sqlite3DebugPrintf printf
17786 #define PAGERTRACE1(X) sqlite3DebugPrintf(X)
17787 #define PAGERTRACE2(X,Y) sqlite3DebugPrintf(X,Y)
17788 #define PAGERTRACE3(X,Y,Z) sqlite3DebugPrintf(X,Y,Z)
17789 #define PAGERTRACE4(X,Y,Z,W) sqlite3DebugPrintf(X,Y,Z,W)
17790 #define PAGERTRACE5(X,Y,Z,W,V) sqlite3DebugPrintf(X,Y,Z,W,V)
17791 #else
17792 #define PAGERTRACE1(X)
17793 #define PAGERTRACE2(X,Y)
17794 #define PAGERTRACE3(X,Y,Z)
17795 #define PAGERTRACE4(X,Y,Z,W)
17796 #define PAGERTRACE5(X,Y,Z,W,V)
17797 #endif
17800 ** The following two macros are used within the PAGERTRACEX() macros above
17801 ** to print out file-descriptors.
17803 ** PAGERID() takes a pointer to a Pager struct as it's argument. The
17804 ** associated file-descriptor is returned. FILEHANDLEID() takes an OsFile
17805 ** struct as it's argument.
17807 #define PAGERID(p) ((int)(p->fd))
17808 #define FILEHANDLEID(fd) ((int)fd)
17811 ** The page cache as a whole is always in one of the following
17812 ** states:
17814 ** PAGER_UNLOCK The page cache is not currently reading or
17815 ** writing the database file. There is no
17816 ** data held in memory. This is the initial
17817 ** state.
17819 ** PAGER_SHARED The page cache is reading the database.
17820 ** Writing is not permitted. There can be
17821 ** multiple readers accessing the same database
17822 ** file at the same time.
17824 ** PAGER_RESERVED This process has reserved the database for writing
17825 ** but has not yet made any changes. Only one process
17826 ** at a time can reserve the database. The original
17827 ** database file has not been modified so other
17828 ** processes may still be reading the on-disk
17829 ** database file.
17831 ** PAGER_EXCLUSIVE The page cache is writing the database.
17832 ** Access is exclusive. No other processes or
17833 ** threads can be reading or writing while one
17834 ** process is writing.
17836 ** PAGER_SYNCED The pager moves to this state from PAGER_EXCLUSIVE
17837 ** after all dirty pages have been written to the
17838 ** database file and the file has been synced to
17839 ** disk. All that remains to do is to remove or
17840 ** truncate the journal file and the transaction
17841 ** will be committed.
17843 ** The page cache comes up in PAGER_UNLOCK. The first time a
17844 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
17845 ** After all pages have been released using sqlite_page_unref(),
17846 ** the state transitions back to PAGER_UNLOCK. The first time
17847 ** that sqlite3PagerWrite() is called, the state transitions to
17848 ** PAGER_RESERVED. (Note that sqlite3PagerWrite() can only be
17849 ** called on an outstanding page which means that the pager must
17850 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
17851 ** PAGER_RESERVED means that there is an open rollback journal.
17852 ** The transition to PAGER_EXCLUSIVE occurs before any changes
17853 ** are made to the database file, though writes to the rollback
17854 ** journal occurs with just PAGER_RESERVED. After an sqlite3PagerRollback()
17855 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
17856 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
17858 #define PAGER_UNLOCK 0
17859 #define PAGER_SHARED 1 /* same as SHARED_LOCK */
17860 #define PAGER_RESERVED 2 /* same as RESERVED_LOCK */
17861 #define PAGER_EXCLUSIVE 4 /* same as EXCLUSIVE_LOCK */
17862 #define PAGER_SYNCED 5
17865 ** If the SQLITE_BUSY_RESERVED_LOCK macro is set to true at compile-time,
17866 ** then failed attempts to get a reserved lock will invoke the busy callback.
17867 ** This is off by default. To see why, consider the following scenario:
17869 ** Suppose thread A already has a shared lock and wants a reserved lock.
17870 ** Thread B already has a reserved lock and wants an exclusive lock. If
17871 ** both threads are using their busy callbacks, it might be a long time
17872 ** be for one of the threads give up and allows the other to proceed.
17873 ** But if the thread trying to get the reserved lock gives up quickly
17874 ** (if it never invokes its busy callback) then the contention will be
17875 ** resolved quickly.
17877 #ifndef SQLITE_BUSY_RESERVED_LOCK
17878 # define SQLITE_BUSY_RESERVED_LOCK 0
17879 #endif
17882 ** This macro rounds values up so that if the value is an address it
17883 ** is guaranteed to be an address that is aligned to an 8-byte boundary.
17885 #define FORCE_ALIGNMENT(X) (((X)+7)&~7)
17888 ** Each in-memory image of a page begins with the following header.
17889 ** This header is only visible to this pager module. The client
17890 ** code that calls pager sees only the data that follows the header.
17892 ** Client code should call sqlite3PagerWrite() on a page prior to making
17893 ** any modifications to that page. The first time sqlite3PagerWrite()
17894 ** is called, the original page contents are written into the rollback
17895 ** journal and PgHdr.inJournal and PgHdr.needSync are set. Later, once
17896 ** the journal page has made it onto the disk surface, PgHdr.needSync
17897 ** is cleared. The modified page cannot be written back into the original
17898 ** database file until the journal pages has been synced to disk and the
17899 ** PgHdr.needSync has been cleared.
17901 ** The PgHdr.dirty flag is set when sqlite3PagerWrite() is called and
17902 ** is cleared again when the page content is written back to the original
17903 ** database file.
17905 ** Details of important structure elements:
17907 ** needSync
17909 ** If this is true, this means that it is not safe to write the page
17910 ** content to the database because the original content needed
17911 ** for rollback has not by synced to the main rollback journal.
17912 ** The original content may have been written to the rollback journal
17913 ** but it has not yet been synced. So we cannot write to the database
17914 ** file because power failure might cause the page in the journal file
17915 ** to never reach the disk. It is as if the write to the journal file
17916 ** does not occur until the journal file is synced.
17918 ** This flag is false if the page content exactly matches what
17919 ** currently exists in the database file. The needSync flag is also
17920 ** false if the original content has been written to the main rollback
17921 ** journal and synced. If the page represents a new page that has
17922 ** been added onto the end of the database during the current
17923 ** transaction, the needSync flag is true until the original database
17924 ** size in the journal header has been synced to disk.
17926 ** inJournal
17928 ** This is true if the original page has been written into the main
17929 ** rollback journal. This is always false for new pages added to
17930 ** the end of the database file during the current transaction.
17931 ** And this flag says nothing about whether or not the journal
17932 ** has been synced to disk. For pages that are in the original
17933 ** database file, the following expression should always be true:
17935 ** inJournal = (pPager->aInJournal[(pgno-1)/8] & (1<<((pgno-1)%8))!=0
17937 ** The pPager->aInJournal[] array is only valid for the original
17938 ** pages of the database, not new pages that are added to the end
17939 ** of the database, so obviously the above expression cannot be
17940 ** valid for new pages. For new pages inJournal is always 0.
17942 ** dirty
17944 ** When true, this means that the content of the page has been
17945 ** modified and needs to be written back to the database file.
17946 ** If false, it means that either the content of the page is
17947 ** unchanged or else the content is unimportant and we do not
17948 ** care whether or not it is preserved.
17950 ** alwaysRollback
17952 ** This means that the sqlite3PagerDontRollback() API should be
17953 ** ignored for this page. The DontRollback() API attempts to say
17954 ** that the content of the page on disk is unimportant (it is an
17955 ** unused page on the freelist) so that it is unnecessary to
17956 ** rollback changes to this page because the content of the page
17957 ** can change without changing the meaning of the database. This
17958 ** flag overrides any DontRollback() attempt. This flag is set
17959 ** when a page that originally contained valid data is added to
17960 ** the freelist. Later in the same transaction, this page might
17961 ** be pulled from the freelist and reused for something different
17962 ** and at that point the DontRollback() API will be called because
17963 ** pages taken from the freelist do not need to be protected by
17964 ** the rollback journal. But this flag says that the page was
17965 ** not originally part of the freelist so that it still needs to
17966 ** be rolled back in spite of any subsequent DontRollback() calls.
17968 ** needRead
17970 ** This flag means (when true) that the content of the page has
17971 ** not yet been loaded from disk. The in-memory content is just
17972 ** garbage. (Actually, we zero the content, but you should not
17973 ** make any assumptions about the content nevertheless.) If the
17974 ** content is needed in the future, it should be read from the
17975 ** original database file.
17977 typedef struct PgHdr PgHdr;
17978 struct PgHdr {
17979 Pager *pPager; /* The pager to which this page belongs */
17980 Pgno pgno; /* The page number for this page */
17981 PgHdr *pNextHash, *pPrevHash; /* Hash collision chain for PgHdr.pgno */
17982 PgHdr *pNextFree, *pPrevFree; /* Freelist of pages where nRef==0 */
17983 PgHdr *pNextAll; /* A list of all pages */
17984 u8 inJournal; /* TRUE if has been written to journal */
17985 u8 dirty; /* TRUE if we need to write back changes */
17986 u8 needSync; /* Sync journal before writing this page */
17987 u8 alwaysRollback; /* Disable DontRollback() for this page */
17988 u8 needRead; /* Read content if PagerWrite() is called */
17989 short int nRef; /* Number of users of this page */
17990 PgHdr *pDirty, *pPrevDirty; /* Dirty pages */
17991 u32 notUsed; /* Buffer space */
17992 #ifdef SQLITE_CHECK_PAGES
17993 u32 pageHash;
17994 #endif
17995 /* pPager->pageSize bytes of page data follow this header */
17996 /* Pager.nExtra bytes of local data follow the page data */
18000 ** For an in-memory only database, some extra information is recorded about
18001 ** each page so that changes can be rolled back. (Journal files are not
18002 ** used for in-memory databases.) The following information is added to
18003 ** the end of every EXTRA block for in-memory databases.
18005 ** This information could have been added directly to the PgHdr structure.
18006 ** But then it would take up an extra 8 bytes of storage on every PgHdr
18007 ** even for disk-based databases. Splitting it out saves 8 bytes. This
18008 ** is only a savings of 0.8% but those percentages add up.
18010 typedef struct PgHistory PgHistory;
18011 struct PgHistory {
18012 u8 *pOrig; /* Original page text. Restore to this on a full rollback */
18013 u8 *pStmt; /* Text as it was at the beginning of the current statement */
18014 PgHdr *pNextStmt, *pPrevStmt; /* List of pages in the statement journal */
18015 u8 inStmt; /* TRUE if in the statement subjournal */
18019 ** A macro used for invoking the codec if there is one
18021 #ifdef SQLITE_HAS_CODEC
18022 # define CODEC1(P,D,N,X) if( P->xCodec!=0 ){ P->xCodec(P->pCodecArg,D,N,X); }
18023 # define CODEC2(P,D,N,X) ((char*)(P->xCodec!=0?P->xCodec(P->pCodecArg,D,N,X):D))
18024 #else
18025 # define CODEC1(P,D,N,X) /* NO-OP */
18026 # define CODEC2(P,D,N,X) ((char*)D)
18027 #endif
18030 ** Convert a pointer to a PgHdr into a pointer to its data
18031 ** and back again.
18033 #define PGHDR_TO_DATA(P) ((void*)(&(P)[1]))
18034 #define DATA_TO_PGHDR(D) (&((PgHdr*)(D))[-1])
18035 #define PGHDR_TO_EXTRA(G,P) ((void*)&((char*)(&(G)[1]))[(P)->pageSize])
18036 #define PGHDR_TO_HIST(P,PGR) \
18037 ((PgHistory*)&((char*)(&(P)[1]))[(PGR)->pageSize+(PGR)->nExtra])
18040 ** A open page cache is an instance of the following structure.
18042 ** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
18043 ** or SQLITE_FULL. Once one of the first three errors occurs, it persists
18044 ** and is returned as the result of every major pager API call. The
18045 ** SQLITE_FULL return code is slightly different. It persists only until the
18046 ** next successful rollback is performed on the pager cache. Also,
18047 ** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
18048 ** APIs, they may still be used successfully.
18050 struct Pager {
18051 u8 journalOpen; /* True if journal file descriptors is valid */
18052 u8 journalStarted; /* True if header of journal is synced */
18053 u8 useJournal; /* Use a rollback journal on this file */
18054 u8 noReadlock; /* Do not bother to obtain readlocks */
18055 u8 stmtOpen; /* True if the statement subjournal is open */
18056 u8 stmtInUse; /* True we are in a statement subtransaction */
18057 u8 stmtAutoopen; /* Open stmt journal when main journal is opened*/
18058 u8 noSync; /* Do not sync the journal if true */
18059 u8 fullSync; /* Do extra syncs of the journal for robustness */
18060 u8 full_fsync; /* Use F_FULLFSYNC when available */
18061 u8 state; /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
18062 u8 tempFile; /* zFilename is a temporary file */
18063 u8 readOnly; /* True for a read-only database */
18064 u8 needSync; /* True if an fsync() is needed on the journal */
18065 u8 dirtyCache; /* True if cached pages have changed */
18066 u8 alwaysRollback; /* Disable DontRollback() for all pages */
18067 u8 memDb; /* True to inhibit all file I/O */
18068 u8 setMaster; /* True if a m-j name has been written to jrnl */
18069 u8 doNotSync; /* Boolean. While true, do not spill the cache */
18070 u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
18071 u8 changeCountDone; /* Set after incrementing the change-counter */
18072 int errCode; /* One of several kinds of errors */
18073 int dbSize; /* Number of pages in the file */
18074 int origDbSize; /* dbSize before the current change */
18075 int stmtSize; /* Size of database (in pages) at stmt_begin() */
18076 int nRec; /* Number of pages written to the journal */
18077 u32 cksumInit; /* Quasi-random value added to every checksum */
18078 int stmtNRec; /* Number of records in stmt subjournal */
18079 int nExtra; /* Add this many bytes to each in-memory page */
18080 int pageSize; /* Number of bytes in a page */
18081 int nPage; /* Total number of in-memory pages */
18082 int nRef; /* Number of in-memory pages with PgHdr.nRef>0 */
18083 int mxPage; /* Maximum number of pages to hold in cache */
18084 Pgno mxPgno; /* Maximum allowed size of the database */
18085 u8 *aInJournal; /* One bit for each page in the database file */
18086 u8 *aInStmt; /* One bit for each page in the database */
18087 char *zFilename; /* Name of the database file */
18088 char *zJournal; /* Name of the journal file */
18089 char *zDirectory; /* Directory hold database and journal files */
18090 OsFile *fd, *jfd; /* File descriptors for database and journal */
18091 OsFile *stfd; /* File descriptor for the statement subjournal*/
18092 BusyHandler *pBusyHandler; /* Pointer to sqlite.busyHandler */
18093 PgHdr *pFirst, *pLast; /* List of free pages */
18094 PgHdr *pFirstSynced; /* First free page with PgHdr.needSync==0 */
18095 PgHdr *pAll; /* List of all pages */
18096 PgHdr *pStmt; /* List of pages in the statement subjournal */
18097 PgHdr *pDirty; /* List of all dirty pages */
18098 i64 journalOff; /* Current byte offset in the journal file */
18099 i64 journalHdr; /* Byte offset to previous journal header */
18100 i64 stmtHdrOff; /* First journal header written this statement */
18101 i64 stmtCksum; /* cksumInit when statement was started */
18102 i64 stmtJSize; /* Size of journal at stmt_begin() */
18103 int sectorSize; /* Assumed sector size during rollback */
18104 #ifdef SQLITE_TEST
18105 int nHit, nMiss; /* Cache hits and missing */
18106 int nRead, nWrite; /* Database pages read/written */
18107 #endif
18108 void (*xDestructor)(DbPage*,int); /* Call this routine when freeing pages */
18109 void (*xReiniter)(DbPage*,int); /* Call this routine when reloading pages */
18110 #ifdef SQLITE_HAS_CODEC
18111 void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
18112 void *pCodecArg; /* First argument to xCodec() */
18113 #endif
18114 int nHash; /* Size of the pager hash table */
18115 PgHdr **aHash; /* Hash table to map page number to PgHdr */
18116 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18117 Pager *pNext; /* Linked list of pagers in this thread */
18118 #endif
18119 char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
18120 char dbFileVers[16]; /* Changes whenever database file changes */
18124 ** The following global variables hold counters used for
18125 ** testing purposes only. These variables do not exist in
18126 ** a non-testing build. These variables are not thread-safe.
18128 #ifdef SQLITE_TEST
18129 int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
18130 int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
18131 int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
18132 int sqlite3_pager_pgfree_count = 0; /* Number of cache pages freed */
18133 # define PAGER_INCR(v) v++
18134 #else
18135 # define PAGER_INCR(v)
18136 #endif
18141 ** Journal files begin with the following magic string. The data
18142 ** was obtained from /dev/random. It is used only as a sanity check.
18144 ** Since version 2.8.0, the journal format contains additional sanity
18145 ** checking information. If the power fails while the journal is begin
18146 ** written, semi-random garbage data might appear in the journal
18147 ** file after power is restored. If an attempt is then made
18148 ** to roll the journal back, the database could be corrupted. The additional
18149 ** sanity checking data is an attempt to discover the garbage in the
18150 ** journal and ignore it.
18152 ** The sanity checking information for the new journal format consists
18153 ** of a 32-bit checksum on each page of data. The checksum covers both
18154 ** the page number and the pPager->pageSize bytes of data for the page.
18155 ** This cksum is initialized to a 32-bit random value that appears in the
18156 ** journal file right after the header. The random initializer is important,
18157 ** because garbage data that appears at the end of a journal is likely
18158 ** data that was once in other files that have now been deleted. If the
18159 ** garbage data came from an obsolete journal file, the checksums might
18160 ** be correct. But by initializing the checksum to random value which
18161 ** is different for every journal, we minimize that risk.
18163 static const unsigned char aJournalMagic[] = {
18164 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
18168 ** The size of the header and of each page in the journal is determined
18169 ** by the following macros.
18171 #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
18174 ** The journal header size for this pager. In the future, this could be
18175 ** set to some value read from the disk controller. The important
18176 ** characteristic is that it is the same size as a disk sector.
18178 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
18181 ** The macro MEMDB is true if we are dealing with an in-memory database.
18182 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
18183 ** the value of MEMDB will be a constant and the compiler will optimize
18184 ** out code that would never execute.
18186 #ifdef SQLITE_OMIT_MEMORYDB
18187 # define MEMDB 0
18188 #else
18189 # define MEMDB pPager->memDb
18190 #endif
18193 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
18194 ** reserved for working around a windows/posix incompatibility). It is
18195 ** used in the journal to signify that the remainder of the journal file
18196 ** is devoted to storing a master journal name - there are no more pages to
18197 ** roll back. See comments for function writeMasterJournal() for details.
18199 /* #define PAGER_MJ_PGNO(x) (PENDING_BYTE/((x)->pageSize)) */
18200 #define PAGER_MJ_PGNO(x) ((PENDING_BYTE/((x)->pageSize))+1)
18203 ** The maximum legal page number is (2^31 - 1).
18205 #define PAGER_MAX_PGNO 2147483647
18208 ** Enable reference count tracking (for debugging) here:
18210 #ifdef SQLITE_DEBUG
18211 int pager3_refinfo_enable = 0;
18212 static void pager_refinfo(PgHdr *p){
18213 static int cnt = 0;
18214 if( !pager3_refinfo_enable ) return;
18215 sqlite3DebugPrintf(
18216 "REFCNT: %4d addr=%p nRef=%-3d total=%d\n",
18217 p->pgno, PGHDR_TO_DATA(p), p->nRef, p->pPager->nRef
18219 cnt++; /* Something to set a breakpoint on */
18221 # define REFINFO(X) pager_refinfo(X)
18222 #else
18223 # define REFINFO(X)
18224 #endif
18227 ** Return true if page *pPg has already been written to the statement
18228 ** journal (or statement snapshot has been created, if *pPg is part
18229 ** of an in-memory database).
18231 static int pageInStatement(PgHdr *pPg){
18232 Pager *pPager = pPg->pPager;
18233 if( MEMDB ){
18234 return PGHDR_TO_HIST(pPg, pPager)->inStmt;
18235 }else{
18236 Pgno pgno = pPg->pgno;
18237 u8 *a = pPager->aInStmt;
18238 return (a && (int)pgno<=pPager->stmtSize && (a[pgno/8] & (1<<(pgno&7))));
18243 ** Change the size of the pager hash table to N. N must be a power
18244 ** of two.
18246 static void pager_resize_hash_table(Pager *pPager, int N){
18247 PgHdr **aHash, *pPg;
18248 assert( N>0 && (N&(N-1))==0 );
18249 aHash = sqliteMalloc( sizeof(aHash[0])*N );
18250 if( aHash==0 ){
18251 /* Failure to rehash is not an error. It is only a performance hit. */
18252 return;
18254 sqliteFree(pPager->aHash);
18255 pPager->nHash = N;
18256 pPager->aHash = aHash;
18257 for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
18258 int h;
18259 if( pPg->pgno==0 ){
18260 assert( pPg->pNextHash==0 && pPg->pPrevHash==0 );
18261 continue;
18263 h = pPg->pgno & (N-1);
18264 pPg->pNextHash = aHash[h];
18265 if( aHash[h] ){
18266 aHash[h]->pPrevHash = pPg;
18268 aHash[h] = pPg;
18269 pPg->pPrevHash = 0;
18274 ** Read a 32-bit integer from the given file descriptor. Store the integer
18275 ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
18276 ** error code is something goes wrong.
18278 ** All values are stored on disk as big-endian.
18280 static int read32bits(OsFile *fd, u32 *pRes){
18281 unsigned char ac[4];
18282 int rc = sqlite3OsRead(fd, ac, sizeof(ac));
18283 if( rc==SQLITE_OK ){
18284 *pRes = sqlite3Get4byte(ac);
18286 return rc;
18290 ** Write a 32-bit integer into a string buffer in big-endian byte order.
18292 #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
18295 ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
18296 ** on success or an error code is something goes wrong.
18298 static int write32bits(OsFile *fd, u32 val){
18299 char ac[4];
18300 put32bits(ac, val);
18301 return sqlite3OsWrite(fd, ac, 4);
18305 ** Read a 32-bit integer at offset 'offset' from the page identified by
18306 ** page header 'p'.
18308 static u32 retrieve32bits(PgHdr *p, int offset){
18309 unsigned char *ac;
18310 ac = &((unsigned char*)PGHDR_TO_DATA(p))[offset];
18311 return sqlite3Get4byte(ac);
18316 ** This function should be called when an error occurs within the pager
18317 ** code. The first argument is a pointer to the pager structure, the
18318 ** second the error-code about to be returned by a pager API function.
18319 ** The value returned is a copy of the second argument to this function.
18321 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
18322 ** the error becomes persistent. All subsequent API calls on this Pager
18323 ** will immediately return the same error code.
18325 static int pager_error(Pager *pPager, int rc){
18326 int rc2 = rc & 0xff;
18327 assert( pPager->errCode==SQLITE_FULL || pPager->errCode==SQLITE_OK );
18329 rc2==SQLITE_FULL ||
18330 rc2==SQLITE_IOERR ||
18331 rc2==SQLITE_CORRUPT
18333 pPager->errCode = rc;
18335 return rc;
18339 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
18340 ** on the cache using a hash function. This is used for testing
18341 ** and debugging only.
18343 #ifdef SQLITE_CHECK_PAGES
18345 ** Return a 32-bit hash of the page data for pPage.
18347 static u32 pager_datahash(int nByte, unsigned char *pData){
18348 u32 hash = 0;
18349 int i;
18350 for(i=0; i<nByte; i++){
18351 hash = (hash*1039) + pData[i];
18353 return hash;
18355 static u32 pager_pagehash(PgHdr *pPage){
18356 return pager_datahash(pPage->pPager->pageSize,
18357 (unsigned char *)PGHDR_TO_DATA(pPage));
18361 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
18362 ** is defined, and NDEBUG is not defined, an assert() statement checks
18363 ** that the page is either dirty or still matches the calculated page-hash.
18365 #define CHECK_PAGE(x) checkPage(x)
18366 static void checkPage(PgHdr *pPg){
18367 Pager *pPager = pPg->pPager;
18368 assert( !pPg->pageHash || pPager->errCode || MEMDB || pPg->dirty ||
18369 pPg->pageHash==pager_pagehash(pPg) );
18372 #else
18373 #define pager_datahash(X,Y) 0
18374 #define pager_pagehash(X) 0
18375 #define CHECK_PAGE(x)
18376 #endif
18379 ** When this is called the journal file for pager pPager must be open.
18380 ** The master journal file name is read from the end of the file and
18381 ** written into memory obtained from sqliteMalloc(). *pzMaster is
18382 ** set to point at the memory and SQLITE_OK returned. The caller must
18383 ** sqliteFree() *pzMaster.
18385 ** If no master journal file name is present *pzMaster is set to 0 and
18386 ** SQLITE_OK returned.
18388 static int readMasterJournal(OsFile *pJrnl, char **pzMaster){
18389 int rc;
18390 u32 len;
18391 i64 szJ;
18392 u32 cksum;
18393 int i;
18394 unsigned char aMagic[8]; /* A buffer to hold the magic header */
18396 *pzMaster = 0;
18398 rc = sqlite3OsFileSize(pJrnl, &szJ);
18399 if( rc!=SQLITE_OK || szJ<16 ) return rc;
18401 rc = sqlite3OsSeek(pJrnl, szJ-16);
18402 if( rc!=SQLITE_OK ) return rc;
18404 rc = read32bits(pJrnl, &len);
18405 if( rc!=SQLITE_OK ) return rc;
18407 rc = read32bits(pJrnl, &cksum);
18408 if( rc!=SQLITE_OK ) return rc;
18410 rc = sqlite3OsRead(pJrnl, aMagic, 8);
18411 if( rc!=SQLITE_OK || memcmp(aMagic, aJournalMagic, 8) ) return rc;
18413 rc = sqlite3OsSeek(pJrnl, szJ-16-len);
18414 if( rc!=SQLITE_OK ) return rc;
18416 *pzMaster = (char *)sqliteMalloc(len+1);
18417 if( !*pzMaster ){
18418 return SQLITE_NOMEM;
18420 rc = sqlite3OsRead(pJrnl, *pzMaster, len);
18421 if( rc!=SQLITE_OK ){
18422 sqliteFree(*pzMaster);
18423 *pzMaster = 0;
18424 return rc;
18427 /* See if the checksum matches the master journal name */
18428 for(i=0; i<len; i++){
18429 cksum -= (*pzMaster)[i];
18431 if( cksum ){
18432 /* If the checksum doesn't add up, then one or more of the disk sectors
18433 ** containing the master journal filename is corrupted. This means
18434 ** definitely roll back, so just return SQLITE_OK and report a (nul)
18435 ** master-journal filename.
18437 sqliteFree(*pzMaster);
18438 *pzMaster = 0;
18439 }else{
18440 (*pzMaster)[len] = '\0';
18443 return SQLITE_OK;
18447 ** Seek the journal file descriptor to the next sector boundary where a
18448 ** journal header may be read or written. Pager.journalOff is updated with
18449 ** the new seek offset.
18451 ** i.e for a sector size of 512:
18453 ** Input Offset Output Offset
18454 ** ---------------------------------------
18455 ** 0 0
18456 ** 512 512
18457 ** 100 512
18458 ** 2000 2048
18461 static int seekJournalHdr(Pager *pPager){
18462 i64 offset = 0;
18463 i64 c = pPager->journalOff;
18464 if( c ){
18465 offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
18467 assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
18468 assert( offset>=c );
18469 assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
18470 pPager->journalOff = offset;
18471 return sqlite3OsSeek(pPager->jfd, pPager->journalOff);
18475 ** The journal file must be open when this routine is called. A journal
18476 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
18477 ** current location.
18479 ** The format for the journal header is as follows:
18480 ** - 8 bytes: Magic identifying journal format.
18481 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
18482 ** - 4 bytes: Random number used for page hash.
18483 ** - 4 bytes: Initial database page count.
18484 ** - 4 bytes: Sector size used by the process that wrote this journal.
18486 ** Followed by (JOURNAL_HDR_SZ - 24) bytes of unused space.
18488 static int writeJournalHdr(Pager *pPager){
18489 char zHeader[sizeof(aJournalMagic)+16];
18490 int rc;
18492 if( pPager->stmtHdrOff==0 ){
18493 pPager->stmtHdrOff = pPager->journalOff;
18496 rc = seekJournalHdr(pPager);
18497 if( rc ) return rc;
18499 pPager->journalHdr = pPager->journalOff;
18500 pPager->journalOff += JOURNAL_HDR_SZ(pPager);
18502 /* FIX ME:
18504 ** Possibly for a pager not in no-sync mode, the journal magic should not
18505 ** be written until nRec is filled in as part of next syncJournal().
18507 ** Actually maybe the whole journal header should be delayed until that
18508 ** point. Think about this.
18510 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
18511 /* The nRec Field. 0xFFFFFFFF for no-sync journals. */
18512 put32bits(&zHeader[sizeof(aJournalMagic)], pPager->noSync ? 0xffffffff : 0);
18513 /* The random check-hash initialiser */
18514 sqlite3Randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
18515 put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
18516 /* The initial database size */
18517 put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbSize);
18518 /* The assumed sector size for this process */
18519 put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
18520 IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, sizeof(zHeader)))
18521 rc = sqlite3OsWrite(pPager->jfd, zHeader, sizeof(zHeader));
18523 /* The journal header has been written successfully. Seek the journal
18524 ** file descriptor to the end of the journal header sector.
18526 if( rc==SQLITE_OK ){
18527 IOTRACE(("JTAIL %p %lld\n", pPager, pPager->journalOff-1))
18528 rc = sqlite3OsSeek(pPager->jfd, pPager->journalOff-1);
18529 if( rc==SQLITE_OK ){
18530 rc = sqlite3OsWrite(pPager->jfd, "\000", 1);
18533 return rc;
18537 ** The journal file must be open when this is called. A journal header file
18538 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
18539 ** file. See comments above function writeJournalHdr() for a description of
18540 ** the journal header format.
18542 ** If the header is read successfully, *nRec is set to the number of
18543 ** page records following this header and *dbSize is set to the size of the
18544 ** database before the transaction began, in pages. Also, pPager->cksumInit
18545 ** is set to the value read from the journal header. SQLITE_OK is returned
18546 ** in this case.
18548 ** If the journal header file appears to be corrupted, SQLITE_DONE is
18549 ** returned and *nRec and *dbSize are not set. If JOURNAL_HDR_SZ bytes
18550 ** cannot be read from the journal file an error code is returned.
18552 static int readJournalHdr(
18553 Pager *pPager,
18554 i64 journalSize,
18555 u32 *pNRec,
18556 u32 *pDbSize
18558 int rc;
18559 unsigned char aMagic[8]; /* A buffer to hold the magic header */
18561 rc = seekJournalHdr(pPager);
18562 if( rc ) return rc;
18564 if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
18565 return SQLITE_DONE;
18568 rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic));
18569 if( rc ) return rc;
18571 if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
18572 return SQLITE_DONE;
18575 rc = read32bits(pPager->jfd, pNRec);
18576 if( rc ) return rc;
18578 rc = read32bits(pPager->jfd, &pPager->cksumInit);
18579 if( rc ) return rc;
18581 rc = read32bits(pPager->jfd, pDbSize);
18582 if( rc ) return rc;
18584 /* Update the assumed sector-size to match the value used by
18585 ** the process that created this journal. If this journal was
18586 ** created by a process other than this one, then this routine
18587 ** is being called from within pager_playback(). The local value
18588 ** of Pager.sectorSize is restored at the end of that routine.
18590 rc = read32bits(pPager->jfd, (u32 *)&pPager->sectorSize);
18591 if( rc ) return rc;
18593 pPager->journalOff += JOURNAL_HDR_SZ(pPager);
18594 rc = sqlite3OsSeek(pPager->jfd, pPager->journalOff);
18595 return rc;
18600 ** Write the supplied master journal name into the journal file for pager
18601 ** pPager at the current location. The master journal name must be the last
18602 ** thing written to a journal file. If the pager is in full-sync mode, the
18603 ** journal file descriptor is advanced to the next sector boundary before
18604 ** anything is written. The format is:
18606 ** + 4 bytes: PAGER_MJ_PGNO.
18607 ** + N bytes: length of master journal name.
18608 ** + 4 bytes: N
18609 ** + 4 bytes: Master journal name checksum.
18610 ** + 8 bytes: aJournalMagic[].
18612 ** The master journal page checksum is the sum of the bytes in the master
18613 ** journal name.
18615 ** If zMaster is a NULL pointer (occurs for a single database transaction),
18616 ** this call is a no-op.
18618 static int writeMasterJournal(Pager *pPager, const char *zMaster){
18619 int rc;
18620 int len;
18621 int i;
18622 u32 cksum = 0;
18623 char zBuf[sizeof(aJournalMagic)+2*4];
18625 if( !zMaster || pPager->setMaster) return SQLITE_OK;
18626 pPager->setMaster = 1;
18628 len = strlen(zMaster);
18629 for(i=0; i<len; i++){
18630 cksum += zMaster[i];
18633 /* If in full-sync mode, advance to the next disk sector before writing
18634 ** the master journal name. This is in case the previous page written to
18635 ** the journal has already been synced.
18637 if( pPager->fullSync ){
18638 rc = seekJournalHdr(pPager);
18639 if( rc!=SQLITE_OK ) return rc;
18641 pPager->journalOff += (len+20);
18643 rc = write32bits(pPager->jfd, PAGER_MJ_PGNO(pPager));
18644 if( rc!=SQLITE_OK ) return rc;
18646 rc = sqlite3OsWrite(pPager->jfd, zMaster, len);
18647 if( rc!=SQLITE_OK ) return rc;
18649 put32bits(zBuf, len);
18650 put32bits(&zBuf[4], cksum);
18651 memcpy(&zBuf[8], aJournalMagic, sizeof(aJournalMagic));
18652 rc = sqlite3OsWrite(pPager->jfd, zBuf, 8+sizeof(aJournalMagic));
18653 pPager->needSync = !pPager->noSync;
18654 return rc;
18658 ** Add or remove a page from the list of all pages that are in the
18659 ** statement journal.
18661 ** The Pager keeps a separate list of pages that are currently in
18662 ** the statement journal. This helps the sqlite3PagerStmtCommit()
18663 ** routine run MUCH faster for the common case where there are many
18664 ** pages in memory but only a few are in the statement journal.
18666 static void page_add_to_stmt_list(PgHdr *pPg){
18667 Pager *pPager = pPg->pPager;
18668 PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
18669 assert( MEMDB );
18670 if( !pHist->inStmt ){
18671 assert( pHist->pPrevStmt==0 && pHist->pNextStmt==0 );
18672 if( pPager->pStmt ){
18673 PGHDR_TO_HIST(pPager->pStmt, pPager)->pPrevStmt = pPg;
18675 pHist->pNextStmt = pPager->pStmt;
18676 pPager->pStmt = pPg;
18677 pHist->inStmt = 1;
18682 ** Find a page in the hash table given its page number. Return
18683 ** a pointer to the page or NULL if not found.
18685 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
18686 PgHdr *p;
18687 if( pPager->aHash==0 ) return 0;
18688 p = pPager->aHash[pgno & (pPager->nHash-1)];
18689 while( p && p->pgno!=pgno ){
18690 p = p->pNextHash;
18692 return p;
18696 ** Unlock the database file.
18698 static void pager_unlock(Pager *pPager){
18699 if( !pPager->exclusiveMode ){
18700 if( !MEMDB ){
18701 sqlite3OsUnlock(pPager->fd, NO_LOCK);
18702 pPager->dbSize = -1;
18703 IOTRACE(("UNLOCK %p\n", pPager))
18705 pPager->state = PAGER_UNLOCK;
18706 pPager->changeCountDone = 0;
18711 ** Execute a rollback if a transaction is active and unlock the
18712 ** database file. This is a no-op if the pager has already entered
18713 ** the error-state.
18715 static void pagerUnlockAndRollback(Pager *p){
18716 if( p->errCode ) return;
18717 assert( p->state>=PAGER_RESERVED || p->journalOpen==0 );
18718 if( p->state>=PAGER_RESERVED ){
18719 sqlite3PagerRollback(p);
18721 pager_unlock(p);
18722 assert( p->errCode || !p->journalOpen || (p->exclusiveMode&&!p->journalOff) );
18723 assert( p->errCode || !p->stmtOpen || p->exclusiveMode );
18728 ** Clear the in-memory cache. This routine
18729 ** sets the state of the pager back to what it was when it was first
18730 ** opened. Any outstanding pages are invalidated and subsequent attempts
18731 ** to access those pages will likely result in a coredump.
18733 static void pager_reset(Pager *pPager){
18734 PgHdr *pPg, *pNext;
18735 if( pPager->errCode ) return;
18736 for(pPg=pPager->pAll; pPg; pPg=pNext){
18737 IOTRACE(("PGFREE %p %d\n", pPager, pPg->pgno));
18738 PAGER_INCR(sqlite3_pager_pgfree_count);
18739 pNext = pPg->pNextAll;
18740 sqliteFree(pPg);
18742 pPager->pStmt = 0;
18743 pPager->pFirst = 0;
18744 pPager->pFirstSynced = 0;
18745 pPager->pLast = 0;
18746 pPager->pAll = 0;
18747 pPager->nHash = 0;
18748 sqliteFree(pPager->aHash);
18749 pPager->nPage = 0;
18750 pPager->aHash = 0;
18751 pPager->nRef = 0;
18755 ** This routine ends a transaction. A transaction is ended by either
18756 ** a COMMIT or a ROLLBACK.
18758 ** When this routine is called, the pager has the journal file open and
18759 ** a RESERVED or EXCLUSIVE lock on the database. This routine will release
18760 ** the database lock and acquires a SHARED lock in its place if that is
18761 ** the appropriate thing to do. Release locks usually is appropriate,
18762 ** unless we are in exclusive access mode or unless this is a
18763 ** COMMIT AND BEGIN or ROLLBACK AND BEGIN operation.
18765 ** The journal file is either deleted or truncated.
18767 ** TODO: Consider keeping the journal file open for temporary databases.
18768 ** This might give a performance improvement on windows where opening
18769 ** a file is an expensive operation.
18771 static int pager_end_transaction(Pager *pPager){
18772 PgHdr *pPg;
18773 int rc = SQLITE_OK;
18774 int rc2 = SQLITE_OK;
18775 assert( !MEMDB );
18776 if( pPager->state<PAGER_RESERVED ){
18777 return SQLITE_OK;
18779 sqlite3PagerStmtCommit(pPager);
18780 if( pPager->stmtOpen && !pPager->exclusiveMode ){
18781 sqlite3OsClose(&pPager->stfd);
18782 pPager->stmtOpen = 0;
18784 if( pPager->journalOpen ){
18785 if( pPager->exclusiveMode
18786 && (rc = sqlite3OsTruncate(pPager->jfd, 0))==SQLITE_OK ){;
18787 sqlite3OsSeek(pPager->jfd, 0);
18788 pPager->journalOff = 0;
18789 pPager->journalStarted = 0;
18790 }else{
18791 sqlite3OsClose(&pPager->jfd);
18792 pPager->journalOpen = 0;
18793 if( rc==SQLITE_OK ){
18794 rc = sqlite3OsDelete(pPager->zJournal);
18797 sqliteFree( pPager->aInJournal );
18798 pPager->aInJournal = 0;
18799 for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
18800 pPg->inJournal = 0;
18801 pPg->dirty = 0;
18802 pPg->needSync = 0;
18803 pPg->alwaysRollback = 0;
18804 #ifdef SQLITE_CHECK_PAGES
18805 pPg->pageHash = pager_pagehash(pPg);
18806 #endif
18808 pPager->pDirty = 0;
18809 pPager->dirtyCache = 0;
18810 pPager->nRec = 0;
18811 }else{
18812 assert( pPager->aInJournal==0 );
18813 assert( pPager->dirtyCache==0 || pPager->useJournal==0 );
18816 if( !pPager->exclusiveMode ){
18817 rc2 = sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
18818 pPager->state = PAGER_SHARED;
18819 }else if( pPager->state==PAGER_SYNCED ){
18820 pPager->state = PAGER_EXCLUSIVE;
18822 pPager->origDbSize = 0;
18823 pPager->setMaster = 0;
18824 pPager->needSync = 0;
18825 pPager->pFirstSynced = pPager->pFirst;
18826 pPager->dbSize = -1;
18828 return (rc==SQLITE_OK?rc2:rc);
18832 ** Compute and return a checksum for the page of data.
18834 ** This is not a real checksum. It is really just the sum of the
18835 ** random initial value and the page number. We experimented with
18836 ** a checksum of the entire data, but that was found to be too slow.
18838 ** Note that the page number is stored at the beginning of data and
18839 ** the checksum is stored at the end. This is important. If journal
18840 ** corruption occurs due to a power failure, the most likely scenario
18841 ** is that one end or the other of the record will be changed. It is
18842 ** much less likely that the two ends of the journal record will be
18843 ** correct and the middle be corrupt. Thus, this "checksum" scheme,
18844 ** though fast and simple, catches the mostly likely kind of corruption.
18846 ** FIX ME: Consider adding every 200th (or so) byte of the data to the
18847 ** checksum. That way if a single page spans 3 or more disk sectors and
18848 ** only the middle sector is corrupt, we will still have a reasonable
18849 ** chance of failing the checksum and thus detecting the problem.
18851 static u32 pager_cksum(Pager *pPager, const u8 *aData){
18852 u32 cksum = pPager->cksumInit;
18853 int i = pPager->pageSize-200;
18854 while( i>0 ){
18855 cksum += aData[i];
18856 i -= 200;
18858 return cksum;
18861 /* Forward declaration */
18862 static void makeClean(PgHdr*);
18865 ** Read a single page from the journal file opened on file descriptor
18866 ** jfd. Playback this one page.
18868 ** If useCksum==0 it means this journal does not use checksums. Checksums
18869 ** are not used in statement journals because statement journals do not
18870 ** need to survive power failures.
18872 static int pager_playback_one_page(Pager *pPager, OsFile *jfd, int useCksum){
18873 int rc;
18874 PgHdr *pPg; /* An existing page in the cache */
18875 Pgno pgno; /* The page number of a page in journal */
18876 u32 cksum; /* Checksum used for sanity checking */
18877 u8 *aData = (u8 *)pPager->pTmpSpace; /* Temp storage for a page */
18879 /* useCksum should be true for the main journal and false for
18880 ** statement journals. Verify that this is always the case
18882 assert( jfd == (useCksum ? pPager->jfd : pPager->stfd) );
18883 assert( aData );
18885 rc = read32bits(jfd, &pgno);
18886 if( rc!=SQLITE_OK ) return rc;
18887 rc = sqlite3OsRead(jfd, aData, pPager->pageSize);
18888 if( rc!=SQLITE_OK ) return rc;
18889 pPager->journalOff += pPager->pageSize + 4;
18891 /* Sanity checking on the page. This is more important that I originally
18892 ** thought. If a power failure occurs while the journal is being written,
18893 ** it could cause invalid data to be written into the journal. We need to
18894 ** detect this invalid data (with high probability) and ignore it.
18896 if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
18897 return SQLITE_DONE;
18899 if( pgno>(unsigned)pPager->dbSize ){
18900 return SQLITE_OK;
18902 if( useCksum ){
18903 rc = read32bits(jfd, &cksum);
18904 if( rc ) return rc;
18905 pPager->journalOff += 4;
18906 if( pager_cksum(pPager, aData)!=cksum ){
18907 return SQLITE_DONE;
18911 assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
18913 /* If the pager is in RESERVED state, then there must be a copy of this
18914 ** page in the pager cache. In this case just update the pager cache,
18915 ** not the database file. The page is left marked dirty in this case.
18917 ** An exception to the above rule: If the database is in no-sync mode
18918 ** and a page is moved during an incremental vacuum then the page may
18919 ** not be in the pager cache. Later: if a malloc() or IO error occurs
18920 ** during a Movepage() call, then the page may not be in the cache
18921 ** either. So the condition described in the above paragraph is not
18922 ** assert()able.
18924 ** If in EXCLUSIVE state, then we update the pager cache if it exists
18925 ** and the main file. The page is then marked not dirty.
18927 ** Ticket #1171: The statement journal might contain page content that is
18928 ** different from the page content at the start of the transaction.
18929 ** This occurs when a page is changed prior to the start of a statement
18930 ** then changed again within the statement. When rolling back such a
18931 ** statement we must not write to the original database unless we know
18932 ** for certain that original page contents are synced into the main rollback
18933 ** journal. Otherwise, a power loss might leave modified data in the
18934 ** database file without an entry in the rollback journal that can
18935 ** restore the database to its original form. Two conditions must be
18936 ** met before writing to the database files. (1) the database must be
18937 ** locked. (2) we know that the original page content is fully synced
18938 ** in the main journal either because the page is not in cache or else
18939 ** the page is marked as needSync==0.
18941 pPg = pager_lookup(pPager, pgno);
18942 PAGERTRACE4("PLAYBACK %d page %d hash(%08x)\n",
18943 PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData));
18944 if( pPager->state>=PAGER_EXCLUSIVE && (pPg==0 || pPg->needSync==0) ){
18945 rc = sqlite3OsSeek(pPager->fd, (pgno-1)*(i64)pPager->pageSize);
18946 if( rc==SQLITE_OK ){
18947 rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize);
18949 if( pPg ){
18950 makeClean(pPg);
18953 if( pPg ){
18954 /* No page should ever be explicitly rolled back that is in use, except
18955 ** for page 1 which is held in use in order to keep the lock on the
18956 ** database active. However such a page may be rolled back as a result
18957 ** of an internal error resulting in an automatic call to
18958 ** sqlite3PagerRollback().
18960 void *pData;
18961 /* assert( pPg->nRef==0 || pPg->pgno==1 ); */
18962 pData = PGHDR_TO_DATA(pPg);
18963 memcpy(pData, aData, pPager->pageSize);
18964 if( pPager->xReiniter ){
18965 pPager->xReiniter(pPg, pPager->pageSize);
18967 #ifdef SQLITE_CHECK_PAGES
18968 pPg->pageHash = pager_pagehash(pPg);
18969 #endif
18970 /* If this was page 1, then restore the value of Pager.dbFileVers.
18971 ** Do this before any decoding. */
18972 if( pgno==1 ){
18973 memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
18976 /* Decode the page just read from disk */
18977 CODEC1(pPager, pData, pPg->pgno, 3);
18979 return rc;
18983 ** Parameter zMaster is the name of a master journal file. A single journal
18984 ** file that referred to the master journal file has just been rolled back.
18985 ** This routine checks if it is possible to delete the master journal file,
18986 ** and does so if it is.
18988 ** The master journal file contains the names of all child journals.
18989 ** To tell if a master journal can be deleted, check to each of the
18990 ** children. If all children are either missing or do not refer to
18991 ** a different master journal, then this master journal can be deleted.
18993 static int pager_delmaster(const char *zMaster){
18994 int rc;
18995 int master_open = 0;
18996 OsFile *master = 0;
18997 char *zMasterJournal = 0; /* Contents of master journal file */
18998 i64 nMasterJournal; /* Size of master journal file */
19000 /* Open the master journal file exclusively in case some other process
19001 ** is running this routine also. Not that it makes too much difference.
19003 rc = sqlite3OsOpenReadOnly(zMaster, &master);
19004 assert( rc!=SQLITE_OK || master );
19005 if( rc!=SQLITE_OK ) goto delmaster_out;
19006 master_open = 1;
19007 rc = sqlite3OsFileSize(master, &nMasterJournal);
19008 if( rc!=SQLITE_OK ) goto delmaster_out;
19010 if( nMasterJournal>0 ){
19011 char *zJournal;
19012 char *zMasterPtr = 0;
19014 /* Load the entire master journal file into space obtained from
19015 ** sqliteMalloc() and pointed to by zMasterJournal.
19017 zMasterJournal = (char *)sqliteMalloc(nMasterJournal);
19018 if( !zMasterJournal ){
19019 rc = SQLITE_NOMEM;
19020 goto delmaster_out;
19022 rc = sqlite3OsRead(master, zMasterJournal, nMasterJournal);
19023 if( rc!=SQLITE_OK ) goto delmaster_out;
19025 zJournal = zMasterJournal;
19026 while( (zJournal-zMasterJournal)<nMasterJournal ){
19027 if( sqlite3OsFileExists(zJournal) ){
19028 /* One of the journals pointed to by the master journal exists.
19029 ** Open it and check if it points at the master journal. If
19030 ** so, return without deleting the master journal file.
19032 OsFile *journal = 0;
19033 int c;
19035 rc = sqlite3OsOpenReadOnly(zJournal, &journal);
19036 assert( rc!=SQLITE_OK || journal );
19037 if( rc!=SQLITE_OK ){
19038 goto delmaster_out;
19041 rc = readMasterJournal(journal, &zMasterPtr);
19042 sqlite3OsClose(&journal);
19043 if( rc!=SQLITE_OK ){
19044 goto delmaster_out;
19047 c = zMasterPtr!=0 && strcmp(zMasterPtr, zMaster)==0;
19048 sqliteFree(zMasterPtr);
19049 if( c ){
19050 /* We have a match. Do not delete the master journal file. */
19051 goto delmaster_out;
19054 zJournal += (strlen(zJournal)+1);
19058 rc = sqlite3OsDelete(zMaster);
19060 delmaster_out:
19061 if( zMasterJournal ){
19062 sqliteFree(zMasterJournal);
19064 if( master_open ){
19065 sqlite3OsClose(&master);
19067 return rc;
19071 static void pager_truncate_cache(Pager *pPager);
19074 ** Truncate the main file of the given pager to the number of pages
19075 ** indicated. Also truncate the cached representation of the file.
19077 static int pager_truncate(Pager *pPager, int nPage){
19078 int rc = SQLITE_OK;
19079 if( pPager->state>=PAGER_EXCLUSIVE ){
19080 rc = sqlite3OsTruncate(pPager->fd, pPager->pageSize*(i64)nPage);
19082 if( rc==SQLITE_OK ){
19083 pPager->dbSize = nPage;
19084 pager_truncate_cache(pPager);
19086 return rc;
19090 ** Set the sectorSize for the given pager.
19092 ** The sector size is the larger of the sector size reported
19093 ** by sqlite3OsSectorSize() and the pageSize.
19095 static void setSectorSize(Pager *pPager){
19096 pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
19097 if( pPager->sectorSize<pPager->pageSize ){
19098 pPager->sectorSize = pPager->pageSize;
19103 ** Playback the journal and thus restore the database file to
19104 ** the state it was in before we started making changes.
19106 ** The journal file format is as follows:
19108 ** (1) 8 byte prefix. A copy of aJournalMagic[].
19109 ** (2) 4 byte big-endian integer which is the number of valid page records
19110 ** in the journal. If this value is 0xffffffff, then compute the
19111 ** number of page records from the journal size.
19112 ** (3) 4 byte big-endian integer which is the initial value for the
19113 ** sanity checksum.
19114 ** (4) 4 byte integer which is the number of pages to truncate the
19115 ** database to during a rollback.
19116 ** (5) 4 byte integer which is the number of bytes in the master journal
19117 ** name. The value may be zero (indicate that there is no master
19118 ** journal.)
19119 ** (6) N bytes of the master journal name. The name will be nul-terminated
19120 ** and might be shorter than the value read from (5). If the first byte
19121 ** of the name is \000 then there is no master journal. The master
19122 ** journal name is stored in UTF-8.
19123 ** (7) Zero or more pages instances, each as follows:
19124 ** + 4 byte page number.
19125 ** + pPager->pageSize bytes of data.
19126 ** + 4 byte checksum
19128 ** When we speak of the journal header, we mean the first 6 items above.
19129 ** Each entry in the journal is an instance of the 7th item.
19131 ** Call the value from the second bullet "nRec". nRec is the number of
19132 ** valid page entries in the journal. In most cases, you can compute the
19133 ** value of nRec from the size of the journal file. But if a power
19134 ** failure occurred while the journal was being written, it could be the
19135 ** case that the size of the journal file had already been increased but
19136 ** the extra entries had not yet made it safely to disk. In such a case,
19137 ** the value of nRec computed from the file size would be too large. For
19138 ** that reason, we always use the nRec value in the header.
19140 ** If the nRec value is 0xffffffff it means that nRec should be computed
19141 ** from the file size. This value is used when the user selects the
19142 ** no-sync option for the journal. A power failure could lead to corruption
19143 ** in this case. But for things like temporary table (which will be
19144 ** deleted when the power is restored) we don't care.
19146 ** If the file opened as the journal file is not a well-formed
19147 ** journal file then all pages up to the first corrupted page are rolled
19148 ** back (or no pages if the journal header is corrupted). The journal file
19149 ** is then deleted and SQLITE_OK returned, just as if no corruption had
19150 ** been encountered.
19152 ** If an I/O or malloc() error occurs, the journal-file is not deleted
19153 ** and an error code is returned.
19155 static int pager_playback(Pager *pPager, int isHot){
19156 i64 szJ; /* Size of the journal file in bytes */
19157 u32 nRec; /* Number of Records in the journal */
19158 int i; /* Loop counter */
19159 Pgno mxPg = 0; /* Size of the original file in pages */
19160 int rc; /* Result code of a subroutine */
19161 char *zMaster = 0; /* Name of master journal file if any */
19163 /* Figure out how many records are in the journal. Abort early if
19164 ** the journal is empty.
19166 assert( pPager->journalOpen );
19167 rc = sqlite3OsFileSize(pPager->jfd, &szJ);
19168 if( rc!=SQLITE_OK || szJ==0 ){
19169 goto end_playback;
19172 /* Read the master journal name from the journal, if it is present.
19173 ** If a master journal file name is specified, but the file is not
19174 ** present on disk, then the journal is not hot and does not need to be
19175 ** played back.
19177 rc = readMasterJournal(pPager->jfd, &zMaster);
19178 assert( rc!=SQLITE_DONE );
19179 if( rc!=SQLITE_OK || (zMaster && !sqlite3OsFileExists(zMaster)) ){
19180 sqliteFree(zMaster);
19181 zMaster = 0;
19182 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
19183 goto end_playback;
19185 sqlite3OsSeek(pPager->jfd, 0);
19186 pPager->journalOff = 0;
19188 /* This loop terminates either when the readJournalHdr() call returns
19189 ** SQLITE_DONE or an IO error occurs. */
19190 while( 1 ){
19192 /* Read the next journal header from the journal file. If there are
19193 ** not enough bytes left in the journal file for a complete header, or
19194 ** it is corrupted, then a process must of failed while writing it.
19195 ** This indicates nothing more needs to be rolled back.
19197 rc = readJournalHdr(pPager, szJ, &nRec, &mxPg);
19198 if( rc!=SQLITE_OK ){
19199 if( rc==SQLITE_DONE ){
19200 rc = SQLITE_OK;
19202 goto end_playback;
19205 /* If nRec is 0xffffffff, then this journal was created by a process
19206 ** working in no-sync mode. This means that the rest of the journal
19207 ** file consists of pages, there are no more journal headers. Compute
19208 ** the value of nRec based on this assumption.
19210 if( nRec==0xffffffff ){
19211 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
19212 nRec = (szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager);
19215 /* If nRec is 0 and this rollback is of a transaction created by this
19216 ** process. In this case the rest of the journal file consists of
19217 ** journalled copies of pages that need to be read back into the cache.
19219 if( nRec==0 && !isHot ){
19220 nRec = (szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager);
19223 /* If this is the first header read from the journal, truncate the
19224 ** database file back to it's original size.
19226 if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
19227 rc = pager_truncate(pPager, mxPg);
19228 if( rc!=SQLITE_OK ){
19229 goto end_playback;
19233 /* Copy original pages out of the journal and back into the database file.
19235 for(i=0; i<nRec; i++){
19236 rc = pager_playback_one_page(pPager, pPager->jfd, 1);
19237 if( rc!=SQLITE_OK ){
19238 if( rc==SQLITE_DONE ){
19239 rc = SQLITE_OK;
19240 pPager->journalOff = szJ;
19241 break;
19242 }else{
19243 goto end_playback;
19248 /*NOTREACHED*/
19249 assert( 0 );
19251 end_playback:
19252 if( rc==SQLITE_OK ){
19253 rc = pager_end_transaction(pPager);
19255 if( zMaster ){
19256 /* If there was a master journal and this routine will return success,
19257 ** see if it is possible to delete the master journal.
19259 if( rc==SQLITE_OK ){
19260 rc = pager_delmaster(zMaster);
19262 sqliteFree(zMaster);
19265 /* The Pager.sectorSize variable may have been updated while rolling
19266 ** back a journal created by a process with a different sector size
19267 ** value. Reset it to the correct value for this process.
19269 setSectorSize(pPager);
19270 return rc;
19274 ** Playback the statement journal.
19276 ** This is similar to playing back the transaction journal but with
19277 ** a few extra twists.
19279 ** (1) The number of pages in the database file at the start of
19280 ** the statement is stored in pPager->stmtSize, not in the
19281 ** journal file itself.
19283 ** (2) In addition to playing back the statement journal, also
19284 ** playback all pages of the transaction journal beginning
19285 ** at offset pPager->stmtJSize.
19287 static int pager_stmt_playback(Pager *pPager){
19288 i64 szJ; /* Size of the full journal */
19289 i64 hdrOff;
19290 int nRec; /* Number of Records */
19291 int i; /* Loop counter */
19292 int rc;
19294 szJ = pPager->journalOff;
19295 #ifndef NDEBUG
19297 i64 os_szJ;
19298 rc = sqlite3OsFileSize(pPager->jfd, &os_szJ);
19299 if( rc!=SQLITE_OK ) return rc;
19300 assert( szJ==os_szJ );
19302 #endif
19304 /* Set hdrOff to be the offset just after the end of the last journal
19305 ** page written before the first journal-header for this statement
19306 ** transaction was written, or the end of the file if no journal
19307 ** header was written.
19309 hdrOff = pPager->stmtHdrOff;
19310 assert( pPager->fullSync || !hdrOff );
19311 if( !hdrOff ){
19312 hdrOff = szJ;
19315 /* Truncate the database back to its original size.
19317 rc = pager_truncate(pPager, pPager->stmtSize);
19318 assert( pPager->state>=PAGER_SHARED );
19320 /* Figure out how many records are in the statement journal.
19322 assert( pPager->stmtInUse && pPager->journalOpen );
19323 sqlite3OsSeek(pPager->stfd, 0);
19324 nRec = pPager->stmtNRec;
19326 /* Copy original pages out of the statement journal and back into the
19327 ** database file. Note that the statement journal omits checksums from
19328 ** each record since power-failure recovery is not important to statement
19329 ** journals.
19331 for(i=nRec-1; i>=0; i--){
19332 rc = pager_playback_one_page(pPager, pPager->stfd, 0);
19333 assert( rc!=SQLITE_DONE );
19334 if( rc!=SQLITE_OK ) goto end_stmt_playback;
19337 /* Now roll some pages back from the transaction journal. Pager.stmtJSize
19338 ** was the size of the journal file when this statement was started, so
19339 ** everything after that needs to be rolled back, either into the
19340 ** database, the memory cache, or both.
19342 ** If it is not zero, then Pager.stmtHdrOff is the offset to the start
19343 ** of the first journal header written during this statement transaction.
19345 rc = sqlite3OsSeek(pPager->jfd, pPager->stmtJSize);
19346 if( rc!=SQLITE_OK ){
19347 goto end_stmt_playback;
19349 pPager->journalOff = pPager->stmtJSize;
19350 pPager->cksumInit = pPager->stmtCksum;
19351 while( pPager->journalOff < hdrOff ){
19352 rc = pager_playback_one_page(pPager, pPager->jfd, 1);
19353 assert( rc!=SQLITE_DONE );
19354 if( rc!=SQLITE_OK ) goto end_stmt_playback;
19357 while( pPager->journalOff < szJ ){
19358 u32 nJRec; /* Number of Journal Records */
19359 u32 dummy;
19360 rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
19361 if( rc!=SQLITE_OK ){
19362 assert( rc!=SQLITE_DONE );
19363 goto end_stmt_playback;
19365 if( nJRec==0 ){
19366 nJRec = (szJ - pPager->journalOff) / (pPager->pageSize+8);
19368 for(i=nJRec-1; i>=0 && pPager->journalOff < szJ; i--){
19369 rc = pager_playback_one_page(pPager, pPager->jfd, 1);
19370 assert( rc!=SQLITE_DONE );
19371 if( rc!=SQLITE_OK ) goto end_stmt_playback;
19375 pPager->journalOff = szJ;
19377 end_stmt_playback:
19378 if( rc==SQLITE_OK) {
19379 pPager->journalOff = szJ;
19380 /* pager_reload_cache(pPager); */
19382 return rc;
19386 ** Change the maximum number of in-memory pages that are allowed.
19388 static void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
19389 if( mxPage>10 ){
19390 pPager->mxPage = mxPage;
19391 }else{
19392 pPager->mxPage = 10;
19397 ** Adjust the robustness of the database to damage due to OS crashes
19398 ** or power failures by changing the number of syncs()s when writing
19399 ** the rollback journal. There are three levels:
19401 ** OFF sqlite3OsSync() is never called. This is the default
19402 ** for temporary and transient files.
19404 ** NORMAL The journal is synced once before writes begin on the
19405 ** database. This is normally adequate protection, but
19406 ** it is theoretically possible, though very unlikely,
19407 ** that an inopertune power failure could leave the journal
19408 ** in a state which would cause damage to the database
19409 ** when it is rolled back.
19411 ** FULL The journal is synced twice before writes begin on the
19412 ** database (with some additional information - the nRec field
19413 ** of the journal header - being written in between the two
19414 ** syncs). If we assume that writing a
19415 ** single disk sector is atomic, then this mode provides
19416 ** assurance that the journal will not be corrupted to the
19417 ** point of causing damage to the database during rollback.
19419 ** Numeric values associated with these states are OFF==1, NORMAL=2,
19420 ** and FULL=3.
19422 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
19423 static void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int full_fsync){
19424 pPager->noSync = level==1 || pPager->tempFile;
19425 pPager->fullSync = level==3 && !pPager->tempFile;
19426 pPager->full_fsync = full_fsync;
19427 if( pPager->noSync ) pPager->needSync = 0;
19429 #endif
19432 ** The following global variable is incremented whenever the library
19433 ** attempts to open a temporary file. This information is used for
19434 ** testing and analysis only.
19436 #ifdef SQLITE_TEST
19437 int sqlite3_opentemp_count = 0;
19438 #endif
19441 ** Open a temporary file.
19443 ** Write the file descriptor into *fd. Return SQLITE_OK on success or some
19444 ** other error code if we fail.
19446 ** The OS will automatically delete the temporary file when it is
19447 ** closed.
19449 static int sqlite3PagerOpentemp(OsFile **pFd){
19450 int cnt = 8;
19451 int rc;
19452 char zFile[SQLITE_TEMPNAME_SIZE];
19454 #ifdef SQLITE_TEST
19455 sqlite3_opentemp_count++; /* Used for testing and analysis only */
19456 #endif
19458 cnt--;
19459 sqlite3OsTempFileName(zFile);
19460 rc = sqlite3OsOpenExclusive(zFile, pFd, 1);
19461 assert( rc!=SQLITE_OK || *pFd );
19462 }while( cnt>0 && rc!=SQLITE_OK && rc!=SQLITE_NOMEM );
19463 return rc;
19467 ** Create a new page cache and put a pointer to the page cache in *ppPager.
19468 ** The file to be cached need not exist. The file is not locked until
19469 ** the first call to sqlite3PagerGet() and is only held open until the
19470 ** last page is released using sqlite3PagerUnref().
19472 ** If zFilename is NULL then a randomly-named temporary file is created
19473 ** and used as the file to be cached. The file will be deleted
19474 ** automatically when it is closed.
19476 ** If zFilename is ":memory:" then all information is held in cache.
19477 ** It is never written to disk. This can be used to implement an
19478 ** in-memory database.
19480 static int sqlite3PagerOpen(
19481 Pager **ppPager, /* Return the Pager structure here */
19482 const char *zFilename, /* Name of the database file to open */
19483 int nExtra, /* Extra bytes append to each in-memory page */
19484 int flags /* flags controlling this file */
19486 Pager *pPager = 0;
19487 char *zFullPathname = 0;
19488 int nameLen; /* Compiler is wrong. This is always initialized before use */
19489 OsFile *fd = 0;
19490 int rc = SQLITE_OK;
19491 int i;
19492 int tempFile = 0;
19493 int memDb = 0;
19494 int readOnly = 0;
19495 int useJournal = (flags & PAGER_OMIT_JOURNAL)==0;
19496 int noReadlock = (flags & PAGER_NO_READLOCK)!=0;
19497 char zTemp[SQLITE_TEMPNAME_SIZE];
19498 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
19499 /* A malloc() cannot fail in sqlite3ThreadData() as one or more calls to
19500 ** malloc() must have already been made by this thread before it gets
19501 ** to this point. This means the ThreadData must have been allocated already
19502 ** so that ThreadData.nAlloc can be set. It would be nice to assert
19503 ** that ThreadData.nAlloc is non-zero, but alas this breaks test cases
19504 ** written to invoke the pager directly.
19506 ThreadData *pTsd = sqlite3ThreadData();
19507 assert( pTsd );
19508 #endif
19510 /* We used to test if malloc() had already failed before proceeding.
19511 ** But the way this function is used in SQLite means that can never
19512 ** happen. Furthermore, if the malloc-failed flag is already set,
19513 ** either the call to sqliteStrDup() or sqliteMalloc() below will
19514 ** fail shortly and SQLITE_NOMEM returned anyway.
19516 *ppPager = 0;
19518 /* Open the pager file and set zFullPathname to point at malloc()ed
19519 ** memory containing the complete filename (i.e. including the directory).
19521 if( zFilename && zFilename[0] ){
19522 #ifndef SQLITE_OMIT_MEMORYDB
19523 if( strcmp(zFilename,":memory:")==0 ){
19524 memDb = 1;
19525 zFullPathname = sqliteStrDup("");
19526 }else
19527 #endif
19529 zFullPathname = sqlite3OsFullPathname(zFilename);
19530 if( zFullPathname ){
19531 rc = sqlite3OsOpenReadWrite(zFullPathname, &fd, &readOnly);
19532 assert( rc!=SQLITE_OK || fd );
19535 }else{
19536 rc = sqlite3PagerOpentemp(&fd);
19537 sqlite3OsTempFileName(zTemp);
19538 zFilename = zTemp;
19539 zFullPathname = sqlite3OsFullPathname(zFilename);
19540 if( rc==SQLITE_OK ){
19541 tempFile = 1;
19545 /* Allocate the Pager structure. As part of the same allocation, allocate
19546 ** space for the full paths of the file, directory and journal
19547 ** (Pager.zFilename, Pager.zDirectory and Pager.zJournal).
19549 if( zFullPathname ){
19550 nameLen = strlen(zFullPathname);
19551 pPager = sqliteMalloc( sizeof(*pPager) + nameLen*3 + 30 );
19552 if( pPager && rc==SQLITE_OK ){
19553 pPager->pTmpSpace = (char *)sqliteMallocRaw(SQLITE_DEFAULT_PAGE_SIZE);
19558 /* If an error occured in either of the blocks above, free the memory
19559 ** pointed to by zFullPathname, free the Pager structure and close the
19560 ** file. Since the pager is not allocated there is no need to set
19561 ** any Pager.errMask variables.
19563 if( !pPager || !zFullPathname || !pPager->pTmpSpace || rc!=SQLITE_OK ){
19564 sqlite3OsClose(&fd);
19565 sqliteFree(zFullPathname);
19566 sqliteFree(pPager);
19567 return ((rc==SQLITE_OK)?SQLITE_NOMEM:rc);
19570 PAGERTRACE3("OPEN %d %s\n", FILEHANDLEID(fd), zFullPathname);
19571 IOTRACE(("OPEN %p %s\n", pPager, zFullPathname))
19572 pPager->zFilename = (char*)&pPager[1];
19573 pPager->zDirectory = &pPager->zFilename[nameLen+1];
19574 pPager->zJournal = &pPager->zDirectory[nameLen+1];
19575 memcpy(pPager->zFilename, zFullPathname, nameLen+1);
19576 memcpy(pPager->zDirectory, zFullPathname, nameLen+1);
19578 for(i=nameLen; i>0 && pPager->zDirectory[i-1]!='/'; i--){}
19579 if( i>0 ) pPager->zDirectory[i-1] = 0;
19580 memcpy(pPager->zJournal, zFullPathname,nameLen);
19581 sqliteFree(zFullPathname);
19582 memcpy(&pPager->zJournal[nameLen], "-journal",sizeof("-journal"));
19583 pPager->fd = fd;
19584 /* pPager->journalOpen = 0; */
19585 pPager->useJournal = useJournal && !memDb;
19586 pPager->noReadlock = noReadlock && readOnly;
19587 /* pPager->stmtOpen = 0; */
19588 /* pPager->stmtInUse = 0; */
19589 /* pPager->nRef = 0; */
19590 pPager->dbSize = memDb-1;
19591 pPager->pageSize = SQLITE_DEFAULT_PAGE_SIZE;
19592 /* pPager->stmtSize = 0; */
19593 /* pPager->stmtJSize = 0; */
19594 /* pPager->nPage = 0; */
19595 pPager->mxPage = 100;
19596 pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
19597 assert( PAGER_UNLOCK==0 );
19598 /* pPager->state = PAGER_UNLOCK; */
19599 /* pPager->errMask = 0; */
19600 pPager->tempFile = tempFile;
19601 assert( tempFile==PAGER_LOCKINGMODE_NORMAL
19602 || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
19603 assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
19604 pPager->exclusiveMode = tempFile;
19605 pPager->memDb = memDb;
19606 pPager->readOnly = readOnly;
19607 /* pPager->needSync = 0; */
19608 pPager->noSync = pPager->tempFile || !useJournal;
19609 pPager->fullSync = (pPager->noSync?0:1);
19610 /* pPager->pFirst = 0; */
19611 /* pPager->pFirstSynced = 0; */
19612 /* pPager->pLast = 0; */
19613 pPager->nExtra = FORCE_ALIGNMENT(nExtra);
19614 assert(fd||memDb);
19615 if( !memDb ){
19616 setSectorSize(pPager);
19618 /* pPager->pBusyHandler = 0; */
19619 /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
19620 *ppPager = pPager;
19621 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
19622 pPager->pNext = pTsd->pPager;
19623 pTsd->pPager = pPager;
19624 #endif
19625 return SQLITE_OK;
19629 ** Set the busy handler function.
19631 static void sqlite3PagerSetBusyhandler(Pager *pPager, BusyHandler *pBusyHandler){
19632 pPager->pBusyHandler = pBusyHandler;
19636 ** Set the destructor for this pager. If not NULL, the destructor is called
19637 ** when the reference count on each page reaches zero. The destructor can
19638 ** be used to clean up information in the extra segment appended to each page.
19640 ** The destructor is not called as a result sqlite3PagerClose().
19641 ** Destructors are only called by sqlite3PagerUnref().
19643 static void sqlite3PagerSetDestructor(Pager *pPager, void (*xDesc)(DbPage*,int)){
19644 pPager->xDestructor = xDesc;
19648 ** Set the reinitializer for this pager. If not NULL, the reinitializer
19649 ** is called when the content of a page in cache is restored to its original
19650 ** value as a result of a rollback. The callback gives higher-level code
19651 ** an opportunity to restore the EXTRA section to agree with the restored
19652 ** page data.
19654 static void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*,int)){
19655 pPager->xReiniter = xReinit;
19659 ** Set the page size. Return the new size. If the suggest new page
19660 ** size is inappropriate, then an alternative page size is selected
19661 ** and returned.
19663 static int sqlite3PagerSetPagesize(Pager *pPager, int pageSize){
19664 assert( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE );
19665 if( !pPager->memDb && pPager->nRef==0 ){
19666 pager_reset(pPager);
19667 pPager->pageSize = pageSize;
19668 pPager->pTmpSpace = sqlite3ReallocOrFree(pPager->pTmpSpace, pageSize);
19670 return pPager->pageSize;
19674 ** Attempt to set the maximum database page count if mxPage is positive.
19675 ** Make no changes if mxPage is zero or negative. And never reduce the
19676 ** maximum page count below the current size of the database.
19678 ** Regardless of mxPage, return the current maximum page count.
19680 static int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
19681 if( mxPage>0 ){
19682 pPager->mxPgno = mxPage;
19684 sqlite3PagerPagecount(pPager);
19685 return pPager->mxPgno;
19689 ** The following set of routines are used to disable the simulated
19690 ** I/O error mechanism. These routines are used to avoid simulated
19691 ** errors in places where we do not care about errors.
19693 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
19694 ** and generate no code.
19696 #ifdef SQLITE_TEST
19697 extern int sqlite3_io_error_pending;
19698 extern int sqlite3_io_error_hit;
19699 static int saved_cnt;
19700 void disable_simulated_io_errors(void){
19701 saved_cnt = sqlite3_io_error_pending;
19702 sqlite3_io_error_pending = -1;
19704 void enable_simulated_io_errors(void){
19705 sqlite3_io_error_pending = saved_cnt;
19707 #else
19708 # define disable_simulated_io_errors()
19709 # define enable_simulated_io_errors()
19710 #endif
19713 ** Read the first N bytes from the beginning of the file into memory
19714 ** that pDest points to.
19716 ** No error checking is done. The rational for this is that this function
19717 ** may be called even if the file does not exist or contain a header. In
19718 ** these cases sqlite3OsRead() will return an error, to which the correct
19719 ** response is to zero the memory at pDest and continue. A real IO error
19720 ** will presumably recur and be picked up later (Todo: Think about this).
19722 static int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
19723 int rc = SQLITE_OK;
19724 memset(pDest, 0, N);
19725 if( MEMDB==0 ){
19726 disable_simulated_io_errors();
19727 sqlite3OsSeek(pPager->fd, 0);
19728 enable_simulated_io_errors();
19729 IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
19730 rc = sqlite3OsRead(pPager->fd, pDest, N);
19731 if( rc==SQLITE_IOERR_SHORT_READ ){
19732 rc = SQLITE_OK;
19735 return rc;
19739 ** Return the total number of pages in the disk file associated with
19740 ** pPager.
19742 ** If the PENDING_BYTE lies on the page directly after the end of the
19743 ** file, then consider this page part of the file too. For example, if
19744 ** PENDING_BYTE is byte 4096 (the first byte of page 5) and the size of the
19745 ** file is 4096 bytes, 5 is returned instead of 4.
19747 static int sqlite3PagerPagecount(Pager *pPager){
19748 i64 n;
19749 int rc;
19750 assert( pPager!=0 );
19751 if( pPager->errCode ){
19752 return 0;
19754 if( pPager->dbSize>=0 ){
19755 n = pPager->dbSize;
19756 } else {
19757 if( (rc = sqlite3OsFileSize(pPager->fd, &n))!=SQLITE_OK ){
19758 pager_error(pPager, rc);
19759 return 0;
19761 if( n>0 && n<pPager->pageSize ){
19762 n = 1;
19763 }else{
19764 n /= pPager->pageSize;
19766 if( pPager->state!=PAGER_UNLOCK ){
19767 pPager->dbSize = n;
19770 if( n==(PENDING_BYTE/pPager->pageSize) ){
19771 n++;
19773 if( n>pPager->mxPgno ){
19774 pPager->mxPgno = n;
19776 return n;
19780 #ifndef SQLITE_OMIT_MEMORYDB
19782 ** Clear a PgHistory block
19784 static void clearHistory(PgHistory *pHist){
19785 sqliteFree(pHist->pOrig);
19786 sqliteFree(pHist->pStmt);
19787 pHist->pOrig = 0;
19788 pHist->pStmt = 0;
19790 #else
19791 #define clearHistory(x)
19792 #endif
19795 ** Forward declaration
19797 static int syncJournal(Pager*);
19800 ** Unlink pPg from it's hash chain. Also set the page number to 0 to indicate
19801 ** that the page is not part of any hash chain. This is required because the
19802 ** sqlite3PagerMovepage() routine can leave a page in the
19803 ** pNextFree/pPrevFree list that is not a part of any hash-chain.
19805 static void unlinkHashChain(Pager *pPager, PgHdr *pPg){
19806 if( pPg->pgno==0 ){
19807 assert( pPg->pNextHash==0 && pPg->pPrevHash==0 );
19808 return;
19810 if( pPg->pNextHash ){
19811 pPg->pNextHash->pPrevHash = pPg->pPrevHash;
19813 if( pPg->pPrevHash ){
19814 assert( pPager->aHash[pPg->pgno & (pPager->nHash-1)]!=pPg );
19815 pPg->pPrevHash->pNextHash = pPg->pNextHash;
19816 }else{
19817 int h = pPg->pgno & (pPager->nHash-1);
19818 pPager->aHash[h] = pPg->pNextHash;
19820 if( MEMDB ){
19821 clearHistory(PGHDR_TO_HIST(pPg, pPager));
19823 pPg->pgno = 0;
19824 pPg->pNextHash = pPg->pPrevHash = 0;
19828 ** Unlink a page from the free list (the list of all pages where nRef==0)
19829 ** and from its hash collision chain.
19831 static void unlinkPage(PgHdr *pPg){
19832 Pager *pPager = pPg->pPager;
19834 /* Keep the pFirstSynced pointer pointing at the first synchronized page */
19835 if( pPg==pPager->pFirstSynced ){
19836 PgHdr *p = pPg->pNextFree;
19837 while( p && p->needSync ){ p = p->pNextFree; }
19838 pPager->pFirstSynced = p;
19841 /* Unlink from the freelist */
19842 if( pPg->pPrevFree ){
19843 pPg->pPrevFree->pNextFree = pPg->pNextFree;
19844 }else{
19845 assert( pPager->pFirst==pPg );
19846 pPager->pFirst = pPg->pNextFree;
19848 if( pPg->pNextFree ){
19849 pPg->pNextFree->pPrevFree = pPg->pPrevFree;
19850 }else{
19851 assert( pPager->pLast==pPg );
19852 pPager->pLast = pPg->pPrevFree;
19854 pPg->pNextFree = pPg->pPrevFree = 0;
19856 /* Unlink from the pgno hash table */
19857 unlinkHashChain(pPager, pPg);
19861 ** This routine is used to truncate the cache when a database
19862 ** is truncated. Drop from the cache all pages whose pgno is
19863 ** larger than pPager->dbSize and is unreferenced.
19865 ** Referenced pages larger than pPager->dbSize are zeroed.
19867 ** Actually, at the point this routine is called, it would be
19868 ** an error to have a referenced page. But rather than delete
19869 ** that page and guarantee a subsequent segfault, it seems better
19870 ** to zero it and hope that we error out sanely.
19872 static void pager_truncate_cache(Pager *pPager){
19873 PgHdr *pPg;
19874 PgHdr **ppPg;
19875 int dbSize = pPager->dbSize;
19877 ppPg = &pPager->pAll;
19878 while( (pPg = *ppPg)!=0 ){
19879 if( pPg->pgno<=dbSize ){
19880 ppPg = &pPg->pNextAll;
19881 }else if( pPg->nRef>0 ){
19882 memset(PGHDR_TO_DATA(pPg), 0, pPager->pageSize);
19883 ppPg = &pPg->pNextAll;
19884 }else{
19885 *ppPg = pPg->pNextAll;
19886 IOTRACE(("PGFREE %p %d\n", pPager, pPg->pgno));
19887 PAGER_INCR(sqlite3_pager_pgfree_count);
19888 unlinkPage(pPg);
19889 makeClean(pPg);
19890 sqliteFree(pPg);
19891 pPager->nPage--;
19897 ** Try to obtain a lock on a file. Invoke the busy callback if the lock
19898 ** is currently not available. Repeat until the busy callback returns
19899 ** false or until the lock succeeds.
19901 ** Return SQLITE_OK on success and an error code if we cannot obtain
19902 ** the lock.
19904 static int pager_wait_on_lock(Pager *pPager, int locktype){
19905 int rc;
19907 /* The OS lock values must be the same as the Pager lock values */
19908 assert( PAGER_SHARED==SHARED_LOCK );
19909 assert( PAGER_RESERVED==RESERVED_LOCK );
19910 assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
19912 /* If the file is currently unlocked then the size must be unknown */
19913 assert( pPager->state>=PAGER_SHARED || pPager->dbSize<0 || MEMDB );
19915 if( pPager->state>=locktype ){
19916 rc = SQLITE_OK;
19917 }else{
19918 do {
19919 rc = sqlite3OsLock(pPager->fd, locktype);
19920 }while( rc==SQLITE_BUSY && sqlite3InvokeBusyHandler(pPager->pBusyHandler) );
19921 if( rc==SQLITE_OK ){
19922 pPager->state = locktype;
19923 IOTRACE(("LOCK %p %d\n", pPager, locktype))
19926 return rc;
19930 ** Truncate the file to the number of pages specified.
19932 static int sqlite3PagerTruncate(Pager *pPager, Pgno nPage){
19933 int rc;
19934 assert( pPager->state>=PAGER_SHARED || MEMDB );
19935 sqlite3PagerPagecount(pPager);
19936 if( pPager->errCode ){
19937 rc = pPager->errCode;
19938 return rc;
19940 if( nPage>=(unsigned)pPager->dbSize ){
19941 return SQLITE_OK;
19943 if( MEMDB ){
19944 pPager->dbSize = nPage;
19945 pager_truncate_cache(pPager);
19946 return SQLITE_OK;
19948 rc = syncJournal(pPager);
19949 if( rc!=SQLITE_OK ){
19950 return rc;
19953 /* Get an exclusive lock on the database before truncating. */
19954 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
19955 if( rc!=SQLITE_OK ){
19956 return rc;
19959 rc = pager_truncate(pPager, nPage);
19960 return rc;
19964 ** Shutdown the page cache. Free all memory and close all files.
19966 ** If a transaction was in progress when this routine is called, that
19967 ** transaction is rolled back. All outstanding pages are invalidated
19968 ** and their memory is freed. Any attempt to use a page associated
19969 ** with this page cache after this function returns will likely
19970 ** result in a coredump.
19972 ** This function always succeeds. If a transaction is active an attempt
19973 ** is made to roll it back. If an error occurs during the rollback
19974 ** a hot journal may be left in the filesystem but no error is returned
19975 ** to the caller.
19977 static int sqlite3PagerClose(Pager *pPager){
19978 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
19979 /* A malloc() cannot fail in sqlite3ThreadData() as one or more calls to
19980 ** malloc() must have already been made by this thread before it gets
19981 ** to this point. This means the ThreadData must have been allocated already
19982 ** so that ThreadData.nAlloc can be set.
19984 ThreadData *pTsd = sqlite3ThreadData();
19985 assert( pPager );
19986 assert( pTsd && pTsd->nAlloc );
19987 #endif
19989 disable_simulated_io_errors();
19990 pPager->errCode = 0;
19991 pPager->exclusiveMode = 0;
19992 pager_reset(pPager);
19993 pagerUnlockAndRollback(pPager);
19994 enable_simulated_io_errors();
19995 PAGERTRACE2("CLOSE %d\n", PAGERID(pPager));
19996 IOTRACE(("CLOSE %p\n", pPager))
19997 assert( pPager->errCode || (pPager->journalOpen==0 && pPager->stmtOpen==0) );
19998 if( pPager->journalOpen ){
19999 sqlite3OsClose(&pPager->jfd);
20001 sqliteFree(pPager->aInJournal);
20002 if( pPager->stmtOpen ){
20003 sqlite3OsClose(&pPager->stfd);
20005 sqlite3OsClose(&pPager->fd);
20006 /* Temp files are automatically deleted by the OS
20007 ** if( pPager->tempFile ){
20008 ** sqlite3OsDelete(pPager->zFilename);
20009 ** }
20012 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20013 /* Remove the pager from the linked list of pagers starting at
20014 ** ThreadData.pPager if memory-management is enabled.
20016 if( pPager==pTsd->pPager ){
20017 pTsd->pPager = pPager->pNext;
20018 }else{
20019 Pager *pTmp;
20020 for(pTmp = pTsd->pPager; pTmp->pNext!=pPager; pTmp=pTmp->pNext){}
20021 pTmp->pNext = pPager->pNext;
20023 #endif
20024 sqliteFree(pPager->aHash);
20025 sqliteFree(pPager->pTmpSpace);
20026 sqliteFree(pPager);
20027 return SQLITE_OK;
20030 #if !defined(NDEBUG) || defined(SQLITE_TEST)
20032 ** Return the page number for the given page data.
20034 static Pgno sqlite3PagerPagenumber(DbPage *p){
20035 return p->pgno;
20037 #endif
20040 ** The page_ref() function increments the reference count for a page.
20041 ** If the page is currently on the freelist (the reference count is zero) then
20042 ** remove it from the freelist.
20044 ** For non-test systems, page_ref() is a macro that calls _page_ref()
20045 ** online of the reference count is zero. For test systems, page_ref()
20046 ** is a real function so that we can set breakpoints and trace it.
20048 static void _page_ref(PgHdr *pPg){
20049 if( pPg->nRef==0 ){
20050 /* The page is currently on the freelist. Remove it. */
20051 if( pPg==pPg->pPager->pFirstSynced ){
20052 PgHdr *p = pPg->pNextFree;
20053 while( p && p->needSync ){ p = p->pNextFree; }
20054 pPg->pPager->pFirstSynced = p;
20056 if( pPg->pPrevFree ){
20057 pPg->pPrevFree->pNextFree = pPg->pNextFree;
20058 }else{
20059 pPg->pPager->pFirst = pPg->pNextFree;
20061 if( pPg->pNextFree ){
20062 pPg->pNextFree->pPrevFree = pPg->pPrevFree;
20063 }else{
20064 pPg->pPager->pLast = pPg->pPrevFree;
20066 pPg->pPager->nRef++;
20068 pPg->nRef++;
20069 REFINFO(pPg);
20071 #ifdef SQLITE_DEBUG
20072 static void page_ref(PgHdr *pPg){
20073 if( pPg->nRef==0 ){
20074 _page_ref(pPg);
20075 }else{
20076 pPg->nRef++;
20077 REFINFO(pPg);
20080 #else
20081 # define page_ref(P) ((P)->nRef==0?_page_ref(P):(void)(P)->nRef++)
20082 #endif
20085 ** Increment the reference count for a page. The input pointer is
20086 ** a reference to the page data.
20088 static int sqlite3PagerRef(DbPage *pPg){
20089 page_ref(pPg);
20090 return SQLITE_OK;
20094 ** Sync the journal. In other words, make sure all the pages that have
20095 ** been written to the journal have actually reached the surface of the
20096 ** disk. It is not safe to modify the original database file until after
20097 ** the journal has been synced. If the original database is modified before
20098 ** the journal is synced and a power failure occurs, the unsynced journal
20099 ** data would be lost and we would be unable to completely rollback the
20100 ** database changes. Database corruption would occur.
20102 ** This routine also updates the nRec field in the header of the journal.
20103 ** (See comments on the pager_playback() routine for additional information.)
20104 ** If the sync mode is FULL, two syncs will occur. First the whole journal
20105 ** is synced, then the nRec field is updated, then a second sync occurs.
20107 ** For temporary databases, we do not care if we are able to rollback
20108 ** after a power failure, so sync occurs.
20110 ** This routine clears the needSync field of every page current held in
20111 ** memory.
20113 static int syncJournal(Pager *pPager){
20114 PgHdr *pPg;
20115 int rc = SQLITE_OK;
20117 /* Sync the journal before modifying the main database
20118 ** (assuming there is a journal and it needs to be synced.)
20120 if( pPager->needSync ){
20121 if( !pPager->tempFile ){
20122 assert( pPager->journalOpen );
20123 /* assert( !pPager->noSync ); // noSync might be set if synchronous
20124 ** was turned off after the transaction was started. Ticket #615 */
20125 #ifndef NDEBUG
20127 /* Make sure the pPager->nRec counter we are keeping agrees
20128 ** with the nRec computed from the size of the journal file.
20130 i64 jSz;
20131 rc = sqlite3OsFileSize(pPager->jfd, &jSz);
20132 if( rc!=0 ) return rc;
20133 assert( pPager->journalOff==jSz );
20135 #endif
20137 /* Write the nRec value into the journal file header. If in
20138 ** full-synchronous mode, sync the journal first. This ensures that
20139 ** all data has really hit the disk before nRec is updated to mark
20140 ** it as a candidate for rollback.
20142 if( pPager->fullSync ){
20143 PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
20144 IOTRACE(("JSYNC %p\n", pPager))
20145 rc = sqlite3OsSync(pPager->jfd, 0);
20146 if( rc!=0 ) return rc;
20148 rc = sqlite3OsSeek(pPager->jfd,
20149 pPager->journalHdr + sizeof(aJournalMagic));
20150 if( rc ) return rc;
20151 IOTRACE(("JHDR %p %lld %d\n", pPager,
20152 pPager->journalHdr + sizeof(aJournalMagic), 4))
20153 rc = write32bits(pPager->jfd, pPager->nRec);
20154 if( rc ) return rc;
20156 rc = sqlite3OsSeek(pPager->jfd, pPager->journalOff);
20157 if( rc ) return rc;
20159 PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
20160 IOTRACE(("JSYNC %p\n", pPager))
20161 rc = sqlite3OsSync(pPager->jfd, pPager->full_fsync);
20162 if( rc!=0 ) return rc;
20163 pPager->journalStarted = 1;
20165 pPager->needSync = 0;
20167 /* Erase the needSync flag from every page.
20169 for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
20170 pPg->needSync = 0;
20172 pPager->pFirstSynced = pPager->pFirst;
20175 #ifndef NDEBUG
20176 /* If the Pager.needSync flag is clear then the PgHdr.needSync
20177 ** flag must also be clear for all pages. Verify that this
20178 ** invariant is true.
20180 else{
20181 for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
20182 assert( pPg->needSync==0 );
20184 assert( pPager->pFirstSynced==pPager->pFirst );
20186 #endif
20188 return rc;
20192 ** Merge two lists of pages connected by pDirty and in pgno order.
20193 ** Do not both fixing the pPrevDirty pointers.
20195 static PgHdr *merge_pagelist(PgHdr *pA, PgHdr *pB){
20196 PgHdr result, *pTail;
20197 pTail = &result;
20198 while( pA && pB ){
20199 if( pA->pgno<pB->pgno ){
20200 pTail->pDirty = pA;
20201 pTail = pA;
20202 pA = pA->pDirty;
20203 }else{
20204 pTail->pDirty = pB;
20205 pTail = pB;
20206 pB = pB->pDirty;
20209 if( pA ){
20210 pTail->pDirty = pA;
20211 }else if( pB ){
20212 pTail->pDirty = pB;
20213 }else{
20214 pTail->pDirty = 0;
20216 return result.pDirty;
20220 ** Sort the list of pages in accending order by pgno. Pages are
20221 ** connected by pDirty pointers. The pPrevDirty pointers are
20222 ** corrupted by this sort.
20224 #define N_SORT_BUCKET_ALLOC 25
20225 #define N_SORT_BUCKET 25
20226 #ifdef SQLITE_TEST
20227 int sqlite3_pager_n_sort_bucket = 0;
20228 #undef N_SORT_BUCKET
20229 #define N_SORT_BUCKET \
20230 (sqlite3_pager_n_sort_bucket?sqlite3_pager_n_sort_bucket:N_SORT_BUCKET_ALLOC)
20231 #endif
20232 static PgHdr *sort_pagelist(PgHdr *pIn){
20233 PgHdr *a[N_SORT_BUCKET_ALLOC], *p;
20234 int i;
20235 memset(a, 0, sizeof(a));
20236 while( pIn ){
20237 p = pIn;
20238 pIn = p->pDirty;
20239 p->pDirty = 0;
20240 for(i=0; i<N_SORT_BUCKET-1; i++){
20241 if( a[i]==0 ){
20242 a[i] = p;
20243 break;
20244 }else{
20245 p = merge_pagelist(a[i], p);
20246 a[i] = 0;
20249 if( i==N_SORT_BUCKET-1 ){
20250 /* Coverage: To get here, there need to be 2^(N_SORT_BUCKET)
20251 ** elements in the input list. This is possible, but impractical.
20252 ** Testing this line is the point of global variable
20253 ** sqlite3_pager_n_sort_bucket.
20255 a[i] = merge_pagelist(a[i], p);
20258 p = a[0];
20259 for(i=1; i<N_SORT_BUCKET; i++){
20260 p = merge_pagelist(p, a[i]);
20262 return p;
20266 ** Given a list of pages (connected by the PgHdr.pDirty pointer) write
20267 ** every one of those pages out to the database file and mark them all
20268 ** as clean.
20270 static int pager_write_pagelist(PgHdr *pList){
20271 Pager *pPager;
20272 int rc;
20274 if( pList==0 ) return SQLITE_OK;
20275 pPager = pList->pPager;
20277 /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
20278 ** database file. If there is already an EXCLUSIVE lock, the following
20279 ** calls to sqlite3OsLock() are no-ops.
20281 ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
20282 ** through an intermediate state PENDING. A PENDING lock prevents new
20283 ** readers from attaching to the database but is unsufficient for us to
20284 ** write. The idea of a PENDING lock is to prevent new readers from
20285 ** coming in while we wait for existing readers to clear.
20287 ** While the pager is in the RESERVED state, the original database file
20288 ** is unchanged and we can rollback without having to playback the
20289 ** journal into the original database file. Once we transition to
20290 ** EXCLUSIVE, it means the database file has been changed and any rollback
20291 ** will require a journal playback.
20293 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
20294 if( rc!=SQLITE_OK ){
20295 return rc;
20298 pList = sort_pagelist(pList);
20299 while( pList ){
20300 assert( pList->dirty );
20301 rc = sqlite3OsSeek(pPager->fd, (pList->pgno-1)*(i64)pPager->pageSize);
20302 if( rc ) return rc;
20303 /* If there are dirty pages in the page cache with page numbers greater
20304 ** than Pager.dbSize, this means sqlite3PagerTruncate() was called to
20305 ** make the file smaller (presumably by auto-vacuum code). Do not write
20306 ** any such pages to the file.
20308 if( pList->pgno<=pPager->dbSize ){
20309 char *pData = CODEC2(pPager, PGHDR_TO_DATA(pList), pList->pgno, 6);
20310 PAGERTRACE4("STORE %d page %d hash(%08x)\n",
20311 PAGERID(pPager), pList->pgno, pager_pagehash(pList));
20312 IOTRACE(("PGOUT %p %d\n", pPager, pList->pgno));
20313 rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize);
20314 PAGER_INCR(sqlite3_pager_writedb_count);
20315 PAGER_INCR(pPager->nWrite);
20316 if( pList->pgno==1 ){
20317 memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
20320 #ifndef NDEBUG
20321 else{
20322 PAGERTRACE3("NOSTORE %d page %d\n", PAGERID(pPager), pList->pgno);
20324 #endif
20325 if( rc ) return rc;
20326 pList->dirty = 0;
20327 #ifdef SQLITE_CHECK_PAGES
20328 pList->pageHash = pager_pagehash(pList);
20329 #endif
20330 pList = pList->pDirty;
20332 return SQLITE_OK;
20336 ** Collect every dirty page into a dirty list and
20337 ** return a pointer to the head of that list. All pages are
20338 ** collected even if they are still in use.
20340 static PgHdr *pager_get_all_dirty_pages(Pager *pPager){
20341 return pPager->pDirty;
20345 ** Return TRUE if there is a hot journal on the given pager.
20346 ** A hot journal is one that needs to be played back.
20348 ** If the current size of the database file is 0 but a journal file
20349 ** exists, that is probably an old journal left over from a prior
20350 ** database with the same name. Just delete the journal.
20352 static int hasHotJournal(Pager *pPager){
20353 if( !pPager->useJournal ) return 0;
20354 if( !sqlite3OsFileExists(pPager->zJournal) ){
20355 return 0;
20357 if( sqlite3OsCheckReservedLock(pPager->fd) ){
20358 return 0;
20360 if( sqlite3PagerPagecount(pPager)==0 ){
20361 sqlite3OsDelete(pPager->zJournal);
20362 return 0;
20363 }else{
20364 return 1;
20369 ** Try to find a page in the cache that can be recycled.
20371 ** This routine may return SQLITE_IOERR, SQLITE_FULL or SQLITE_OK. It
20372 ** does not set the pPager->errCode variable.
20374 static int pager_recycle(Pager *pPager, int syncOk, PgHdr **ppPg){
20375 PgHdr *pPg;
20376 *ppPg = 0;
20378 assert(!MEMDB);
20380 /* Find a page to recycle. Try to locate a page that does not
20381 ** require us to do an fsync() on the journal.
20383 pPg = pPager->pFirstSynced;
20385 /* If we could not find a page that does not require an fsync()
20386 ** on the journal file then fsync the journal file. This is a
20387 ** very slow operation, so we work hard to avoid it. But sometimes
20388 ** it can't be helped.
20390 if( pPg==0 && pPager->pFirst && syncOk && !MEMDB){
20391 int rc = syncJournal(pPager);
20392 if( rc!=0 ){
20393 return rc;
20395 if( pPager->fullSync ){
20396 /* If in full-sync mode, write a new journal header into the
20397 ** journal file. This is done to avoid ever modifying a journal
20398 ** header that is involved in the rollback of pages that have
20399 ** already been written to the database (in case the header is
20400 ** trashed when the nRec field is updated).
20402 pPager->nRec = 0;
20403 assert( pPager->journalOff > 0 );
20404 assert( pPager->doNotSync==0 );
20405 rc = writeJournalHdr(pPager);
20406 if( rc!=0 ){
20407 return rc;
20410 pPg = pPager->pFirst;
20412 if( pPg==0 ){
20413 return SQLITE_OK;
20416 assert( pPg->nRef==0 );
20418 /* Write the page to the database file if it is dirty.
20420 if( pPg->dirty ){
20421 int rc;
20422 assert( pPg->needSync==0 );
20423 makeClean(pPg);
20424 pPg->dirty = 1;
20425 pPg->pDirty = 0;
20426 rc = pager_write_pagelist( pPg );
20427 if( rc!=SQLITE_OK ){
20428 return rc;
20431 assert( pPg->dirty==0 );
20433 /* If the page we are recycling is marked as alwaysRollback, then
20434 ** set the global alwaysRollback flag, thus disabling the
20435 ** sqlite3PagerDontRollback() optimization for the rest of this transaction.
20436 ** It is necessary to do this because the page marked alwaysRollback
20437 ** might be reloaded at a later time but at that point we won't remember
20438 ** that is was marked alwaysRollback. This means that all pages must
20439 ** be marked as alwaysRollback from here on out.
20441 if( pPg->alwaysRollback ){
20442 IOTRACE(("ALWAYS_ROLLBACK %p\n", pPager))
20443 pPager->alwaysRollback = 1;
20446 /* Unlink the old page from the free list and the hash table
20448 unlinkPage(pPg);
20449 assert( pPg->pgno==0 );
20451 *ppPg = pPg;
20452 return SQLITE_OK;
20456 ** This function is called to free superfluous dynamically allocated memory
20457 ** held by the pager system. Memory in use by any SQLite pager allocated
20458 ** by the current thread may be sqliteFree()ed.
20460 ** nReq is the number of bytes of memory required. Once this much has
20461 ** been released, the function returns. A negative value for nReq means
20462 ** free as much memory as possible. The return value is the total number
20463 ** of bytes of memory released.
20465 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
20466 static int sqlite3PagerReleaseMemory(int nReq){
20467 const ThreadData *pTsdro = sqlite3ThreadDataReadOnly();
20468 int nReleased = 0;
20469 int i;
20471 /* If the the global mutex is held, this subroutine becomes a
20472 ** o-op; zero bytes of memory are freed. This is because
20473 ** some of the code invoked by this function may also
20474 ** try to obtain the mutex, resulting in a deadlock.
20476 if( sqlite3OsInMutex(0) ){
20477 return 0;
20480 /* Outermost loop runs for at most two iterations. First iteration we
20481 ** try to find memory that can be released without calling fsync(). Second
20482 ** iteration (which only runs if the first failed to free nReq bytes of
20483 ** memory) is permitted to call fsync(). This is of course much more
20484 ** expensive.
20486 for(i=0; i<=1; i++){
20488 /* Loop through all the SQLite pagers opened by the current thread. */
20489 Pager *pPager = pTsdro->pPager;
20490 for( ; pPager && (nReq<0 || nReleased<nReq); pPager=pPager->pNext){
20491 PgHdr *pPg;
20492 int rc;
20494 if( MEMDB ){
20495 continue;
20498 /* For each pager, try to free as many pages as possible (without
20499 ** calling fsync() if this is the first iteration of the outermost
20500 ** loop).
20502 while( SQLITE_OK==(rc = pager_recycle(pPager, i, &pPg)) && pPg) {
20503 /* We've found a page to free. At this point the page has been
20504 ** removed from the page hash-table, free-list and synced-list
20505 ** (pFirstSynced). It is still in the all pages (pAll) list.
20506 ** Remove it from this list before freeing.
20508 ** Todo: Check the Pager.pStmt list to make sure this is Ok. It
20509 ** probably is though.
20511 PgHdr *pTmp;
20512 assert( pPg );
20513 if( pPg==pPager->pAll ){
20514 pPager->pAll = pPg->pNextAll;
20515 }else{
20516 for( pTmp=pPager->pAll; pTmp->pNextAll!=pPg; pTmp=pTmp->pNextAll ){}
20517 pTmp->pNextAll = pPg->pNextAll;
20519 nReleased += sqliteAllocSize(pPg);
20520 IOTRACE(("PGFREE %p %d\n", pPager, pPg->pgno));
20521 PAGER_INCR(sqlite3_pager_pgfree_count);
20522 sqliteFree(pPg);
20525 if( rc!=SQLITE_OK ){
20526 /* An error occured whilst writing to the database file or
20527 ** journal in pager_recycle(). The error is not returned to the
20528 ** caller of this function. Instead, set the Pager.errCode variable.
20529 ** The error will be returned to the user (or users, in the case
20530 ** of a shared pager cache) of the pager for which the error occured.
20532 assert( (rc&0xff)==SQLITE_IOERR || rc==SQLITE_FULL );
20533 assert( pPager->state>=PAGER_RESERVED );
20534 pager_error(pPager, rc);
20539 return nReleased;
20541 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT && !SQLITE_OMIT_DISKIO */
20544 ** Read the content of page pPg out of the database file.
20546 static int readDbPage(Pager *pPager, PgHdr *pPg, Pgno pgno){
20547 int rc;
20548 assert( MEMDB==0 );
20549 rc = sqlite3OsSeek(pPager->fd, (pgno-1)*(i64)pPager->pageSize);
20550 if( rc==SQLITE_OK ){
20551 rc = sqlite3OsRead(pPager->fd, PGHDR_TO_DATA(pPg),
20552 pPager->pageSize);
20554 PAGER_INCR(sqlite3_pager_readdb_count);
20555 PAGER_INCR(pPager->nRead);
20556 IOTRACE(("PGIN %p %d\n", pPager, pgno));
20557 if( pgno==1 ){
20558 memcpy(&pPager->dbFileVers, &((u8*)PGHDR_TO_DATA(pPg))[24],
20559 sizeof(pPager->dbFileVers));
20561 CODEC1(pPager, PGHDR_TO_DATA(pPg), pPg->pgno, 3);
20562 PAGERTRACE4("FETCH %d page %d hash(%08x)\n",
20563 PAGERID(pPager), pPg->pgno, pager_pagehash(pPg));
20564 return rc;
20569 ** This function is called to obtain the shared lock required before
20570 ** data may be read from the pager cache. If the shared lock has already
20571 ** been obtained, this function is a no-op.
20573 ** Immediately after obtaining the shared lock (if required), this function
20574 ** checks for a hot-journal file. If one is found, an emergency rollback
20575 ** is performed immediately.
20577 static int pagerSharedLock(Pager *pPager){
20578 int rc = SQLITE_OK;
20580 if( pPager->state==PAGER_UNLOCK ){
20581 if( !MEMDB ){
20582 assert( pPager->nRef==0 );
20583 if( !pPager->noReadlock ){
20584 rc = pager_wait_on_lock(pPager, SHARED_LOCK);
20585 if( rc!=SQLITE_OK ){
20586 return pager_error(pPager, rc);
20588 assert( pPager->state>=SHARED_LOCK );
20591 /* If a journal file exists, and there is no RESERVED lock on the
20592 ** database file, then it either needs to be played back or deleted.
20594 if( hasHotJournal(pPager) ){
20595 /* Get an EXCLUSIVE lock on the database file. At this point it is
20596 ** important that a RESERVED lock is not obtained on the way to the
20597 ** EXCLUSIVE lock. If it were, another process might open the
20598 ** database file, detect the RESERVED lock, and conclude that the
20599 ** database is safe to read while this process is still rolling it
20600 ** back.
20602 ** Because the intermediate RESERVED lock is not requested, the
20603 ** second process will get to this point in the code and fail to
20604 ** obtain it's own EXCLUSIVE lock on the database file.
20606 rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
20607 if( rc!=SQLITE_OK ){
20608 pager_unlock(pPager);
20609 return pager_error(pPager, rc);
20611 pPager->state = PAGER_EXCLUSIVE;
20613 /* Open the journal for reading only. Return SQLITE_BUSY if
20614 ** we are unable to open the journal file.
20616 ** The journal file does not need to be locked itself. The
20617 ** journal file is never open unless the main database file holds
20618 ** a write lock, so there is never any chance of two or more
20619 ** processes opening the journal at the same time.
20621 ** Open the journal for read/write access. This is because in
20622 ** exclusive-access mode the file descriptor will be kept open and
20623 ** possibly used for a transaction later on. On some systems, the
20624 ** OsTruncate() call used in exclusive-access mode also requires
20625 ** a read/write file handle.
20627 rc = SQLITE_BUSY;
20628 if( sqlite3OsFileExists(pPager->zJournal) ){
20629 int ro;
20630 assert( !pPager->tempFile );
20631 rc = sqlite3OsOpenReadWrite(pPager->zJournal, &pPager->jfd, &ro);
20632 assert( rc!=SQLITE_OK || pPager->jfd );
20633 if( ro ){
20634 rc = SQLITE_BUSY;
20635 sqlite3OsClose(&pPager->jfd);
20638 if( rc!=SQLITE_OK ){
20639 pager_unlock(pPager);
20640 return SQLITE_BUSY;
20642 pPager->journalOpen = 1;
20643 pPager->journalStarted = 0;
20644 pPager->journalOff = 0;
20645 pPager->setMaster = 0;
20646 pPager->journalHdr = 0;
20648 /* Playback and delete the journal. Drop the database write
20649 ** lock and reacquire the read lock.
20651 rc = pager_playback(pPager, 1);
20652 if( rc!=SQLITE_OK ){
20653 return pager_error(pPager, rc);
20655 assert(pPager->state==PAGER_SHARED ||
20656 (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
20660 if( pPager->pAll ){
20661 /* The shared-lock has just been acquired on the database file
20662 ** and there are already pages in the cache (from a previous
20663 ** read or write transaction). Check to see if the database
20664 ** has been modified. If the database has changed, flush the
20665 ** cache.
20667 ** Database changes is detected by looking at 15 bytes beginning
20668 ** at offset 24 into the file. The first 4 of these 16 bytes are
20669 ** a 32-bit counter that is incremented with each change. The
20670 ** other bytes change randomly with each file change when
20671 ** a codec is in use.
20673 ** There is a vanishingly small chance that a change will not be
20674 ** detected. The chance of an undetected change is so small that
20675 ** it can be neglected.
20677 char dbFileVers[sizeof(pPager->dbFileVers)];
20678 sqlite3PagerPagecount(pPager);
20680 if( pPager->errCode ){
20681 return pPager->errCode;
20684 if( pPager->dbSize>0 ){
20685 IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
20686 rc = sqlite3OsSeek(pPager->fd, 24);
20687 if( rc!=SQLITE_OK ){
20688 return rc;
20690 rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers));
20691 if( rc!=SQLITE_OK ){
20692 return rc;
20694 }else{
20695 memset(dbFileVers, 0, sizeof(dbFileVers));
20698 if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
20699 pager_reset(pPager);
20703 assert( pPager->exclusiveMode || pPager->state<=PAGER_SHARED );
20704 if( pPager->state==PAGER_UNLOCK ){
20705 pPager->state = PAGER_SHARED;
20709 return rc;
20713 ** Allocate a PgHdr object. Either create a new one or reuse
20714 ** an existing one that is not otherwise in use.
20716 ** A new PgHdr structure is created if any of the following are
20717 ** true:
20719 ** (1) We have not exceeded our maximum allocated cache size
20720 ** as set by the "PRAGMA cache_size" command.
20722 ** (2) There are no unused PgHdr objects available at this time.
20724 ** (3) This is an in-memory database.
20726 ** (4) There are no PgHdr objects that do not require a journal
20727 ** file sync and a sync of the journal file is currently
20728 ** prohibited.
20730 ** Otherwise, reuse an existing PgHdr. In other words, reuse an
20731 ** existing PgHdr if all of the following are true:
20733 ** (1) We have reached or exceeded the maximum cache size
20734 ** allowed by "PRAGMA cache_size".
20736 ** (2) There is a PgHdr available with PgHdr->nRef==0
20738 ** (3) We are not in an in-memory database
20740 ** (4) Either there is an available PgHdr that does not need
20741 ** to be synced to disk or else disk syncing is currently
20742 ** allowed.
20744 static int pagerAllocatePage(Pager *pPager, PgHdr **ppPg){
20745 int rc = SQLITE_OK;
20746 PgHdr *pPg;
20748 /* Create a new PgHdr if any of the four conditions defined
20749 ** above is met: */
20750 if( pPager->nPage<pPager->mxPage
20751 || pPager->pFirst==0
20752 || MEMDB
20753 || (pPager->pFirstSynced==0 && pPager->doNotSync)
20755 if( pPager->nPage>=pPager->nHash ){
20756 pager_resize_hash_table(pPager,
20757 pPager->nHash<256 ? 256 : pPager->nHash*2);
20758 if( pPager->nHash==0 ){
20759 rc = SQLITE_NOMEM;
20760 goto pager_allocate_out;
20763 pPg = sqliteMallocRaw( sizeof(*pPg) + pPager->pageSize
20764 + sizeof(u32) + pPager->nExtra
20765 + MEMDB*sizeof(PgHistory) );
20766 if( pPg==0 ){
20767 rc = SQLITE_NOMEM;
20768 goto pager_allocate_out;
20770 memset(pPg, 0, sizeof(*pPg));
20771 if( MEMDB ){
20772 memset(PGHDR_TO_HIST(pPg, pPager), 0, sizeof(PgHistory));
20774 pPg->pPager = pPager;
20775 pPg->pNextAll = pPager->pAll;
20776 pPager->pAll = pPg;
20777 pPager->nPage++;
20778 }else{
20779 /* Recycle an existing page with a zero ref-count. */
20780 rc = pager_recycle(pPager, 1, &pPg);
20781 if( rc==SQLITE_BUSY ){
20782 rc = SQLITE_IOERR_BLOCKED;
20784 if( rc!=SQLITE_OK ){
20785 goto pager_allocate_out;
20787 assert( pPager->state>=SHARED_LOCK );
20788 assert(pPg);
20790 *ppPg = pPg;
20792 pager_allocate_out:
20793 return rc;
20797 ** Make sure we have the content for a page. If the page was
20798 ** previously acquired with noContent==1, then the content was
20799 ** just initialized to zeros instead of being read from disk.
20800 ** But now we need the real data off of disk. So make sure we
20801 ** have it. Read it in if we do not have it already.
20803 static int pager_get_content(PgHdr *pPg){
20804 if( pPg->needRead ){
20805 int rc = readDbPage(pPg->pPager, pPg, pPg->pgno);
20806 if( rc==SQLITE_OK ){
20807 pPg->needRead = 0;
20808 }else{
20809 return rc;
20812 return SQLITE_OK;
20816 ** Acquire a page.
20818 ** A read lock on the disk file is obtained when the first page is acquired.
20819 ** This read lock is dropped when the last page is released.
20821 ** This routine works for any page number greater than 0. If the database
20822 ** file is smaller than the requested page, then no actual disk
20823 ** read occurs and the memory image of the page is initialized to
20824 ** all zeros. The extra data appended to a page is always initialized
20825 ** to zeros the first time a page is loaded into memory.
20827 ** The acquisition might fail for several reasons. In all cases,
20828 ** an appropriate error code is returned and *ppPage is set to NULL.
20830 ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
20831 ** to find a page in the in-memory cache first. If the page is not already
20832 ** in memory, this routine goes to disk to read it in whereas Lookup()
20833 ** just returns 0. This routine acquires a read-lock the first time it
20834 ** has to go to disk, and could also playback an old journal if necessary.
20835 ** Since Lookup() never goes to disk, it never has to deal with locks
20836 ** or journal files.
20838 ** If noContent is false, the page contents are actually read from disk.
20839 ** If noContent is true, it means that we do not care about the contents
20840 ** of the page at this time, so do not do a disk read. Just fill in the
20841 ** page content with zeros. But mark the fact that we have not read the
20842 ** content by setting the PgHdr.needRead flag. Later on, if
20843 ** sqlite3PagerWrite() is called on this page or if this routine is
20844 ** called again with noContent==0, that means that the content is needed
20845 ** and the disk read should occur at that point.
20847 static int sqlite3PagerAcquire(
20848 Pager *pPager, /* The pager open on the database file */
20849 Pgno pgno, /* Page number to fetch */
20850 DbPage **ppPage, /* Write a pointer to the page here */
20851 int noContent /* Do not bother reading content from disk if true */
20853 PgHdr *pPg;
20854 int rc;
20856 assert( pPager->state==PAGER_UNLOCK || pPager->nRef>0 || pgno==1 );
20858 /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
20859 ** number greater than this, or zero, is requested.
20861 if( pgno>PAGER_MAX_PGNO || pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
20862 return SQLITE_CORRUPT_BKPT;
20865 /* Make sure we have not hit any critical errors.
20867 assert( pPager!=0 );
20868 *ppPage = 0;
20869 if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
20870 return pPager->errCode;
20873 /* If this is the first page accessed, then get a SHARED lock
20874 ** on the database file. pagerSharedLock() is a no-op if
20875 ** a database lock is already held.
20877 rc = pagerSharedLock(pPager);
20878 if( rc!=SQLITE_OK ){
20879 return rc;
20881 assert( pPager->state!=PAGER_UNLOCK );
20883 pPg = pager_lookup(pPager, pgno);
20884 if( pPg==0 ){
20885 /* The requested page is not in the page cache. */
20886 int nMax;
20887 int h;
20888 PAGER_INCR(pPager->nMiss);
20889 rc = pagerAllocatePage(pPager, &pPg);
20890 if( rc!=SQLITE_OK ){
20891 return rc;
20894 pPg->pgno = pgno;
20895 assert( !MEMDB || pgno>pPager->stmtSize );
20896 if( pPager->aInJournal && (int)pgno<=pPager->origDbSize ){
20897 sqlite3CheckMemory(pPager->aInJournal, pgno/8);
20898 assert( pPager->journalOpen );
20899 pPg->inJournal = (pPager->aInJournal[pgno/8] & (1<<(pgno&7)))!=0;
20900 pPg->needSync = 0;
20901 }else{
20902 pPg->inJournal = 0;
20903 pPg->needSync = 0;
20906 makeClean(pPg);
20907 pPg->nRef = 1;
20908 REFINFO(pPg);
20910 pPager->nRef++;
20911 if( pPager->nExtra>0 ){
20912 memset(PGHDR_TO_EXTRA(pPg, pPager), 0, pPager->nExtra);
20914 nMax = sqlite3PagerPagecount(pPager);
20915 if( pPager->errCode ){
20916 sqlite3PagerUnref(pPg);
20917 rc = pPager->errCode;
20918 return rc;
20921 /* Populate the page with data, either by reading from the database
20922 ** file, or by setting the entire page to zero.
20924 if( nMax<(int)pgno || MEMDB || (noContent && !pPager->alwaysRollback) ){
20925 if( pgno>pPager->mxPgno ){
20926 sqlite3PagerUnref(pPg);
20927 return SQLITE_FULL;
20929 memset(PGHDR_TO_DATA(pPg), 0, pPager->pageSize);
20930 pPg->needRead = noContent && !pPager->alwaysRollback;
20931 IOTRACE(("ZERO %p %d\n", pPager, pgno));
20932 }else{
20933 rc = readDbPage(pPager, pPg, pgno);
20934 if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
20935 pPg->pgno = 0;
20936 sqlite3PagerUnref(pPg);
20937 return rc;
20939 pPg->needRead = 0;
20942 /* Link the page into the page hash table */
20943 h = pgno & (pPager->nHash-1);
20944 assert( pgno!=0 );
20945 pPg->pNextHash = pPager->aHash[h];
20946 pPager->aHash[h] = pPg;
20947 if( pPg->pNextHash ){
20948 assert( pPg->pNextHash->pPrevHash==0 );
20949 pPg->pNextHash->pPrevHash = pPg;
20952 #ifdef SQLITE_CHECK_PAGES
20953 pPg->pageHash = pager_pagehash(pPg);
20954 #endif
20955 }else{
20956 /* The requested page is in the page cache. */
20957 assert(pPager->nRef>0 || pgno==1);
20958 PAGER_INCR(pPager->nHit);
20959 if( !noContent ){
20960 rc = pager_get_content(pPg);
20961 if( rc ){
20962 return rc;
20965 page_ref(pPg);
20967 *ppPage = pPg;
20968 return SQLITE_OK;
20972 ** Acquire a page if it is already in the in-memory cache. Do
20973 ** not read the page from disk. Return a pointer to the page,
20974 ** or 0 if the page is not in cache.
20976 ** See also sqlite3PagerGet(). The difference between this routine
20977 ** and sqlite3PagerGet() is that _get() will go to the disk and read
20978 ** in the page if the page is not already in cache. This routine
20979 ** returns NULL if the page is not in cache or if a disk I/O error
20980 ** has ever happened.
20982 static DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
20983 PgHdr *pPg;
20985 assert( pPager!=0 );
20986 assert( pgno!=0 );
20988 if( pPager->state==PAGER_UNLOCK ){
20989 assert( !pPager->pAll || pPager->exclusiveMode );
20990 return 0;
20992 if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
20993 return 0;
20995 pPg = pager_lookup(pPager, pgno);
20996 if( pPg==0 ) return 0;
20997 page_ref(pPg);
20998 return pPg;
21002 ** Release a page.
21004 ** If the number of references to the page drop to zero, then the
21005 ** page is added to the LRU list. When all references to all pages
21006 ** are released, a rollback occurs and the lock on the database is
21007 ** removed.
21009 static int sqlite3PagerUnref(DbPage *pPg){
21011 /* Decrement the reference count for this page
21013 assert( pPg->nRef>0 );
21014 pPg->nRef--;
21015 REFINFO(pPg);
21017 CHECK_PAGE(pPg);
21019 /* When the number of references to a page reach 0, call the
21020 ** destructor and add the page to the freelist.
21022 if( pPg->nRef==0 ){
21023 Pager *pPager;
21024 pPager = pPg->pPager;
21025 pPg->pNextFree = 0;
21026 pPg->pPrevFree = pPager->pLast;
21027 pPager->pLast = pPg;
21028 if( pPg->pPrevFree ){
21029 pPg->pPrevFree->pNextFree = pPg;
21030 }else{
21031 pPager->pFirst = pPg;
21033 if( pPg->needSync==0 && pPager->pFirstSynced==0 ){
21034 pPager->pFirstSynced = pPg;
21036 if( pPager->xDestructor ){
21037 pPager->xDestructor(pPg, pPager->pageSize);
21040 /* When all pages reach the freelist, drop the read lock from
21041 ** the database file.
21043 pPager->nRef--;
21044 assert( pPager->nRef>=0 );
21045 if( pPager->nRef==0 && (!pPager->exclusiveMode || pPager->journalOff>0) ){
21046 pagerUnlockAndRollback(pPager);
21049 return SQLITE_OK;
21053 ** Create a journal file for pPager. There should already be a RESERVED
21054 ** or EXCLUSIVE lock on the database file when this routine is called.
21056 ** Return SQLITE_OK if everything. Return an error code and release the
21057 ** write lock if anything goes wrong.
21059 static int pager_open_journal(Pager *pPager){
21060 int rc;
21061 assert( !MEMDB );
21062 assert( pPager->state>=PAGER_RESERVED );
21063 assert( pPager->journalOpen==0 );
21064 assert( pPager->useJournal );
21065 assert( pPager->aInJournal==0 );
21066 sqlite3PagerPagecount(pPager);
21067 pPager->aInJournal = sqliteMalloc( pPager->dbSize/8 + 1 );
21068 if( pPager->aInJournal==0 ){
21069 rc = SQLITE_NOMEM;
21070 goto failed_to_open_journal;
21072 rc = sqlite3OsOpenExclusive(pPager->zJournal, &pPager->jfd,
21073 pPager->tempFile);
21074 assert( rc!=SQLITE_OK || pPager->jfd );
21075 pPager->journalOff = 0;
21076 pPager->setMaster = 0;
21077 pPager->journalHdr = 0;
21078 if( rc!=SQLITE_OK ){
21079 if( rc==SQLITE_NOMEM ){
21080 sqlite3OsDelete(pPager->zJournal);
21082 goto failed_to_open_journal;
21084 sqlite3OsSetFullSync(pPager->jfd, pPager->full_fsync);
21085 sqlite3OsSetFullSync(pPager->fd, pPager->full_fsync);
21086 sqlite3OsOpenDirectory(pPager->jfd, pPager->zDirectory);
21087 pPager->journalOpen = 1;
21088 pPager->journalStarted = 0;
21089 pPager->needSync = 0;
21090 pPager->alwaysRollback = 0;
21091 pPager->nRec = 0;
21092 if( pPager->errCode ){
21093 rc = pPager->errCode;
21094 goto failed_to_open_journal;
21096 pPager->origDbSize = pPager->dbSize;
21098 rc = writeJournalHdr(pPager);
21100 if( pPager->stmtAutoopen && rc==SQLITE_OK ){
21101 rc = sqlite3PagerStmtBegin(pPager);
21103 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
21104 rc = pager_end_transaction(pPager);
21105 if( rc==SQLITE_OK ){
21106 rc = SQLITE_FULL;
21109 return rc;
21111 failed_to_open_journal:
21112 sqliteFree(pPager->aInJournal);
21113 pPager->aInJournal = 0;
21114 return rc;
21118 ** Acquire a write-lock on the database. The lock is removed when
21119 ** the any of the following happen:
21121 ** * sqlite3PagerCommitPhaseTwo() is called.
21122 ** * sqlite3PagerRollback() is called.
21123 ** * sqlite3PagerClose() is called.
21124 ** * sqlite3PagerUnref() is called to on every outstanding page.
21126 ** The first parameter to this routine is a pointer to any open page of the
21127 ** database file. Nothing changes about the page - it is used merely to
21128 ** acquire a pointer to the Pager structure and as proof that there is
21129 ** already a read-lock on the database.
21131 ** The second parameter indicates how much space in bytes to reserve for a
21132 ** master journal file-name at the start of the journal when it is created.
21134 ** A journal file is opened if this is not a temporary file. For temporary
21135 ** files, the opening of the journal file is deferred until there is an
21136 ** actual need to write to the journal.
21138 ** If the database is already reserved for writing, this routine is a no-op.
21140 ** If exFlag is true, go ahead and get an EXCLUSIVE lock on the file
21141 ** immediately instead of waiting until we try to flush the cache. The
21142 ** exFlag is ignored if a transaction is already active.
21144 static int sqlite3PagerBegin(DbPage *pPg, int exFlag){
21145 Pager *pPager = pPg->pPager;
21146 int rc = SQLITE_OK;
21147 assert( pPg->nRef>0 );
21148 assert( pPager->state!=PAGER_UNLOCK );
21149 if( pPager->state==PAGER_SHARED ){
21150 assert( pPager->aInJournal==0 );
21151 if( MEMDB ){
21152 pPager->state = PAGER_EXCLUSIVE;
21153 pPager->origDbSize = pPager->dbSize;
21154 }else{
21155 rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
21156 if( rc==SQLITE_OK ){
21157 pPager->state = PAGER_RESERVED;
21158 if( exFlag ){
21159 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
21162 if( rc!=SQLITE_OK ){
21163 return rc;
21165 pPager->dirtyCache = 0;
21166 PAGERTRACE2("TRANSACTION %d\n", PAGERID(pPager));
21167 if( pPager->useJournal && !pPager->tempFile ){
21168 rc = pager_open_journal(pPager);
21171 }else if( pPager->journalOpen && pPager->journalOff==0 ){
21172 /* This happens when the pager was in exclusive-access mode last
21173 ** time a (read or write) transaction was successfully concluded
21174 ** by this connection. Instead of deleting the journal file it was
21175 ** kept open and truncated to 0 bytes.
21177 assert( pPager->nRec==0 );
21178 assert( pPager->origDbSize==0 );
21179 assert( pPager->aInJournal==0 );
21180 sqlite3PagerPagecount(pPager);
21181 pPager->aInJournal = sqliteMalloc( pPager->dbSize/8 + 1 );
21182 if( !pPager->aInJournal ){
21183 rc = SQLITE_NOMEM;
21184 }else{
21185 pPager->origDbSize = pPager->dbSize;
21186 rc = writeJournalHdr(pPager);
21189 assert( !pPager->journalOpen || pPager->journalOff>0 || rc!=SQLITE_OK );
21190 return rc;
21194 ** Make a page dirty. Set its dirty flag and add it to the dirty
21195 ** page list.
21197 static void makeDirty(PgHdr *pPg){
21198 if( pPg->dirty==0 ){
21199 Pager *pPager = pPg->pPager;
21200 pPg->dirty = 1;
21201 pPg->pDirty = pPager->pDirty;
21202 if( pPager->pDirty ){
21203 pPager->pDirty->pPrevDirty = pPg;
21205 pPg->pPrevDirty = 0;
21206 pPager->pDirty = pPg;
21211 ** Make a page clean. Clear its dirty bit and remove it from the
21212 ** dirty page list.
21214 static void makeClean(PgHdr *pPg){
21215 if( pPg->dirty ){
21216 pPg->dirty = 0;
21217 if( pPg->pDirty ){
21218 pPg->pDirty->pPrevDirty = pPg->pPrevDirty;
21220 if( pPg->pPrevDirty ){
21221 pPg->pPrevDirty->pDirty = pPg->pDirty;
21222 }else{
21223 pPg->pPager->pDirty = pPg->pDirty;
21230 ** Mark a data page as writeable. The page is written into the journal
21231 ** if it is not there already. This routine must be called before making
21232 ** changes to a page.
21234 ** The first time this routine is called, the pager creates a new
21235 ** journal and acquires a RESERVED lock on the database. If the RESERVED
21236 ** lock could not be acquired, this routine returns SQLITE_BUSY. The
21237 ** calling routine must check for that return value and be careful not to
21238 ** change any page data until this routine returns SQLITE_OK.
21240 ** If the journal file could not be written because the disk is full,
21241 ** then this routine returns SQLITE_FULL and does an immediate rollback.
21242 ** All subsequent write attempts also return SQLITE_FULL until there
21243 ** is a call to sqlite3PagerCommit() or sqlite3PagerRollback() to
21244 ** reset.
21246 static int pager_write(PgHdr *pPg){
21247 void *pData = PGHDR_TO_DATA(pPg);
21248 Pager *pPager = pPg->pPager;
21249 int rc = SQLITE_OK;
21251 /* Check for errors
21253 if( pPager->errCode ){
21254 return pPager->errCode;
21256 if( pPager->readOnly ){
21257 return SQLITE_PERM;
21260 assert( !pPager->setMaster );
21262 CHECK_PAGE(pPg);
21264 /* If this page was previously acquired with noContent==1, that means
21265 ** we didn't really read in the content of the page. This can happen
21266 ** (for example) when the page is being moved to the freelist. But
21267 ** now we are (perhaps) moving the page off of the freelist for
21268 ** reuse and we need to know its original content so that content
21269 ** can be stored in the rollback journal. So do the read at this
21270 ** time.
21272 rc = pager_get_content(pPg);
21273 if( rc ){
21274 return rc;
21277 /* Mark the page as dirty. If the page has already been written
21278 ** to the journal then we can return right away.
21280 makeDirty(pPg);
21281 if( pPg->inJournal && (pageInStatement(pPg) || pPager->stmtInUse==0) ){
21282 pPager->dirtyCache = 1;
21283 }else{
21285 /* If we get this far, it means that the page needs to be
21286 ** written to the transaction journal or the ckeckpoint journal
21287 ** or both.
21289 ** First check to see that the transaction journal exists and
21290 ** create it if it does not.
21292 assert( pPager->state!=PAGER_UNLOCK );
21293 rc = sqlite3PagerBegin(pPg, 0);
21294 if( rc!=SQLITE_OK ){
21295 return rc;
21297 assert( pPager->state>=PAGER_RESERVED );
21298 if( !pPager->journalOpen && pPager->useJournal ){
21299 rc = pager_open_journal(pPager);
21300 if( rc!=SQLITE_OK ) return rc;
21302 assert( pPager->journalOpen || !pPager->useJournal );
21303 pPager->dirtyCache = 1;
21305 /* The transaction journal now exists and we have a RESERVED or an
21306 ** EXCLUSIVE lock on the main database file. Write the current page to
21307 ** the transaction journal if it is not there already.
21309 if( !pPg->inJournal && (pPager->useJournal || MEMDB) ){
21310 if( (int)pPg->pgno <= pPager->origDbSize ){
21311 int szPg;
21312 if( MEMDB ){
21313 PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
21314 PAGERTRACE3("JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
21315 assert( pHist->pOrig==0 );
21316 pHist->pOrig = sqliteMallocRaw( pPager->pageSize );
21317 if( pHist->pOrig ){
21318 memcpy(pHist->pOrig, PGHDR_TO_DATA(pPg), pPager->pageSize);
21320 }else{
21321 u32 cksum, saved;
21322 char *pData2, *pEnd;
21323 /* We should never write to the journal file the page that
21324 ** contains the database locks. The following assert verifies
21325 ** that we do not. */
21326 assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
21327 pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
21328 cksum = pager_cksum(pPager, (u8*)pData2);
21329 pEnd = pData2 + pPager->pageSize;
21330 pData2 -= 4;
21331 saved = *(u32*)pEnd;
21332 put32bits(pEnd, cksum);
21333 szPg = pPager->pageSize+8;
21334 put32bits(pData2, pPg->pgno);
21335 rc = sqlite3OsWrite(pPager->jfd, pData2, szPg);
21336 IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
21337 pPager->journalOff, szPg));
21338 PAGER_INCR(sqlite3_pager_writej_count);
21339 pPager->journalOff += szPg;
21340 PAGERTRACE5("JOURNAL %d page %d needSync=%d hash(%08x)\n",
21341 PAGERID(pPager), pPg->pgno, pPg->needSync, pager_pagehash(pPg));
21342 *(u32*)pEnd = saved;
21344 /* An error has occured writing to the journal file. The
21345 ** transaction will be rolled back by the layer above.
21347 if( rc!=SQLITE_OK ){
21348 return rc;
21351 pPager->nRec++;
21352 assert( pPager->aInJournal!=0 );
21353 pPager->aInJournal[pPg->pgno/8] |= 1<<(pPg->pgno&7);
21354 pPg->needSync = !pPager->noSync;
21355 if( pPager->stmtInUse ){
21356 pPager->aInStmt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
21359 }else{
21360 pPg->needSync = !pPager->journalStarted && !pPager->noSync;
21361 PAGERTRACE4("APPEND %d page %d needSync=%d\n",
21362 PAGERID(pPager), pPg->pgno, pPg->needSync);
21364 if( pPg->needSync ){
21365 pPager->needSync = 1;
21367 pPg->inJournal = 1;
21370 /* If the statement journal is open and the page is not in it,
21371 ** then write the current page to the statement journal. Note that
21372 ** the statement journal format differs from the standard journal format
21373 ** in that it omits the checksums and the header.
21375 if( pPager->stmtInUse
21376 && !pageInStatement(pPg)
21377 && (int)pPg->pgno<=pPager->stmtSize
21379 assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
21380 if( MEMDB ){
21381 PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
21382 assert( pHist->pStmt==0 );
21383 pHist->pStmt = sqliteMallocRaw( pPager->pageSize );
21384 if( pHist->pStmt ){
21385 memcpy(pHist->pStmt, PGHDR_TO_DATA(pPg), pPager->pageSize);
21387 PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
21388 page_add_to_stmt_list(pPg);
21389 }else{
21390 char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7)-4;
21391 put32bits(pData2, pPg->pgno);
21392 rc = sqlite3OsWrite(pPager->stfd, pData2, pPager->pageSize+4);
21393 PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
21394 if( rc!=SQLITE_OK ){
21395 return rc;
21397 pPager->stmtNRec++;
21398 assert( pPager->aInStmt!=0 );
21399 pPager->aInStmt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
21404 /* Update the database size and return.
21406 assert( pPager->state>=PAGER_SHARED );
21407 if( pPager->dbSize<(int)pPg->pgno ){
21408 pPager->dbSize = pPg->pgno;
21409 if( !MEMDB && pPager->dbSize==PENDING_BYTE/pPager->pageSize ){
21410 pPager->dbSize++;
21413 return rc;
21417 ** This function is used to mark a data-page as writable. It uses
21418 ** pager_write() to open a journal file (if it is not already open)
21419 ** and write the page *pData to the journal.
21421 ** The difference between this function and pager_write() is that this
21422 ** function also deals with the special case where 2 or more pages
21423 ** fit on a single disk sector. In this case all co-resident pages
21424 ** must have been written to the journal file before returning.
21426 static int sqlite3PagerWrite(DbPage *pDbPage){
21427 int rc = SQLITE_OK;
21429 PgHdr *pPg = pDbPage;
21430 Pager *pPager = pPg->pPager;
21431 Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
21433 if( !MEMDB && nPagePerSector>1 ){
21434 Pgno nPageCount; /* Total number of pages in database file */
21435 Pgno pg1; /* First page of the sector pPg is located on. */
21436 int nPage; /* Number of pages starting at pg1 to journal */
21437 int ii;
21439 /* Set the doNotSync flag to 1. This is because we cannot allow a journal
21440 ** header to be written between the pages journaled by this function.
21442 assert( pPager->doNotSync==0 );
21443 pPager->doNotSync = 1;
21445 /* This trick assumes that both the page-size and sector-size are
21446 ** an integer power of 2. It sets variable pg1 to the identifier
21447 ** of the first page of the sector pPg is located on.
21449 pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
21451 nPageCount = sqlite3PagerPagecount(pPager);
21452 if( pPg->pgno>nPageCount ){
21453 nPage = (pPg->pgno - pg1)+1;
21454 }else if( (pg1+nPagePerSector-1)>nPageCount ){
21455 nPage = nPageCount+1-pg1;
21456 }else{
21457 nPage = nPagePerSector;
21459 assert(nPage>0);
21460 assert(pg1<=pPg->pgno);
21461 assert((pg1+nPage)>pPg->pgno);
21463 for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
21464 Pgno pg = pg1+ii;
21465 if( !pPager->aInJournal || pg==pPg->pgno ||
21466 pg>pPager->origDbSize || !(pPager->aInJournal[pg/8]&(1<<(pg&7)))
21468 if( pg!=PAGER_MJ_PGNO(pPager) ){
21469 PgHdr *pPage;
21470 rc = sqlite3PagerGet(pPager, pg, &pPage);
21471 if( rc==SQLITE_OK ){
21472 rc = pager_write(pPage);
21473 sqlite3PagerUnref(pPage);
21479 assert( pPager->doNotSync==1 );
21480 pPager->doNotSync = 0;
21481 }else{
21482 rc = pager_write(pDbPage);
21484 return rc;
21488 ** Return TRUE if the page given in the argument was previously passed
21489 ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
21490 ** to change the content of the page.
21492 #ifndef NDEBUG
21493 static int sqlite3PagerIswriteable(DbPage *pPg){
21494 return pPg->dirty;
21496 #endif
21498 #ifndef SQLITE_OMIT_VACUUM
21500 ** Replace the content of a single page with the information in the third
21501 ** argument.
21503 static int sqlite3PagerOverwrite(Pager *pPager, Pgno pgno, void *pData){
21504 PgHdr *pPg;
21505 int rc;
21507 rc = sqlite3PagerGet(pPager, pgno, &pPg);
21508 if( rc==SQLITE_OK ){
21509 rc = sqlite3PagerWrite(pPg);
21510 if( rc==SQLITE_OK ){
21511 memcpy(sqlite3PagerGetData(pPg), pData, pPager->pageSize);
21513 sqlite3PagerUnref(pPg);
21515 return rc;
21517 #endif
21520 ** A call to this routine tells the pager that it is not necessary to
21521 ** write the information on page pPg back to the disk, even though
21522 ** that page might be marked as dirty.
21524 ** The overlying software layer calls this routine when all of the data
21525 ** on the given page is unused. The pager marks the page as clean so
21526 ** that it does not get written to disk.
21528 ** Tests show that this optimization, together with the
21529 ** sqlite3PagerDontRollback() below, more than double the speed
21530 ** of large INSERT operations and quadruple the speed of large DELETEs.
21532 ** When this routine is called, set the alwaysRollback flag to true.
21533 ** Subsequent calls to sqlite3PagerDontRollback() for the same page
21534 ** will thereafter be ignored. This is necessary to avoid a problem
21535 ** where a page with data is added to the freelist during one part of
21536 ** a transaction then removed from the freelist during a later part
21537 ** of the same transaction and reused for some other purpose. When it
21538 ** is first added to the freelist, this routine is called. When reused,
21539 ** the sqlite3PagerDontRollback() routine is called. But because the
21540 ** page contains critical data, we still need to be sure it gets
21541 ** rolled back in spite of the sqlite3PagerDontRollback() call.
21543 static void sqlite3PagerDontWrite(DbPage *pDbPage){
21544 PgHdr *pPg = pDbPage;
21545 Pager *pPager = pPg->pPager;
21547 if( MEMDB ) return;
21548 pPg->alwaysRollback = 1;
21549 if( pPg->dirty && !pPager->stmtInUse ){
21550 assert( pPager->state>=PAGER_SHARED );
21551 if( pPager->dbSize==(int)pPg->pgno && pPager->origDbSize<pPager->dbSize ){
21552 /* If this pages is the last page in the file and the file has grown
21553 ** during the current transaction, then do NOT mark the page as clean.
21554 ** When the database file grows, we must make sure that the last page
21555 ** gets written at least once so that the disk file will be the correct
21556 ** size. If you do not write this page and the size of the file
21557 ** on the disk ends up being too small, that can lead to database
21558 ** corruption during the next transaction.
21560 }else{
21561 PAGERTRACE3("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager));
21562 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
21563 makeClean(pPg);
21564 #ifdef SQLITE_CHECK_PAGES
21565 pPg->pageHash = pager_pagehash(pPg);
21566 #endif
21572 ** A call to this routine tells the pager that if a rollback occurs,
21573 ** it is not necessary to restore the data on the given page. This
21574 ** means that the pager does not have to record the given page in the
21575 ** rollback journal.
21577 ** If we have not yet actually read the content of this page (if
21578 ** the PgHdr.needRead flag is set) then this routine acts as a promise
21579 ** that we will never need to read the page content in the future.
21580 ** so the needRead flag can be cleared at this point.
21582 static void sqlite3PagerDontRollback(DbPage *pPg){
21583 Pager *pPager = pPg->pPager;
21585 assert( pPager->state>=PAGER_RESERVED );
21586 if( pPager->journalOpen==0 ) return;
21587 if( pPg->alwaysRollback || pPager->alwaysRollback || MEMDB ) return;
21588 if( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize ){
21589 assert( pPager->aInJournal!=0 );
21590 pPager->aInJournal[pPg->pgno/8] |= 1<<(pPg->pgno&7);
21591 pPg->inJournal = 1;
21592 pPg->needRead = 0;
21593 if( pPager->stmtInUse ){
21594 pPager->aInStmt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
21596 PAGERTRACE3("DONT_ROLLBACK page %d of %d\n", pPg->pgno, PAGERID(pPager));
21597 IOTRACE(("GARBAGE %p %d\n", pPager, pPg->pgno))
21599 if( pPager->stmtInUse
21600 && !pageInStatement(pPg)
21601 && (int)pPg->pgno<=pPager->stmtSize
21603 assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
21604 assert( pPager->aInStmt!=0 );
21605 pPager->aInStmt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
21611 ** This routine is called to increment the database file change-counter,
21612 ** stored at byte 24 of the pager file.
21614 static int pager_incr_changecounter(Pager *pPager){
21615 PgHdr *pPgHdr;
21616 u32 change_counter;
21617 int rc;
21619 if( !pPager->changeCountDone ){
21620 /* Open page 1 of the file for writing. */
21621 rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
21622 if( rc!=SQLITE_OK ) return rc;
21623 rc = sqlite3PagerWrite(pPgHdr);
21624 if( rc!=SQLITE_OK ) return rc;
21626 /* Read the current value at byte 24. */
21627 change_counter = retrieve32bits(pPgHdr, 24);
21629 /* Increment the value just read and write it back to byte 24. */
21630 change_counter++;
21631 put32bits(((char*)PGHDR_TO_DATA(pPgHdr))+24, change_counter);
21633 /* Release the page reference. */
21634 sqlite3PagerUnref(pPgHdr);
21635 pPager->changeCountDone = 1;
21637 return SQLITE_OK;
21641 ** Sync the database file for the pager pPager. zMaster points to the name
21642 ** of a master journal file that should be written into the individual
21643 ** journal file. zMaster may be NULL, which is interpreted as no master
21644 ** journal (a single database transaction).
21646 ** This routine ensures that the journal is synced, all dirty pages written
21647 ** to the database file and the database file synced. The only thing that
21648 ** remains to commit the transaction is to delete the journal file (or
21649 ** master journal file if specified).
21651 ** Note that if zMaster==NULL, this does not overwrite a previous value
21652 ** passed to an sqlite3PagerCommitPhaseOne() call.
21654 ** If parameter nTrunc is non-zero, then the pager file is truncated to
21655 ** nTrunc pages (this is used by auto-vacuum databases).
21657 static int sqlite3PagerCommitPhaseOne(Pager *pPager, const char *zMaster, Pgno nTrunc){
21658 int rc = SQLITE_OK;
21660 PAGERTRACE4("DATABASE SYNC: File=%s zMaster=%s nTrunc=%d\n",
21661 pPager->zFilename, zMaster, nTrunc);
21663 /* If this is an in-memory db, or no pages have been written to, or this
21664 ** function has already been called, it is a no-op.
21666 if( pPager->state!=PAGER_SYNCED && !MEMDB && pPager->dirtyCache ){
21667 PgHdr *pPg;
21668 assert( pPager->journalOpen );
21670 /* If a master journal file name has already been written to the
21671 ** journal file, then no sync is required. This happens when it is
21672 ** written, then the process fails to upgrade from a RESERVED to an
21673 ** EXCLUSIVE lock. The next time the process tries to commit the
21674 ** transaction the m-j name will have already been written.
21676 if( !pPager->setMaster ){
21677 rc = pager_incr_changecounter(pPager);
21678 if( rc!=SQLITE_OK ) goto sync_exit;
21679 #ifndef SQLITE_OMIT_AUTOVACUUM
21680 if( nTrunc!=0 ){
21681 /* If this transaction has made the database smaller, then all pages
21682 ** being discarded by the truncation must be written to the journal
21683 ** file.
21685 Pgno i;
21686 int iSkip = PAGER_MJ_PGNO(pPager);
21687 for( i=nTrunc+1; i<=pPager->origDbSize; i++ ){
21688 if( !(pPager->aInJournal[i/8] & (1<<(i&7))) && i!=iSkip ){
21689 rc = sqlite3PagerGet(pPager, i, &pPg);
21690 if( rc!=SQLITE_OK ) goto sync_exit;
21691 rc = sqlite3PagerWrite(pPg);
21692 sqlite3PagerUnref(pPg);
21693 if( rc!=SQLITE_OK ) goto sync_exit;
21697 #endif
21698 rc = writeMasterJournal(pPager, zMaster);
21699 if( rc!=SQLITE_OK ) goto sync_exit;
21700 rc = syncJournal(pPager);
21701 if( rc!=SQLITE_OK ) goto sync_exit;
21704 #ifndef SQLITE_OMIT_AUTOVACUUM
21705 if( nTrunc!=0 ){
21706 rc = sqlite3PagerTruncate(pPager, nTrunc);
21707 if( rc!=SQLITE_OK ) goto sync_exit;
21709 #endif
21711 /* Write all dirty pages to the database file */
21712 pPg = pager_get_all_dirty_pages(pPager);
21713 rc = pager_write_pagelist(pPg);
21714 if( rc!=SQLITE_OK ) goto sync_exit;
21715 pPager->pDirty = 0;
21717 /* Sync the database file. */
21718 if( !pPager->noSync ){
21719 rc = sqlite3OsSync(pPager->fd, 0);
21721 IOTRACE(("DBSYNC %p\n", pPager))
21723 pPager->state = PAGER_SYNCED;
21724 }else if( MEMDB && nTrunc!=0 ){
21725 rc = sqlite3PagerTruncate(pPager, nTrunc);
21728 sync_exit:
21729 if( rc==SQLITE_IOERR_BLOCKED ){
21730 /* pager_incr_changecounter() may attempt to obtain an exclusive
21731 * lock to spill the cache and return IOERR_BLOCKED. But since
21732 * there is no chance the cache is inconsistent, it's
21733 * better to return SQLITE_BUSY.
21735 rc = SQLITE_BUSY;
21737 return rc;
21742 ** Commit all changes to the database and release the write lock.
21744 ** If the commit fails for any reason, a rollback attempt is made
21745 ** and an error code is returned. If the commit worked, SQLITE_OK
21746 ** is returned.
21748 static int sqlite3PagerCommitPhaseTwo(Pager *pPager){
21749 int rc;
21750 PgHdr *pPg;
21752 if( pPager->errCode ){
21753 return pPager->errCode;
21755 if( pPager->state<PAGER_RESERVED ){
21756 return SQLITE_ERROR;
21758 PAGERTRACE2("COMMIT %d\n", PAGERID(pPager));
21759 if( MEMDB ){
21760 pPg = pager_get_all_dirty_pages(pPager);
21761 while( pPg ){
21762 PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
21763 clearHistory(pHist);
21764 pPg->dirty = 0;
21765 pPg->inJournal = 0;
21766 pHist->inStmt = 0;
21767 pPg->needSync = 0;
21768 pHist->pPrevStmt = pHist->pNextStmt = 0;
21769 pPg = pPg->pDirty;
21771 pPager->pDirty = 0;
21772 #ifndef NDEBUG
21773 for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
21774 PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
21775 assert( !pPg->alwaysRollback );
21776 assert( !pHist->pOrig );
21777 assert( !pHist->pStmt );
21779 #endif
21780 pPager->pStmt = 0;
21781 pPager->state = PAGER_SHARED;
21782 return SQLITE_OK;
21784 assert( pPager->journalOpen || !pPager->dirtyCache );
21785 assert( pPager->state==PAGER_SYNCED || !pPager->dirtyCache );
21786 rc = pager_end_transaction(pPager);
21787 return pager_error(pPager, rc);
21791 ** Rollback all changes. The database falls back to PAGER_SHARED mode.
21792 ** All in-memory cache pages revert to their original data contents.
21793 ** The journal is deleted.
21795 ** This routine cannot fail unless some other process is not following
21796 ** the correct locking protocol or unless some other
21797 ** process is writing trash into the journal file (SQLITE_CORRUPT) or
21798 ** unless a prior malloc() failed (SQLITE_NOMEM). Appropriate error
21799 ** codes are returned for all these occasions. Otherwise,
21800 ** SQLITE_OK is returned.
21802 static int sqlite3PagerRollback(Pager *pPager){
21803 int rc;
21804 PAGERTRACE2("ROLLBACK %d\n", PAGERID(pPager));
21805 if( MEMDB ){
21806 PgHdr *p;
21807 for(p=pPager->pAll; p; p=p->pNextAll){
21808 PgHistory *pHist;
21809 assert( !p->alwaysRollback );
21810 if( !p->dirty ){
21811 assert( !((PgHistory *)PGHDR_TO_HIST(p, pPager))->pOrig );
21812 assert( !((PgHistory *)PGHDR_TO_HIST(p, pPager))->pStmt );
21813 continue;
21816 pHist = PGHDR_TO_HIST(p, pPager);
21817 if( pHist->pOrig ){
21818 memcpy(PGHDR_TO_DATA(p), pHist->pOrig, pPager->pageSize);
21819 PAGERTRACE3("ROLLBACK-PAGE %d of %d\n", p->pgno, PAGERID(pPager));
21820 }else{
21821 PAGERTRACE3("PAGE %d is clean on %d\n", p->pgno, PAGERID(pPager));
21823 clearHistory(pHist);
21824 p->dirty = 0;
21825 p->inJournal = 0;
21826 pHist->inStmt = 0;
21827 pHist->pPrevStmt = pHist->pNextStmt = 0;
21828 if( pPager->xReiniter ){
21829 pPager->xReiniter(p, pPager->pageSize);
21832 pPager->pDirty = 0;
21833 pPager->pStmt = 0;
21834 pPager->dbSize = pPager->origDbSize;
21835 pager_truncate_cache(pPager);
21836 pPager->stmtInUse = 0;
21837 pPager->state = PAGER_SHARED;
21838 return SQLITE_OK;
21841 if( !pPager->dirtyCache || !pPager->journalOpen ){
21842 rc = pager_end_transaction(pPager);
21843 return rc;
21846 if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
21847 if( pPager->state>=PAGER_EXCLUSIVE ){
21848 pager_playback(pPager, 0);
21850 return pPager->errCode;
21852 if( pPager->state==PAGER_RESERVED ){
21853 int rc2;
21854 rc = pager_playback(pPager, 0);
21855 rc2 = pager_end_transaction(pPager);
21856 if( rc==SQLITE_OK ){
21857 rc = rc2;
21859 }else{
21860 rc = pager_playback(pPager, 0);
21862 /* pager_reset(pPager); */
21863 pPager->dbSize = -1;
21865 /* If an error occurs during a ROLLBACK, we can no longer trust the pager
21866 ** cache. So call pager_error() on the way out to make any error
21867 ** persistent.
21869 return pager_error(pPager, rc);
21873 ** Return TRUE if the database file is opened read-only. Return FALSE
21874 ** if the database is (in theory) writable.
21876 static int sqlite3PagerIsreadonly(Pager *pPager){
21877 return pPager->readOnly;
21881 ** Return the number of references to the pager.
21883 static int sqlite3PagerRefcount(Pager *pPager){
21884 return pPager->nRef;
21887 #ifdef SQLITE_TEST
21889 ** This routine is used for testing and analysis only.
21891 static int *sqlite3PagerStats(Pager *pPager){
21892 static int a[11];
21893 a[0] = pPager->nRef;
21894 a[1] = pPager->nPage;
21895 a[2] = pPager->mxPage;
21896 a[3] = pPager->dbSize;
21897 a[4] = pPager->state;
21898 a[5] = pPager->errCode;
21899 a[6] = pPager->nHit;
21900 a[7] = pPager->nMiss;
21901 a[8] = 0; /* Used to be pPager->nOvfl */
21902 a[9] = pPager->nRead;
21903 a[10] = pPager->nWrite;
21904 return a;
21906 #endif
21909 ** Set the statement rollback point.
21911 ** This routine should be called with the transaction journal already
21912 ** open. A new statement journal is created that can be used to rollback
21913 ** changes of a single SQL command within a larger transaction.
21915 static int sqlite3PagerStmtBegin(Pager *pPager){
21916 int rc;
21917 assert( !pPager->stmtInUse );
21918 assert( pPager->state>=PAGER_SHARED );
21919 assert( pPager->dbSize>=0 );
21920 PAGERTRACE2("STMT-BEGIN %d\n", PAGERID(pPager));
21921 if( MEMDB ){
21922 pPager->stmtInUse = 1;
21923 pPager->stmtSize = pPager->dbSize;
21924 return SQLITE_OK;
21926 if( !pPager->journalOpen ){
21927 pPager->stmtAutoopen = 1;
21928 return SQLITE_OK;
21930 assert( pPager->journalOpen );
21931 pPager->aInStmt = sqliteMalloc( pPager->dbSize/8 + 1 );
21932 if( pPager->aInStmt==0 ){
21933 /* sqlite3OsLock(pPager->fd, SHARED_LOCK); */
21934 return SQLITE_NOMEM;
21936 #ifndef NDEBUG
21937 rc = sqlite3OsFileSize(pPager->jfd, &pPager->stmtJSize);
21938 if( rc ) goto stmt_begin_failed;
21939 assert( pPager->stmtJSize == pPager->journalOff );
21940 #endif
21941 pPager->stmtJSize = pPager->journalOff;
21942 pPager->stmtSize = pPager->dbSize;
21943 pPager->stmtHdrOff = 0;
21944 pPager->stmtCksum = pPager->cksumInit;
21945 if( !pPager->stmtOpen ){
21946 rc = sqlite3PagerOpentemp(&pPager->stfd);
21947 if( rc ) goto stmt_begin_failed;
21948 pPager->stmtOpen = 1;
21949 pPager->stmtNRec = 0;
21951 pPager->stmtInUse = 1;
21952 return SQLITE_OK;
21954 stmt_begin_failed:
21955 if( pPager->aInStmt ){
21956 sqliteFree(pPager->aInStmt);
21957 pPager->aInStmt = 0;
21959 return rc;
21963 ** Commit a statement.
21965 static int sqlite3PagerStmtCommit(Pager *pPager){
21966 if( pPager->stmtInUse ){
21967 PgHdr *pPg, *pNext;
21968 PAGERTRACE2("STMT-COMMIT %d\n", PAGERID(pPager));
21969 if( !MEMDB ){
21970 sqlite3OsSeek(pPager->stfd, 0);
21971 /* sqlite3OsTruncate(pPager->stfd, 0); */
21972 sqliteFree( pPager->aInStmt );
21973 pPager->aInStmt = 0;
21974 }else{
21975 for(pPg=pPager->pStmt; pPg; pPg=pNext){
21976 PgHistory *pHist = PGHDR_TO_HIST(pPg, pPager);
21977 pNext = pHist->pNextStmt;
21978 assert( pHist->inStmt );
21979 pHist->inStmt = 0;
21980 pHist->pPrevStmt = pHist->pNextStmt = 0;
21981 sqliteFree(pHist->pStmt);
21982 pHist->pStmt = 0;
21985 pPager->stmtNRec = 0;
21986 pPager->stmtInUse = 0;
21987 pPager->pStmt = 0;
21989 pPager->stmtAutoopen = 0;
21990 return SQLITE_OK;
21994 ** Rollback a statement.
21996 static int sqlite3PagerStmtRollback(Pager *pPager){
21997 int rc;
21998 if( pPager->stmtInUse ){
21999 PAGERTRACE2("STMT-ROLLBACK %d\n", PAGERID(pPager));
22000 if( MEMDB ){
22001 PgHdr *pPg;
22002 PgHistory *pHist;
22003 for(pPg=pPager->pStmt; pPg; pPg=pHist->pNextStmt){
22004 pHist = PGHDR_TO_HIST(pPg, pPager);
22005 if( pHist->pStmt ){
22006 memcpy(PGHDR_TO_DATA(pPg), pHist->pStmt, pPager->pageSize);
22007 sqliteFree(pHist->pStmt);
22008 pHist->pStmt = 0;
22011 pPager->dbSize = pPager->stmtSize;
22012 pager_truncate_cache(pPager);
22013 rc = SQLITE_OK;
22014 }else{
22015 rc = pager_stmt_playback(pPager);
22017 sqlite3PagerStmtCommit(pPager);
22018 }else{
22019 rc = SQLITE_OK;
22021 pPager->stmtAutoopen = 0;
22022 return rc;
22026 ** Return the full pathname of the database file.
22028 static const char *sqlite3PagerFilename(Pager *pPager){
22029 return pPager->zFilename;
22033 ** Return the directory of the database file.
22035 static const char *sqlite3PagerDirname(Pager *pPager){
22036 return pPager->zDirectory;
22040 ** Return the full pathname of the journal file.
22042 static const char *sqlite3PagerJournalname(Pager *pPager){
22043 return pPager->zJournal;
22047 ** Return true if fsync() calls are disabled for this pager. Return FALSE
22048 ** if fsync()s are executed normally.
22050 static int sqlite3PagerNosync(Pager *pPager){
22051 return pPager->noSync;
22054 #ifdef SQLITE_HAS_CODEC
22056 ** Set the codec for this pager
22058 static void sqlite3PagerSetCodec(
22059 Pager *pPager,
22060 void *(*xCodec)(void*,void*,Pgno,int),
22061 void *pCodecArg
22063 pPager->xCodec = xCodec;
22064 pPager->pCodecArg = pCodecArg;
22066 #endif
22068 #ifndef SQLITE_OMIT_AUTOVACUUM
22070 ** Move the page pPg to location pgno in the file.
22072 ** There must be no references to the page previously located at
22073 ** pgno (which we call pPgOld) though that page is allowed to be
22074 ** in cache. If the page previous located at pgno is not already
22075 ** in the rollback journal, it is not put there by by this routine.
22077 ** References to the page pPg remain valid. Updating any
22078 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
22079 ** allocated along with the page) is the responsibility of the caller.
22081 ** A transaction must be active when this routine is called. It used to be
22082 ** required that a statement transaction was not active, but this restriction
22083 ** has been removed (CREATE INDEX needs to move a page when a statement
22084 ** transaction is active).
22086 static int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno){
22087 PgHdr *pPgOld; /* The page being overwritten. */
22088 int h;
22089 Pgno needSyncPgno = 0;
22091 assert( pPg->nRef>0 );
22093 PAGERTRACE5("MOVE %d page %d (needSync=%d) moves to %d\n",
22094 PAGERID(pPager), pPg->pgno, pPg->needSync, pgno);
22095 IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
22097 pager_get_content(pPg);
22098 if( pPg->needSync ){
22099 needSyncPgno = pPg->pgno;
22100 assert( pPg->inJournal || (int)pgno>pPager->origDbSize );
22101 assert( pPg->dirty );
22102 assert( pPager->needSync );
22105 /* Unlink pPg from it's hash-chain */
22106 unlinkHashChain(pPager, pPg);
22108 /* If the cache contains a page with page-number pgno, remove it
22109 ** from it's hash chain. Also, if the PgHdr.needSync was set for
22110 ** page pgno before the 'move' operation, it needs to be retained
22111 ** for the page moved there.
22113 pPg->needSync = 0;
22114 pPgOld = pager_lookup(pPager, pgno);
22115 if( pPgOld ){
22116 assert( pPgOld->nRef==0 );
22117 unlinkHashChain(pPager, pPgOld);
22118 makeClean(pPgOld);
22119 pPg->needSync = pPgOld->needSync;
22120 }else{
22121 pPg->needSync = 0;
22123 if( pPager->aInJournal && (int)pgno<=pPager->origDbSize ){
22124 pPg->inJournal = (pPager->aInJournal[pgno/8] & (1<<(pgno&7)))!=0;
22125 }else{
22126 pPg->inJournal = 0;
22127 assert( pPg->needSync==0 || (int)pgno>pPager->origDbSize );
22130 /* Change the page number for pPg and insert it into the new hash-chain. */
22131 assert( pgno!=0 );
22132 pPg->pgno = pgno;
22133 h = pgno & (pPager->nHash-1);
22134 if( pPager->aHash[h] ){
22135 assert( pPager->aHash[h]->pPrevHash==0 );
22136 pPager->aHash[h]->pPrevHash = pPg;
22138 pPg->pNextHash = pPager->aHash[h];
22139 pPager->aHash[h] = pPg;
22140 pPg->pPrevHash = 0;
22142 makeDirty(pPg);
22143 pPager->dirtyCache = 1;
22145 if( needSyncPgno ){
22146 /* If needSyncPgno is non-zero, then the journal file needs to be
22147 ** sync()ed before any data is written to database file page needSyncPgno.
22148 ** Currently, no such page exists in the page-cache and the
22149 ** Pager.aInJournal bit has been set. This needs to be remedied by loading
22150 ** the page into the pager-cache and setting the PgHdr.needSync flag.
22152 ** The sqlite3PagerGet() call may cause the journal to sync. So make
22153 ** sure the Pager.needSync flag is set too.
22155 int rc;
22156 PgHdr *pPgHdr;
22157 assert( pPager->needSync );
22158 rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
22159 if( rc!=SQLITE_OK ) return rc;
22160 pPager->needSync = 1;
22161 pPgHdr->needSync = 1;
22162 pPgHdr->inJournal = 1;
22163 makeDirty(pPgHdr);
22164 sqlite3PagerUnref(pPgHdr);
22167 return SQLITE_OK;
22169 #endif
22172 ** Return a pointer to the data for the specified page.
22174 static void *sqlite3PagerGetData(DbPage *pPg){
22175 return PGHDR_TO_DATA(pPg);
22179 ** Return a pointer to the Pager.nExtra bytes of "extra" space
22180 ** allocated along with the specified page.
22182 static void *sqlite3PagerGetExtra(DbPage *pPg){
22183 Pager *pPager = pPg->pPager;
22184 return (pPager?PGHDR_TO_EXTRA(pPg, pPager):0);
22188 ** Get/set the locking-mode for this pager. Parameter eMode must be one
22189 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
22190 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
22191 ** the locking-mode is set to the value specified.
22193 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
22194 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
22195 ** locking-mode.
22197 static int sqlite3PagerLockingMode(Pager *pPager, int eMode){
22198 assert( eMode==PAGER_LOCKINGMODE_QUERY
22199 || eMode==PAGER_LOCKINGMODE_NORMAL
22200 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
22201 assert( PAGER_LOCKINGMODE_QUERY<0 );
22202 assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
22203 if( eMode>=0 && !pPager->tempFile ){
22204 pPager->exclusiveMode = eMode;
22206 return (int)pPager->exclusiveMode;
22209 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22211 ** Return the current state of the file lock for the given pager.
22212 ** The return value is one of NO_LOCK, SHARED_LOCK, RESERVED_LOCK,
22213 ** PENDING_LOCK, or EXCLUSIVE_LOCK.
22215 static int sqlite3PagerLockstate(Pager *pPager){
22216 return sqlite3OsLockState(pPager->fd);
22218 #endif
22220 #ifdef SQLITE_DEBUG
22222 ** Print a listing of all referenced pages and their ref count.
22224 static void sqlite3PagerRefdump(Pager *pPager){
22225 PgHdr *pPg;
22226 for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
22227 if( pPg->nRef<=0 ) continue;
22228 sqlite3DebugPrintf("PAGE %3d addr=%p nRef=%d\n",
22229 pPg->pgno, PGHDR_TO_DATA(pPg), pPg->nRef);
22232 #endif
22234 #endif /* SQLITE_OMIT_DISKIO */
22236 /************** End of pager.c ***********************************************/
22237 /************** Begin file btree.c *******************************************/
22239 ** 2004 April 6
22241 ** The author disclaims copyright to this source code. In place of
22242 ** a legal notice, here is a blessing:
22244 ** May you do good and not evil.
22245 ** May you find forgiveness for yourself and forgive others.
22246 ** May you share freely, never taking more than you give.
22248 *************************************************************************
22249 ** $Id: btree.c,v 1.388 2007/05/24 09:20:16 danielk1977 Exp $
22251 ** This file implements a external (disk-based) database using BTrees.
22252 ** See the header comment on "btreeInt.h" for additional information.
22253 ** Including a description of file format and an overview of operation.
22255 /************** Include btreeInt.h in the middle of btree.c ******************/
22256 /************** Begin file btreeInt.h ****************************************/
22258 ** 2004 April 6
22260 ** The author disclaims copyright to this source code. In place of
22261 ** a legal notice, here is a blessing:
22263 ** May you do good and not evil.
22264 ** May you find forgiveness for yourself and forgive others.
22265 ** May you share freely, never taking more than you give.
22267 *************************************************************************
22268 ** $Id: btreeInt.h,v 1.5 2007/06/15 12:06:59 drh Exp $
22270 ** This file implements a external (disk-based) database using BTrees.
22271 ** For a detailed discussion of BTrees, refer to
22273 ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
22274 ** "Sorting And Searching", pages 473-480. Addison-Wesley
22275 ** Publishing Company, Reading, Massachusetts.
22277 ** The basic idea is that each page of the file contains N database
22278 ** entries and N+1 pointers to subpages.
22280 ** ----------------------------------------------------------------
22281 ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
22282 ** ----------------------------------------------------------------
22284 ** All of the keys on the page that Ptr(0) points to have values less
22285 ** than Key(0). All of the keys on page Ptr(1) and its subpages have
22286 ** values greater than Key(0) and less than Key(1). All of the keys
22287 ** on Ptr(N) and its subpages have values greater than Key(N-1). And
22288 ** so forth.
22290 ** Finding a particular key requires reading O(log(M)) pages from the
22291 ** disk where M is the number of entries in the tree.
22293 ** In this implementation, a single file can hold one or more separate
22294 ** BTrees. Each BTree is identified by the index of its root page. The
22295 ** key and data for any entry are combined to form the "payload". A
22296 ** fixed amount of payload can be carried directly on the database
22297 ** page. If the payload is larger than the preset amount then surplus
22298 ** bytes are stored on overflow pages. The payload for an entry
22299 ** and the preceding pointer are combined to form a "Cell". Each
22300 ** page has a small header which contains the Ptr(N) pointer and other
22301 ** information such as the size of key and data.
22303 ** FORMAT DETAILS
22305 ** The file is divided into pages. The first page is called page 1,
22306 ** the second is page 2, and so forth. A page number of zero indicates
22307 ** "no such page". The page size can be anything between 512 and 65536.
22308 ** Each page can be either a btree page, a freelist page or an overflow
22309 ** page.
22311 ** The first page is always a btree page. The first 100 bytes of the first
22312 ** page contain a special header (the "file header") that describes the file.
22313 ** The format of the file header is as follows:
22315 ** OFFSET SIZE DESCRIPTION
22316 ** 0 16 Header string: "SQLite format 3\000"
22317 ** 16 2 Page size in bytes.
22318 ** 18 1 File format write version
22319 ** 19 1 File format read version
22320 ** 20 1 Bytes of unused space at the end of each page
22321 ** 21 1 Max embedded payload fraction
22322 ** 22 1 Min embedded payload fraction
22323 ** 23 1 Min leaf payload fraction
22324 ** 24 4 File change counter
22325 ** 28 4 Reserved for future use
22326 ** 32 4 First freelist page
22327 ** 36 4 Number of freelist pages in the file
22328 ** 40 60 15 4-byte meta values passed to higher layers
22330 ** All of the integer values are big-endian (most significant byte first).
22332 ** The file change counter is incremented when the database is changed
22333 ** This counter allows other processes to know when the file has changed
22334 ** and thus when they need to flush their cache.
22336 ** The max embedded payload fraction is the amount of the total usable
22337 ** space in a page that can be consumed by a single cell for standard
22338 ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
22339 ** is to limit the maximum cell size so that at least 4 cells will fit
22340 ** on one page. Thus the default max embedded payload fraction is 64.
22342 ** If the payload for a cell is larger than the max payload, then extra
22343 ** payload is spilled to overflow pages. Once an overflow page is allocated,
22344 ** as many bytes as possible are moved into the overflow pages without letting
22345 ** the cell size drop below the min embedded payload fraction.
22347 ** The min leaf payload fraction is like the min embedded payload fraction
22348 ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
22349 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
22350 ** not specified in the header.
22352 ** Each btree pages is divided into three sections: The header, the
22353 ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
22354 ** file header that occurs before the page header.
22356 ** |----------------|
22357 ** | file header | 100 bytes. Page 1 only.
22358 ** |----------------|
22359 ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
22360 ** |----------------|
22361 ** | cell pointer | | 2 bytes per cell. Sorted order.
22362 ** | array | | Grows downward
22363 ** | | v
22364 ** |----------------|
22365 ** | unallocated |
22366 ** | space |
22367 ** |----------------| ^ Grows upwards
22368 ** | cell content | | Arbitrary order interspersed with freeblocks.
22369 ** | area | | and free space fragments.
22370 ** |----------------|
22372 ** The page headers looks like this:
22374 ** OFFSET SIZE DESCRIPTION
22375 ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
22376 ** 1 2 byte offset to the first freeblock
22377 ** 3 2 number of cells on this page
22378 ** 5 2 first byte of the cell content area
22379 ** 7 1 number of fragmented free bytes
22380 ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
22382 ** The flags define the format of this btree page. The leaf flag means that
22383 ** this page has no children. The zerodata flag means that this page carries
22384 ** only keys and no data. The intkey flag means that the key is a integer
22385 ** which is stored in the key size entry of the cell header rather than in
22386 ** the payload area.
22388 ** The cell pointer array begins on the first byte after the page header.
22389 ** The cell pointer array contains zero or more 2-byte numbers which are
22390 ** offsets from the beginning of the page to the cell content in the cell
22391 ** content area. The cell pointers occur in sorted order. The system strives
22392 ** to keep free space after the last cell pointer so that new cells can
22393 ** be easily added without having to defragment the page.
22395 ** Cell content is stored at the very end of the page and grows toward the
22396 ** beginning of the page.
22398 ** Unused space within the cell content area is collected into a linked list of
22399 ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
22400 ** to the first freeblock is given in the header. Freeblocks occur in
22401 ** increasing order. Because a freeblock must be at least 4 bytes in size,
22402 ** any group of 3 or fewer unused bytes in the cell content area cannot
22403 ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
22404 ** a fragment. The total number of bytes in all fragments is recorded.
22405 ** in the page header at offset 7.
22407 ** SIZE DESCRIPTION
22408 ** 2 Byte offset of the next freeblock
22409 ** 2 Bytes in this freeblock
22411 ** Cells are of variable length. Cells are stored in the cell content area at
22412 ** the end of the page. Pointers to the cells are in the cell pointer array
22413 ** that immediately follows the page header. Cells is not necessarily
22414 ** contiguous or in order, but cell pointers are contiguous and in order.
22416 ** Cell content makes use of variable length integers. A variable
22417 ** length integer is 1 to 9 bytes where the lower 7 bits of each
22418 ** byte are used. The integer consists of all bytes that have bit 8 set and
22419 ** the first byte with bit 8 clear. The most significant byte of the integer
22420 ** appears first. A variable-length integer may not be more than 9 bytes long.
22421 ** As a special case, all 8 bytes of the 9th byte are used as data. This
22422 ** allows a 64-bit integer to be encoded in 9 bytes.
22424 ** 0x00 becomes 0x00000000
22425 ** 0x7f becomes 0x0000007f
22426 ** 0x81 0x00 becomes 0x00000080
22427 ** 0x82 0x00 becomes 0x00000100
22428 ** 0x80 0x7f becomes 0x0000007f
22429 ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
22430 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
22432 ** Variable length integers are used for rowids and to hold the number of
22433 ** bytes of key and data in a btree cell.
22435 ** The content of a cell looks like this:
22437 ** SIZE DESCRIPTION
22438 ** 4 Page number of the left child. Omitted if leaf flag is set.
22439 ** var Number of bytes of data. Omitted if the zerodata flag is set.
22440 ** var Number of bytes of key. Or the key itself if intkey flag is set.
22441 ** * Payload
22442 ** 4 First page of the overflow chain. Omitted if no overflow
22444 ** Overflow pages form a linked list. Each page except the last is completely
22445 ** filled with data (pagesize - 4 bytes). The last page can have as little
22446 ** as 1 byte of data.
22448 ** SIZE DESCRIPTION
22449 ** 4 Page number of next overflow page
22450 ** * Data
22452 ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
22453 ** file header points to the first in a linked list of trunk page. Each trunk
22454 ** page points to multiple leaf pages. The content of a leaf page is
22455 ** unspecified. A trunk page looks like this:
22457 ** SIZE DESCRIPTION
22458 ** 4 Page number of next trunk page
22459 ** 4 Number of leaf pointers on this page
22460 ** * zero or more pages numbers of leaves
22463 /* Round up a number to the next larger multiple of 8. This is used
22464 ** to force 8-byte alignment on 64-bit architectures.
22466 #define ROUND8(x) ((x+7)&~7)
22469 /* The following value is the maximum cell size assuming a maximum page
22470 ** size give above.
22472 #define MX_CELL_SIZE(pBt) (pBt->pageSize-8)
22474 /* The maximum number of cells on a single page of the database. This
22475 ** assumes a minimum cell size of 3 bytes. Such small cells will be
22476 ** exceedingly rare, but they are possible.
22478 #define MX_CELL(pBt) ((pBt->pageSize-8)/3)
22480 /* Forward declarations */
22481 typedef struct MemPage MemPage;
22482 typedef struct BtLock BtLock;
22485 ** This is a magic string that appears at the beginning of every
22486 ** SQLite database in order to identify the file as a real database.
22488 ** You can change this value at compile-time by specifying a
22489 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
22490 ** header must be exactly 16 bytes including the zero-terminator so
22491 ** the string itself should be 15 characters long. If you change
22492 ** the header, then your custom library will not be able to read
22493 ** databases generated by the standard tools and the standard tools
22494 ** will not be able to read databases created by your custom library.
22496 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
22497 # define SQLITE_FILE_HEADER "SQLite format 3"
22498 #endif
22501 ** Page type flags. An ORed combination of these flags appear as the
22502 ** first byte of every BTree page.
22504 #define PTF_INTKEY 0x01
22505 #define PTF_ZERODATA 0x02
22506 #define PTF_LEAFDATA 0x04
22507 #define PTF_LEAF 0x08
22510 ** As each page of the file is loaded into memory, an instance of the following
22511 ** structure is appended and initialized to zero. This structure stores
22512 ** information about the page that is decoded from the raw file page.
22514 ** The pParent field points back to the parent page. This allows us to
22515 ** walk up the BTree from any leaf to the root. Care must be taken to
22516 ** unref() the parent page pointer when this page is no longer referenced.
22517 ** The pageDestructor() routine handles that chore.
22519 struct MemPage {
22520 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
22521 u8 idxShift; /* True if Cell indices have changed */
22522 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
22523 u8 intKey; /* True if intkey flag is set */
22524 u8 leaf; /* True if leaf flag is set */
22525 u8 zeroData; /* True if table stores keys only */
22526 u8 leafData; /* True if tables stores data on leaves only */
22527 u8 hasData; /* True if this page stores data */
22528 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
22529 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
22530 u16 maxLocal; /* Copy of Btree.maxLocal or Btree.maxLeaf */
22531 u16 minLocal; /* Copy of Btree.minLocal or Btree.minLeaf */
22532 u16 cellOffset; /* Index in aData of first cell pointer */
22533 u16 idxParent; /* Index in parent of this node */
22534 u16 nFree; /* Number of free bytes on the page */
22535 u16 nCell; /* Number of cells on this page, local and ovfl */
22536 struct _OvflCell { /* Cells that will not fit on aData[] */
22537 u8 *pCell; /* Pointers to the body of the overflow cell */
22538 u16 idx; /* Insert this cell before idx-th non-overflow cell */
22539 } aOvfl[5];
22540 BtShared *pBt; /* Pointer back to BTree structure */
22541 u8 *aData; /* Pointer back to the start of the page */
22542 DbPage *pDbPage; /* Pager page handle */
22543 Pgno pgno; /* Page number for this page */
22544 MemPage *pParent; /* The parent of this page. NULL for root */
22548 ** The in-memory image of a disk page has the auxiliary information appended
22549 ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
22550 ** that extra information.
22552 #define EXTRA_SIZE sizeof(MemPage)
22554 /* Btree handle */
22555 struct Btree {
22556 sqlite3 *pSqlite;
22557 BtShared *pBt;
22558 u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
22562 ** Btree.inTrans may take one of the following values.
22564 ** If the shared-data extension is enabled, there may be multiple users
22565 ** of the Btree structure. At most one of these may open a write transaction,
22566 ** but any number may have active read transactions. Variable Btree.pDb
22567 ** points to the handle that owns any current write-transaction.
22569 #define TRANS_NONE 0
22570 #define TRANS_READ 1
22571 #define TRANS_WRITE 2
22574 ** Everything we need to know about an open database
22576 struct BtShared {
22577 Pager *pPager; /* The page cache */
22578 BtCursor *pCursor; /* A list of all open cursors */
22579 MemPage *pPage1; /* First page of the database */
22580 u8 inStmt; /* True if we are in a statement subtransaction */
22581 u8 readOnly; /* True if the underlying file is readonly */
22582 u8 maxEmbedFrac; /* Maximum payload as % of total page size */
22583 u8 minEmbedFrac; /* Minimum payload as % of total page size */
22584 u8 minLeafFrac; /* Minimum leaf payload as % of total page size */
22585 u8 pageSizeFixed; /* True if the page size can no longer be changed */
22586 #ifndef SQLITE_OMIT_AUTOVACUUM
22587 u8 autoVacuum; /* True if auto-vacuum is enabled */
22588 u8 incrVacuum; /* True if incr-vacuum is enabled */
22589 Pgno nTrunc; /* Non-zero if the db will be truncated (incr vacuum) */
22590 #endif
22591 u16 pageSize; /* Total number of bytes on a page */
22592 u16 usableSize; /* Number of usable bytes on each page */
22593 int maxLocal; /* Maximum local payload in non-LEAFDATA tables */
22594 int minLocal; /* Minimum local payload in non-LEAFDATA tables */
22595 int maxLeaf; /* Maximum local payload in a LEAFDATA table */
22596 int minLeaf; /* Minimum local payload in a LEAFDATA table */
22597 BusyHandler *pBusyHandler; /* Callback for when there is lock contention */
22598 u8 inTransaction; /* Transaction state */
22599 int nRef; /* Number of references to this structure */
22600 int nTransaction; /* Number of open transactions (read + write) */
22601 void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
22602 void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
22603 #ifndef SQLITE_OMIT_SHARED_CACHE
22604 BtLock *pLock; /* List of locks held on this shared-btree struct */
22605 BtShared *pNext; /* Next in ThreadData.pBtree linked list */
22606 #endif
22610 ** An instance of the following structure is used to hold information
22611 ** about a cell. The parseCellPtr() function fills in this structure
22612 ** based on information extract from the raw disk page.
22614 typedef struct CellInfo CellInfo;
22615 struct CellInfo {
22616 u8 *pCell; /* Pointer to the start of cell content */
22617 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
22618 u32 nData; /* Number of bytes of data */
22619 u32 nPayload; /* Total amount of payload */
22620 u16 nHeader; /* Size of the cell content header in bytes */
22621 u16 nLocal; /* Amount of payload held locally */
22622 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
22623 u16 nSize; /* Size of the cell content on the main b-tree page */
22627 ** A cursor is a pointer to a particular entry in the BTree.
22628 ** The entry is identified by its MemPage and the index in
22629 ** MemPage.aCell[] of the entry.
22631 struct BtCursor {
22632 Btree *pBtree; /* The Btree to which this cursor belongs */
22633 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
22634 int (*xCompare)(void*,int,const void*,int,const void*); /* Key comp func */
22635 void *pArg; /* First arg to xCompare() */
22636 Pgno pgnoRoot; /* The root page of this tree */
22637 MemPage *pPage; /* Page that contains the entry */
22638 int idx; /* Index of the entry in pPage->aCell[] */
22639 CellInfo info; /* A parse of the cell we are pointing at */
22640 u8 wrFlag; /* True if writable */
22641 u8 eState; /* One of the CURSOR_XXX constants (see below) */
22642 void *pKey; /* Saved key that was cursor's last known position */
22643 i64 nKey; /* Size of pKey, or last integer key */
22644 int skip; /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
22645 #ifndef SQLITE_OMIT_INCRBLOB
22646 u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
22647 Pgno *aOverflow; /* Cache of overflow page locations */
22648 #endif
22652 ** Potential values for BtCursor.eState.
22654 ** CURSOR_VALID:
22655 ** Cursor points to a valid entry. getPayload() etc. may be called.
22657 ** CURSOR_INVALID:
22658 ** Cursor does not point to a valid entry. This can happen (for example)
22659 ** because the table is empty or because BtreeCursorFirst() has not been
22660 ** called.
22662 ** CURSOR_REQUIRESEEK:
22663 ** The table that this cursor was opened on still exists, but has been
22664 ** modified since the cursor was last used. The cursor position is saved
22665 ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
22666 ** this state, restoreOrClearCursorPosition() can be called to attempt to
22667 ** seek the cursor to the saved position.
22669 #define CURSOR_INVALID 0
22670 #define CURSOR_VALID 1
22671 #define CURSOR_REQUIRESEEK 2
22674 ** The TRACE macro will print high-level status information about the
22675 ** btree operation when the global variable sqlite3_btree_trace is
22676 ** enabled.
22678 #if SQLITE_TEST
22679 # define TRACE(X) if( sqlite3_btree_trace ){ printf X; fflush(stdout); }
22680 #else
22681 # define TRACE(X)
22682 #endif
22685 ** Routines to read and write variable-length integers. These used to
22686 ** be defined locally, but now we use the varint routines in the util.c
22687 ** file.
22689 #define getVarint sqlite3GetVarint
22690 #define getVarint32(A,B) ((*B=*(A))<=0x7f?1:sqlite3GetVarint32(A,B))
22691 #define putVarint sqlite3PutVarint
22693 /* The database page the PENDING_BYTE occupies. This page is never used.
22694 ** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
22695 ** should possibly be consolidated (presumably in pager.h).
22697 ** If disk I/O is omitted (meaning that the database is stored purely
22698 ** in memory) then there is no pending byte.
22700 #ifdef SQLITE_OMIT_DISKIO
22701 # define PENDING_BYTE_PAGE(pBt) 0x7fffffff
22702 #else
22703 # define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
22704 #endif
22707 ** A linked list of the following structures is stored at BtShared.pLock.
22708 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
22709 ** is opened on the table with root page BtShared.iTable. Locks are removed
22710 ** from this list when a transaction is committed or rolled back, or when
22711 ** a btree handle is closed.
22713 struct BtLock {
22714 Btree *pBtree; /* Btree handle holding this lock */
22715 Pgno iTable; /* Root page of table */
22716 u8 eLock; /* READ_LOCK or WRITE_LOCK */
22717 BtLock *pNext; /* Next in BtShared.pLock list */
22720 /* Candidate values for BtLock.eLock */
22721 #define READ_LOCK 1
22722 #define WRITE_LOCK 2
22725 ** These macros define the location of the pointer-map entry for a
22726 ** database page. The first argument to each is the number of usable
22727 ** bytes on each page of the database (often 1024). The second is the
22728 ** page number to look up in the pointer map.
22730 ** PTRMAP_PAGENO returns the database page number of the pointer-map
22731 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
22732 ** the offset of the requested map entry.
22734 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
22735 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
22736 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
22737 ** this test.
22739 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
22740 #define PTRMAP_PTROFFSET(pBt, pgno) (5*(pgno-ptrmapPageno(pBt, pgno)-1))
22741 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
22744 ** The pointer map is a lookup table that identifies the parent page for
22745 ** each child page in the database file. The parent page is the page that
22746 ** contains a pointer to the child. Every page in the database contains
22747 ** 0 or 1 parent pages. (In this context 'database page' refers
22748 ** to any page that is not part of the pointer map itself.) Each pointer map
22749 ** entry consists of a single byte 'type' and a 4 byte parent page number.
22750 ** The PTRMAP_XXX identifiers below are the valid types.
22752 ** The purpose of the pointer map is to facility moving pages from one
22753 ** position in the file to another as part of autovacuum. When a page
22754 ** is moved, the pointer in its parent must be updated to point to the
22755 ** new location. The pointer map is used to locate the parent page quickly.
22757 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
22758 ** used in this case.
22760 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
22761 ** is not used in this case.
22763 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
22764 ** overflow pages. The page number identifies the page that
22765 ** contains the cell with a pointer to this overflow page.
22767 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
22768 ** overflow pages. The page-number identifies the previous
22769 ** page in the overflow page list.
22771 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
22772 ** identifies the parent page in the btree.
22774 #define PTRMAP_ROOTPAGE 1
22775 #define PTRMAP_FREEPAGE 2
22776 #define PTRMAP_OVERFLOW1 3
22777 #define PTRMAP_OVERFLOW2 4
22778 #define PTRMAP_BTREE 5
22780 /* A bunch of assert() statements to check the transaction state variables
22781 ** of handle p (type Btree*) are internally consistent.
22783 #define btreeIntegrity(p) \
22784 assert( p->inTrans!=TRANS_NONE || p->pBt->nTransaction<p->pBt->nRef ); \
22785 assert( p->pBt->nTransaction<=p->pBt->nRef ); \
22786 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
22787 assert( p->pBt->inTransaction>=p->inTrans );
22791 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
22792 ** if the database supports auto-vacuum or not. Because it is used
22793 ** within an expression that is an argument to another macro
22794 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
22795 ** So, this macro is defined instead.
22797 #ifndef SQLITE_OMIT_AUTOVACUUM
22798 #define ISAUTOVACUUM (pBt->autoVacuum)
22799 #else
22800 #define ISAUTOVACUUM 0
22801 #endif
22805 ** This structure is passed around through all the sanity checking routines
22806 ** in order to keep track of some global state information.
22808 typedef struct IntegrityCk IntegrityCk;
22809 struct IntegrityCk {
22810 BtShared *pBt; /* The tree being checked out */
22811 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
22812 int nPage; /* Number of pages in the database */
22813 int *anRef; /* Number of times each page is referenced */
22814 int mxErr; /* Stop accumulating errors when this reaches zero */
22815 char *zErrMsg; /* An error message. NULL if no errors seen. */
22816 int nErr; /* Number of messages written to zErrMsg so far */
22820 ** Read or write a two- and four-byte big-endian integer values.
22822 #define get2byte(x) ((x)[0]<<8 | (x)[1])
22823 #define put2byte(p,v) ((p)[0] = (v)>>8, (p)[1] = (v))
22824 #define get4byte sqlite3Get4byte
22825 #define put4byte sqlite3Put4byte
22828 ** Internal routines that should be accessed by the btree layer only.
22830 static int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int);
22831 static int sqlite3BtreeInitPage(MemPage *pPage, MemPage *pParent);
22832 static void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*);
22833 static void sqlite3BtreeParseCell(MemPage*, int, CellInfo*);
22834 static u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell);
22835 static int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur);
22836 static void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur);
22837 static void sqlite3BtreeReleaseTempCursor(BtCursor *pCur);
22838 static int sqlite3BtreeIsRootPage(MemPage *pPage);
22839 static void sqlite3BtreeMoveToParent(BtCursor *pCur);
22841 /************** End of btreeInt.h ********************************************/
22842 /************** Continuing where we left off in btree.c **********************/
22845 ** The header string that appears at the beginning of every
22846 ** SQLite database.
22848 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
22852 ** Set this global variable to 1 to enable tracing using the TRACE
22853 ** macro.
22855 #if SQLITE_TEST
22856 int sqlite3_btree_trace=0; /* True to enable tracing */
22857 #endif
22860 ** Forward declaration
22862 static int checkReadLocks(Btree*,Pgno,BtCursor*);
22865 #ifdef SQLITE_OMIT_SHARED_CACHE
22867 ** The functions queryTableLock(), lockTable() and unlockAllTables()
22868 ** manipulate entries in the BtShared.pLock linked list used to store
22869 ** shared-cache table level locks. If the library is compiled with the
22870 ** shared-cache feature disabled, then there is only ever one user
22871 ** of each BtShared structure and so this locking is not necessary.
22872 ** So define the lock related functions as no-ops.
22874 #define queryTableLock(a,b,c) SQLITE_OK
22875 #define lockTable(a,b,c) SQLITE_OK
22876 #define unlockAllTables(a)
22877 #else
22880 ** Query to see if btree handle p may obtain a lock of type eLock
22881 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
22882 ** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
22883 ** SQLITE_LOCKED if not.
22885 static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
22886 BtShared *pBt = p->pBt;
22887 BtLock *pIter;
22889 /* This is a no-op if the shared-cache is not enabled */
22890 if( 0==sqlite3ThreadDataReadOnly()->useSharedData ){
22891 return SQLITE_OK;
22894 /* This (along with lockTable()) is where the ReadUncommitted flag is
22895 ** dealt with. If the caller is querying for a read-lock and the flag is
22896 ** set, it is unconditionally granted - even if there are write-locks
22897 ** on the table. If a write-lock is requested, the ReadUncommitted flag
22898 ** is not considered.
22900 ** In function lockTable(), if a read-lock is demanded and the
22901 ** ReadUncommitted flag is set, no entry is added to the locks list
22902 ** (BtShared.pLock).
22904 ** To summarize: If the ReadUncommitted flag is set, then read cursors do
22905 ** not create or respect table locks. The locking procedure for a
22906 ** write-cursor does not change.
22908 if(
22909 !p->pSqlite ||
22910 0==(p->pSqlite->flags&SQLITE_ReadUncommitted) ||
22911 eLock==WRITE_LOCK ||
22912 iTab==MASTER_ROOT
22914 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
22915 if( pIter->pBtree!=p && pIter->iTable==iTab &&
22916 (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
22917 return SQLITE_LOCKED;
22921 return SQLITE_OK;
22925 ** Add a lock on the table with root-page iTable to the shared-btree used
22926 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
22927 ** WRITE_LOCK.
22929 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
22930 ** SQLITE_NOMEM may also be returned.
22932 static int lockTable(Btree *p, Pgno iTable, u8 eLock){
22933 BtShared *pBt = p->pBt;
22934 BtLock *pLock = 0;
22935 BtLock *pIter;
22937 /* This is a no-op if the shared-cache is not enabled */
22938 if( 0==sqlite3ThreadDataReadOnly()->useSharedData ){
22939 return SQLITE_OK;
22942 assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
22944 /* If the read-uncommitted flag is set and a read-lock is requested,
22945 ** return early without adding an entry to the BtShared.pLock list. See
22946 ** comment in function queryTableLock() for more info on handling
22947 ** the ReadUncommitted flag.
22949 if(
22950 (p->pSqlite) &&
22951 (p->pSqlite->flags&SQLITE_ReadUncommitted) &&
22952 (eLock==READ_LOCK) &&
22953 iTable!=MASTER_ROOT
22955 return SQLITE_OK;
22958 /* First search the list for an existing lock on this table. */
22959 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
22960 if( pIter->iTable==iTable && pIter->pBtree==p ){
22961 pLock = pIter;
22962 break;
22966 /* If the above search did not find a BtLock struct associating Btree p
22967 ** with table iTable, allocate one and link it into the list.
22969 if( !pLock ){
22970 pLock = (BtLock *)sqliteMalloc(sizeof(BtLock));
22971 if( !pLock ){
22972 return SQLITE_NOMEM;
22974 pLock->iTable = iTable;
22975 pLock->pBtree = p;
22976 pLock->pNext = pBt->pLock;
22977 pBt->pLock = pLock;
22980 /* Set the BtLock.eLock variable to the maximum of the current lock
22981 ** and the requested lock. This means if a write-lock was already held
22982 ** and a read-lock requested, we don't incorrectly downgrade the lock.
22984 assert( WRITE_LOCK>READ_LOCK );
22985 if( eLock>pLock->eLock ){
22986 pLock->eLock = eLock;
22989 return SQLITE_OK;
22993 ** Release all the table locks (locks obtained via calls to the lockTable()
22994 ** procedure) held by Btree handle p.
22996 static void unlockAllTables(Btree *p){
22997 BtLock **ppIter = &p->pBt->pLock;
22999 /* If the shared-cache extension is not enabled, there should be no
23000 ** locks in the BtShared.pLock list, making this procedure a no-op. Assert
23001 ** that this is the case.
23003 assert( sqlite3ThreadDataReadOnly()->useSharedData || 0==*ppIter );
23005 while( *ppIter ){
23006 BtLock *pLock = *ppIter;
23007 if( pLock->pBtree==p ){
23008 *ppIter = pLock->pNext;
23009 sqliteFree(pLock);
23010 }else{
23011 ppIter = &pLock->pNext;
23015 #endif /* SQLITE_OMIT_SHARED_CACHE */
23017 static void releasePage(MemPage *pPage); /* Forward reference */
23019 #ifndef SQLITE_OMIT_INCRBLOB
23021 ** Invalidate the overflow page-list cache for cursor pCur, if any.
23023 static void invalidateOverflowCache(BtCursor *pCur){
23024 sqliteFree(pCur->aOverflow);
23025 pCur->aOverflow = 0;
23029 ** Invalidate the overflow page-list cache for all cursors opened
23030 ** on the shared btree structure pBt.
23032 static void invalidateAllOverflowCache(BtShared *pBt){
23033 BtCursor *p;
23034 for(p=pBt->pCursor; p; p=p->pNext){
23035 invalidateOverflowCache(p);
23038 #else
23039 #define invalidateOverflowCache(x)
23040 #define invalidateAllOverflowCache(x)
23041 #endif
23044 ** Save the current cursor position in the variables BtCursor.nKey
23045 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
23047 static int saveCursorPosition(BtCursor *pCur){
23048 int rc;
23050 assert( CURSOR_VALID==pCur->eState );
23051 assert( 0==pCur->pKey );
23053 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
23055 /* If this is an intKey table, then the above call to BtreeKeySize()
23056 ** stores the integer key in pCur->nKey. In this case this value is
23057 ** all that is required. Otherwise, if pCur is not open on an intKey
23058 ** table, then malloc space for and store the pCur->nKey bytes of key
23059 ** data.
23061 if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
23062 void *pKey = sqliteMalloc(pCur->nKey);
23063 if( pKey ){
23064 rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
23065 if( rc==SQLITE_OK ){
23066 pCur->pKey = pKey;
23067 }else{
23068 sqliteFree(pKey);
23070 }else{
23071 rc = SQLITE_NOMEM;
23074 assert( !pCur->pPage->intKey || !pCur->pKey );
23076 if( rc==SQLITE_OK ){
23077 releasePage(pCur->pPage);
23078 pCur->pPage = 0;
23079 pCur->eState = CURSOR_REQUIRESEEK;
23082 invalidateOverflowCache(pCur);
23083 return rc;
23087 ** Save the positions of all cursors except pExcept open on the table
23088 ** with root-page iRoot. Usually, this is called just before cursor
23089 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
23091 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
23092 BtCursor *p;
23093 for(p=pBt->pCursor; p; p=p->pNext){
23094 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
23095 p->eState==CURSOR_VALID ){
23096 int rc = saveCursorPosition(p);
23097 if( SQLITE_OK!=rc ){
23098 return rc;
23102 return SQLITE_OK;
23106 ** Clear the current cursor position.
23108 static void clearCursorPosition(BtCursor *pCur){
23109 sqliteFree(pCur->pKey);
23110 pCur->pKey = 0;
23111 pCur->eState = CURSOR_INVALID;
23115 ** Restore the cursor to the position it was in (or as close to as possible)
23116 ** when saveCursorPosition() was called. Note that this call deletes the
23117 ** saved position info stored by saveCursorPosition(), so there can be
23118 ** at most one effective restoreOrClearCursorPosition() call after each
23119 ** saveCursorPosition().
23121 ** If the second argument argument - doSeek - is false, then instead of
23122 ** returning the cursor to it's saved position, any saved position is deleted
23123 ** and the cursor state set to CURSOR_INVALID.
23125 static int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur){
23126 int rc;
23127 assert( pCur->eState==CURSOR_REQUIRESEEK );
23128 #ifndef SQLITE_OMIT_INCRBLOB
23129 if( pCur->isIncrblobHandle ){
23130 return SQLITE_ABORT;
23132 #endif
23133 pCur->eState = CURSOR_INVALID;
23134 rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
23135 if( rc==SQLITE_OK ){
23136 sqliteFree(pCur->pKey);
23137 pCur->pKey = 0;
23138 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
23140 return rc;
23143 #define restoreOrClearCursorPosition(p) \
23144 (p->eState==CURSOR_REQUIRESEEK ? \
23145 sqlite3BtreeRestoreOrClearCursorPosition(p) : \
23146 SQLITE_OK)
23148 #ifndef SQLITE_OMIT_AUTOVACUUM
23150 ** Given a page number of a regular database page, return the page
23151 ** number for the pointer-map page that contains the entry for the
23152 ** input page number.
23154 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
23155 int nPagesPerMapPage = (pBt->usableSize/5)+1;
23156 int iPtrMap = (pgno-2)/nPagesPerMapPage;
23157 int ret = (iPtrMap*nPagesPerMapPage) + 2;
23158 if( ret==PENDING_BYTE_PAGE(pBt) ){
23159 ret++;
23161 return ret;
23165 ** Write an entry into the pointer map.
23167 ** This routine updates the pointer map entry for page number 'key'
23168 ** so that it maps to type 'eType' and parent page number 'pgno'.
23169 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
23171 static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
23172 DbPage *pDbPage; /* The pointer map page */
23173 u8 *pPtrmap; /* The pointer map data */
23174 Pgno iPtrmap; /* The pointer map page number */
23175 int offset; /* Offset in pointer map page */
23176 int rc;
23178 /* The master-journal page number must never be used as a pointer map page */
23179 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
23181 assert( pBt->autoVacuum );
23182 if( key==0 ){
23183 return SQLITE_CORRUPT_BKPT;
23185 iPtrmap = PTRMAP_PAGENO(pBt, key);
23186 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
23187 if( rc!=SQLITE_OK ){
23188 return rc;
23190 offset = PTRMAP_PTROFFSET(pBt, key);
23191 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
23193 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
23194 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
23195 rc = sqlite3PagerWrite(pDbPage);
23196 if( rc==SQLITE_OK ){
23197 pPtrmap[offset] = eType;
23198 put4byte(&pPtrmap[offset+1], parent);
23202 sqlite3PagerUnref(pDbPage);
23203 return rc;
23207 ** Read an entry from the pointer map.
23209 ** This routine retrieves the pointer map entry for page 'key', writing
23210 ** the type and parent page number to *pEType and *pPgno respectively.
23211 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
23213 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
23214 DbPage *pDbPage; /* The pointer map page */
23215 int iPtrmap; /* Pointer map page index */
23216 u8 *pPtrmap; /* Pointer map page data */
23217 int offset; /* Offset of entry in pointer map */
23218 int rc;
23220 iPtrmap = PTRMAP_PAGENO(pBt, key);
23221 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
23222 if( rc!=0 ){
23223 return rc;
23225 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
23227 offset = PTRMAP_PTROFFSET(pBt, key);
23228 assert( pEType!=0 );
23229 *pEType = pPtrmap[offset];
23230 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
23232 sqlite3PagerUnref(pDbPage);
23233 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
23234 return SQLITE_OK;
23237 #endif /* SQLITE_OMIT_AUTOVACUUM */
23240 ** Given a btree page and a cell index (0 means the first cell on
23241 ** the page, 1 means the second cell, and so forth) return a pointer
23242 ** to the cell content.
23244 ** This routine works only for pages that do not contain overflow cells.
23246 #define findCell(pPage, iCell) \
23247 ((pPage)->aData + get2byte(&(pPage)->aData[(pPage)->cellOffset+2*(iCell)]))
23248 static u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell){
23249 u8 *data = pPage->aData;
23250 assert( iCell>=0 );
23251 assert( iCell<get2byte(&data[pPage->hdrOffset+3]) );
23252 return findCell(pPage, iCell);
23256 ** This a more complex version of sqlite3BtreeFindCell() that works for
23257 ** pages that do contain overflow cells. See insert
23259 static u8 *findOverflowCell(MemPage *pPage, int iCell){
23260 int i;
23261 for(i=pPage->nOverflow-1; i>=0; i--){
23262 int k;
23263 struct _OvflCell *pOvfl;
23264 pOvfl = &pPage->aOvfl[i];
23265 k = pOvfl->idx;
23266 if( k<=iCell ){
23267 if( k==iCell ){
23268 return pOvfl->pCell;
23270 iCell--;
23273 return findCell(pPage, iCell);
23277 ** Parse a cell content block and fill in the CellInfo structure. There
23278 ** are two versions of this function. sqlite3BtreeParseCell() takes a
23279 ** cell index as the second argument and sqlite3BtreeParseCellPtr()
23280 ** takes a pointer to the body of the cell as its second argument.
23282 ** Within this file, the parseCell() macro can be called instead of
23283 ** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
23285 static void sqlite3BtreeParseCellPtr(
23286 MemPage *pPage, /* Page containing the cell */
23287 u8 *pCell, /* Pointer to the cell text. */
23288 CellInfo *pInfo /* Fill in this structure */
23290 int n; /* Number bytes in cell content header */
23291 u32 nPayload; /* Number of bytes of cell payload */
23293 pInfo->pCell = pCell;
23294 assert( pPage->leaf==0 || pPage->leaf==1 );
23295 n = pPage->childPtrSize;
23296 assert( n==4-4*pPage->leaf );
23297 if( pPage->hasData ){
23298 n += getVarint32(&pCell[n], &nPayload);
23299 }else{
23300 nPayload = 0;
23302 pInfo->nData = nPayload;
23303 if( pPage->intKey ){
23304 n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
23305 }else{
23306 u32 x;
23307 n += getVarint32(&pCell[n], &x);
23308 pInfo->nKey = x;
23309 nPayload += x;
23311 pInfo->nPayload = nPayload;
23312 pInfo->nHeader = n;
23313 if( nPayload<=pPage->maxLocal ){
23314 /* This is the (easy) common case where the entire payload fits
23315 ** on the local page. No overflow is required.
23317 int nSize; /* Total size of cell content in bytes */
23318 pInfo->nLocal = nPayload;
23319 pInfo->iOverflow = 0;
23320 nSize = nPayload + n;
23321 if( nSize<4 ){
23322 nSize = 4; /* Minimum cell size is 4 */
23324 pInfo->nSize = nSize;
23325 }else{
23326 /* If the payload will not fit completely on the local page, we have
23327 ** to decide how much to store locally and how much to spill onto
23328 ** overflow pages. The strategy is to minimize the amount of unused
23329 ** space on overflow pages while keeping the amount of local storage
23330 ** in between minLocal and maxLocal.
23332 ** Warning: changing the way overflow payload is distributed in any
23333 ** way will result in an incompatible file format.
23335 int minLocal; /* Minimum amount of payload held locally */
23336 int maxLocal; /* Maximum amount of payload held locally */
23337 int surplus; /* Overflow payload available for local storage */
23339 minLocal = pPage->minLocal;
23340 maxLocal = pPage->maxLocal;
23341 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
23342 if( surplus <= maxLocal ){
23343 pInfo->nLocal = surplus;
23344 }else{
23345 pInfo->nLocal = minLocal;
23347 pInfo->iOverflow = pInfo->nLocal + n;
23348 pInfo->nSize = pInfo->iOverflow + 4;
23351 #define parseCell(pPage, iCell, pInfo) \
23352 sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
23353 static void sqlite3BtreeParseCell(
23354 MemPage *pPage, /* Page containing the cell */
23355 int iCell, /* The cell index. First cell is 0 */
23356 CellInfo *pInfo /* Fill in this structure */
23358 parseCell(pPage, iCell, pInfo);
23362 ** Compute the total number of bytes that a Cell needs in the cell
23363 ** data area of the btree-page. The return number includes the cell
23364 ** data header and the local payload, but not any overflow page or
23365 ** the space used by the cell pointer.
23367 #ifndef NDEBUG
23368 static int cellSize(MemPage *pPage, int iCell){
23369 CellInfo info;
23370 sqlite3BtreeParseCell(pPage, iCell, &info);
23371 return info.nSize;
23373 #endif
23374 static int cellSizePtr(MemPage *pPage, u8 *pCell){
23375 CellInfo info;
23376 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
23377 return info.nSize;
23380 #ifndef SQLITE_OMIT_AUTOVACUUM
23382 ** If the cell pCell, part of page pPage contains a pointer
23383 ** to an overflow page, insert an entry into the pointer-map
23384 ** for the overflow page.
23386 static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
23387 if( pCell ){
23388 CellInfo info;
23389 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
23390 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
23391 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
23392 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
23393 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
23396 return SQLITE_OK;
23399 ** If the cell with index iCell on page pPage contains a pointer
23400 ** to an overflow page, insert an entry into the pointer-map
23401 ** for the overflow page.
23403 static int ptrmapPutOvfl(MemPage *pPage, int iCell){
23404 u8 *pCell;
23405 pCell = findOverflowCell(pPage, iCell);
23406 return ptrmapPutOvflPtr(pPage, pCell);
23408 #endif
23412 ** Defragment the page given. All Cells are moved to the
23413 ** end of the page and all free space is collected into one
23414 ** big FreeBlk that occurs in between the header and cell
23415 ** pointer array and the cell content area.
23417 static int defragmentPage(MemPage *pPage){
23418 int i; /* Loop counter */
23419 int pc; /* Address of a i-th cell */
23420 int addr; /* Offset of first byte after cell pointer array */
23421 int hdr; /* Offset to the page header */
23422 int size; /* Size of a cell */
23423 int usableSize; /* Number of usable bytes on a page */
23424 int cellOffset; /* Offset to the cell pointer array */
23425 int brk; /* Offset to the cell content area */
23426 int nCell; /* Number of cells on the page */
23427 unsigned char *data; /* The page data */
23428 unsigned char *temp; /* Temp area for cell content */
23430 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
23431 assert( pPage->pBt!=0 );
23432 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
23433 assert( pPage->nOverflow==0 );
23434 temp = sqliteMalloc( pPage->pBt->pageSize );
23435 if( temp==0 ) return SQLITE_NOMEM;
23436 data = pPage->aData;
23437 hdr = pPage->hdrOffset;
23438 cellOffset = pPage->cellOffset;
23439 nCell = pPage->nCell;
23440 assert( nCell==get2byte(&data[hdr+3]) );
23441 usableSize = pPage->pBt->usableSize;
23442 brk = get2byte(&data[hdr+5]);
23443 memcpy(&temp[brk], &data[brk], usableSize - brk);
23444 brk = usableSize;
23445 for(i=0; i<nCell; i++){
23446 u8 *pAddr; /* The i-th cell pointer */
23447 pAddr = &data[cellOffset + i*2];
23448 pc = get2byte(pAddr);
23449 assert( pc<pPage->pBt->usableSize );
23450 size = cellSizePtr(pPage, &temp[pc]);
23451 brk -= size;
23452 memcpy(&data[brk], &temp[pc], size);
23453 put2byte(pAddr, brk);
23455 assert( brk>=cellOffset+2*nCell );
23456 put2byte(&data[hdr+5], brk);
23457 data[hdr+1] = 0;
23458 data[hdr+2] = 0;
23459 data[hdr+7] = 0;
23460 addr = cellOffset+2*nCell;
23461 memset(&data[addr], 0, brk-addr);
23462 sqliteFree(temp);
23463 return SQLITE_OK;
23467 ** Allocate nByte bytes of space on a page.
23469 ** Return the index into pPage->aData[] of the first byte of
23470 ** the new allocation. Or return 0 if there is not enough free
23471 ** space on the page to satisfy the allocation request.
23473 ** If the page contains nBytes of free space but does not contain
23474 ** nBytes of contiguous free space, then this routine automatically
23475 ** calls defragementPage() to consolidate all free space before
23476 ** allocating the new chunk.
23478 static int allocateSpace(MemPage *pPage, int nByte){
23479 int addr, pc, hdr;
23480 int size;
23481 int nFrag;
23482 int top;
23483 int nCell;
23484 int cellOffset;
23485 unsigned char *data;
23487 data = pPage->aData;
23488 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
23489 assert( pPage->pBt );
23490 if( nByte<4 ) nByte = 4;
23491 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
23492 pPage->nFree -= nByte;
23493 hdr = pPage->hdrOffset;
23495 nFrag = data[hdr+7];
23496 if( nFrag<60 ){
23497 /* Search the freelist looking for a slot big enough to satisfy the
23498 ** space request. */
23499 addr = hdr+1;
23500 while( (pc = get2byte(&data[addr]))>0 ){
23501 size = get2byte(&data[pc+2]);
23502 if( size>=nByte ){
23503 if( size<nByte+4 ){
23504 memcpy(&data[addr], &data[pc], 2);
23505 data[hdr+7] = nFrag + size - nByte;
23506 return pc;
23507 }else{
23508 put2byte(&data[pc+2], size-nByte);
23509 return pc + size - nByte;
23512 addr = pc;
23516 /* Allocate memory from the gap in between the cell pointer array
23517 ** and the cell content area.
23519 top = get2byte(&data[hdr+5]);
23520 nCell = get2byte(&data[hdr+3]);
23521 cellOffset = pPage->cellOffset;
23522 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
23523 if( defragmentPage(pPage) ) return 0;
23524 top = get2byte(&data[hdr+5]);
23526 top -= nByte;
23527 assert( cellOffset + 2*nCell <= top );
23528 put2byte(&data[hdr+5], top);
23529 return top;
23533 ** Return a section of the pPage->aData to the freelist.
23534 ** The first byte of the new free block is pPage->aDisk[start]
23535 ** and the size of the block is "size" bytes.
23537 ** Most of the effort here is involved in coalesing adjacent
23538 ** free blocks into a single big free block.
23540 static void freeSpace(MemPage *pPage, int start, int size){
23541 int addr, pbegin, hdr;
23542 unsigned char *data = pPage->aData;
23544 assert( pPage->pBt!=0 );
23545 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
23546 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
23547 assert( (start + size)<=pPage->pBt->usableSize );
23548 if( size<4 ) size = 4;
23550 #ifdef SQLITE_SECURE_DELETE
23551 /* Overwrite deleted information with zeros when the SECURE_DELETE
23552 ** option is enabled at compile-time */
23553 memset(&data[start], 0, size);
23554 #endif
23556 /* Add the space back into the linked list of freeblocks */
23557 hdr = pPage->hdrOffset;
23558 addr = hdr + 1;
23559 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
23560 assert( pbegin<=pPage->pBt->usableSize-4 );
23561 assert( pbegin>addr );
23562 addr = pbegin;
23564 assert( pbegin<=pPage->pBt->usableSize-4 );
23565 assert( pbegin>addr || pbegin==0 );
23566 put2byte(&data[addr], start);
23567 put2byte(&data[start], pbegin);
23568 put2byte(&data[start+2], size);
23569 pPage->nFree += size;
23571 /* Coalesce adjacent free blocks */
23572 addr = pPage->hdrOffset + 1;
23573 while( (pbegin = get2byte(&data[addr]))>0 ){
23574 int pnext, psize;
23575 assert( pbegin>addr );
23576 assert( pbegin<=pPage->pBt->usableSize-4 );
23577 pnext = get2byte(&data[pbegin]);
23578 psize = get2byte(&data[pbegin+2]);
23579 if( pbegin + psize + 3 >= pnext && pnext>0 ){
23580 int frag = pnext - (pbegin+psize);
23581 assert( frag<=data[pPage->hdrOffset+7] );
23582 data[pPage->hdrOffset+7] -= frag;
23583 put2byte(&data[pbegin], get2byte(&data[pnext]));
23584 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
23585 }else{
23586 addr = pbegin;
23590 /* If the cell content area begins with a freeblock, remove it. */
23591 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
23592 int top;
23593 pbegin = get2byte(&data[hdr+1]);
23594 memcpy(&data[hdr+1], &data[pbegin], 2);
23595 top = get2byte(&data[hdr+5]);
23596 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
23601 ** Decode the flags byte (the first byte of the header) for a page
23602 ** and initialize fields of the MemPage structure accordingly.
23604 static void decodeFlags(MemPage *pPage, int flagByte){
23605 BtShared *pBt; /* A copy of pPage->pBt */
23607 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
23608 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
23609 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
23610 pPage->leaf = (flagByte & PTF_LEAF)!=0;
23611 pPage->childPtrSize = 4*(pPage->leaf==0);
23612 pBt = pPage->pBt;
23613 if( flagByte & PTF_LEAFDATA ){
23614 pPage->leafData = 1;
23615 pPage->maxLocal = pBt->maxLeaf;
23616 pPage->minLocal = pBt->minLeaf;
23617 }else{
23618 pPage->leafData = 0;
23619 pPage->maxLocal = pBt->maxLocal;
23620 pPage->minLocal = pBt->minLocal;
23622 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
23626 ** Initialize the auxiliary information for a disk block.
23628 ** The pParent parameter must be a pointer to the MemPage which
23629 ** is the parent of the page being initialized. The root of a
23630 ** BTree has no parent and so for that page, pParent==NULL.
23632 ** Return SQLITE_OK on success. If we see that the page does
23633 ** not contain a well-formed database page, then return
23634 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
23635 ** guarantee that the page is well-formed. It only shows that
23636 ** we failed to detect any corruption.
23638 static int sqlite3BtreeInitPage(
23639 MemPage *pPage, /* The page to be initialized */
23640 MemPage *pParent /* The parent. Might be NULL */
23642 int pc; /* Address of a freeblock within pPage->aData[] */
23643 int hdr; /* Offset to beginning of page header */
23644 u8 *data; /* Equal to pPage->aData */
23645 BtShared *pBt; /* The main btree structure */
23646 int usableSize; /* Amount of usable space on each page */
23647 int cellOffset; /* Offset from start of page to first cell pointer */
23648 int nFree; /* Number of unused bytes on the page */
23649 int top; /* First byte of the cell content area */
23651 pBt = pPage->pBt;
23652 assert( pBt!=0 );
23653 assert( pParent==0 || pParent->pBt==pBt );
23654 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
23655 assert( pPage->aData == &((unsigned char*)pPage)[-pBt->pageSize] );
23656 if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
23657 /* The parent page should never change unless the file is corrupt */
23658 return SQLITE_CORRUPT_BKPT;
23660 if( pPage->isInit ) return SQLITE_OK;
23661 if( pPage->pParent==0 && pParent!=0 ){
23662 pPage->pParent = pParent;
23663 sqlite3PagerRef(pParent->pDbPage);
23665 hdr = pPage->hdrOffset;
23666 data = pPage->aData;
23667 decodeFlags(pPage, data[hdr]);
23668 pPage->nOverflow = 0;
23669 pPage->idxShift = 0;
23670 usableSize = pBt->usableSize;
23671 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
23672 top = get2byte(&data[hdr+5]);
23673 pPage->nCell = get2byte(&data[hdr+3]);
23674 if( pPage->nCell>MX_CELL(pBt) ){
23675 /* To many cells for a single page. The page must be corrupt */
23676 return SQLITE_CORRUPT_BKPT;
23678 if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
23679 /* All pages must have at least one cell, except for root pages */
23680 return SQLITE_CORRUPT_BKPT;
23683 /* Compute the total free space on the page */
23684 pc = get2byte(&data[hdr+1]);
23685 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
23686 while( pc>0 ){
23687 int next, size;
23688 if( pc>usableSize-4 ){
23689 /* Free block is off the page */
23690 return SQLITE_CORRUPT_BKPT;
23692 next = get2byte(&data[pc]);
23693 size = get2byte(&data[pc+2]);
23694 if( next>0 && next<=pc+size+3 ){
23695 /* Free blocks must be in accending order */
23696 return SQLITE_CORRUPT_BKPT;
23698 nFree += size;
23699 pc = next;
23701 pPage->nFree = nFree;
23702 if( nFree>=usableSize ){
23703 /* Free space cannot exceed total page size */
23704 return SQLITE_CORRUPT_BKPT;
23707 pPage->isInit = 1;
23708 return SQLITE_OK;
23712 ** Set up a raw page so that it looks like a database page holding
23713 ** no entries.
23715 static void zeroPage(MemPage *pPage, int flags){
23716 unsigned char *data = pPage->aData;
23717 BtShared *pBt = pPage->pBt;
23718 int hdr = pPage->hdrOffset;
23719 int first;
23721 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
23722 assert( &data[pBt->pageSize] == (unsigned char*)pPage );
23723 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
23724 memset(&data[hdr], 0, pBt->usableSize - hdr);
23725 data[hdr] = flags;
23726 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
23727 memset(&data[hdr+1], 0, 4);
23728 data[hdr+7] = 0;
23729 put2byte(&data[hdr+5], pBt->usableSize);
23730 pPage->nFree = pBt->usableSize - first;
23731 decodeFlags(pPage, flags);
23732 pPage->hdrOffset = hdr;
23733 pPage->cellOffset = first;
23734 pPage->nOverflow = 0;
23735 pPage->idxShift = 0;
23736 pPage->nCell = 0;
23737 pPage->isInit = 1;
23741 ** Get a page from the pager. Initialize the MemPage.pBt and
23742 ** MemPage.aData elements if needed.
23744 ** If the noContent flag is set, it means that we do not care about
23745 ** the content of the page at this time. So do not go to the disk
23746 ** to fetch the content. Just fill in the content with zeros for now.
23747 ** If in the future we call sqlite3PagerWrite() on this page, that
23748 ** means we have started to be concerned about content and the disk
23749 ** read should occur at that point.
23751 static int sqlite3BtreeGetPage(
23752 BtShared *pBt, /* The btree */
23753 Pgno pgno, /* Number of the page to fetch */
23754 MemPage **ppPage, /* Return the page in this parameter */
23755 int noContent /* Do not load page content if true */
23757 int rc;
23758 MemPage *pPage;
23759 DbPage *pDbPage;
23761 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
23762 if( rc ) return rc;
23763 pPage = (MemPage *)sqlite3PagerGetExtra(pDbPage);
23764 pPage->aData = sqlite3PagerGetData(pDbPage);
23765 pPage->pDbPage = pDbPage;
23766 pPage->pBt = pBt;
23767 pPage->pgno = pgno;
23768 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
23769 *ppPage = pPage;
23770 return SQLITE_OK;
23774 ** Get a page from the pager and initialize it. This routine
23775 ** is just a convenience wrapper around separate calls to
23776 ** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
23778 static int getAndInitPage(
23779 BtShared *pBt, /* The database file */
23780 Pgno pgno, /* Number of the page to get */
23781 MemPage **ppPage, /* Write the page pointer here */
23782 MemPage *pParent /* Parent of the page */
23784 int rc;
23785 if( pgno==0 ){
23786 return SQLITE_CORRUPT_BKPT;
23788 rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
23789 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
23790 rc = sqlite3BtreeInitPage(*ppPage, pParent);
23792 return rc;
23796 ** Release a MemPage. This should be called once for each prior
23797 ** call to sqlite3BtreeGetPage.
23799 static void releasePage(MemPage *pPage){
23800 if( pPage ){
23801 assert( pPage->aData );
23802 assert( pPage->pBt );
23803 assert( &pPage->aData[pPage->pBt->pageSize]==(unsigned char*)pPage );
23804 sqlite3PagerUnref(pPage->pDbPage);
23809 ** This routine is called when the reference count for a page
23810 ** reaches zero. We need to unref the pParent pointer when that
23811 ** happens.
23813 static void pageDestructor(DbPage *pData, int pageSize){
23814 MemPage *pPage;
23815 assert( (pageSize & 7)==0 );
23816 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
23817 if( pPage->pParent ){
23818 MemPage *pParent = pPage->pParent;
23819 pPage->pParent = 0;
23820 releasePage(pParent);
23822 pPage->isInit = 0;
23826 ** During a rollback, when the pager reloads information into the cache
23827 ** so that the cache is restored to its original state at the start of
23828 ** the transaction, for each page restored this routine is called.
23830 ** This routine needs to reset the extra data section at the end of the
23831 ** page to agree with the restored data.
23833 static void pageReinit(DbPage *pData, int pageSize){
23834 MemPage *pPage;
23835 assert( (pageSize & 7)==0 );
23836 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
23837 if( pPage->isInit ){
23838 pPage->isInit = 0;
23839 sqlite3BtreeInitPage(pPage, pPage->pParent);
23844 ** Open a database file.
23846 ** zFilename is the name of the database file. If zFilename is NULL
23847 ** a new database with a random name is created. This randomly named
23848 ** database file will be deleted when sqlite3BtreeClose() is called.
23850 static int sqlite3BtreeOpen(
23851 const char *zFilename, /* Name of the file containing the BTree database */
23852 sqlite3 *pSqlite, /* Associated database handle */
23853 Btree **ppBtree, /* Pointer to new Btree object written here */
23854 int flags /* Options */
23856 BtShared *pBt; /* Shared part of btree structure */
23857 Btree *p; /* Handle to return */
23858 int rc = SQLITE_OK;
23859 int nReserve;
23860 unsigned char zDbHeader[100];
23861 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
23862 const ThreadData *pTsdro;
23863 #endif
23865 /* Set the variable isMemdb to true for an in-memory database, or
23866 ** false for a file-based database. This symbol is only required if
23867 ** either of the shared-data or autovacuum features are compiled
23868 ** into the library.
23870 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
23871 #ifdef SQLITE_OMIT_MEMORYDB
23872 const int isMemdb = 0;
23873 #else
23874 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
23875 #endif
23876 #endif
23878 p = sqliteMalloc(sizeof(Btree));
23879 if( !p ){
23880 return SQLITE_NOMEM;
23882 p->inTrans = TRANS_NONE;
23883 p->pSqlite = pSqlite;
23885 /* Try to find an existing Btree structure opened on zFilename. */
23886 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
23887 pTsdro = sqlite3ThreadDataReadOnly();
23888 if( pTsdro->useSharedData && zFilename && !isMemdb ){
23889 char *zFullPathname = sqlite3OsFullPathname(zFilename);
23890 if( !zFullPathname ){
23891 sqliteFree(p);
23892 return SQLITE_NOMEM;
23894 for(pBt=pTsdro->pBtree; pBt; pBt=pBt->pNext){
23895 assert( pBt->nRef>0 );
23896 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager)) ){
23897 p->pBt = pBt;
23898 *ppBtree = p;
23899 pBt->nRef++;
23900 sqliteFree(zFullPathname);
23901 return SQLITE_OK;
23904 sqliteFree(zFullPathname);
23906 #endif
23909 ** The following asserts make sure that structures used by the btree are
23910 ** the right size. This is to guard against size changes that result
23911 ** when compiling on a different architecture.
23913 assert( sizeof(i64)==8 || sizeof(i64)==4 );
23914 assert( sizeof(u64)==8 || sizeof(u64)==4 );
23915 assert( sizeof(u32)==4 );
23916 assert( sizeof(u16)==2 );
23917 assert( sizeof(Pgno)==4 );
23919 pBt = sqliteMalloc( sizeof(*pBt) );
23920 if( pBt==0 ){
23921 rc = SQLITE_NOMEM;
23922 goto btree_open_out;
23924 rc = sqlite3PagerOpen(&pBt->pPager, zFilename, EXTRA_SIZE, flags);
23925 if( rc==SQLITE_OK ){
23926 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
23928 if( rc!=SQLITE_OK ){
23929 goto btree_open_out;
23931 p->pBt = pBt;
23933 sqlite3PagerSetDestructor(pBt->pPager, pageDestructor);
23934 sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
23935 pBt->pCursor = 0;
23936 pBt->pPage1 = 0;
23937 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
23938 pBt->pageSize = get2byte(&zDbHeader[16]);
23939 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
23940 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
23941 pBt->pageSize = SQLITE_DEFAULT_PAGE_SIZE;
23942 pBt->maxEmbedFrac = 64; /* 25% */
23943 pBt->minEmbedFrac = 32; /* 12.5% */
23944 pBt->minLeafFrac = 32; /* 12.5% */
23945 #ifndef SQLITE_OMIT_AUTOVACUUM
23946 /* If the magic name ":memory:" will create an in-memory database, then
23947 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
23948 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
23949 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
23950 ** regular file-name. In this case the auto-vacuum applies as per normal.
23952 if( zFilename && !isMemdb ){
23953 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
23954 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
23956 #endif
23957 nReserve = 0;
23958 }else{
23959 nReserve = zDbHeader[20];
23960 pBt->maxEmbedFrac = zDbHeader[21];
23961 pBt->minEmbedFrac = zDbHeader[22];
23962 pBt->minLeafFrac = zDbHeader[23];
23963 pBt->pageSizeFixed = 1;
23964 #ifndef SQLITE_OMIT_AUTOVACUUM
23965 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
23966 #endif
23968 pBt->usableSize = pBt->pageSize - nReserve;
23969 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
23970 sqlite3PagerSetPagesize(pBt->pPager, pBt->pageSize);
23972 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
23973 /* Add the new btree to the linked list starting at ThreadData.pBtree.
23974 ** There is no chance that a malloc() may fail inside of the
23975 ** sqlite3ThreadData() call, as the ThreadData structure must have already
23976 ** been allocated for pTsdro->useSharedData to be non-zero.
23978 if( pTsdro->useSharedData && zFilename && !isMemdb ){
23979 pBt->pNext = pTsdro->pBtree;
23980 sqlite3ThreadData()->pBtree = pBt;
23982 #endif
23983 pBt->nRef = 1;
23984 *ppBtree = p;
23986 btree_open_out:
23987 if( rc!=SQLITE_OK ){
23988 if( pBt && pBt->pPager ){
23989 sqlite3PagerClose(pBt->pPager);
23991 sqliteFree(pBt);
23992 sqliteFree(p);
23993 *ppBtree = 0;
23995 return rc;
23999 ** Close an open database and invalidate all cursors.
24001 static int sqlite3BtreeClose(Btree *p){
24002 BtShared *pBt = p->pBt;
24003 BtCursor *pCur;
24005 #ifndef SQLITE_OMIT_SHARED_CACHE
24006 ThreadData *pTsd;
24007 #endif
24009 /* Close all cursors opened via this handle. */
24010 pCur = pBt->pCursor;
24011 while( pCur ){
24012 BtCursor *pTmp = pCur;
24013 pCur = pCur->pNext;
24014 if( pTmp->pBtree==p ){
24015 sqlite3BtreeCloseCursor(pTmp);
24019 /* Rollback any active transaction and free the handle structure.
24020 ** The call to sqlite3BtreeRollback() drops any table-locks held by
24021 ** this handle.
24023 sqlite3BtreeRollback(p);
24024 sqliteFree(p);
24026 #ifndef SQLITE_OMIT_SHARED_CACHE
24027 /* If there are still other outstanding references to the shared-btree
24028 ** structure, return now. The remainder of this procedure cleans
24029 ** up the shared-btree.
24031 assert( pBt->nRef>0 );
24032 pBt->nRef--;
24033 if( pBt->nRef ){
24034 return SQLITE_OK;
24037 /* Remove the shared-btree from the thread wide list. Call
24038 ** ThreadDataReadOnly() and then cast away the const property of the
24039 ** pointer to avoid allocating thread data if it is not really required.
24041 pTsd = (ThreadData *)sqlite3ThreadDataReadOnly();
24042 if( pTsd->pBtree==pBt ){
24043 assert( pTsd==sqlite3ThreadData() );
24044 pTsd->pBtree = pBt->pNext;
24045 }else{
24046 BtShared *pPrev;
24047 for(pPrev=pTsd->pBtree; pPrev && pPrev->pNext!=pBt; pPrev=pPrev->pNext){}
24048 if( pPrev ){
24049 assert( pTsd==sqlite3ThreadData() );
24050 pPrev->pNext = pBt->pNext;
24053 #endif
24055 /* Close the pager and free the shared-btree structure */
24056 assert( !pBt->pCursor );
24057 sqlite3PagerClose(pBt->pPager);
24058 if( pBt->xFreeSchema && pBt->pSchema ){
24059 pBt->xFreeSchema(pBt->pSchema);
24061 sqliteFree(pBt->pSchema);
24062 sqliteFree(pBt);
24063 return SQLITE_OK;
24067 ** Change the busy handler callback function.
24069 static int sqlite3BtreeSetBusyHandler(Btree *p, BusyHandler *pHandler){
24070 BtShared *pBt = p->pBt;
24071 pBt->pBusyHandler = pHandler;
24072 sqlite3PagerSetBusyhandler(pBt->pPager, pHandler);
24073 return SQLITE_OK;
24077 ** Change the limit on the number of pages allowed in the cache.
24079 ** The maximum number of cache pages is set to the absolute
24080 ** value of mxPage. If mxPage is negative, the pager will
24081 ** operate asynchronously - it will not stop to do fsync()s
24082 ** to insure data is written to the disk surface before
24083 ** continuing. Transactions still work if synchronous is off,
24084 ** and the database cannot be corrupted if this program
24085 ** crashes. But if the operating system crashes or there is
24086 ** an abrupt power failure when synchronous is off, the database
24087 ** could be left in an inconsistent and unrecoverable state.
24088 ** Synchronous is on by default so database corruption is not
24089 ** normally a worry.
24091 static int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
24092 BtShared *pBt = p->pBt;
24093 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
24094 return SQLITE_OK;
24098 ** Change the way data is synced to disk in order to increase or decrease
24099 ** how well the database resists damage due to OS crashes and power
24100 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
24101 ** there is a high probability of damage) Level 2 is the default. There
24102 ** is a very low but non-zero probability of damage. Level 3 reduces the
24103 ** probability of damage to near zero but with a write performance reduction.
24105 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
24106 static int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
24107 BtShared *pBt = p->pBt;
24108 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
24109 return SQLITE_OK;
24111 #endif
24114 ** Return TRUE if the given btree is set to safety level 1. In other
24115 ** words, return TRUE if no sync() occurs on the disk files.
24117 static int sqlite3BtreeSyncDisabled(Btree *p){
24118 BtShared *pBt = p->pBt;
24119 assert( pBt && pBt->pPager );
24120 return sqlite3PagerNosync(pBt->pPager);
24123 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
24125 ** Change the default pages size and the number of reserved bytes per page.
24127 ** The page size must be a power of 2 between 512 and 65536. If the page
24128 ** size supplied does not meet this constraint then the page size is not
24129 ** changed.
24131 ** Page sizes are constrained to be a power of two so that the region
24132 ** of the database file used for locking (beginning at PENDING_BYTE,
24133 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
24134 ** at the beginning of a page.
24136 ** If parameter nReserve is less than zero, then the number of reserved
24137 ** bytes per page is left unchanged.
24139 static int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
24140 BtShared *pBt = p->pBt;
24141 if( pBt->pageSizeFixed ){
24142 return SQLITE_READONLY;
24144 if( nReserve<0 ){
24145 nReserve = pBt->pageSize - pBt->usableSize;
24147 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
24148 ((pageSize-1)&pageSize)==0 ){
24149 assert( (pageSize & 7)==0 );
24150 assert( !pBt->pPage1 && !pBt->pCursor );
24151 pBt->pageSize = sqlite3PagerSetPagesize(pBt->pPager, pageSize);
24153 pBt->usableSize = pBt->pageSize - nReserve;
24154 return SQLITE_OK;
24158 ** Return the currently defined page size
24160 static int sqlite3BtreeGetPageSize(Btree *p){
24161 return p->pBt->pageSize;
24163 static int sqlite3BtreeGetReserve(Btree *p){
24164 return p->pBt->pageSize - p->pBt->usableSize;
24168 ** Set the maximum page count for a database if mxPage is positive.
24169 ** No changes are made if mxPage is 0 or negative.
24170 ** Regardless of the value of mxPage, return the maximum page count.
24172 static int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
24173 return sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
24175 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
24178 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
24179 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
24180 ** is disabled. The default value for the auto-vacuum property is
24181 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
24183 static int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
24184 #ifdef SQLITE_OMIT_AUTOVACUUM
24185 return SQLITE_READONLY;
24186 #else
24187 BtShared *pBt = p->pBt;
24188 int av = (autoVacuum?1:0);
24189 int iv = (autoVacuum==BTREE_AUTOVACUUM_INCR?1:0);
24190 if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
24191 return SQLITE_READONLY;
24193 pBt->autoVacuum = av;
24194 pBt->incrVacuum = iv;
24195 return SQLITE_OK;
24196 #endif
24200 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
24201 ** enabled 1 is returned. Otherwise 0.
24203 static int sqlite3BtreeGetAutoVacuum(Btree *p){
24204 #ifdef SQLITE_OMIT_AUTOVACUUM
24205 return BTREE_AUTOVACUUM_NONE;
24206 #else
24207 return (
24208 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
24209 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
24210 BTREE_AUTOVACUUM_INCR
24212 #endif
24217 ** Get a reference to pPage1 of the database file. This will
24218 ** also acquire a readlock on that file.
24220 ** SQLITE_OK is returned on success. If the file is not a
24221 ** well-formed database file, then SQLITE_CORRUPT is returned.
24222 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
24223 ** is returned if we run out of memory.
24225 static int lockBtree(BtShared *pBt){
24226 int rc, pageSize;
24227 MemPage *pPage1;
24228 if( pBt->pPage1 ) return SQLITE_OK;
24229 rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
24230 if( rc!=SQLITE_OK ) return rc;
24233 /* Do some checking to help insure the file we opened really is
24234 ** a valid database file.
24236 rc = SQLITE_NOTADB;
24237 if( sqlite3PagerPagecount(pBt->pPager)>0 ){
24238 u8 *page1 = pPage1->aData;
24239 if( memcmp(page1, zMagicHeader, 16)!=0 ){
24240 goto page1_init_failed;
24242 if( page1[18]>1 ){
24243 pBt->readOnly = 1;
24245 if( page1[19]>1 ){
24246 goto page1_init_failed;
24248 pageSize = get2byte(&page1[16]);
24249 if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ){
24250 goto page1_init_failed;
24252 assert( (pageSize & 7)==0 );
24253 pBt->pageSize = pageSize;
24254 pBt->usableSize = pageSize - page1[20];
24255 if( pBt->usableSize<500 ){
24256 goto page1_init_failed;
24258 pBt->maxEmbedFrac = page1[21];
24259 pBt->minEmbedFrac = page1[22];
24260 pBt->minLeafFrac = page1[23];
24261 #ifndef SQLITE_OMIT_AUTOVACUUM
24262 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
24263 #endif
24266 /* maxLocal is the maximum amount of payload to store locally for
24267 ** a cell. Make sure it is small enough so that at least minFanout
24268 ** cells can will fit on one page. We assume a 10-byte page header.
24269 ** Besides the payload, the cell must store:
24270 ** 2-byte pointer to the cell
24271 ** 4-byte child pointer
24272 ** 9-byte nKey value
24273 ** 4-byte nData value
24274 ** 4-byte overflow page pointer
24275 ** So a cell consists of a 2-byte poiner, a header which is as much as
24276 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
24277 ** page pointer.
24279 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
24280 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
24281 pBt->maxLeaf = pBt->usableSize - 35;
24282 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
24283 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
24284 goto page1_init_failed;
24286 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
24287 pBt->pPage1 = pPage1;
24288 return SQLITE_OK;
24290 page1_init_failed:
24291 releasePage(pPage1);
24292 pBt->pPage1 = 0;
24293 return rc;
24297 ** This routine works like lockBtree() except that it also invokes the
24298 ** busy callback if there is lock contention.
24300 static int lockBtreeWithRetry(Btree *pRef){
24301 int rc = SQLITE_OK;
24302 if( pRef->inTrans==TRANS_NONE ){
24303 u8 inTransaction = pRef->pBt->inTransaction;
24304 btreeIntegrity(pRef);
24305 rc = sqlite3BtreeBeginTrans(pRef, 0);
24306 pRef->pBt->inTransaction = inTransaction;
24307 pRef->inTrans = TRANS_NONE;
24308 if( rc==SQLITE_OK ){
24309 pRef->pBt->nTransaction--;
24311 btreeIntegrity(pRef);
24313 return rc;
24318 ** If there are no outstanding cursors and we are not in the middle
24319 ** of a transaction but there is a read lock on the database, then
24320 ** this routine unrefs the first page of the database file which
24321 ** has the effect of releasing the read lock.
24323 ** If there are any outstanding cursors, this routine is a no-op.
24325 ** If there is a transaction in progress, this routine is a no-op.
24327 static void unlockBtreeIfUnused(BtShared *pBt){
24328 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
24329 if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
24330 if( pBt->pPage1->aData==0 ){
24331 MemPage *pPage = pBt->pPage1;
24332 pPage->aData = &((u8*)pPage)[-pBt->pageSize];
24333 pPage->pBt = pBt;
24334 pPage->pgno = 1;
24336 releasePage(pBt->pPage1);
24338 pBt->pPage1 = 0;
24339 pBt->inStmt = 0;
24344 ** Create a new database by initializing the first page of the
24345 ** file.
24347 static int newDatabase(BtShared *pBt){
24348 MemPage *pP1;
24349 unsigned char *data;
24350 int rc;
24351 if( sqlite3PagerPagecount(pBt->pPager)>0 ) return SQLITE_OK;
24352 pP1 = pBt->pPage1;
24353 assert( pP1!=0 );
24354 data = pP1->aData;
24355 rc = sqlite3PagerWrite(pP1->pDbPage);
24356 if( rc ) return rc;
24357 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
24358 assert( sizeof(zMagicHeader)==16 );
24359 put2byte(&data[16], pBt->pageSize);
24360 data[18] = 1;
24361 data[19] = 1;
24362 data[20] = pBt->pageSize - pBt->usableSize;
24363 data[21] = pBt->maxEmbedFrac;
24364 data[22] = pBt->minEmbedFrac;
24365 data[23] = pBt->minLeafFrac;
24366 memset(&data[24], 0, 100-24);
24367 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
24368 pBt->pageSizeFixed = 1;
24369 #ifndef SQLITE_OMIT_AUTOVACUUM
24370 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
24371 put4byte(&data[36 + 4*4], pBt->autoVacuum);
24372 #endif
24373 return SQLITE_OK;
24377 ** Attempt to start a new transaction. A write-transaction
24378 ** is started if the second argument is nonzero, otherwise a read-
24379 ** transaction. If the second argument is 2 or more and exclusive
24380 ** transaction is started, meaning that no other process is allowed
24381 ** to access the database. A preexisting transaction may not be
24382 ** upgraded to exclusive by calling this routine a second time - the
24383 ** exclusivity flag only works for a new transaction.
24385 ** A write-transaction must be started before attempting any
24386 ** changes to the database. None of the following routines
24387 ** will work unless a transaction is started first:
24389 ** sqlite3BtreeCreateTable()
24390 ** sqlite3BtreeCreateIndex()
24391 ** sqlite3BtreeClearTable()
24392 ** sqlite3BtreeDropTable()
24393 ** sqlite3BtreeInsert()
24394 ** sqlite3BtreeDelete()
24395 ** sqlite3BtreeUpdateMeta()
24397 ** If an initial attempt to acquire the lock fails because of lock contention
24398 ** and the database was previously unlocked, then invoke the busy handler
24399 ** if there is one. But if there was previously a read-lock, do not
24400 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
24401 ** returned when there is already a read-lock in order to avoid a deadlock.
24403 ** Suppose there are two processes A and B. A has a read lock and B has
24404 ** a reserved lock. B tries to promote to exclusive but is blocked because
24405 ** of A's read lock. A tries to promote to reserved but is blocked by B.
24406 ** One or the other of the two processes must give way or there can be
24407 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
24408 ** when A already has a read lock, we encourage A to give up and let B
24409 ** proceed.
24411 static int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
24412 BtShared *pBt = p->pBt;
24413 int rc = SQLITE_OK;
24415 btreeIntegrity(p);
24417 /* If the btree is already in a write-transaction, or it
24418 ** is already in a read-transaction and a read-transaction
24419 ** is requested, this is a no-op.
24421 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
24422 return SQLITE_OK;
24425 /* Write transactions are not possible on a read-only database */
24426 if( pBt->readOnly && wrflag ){
24427 return SQLITE_READONLY;
24430 /* If another database handle has already opened a write transaction
24431 ** on this shared-btree structure and a second write transaction is
24432 ** requested, return SQLITE_BUSY.
24434 if( pBt->inTransaction==TRANS_WRITE && wrflag ){
24435 return SQLITE_BUSY;
24438 do {
24439 if( pBt->pPage1==0 ){
24440 rc = lockBtree(pBt);
24443 if( rc==SQLITE_OK && wrflag ){
24444 if( pBt->readOnly ){
24445 rc = SQLITE_READONLY;
24446 }else{
24447 rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
24448 if( rc==SQLITE_OK ){
24449 rc = newDatabase(pBt);
24454 if( rc==SQLITE_OK ){
24455 if( wrflag ) pBt->inStmt = 0;
24456 }else{
24457 unlockBtreeIfUnused(pBt);
24459 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
24460 sqlite3InvokeBusyHandler(pBt->pBusyHandler) );
24462 if( rc==SQLITE_OK ){
24463 if( p->inTrans==TRANS_NONE ){
24464 pBt->nTransaction++;
24466 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
24467 if( p->inTrans>pBt->inTransaction ){
24468 pBt->inTransaction = p->inTrans;
24472 btreeIntegrity(p);
24473 return rc;
24476 #ifndef SQLITE_OMIT_AUTOVACUUM
24479 ** Set the pointer-map entries for all children of page pPage. Also, if
24480 ** pPage contains cells that point to overflow pages, set the pointer
24481 ** map entries for the overflow pages as well.
24483 static int setChildPtrmaps(MemPage *pPage){
24484 int i; /* Counter variable */
24485 int nCell; /* Number of cells in page pPage */
24486 int rc; /* Return code */
24487 BtShared *pBt = pPage->pBt;
24488 int isInitOrig = pPage->isInit;
24489 Pgno pgno = pPage->pgno;
24491 rc = sqlite3BtreeInitPage(pPage, pPage->pParent);
24492 if( rc!=SQLITE_OK ){
24493 goto set_child_ptrmaps_out;
24495 nCell = pPage->nCell;
24497 for(i=0; i<nCell; i++){
24498 u8 *pCell = findCell(pPage, i);
24500 rc = ptrmapPutOvflPtr(pPage, pCell);
24501 if( rc!=SQLITE_OK ){
24502 goto set_child_ptrmaps_out;
24505 if( !pPage->leaf ){
24506 Pgno childPgno = get4byte(pCell);
24507 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
24508 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
24512 if( !pPage->leaf ){
24513 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
24514 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
24517 set_child_ptrmaps_out:
24518 pPage->isInit = isInitOrig;
24519 return rc;
24523 ** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
24524 ** page, is a pointer to page iFrom. Modify this pointer so that it points to
24525 ** iTo. Parameter eType describes the type of pointer to be modified, as
24526 ** follows:
24528 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
24529 ** page of pPage.
24531 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
24532 ** page pointed to by one of the cells on pPage.
24534 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
24535 ** overflow page in the list.
24537 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
24538 if( eType==PTRMAP_OVERFLOW2 ){
24539 /* The pointer is always the first 4 bytes of the page in this case. */
24540 if( get4byte(pPage->aData)!=iFrom ){
24541 return SQLITE_CORRUPT_BKPT;
24543 put4byte(pPage->aData, iTo);
24544 }else{
24545 int isInitOrig = pPage->isInit;
24546 int i;
24547 int nCell;
24549 sqlite3BtreeInitPage(pPage, 0);
24550 nCell = pPage->nCell;
24552 for(i=0; i<nCell; i++){
24553 u8 *pCell = findCell(pPage, i);
24554 if( eType==PTRMAP_OVERFLOW1 ){
24555 CellInfo info;
24556 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
24557 if( info.iOverflow ){
24558 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
24559 put4byte(&pCell[info.iOverflow], iTo);
24560 break;
24563 }else{
24564 if( get4byte(pCell)==iFrom ){
24565 put4byte(pCell, iTo);
24566 break;
24571 if( i==nCell ){
24572 if( eType!=PTRMAP_BTREE ||
24573 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
24574 return SQLITE_CORRUPT_BKPT;
24576 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
24579 pPage->isInit = isInitOrig;
24581 return SQLITE_OK;
24586 ** Move the open database page pDbPage to location iFreePage in the
24587 ** database. The pDbPage reference remains valid.
24589 static int relocatePage(
24590 BtShared *pBt, /* Btree */
24591 MemPage *pDbPage, /* Open page to move */
24592 u8 eType, /* Pointer map 'type' entry for pDbPage */
24593 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
24594 Pgno iFreePage /* The location to move pDbPage to */
24596 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
24597 Pgno iDbPage = pDbPage->pgno;
24598 Pager *pPager = pBt->pPager;
24599 int rc;
24601 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
24602 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
24604 /* Move page iDbPage from it's current location to page number iFreePage */
24605 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
24606 iDbPage, iFreePage, iPtrPage, eType));
24607 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage);
24608 if( rc!=SQLITE_OK ){
24609 return rc;
24611 pDbPage->pgno = iFreePage;
24613 /* If pDbPage was a btree-page, then it may have child pages and/or cells
24614 ** that point to overflow pages. The pointer map entries for all these
24615 ** pages need to be changed.
24617 ** If pDbPage is an overflow page, then the first 4 bytes may store a
24618 ** pointer to a subsequent overflow page. If this is the case, then
24619 ** the pointer map needs to be updated for the subsequent overflow page.
24621 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
24622 rc = setChildPtrmaps(pDbPage);
24623 if( rc!=SQLITE_OK ){
24624 return rc;
24626 }else{
24627 Pgno nextOvfl = get4byte(pDbPage->aData);
24628 if( nextOvfl!=0 ){
24629 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
24630 if( rc!=SQLITE_OK ){
24631 return rc;
24636 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
24637 ** that it points at iFreePage. Also fix the pointer map entry for
24638 ** iPtrPage.
24640 if( eType!=PTRMAP_ROOTPAGE ){
24641 rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
24642 if( rc!=SQLITE_OK ){
24643 return rc;
24645 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
24646 if( rc!=SQLITE_OK ){
24647 releasePage(pPtrPage);
24648 return rc;
24650 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
24651 releasePage(pPtrPage);
24652 if( rc==SQLITE_OK ){
24653 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
24656 return rc;
24659 /* Forward declaration required by incrVacuumStep(). */
24660 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
24663 ** Perform a single step of an incremental-vacuum. If successful,
24664 ** return SQLITE_OK. If there is no work to do (and therefore no
24665 ** point in calling this function again), return SQLITE_DONE.
24667 ** More specificly, this function attempts to re-organize the
24668 ** database so that the last page of the file currently in use
24669 ** is no longer in use.
24671 ** If the nFin parameter is non-zero, the implementation assumes
24672 ** that the caller will keep calling incrVacuumStep() until
24673 ** it returns SQLITE_DONE or an error, and that nFin is the
24674 ** number of pages the database file will contain after this
24675 ** process is complete.
24677 static int incrVacuumStep(BtShared *pBt, Pgno nFin){
24678 Pgno iLastPg; /* Last page in the database */
24679 Pgno nFreeList; /* Number of pages still on the free-list */
24681 iLastPg = pBt->nTrunc;
24682 if( iLastPg==0 ){
24683 iLastPg = sqlite3PagerPagecount(pBt->pPager);
24686 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
24687 int rc;
24688 u8 eType;
24689 Pgno iPtrPage;
24691 nFreeList = get4byte(&pBt->pPage1->aData[36]);
24692 if( nFreeList==0 || nFin==iLastPg ){
24693 return SQLITE_DONE;
24696 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
24697 if( rc!=SQLITE_OK ){
24698 return rc;
24700 if( eType==PTRMAP_ROOTPAGE ){
24701 return SQLITE_CORRUPT_BKPT;
24704 if( eType==PTRMAP_FREEPAGE ){
24705 if( nFin==0 ){
24706 /* Remove the page from the files free-list. This is not required
24707 ** if nFin is non-zero. In that case, the free-list will be
24708 ** truncated to zero after this function returns, so it doesn't
24709 ** matter if it still contains some garbage entries.
24711 Pgno iFreePg;
24712 MemPage *pFreePg;
24713 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
24714 if( rc!=SQLITE_OK ){
24715 return rc;
24717 assert( iFreePg==iLastPg );
24718 releasePage(pFreePg);
24720 } else {
24721 Pgno iFreePg; /* Index of free page to move pLastPg to */
24722 MemPage *pLastPg;
24724 rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
24725 if( rc!=SQLITE_OK ){
24726 return rc;
24729 /* If nFin is zero, this loop runs exactly once and page pLastPg
24730 ** is swapped with the first free page pulled off the free list.
24732 ** On the other hand, if nFin is greater than zero, then keep
24733 ** looping until a free-page located within the first nFin pages
24734 ** of the file is found.
24736 do {
24737 MemPage *pFreePg;
24738 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
24739 if( rc!=SQLITE_OK ){
24740 releasePage(pLastPg);
24741 return rc;
24743 releasePage(pFreePg);
24744 }while( nFin!=0 && iFreePg>nFin );
24745 assert( iFreePg<iLastPg );
24747 rc = sqlite3PagerWrite(pLastPg->pDbPage);
24748 if( rc!=SQLITE_OK ){
24749 return rc;
24751 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg);
24752 releasePage(pLastPg);
24753 if( rc!=SQLITE_OK ){
24754 return rc;
24759 pBt->nTrunc = iLastPg - 1;
24760 while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
24761 pBt->nTrunc--;
24763 return SQLITE_OK;
24767 ** A write-transaction must be opened before calling this function.
24768 ** It performs a single unit of work towards an incremental vacuum.
24770 ** If the incremental vacuum is finished after this function has run,
24771 ** SQLITE_DONE is returned. If it is not finished, but no error occured,
24772 ** SQLITE_OK is returned. Otherwise an SQLite error code.
24774 static int sqlite3BtreeIncrVacuum(Btree *p){
24775 BtShared *pBt = p->pBt;
24776 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
24777 if( !pBt->autoVacuum ){
24778 return SQLITE_DONE;
24780 invalidateAllOverflowCache(pBt);
24781 return incrVacuumStep(pBt, 0);
24785 ** This routine is called prior to sqlite3PagerCommit when a transaction
24786 ** is commited for an auto-vacuum database.
24788 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
24789 ** the database file should be truncated to during the commit process.
24790 ** i.e. the database has been reorganized so that only the first *pnTrunc
24791 ** pages are in use.
24793 static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
24794 int rc = SQLITE_OK;
24795 Pager *pPager = pBt->pPager;
24796 #ifndef NDEBUG
24797 int nRef = sqlite3PagerRefcount(pPager);
24798 #endif
24800 invalidateAllOverflowCache(pBt);
24801 assert(pBt->autoVacuum);
24802 if( !pBt->incrVacuum ){
24803 Pgno nFin = 0;
24805 if( pBt->nTrunc==0 ){
24806 Pgno nFree;
24807 Pgno nPtrmap;
24808 const int pgsz = pBt->pageSize;
24809 Pgno nOrig = sqlite3PagerPagecount(pBt->pPager);
24811 if( PTRMAP_ISPAGE(pBt, nOrig) ){
24812 return SQLITE_CORRUPT_BKPT;
24814 if( nOrig==PENDING_BYTE_PAGE(pBt) ){
24815 nOrig--;
24817 nFree = get4byte(&pBt->pPage1->aData[36]);
24818 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
24819 nFin = nOrig - nFree - nPtrmap;
24820 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
24821 nFin--;
24823 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
24824 nFin--;
24828 while( rc==SQLITE_OK ){
24829 rc = incrVacuumStep(pBt, nFin);
24831 if( rc==SQLITE_DONE ){
24832 assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
24833 rc = SQLITE_OK;
24834 if( pBt->nTrunc ){
24835 sqlite3PagerWrite(pBt->pPage1->pDbPage);
24836 put4byte(&pBt->pPage1->aData[32], 0);
24837 put4byte(&pBt->pPage1->aData[36], 0);
24838 pBt->nTrunc = nFin;
24841 if( rc!=SQLITE_OK ){
24842 sqlite3PagerRollback(pPager);
24846 if( rc==SQLITE_OK ){
24847 *pnTrunc = pBt->nTrunc;
24848 pBt->nTrunc = 0;
24850 assert( nRef==sqlite3PagerRefcount(pPager) );
24851 return rc;
24854 #endif
24857 ** This routine does the first phase of a two-phase commit. This routine
24858 ** causes a rollback journal to be created (if it does not already exist)
24859 ** and populated with enough information so that if a power loss occurs
24860 ** the database can be restored to its original state by playing back
24861 ** the journal. Then the contents of the journal are flushed out to
24862 ** the disk. After the journal is safely on oxide, the changes to the
24863 ** database are written into the database file and flushed to oxide.
24864 ** At the end of this call, the rollback journal still exists on the
24865 ** disk and we are still holding all locks, so the transaction has not
24866 ** committed. See sqlite3BtreeCommit() for the second phase of the
24867 ** commit process.
24869 ** This call is a no-op if no write-transaction is currently active on pBt.
24871 ** Otherwise, sync the database file for the btree pBt. zMaster points to
24872 ** the name of a master journal file that should be written into the
24873 ** individual journal file, or is NULL, indicating no master journal file
24874 ** (single database transaction).
24876 ** When this is called, the master journal should already have been
24877 ** created, populated with this journal pointer and synced to disk.
24879 ** Once this is routine has returned, the only thing required to commit
24880 ** the write-transaction for this database file is to delete the journal.
24882 static int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
24883 int rc = SQLITE_OK;
24884 if( p->inTrans==TRANS_WRITE ){
24885 BtShared *pBt = p->pBt;
24886 Pgno nTrunc = 0;
24887 #ifndef SQLITE_OMIT_AUTOVACUUM
24888 if( pBt->autoVacuum ){
24889 rc = autoVacuumCommit(pBt, &nTrunc);
24890 if( rc!=SQLITE_OK ){
24891 return rc;
24894 #endif
24895 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc);
24897 return rc;
24901 ** Commit the transaction currently in progress.
24903 ** This routine implements the second phase of a 2-phase commit. The
24904 ** sqlite3BtreeSync() routine does the first phase and should be invoked
24905 ** prior to calling this routine. The sqlite3BtreeSync() routine did
24906 ** all the work of writing information out to disk and flushing the
24907 ** contents so that they are written onto the disk platter. All this
24908 ** routine has to do is delete or truncate the rollback journal
24909 ** (which causes the transaction to commit) and drop locks.
24911 ** This will release the write lock on the database file. If there
24912 ** are no active cursors, it also releases the read lock.
24914 static int sqlite3BtreeCommitPhaseTwo(Btree *p){
24915 BtShared *pBt = p->pBt;
24917 btreeIntegrity(p);
24919 /* If the handle has a write-transaction open, commit the shared-btrees
24920 ** transaction and set the shared state to TRANS_READ.
24922 if( p->inTrans==TRANS_WRITE ){
24923 int rc;
24924 assert( pBt->inTransaction==TRANS_WRITE );
24925 assert( pBt->nTransaction>0 );
24926 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
24927 if( rc!=SQLITE_OK ){
24928 return rc;
24930 pBt->inTransaction = TRANS_READ;
24931 pBt->inStmt = 0;
24933 unlockAllTables(p);
24935 /* If the handle has any kind of transaction open, decrement the transaction
24936 ** count of the shared btree. If the transaction count reaches 0, set
24937 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
24938 ** will unlock the pager.
24940 if( p->inTrans!=TRANS_NONE ){
24941 pBt->nTransaction--;
24942 if( 0==pBt->nTransaction ){
24943 pBt->inTransaction = TRANS_NONE;
24947 /* Set the handles current transaction state to TRANS_NONE and unlock
24948 ** the pager if this call closed the only read or write transaction.
24950 p->inTrans = TRANS_NONE;
24951 unlockBtreeIfUnused(pBt);
24953 btreeIntegrity(p);
24954 return SQLITE_OK;
24958 ** Do both phases of a commit.
24960 static int sqlite3BtreeCommit(Btree *p){
24961 int rc;
24962 rc = sqlite3BtreeCommitPhaseOne(p, 0);
24963 if( rc==SQLITE_OK ){
24964 rc = sqlite3BtreeCommitPhaseTwo(p);
24966 return rc;
24969 #ifndef NDEBUG
24971 ** Return the number of write-cursors open on this handle. This is for use
24972 ** in assert() expressions, so it is only compiled if NDEBUG is not
24973 ** defined.
24975 static int countWriteCursors(BtShared *pBt){
24976 BtCursor *pCur;
24977 int r = 0;
24978 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
24979 if( pCur->wrFlag ) r++;
24981 return r;
24983 #endif
24986 ** Rollback the transaction in progress. All cursors will be
24987 ** invalided by this operation. Any attempt to use a cursor
24988 ** that was open at the beginning of this operation will result
24989 ** in an error.
24991 ** This will release the write lock on the database file. If there
24992 ** are no active cursors, it also releases the read lock.
24994 static int sqlite3BtreeRollback(Btree *p){
24995 int rc;
24996 BtShared *pBt = p->pBt;
24997 MemPage *pPage1;
24999 rc = saveAllCursors(pBt, 0, 0);
25000 #ifndef SQLITE_OMIT_SHARED_CACHE
25001 if( rc!=SQLITE_OK ){
25002 /* This is a horrible situation. An IO or malloc() error occured whilst
25003 ** trying to save cursor positions. If this is an automatic rollback (as
25004 ** the result of a constraint, malloc() failure or IO error) then
25005 ** the cache may be internally inconsistent (not contain valid trees) so
25006 ** we cannot simply return the error to the caller. Instead, abort
25007 ** all queries that may be using any of the cursors that failed to save.
25009 while( pBt->pCursor ){
25010 sqlite3 *db = pBt->pCursor->pBtree->pSqlite;
25011 if( db ){
25012 sqlite3AbortOtherActiveVdbes(db, 0);
25016 #endif
25017 btreeIntegrity(p);
25018 unlockAllTables(p);
25020 if( p->inTrans==TRANS_WRITE ){
25021 int rc2;
25023 #ifndef SQLITE_OMIT_AUTOVACUUM
25024 pBt->nTrunc = 0;
25025 #endif
25027 assert( TRANS_WRITE==pBt->inTransaction );
25028 rc2 = sqlite3PagerRollback(pBt->pPager);
25029 if( rc2!=SQLITE_OK ){
25030 rc = rc2;
25033 /* The rollback may have destroyed the pPage1->aData value. So
25034 ** call sqlite3BtreeGetPage() on page 1 again to make
25035 ** sure pPage1->aData is set correctly. */
25036 if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
25037 releasePage(pPage1);
25039 assert( countWriteCursors(pBt)==0 );
25040 pBt->inTransaction = TRANS_READ;
25043 if( p->inTrans!=TRANS_NONE ){
25044 assert( pBt->nTransaction>0 );
25045 pBt->nTransaction--;
25046 if( 0==pBt->nTransaction ){
25047 pBt->inTransaction = TRANS_NONE;
25051 p->inTrans = TRANS_NONE;
25052 pBt->inStmt = 0;
25053 unlockBtreeIfUnused(pBt);
25055 btreeIntegrity(p);
25056 return rc;
25060 ** Start a statement subtransaction. The subtransaction can
25061 ** can be rolled back independently of the main transaction.
25062 ** You must start a transaction before starting a subtransaction.
25063 ** The subtransaction is ended automatically if the main transaction
25064 ** commits or rolls back.
25066 ** Only one subtransaction may be active at a time. It is an error to try
25067 ** to start a new subtransaction if another subtransaction is already active.
25069 ** Statement subtransactions are used around individual SQL statements
25070 ** that are contained within a BEGIN...COMMIT block. If a constraint
25071 ** error occurs within the statement, the effect of that one statement
25072 ** can be rolled back without having to rollback the entire transaction.
25074 static int sqlite3BtreeBeginStmt(Btree *p){
25075 int rc;
25076 BtShared *pBt = p->pBt;
25077 if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
25078 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
25080 assert( pBt->inTransaction==TRANS_WRITE );
25081 rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
25082 pBt->inStmt = 1;
25083 return rc;
25088 ** Commit the statment subtransaction currently in progress. If no
25089 ** subtransaction is active, this is a no-op.
25091 static int sqlite3BtreeCommitStmt(Btree *p){
25092 int rc;
25093 BtShared *pBt = p->pBt;
25094 if( pBt->inStmt && !pBt->readOnly ){
25095 rc = sqlite3PagerStmtCommit(pBt->pPager);
25096 }else{
25097 rc = SQLITE_OK;
25099 pBt->inStmt = 0;
25100 return rc;
25104 ** Rollback the active statement subtransaction. If no subtransaction
25105 ** is active this routine is a no-op.
25107 ** All cursors will be invalidated by this operation. Any attempt
25108 ** to use a cursor that was open at the beginning of this operation
25109 ** will result in an error.
25111 static int sqlite3BtreeRollbackStmt(Btree *p){
25112 int rc = SQLITE_OK;
25113 BtShared *pBt = p->pBt;
25114 sqlite3MallocDisallow();
25115 if( pBt->inStmt && !pBt->readOnly ){
25116 rc = sqlite3PagerStmtRollback(pBt->pPager);
25117 assert( countWriteCursors(pBt)==0 );
25118 pBt->inStmt = 0;
25120 sqlite3MallocAllow();
25121 return rc;
25125 ** Default key comparison function to be used if no comparison function
25126 ** is specified on the sqlite3BtreeCursor() call.
25128 static int dfltCompare(
25129 void *NotUsed, /* User data is not used */
25130 int n1, const void *p1, /* First key to compare */
25131 int n2, const void *p2 /* Second key to compare */
25133 int c;
25134 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
25135 if( c==0 ){
25136 c = n1 - n2;
25138 return c;
25142 ** Create a new cursor for the BTree whose root is on the page
25143 ** iTable. The act of acquiring a cursor gets a read lock on
25144 ** the database file.
25146 ** If wrFlag==0, then the cursor can only be used for reading.
25147 ** If wrFlag==1, then the cursor can be used for reading or for
25148 ** writing if other conditions for writing are also met. These
25149 ** are the conditions that must be met in order for writing to
25150 ** be allowed:
25152 ** 1: The cursor must have been opened with wrFlag==1
25154 ** 2: Other database connections that share the same pager cache
25155 ** but which are not in the READ_UNCOMMITTED state may not have
25156 ** cursors open with wrFlag==0 on the same table. Otherwise
25157 ** the changes made by this write cursor would be visible to
25158 ** the read cursors in the other database connection.
25160 ** 3: The database must be writable (not on read-only media)
25162 ** 4: There must be an active transaction.
25164 ** No checking is done to make sure that page iTable really is the
25165 ** root page of a b-tree. If it is not, then the cursor acquired
25166 ** will not work correctly.
25168 ** The comparison function must be logically the same for every cursor
25169 ** on a particular table. Changing the comparison function will result
25170 ** in incorrect operations. If the comparison function is NULL, a
25171 ** default comparison function is used. The comparison function is
25172 ** always ignored for INTKEY tables.
25174 static int sqlite3BtreeCursor(
25175 Btree *p, /* The btree */
25176 int iTable, /* Root page of table to open */
25177 int wrFlag, /* 1 to write. 0 read-only */
25178 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
25179 void *pArg, /* First arg to xCompare() */
25180 BtCursor **ppCur /* Write new cursor here */
25182 int rc;
25183 BtCursor *pCur;
25184 BtShared *pBt = p->pBt;
25186 *ppCur = 0;
25187 if( wrFlag ){
25188 if( pBt->readOnly ){
25189 return SQLITE_READONLY;
25191 if( checkReadLocks(p, iTable, 0) ){
25192 return SQLITE_LOCKED;
25196 if( pBt->pPage1==0 ){
25197 rc = lockBtreeWithRetry(p);
25198 if( rc!=SQLITE_OK ){
25199 return rc;
25201 if( pBt->readOnly && wrFlag ){
25202 return SQLITE_READONLY;
25205 pCur = sqliteMalloc( sizeof(*pCur) );
25206 if( pCur==0 ){
25207 rc = SQLITE_NOMEM;
25208 goto create_cursor_exception;
25210 pCur->pgnoRoot = (Pgno)iTable;
25211 if( iTable==1 && sqlite3PagerPagecount(pBt->pPager)==0 ){
25212 rc = SQLITE_EMPTY;
25213 goto create_cursor_exception;
25215 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
25216 if( rc!=SQLITE_OK ){
25217 goto create_cursor_exception;
25220 /* Now that no other errors can occur, finish filling in the BtCursor
25221 ** variables, link the cursor into the BtShared list and set *ppCur (the
25222 ** output argument to this function).
25224 pCur->xCompare = xCmp ? xCmp : dfltCompare;
25225 pCur->pArg = pArg;
25226 pCur->pBtree = p;
25227 pCur->wrFlag = wrFlag;
25228 pCur->pNext = pBt->pCursor;
25229 if( pCur->pNext ){
25230 pCur->pNext->pPrev = pCur;
25232 pBt->pCursor = pCur;
25233 pCur->eState = CURSOR_INVALID;
25234 *ppCur = pCur;
25236 return SQLITE_OK;
25237 create_cursor_exception:
25238 if( pCur ){
25239 releasePage(pCur->pPage);
25240 sqliteFree(pCur);
25242 unlockBtreeIfUnused(pBt);
25243 return rc;
25247 ** Close a cursor. The read lock on the database file is released
25248 ** when the last cursor is closed.
25250 static int sqlite3BtreeCloseCursor(BtCursor *pCur){
25251 BtShared *pBt = pCur->pBtree->pBt;
25252 clearCursorPosition(pCur);
25253 if( pCur->pPrev ){
25254 pCur->pPrev->pNext = pCur->pNext;
25255 }else{
25256 pBt->pCursor = pCur->pNext;
25258 if( pCur->pNext ){
25259 pCur->pNext->pPrev = pCur->pPrev;
25261 releasePage(pCur->pPage);
25262 unlockBtreeIfUnused(pBt);
25263 invalidateOverflowCache(pCur);
25264 sqliteFree(pCur);
25265 return SQLITE_OK;
25269 ** Make a temporary cursor by filling in the fields of pTempCur.
25270 ** The temporary cursor is not on the cursor list for the Btree.
25272 static void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
25273 memcpy(pTempCur, pCur, sizeof(*pCur));
25274 pTempCur->pNext = 0;
25275 pTempCur->pPrev = 0;
25276 if( pTempCur->pPage ){
25277 sqlite3PagerRef(pTempCur->pPage->pDbPage);
25282 ** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
25283 ** function above.
25285 static void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
25286 if( pCur->pPage ){
25287 sqlite3PagerUnref(pCur->pPage->pDbPage);
25292 ** The GET_CELL_INFO() macro. Takes one argument, a pointer to a valid
25293 ** btree cursor (type BtCursor*). This macro makes sure the BtCursor.info
25294 ** field of the given cursor is valid. If it is not already valid, call
25295 ** sqlite3BtreeParseCell() to fill it in.
25297 ** BtCursor.info is a cache of the information in the current cell.
25298 ** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
25300 #ifndef NDEBUG
25301 static void assertCellInfo(BtCursor *pCur){
25302 CellInfo info;
25303 memset(&info, 0, sizeof(info));
25304 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &info);
25305 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
25307 #else
25308 #define assertCellInfo(x)
25309 #endif
25311 #define GET_CELL_INFO(pCur) \
25312 if( pCur->info.nSize==0 ) \
25313 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info); \
25314 else \
25315 assertCellInfo(pCur);
25319 ** Set *pSize to the size of the buffer needed to hold the value of
25320 ** the key for the current entry. If the cursor is not pointing
25321 ** to a valid entry, *pSize is set to 0.
25323 ** For a table with the INTKEY flag set, this routine returns the key
25324 ** itself, not the number of bytes in the key.
25326 static int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
25327 int rc = restoreOrClearCursorPosition(pCur);
25328 if( rc==SQLITE_OK ){
25329 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
25330 if( pCur->eState==CURSOR_INVALID ){
25331 *pSize = 0;
25332 }else{
25333 GET_CELL_INFO(pCur);
25334 *pSize = pCur->info.nKey;
25337 return rc;
25341 ** Set *pSize to the number of bytes of data in the entry the
25342 ** cursor currently points to. Always return SQLITE_OK.
25343 ** Failure is not possible. If the cursor is not currently
25344 ** pointing to an entry (which can happen, for example, if
25345 ** the database is empty) then *pSize is set to 0.
25347 static int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
25348 int rc = restoreOrClearCursorPosition(pCur);
25349 if( rc==SQLITE_OK ){
25350 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
25351 if( pCur->eState==CURSOR_INVALID ){
25352 /* Not pointing at a valid entry - set *pSize to 0. */
25353 *pSize = 0;
25354 }else{
25355 GET_CELL_INFO(pCur);
25356 *pSize = pCur->info.nData;
25359 return rc;
25363 ** Given the page number of an overflow page in the database (parameter
25364 ** ovfl), this function finds the page number of the next page in the
25365 ** linked list of overflow pages. If possible, it uses the auto-vacuum
25366 ** pointer-map data instead of reading the content of page ovfl to do so.
25368 ** If an error occurs an SQLite error code is returned. Otherwise:
25370 ** Unless pPgnoNext is NULL, the page number of the next overflow
25371 ** page in the linked list is written to *pPgnoNext. If page ovfl
25372 ** is the last page in it's linked list, *pPgnoNext is set to zero.
25374 ** If ppPage is not NULL, *ppPage is set to the MemPage* handle
25375 ** for page ovfl. The underlying pager page may have been requested
25376 ** with the noContent flag set, so the page data accessable via
25377 ** this handle may not be trusted.
25379 static int getOverflowPage(
25380 BtShared *pBt,
25381 Pgno ovfl, /* Overflow page */
25382 MemPage **ppPage, /* OUT: MemPage handle */
25383 Pgno *pPgnoNext /* OUT: Next overflow page number */
25385 Pgno next = 0;
25386 int rc;
25388 /* One of these must not be NULL. Otherwise, why call this function? */
25389 assert(ppPage || pPgnoNext);
25391 /* If pPgnoNext is NULL, then this function is being called to obtain
25392 ** a MemPage* reference only. No page-data is required in this case.
25394 if( !pPgnoNext ){
25395 return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
25398 #ifndef SQLITE_OMIT_AUTOVACUUM
25399 /* Try to find the next page in the overflow list using the
25400 ** autovacuum pointer-map pages. Guess that the next page in
25401 ** the overflow list is page number (ovfl+1). If that guess turns
25402 ** out to be wrong, fall back to loading the data of page
25403 ** number ovfl to determine the next page number.
25405 if( pBt->autoVacuum ){
25406 Pgno pgno;
25407 Pgno iGuess = ovfl+1;
25408 u8 eType;
25410 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
25411 iGuess++;
25414 if( iGuess<=sqlite3PagerPagecount(pBt->pPager) ){
25415 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
25416 if( rc!=SQLITE_OK ){
25417 return rc;
25419 if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
25420 next = iGuess;
25424 #endif
25426 if( next==0 || ppPage ){
25427 MemPage *pPage = 0;
25429 rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
25430 assert(rc==SQLITE_OK || pPage==0);
25431 if( next==0 && rc==SQLITE_OK ){
25432 next = get4byte(pPage->aData);
25435 if( ppPage ){
25436 *ppPage = pPage;
25437 }else{
25438 releasePage(pPage);
25441 *pPgnoNext = next;
25443 return rc;
25447 ** Copy data from a buffer to a page, or from a page to a buffer.
25449 ** pPayload is a pointer to data stored on database page pDbPage.
25450 ** If argument eOp is false, then nByte bytes of data are copied
25451 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
25452 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
25453 ** of data are copied from the buffer pBuf to pPayload.
25455 ** SQLITE_OK is returned on success, otherwise an error code.
25457 static int copyPayload(
25458 void *pPayload, /* Pointer to page data */
25459 void *pBuf, /* Pointer to buffer */
25460 int nByte, /* Number of bytes to copy */
25461 int eOp, /* 0 -> copy from page, 1 -> copy to page */
25462 DbPage *pDbPage /* Page containing pPayload */
25464 if( eOp ){
25465 /* Copy data from buffer to page (a write operation) */
25466 int rc = sqlite3PagerWrite(pDbPage);
25467 if( rc!=SQLITE_OK ){
25468 return rc;
25470 memcpy(pPayload, pBuf, nByte);
25471 }else{
25472 /* Copy data from page to buffer (a read operation) */
25473 memcpy(pBuf, pPayload, nByte);
25475 return SQLITE_OK;
25479 ** This function is used to read or overwrite payload information
25480 ** for the entry that the pCur cursor is pointing to. If the eOp
25481 ** parameter is 0, this is a read operation (data copied into
25482 ** buffer pBuf). If it is non-zero, a write (data copied from
25483 ** buffer pBuf).
25485 ** A total of "amt" bytes are read or written beginning at "offset".
25486 ** Data is read to or from the buffer pBuf.
25488 ** This routine does not make a distinction between key and data.
25489 ** It just reads or writes bytes from the payload area. Data might
25490 ** appear on the main page or be scattered out on multiple overflow
25491 ** pages.
25493 ** If the BtCursor.isIncrblobHandle flag is set, and the current
25494 ** cursor entry uses one or more overflow pages, this function
25495 ** allocates space for and lazily popluates the overflow page-list
25496 ** cache array (BtCursor.aOverflow). Subsequent calls use this
25497 ** cache to make seeking to the supplied offset more efficient.
25499 ** Once an overflow page-list cache has been allocated, it may be
25500 ** invalidated if some other cursor writes to the same table, or if
25501 ** the cursor is moved to a different row. Additionally, in auto-vacuum
25502 ** mode, the following events may invalidate an overflow page-list cache.
25504 ** * An incremental vacuum,
25505 ** * A commit in auto_vacuum="full" mode,
25506 ** * Creating a table (may require moving an overflow page).
25508 static int accessPayload(
25509 BtCursor *pCur, /* Cursor pointing to entry to read from */
25510 int offset, /* Begin reading this far into payload */
25511 int amt, /* Read this many bytes */
25512 unsigned char *pBuf, /* Write the bytes into this buffer */
25513 int skipKey, /* offset begins at data if this is true */
25514 int eOp /* zero to read. non-zero to write. */
25516 unsigned char *aPayload;
25517 int rc = SQLITE_OK;
25518 u32 nKey;
25519 int iIdx = 0;
25520 MemPage *pPage = pCur->pPage; /* Btree page of current cursor entry */
25521 BtShared *pBt = pCur->pBtree->pBt; /* Btree this cursor belongs to */
25523 assert( pPage );
25524 assert( pCur->eState==CURSOR_VALID );
25525 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
25526 assert( offset>=0 );
25528 GET_CELL_INFO(pCur);
25529 aPayload = pCur->info.pCell + pCur->info.nHeader;
25530 nKey = (pPage->intKey ? 0 : pCur->info.nKey);
25532 if( skipKey ){
25533 offset += nKey;
25535 if( offset+amt > nKey+pCur->info.nData ){
25536 /* Trying to read or write past the end of the data is an error */
25537 return SQLITE_ERROR;
25540 /* Check if data must be read/written to/from the btree page itself. */
25541 if( offset<pCur->info.nLocal ){
25542 int a = amt;
25543 if( a+offset>pCur->info.nLocal ){
25544 a = pCur->info.nLocal - offset;
25546 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
25547 offset = 0;
25548 pBuf += a;
25549 amt -= a;
25550 }else{
25551 offset -= pCur->info.nLocal;
25554 if( rc==SQLITE_OK && amt>0 ){
25555 const int ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
25556 Pgno nextPage;
25558 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
25560 #ifndef SQLITE_OMIT_INCRBLOB
25561 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
25562 ** has not been allocated, allocate it now. The array is sized at
25563 ** one entry for each overflow page in the overflow chain. The
25564 ** page number of the first overflow page is stored in aOverflow[0],
25565 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
25566 ** (the cache is lazily populated).
25568 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
25569 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
25570 pCur->aOverflow = (Pgno *)sqliteMalloc(sizeof(Pgno)*nOvfl);
25571 if( nOvfl && !pCur->aOverflow ){
25572 rc = SQLITE_NOMEM;
25576 /* If the overflow page-list cache has been allocated and the
25577 ** entry for the first required overflow page is valid, skip
25578 ** directly to it.
25580 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
25581 iIdx = (offset/ovflSize);
25582 nextPage = pCur->aOverflow[iIdx];
25583 offset = (offset%ovflSize);
25585 #endif
25587 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
25589 #ifndef SQLITE_OMIT_INCRBLOB
25590 /* If required, populate the overflow page-list cache. */
25591 if( pCur->aOverflow ){
25592 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
25593 pCur->aOverflow[iIdx] = nextPage;
25595 #endif
25597 if( offset>=ovflSize ){
25598 /* The only reason to read this page is to obtain the page
25599 ** number for the next page in the overflow chain. The page
25600 ** data is not required. So first try to lookup the overflow
25601 ** page-list cache, if any, then fall back to the getOverflowPage()
25602 ** function.
25604 #ifndef SQLITE_OMIT_INCRBLOB
25605 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
25606 nextPage = pCur->aOverflow[iIdx+1];
25607 } else
25608 #endif
25609 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
25610 offset -= ovflSize;
25611 }else{
25612 /* Need to read this page properly. It contains some of the
25613 ** range of data that is being read (eOp==0) or written (eOp!=0).
25615 DbPage *pDbPage;
25616 int a = amt;
25617 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
25618 if( rc==SQLITE_OK ){
25619 aPayload = sqlite3PagerGetData(pDbPage);
25620 nextPage = get4byte(aPayload);
25621 if( a + offset > ovflSize ){
25622 a = ovflSize - offset;
25624 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
25625 sqlite3PagerUnref(pDbPage);
25626 offset = 0;
25627 amt -= a;
25628 pBuf += a;
25634 if( rc==SQLITE_OK && amt>0 ){
25635 return SQLITE_CORRUPT_BKPT;
25637 return rc;
25641 ** Read part of the key associated with cursor pCur. Exactly
25642 ** "amt" bytes will be transfered into pBuf[]. The transfer
25643 ** begins at "offset".
25645 ** Return SQLITE_OK on success or an error code if anything goes
25646 ** wrong. An error is returned if "offset+amt" is larger than
25647 ** the available payload.
25649 static int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
25650 int rc = restoreOrClearCursorPosition(pCur);
25651 if( rc==SQLITE_OK ){
25652 assert( pCur->eState==CURSOR_VALID );
25653 assert( pCur->pPage!=0 );
25654 if( pCur->pPage->intKey ){
25655 return SQLITE_CORRUPT_BKPT;
25657 assert( pCur->pPage->intKey==0 );
25658 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
25659 rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
25661 return rc;
25665 ** Read part of the data associated with cursor pCur. Exactly
25666 ** "amt" bytes will be transfered into pBuf[]. The transfer
25667 ** begins at "offset".
25669 ** Return SQLITE_OK on success or an error code if anything goes
25670 ** wrong. An error is returned if "offset+amt" is larger than
25671 ** the available payload.
25673 static int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
25674 int rc = restoreOrClearCursorPosition(pCur);
25675 if( rc==SQLITE_OK ){
25676 assert( pCur->eState==CURSOR_VALID );
25677 assert( pCur->pPage!=0 );
25678 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
25679 rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
25681 return rc;
25685 ** Return a pointer to payload information from the entry that the
25686 ** pCur cursor is pointing to. The pointer is to the beginning of
25687 ** the key if skipKey==0 and it points to the beginning of data if
25688 ** skipKey==1. The number of bytes of available key/data is written
25689 ** into *pAmt. If *pAmt==0, then the value returned will not be
25690 ** a valid pointer.
25692 ** This routine is an optimization. It is common for the entire key
25693 ** and data to fit on the local page and for there to be no overflow
25694 ** pages. When that is so, this routine can be used to access the
25695 ** key and data without making a copy. If the key and/or data spills
25696 ** onto overflow pages, then accessPayload() must be used to reassembly
25697 ** the key/data and copy it into a preallocated buffer.
25699 ** The pointer returned by this routine looks directly into the cached
25700 ** page of the database. The data might change or move the next time
25701 ** any btree routine is called.
25703 static const unsigned char *fetchPayload(
25704 BtCursor *pCur, /* Cursor pointing to entry to read from */
25705 int *pAmt, /* Write the number of available bytes here */
25706 int skipKey /* read beginning at data if this is true */
25708 unsigned char *aPayload;
25709 MemPage *pPage;
25710 u32 nKey;
25711 int nLocal;
25713 assert( pCur!=0 && pCur->pPage!=0 );
25714 assert( pCur->eState==CURSOR_VALID );
25715 pPage = pCur->pPage;
25716 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
25717 GET_CELL_INFO(pCur);
25718 aPayload = pCur->info.pCell;
25719 aPayload += pCur->info.nHeader;
25720 if( pPage->intKey ){
25721 nKey = 0;
25722 }else{
25723 nKey = pCur->info.nKey;
25725 if( skipKey ){
25726 aPayload += nKey;
25727 nLocal = pCur->info.nLocal - nKey;
25728 }else{
25729 nLocal = pCur->info.nLocal;
25730 if( nLocal>nKey ){
25731 nLocal = nKey;
25734 *pAmt = nLocal;
25735 return aPayload;
25740 ** For the entry that cursor pCur is point to, return as
25741 ** many bytes of the key or data as are available on the local
25742 ** b-tree page. Write the number of available bytes into *pAmt.
25744 ** The pointer returned is ephemeral. The key/data may move
25745 ** or be destroyed on the next call to any Btree routine.
25747 ** These routines is used to get quick access to key and data
25748 ** in the common case where no overflow pages are used.
25750 static const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
25751 if( pCur->eState==CURSOR_VALID ){
25752 return (const void*)fetchPayload(pCur, pAmt, 0);
25754 return 0;
25756 static const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
25757 if( pCur->eState==CURSOR_VALID ){
25758 return (const void*)fetchPayload(pCur, pAmt, 1);
25760 return 0;
25765 ** Move the cursor down to a new child page. The newPgno argument is the
25766 ** page number of the child page to move to.
25768 static int moveToChild(BtCursor *pCur, u32 newPgno){
25769 int rc;
25770 MemPage *pNewPage;
25771 MemPage *pOldPage;
25772 BtShared *pBt = pCur->pBtree->pBt;
25774 assert( pCur->eState==CURSOR_VALID );
25775 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
25776 if( rc ) return rc;
25777 pNewPage->idxParent = pCur->idx;
25778 pOldPage = pCur->pPage;
25779 pOldPage->idxShift = 0;
25780 releasePage(pOldPage);
25781 pCur->pPage = pNewPage;
25782 pCur->idx = 0;
25783 pCur->info.nSize = 0;
25784 if( pNewPage->nCell<1 ){
25785 return SQLITE_CORRUPT_BKPT;
25787 return SQLITE_OK;
25791 ** Return true if the page is the virtual root of its table.
25793 ** The virtual root page is the root page for most tables. But
25794 ** for the table rooted on page 1, sometime the real root page
25795 ** is empty except for the right-pointer. In such cases the
25796 ** virtual root page is the page that the right-pointer of page
25797 ** 1 is pointing to.
25799 static int sqlite3BtreeIsRootPage(MemPage *pPage){
25800 MemPage *pParent = pPage->pParent;
25801 if( pParent==0 ) return 1;
25802 if( pParent->pgno>1 ) return 0;
25803 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
25804 return 0;
25808 ** Move the cursor up to the parent page.
25810 ** pCur->idx is set to the cell index that contains the pointer
25811 ** to the page we are coming from. If we are coming from the
25812 ** right-most child page then pCur->idx is set to one more than
25813 ** the largest cell index.
25815 static void sqlite3BtreeMoveToParent(BtCursor *pCur){
25816 MemPage *pParent;
25817 MemPage *pPage;
25818 int idxParent;
25820 assert( pCur->eState==CURSOR_VALID );
25821 pPage = pCur->pPage;
25822 assert( pPage!=0 );
25823 assert( !sqlite3BtreeIsRootPage(pPage) );
25824 pParent = pPage->pParent;
25825 assert( pParent!=0 );
25826 idxParent = pPage->idxParent;
25827 sqlite3PagerRef(pParent->pDbPage);
25828 releasePage(pPage);
25829 pCur->pPage = pParent;
25830 pCur->info.nSize = 0;
25831 assert( pParent->idxShift==0 );
25832 pCur->idx = idxParent;
25836 ** Move the cursor to the root page
25838 static int moveToRoot(BtCursor *pCur){
25839 MemPage *pRoot;
25840 int rc = SQLITE_OK;
25841 BtShared *pBt = pCur->pBtree->pBt;
25843 if( pCur->eState==CURSOR_REQUIRESEEK ){
25844 clearCursorPosition(pCur);
25846 pRoot = pCur->pPage;
25847 if( pRoot && pRoot->pgno==pCur->pgnoRoot ){
25848 assert( pRoot->isInit );
25849 }else{
25850 if(
25851 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
25853 pCur->eState = CURSOR_INVALID;
25854 return rc;
25856 releasePage(pCur->pPage);
25857 pCur->pPage = pRoot;
25859 pCur->idx = 0;
25860 pCur->info.nSize = 0;
25861 if( pRoot->nCell==0 && !pRoot->leaf ){
25862 Pgno subpage;
25863 assert( pRoot->pgno==1 );
25864 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
25865 assert( subpage>0 );
25866 pCur->eState = CURSOR_VALID;
25867 rc = moveToChild(pCur, subpage);
25869 pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
25870 return rc;
25874 ** Move the cursor down to the left-most leaf entry beneath the
25875 ** entry to which it is currently pointing.
25877 ** The left-most leaf is the one with the smallest key - the first
25878 ** in ascending order.
25880 static int moveToLeftmost(BtCursor *pCur){
25881 Pgno pgno;
25882 int rc;
25883 MemPage *pPage;
25885 assert( pCur->eState==CURSOR_VALID );
25886 while( !(pPage = pCur->pPage)->leaf ){
25887 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
25888 pgno = get4byte(findCell(pPage, pCur->idx));
25889 rc = moveToChild(pCur, pgno);
25890 if( rc ) return rc;
25892 return SQLITE_OK;
25896 ** Move the cursor down to the right-most leaf entry beneath the
25897 ** page to which it is currently pointing. Notice the difference
25898 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
25899 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
25900 ** finds the right-most entry beneath the *page*.
25902 ** The right-most entry is the one with the largest key - the last
25903 ** key in ascending order.
25905 static int moveToRightmost(BtCursor *pCur){
25906 Pgno pgno;
25907 int rc;
25908 MemPage *pPage;
25910 assert( pCur->eState==CURSOR_VALID );
25911 while( !(pPage = pCur->pPage)->leaf ){
25912 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
25913 pCur->idx = pPage->nCell;
25914 rc = moveToChild(pCur, pgno);
25915 if( rc ) return rc;
25917 pCur->idx = pPage->nCell - 1;
25918 pCur->info.nSize = 0;
25919 return SQLITE_OK;
25922 /* Move the cursor to the first entry in the table. Return SQLITE_OK
25923 ** on success. Set *pRes to 0 if the cursor actually points to something
25924 ** or set *pRes to 1 if the table is empty.
25926 static int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
25927 int rc;
25928 rc = moveToRoot(pCur);
25929 if( rc ) return rc;
25930 if( pCur->eState==CURSOR_INVALID ){
25931 assert( pCur->pPage->nCell==0 );
25932 *pRes = 1;
25933 return SQLITE_OK;
25935 assert( pCur->pPage->nCell>0 );
25936 *pRes = 0;
25937 rc = moveToLeftmost(pCur);
25938 return rc;
25941 /* Move the cursor to the last entry in the table. Return SQLITE_OK
25942 ** on success. Set *pRes to 0 if the cursor actually points to something
25943 ** or set *pRes to 1 if the table is empty.
25945 static int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
25946 int rc;
25947 rc = moveToRoot(pCur);
25948 if( rc ) return rc;
25949 if( CURSOR_INVALID==pCur->eState ){
25950 assert( pCur->pPage->nCell==0 );
25951 *pRes = 1;
25952 return SQLITE_OK;
25954 assert( pCur->eState==CURSOR_VALID );
25955 *pRes = 0;
25956 rc = moveToRightmost(pCur);
25957 return rc;
25960 /* Move the cursor so that it points to an entry near pKey/nKey.
25961 ** Return a success code.
25963 ** For INTKEY tables, only the nKey parameter is used. pKey is
25964 ** ignored. For other tables, nKey is the number of bytes of data
25965 ** in pKey. The comparison function specified when the cursor was
25966 ** created is used to compare keys.
25968 ** If an exact match is not found, then the cursor is always
25969 ** left pointing at a leaf page which would hold the entry if it
25970 ** were present. The cursor might point to an entry that comes
25971 ** before or after the key.
25973 ** The result of comparing the key with the entry to which the
25974 ** cursor is written to *pRes if pRes!=NULL. The meaning of
25975 ** this value is as follows:
25977 ** *pRes<0 The cursor is left pointing at an entry that
25978 ** is smaller than pKey or if the table is empty
25979 ** and the cursor is therefore left point to nothing.
25981 ** *pRes==0 The cursor is left pointing at an entry that
25982 ** exactly matches pKey.
25984 ** *pRes>0 The cursor is left pointing at an entry that
25985 ** is larger than pKey.
25987 static int sqlite3BtreeMoveto(
25988 BtCursor *pCur, /* The cursor to be moved */
25989 const void *pKey, /* The key content for indices. Not used by tables */
25990 i64 nKey, /* Size of pKey. Or the key for tables */
25991 int biasRight, /* If true, bias the search to the high end */
25992 int *pRes /* Search result flag */
25994 int rc;
25995 rc = moveToRoot(pCur);
25996 if( rc ) return rc;
25997 assert( pCur->pPage );
25998 assert( pCur->pPage->isInit );
25999 if( pCur->eState==CURSOR_INVALID ){
26000 *pRes = -1;
26001 assert( pCur->pPage->nCell==0 );
26002 return SQLITE_OK;
26004 for(;;){
26005 int lwr, upr;
26006 Pgno chldPg;
26007 MemPage *pPage = pCur->pPage;
26008 int c = -1; /* pRes return if table is empty must be -1 */
26009 lwr = 0;
26010 upr = pPage->nCell-1;
26011 if( !pPage->intKey && pKey==0 ){
26012 return SQLITE_CORRUPT_BKPT;
26014 if( biasRight ){
26015 pCur->idx = upr;
26016 }else{
26017 pCur->idx = (upr+lwr)/2;
26019 if( lwr<=upr ) for(;;){
26020 void *pCellKey;
26021 i64 nCellKey;
26022 pCur->info.nSize = 0;
26023 if( pPage->intKey ){
26024 u8 *pCell;
26025 pCell = findCell(pPage, pCur->idx) + pPage->childPtrSize;
26026 if( pPage->hasData ){
26027 u32 dummy;
26028 pCell += getVarint32(pCell, &dummy);
26030 getVarint(pCell, (u64 *)&nCellKey);
26031 if( nCellKey<nKey ){
26032 c = -1;
26033 }else if( nCellKey>nKey ){
26034 c = +1;
26035 }else{
26036 c = 0;
26038 }else{
26039 int available;
26040 pCellKey = (void *)fetchPayload(pCur, &available, 0);
26041 nCellKey = pCur->info.nKey;
26042 if( available>=nCellKey ){
26043 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
26044 }else{
26045 pCellKey = sqliteMallocRaw( nCellKey );
26046 if( pCellKey==0 ) return SQLITE_NOMEM;
26047 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
26048 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
26049 sqliteFree(pCellKey);
26050 if( rc ) return rc;
26053 if( c==0 ){
26054 if( pPage->leafData && !pPage->leaf ){
26055 lwr = pCur->idx;
26056 upr = lwr - 1;
26057 break;
26058 }else{
26059 if( pRes ) *pRes = 0;
26060 return SQLITE_OK;
26063 if( c<0 ){
26064 lwr = pCur->idx+1;
26065 }else{
26066 upr = pCur->idx-1;
26068 if( lwr>upr ){
26069 break;
26071 pCur->idx = (lwr+upr)/2;
26073 assert( lwr==upr+1 );
26074 assert( pPage->isInit );
26075 if( pPage->leaf ){
26076 chldPg = 0;
26077 }else if( lwr>=pPage->nCell ){
26078 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
26079 }else{
26080 chldPg = get4byte(findCell(pPage, lwr));
26082 if( chldPg==0 ){
26083 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
26084 if( pRes ) *pRes = c;
26085 return SQLITE_OK;
26087 pCur->idx = lwr;
26088 pCur->info.nSize = 0;
26089 rc = moveToChild(pCur, chldPg);
26090 if( rc ){
26091 return rc;
26094 /* NOT REACHED */
26098 ** Return TRUE if the cursor is not pointing at an entry of the table.
26100 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
26101 ** past the last entry in the table or sqlite3BtreePrev() moves past
26102 ** the first entry. TRUE is also returned if the table is empty.
26104 static int sqlite3BtreeEof(BtCursor *pCur){
26105 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
26106 ** have been deleted? This API will need to change to return an error code
26107 ** as well as the boolean result value.
26109 return (CURSOR_VALID!=pCur->eState);
26113 ** Advance the cursor to the next entry in the database. If
26114 ** successful then set *pRes=0. If the cursor
26115 ** was already pointing to the last entry in the database before
26116 ** this routine was called, then set *pRes=1.
26118 static int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
26119 int rc;
26120 MemPage *pPage;
26122 rc = restoreOrClearCursorPosition(pCur);
26123 if( rc!=SQLITE_OK ){
26124 return rc;
26126 assert( pRes!=0 );
26127 pPage = pCur->pPage;
26128 if( CURSOR_INVALID==pCur->eState ){
26129 *pRes = 1;
26130 return SQLITE_OK;
26132 if( pCur->skip>0 ){
26133 pCur->skip = 0;
26134 *pRes = 0;
26135 return SQLITE_OK;
26137 pCur->skip = 0;
26139 assert( pPage->isInit );
26140 assert( pCur->idx<pPage->nCell );
26142 pCur->idx++;
26143 pCur->info.nSize = 0;
26144 if( pCur->idx>=pPage->nCell ){
26145 if( !pPage->leaf ){
26146 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
26147 if( rc ) return rc;
26148 rc = moveToLeftmost(pCur);
26149 *pRes = 0;
26150 return rc;
26153 if( sqlite3BtreeIsRootPage(pPage) ){
26154 *pRes = 1;
26155 pCur->eState = CURSOR_INVALID;
26156 return SQLITE_OK;
26158 sqlite3BtreeMoveToParent(pCur);
26159 pPage = pCur->pPage;
26160 }while( pCur->idx>=pPage->nCell );
26161 *pRes = 0;
26162 if( pPage->leafData ){
26163 rc = sqlite3BtreeNext(pCur, pRes);
26164 }else{
26165 rc = SQLITE_OK;
26167 return rc;
26169 *pRes = 0;
26170 if( pPage->leaf ){
26171 return SQLITE_OK;
26173 rc = moveToLeftmost(pCur);
26174 return rc;
26178 ** Step the cursor to the back to the previous entry in the database. If
26179 ** successful then set *pRes=0. If the cursor
26180 ** was already pointing to the first entry in the database before
26181 ** this routine was called, then set *pRes=1.
26183 static int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
26184 int rc;
26185 Pgno pgno;
26186 MemPage *pPage;
26188 rc = restoreOrClearCursorPosition(pCur);
26189 if( rc!=SQLITE_OK ){
26190 return rc;
26192 if( CURSOR_INVALID==pCur->eState ){
26193 *pRes = 1;
26194 return SQLITE_OK;
26196 if( pCur->skip<0 ){
26197 pCur->skip = 0;
26198 *pRes = 0;
26199 return SQLITE_OK;
26201 pCur->skip = 0;
26203 pPage = pCur->pPage;
26204 assert( pPage->isInit );
26205 assert( pCur->idx>=0 );
26206 if( !pPage->leaf ){
26207 pgno = get4byte( findCell(pPage, pCur->idx) );
26208 rc = moveToChild(pCur, pgno);
26209 if( rc ) return rc;
26210 rc = moveToRightmost(pCur);
26211 }else{
26212 while( pCur->idx==0 ){
26213 if( sqlite3BtreeIsRootPage(pPage) ){
26214 pCur->eState = CURSOR_INVALID;
26215 *pRes = 1;
26216 return SQLITE_OK;
26218 sqlite3BtreeMoveToParent(pCur);
26219 pPage = pCur->pPage;
26221 pCur->idx--;
26222 pCur->info.nSize = 0;
26223 if( pPage->leafData && !pPage->leaf ){
26224 rc = sqlite3BtreePrevious(pCur, pRes);
26225 }else{
26226 rc = SQLITE_OK;
26229 *pRes = 0;
26230 return rc;
26234 ** Allocate a new page from the database file.
26236 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
26237 ** has already been called on the new page.) The new page has also
26238 ** been referenced and the calling routine is responsible for calling
26239 ** sqlite3PagerUnref() on the new page when it is done.
26241 ** SQLITE_OK is returned on success. Any other return value indicates
26242 ** an error. *ppPage and *pPgno are undefined in the event of an error.
26243 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
26245 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
26246 ** locate a page close to the page number "nearby". This can be used in an
26247 ** attempt to keep related pages close to each other in the database file,
26248 ** which in turn can make database access faster.
26250 ** If the "exact" parameter is not 0, and the page-number nearby exists
26251 ** anywhere on the free-list, then it is guarenteed to be returned. This
26252 ** is only used by auto-vacuum databases when allocating a new table.
26254 static int allocateBtreePage(
26255 BtShared *pBt,
26256 MemPage **ppPage,
26257 Pgno *pPgno,
26258 Pgno nearby,
26259 u8 exact
26261 MemPage *pPage1;
26262 int rc;
26263 int n; /* Number of pages on the freelist */
26264 int k; /* Number of leaves on the trunk of the freelist */
26265 MemPage *pTrunk = 0;
26266 MemPage *pPrevTrunk = 0;
26268 pPage1 = pBt->pPage1;
26269 n = get4byte(&pPage1->aData[36]);
26270 if( n>0 ){
26271 /* There are pages on the freelist. Reuse one of those pages. */
26272 Pgno iTrunk;
26273 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
26275 /* If the 'exact' parameter was true and a query of the pointer-map
26276 ** shows that the page 'nearby' is somewhere on the free-list, then
26277 ** the entire-list will be searched for that page.
26279 #ifndef SQLITE_OMIT_AUTOVACUUM
26280 if( exact && nearby<=sqlite3PagerPagecount(pBt->pPager) ){
26281 u8 eType;
26282 assert( nearby>0 );
26283 assert( pBt->autoVacuum );
26284 rc = ptrmapGet(pBt, nearby, &eType, 0);
26285 if( rc ) return rc;
26286 if( eType==PTRMAP_FREEPAGE ){
26287 searchList = 1;
26289 *pPgno = nearby;
26291 #endif
26293 /* Decrement the free-list count by 1. Set iTrunk to the index of the
26294 ** first free-list trunk page. iPrevTrunk is initially 1.
26296 rc = sqlite3PagerWrite(pPage1->pDbPage);
26297 if( rc ) return rc;
26298 put4byte(&pPage1->aData[36], n-1);
26300 /* The code within this loop is run only once if the 'searchList' variable
26301 ** is not true. Otherwise, it runs once for each trunk-page on the
26302 ** free-list until the page 'nearby' is located.
26304 do {
26305 pPrevTrunk = pTrunk;
26306 if( pPrevTrunk ){
26307 iTrunk = get4byte(&pPrevTrunk->aData[0]);
26308 }else{
26309 iTrunk = get4byte(&pPage1->aData[32]);
26311 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
26312 if( rc ){
26313 pTrunk = 0;
26314 goto end_allocate_page;
26317 k = get4byte(&pTrunk->aData[4]);
26318 if( k==0 && !searchList ){
26319 /* The trunk has no leaves and the list is not being searched.
26320 ** So extract the trunk page itself and use it as the newly
26321 ** allocated page */
26322 assert( pPrevTrunk==0 );
26323 rc = sqlite3PagerWrite(pTrunk->pDbPage);
26324 if( rc ){
26325 goto end_allocate_page;
26327 *pPgno = iTrunk;
26328 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
26329 *ppPage = pTrunk;
26330 pTrunk = 0;
26331 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
26332 }else if( k>pBt->usableSize/4 - 8 ){
26333 /* Value of k is out of range. Database corruption */
26334 rc = SQLITE_CORRUPT_BKPT;
26335 goto end_allocate_page;
26336 #ifndef SQLITE_OMIT_AUTOVACUUM
26337 }else if( searchList && nearby==iTrunk ){
26338 /* The list is being searched and this trunk page is the page
26339 ** to allocate, regardless of whether it has leaves.
26341 assert( *pPgno==iTrunk );
26342 *ppPage = pTrunk;
26343 searchList = 0;
26344 rc = sqlite3PagerWrite(pTrunk->pDbPage);
26345 if( rc ){
26346 goto end_allocate_page;
26348 if( k==0 ){
26349 if( !pPrevTrunk ){
26350 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
26351 }else{
26352 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
26354 }else{
26355 /* The trunk page is required by the caller but it contains
26356 ** pointers to free-list leaves. The first leaf becomes a trunk
26357 ** page in this case.
26359 MemPage *pNewTrunk;
26360 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
26361 rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
26362 if( rc!=SQLITE_OK ){
26363 goto end_allocate_page;
26365 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
26366 if( rc!=SQLITE_OK ){
26367 releasePage(pNewTrunk);
26368 goto end_allocate_page;
26370 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
26371 put4byte(&pNewTrunk->aData[4], k-1);
26372 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
26373 releasePage(pNewTrunk);
26374 if( !pPrevTrunk ){
26375 put4byte(&pPage1->aData[32], iNewTrunk);
26376 }else{
26377 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
26378 if( rc ){
26379 goto end_allocate_page;
26381 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
26384 pTrunk = 0;
26385 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
26386 #endif
26387 }else{
26388 /* Extract a leaf from the trunk */
26389 int closest;
26390 Pgno iPage;
26391 unsigned char *aData = pTrunk->aData;
26392 rc = sqlite3PagerWrite(pTrunk->pDbPage);
26393 if( rc ){
26394 goto end_allocate_page;
26396 if( nearby>0 ){
26397 int i, dist;
26398 closest = 0;
26399 dist = get4byte(&aData[8]) - nearby;
26400 if( dist<0 ) dist = -dist;
26401 for(i=1; i<k; i++){
26402 int d2 = get4byte(&aData[8+i*4]) - nearby;
26403 if( d2<0 ) d2 = -d2;
26404 if( d2<dist ){
26405 closest = i;
26406 dist = d2;
26409 }else{
26410 closest = 0;
26413 iPage = get4byte(&aData[8+closest*4]);
26414 if( !searchList || iPage==nearby ){
26415 *pPgno = iPage;
26416 if( *pPgno>sqlite3PagerPagecount(pBt->pPager) ){
26417 /* Free page off the end of the file */
26418 return SQLITE_CORRUPT_BKPT;
26420 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
26421 ": %d more free pages\n",
26422 *pPgno, closest+1, k, pTrunk->pgno, n-1));
26423 if( closest<k-1 ){
26424 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
26426 put4byte(&aData[4], k-1);
26427 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
26428 if( rc==SQLITE_OK ){
26429 sqlite3PagerDontRollback((*ppPage)->pDbPage);
26430 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
26431 if( rc!=SQLITE_OK ){
26432 releasePage(*ppPage);
26435 searchList = 0;
26438 releasePage(pPrevTrunk);
26439 pPrevTrunk = 0;
26440 }while( searchList );
26441 }else{
26442 /* There are no pages on the freelist, so create a new page at the
26443 ** end of the file */
26444 *pPgno = sqlite3PagerPagecount(pBt->pPager) + 1;
26446 #ifndef SQLITE_OMIT_AUTOVACUUM
26447 if( pBt->nTrunc ){
26448 /* An incr-vacuum has already run within this transaction. So the
26449 ** page to allocate is not from the physical end of the file, but
26450 ** at pBt->nTrunc.
26452 *pPgno = pBt->nTrunc+1;
26453 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
26454 (*pPgno)++;
26457 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
26458 /* If *pPgno refers to a pointer-map page, allocate two new pages
26459 ** at the end of the file instead of one. The first allocated page
26460 ** becomes a new pointer-map page, the second is used by the caller.
26462 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
26463 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
26464 (*pPgno)++;
26466 if( pBt->nTrunc ){
26467 pBt->nTrunc = *pPgno;
26469 #endif
26471 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
26472 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
26473 if( rc ) return rc;
26474 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
26475 if( rc!=SQLITE_OK ){
26476 releasePage(*ppPage);
26478 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
26481 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
26483 end_allocate_page:
26484 releasePage(pTrunk);
26485 releasePage(pPrevTrunk);
26486 return rc;
26490 ** Add a page of the database file to the freelist.
26492 ** sqlite3PagerUnref() is NOT called for pPage.
26494 static int freePage(MemPage *pPage){
26495 BtShared *pBt = pPage->pBt;
26496 MemPage *pPage1 = pBt->pPage1;
26497 int rc, n, k;
26499 /* Prepare the page for freeing */
26500 assert( pPage->pgno>1 );
26501 pPage->isInit = 0;
26502 releasePage(pPage->pParent);
26503 pPage->pParent = 0;
26505 /* Increment the free page count on pPage1 */
26506 rc = sqlite3PagerWrite(pPage1->pDbPage);
26507 if( rc ) return rc;
26508 n = get4byte(&pPage1->aData[36]);
26509 put4byte(&pPage1->aData[36], n+1);
26511 #ifdef SQLITE_SECURE_DELETE
26512 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
26513 ** always fully overwrite deleted information with zeros.
26515 rc = sqlite3PagerWrite(pPage->pDbPage);
26516 if( rc ) return rc;
26517 memset(pPage->aData, 0, pPage->pBt->pageSize);
26518 #endif
26520 #ifndef SQLITE_OMIT_AUTOVACUUM
26521 /* If the database supports auto-vacuum, write an entry in the pointer-map
26522 ** to indicate that the page is free.
26524 if( pBt->autoVacuum ){
26525 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
26526 if( rc ) return rc;
26528 #endif
26530 if( n==0 ){
26531 /* This is the first free page */
26532 rc = sqlite3PagerWrite(pPage->pDbPage);
26533 if( rc ) return rc;
26534 memset(pPage->aData, 0, 8);
26535 put4byte(&pPage1->aData[32], pPage->pgno);
26536 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
26537 }else{
26538 /* Other free pages already exist. Retrive the first trunk page
26539 ** of the freelist and find out how many leaves it has. */
26540 MemPage *pTrunk;
26541 rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
26542 if( rc ) return rc;
26543 k = get4byte(&pTrunk->aData[4]);
26544 if( k>=pBt->usableSize/4 - 8 ){
26545 /* The trunk is full. Turn the page being freed into a new
26546 ** trunk page with no leaves. */
26547 rc = sqlite3PagerWrite(pPage->pDbPage);
26548 if( rc ) return rc;
26549 put4byte(pPage->aData, pTrunk->pgno);
26550 put4byte(&pPage->aData[4], 0);
26551 put4byte(&pPage1->aData[32], pPage->pgno);
26552 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
26553 pPage->pgno, pTrunk->pgno));
26554 }else{
26555 /* Add the newly freed page as a leaf on the current trunk */
26556 rc = sqlite3PagerWrite(pTrunk->pDbPage);
26557 if( rc==SQLITE_OK ){
26558 put4byte(&pTrunk->aData[4], k+1);
26559 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
26560 #ifndef SQLITE_SECURE_DELETE
26561 sqlite3PagerDontWrite(pPage->pDbPage);
26562 #endif
26564 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
26566 releasePage(pTrunk);
26568 return rc;
26572 ** Free any overflow pages associated with the given Cell.
26574 static int clearCell(MemPage *pPage, unsigned char *pCell){
26575 BtShared *pBt = pPage->pBt;
26576 CellInfo info;
26577 Pgno ovflPgno;
26578 int rc;
26579 int nOvfl;
26580 int ovflPageSize;
26582 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
26583 if( info.iOverflow==0 ){
26584 return SQLITE_OK; /* No overflow pages. Return without doing anything */
26586 ovflPgno = get4byte(&pCell[info.iOverflow]);
26587 ovflPageSize = pBt->usableSize - 4;
26588 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
26589 assert( ovflPgno==0 || nOvfl>0 );
26590 while( nOvfl-- ){
26591 MemPage *pOvfl;
26592 if( ovflPgno==0 || ovflPgno>sqlite3PagerPagecount(pBt->pPager) ){
26593 return SQLITE_CORRUPT_BKPT;
26596 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
26597 if( rc ) return rc;
26598 rc = freePage(pOvfl);
26599 sqlite3PagerUnref(pOvfl->pDbPage);
26600 if( rc ) return rc;
26602 return SQLITE_OK;
26606 ** Create the byte sequence used to represent a cell on page pPage
26607 ** and write that byte sequence into pCell[]. Overflow pages are
26608 ** allocated and filled in as necessary. The calling procedure
26609 ** is responsible for making sure sufficient space has been allocated
26610 ** for pCell[].
26612 ** Note that pCell does not necessary need to point to the pPage->aData
26613 ** area. pCell might point to some temporary storage. The cell will
26614 ** be constructed in this temporary area then copied into pPage->aData
26615 ** later.
26617 static int fillInCell(
26618 MemPage *pPage, /* The page that contains the cell */
26619 unsigned char *pCell, /* Complete text of the cell */
26620 const void *pKey, i64 nKey, /* The key */
26621 const void *pData,int nData, /* The data */
26622 int nZero, /* Extra zero bytes to append to pData */
26623 int *pnSize /* Write cell size here */
26625 int nPayload;
26626 const u8 *pSrc;
26627 int nSrc, n, rc;
26628 int spaceLeft;
26629 MemPage *pOvfl = 0;
26630 MemPage *pToRelease = 0;
26631 unsigned char *pPrior;
26632 unsigned char *pPayload;
26633 BtShared *pBt = pPage->pBt;
26634 Pgno pgnoOvfl = 0;
26635 int nHeader;
26636 CellInfo info;
26638 /* Fill in the header. */
26639 nHeader = 0;
26640 if( !pPage->leaf ){
26641 nHeader += 4;
26643 if( pPage->hasData ){
26644 nHeader += putVarint(&pCell[nHeader], nData+nZero);
26645 }else{
26646 nData = nZero = 0;
26648 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
26649 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
26650 assert( info.nHeader==nHeader );
26651 assert( info.nKey==nKey );
26652 assert( info.nData==nData+nZero );
26654 /* Fill in the payload */
26655 nPayload = nData + nZero;
26656 if( pPage->intKey ){
26657 pSrc = pData;
26658 nSrc = nData;
26659 nData = 0;
26660 }else{
26661 nPayload += nKey;
26662 pSrc = pKey;
26663 nSrc = nKey;
26665 *pnSize = info.nSize;
26666 spaceLeft = info.nLocal;
26667 pPayload = &pCell[nHeader];
26668 pPrior = &pCell[info.iOverflow];
26670 while( nPayload>0 ){
26671 if( spaceLeft==0 ){
26672 int isExact = 0;
26673 #ifndef SQLITE_OMIT_AUTOVACUUM
26674 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
26675 if( pBt->autoVacuum ){
26677 pgnoOvfl++;
26678 } while(
26679 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
26681 if( pgnoOvfl>1 ){
26682 /* isExact = 1; */
26685 #endif
26686 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
26687 #ifndef SQLITE_OMIT_AUTOVACUUM
26688 /* If the database supports auto-vacuum, and the second or subsequent
26689 ** overflow page is being allocated, add an entry to the pointer-map
26690 ** for that page now.
26692 ** If this is the first overflow page, then write a partial entry
26693 ** to the pointer-map. If we write nothing to this pointer-map slot,
26694 ** then the optimistic overflow chain processing in clearCell()
26695 ** may misinterpret the uninitialised values and delete the
26696 ** wrong pages from the database.
26698 if( pBt->autoVacuum && rc==SQLITE_OK ){
26699 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
26700 rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
26701 if( rc ){
26702 releasePage(pOvfl);
26705 #endif
26706 if( rc ){
26707 releasePage(pToRelease);
26708 return rc;
26710 put4byte(pPrior, pgnoOvfl);
26711 releasePage(pToRelease);
26712 pToRelease = pOvfl;
26713 pPrior = pOvfl->aData;
26714 put4byte(pPrior, 0);
26715 pPayload = &pOvfl->aData[4];
26716 spaceLeft = pBt->usableSize - 4;
26718 n = nPayload;
26719 if( n>spaceLeft ) n = spaceLeft;
26720 if( nSrc>0 ){
26721 if( n>nSrc ) n = nSrc;
26722 assert( pSrc );
26723 memcpy(pPayload, pSrc, n);
26724 }else{
26725 memset(pPayload, 0, n);
26727 nPayload -= n;
26728 pPayload += n;
26729 pSrc += n;
26730 nSrc -= n;
26731 spaceLeft -= n;
26732 if( nSrc==0 ){
26733 nSrc = nData;
26734 pSrc = pData;
26737 releasePage(pToRelease);
26738 return SQLITE_OK;
26742 ** Change the MemPage.pParent pointer on the page whose number is
26743 ** given in the second argument so that MemPage.pParent holds the
26744 ** pointer in the third argument.
26746 static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
26747 MemPage *pThis;
26748 DbPage *pDbPage;
26750 assert( pNewParent!=0 );
26751 if( pgno==0 ) return SQLITE_OK;
26752 assert( pBt->pPager!=0 );
26753 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
26754 if( pDbPage ){
26755 pThis = (MemPage *)sqlite3PagerGetExtra(pDbPage);
26756 if( pThis->isInit ){
26757 assert( pThis->aData==(sqlite3PagerGetData(pDbPage)) );
26758 if( pThis->pParent!=pNewParent ){
26759 if( pThis->pParent ) sqlite3PagerUnref(pThis->pParent->pDbPage);
26760 pThis->pParent = pNewParent;
26761 sqlite3PagerRef(pNewParent->pDbPage);
26763 pThis->idxParent = idx;
26765 sqlite3PagerUnref(pDbPage);
26768 #ifndef SQLITE_OMIT_AUTOVACUUM
26769 if( pBt->autoVacuum ){
26770 return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
26772 #endif
26773 return SQLITE_OK;
26779 ** Change the pParent pointer of all children of pPage to point back
26780 ** to pPage.
26782 ** In other words, for every child of pPage, invoke reparentPage()
26783 ** to make sure that each child knows that pPage is its parent.
26785 ** This routine gets called after you memcpy() one page into
26786 ** another.
26788 static int reparentChildPages(MemPage *pPage){
26789 int i;
26790 BtShared *pBt = pPage->pBt;
26791 int rc = SQLITE_OK;
26793 if( pPage->leaf ) return SQLITE_OK;
26795 for(i=0; i<pPage->nCell; i++){
26796 u8 *pCell = findCell(pPage, i);
26797 if( !pPage->leaf ){
26798 rc = reparentPage(pBt, get4byte(pCell), pPage, i);
26799 if( rc!=SQLITE_OK ) return rc;
26802 if( !pPage->leaf ){
26803 rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]),
26804 pPage, i);
26805 pPage->idxShift = 0;
26807 return rc;
26811 ** Remove the i-th cell from pPage. This routine effects pPage only.
26812 ** The cell content is not freed or deallocated. It is assumed that
26813 ** the cell content has been copied someplace else. This routine just
26814 ** removes the reference to the cell from pPage.
26816 ** "sz" must be the number of bytes in the cell.
26818 static void dropCell(MemPage *pPage, int idx, int sz){
26819 int i; /* Loop counter */
26820 int pc; /* Offset to cell content of cell being deleted */
26821 u8 *data; /* pPage->aData */
26822 u8 *ptr; /* Used to move bytes around within data[] */
26824 assert( idx>=0 && idx<pPage->nCell );
26825 assert( sz==cellSize(pPage, idx) );
26826 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
26827 data = pPage->aData;
26828 ptr = &data[pPage->cellOffset + 2*idx];
26829 pc = get2byte(ptr);
26830 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
26831 freeSpace(pPage, pc, sz);
26832 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
26833 ptr[0] = ptr[2];
26834 ptr[1] = ptr[3];
26836 pPage->nCell--;
26837 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
26838 pPage->nFree += 2;
26839 pPage->idxShift = 1;
26843 ** Insert a new cell on pPage at cell index "i". pCell points to the
26844 ** content of the cell.
26846 ** If the cell content will fit on the page, then put it there. If it
26847 ** will not fit, then make a copy of the cell content into pTemp if
26848 ** pTemp is not null. Regardless of pTemp, allocate a new entry
26849 ** in pPage->aOvfl[] and make it point to the cell content (either
26850 ** in pTemp or the original pCell) and also record its index.
26851 ** Allocating a new entry in pPage->aCell[] implies that
26852 ** pPage->nOverflow is incremented.
26854 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
26855 ** cell. The caller will overwrite them after this function returns. If
26856 ** nSkip is non-zero, then pCell may not point to an invalid memory location
26857 ** (but pCell+nSkip is always valid).
26859 static int insertCell(
26860 MemPage *pPage, /* Page into which we are copying */
26861 int i, /* New cell becomes the i-th cell of the page */
26862 u8 *pCell, /* Content of the new cell */
26863 int sz, /* Bytes of content in pCell */
26864 u8 *pTemp, /* Temp storage space for pCell, if needed */
26865 u8 nSkip /* Do not write the first nSkip bytes of the cell */
26867 int idx; /* Where to write new cell content in data[] */
26868 int j; /* Loop counter */
26869 int top; /* First byte of content for any cell in data[] */
26870 int end; /* First byte past the last cell pointer in data[] */
26871 int ins; /* Index in data[] where new cell pointer is inserted */
26872 int hdr; /* Offset into data[] of the page header */
26873 int cellOffset; /* Address of first cell pointer in data[] */
26874 u8 *data; /* The content of the whole page */
26875 u8 *ptr; /* Used for moving information around in data[] */
26877 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
26878 assert( sz==cellSizePtr(pPage, pCell) );
26879 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
26880 if( pPage->nOverflow || sz+2>pPage->nFree ){
26881 if( pTemp ){
26882 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
26883 pCell = pTemp;
26885 j = pPage->nOverflow++;
26886 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
26887 pPage->aOvfl[j].pCell = pCell;
26888 pPage->aOvfl[j].idx = i;
26889 pPage->nFree = 0;
26890 }else{
26891 data = pPage->aData;
26892 hdr = pPage->hdrOffset;
26893 top = get2byte(&data[hdr+5]);
26894 cellOffset = pPage->cellOffset;
26895 end = cellOffset + 2*pPage->nCell + 2;
26896 ins = cellOffset + 2*i;
26897 if( end > top - sz ){
26898 int rc = defragmentPage(pPage);
26899 if( rc!=SQLITE_OK ) return rc;
26900 top = get2byte(&data[hdr+5]);
26901 assert( end + sz <= top );
26903 idx = allocateSpace(pPage, sz);
26904 assert( idx>0 );
26905 assert( end <= get2byte(&data[hdr+5]) );
26906 pPage->nCell++;
26907 pPage->nFree -= 2;
26908 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
26909 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
26910 ptr[0] = ptr[-2];
26911 ptr[1] = ptr[-1];
26913 put2byte(&data[ins], idx);
26914 put2byte(&data[hdr+3], pPage->nCell);
26915 pPage->idxShift = 1;
26916 #ifndef SQLITE_OMIT_AUTOVACUUM
26917 if( pPage->pBt->autoVacuum ){
26918 /* The cell may contain a pointer to an overflow page. If so, write
26919 ** the entry for the overflow page into the pointer map.
26921 CellInfo info;
26922 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
26923 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
26924 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
26925 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
26926 int rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
26927 if( rc!=SQLITE_OK ) return rc;
26930 #endif
26933 return SQLITE_OK;
26937 ** Add a list of cells to a page. The page should be initially empty.
26938 ** The cells are guaranteed to fit on the page.
26940 static void assemblePage(
26941 MemPage *pPage, /* The page to be assemblied */
26942 int nCell, /* The number of cells to add to this page */
26943 u8 **apCell, /* Pointers to cell bodies */
26944 int *aSize /* Sizes of the cells */
26946 int i; /* Loop counter */
26947 int totalSize; /* Total size of all cells */
26948 int hdr; /* Index of page header */
26949 int cellptr; /* Address of next cell pointer */
26950 int cellbody; /* Address of next cell body */
26951 u8 *data; /* Data for the page */
26953 assert( pPage->nOverflow==0 );
26954 totalSize = 0;
26955 for(i=0; i<nCell; i++){
26956 totalSize += aSize[i];
26958 assert( totalSize+2*nCell<=pPage->nFree );
26959 assert( pPage->nCell==0 );
26960 cellptr = pPage->cellOffset;
26961 data = pPage->aData;
26962 hdr = pPage->hdrOffset;
26963 put2byte(&data[hdr+3], nCell);
26964 if( nCell ){
26965 cellbody = allocateSpace(pPage, totalSize);
26966 assert( cellbody>0 );
26967 assert( pPage->nFree >= 2*nCell );
26968 pPage->nFree -= 2*nCell;
26969 for(i=0; i<nCell; i++){
26970 put2byte(&data[cellptr], cellbody);
26971 memcpy(&data[cellbody], apCell[i], aSize[i]);
26972 cellptr += 2;
26973 cellbody += aSize[i];
26975 assert( cellbody==pPage->pBt->usableSize );
26977 pPage->nCell = nCell;
26981 ** The following parameters determine how many adjacent pages get involved
26982 ** in a balancing operation. NN is the number of neighbors on either side
26983 ** of the page that participate in the balancing operation. NB is the
26984 ** total number of pages that participate, including the target page and
26985 ** NN neighbors on either side.
26987 ** The minimum value of NN is 1 (of course). Increasing NN above 1
26988 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
26989 ** in exchange for a larger degradation in INSERT and UPDATE performance.
26990 ** The value of NN appears to give the best results overall.
26992 #define NN 1 /* Number of neighbors on either side of pPage */
26993 #define NB (NN*2+1) /* Total pages involved in the balance */
26995 /* Forward reference */
26996 static int balance(MemPage*, int);
26998 #ifndef SQLITE_OMIT_QUICKBALANCE
27000 ** This version of balance() handles the common special case where
27001 ** a new entry is being inserted on the extreme right-end of the
27002 ** tree, in other words, when the new entry will become the largest
27003 ** entry in the tree.
27005 ** Instead of trying balance the 3 right-most leaf pages, just add
27006 ** a new page to the right-hand side and put the one new entry in
27007 ** that page. This leaves the right side of the tree somewhat
27008 ** unbalanced. But odds are that we will be inserting new entries
27009 ** at the end soon afterwards so the nearly empty page will quickly
27010 ** fill up. On average.
27012 ** pPage is the leaf page which is the right-most page in the tree.
27013 ** pParent is its parent. pPage must have a single overflow entry
27014 ** which is also the right-most entry on the page.
27016 static int balance_quick(MemPage *pPage, MemPage *pParent){
27017 int rc;
27018 MemPage *pNew;
27019 Pgno pgnoNew;
27020 u8 *pCell;
27021 int szCell;
27022 CellInfo info;
27023 BtShared *pBt = pPage->pBt;
27024 int parentIdx = pParent->nCell; /* pParent new divider cell index */
27025 int parentSize; /* Size of new divider cell */
27026 u8 parentCell[64]; /* Space for the new divider cell */
27028 /* Allocate a new page. Insert the overflow cell from pPage
27029 ** into it. Then remove the overflow cell from pPage.
27031 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
27032 if( rc!=SQLITE_OK ){
27033 return rc;
27035 pCell = pPage->aOvfl[0].pCell;
27036 szCell = cellSizePtr(pPage, pCell);
27037 zeroPage(pNew, pPage->aData[0]);
27038 assemblePage(pNew, 1, &pCell, &szCell);
27039 pPage->nOverflow = 0;
27041 /* Set the parent of the newly allocated page to pParent. */
27042 pNew->pParent = pParent;
27043 sqlite3PagerRef(pParent->pDbPage);
27045 /* pPage is currently the right-child of pParent. Change this
27046 ** so that the right-child is the new page allocated above and
27047 ** pPage is the next-to-right child.
27049 assert( pPage->nCell>0 );
27050 pCell = findCell(pPage, pPage->nCell-1);
27051 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
27052 rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
27053 if( rc!=SQLITE_OK ){
27054 return rc;
27056 assert( parentSize<64 );
27057 rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
27058 if( rc!=SQLITE_OK ){
27059 return rc;
27061 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
27062 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
27064 #ifndef SQLITE_OMIT_AUTOVACUUM
27065 /* If this is an auto-vacuum database, update the pointer map
27066 ** with entries for the new page, and any pointer from the
27067 ** cell on the page to an overflow page.
27069 if( pBt->autoVacuum ){
27070 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
27071 if( rc==SQLITE_OK ){
27072 rc = ptrmapPutOvfl(pNew, 0);
27074 if( rc!=SQLITE_OK ){
27075 releasePage(pNew);
27076 return rc;
27079 #endif
27081 /* Release the reference to the new page and balance the parent page,
27082 ** in case the divider cell inserted caused it to become overfull.
27084 releasePage(pNew);
27085 return balance(pParent, 0);
27087 #endif /* SQLITE_OMIT_QUICKBALANCE */
27090 ** This routine redistributes Cells on pPage and up to NN*2 siblings
27091 ** of pPage so that all pages have about the same amount of free space.
27092 ** Usually NN siblings on either side of pPage is used in the balancing,
27093 ** though more siblings might come from one side if pPage is the first
27094 ** or last child of its parent. If pPage has fewer than 2*NN siblings
27095 ** (something which can only happen if pPage is the root page or a
27096 ** child of root) then all available siblings participate in the balancing.
27098 ** The number of siblings of pPage might be increased or decreased by one or
27099 ** two in an effort to keep pages nearly full but not over full. The root page
27100 ** is special and is allowed to be nearly empty. If pPage is
27101 ** the root page, then the depth of the tree might be increased
27102 ** or decreased by one, as necessary, to keep the root page from being
27103 ** overfull or completely empty.
27105 ** Note that when this routine is called, some of the Cells on pPage
27106 ** might not actually be stored in pPage->aData[]. This can happen
27107 ** if the page is overfull. Part of the job of this routine is to
27108 ** make sure all Cells for pPage once again fit in pPage->aData[].
27110 ** In the course of balancing the siblings of pPage, the parent of pPage
27111 ** might become overfull or underfull. If that happens, then this routine
27112 ** is called recursively on the parent.
27114 ** If this routine fails for any reason, it might leave the database
27115 ** in a corrupted state. So if this routine fails, the database should
27116 ** be rolled back.
27118 static int balance_nonroot(MemPage *pPage){
27119 MemPage *pParent; /* The parent of pPage */
27120 BtShared *pBt; /* The whole database */
27121 int nCell = 0; /* Number of cells in apCell[] */
27122 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
27123 int nOld; /* Number of pages in apOld[] */
27124 int nNew; /* Number of pages in apNew[] */
27125 int nDiv; /* Number of cells in apDiv[] */
27126 int i, j, k; /* Loop counters */
27127 int idx; /* Index of pPage in pParent->aCell[] */
27128 int nxDiv; /* Next divider slot in pParent->aCell[] */
27129 int rc; /* The return code */
27130 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
27131 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
27132 int usableSpace; /* Bytes in pPage beyond the header */
27133 int pageFlags; /* Value of pPage->aData[0] */
27134 int subtotal; /* Subtotal of bytes in cells on one page */
27135 int iSpace = 0; /* First unused byte of aSpace[] */
27136 MemPage *apOld[NB]; /* pPage and up to two siblings */
27137 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
27138 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
27139 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
27140 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
27141 u8 *apDiv[NB]; /* Divider cells in pParent */
27142 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
27143 int szNew[NB+2]; /* Combined size of cells place on i-th page */
27144 u8 **apCell = 0; /* All cells begin balanced */
27145 int *szCell; /* Local size of all cells in apCell[] */
27146 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
27147 u8 *aSpace; /* Space to hold copies of dividers cells */
27148 #ifndef SQLITE_OMIT_AUTOVACUUM
27149 u8 *aFrom = 0;
27150 #endif
27153 ** Find the parent page.
27155 assert( pPage->isInit );
27156 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
27157 pBt = pPage->pBt;
27158 pParent = pPage->pParent;
27159 assert( pParent );
27160 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
27161 return rc;
27163 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
27165 #ifndef SQLITE_OMIT_QUICKBALANCE
27167 ** A special case: If a new entry has just been inserted into a
27168 ** table (that is, a btree with integer keys and all data at the leaves)
27169 ** and the new entry is the right-most entry in the tree (it has the
27170 ** largest key) then use the special balance_quick() routine for
27171 ** balancing. balance_quick() is much faster and results in a tighter
27172 ** packing of data in the common case.
27174 if( pPage->leaf &&
27175 pPage->intKey &&
27176 pPage->leafData &&
27177 pPage->nOverflow==1 &&
27178 pPage->aOvfl[0].idx==pPage->nCell &&
27179 pPage->pParent->pgno!=1 &&
27180 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
27183 ** TODO: Check the siblings to the left of pPage. It may be that
27184 ** they are not full and no new page is required.
27186 return balance_quick(pPage, pParent);
27188 #endif
27191 ** Find the cell in the parent page whose left child points back
27192 ** to pPage. The "idx" variable is the index of that cell. If pPage
27193 ** is the rightmost child of pParent then set idx to pParent->nCell
27195 if( pParent->idxShift ){
27196 Pgno pgno;
27197 pgno = pPage->pgno;
27198 assert( pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
27199 for(idx=0; idx<pParent->nCell; idx++){
27200 if( get4byte(findCell(pParent, idx))==pgno ){
27201 break;
27204 assert( idx<pParent->nCell
27205 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
27206 }else{
27207 idx = pPage->idxParent;
27211 ** Initialize variables so that it will be safe to jump
27212 ** directly to balance_cleanup at any moment.
27214 nOld = nNew = 0;
27215 sqlite3PagerRef(pParent->pDbPage);
27218 ** Find sibling pages to pPage and the cells in pParent that divide
27219 ** the siblings. An attempt is made to find NN siblings on either
27220 ** side of pPage. More siblings are taken from one side, however, if
27221 ** pPage there are fewer than NN siblings on the other side. If pParent
27222 ** has NB or fewer children then all children of pParent are taken.
27224 nxDiv = idx - NN;
27225 if( nxDiv + NB > pParent->nCell ){
27226 nxDiv = pParent->nCell - NB + 1;
27228 if( nxDiv<0 ){
27229 nxDiv = 0;
27231 nDiv = 0;
27232 for(i=0, k=nxDiv; i<NB; i++, k++){
27233 if( k<pParent->nCell ){
27234 apDiv[i] = findCell(pParent, k);
27235 nDiv++;
27236 assert( !pParent->leaf );
27237 pgnoOld[i] = get4byte(apDiv[i]);
27238 }else if( k==pParent->nCell ){
27239 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
27240 }else{
27241 break;
27243 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
27244 if( rc ) goto balance_cleanup;
27245 apOld[i]->idxParent = k;
27246 apCopy[i] = 0;
27247 assert( i==nOld );
27248 nOld++;
27249 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
27252 /* Make nMaxCells a multiple of 2 in order to preserve 8-byte
27253 ** alignment */
27254 nMaxCells = (nMaxCells + 1)&~1;
27257 ** Allocate space for memory structures
27259 apCell = sqliteMallocRaw(
27260 nMaxCells*sizeof(u8*) /* apCell */
27261 + nMaxCells*sizeof(int) /* szCell */
27262 + ROUND8(sizeof(MemPage))*NB /* aCopy */
27263 + pBt->pageSize*(5+NB) /* aSpace */
27264 + (ISAUTOVACUUM ? nMaxCells : 0) /* aFrom */
27266 if( apCell==0 ){
27267 rc = SQLITE_NOMEM;
27268 goto balance_cleanup;
27270 szCell = (int*)&apCell[nMaxCells];
27271 aCopy[0] = (u8*)&szCell[nMaxCells];
27272 assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
27273 for(i=1; i<NB; i++){
27274 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
27275 assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
27277 aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
27278 assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
27279 #ifndef SQLITE_OMIT_AUTOVACUUM
27280 if( pBt->autoVacuum ){
27281 aFrom = &aSpace[5*pBt->pageSize];
27283 #endif
27286 ** Make copies of the content of pPage and its siblings into aOld[].
27287 ** The rest of this function will use data from the copies rather
27288 ** that the original pages since the original pages will be in the
27289 ** process of being overwritten.
27291 for(i=0; i<nOld; i++){
27292 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i][pBt->pageSize];
27293 p->aData = &((u8*)p)[-pBt->pageSize];
27294 memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
27295 /* The memcpy() above changes the value of p->aData so we have to
27296 ** set it again. */
27297 p->aData = &((u8*)p)[-pBt->pageSize];
27301 ** Load pointers to all cells on sibling pages and the divider cells
27302 ** into the local apCell[] array. Make copies of the divider cells
27303 ** into space obtained form aSpace[] and remove the the divider Cells
27304 ** from pParent.
27306 ** If the siblings are on leaf pages, then the child pointers of the
27307 ** divider cells are stripped from the cells before they are copied
27308 ** into aSpace[]. In this way, all cells in apCell[] are without
27309 ** child pointers. If siblings are not leaves, then all cell in
27310 ** apCell[] include child pointers. Either way, all cells in apCell[]
27311 ** are alike.
27313 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
27314 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
27316 nCell = 0;
27317 leafCorrection = pPage->leaf*4;
27318 leafData = pPage->leafData && pPage->leaf;
27319 for(i=0; i<nOld; i++){
27320 MemPage *pOld = apCopy[i];
27321 int limit = pOld->nCell+pOld->nOverflow;
27322 for(j=0; j<limit; j++){
27323 assert( nCell<nMaxCells );
27324 apCell[nCell] = findOverflowCell(pOld, j);
27325 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
27326 #ifndef SQLITE_OMIT_AUTOVACUUM
27327 if( pBt->autoVacuum ){
27328 int a;
27329 aFrom[nCell] = i;
27330 for(a=0; a<pOld->nOverflow; a++){
27331 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
27332 aFrom[nCell] = 0xFF;
27333 break;
27337 #endif
27338 nCell++;
27340 if( i<nOld-1 ){
27341 int sz = cellSizePtr(pParent, apDiv[i]);
27342 if( leafData ){
27343 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
27344 ** are duplicates of keys on the child pages. We need to remove
27345 ** the divider cells from pParent, but the dividers cells are not
27346 ** added to apCell[] because they are duplicates of child cells.
27348 dropCell(pParent, nxDiv, sz);
27349 }else{
27350 u8 *pTemp;
27351 assert( nCell<nMaxCells );
27352 szCell[nCell] = sz;
27353 pTemp = &aSpace[iSpace];
27354 iSpace += sz;
27355 assert( iSpace<=pBt->pageSize*5 );
27356 memcpy(pTemp, apDiv[i], sz);
27357 apCell[nCell] = pTemp+leafCorrection;
27358 #ifndef SQLITE_OMIT_AUTOVACUUM
27359 if( pBt->autoVacuum ){
27360 aFrom[nCell] = 0xFF;
27362 #endif
27363 dropCell(pParent, nxDiv, sz);
27364 szCell[nCell] -= leafCorrection;
27365 assert( get4byte(pTemp)==pgnoOld[i] );
27366 if( !pOld->leaf ){
27367 assert( leafCorrection==0 );
27368 /* The right pointer of the child page pOld becomes the left
27369 ** pointer of the divider cell */
27370 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
27371 }else{
27372 assert( leafCorrection==4 );
27373 if( szCell[nCell]<4 ){
27374 /* Do not allow any cells smaller than 4 bytes. */
27375 szCell[nCell] = 4;
27378 nCell++;
27384 ** Figure out the number of pages needed to hold all nCell cells.
27385 ** Store this number in "k". Also compute szNew[] which is the total
27386 ** size of all cells on the i-th page and cntNew[] which is the index
27387 ** in apCell[] of the cell that divides page i from page i+1.
27388 ** cntNew[k] should equal nCell.
27390 ** Values computed by this block:
27392 ** k: The total number of sibling pages
27393 ** szNew[i]: Spaced used on the i-th sibling page.
27394 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
27395 ** the right of the i-th sibling page.
27396 ** usableSpace: Number of bytes of space available on each sibling.
27399 usableSpace = pBt->usableSize - 12 + leafCorrection;
27400 for(subtotal=k=i=0; i<nCell; i++){
27401 assert( i<nMaxCells );
27402 subtotal += szCell[i] + 2;
27403 if( subtotal > usableSpace ){
27404 szNew[k] = subtotal - szCell[i];
27405 cntNew[k] = i;
27406 if( leafData ){ i--; }
27407 subtotal = 0;
27408 k++;
27411 szNew[k] = subtotal;
27412 cntNew[k] = nCell;
27413 k++;
27416 ** The packing computed by the previous block is biased toward the siblings
27417 ** on the left side. The left siblings are always nearly full, while the
27418 ** right-most sibling might be nearly empty. This block of code attempts
27419 ** to adjust the packing of siblings to get a better balance.
27421 ** This adjustment is more than an optimization. The packing above might
27422 ** be so out of balance as to be illegal. For example, the right-most
27423 ** sibling might be completely empty. This adjustment is not optional.
27425 for(i=k-1; i>0; i--){
27426 int szRight = szNew[i]; /* Size of sibling on the right */
27427 int szLeft = szNew[i-1]; /* Size of sibling on the left */
27428 int r; /* Index of right-most cell in left sibling */
27429 int d; /* Index of first cell to the left of right sibling */
27431 r = cntNew[i-1] - 1;
27432 d = r + 1 - leafData;
27433 assert( d<nMaxCells );
27434 assert( r<nMaxCells );
27435 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
27436 szRight += szCell[d] + 2;
27437 szLeft -= szCell[r] + 2;
27438 cntNew[i-1]--;
27439 r = cntNew[i-1] - 1;
27440 d = r + 1 - leafData;
27442 szNew[i] = szRight;
27443 szNew[i-1] = szLeft;
27446 /* Either we found one or more cells (cntnew[0])>0) or we are the
27447 ** a virtual root page. A virtual root page is when the real root
27448 ** page is page 1 and we are the only child of that page.
27450 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
27453 ** Allocate k new pages. Reuse old pages where possible.
27455 assert( pPage->pgno>1 );
27456 pageFlags = pPage->aData[0];
27457 for(i=0; i<k; i++){
27458 MemPage *pNew;
27459 if( i<nOld ){
27460 pNew = apNew[i] = apOld[i];
27461 pgnoNew[i] = pgnoOld[i];
27462 apOld[i] = 0;
27463 rc = sqlite3PagerWrite(pNew->pDbPage);
27464 nNew++;
27465 if( rc ) goto balance_cleanup;
27466 }else{
27467 assert( i>0 );
27468 rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
27469 if( rc ) goto balance_cleanup;
27470 apNew[i] = pNew;
27471 nNew++;
27473 zeroPage(pNew, pageFlags);
27476 /* Free any old pages that were not reused as new pages.
27478 while( i<nOld ){
27479 rc = freePage(apOld[i]);
27480 if( rc ) goto balance_cleanup;
27481 releasePage(apOld[i]);
27482 apOld[i] = 0;
27483 i++;
27487 ** Put the new pages in accending order. This helps to
27488 ** keep entries in the disk file in order so that a scan
27489 ** of the table is a linear scan through the file. That
27490 ** in turn helps the operating system to deliver pages
27491 ** from the disk more rapidly.
27493 ** An O(n^2) insertion sort algorithm is used, but since
27494 ** n is never more than NB (a small constant), that should
27495 ** not be a problem.
27497 ** When NB==3, this one optimization makes the database
27498 ** about 25% faster for large insertions and deletions.
27500 for(i=0; i<k-1; i++){
27501 int minV = pgnoNew[i];
27502 int minI = i;
27503 for(j=i+1; j<k; j++){
27504 if( pgnoNew[j]<(unsigned)minV ){
27505 minI = j;
27506 minV = pgnoNew[j];
27509 if( minI>i ){
27510 int t;
27511 MemPage *pT;
27512 t = pgnoNew[i];
27513 pT = apNew[i];
27514 pgnoNew[i] = pgnoNew[minI];
27515 apNew[i] = apNew[minI];
27516 pgnoNew[minI] = t;
27517 apNew[minI] = pT;
27520 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
27521 pgnoOld[0],
27522 nOld>=2 ? pgnoOld[1] : 0,
27523 nOld>=3 ? pgnoOld[2] : 0,
27524 pgnoNew[0], szNew[0],
27525 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
27526 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
27527 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
27528 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
27531 ** Evenly distribute the data in apCell[] across the new pages.
27532 ** Insert divider cells into pParent as necessary.
27534 j = 0;
27535 for(i=0; i<nNew; i++){
27536 /* Assemble the new sibling page. */
27537 MemPage *pNew = apNew[i];
27538 assert( j<nMaxCells );
27539 assert( pNew->pgno==pgnoNew[i] );
27540 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
27541 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
27542 assert( pNew->nOverflow==0 );
27544 #ifndef SQLITE_OMIT_AUTOVACUUM
27545 /* If this is an auto-vacuum database, update the pointer map entries
27546 ** that point to the siblings that were rearranged. These can be: left
27547 ** children of cells, the right-child of the page, or overflow pages
27548 ** pointed to by cells.
27550 if( pBt->autoVacuum ){
27551 for(k=j; k<cntNew[i]; k++){
27552 assert( k<nMaxCells );
27553 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
27554 rc = ptrmapPutOvfl(pNew, k-j);
27555 if( rc!=SQLITE_OK ){
27556 goto balance_cleanup;
27561 #endif
27563 j = cntNew[i];
27565 /* If the sibling page assembled above was not the right-most sibling,
27566 ** insert a divider cell into the parent page.
27568 if( i<nNew-1 && j<nCell ){
27569 u8 *pCell;
27570 u8 *pTemp;
27571 int sz;
27573 assert( j<nMaxCells );
27574 pCell = apCell[j];
27575 sz = szCell[j] + leafCorrection;
27576 if( !pNew->leaf ){
27577 memcpy(&pNew->aData[8], pCell, 4);
27578 pTemp = 0;
27579 }else if( leafData ){
27580 /* If the tree is a leaf-data tree, and the siblings are leaves,
27581 ** then there is no divider cell in apCell[]. Instead, the divider
27582 ** cell consists of the integer key for the right-most cell of
27583 ** the sibling-page assembled above only.
27585 CellInfo info;
27586 j--;
27587 sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
27588 pCell = &aSpace[iSpace];
27589 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
27590 iSpace += sz;
27591 assert( iSpace<=pBt->pageSize*5 );
27592 pTemp = 0;
27593 }else{
27594 pCell -= 4;
27595 pTemp = &aSpace[iSpace];
27596 iSpace += sz;
27597 assert( iSpace<=pBt->pageSize*5 );
27598 /* Obscure case for non-leaf-data trees: If the cell at pCell was
27599 ** previously stored on a leaf node, and it's reported size was 4
27600 ** bytes, then it may actually be smaller than this
27601 ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
27602 ** any cell). But it's important to pass the correct size to
27603 ** insertCell(), so reparse the cell now.
27605 ** Note that this can never happen in an SQLite data file, as all
27606 ** cells are at least 4 bytes. It only happens in b-trees used
27607 ** to evaluate "IN (SELECT ...)" and similar clauses.
27609 if( szCell[j]==4 ){
27610 assert(leafCorrection==4);
27611 sz = cellSizePtr(pParent, pCell);
27614 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
27615 if( rc!=SQLITE_OK ) goto balance_cleanup;
27616 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
27617 #ifndef SQLITE_OMIT_AUTOVACUUM
27618 /* If this is an auto-vacuum database, and not a leaf-data tree,
27619 ** then update the pointer map with an entry for the overflow page
27620 ** that the cell just inserted points to (if any).
27622 if( pBt->autoVacuum && !leafData ){
27623 rc = ptrmapPutOvfl(pParent, nxDiv);
27624 if( rc!=SQLITE_OK ){
27625 goto balance_cleanup;
27628 #endif
27629 j++;
27630 nxDiv++;
27633 assert( j==nCell );
27634 assert( nOld>0 );
27635 assert( nNew>0 );
27636 if( (pageFlags & PTF_LEAF)==0 ){
27637 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
27639 if( nxDiv==pParent->nCell+pParent->nOverflow ){
27640 /* Right-most sibling is the right-most child of pParent */
27641 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
27642 }else{
27643 /* Right-most sibling is the left child of the first entry in pParent
27644 ** past the right-most divider entry */
27645 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
27649 ** Reparent children of all cells.
27651 for(i=0; i<nNew; i++){
27652 rc = reparentChildPages(apNew[i]);
27653 if( rc!=SQLITE_OK ) goto balance_cleanup;
27655 rc = reparentChildPages(pParent);
27656 if( rc!=SQLITE_OK ) goto balance_cleanup;
27659 ** Balance the parent page. Note that the current page (pPage) might
27660 ** have been added to the freelist so it might no longer be initialized.
27661 ** But the parent page will always be initialized.
27663 assert( pParent->isInit );
27664 rc = balance(pParent, 0);
27667 ** Cleanup before returning.
27669 balance_cleanup:
27670 sqliteFree(apCell);
27671 for(i=0; i<nOld; i++){
27672 releasePage(apOld[i]);
27674 for(i=0; i<nNew; i++){
27675 releasePage(apNew[i]);
27677 releasePage(pParent);
27678 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
27679 pPage->pgno, nOld, nNew, nCell));
27680 return rc;
27684 ** This routine is called for the root page of a btree when the root
27685 ** page contains no cells. This is an opportunity to make the tree
27686 ** shallower by one level.
27688 static int balance_shallower(MemPage *pPage){
27689 MemPage *pChild; /* The only child page of pPage */
27690 Pgno pgnoChild; /* Page number for pChild */
27691 int rc = SQLITE_OK; /* Return code from subprocedures */
27692 BtShared *pBt; /* The main BTree structure */
27693 int mxCellPerPage; /* Maximum number of cells per page */
27694 u8 **apCell; /* All cells from pages being balanced */
27695 int *szCell; /* Local size of all cells */
27697 assert( pPage->pParent==0 );
27698 assert( pPage->nCell==0 );
27699 pBt = pPage->pBt;
27700 mxCellPerPage = MX_CELL(pBt);
27701 apCell = sqliteMallocRaw( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
27702 if( apCell==0 ) return SQLITE_NOMEM;
27703 szCell = (int*)&apCell[mxCellPerPage];
27704 if( pPage->leaf ){
27705 /* The table is completely empty */
27706 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
27707 }else{
27708 /* The root page is empty but has one child. Transfer the
27709 ** information from that one child into the root page if it
27710 ** will fit. This reduces the depth of the tree by one.
27712 ** If the root page is page 1, it has less space available than
27713 ** its child (due to the 100 byte header that occurs at the beginning
27714 ** of the database fle), so it might not be able to hold all of the
27715 ** information currently contained in the child. If this is the
27716 ** case, then do not do the transfer. Leave page 1 empty except
27717 ** for the right-pointer to the child page. The child page becomes
27718 ** the virtual root of the tree.
27720 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
27721 assert( pgnoChild>0 );
27722 assert( pgnoChild<=sqlite3PagerPagecount(pPage->pBt->pPager) );
27723 rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
27724 if( rc ) goto end_shallow_balance;
27725 if( pPage->pgno==1 ){
27726 rc = sqlite3BtreeInitPage(pChild, pPage);
27727 if( rc ) goto end_shallow_balance;
27728 assert( pChild->nOverflow==0 );
27729 if( pChild->nFree>=100 ){
27730 /* The child information will fit on the root page, so do the
27731 ** copy */
27732 int i;
27733 zeroPage(pPage, pChild->aData[0]);
27734 for(i=0; i<pChild->nCell; i++){
27735 apCell[i] = findCell(pChild,i);
27736 szCell[i] = cellSizePtr(pChild, apCell[i]);
27738 assemblePage(pPage, pChild->nCell, apCell, szCell);
27739 /* Copy the right-pointer of the child to the parent. */
27740 put4byte(&pPage->aData[pPage->hdrOffset+8],
27741 get4byte(&pChild->aData[pChild->hdrOffset+8]));
27742 freePage(pChild);
27743 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
27744 }else{
27745 /* The child has more information that will fit on the root.
27746 ** The tree is already balanced. Do nothing. */
27747 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
27749 }else{
27750 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
27751 pPage->isInit = 0;
27752 pPage->pParent = 0;
27753 rc = sqlite3BtreeInitPage(pPage, 0);
27754 assert( rc==SQLITE_OK );
27755 freePage(pChild);
27756 TRACE(("BALANCE: transfer child %d into root %d\n",
27757 pChild->pgno, pPage->pgno));
27759 rc = reparentChildPages(pPage);
27760 assert( pPage->nOverflow==0 );
27761 #ifndef SQLITE_OMIT_AUTOVACUUM
27762 if( pBt->autoVacuum ){
27763 int i;
27764 for(i=0; i<pPage->nCell; i++){
27765 rc = ptrmapPutOvfl(pPage, i);
27766 if( rc!=SQLITE_OK ){
27767 goto end_shallow_balance;
27771 #endif
27772 if( rc!=SQLITE_OK ) goto end_shallow_balance;
27773 releasePage(pChild);
27775 end_shallow_balance:
27776 sqliteFree(apCell);
27777 return rc;
27782 ** The root page is overfull
27784 ** When this happens, Create a new child page and copy the
27785 ** contents of the root into the child. Then make the root
27786 ** page an empty page with rightChild pointing to the new
27787 ** child. Finally, call balance_internal() on the new child
27788 ** to cause it to split.
27790 static int balance_deeper(MemPage *pPage){
27791 int rc; /* Return value from subprocedures */
27792 MemPage *pChild; /* Pointer to a new child page */
27793 Pgno pgnoChild; /* Page number of the new child page */
27794 BtShared *pBt; /* The BTree */
27795 int usableSize; /* Total usable size of a page */
27796 u8 *data; /* Content of the parent page */
27797 u8 *cdata; /* Content of the child page */
27798 int hdr; /* Offset to page header in parent */
27799 int brk; /* Offset to content of first cell in parent */
27801 assert( pPage->pParent==0 );
27802 assert( pPage->nOverflow>0 );
27803 pBt = pPage->pBt;
27804 rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
27805 if( rc ) return rc;
27806 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
27807 usableSize = pBt->usableSize;
27808 data = pPage->aData;
27809 hdr = pPage->hdrOffset;
27810 brk = get2byte(&data[hdr+5]);
27811 cdata = pChild->aData;
27812 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
27813 memcpy(&cdata[brk], &data[brk], usableSize-brk);
27814 assert( pChild->isInit==0 );
27815 rc = sqlite3BtreeInitPage(pChild, pPage);
27816 if( rc ) goto balancedeeper_out;
27817 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
27818 pChild->nOverflow = pPage->nOverflow;
27819 if( pChild->nOverflow ){
27820 pChild->nFree = 0;
27822 assert( pChild->nCell==pPage->nCell );
27823 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
27824 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
27825 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
27826 #ifndef SQLITE_OMIT_AUTOVACUUM
27827 if( pBt->autoVacuum ){
27828 int i;
27829 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
27830 if( rc ) goto balancedeeper_out;
27831 for(i=0; i<pChild->nCell; i++){
27832 rc = ptrmapPutOvfl(pChild, i);
27833 if( rc!=SQLITE_OK ){
27834 return rc;
27838 #endif
27839 rc = balance_nonroot(pChild);
27841 balancedeeper_out:
27842 releasePage(pChild);
27843 return rc;
27847 ** Decide if the page pPage needs to be balanced. If balancing is
27848 ** required, call the appropriate balancing routine.
27850 static int balance(MemPage *pPage, int insert){
27851 int rc = SQLITE_OK;
27852 if( pPage->pParent==0 ){
27853 if( pPage->nOverflow>0 ){
27854 rc = balance_deeper(pPage);
27856 if( rc==SQLITE_OK && pPage->nCell==0 ){
27857 rc = balance_shallower(pPage);
27859 }else{
27860 if( pPage->nOverflow>0 ||
27861 (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
27862 rc = balance_nonroot(pPage);
27865 return rc;
27869 ** This routine checks all cursors that point to table pgnoRoot.
27870 ** If any of those cursors were opened with wrFlag==0 in a different
27871 ** database connection (a database connection that shares the pager
27872 ** cache with the current connection) and that other connection
27873 ** is not in the ReadUncommmitted state, then this routine returns
27874 ** SQLITE_LOCKED.
27876 ** In addition to checking for read-locks (where a read-lock
27877 ** means a cursor opened with wrFlag==0) this routine also moves
27878 ** all write cursors so that they are pointing to the
27879 ** first Cell on the root page. This is necessary because an insert
27880 ** or delete might change the number of cells on a page or delete
27881 ** a page entirely and we do not want to leave any cursors
27882 ** pointing to non-existant pages or cells.
27884 static int checkReadLocks(Btree *pBtree, Pgno pgnoRoot, BtCursor *pExclude){
27885 BtCursor *p;
27886 BtShared *pBt = pBtree->pBt;
27887 sqlite3 *db = pBtree->pSqlite;
27888 for(p=pBt->pCursor; p; p=p->pNext){
27889 if( p==pExclude ) continue;
27890 if( p->eState!=CURSOR_VALID ) continue;
27891 if( p->pgnoRoot!=pgnoRoot ) continue;
27892 if( p->wrFlag==0 ){
27893 sqlite3 *dbOther = p->pBtree->pSqlite;
27894 if( dbOther==0 ||
27895 (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
27896 return SQLITE_LOCKED;
27898 }else if( p->pPage->pgno!=p->pgnoRoot ){
27899 moveToRoot(p);
27902 return SQLITE_OK;
27906 ** Insert a new record into the BTree. The key is given by (pKey,nKey)
27907 ** and the data is given by (pData,nData). The cursor is used only to
27908 ** define what table the record should be inserted into. The cursor
27909 ** is left pointing at a random location.
27911 ** For an INTKEY table, only the nKey value of the key is used. pKey is
27912 ** ignored. For a ZERODATA table, the pData and nData are both ignored.
27914 static int sqlite3BtreeInsert(
27915 BtCursor *pCur, /* Insert data into the table of this cursor */
27916 const void *pKey, i64 nKey, /* The key of the new record */
27917 const void *pData, int nData, /* The data of the new record */
27918 int nZero, /* Number of extra 0 bytes to append to data */
27919 int appendBias /* True if this is likely an append */
27921 int rc;
27922 int loc;
27923 int szNew;
27924 MemPage *pPage;
27925 BtShared *pBt = pCur->pBtree->pBt;
27926 unsigned char *oldCell;
27927 unsigned char *newCell = 0;
27929 if( pBt->inTransaction!=TRANS_WRITE ){
27930 /* Must start a transaction before doing an insert */
27931 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
27933 assert( !pBt->readOnly );
27934 if( !pCur->wrFlag ){
27935 return SQLITE_PERM; /* Cursor not open for writing */
27937 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
27938 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
27941 /* Save the positions of any other cursors open on this table */
27942 clearCursorPosition(pCur);
27943 if(
27944 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
27945 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
27947 return rc;
27950 pPage = pCur->pPage;
27951 assert( pPage->intKey || nKey>=0 );
27952 assert( pPage->leaf || !pPage->leafData );
27953 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
27954 pCur->pgnoRoot, nKey, nData, pPage->pgno,
27955 loc==0 ? "overwrite" : "new entry"));
27956 assert( pPage->isInit );
27957 rc = sqlite3PagerWrite(pPage->pDbPage);
27958 if( rc ) return rc;
27959 newCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
27960 if( newCell==0 ) return SQLITE_NOMEM;
27961 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
27962 if( rc ) goto end_insert;
27963 assert( szNew==cellSizePtr(pPage, newCell) );
27964 assert( szNew<=MX_CELL_SIZE(pBt) );
27965 if( loc==0 && CURSOR_VALID==pCur->eState ){
27966 int szOld;
27967 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
27968 oldCell = findCell(pPage, pCur->idx);
27969 if( !pPage->leaf ){
27970 memcpy(newCell, oldCell, 4);
27972 szOld = cellSizePtr(pPage, oldCell);
27973 rc = clearCell(pPage, oldCell);
27974 if( rc ) goto end_insert;
27975 dropCell(pPage, pCur->idx, szOld);
27976 }else if( loc<0 && pPage->nCell>0 ){
27977 assert( pPage->leaf );
27978 pCur->idx++;
27979 pCur->info.nSize = 0;
27980 }else{
27981 assert( pPage->leaf );
27983 rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
27984 if( rc!=SQLITE_OK ) goto end_insert;
27985 rc = balance(pPage, 1);
27986 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
27987 /* fflush(stdout); */
27988 if( rc==SQLITE_OK ){
27989 moveToRoot(pCur);
27991 end_insert:
27992 sqliteFree(newCell);
27993 return rc;
27997 ** Delete the entry that the cursor is pointing to. The cursor
27998 ** is left pointing at a random location.
28000 static int sqlite3BtreeDelete(BtCursor *pCur){
28001 MemPage *pPage = pCur->pPage;
28002 unsigned char *pCell;
28003 int rc;
28004 Pgno pgnoChild = 0;
28005 BtShared *pBt = pCur->pBtree->pBt;
28007 assert( pPage->isInit );
28008 if( pBt->inTransaction!=TRANS_WRITE ){
28009 /* Must start a transaction before doing a delete */
28010 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
28012 assert( !pBt->readOnly );
28013 if( pCur->idx >= pPage->nCell ){
28014 return SQLITE_ERROR; /* The cursor is not pointing to anything */
28016 if( !pCur->wrFlag ){
28017 return SQLITE_PERM; /* Did not open this cursor for writing */
28019 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
28020 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
28023 /* Restore the current cursor position (a no-op if the cursor is not in
28024 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
28025 ** open on the same table. Then call sqlite3PagerWrite() on the page
28026 ** that the entry will be deleted from.
28028 if(
28029 (rc = restoreOrClearCursorPosition(pCur))!=0 ||
28030 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
28031 (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
28033 return rc;
28036 /* Locate the cell within it's page and leave pCell pointing to the
28037 ** data. The clearCell() call frees any overflow pages associated with the
28038 ** cell. The cell itself is still intact.
28040 pCell = findCell(pPage, pCur->idx);
28041 if( !pPage->leaf ){
28042 pgnoChild = get4byte(pCell);
28044 rc = clearCell(pPage, pCell);
28045 if( rc ) return rc;
28047 if( !pPage->leaf ){
28049 ** The entry we are about to delete is not a leaf so if we do not
28050 ** do something we will leave a hole on an internal page.
28051 ** We have to fill the hole by moving in a cell from a leaf. The
28052 ** next Cell after the one to be deleted is guaranteed to exist and
28053 ** to be a leaf so we can use it.
28055 BtCursor leafCur;
28056 unsigned char *pNext;
28057 int szNext; /* The compiler warning is wrong: szNext is always
28058 ** initialized before use. Adding an extra initialization
28059 ** to silence the compiler slows down the code. */
28060 int notUsed;
28061 unsigned char *tempCell = 0;
28062 assert( !pPage->leafData );
28063 sqlite3BtreeGetTempCursor(pCur, &leafCur);
28064 rc = sqlite3BtreeNext(&leafCur, &notUsed);
28065 if( rc==SQLITE_OK ){
28066 rc = sqlite3PagerWrite(leafCur.pPage->pDbPage);
28068 if( rc==SQLITE_OK ){
28069 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
28070 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
28071 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
28072 pNext = findCell(leafCur.pPage, leafCur.idx);
28073 szNext = cellSizePtr(leafCur.pPage, pNext);
28074 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
28075 tempCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
28076 if( tempCell==0 ){
28077 rc = SQLITE_NOMEM;
28080 if( rc==SQLITE_OK ){
28081 rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
28083 if( rc==SQLITE_OK ){
28084 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
28085 rc = balance(pPage, 0);
28087 if( rc==SQLITE_OK ){
28088 dropCell(leafCur.pPage, leafCur.idx, szNext);
28089 rc = balance(leafCur.pPage, 0);
28091 sqliteFree(tempCell);
28092 sqlite3BtreeReleaseTempCursor(&leafCur);
28093 }else{
28094 TRACE(("DELETE: table=%d delete from leaf %d\n",
28095 pCur->pgnoRoot, pPage->pgno));
28096 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
28097 rc = balance(pPage, 0);
28099 if( rc==SQLITE_OK ){
28100 moveToRoot(pCur);
28102 return rc;
28106 ** Create a new BTree table. Write into *piTable the page
28107 ** number for the root page of the new table.
28109 ** The type of type is determined by the flags parameter. Only the
28110 ** following values of flags are currently in use. Other values for
28111 ** flags might not work:
28113 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
28114 ** BTREE_ZERODATA Used for SQL indices
28116 static int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
28117 BtShared *pBt = p->pBt;
28118 MemPage *pRoot;
28119 Pgno pgnoRoot;
28120 int rc;
28121 if( pBt->inTransaction!=TRANS_WRITE ){
28122 /* Must start a transaction first */
28123 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
28125 assert( !pBt->readOnly );
28127 #ifdef SQLITE_OMIT_AUTOVACUUM
28128 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
28129 if( rc ) return rc;
28130 #else
28131 if( pBt->autoVacuum ){
28132 Pgno pgnoMove; /* Move a page here to make room for the root-page */
28133 MemPage *pPageMove; /* The page to move to. */
28135 /* Creating a new table may probably require moving an existing database
28136 ** to make room for the new tables root page. In case this page turns
28137 ** out to be an overflow page, delete all overflow page-map caches
28138 ** held by open cursors.
28140 invalidateAllOverflowCache(pBt);
28142 /* Read the value of meta[3] from the database to determine where the
28143 ** root page of the new table should go. meta[3] is the largest root-page
28144 ** created so far, so the new root-page is (meta[3]+1).
28146 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
28147 if( rc!=SQLITE_OK ) return rc;
28148 pgnoRoot++;
28150 /* The new root-page may not be allocated on a pointer-map page, or the
28151 ** PENDING_BYTE page.
28153 if( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
28154 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
28155 pgnoRoot++;
28157 assert( pgnoRoot>=3 );
28159 /* Allocate a page. The page that currently resides at pgnoRoot will
28160 ** be moved to the allocated page (unless the allocated page happens
28161 ** to reside at pgnoRoot).
28163 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
28164 if( rc!=SQLITE_OK ){
28165 return rc;
28168 if( pgnoMove!=pgnoRoot ){
28169 /* pgnoRoot is the page that will be used for the root-page of
28170 ** the new table (assuming an error did not occur). But we were
28171 ** allocated pgnoMove. If required (i.e. if it was not allocated
28172 ** by extending the file), the current page at position pgnoMove
28173 ** is already journaled.
28175 u8 eType;
28176 Pgno iPtrPage;
28178 releasePage(pPageMove);
28180 /* Move the page currently at pgnoRoot to pgnoMove. */
28181 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
28182 if( rc!=SQLITE_OK ){
28183 return rc;
28185 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
28186 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
28187 releasePage(pRoot);
28188 return rc;
28190 assert( eType!=PTRMAP_ROOTPAGE );
28191 assert( eType!=PTRMAP_FREEPAGE );
28192 rc = sqlite3PagerWrite(pRoot->pDbPage);
28193 if( rc!=SQLITE_OK ){
28194 releasePage(pRoot);
28195 return rc;
28197 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
28198 releasePage(pRoot);
28200 /* Obtain the page at pgnoRoot */
28201 if( rc!=SQLITE_OK ){
28202 return rc;
28204 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
28205 if( rc!=SQLITE_OK ){
28206 return rc;
28208 rc = sqlite3PagerWrite(pRoot->pDbPage);
28209 if( rc!=SQLITE_OK ){
28210 releasePage(pRoot);
28211 return rc;
28213 }else{
28214 pRoot = pPageMove;
28217 /* Update the pointer-map and meta-data with the new root-page number. */
28218 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
28219 if( rc ){
28220 releasePage(pRoot);
28221 return rc;
28223 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
28224 if( rc ){
28225 releasePage(pRoot);
28226 return rc;
28229 }else{
28230 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
28231 if( rc ) return rc;
28233 #endif
28234 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
28235 zeroPage(pRoot, flags | PTF_LEAF);
28236 sqlite3PagerUnref(pRoot->pDbPage);
28237 *piTable = (int)pgnoRoot;
28238 return SQLITE_OK;
28242 ** Erase the given database page and all its children. Return
28243 ** the page to the freelist.
28245 static int clearDatabasePage(
28246 BtShared *pBt, /* The BTree that contains the table */
28247 Pgno pgno, /* Page number to clear */
28248 MemPage *pParent, /* Parent page. NULL for the root */
28249 int freePageFlag /* Deallocate page if true */
28251 MemPage *pPage = 0;
28252 int rc;
28253 unsigned char *pCell;
28254 int i;
28256 if( pgno>sqlite3PagerPagecount(pBt->pPager) ){
28257 return SQLITE_CORRUPT_BKPT;
28260 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
28261 if( rc ) goto cleardatabasepage_out;
28262 for(i=0; i<pPage->nCell; i++){
28263 pCell = findCell(pPage, i);
28264 if( !pPage->leaf ){
28265 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
28266 if( rc ) goto cleardatabasepage_out;
28268 rc = clearCell(pPage, pCell);
28269 if( rc ) goto cleardatabasepage_out;
28271 if( !pPage->leaf ){
28272 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
28273 if( rc ) goto cleardatabasepage_out;
28275 if( freePageFlag ){
28276 rc = freePage(pPage);
28277 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
28278 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
28281 cleardatabasepage_out:
28282 releasePage(pPage);
28283 return rc;
28287 ** Delete all information from a single table in the database. iTable is
28288 ** the page number of the root of the table. After this routine returns,
28289 ** the root page is empty, but still exists.
28291 ** This routine will fail with SQLITE_LOCKED if there are any open
28292 ** read cursors on the table. Open write cursors are moved to the
28293 ** root of the table.
28295 static int sqlite3BtreeClearTable(Btree *p, int iTable){
28296 int rc;
28297 BtShared *pBt = p->pBt;
28298 if( p->inTrans!=TRANS_WRITE ){
28299 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
28301 rc = checkReadLocks(p, iTable, 0);
28302 if( rc ){
28303 return rc;
28306 /* Save the position of all cursors open on this table */
28307 if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
28308 return rc;
28311 return clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
28315 ** Erase all information in a table and add the root of the table to
28316 ** the freelist. Except, the root of the principle table (the one on
28317 ** page 1) is never added to the freelist.
28319 ** This routine will fail with SQLITE_LOCKED if there are any open
28320 ** cursors on the table.
28322 ** If AUTOVACUUM is enabled and the page at iTable is not the last
28323 ** root page in the database file, then the last root page
28324 ** in the database file is moved into the slot formerly occupied by
28325 ** iTable and that last slot formerly occupied by the last root page
28326 ** is added to the freelist instead of iTable. In this say, all
28327 ** root pages are kept at the beginning of the database file, which
28328 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
28329 ** page number that used to be the last root page in the file before
28330 ** the move. If no page gets moved, *piMoved is set to 0.
28331 ** The last root page is recorded in meta[3] and the value of
28332 ** meta[3] is updated by this procedure.
28334 static int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
28335 int rc;
28336 MemPage *pPage = 0;
28337 BtShared *pBt = p->pBt;
28339 if( p->inTrans!=TRANS_WRITE ){
28340 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
28343 /* It is illegal to drop a table if any cursors are open on the
28344 ** database. This is because in auto-vacuum mode the backend may
28345 ** need to move another root-page to fill a gap left by the deleted
28346 ** root page. If an open cursor was using this page a problem would
28347 ** occur.
28349 if( pBt->pCursor ){
28350 return SQLITE_LOCKED;
28353 rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
28354 if( rc ) return rc;
28355 rc = sqlite3BtreeClearTable(p, iTable);
28356 if( rc ){
28357 releasePage(pPage);
28358 return rc;
28361 *piMoved = 0;
28363 if( iTable>1 ){
28364 #ifdef SQLITE_OMIT_AUTOVACUUM
28365 rc = freePage(pPage);
28366 releasePage(pPage);
28367 #else
28368 if( pBt->autoVacuum ){
28369 Pgno maxRootPgno;
28370 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
28371 if( rc!=SQLITE_OK ){
28372 releasePage(pPage);
28373 return rc;
28376 if( iTable==maxRootPgno ){
28377 /* If the table being dropped is the table with the largest root-page
28378 ** number in the database, put the root page on the free list.
28380 rc = freePage(pPage);
28381 releasePage(pPage);
28382 if( rc!=SQLITE_OK ){
28383 return rc;
28385 }else{
28386 /* The table being dropped does not have the largest root-page
28387 ** number in the database. So move the page that does into the
28388 ** gap left by the deleted root-page.
28390 MemPage *pMove;
28391 releasePage(pPage);
28392 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
28393 if( rc!=SQLITE_OK ){
28394 return rc;
28396 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
28397 releasePage(pMove);
28398 if( rc!=SQLITE_OK ){
28399 return rc;
28401 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
28402 if( rc!=SQLITE_OK ){
28403 return rc;
28405 rc = freePage(pMove);
28406 releasePage(pMove);
28407 if( rc!=SQLITE_OK ){
28408 return rc;
28410 *piMoved = maxRootPgno;
28413 /* Set the new 'max-root-page' value in the database header. This
28414 ** is the old value less one, less one more if that happens to
28415 ** be a root-page number, less one again if that is the
28416 ** PENDING_BYTE_PAGE.
28418 maxRootPgno--;
28419 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
28420 maxRootPgno--;
28422 if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
28423 maxRootPgno--;
28425 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
28427 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
28428 }else{
28429 rc = freePage(pPage);
28430 releasePage(pPage);
28432 #endif
28433 }else{
28434 /* If sqlite3BtreeDropTable was called on page 1. */
28435 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
28436 releasePage(pPage);
28438 return rc;
28443 ** Read the meta-information out of a database file. Meta[0]
28444 ** is the number of free pages currently in the database. Meta[1]
28445 ** through meta[15] are available for use by higher layers. Meta[0]
28446 ** is read-only, the others are read/write.
28448 ** The schema layer numbers meta values differently. At the schema
28449 ** layer (and the SetCookie and ReadCookie opcodes) the number of
28450 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
28452 static int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
28453 DbPage *pDbPage;
28454 int rc;
28455 unsigned char *pP1;
28456 BtShared *pBt = p->pBt;
28458 /* Reading a meta-data value requires a read-lock on page 1 (and hence
28459 ** the sqlite_master table. We grab this lock regardless of whether or
28460 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
28461 ** 1 is treated as a special case by queryTableLock() and lockTable()).
28463 rc = queryTableLock(p, 1, READ_LOCK);
28464 if( rc!=SQLITE_OK ){
28465 return rc;
28468 assert( idx>=0 && idx<=15 );
28469 rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
28470 if( rc ) return rc;
28471 pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
28472 *pMeta = get4byte(&pP1[36 + idx*4]);
28473 sqlite3PagerUnref(pDbPage);
28475 /* If autovacuumed is disabled in this build but we are trying to
28476 ** access an autovacuumed database, then make the database readonly.
28478 #ifdef SQLITE_OMIT_AUTOVACUUM
28479 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
28480 #endif
28482 /* Grab the read-lock on page 1. */
28483 rc = lockTable(p, 1, READ_LOCK);
28484 return rc;
28488 ** Write meta-information back into the database. Meta[0] is
28489 ** read-only and may not be written.
28491 static int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
28492 BtShared *pBt = p->pBt;
28493 unsigned char *pP1;
28494 int rc;
28495 assert( idx>=1 && idx<=15 );
28496 if( p->inTrans!=TRANS_WRITE ){
28497 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
28499 assert( pBt->pPage1!=0 );
28500 pP1 = pBt->pPage1->aData;
28501 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
28502 if( rc ) return rc;
28503 put4byte(&pP1[36 + idx*4], iMeta);
28504 return SQLITE_OK;
28508 ** Return the flag byte at the beginning of the page that the cursor
28509 ** is currently pointing to.
28511 static int sqlite3BtreeFlags(BtCursor *pCur){
28512 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
28513 ** restoreOrClearCursorPosition() here.
28515 MemPage *pPage = pCur->pPage;
28516 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
28521 ** Return the pager associated with a BTree. This routine is used for
28522 ** testing and debugging only.
28524 static Pager *sqlite3BtreePager(Btree *p){
28525 return p->pBt->pPager;
28528 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
28530 ** Append a message to the error message string.
28532 static void checkAppendMsg(
28533 IntegrityCk *pCheck,
28534 char *zMsg1,
28535 const char *zFormat,
28538 va_list ap;
28539 char *zMsg2;
28540 if( !pCheck->mxErr ) return;
28541 pCheck->mxErr--;
28542 pCheck->nErr++;
28543 va_start(ap, zFormat);
28544 zMsg2 = sqlite3VMPrintf(zFormat, ap);
28545 va_end(ap);
28546 if( zMsg1==0 ) zMsg1 = "";
28547 if( pCheck->zErrMsg ){
28548 char *zOld = pCheck->zErrMsg;
28549 pCheck->zErrMsg = 0;
28550 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
28551 sqliteFree(zOld);
28552 }else{
28553 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
28555 sqliteFree(zMsg2);
28557 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
28559 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
28561 ** Add 1 to the reference count for page iPage. If this is the second
28562 ** reference to the page, add an error message to pCheck->zErrMsg.
28563 ** Return 1 if there are 2 ore more references to the page and 0 if
28564 ** if this is the first reference to the page.
28566 ** Also check that the page number is in bounds.
28568 static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
28569 if( iPage==0 ) return 1;
28570 if( iPage>pCheck->nPage || iPage<0 ){
28571 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
28572 return 1;
28574 if( pCheck->anRef[iPage]==1 ){
28575 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
28576 return 1;
28578 return (pCheck->anRef[iPage]++)>1;
28581 #ifndef SQLITE_OMIT_AUTOVACUUM
28583 ** Check that the entry in the pointer-map for page iChild maps to
28584 ** page iParent, pointer type ptrType. If not, append an error message
28585 ** to pCheck.
28587 static void checkPtrmap(
28588 IntegrityCk *pCheck, /* Integrity check context */
28589 Pgno iChild, /* Child page number */
28590 u8 eType, /* Expected pointer map type */
28591 Pgno iParent, /* Expected pointer map parent page number */
28592 char *zContext /* Context description (used for error msg) */
28594 int rc;
28595 u8 ePtrmapType;
28596 Pgno iPtrmapParent;
28598 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
28599 if( rc!=SQLITE_OK ){
28600 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
28601 return;
28604 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
28605 checkAppendMsg(pCheck, zContext,
28606 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
28607 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
28610 #endif
28613 ** Check the integrity of the freelist or of an overflow page list.
28614 ** Verify that the number of pages on the list is N.
28616 static void checkList(
28617 IntegrityCk *pCheck, /* Integrity checking context */
28618 int isFreeList, /* True for a freelist. False for overflow page list */
28619 int iPage, /* Page number for first page in the list */
28620 int N, /* Expected number of pages in the list */
28621 char *zContext /* Context for error messages */
28623 int i;
28624 int expected = N;
28625 int iFirst = iPage;
28626 while( N-- > 0 && pCheck->mxErr ){
28627 DbPage *pOvflPage;
28628 unsigned char *pOvflData;
28629 if( iPage<1 ){
28630 checkAppendMsg(pCheck, zContext,
28631 "%d of %d pages missing from overflow list starting at %d",
28632 N+1, expected, iFirst);
28633 break;
28635 if( checkRef(pCheck, iPage, zContext) ) break;
28636 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
28637 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
28638 break;
28640 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
28641 if( isFreeList ){
28642 int n = get4byte(&pOvflData[4]);
28643 #ifndef SQLITE_OMIT_AUTOVACUUM
28644 if( pCheck->pBt->autoVacuum ){
28645 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
28647 #endif
28648 if( n>pCheck->pBt->usableSize/4-8 ){
28649 checkAppendMsg(pCheck, zContext,
28650 "freelist leaf count too big on page %d", iPage);
28651 N--;
28652 }else{
28653 for(i=0; i<n; i++){
28654 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
28655 #ifndef SQLITE_OMIT_AUTOVACUUM
28656 if( pCheck->pBt->autoVacuum ){
28657 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
28659 #endif
28660 checkRef(pCheck, iFreePage, zContext);
28662 N -= n;
28665 #ifndef SQLITE_OMIT_AUTOVACUUM
28666 else{
28667 /* If this database supports auto-vacuum and iPage is not the last
28668 ** page in this overflow list, check that the pointer-map entry for
28669 ** the following page matches iPage.
28671 if( pCheck->pBt->autoVacuum && N>0 ){
28672 i = get4byte(pOvflData);
28673 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
28676 #endif
28677 iPage = get4byte(pOvflData);
28678 sqlite3PagerUnref(pOvflPage);
28681 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
28683 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
28685 ** Do various sanity checks on a single page of a tree. Return
28686 ** the tree depth. Root pages return 0. Parents of root pages
28687 ** return 1, and so forth.
28689 ** These checks are done:
28691 ** 1. Make sure that cells and freeblocks do not overlap
28692 ** but combine to completely cover the page.
28693 ** NO 2. Make sure cell keys are in order.
28694 ** NO 3. Make sure no key is less than or equal to zLowerBound.
28695 ** NO 4. Make sure no key is greater than or equal to zUpperBound.
28696 ** 5. Check the integrity of overflow pages.
28697 ** 6. Recursively call checkTreePage on all children.
28698 ** 7. Verify that the depth of all children is the same.
28699 ** 8. Make sure this page is at least 33% full or else it is
28700 ** the root of the tree.
28702 static int checkTreePage(
28703 IntegrityCk *pCheck, /* Context for the sanity check */
28704 int iPage, /* Page number of the page to check */
28705 MemPage *pParent, /* Parent page */
28706 char *zParentContext /* Parent context */
28708 MemPage *pPage;
28709 int i, rc, depth, d2, pgno, cnt;
28710 int hdr, cellStart;
28711 int nCell;
28712 u8 *data;
28713 BtShared *pBt;
28714 int usableSize;
28715 char zContext[100];
28716 char *hit;
28718 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
28720 /* Check that the page exists
28722 pBt = pCheck->pBt;
28723 usableSize = pBt->usableSize;
28724 if( iPage==0 ) return 0;
28725 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
28726 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
28727 checkAppendMsg(pCheck, zContext,
28728 "unable to get the page. error code=%d", rc);
28729 return 0;
28731 if( (rc = sqlite3BtreeInitPage(pPage, pParent))!=0 ){
28732 checkAppendMsg(pCheck, zContext,
28733 "sqlite3BtreeInitPage() returns error code %d", rc);
28734 releasePage(pPage);
28735 return 0;
28738 /* Check out all the cells.
28740 depth = 0;
28741 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
28742 u8 *pCell;
28743 int sz;
28744 CellInfo info;
28746 /* Check payload overflow pages
28748 sqlite3_snprintf(sizeof(zContext), zContext,
28749 "On tree page %d cell %d: ", iPage, i);
28750 pCell = findCell(pPage,i);
28751 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
28752 sz = info.nData;
28753 if( !pPage->intKey ) sz += info.nKey;
28754 assert( sz==info.nPayload );
28755 if( sz>info.nLocal ){
28756 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
28757 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
28758 #ifndef SQLITE_OMIT_AUTOVACUUM
28759 if( pBt->autoVacuum ){
28760 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
28762 #endif
28763 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
28766 /* Check sanity of left child page.
28768 if( !pPage->leaf ){
28769 pgno = get4byte(pCell);
28770 #ifndef SQLITE_OMIT_AUTOVACUUM
28771 if( pBt->autoVacuum ){
28772 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
28774 #endif
28775 d2 = checkTreePage(pCheck,pgno,pPage,zContext);
28776 if( i>0 && d2!=depth ){
28777 checkAppendMsg(pCheck, zContext, "Child page depth differs");
28779 depth = d2;
28782 if( !pPage->leaf ){
28783 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
28784 sqlite3_snprintf(sizeof(zContext), zContext,
28785 "On page %d at right child: ", iPage);
28786 #ifndef SQLITE_OMIT_AUTOVACUUM
28787 if( pBt->autoVacuum ){
28788 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
28790 #endif
28791 checkTreePage(pCheck, pgno, pPage, zContext);
28794 /* Check for complete coverage of the page
28796 data = pPage->aData;
28797 hdr = pPage->hdrOffset;
28798 hit = sqliteMalloc( usableSize );
28799 if( hit ){
28800 memset(hit, 1, get2byte(&data[hdr+5]));
28801 nCell = get2byte(&data[hdr+3]);
28802 cellStart = hdr + 12 - 4*pPage->leaf;
28803 for(i=0; i<nCell; i++){
28804 int pc = get2byte(&data[cellStart+i*2]);
28805 int size = cellSizePtr(pPage, &data[pc]);
28806 int j;
28807 if( (pc+size-1)>=usableSize || pc<0 ){
28808 checkAppendMsg(pCheck, 0,
28809 "Corruption detected in cell %d on page %d",i,iPage,0);
28810 }else{
28811 for(j=pc+size-1; j>=pc; j--) hit[j]++;
28814 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
28815 cnt++){
28816 int size = get2byte(&data[i+2]);
28817 int j;
28818 if( (i+size-1)>=usableSize || i<0 ){
28819 checkAppendMsg(pCheck, 0,
28820 "Corruption detected in cell %d on page %d",i,iPage,0);
28821 }else{
28822 for(j=i+size-1; j>=i; j--) hit[j]++;
28824 i = get2byte(&data[i]);
28826 for(i=cnt=0; i<usableSize; i++){
28827 if( hit[i]==0 ){
28828 cnt++;
28829 }else if( hit[i]>1 ){
28830 checkAppendMsg(pCheck, 0,
28831 "Multiple uses for byte %d of page %d", i, iPage);
28832 break;
28835 if( cnt!=data[hdr+7] ){
28836 checkAppendMsg(pCheck, 0,
28837 "Fragmented space is %d byte reported as %d on page %d",
28838 cnt, data[hdr+7], iPage);
28841 sqliteFree(hit);
28843 releasePage(pPage);
28844 return depth+1;
28846 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
28848 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
28850 ** This routine does a complete check of the given BTree file. aRoot[] is
28851 ** an array of pages numbers were each page number is the root page of
28852 ** a table. nRoot is the number of entries in aRoot.
28854 ** If everything checks out, this routine returns NULL. If something is
28855 ** amiss, an error message is written into memory obtained from malloc()
28856 ** and a pointer to that error message is returned. The calling function
28857 ** is responsible for freeing the error message when it is done.
28859 static char *sqlite3BtreeIntegrityCheck(
28860 Btree *p, /* The btree to be checked */
28861 int *aRoot, /* An array of root pages numbers for individual trees */
28862 int nRoot, /* Number of entries in aRoot[] */
28863 int mxErr, /* Stop reporting errors after this many */
28864 int *pnErr /* Write number of errors seen to this variable */
28866 int i;
28867 int nRef;
28868 IntegrityCk sCheck;
28869 BtShared *pBt = p->pBt;
28871 nRef = sqlite3PagerRefcount(pBt->pPager);
28872 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
28873 return sqliteStrDup("Unable to acquire a read lock on the database");
28875 sCheck.pBt = pBt;
28876 sCheck.pPager = pBt->pPager;
28877 sCheck.nPage = sqlite3PagerPagecount(sCheck.pPager);
28878 sCheck.mxErr = mxErr;
28879 sCheck.nErr = 0;
28880 *pnErr = 0;
28881 #ifndef SQLITE_OMIT_AUTOVACUUM
28882 if( pBt->nTrunc!=0 ){
28883 sCheck.nPage = pBt->nTrunc;
28885 #endif
28886 if( sCheck.nPage==0 ){
28887 unlockBtreeIfUnused(pBt);
28888 return 0;
28890 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
28891 if( !sCheck.anRef ){
28892 unlockBtreeIfUnused(pBt);
28893 *pnErr = 1;
28894 return sqlite3MPrintf("Unable to malloc %d bytes",
28895 (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
28897 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
28898 i = PENDING_BYTE_PAGE(pBt);
28899 if( i<=sCheck.nPage ){
28900 sCheck.anRef[i] = 1;
28902 sCheck.zErrMsg = 0;
28904 /* Check the integrity of the freelist
28906 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
28907 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
28909 /* Check all the tables.
28911 for(i=0; i<nRoot && sCheck.mxErr; i++){
28912 if( aRoot[i]==0 ) continue;
28913 #ifndef SQLITE_OMIT_AUTOVACUUM
28914 if( pBt->autoVacuum && aRoot[i]>1 ){
28915 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
28917 #endif
28918 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ");
28921 /* Make sure every page in the file is referenced
28923 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
28924 #ifdef SQLITE_OMIT_AUTOVACUUM
28925 if( sCheck.anRef[i]==0 ){
28926 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
28928 #else
28929 /* If the database supports auto-vacuum, make sure no tables contain
28930 ** references to pointer-map pages.
28932 if( sCheck.anRef[i]==0 &&
28933 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
28934 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
28936 if( sCheck.anRef[i]!=0 &&
28937 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
28938 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
28940 #endif
28943 /* Make sure this analysis did not leave any unref() pages
28945 unlockBtreeIfUnused(pBt);
28946 if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
28947 checkAppendMsg(&sCheck, 0,
28948 "Outstanding page count goes from %d to %d during this analysis",
28949 nRef, sqlite3PagerRefcount(pBt->pPager)
28953 /* Clean up and report errors.
28955 sqliteFree(sCheck.anRef);
28956 *pnErr = sCheck.nErr;
28957 return sCheck.zErrMsg;
28959 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
28962 ** Return the full pathname of the underlying database file.
28964 static const char *sqlite3BtreeGetFilename(Btree *p){
28965 assert( p->pBt->pPager!=0 );
28966 return sqlite3PagerFilename(p->pBt->pPager);
28970 ** Return the pathname of the directory that contains the database file.
28972 static const char *sqlite3BtreeGetDirname(Btree *p){
28973 assert( p->pBt->pPager!=0 );
28974 return sqlite3PagerDirname(p->pBt->pPager);
28978 ** Return the pathname of the journal file for this database. The return
28979 ** value of this routine is the same regardless of whether the journal file
28980 ** has been created or not.
28982 static const char *sqlite3BtreeGetJournalname(Btree *p){
28983 assert( p->pBt->pPager!=0 );
28984 return sqlite3PagerJournalname(p->pBt->pPager);
28987 #ifndef SQLITE_OMIT_VACUUM
28989 ** Copy the complete content of pBtFrom into pBtTo. A transaction
28990 ** must be active for both files.
28992 ** The size of file pBtFrom may be reduced by this operation.
28993 ** If anything goes wrong, the transaction on pBtFrom is rolled back.
28995 static int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
28996 int rc = SQLITE_OK;
28997 Pgno i, nPage, nToPage, iSkip;
28999 BtShared *pBtTo = pTo->pBt;
29000 BtShared *pBtFrom = pFrom->pBt;
29002 if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
29003 return SQLITE_ERROR;
29005 if( pBtTo->pCursor ) return SQLITE_BUSY;
29006 nToPage = sqlite3PagerPagecount(pBtTo->pPager);
29007 nPage = sqlite3PagerPagecount(pBtFrom->pPager);
29008 iSkip = PENDING_BYTE_PAGE(pBtTo);
29009 for(i=1; rc==SQLITE_OK && i<=nPage; i++){
29010 DbPage *pDbPage;
29011 if( i==iSkip ) continue;
29012 rc = sqlite3PagerGet(pBtFrom->pPager, i, &pDbPage);
29013 if( rc ) break;
29014 rc = sqlite3PagerOverwrite(pBtTo->pPager, i, sqlite3PagerGetData(pDbPage));
29015 sqlite3PagerUnref(pDbPage);
29018 /* If the file is shrinking, journal the pages that are being truncated
29019 ** so that they can be rolled back if the commit fails.
29021 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
29022 DbPage *pDbPage;
29023 if( i==iSkip ) continue;
29024 rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
29025 if( rc ) break;
29026 rc = sqlite3PagerWrite(pDbPage);
29027 sqlite3PagerDontWrite(pDbPage);
29028 /* Yeah. It seems wierd to call DontWrite() right after Write(). But
29029 ** that is because the names of those procedures do not exactly
29030 ** represent what they do. Write() really means "put this page in the
29031 ** rollback journal and mark it as dirty so that it will be written
29032 ** to the database file later." DontWrite() undoes the second part of
29033 ** that and prevents the page from being written to the database. The
29034 ** page is still on the rollback journal, though. And that is the whole
29035 ** point of this loop: to put pages on the rollback journal. */
29036 sqlite3PagerUnref(pDbPage);
29038 if( !rc && nPage<nToPage ){
29039 rc = sqlite3PagerTruncate(pBtTo->pPager, nPage);
29042 if( rc ){
29043 sqlite3BtreeRollback(pTo);
29045 return rc;
29047 #endif /* SQLITE_OMIT_VACUUM */
29050 ** Return non-zero if a transaction is active.
29052 static int sqlite3BtreeIsInTrans(Btree *p){
29053 return (p && (p->inTrans==TRANS_WRITE));
29057 ** Return non-zero if a statement transaction is active.
29059 static int sqlite3BtreeIsInStmt(Btree *p){
29060 return (p->pBt && p->pBt->inStmt);
29064 ** Return non-zero if a read (or write) transaction is active.
29066 static int sqlite3BtreeIsInReadTrans(Btree *p){
29067 return (p && (p->inTrans!=TRANS_NONE));
29071 ** This function returns a pointer to a blob of memory associated with
29072 ** a single shared-btree. The memory is used by client code for it's own
29073 ** purposes (for example, to store a high-level schema associated with
29074 ** the shared-btree). The btree layer manages reference counting issues.
29076 ** The first time this is called on a shared-btree, nBytes bytes of memory
29077 ** are allocated, zeroed, and returned to the caller. For each subsequent
29078 ** call the nBytes parameter is ignored and a pointer to the same blob
29079 ** of memory returned.
29081 ** Just before the shared-btree is closed, the function passed as the
29082 ** xFree argument when the memory allocation was made is invoked on the
29083 ** blob of allocated memory. This function should not call sqliteFree()
29084 ** on the memory, the btree layer does that.
29086 static void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
29087 BtShared *pBt = p->pBt;
29088 if( !pBt->pSchema ){
29089 pBt->pSchema = sqliteMalloc(nBytes);
29090 pBt->xFreeSchema = xFree;
29092 return pBt->pSchema;
29096 ** Return true if another user of the same shared btree as the argument
29097 ** handle holds an exclusive lock on the sqlite_master table.
29099 static int sqlite3BtreeSchemaLocked(Btree *p){
29100 return (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
29104 #ifndef SQLITE_OMIT_SHARED_CACHE
29106 ** Obtain a lock on the table whose root page is iTab. The
29107 ** lock is a write lock if isWritelock is true or a read lock
29108 ** if it is false.
29110 static int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
29111 int rc = SQLITE_OK;
29112 u8 lockType = (isWriteLock?WRITE_LOCK:READ_LOCK);
29113 rc = queryTableLock(p, iTab, lockType);
29114 if( rc==SQLITE_OK ){
29115 rc = lockTable(p, iTab, lockType);
29117 return rc;
29119 #endif
29121 #ifndef SQLITE_OMIT_INCRBLOB
29123 ** Argument pCsr must be a cursor opened for writing on an
29124 ** INTKEY table currently pointing at a valid table entry.
29125 ** This function modifies the data stored as part of that entry.
29126 ** Only the data content may only be modified, it is not possible
29127 ** to change the length of the data stored.
29129 static int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
29131 assert(pCsr->isIncrblobHandle);
29132 if( pCsr->eState==CURSOR_REQUIRESEEK ){
29133 return SQLITE_ABORT;
29136 /* Check some preconditions:
29137 ** (a) the cursor is open for writing,
29138 ** (b) there is no read-lock on the table being modified and
29139 ** (c) the cursor points at a valid row of an intKey table.
29141 if( !pCsr->wrFlag ){
29142 return SQLITE_READONLY;
29144 assert( !pCsr->pBtree->pBt->readOnly
29145 && pCsr->pBtree->pBt->inTransaction==TRANS_WRITE );
29146 if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr) ){
29147 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
29149 if( pCsr->eState==CURSOR_INVALID || !pCsr->pPage->intKey ){
29150 return SQLITE_ERROR;
29153 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
29157 ** Set a flag on this cursor to cache the locations of pages from the
29158 ** overflow list for the current row. This is used by cursors opened
29159 ** for incremental blob IO only.
29161 ** This function sets a flag only. The actual page location cache
29162 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
29163 ** accessPayload() (the worker function for sqlite3BtreeData() and
29164 ** sqlite3BtreePutData()).
29166 static void sqlite3BtreeCacheOverflow(BtCursor *pCur){
29167 assert(!pCur->isIncrblobHandle);
29168 assert(!pCur->aOverflow);
29169 pCur->isIncrblobHandle = 1;
29171 #endif
29173 /************** End of btree.c ***********************************************/
29174 /************** Begin file vdbefifo.c ****************************************/
29176 ** 2005 June 16
29178 ** The author disclaims copyright to this source code. In place of
29179 ** a legal notice, here is a blessing:
29181 ** May you do good and not evil.
29182 ** May you find forgiveness for yourself and forgive others.
29183 ** May you share freely, never taking more than you give.
29185 *************************************************************************
29186 ** This file implements a FIFO queue of rowids used for processing
29187 ** UPDATE and DELETE statements.
29191 ** Allocate a new FifoPage and return a pointer to it. Return NULL if
29192 ** we run out of memory. Leave space on the page for nEntry entries.
29194 static FifoPage *allocateFifoPage(int nEntry){
29195 FifoPage *pPage;
29196 if( nEntry>32767 ){
29197 nEntry = 32767;
29199 pPage = sqliteMallocRaw( sizeof(FifoPage) + sizeof(i64)*(nEntry-1) );
29200 if( pPage ){
29201 pPage->nSlot = nEntry;
29202 pPage->iWrite = 0;
29203 pPage->iRead = 0;
29204 pPage->pNext = 0;
29206 return pPage;
29210 ** Initialize a Fifo structure.
29212 static void sqlite3VdbeFifoInit(Fifo *pFifo){
29213 memset(pFifo, 0, sizeof(*pFifo));
29217 ** Push a single 64-bit integer value into the Fifo. Return SQLITE_OK
29218 ** normally. SQLITE_NOMEM is returned if we are unable to allocate
29219 ** memory.
29221 static int sqlite3VdbeFifoPush(Fifo *pFifo, i64 val){
29222 FifoPage *pPage;
29223 pPage = pFifo->pLast;
29224 if( pPage==0 ){
29225 pPage = pFifo->pLast = pFifo->pFirst = allocateFifoPage(20);
29226 if( pPage==0 ){
29227 return SQLITE_NOMEM;
29229 }else if( pPage->iWrite>=pPage->nSlot ){
29230 pPage->pNext = allocateFifoPage(pFifo->nEntry);
29231 if( pPage->pNext==0 ){
29232 return SQLITE_NOMEM;
29234 pPage = pFifo->pLast = pPage->pNext;
29236 pPage->aSlot[pPage->iWrite++] = val;
29237 pFifo->nEntry++;
29238 return SQLITE_OK;
29242 ** Extract a single 64-bit integer value from the Fifo. The integer
29243 ** extracted is the one least recently inserted. If the Fifo is empty
29244 ** return SQLITE_DONE.
29246 static int sqlite3VdbeFifoPop(Fifo *pFifo, i64 *pVal){
29247 FifoPage *pPage;
29248 if( pFifo->nEntry==0 ){
29249 return SQLITE_DONE;
29251 assert( pFifo->nEntry>0 );
29252 pPage = pFifo->pFirst;
29253 assert( pPage!=0 );
29254 assert( pPage->iWrite>pPage->iRead );
29255 assert( pPage->iWrite<=pPage->nSlot );
29256 assert( pPage->iRead<pPage->nSlot );
29257 assert( pPage->iRead>=0 );
29258 *pVal = pPage->aSlot[pPage->iRead++];
29259 pFifo->nEntry--;
29260 if( pPage->iRead>=pPage->iWrite ){
29261 pFifo->pFirst = pPage->pNext;
29262 sqliteFree(pPage);
29263 if( pFifo->nEntry==0 ){
29264 assert( pFifo->pLast==pPage );
29265 pFifo->pLast = 0;
29266 }else{
29267 assert( pFifo->pFirst!=0 );
29269 }else{
29270 assert( pFifo->nEntry>0 );
29272 return SQLITE_OK;
29276 ** Delete all information from a Fifo object. Free all memory held
29277 ** by the Fifo.
29279 static void sqlite3VdbeFifoClear(Fifo *pFifo){
29280 FifoPage *pPage, *pNextPage;
29281 for(pPage=pFifo->pFirst; pPage; pPage=pNextPage){
29282 pNextPage = pPage->pNext;
29283 sqliteFree(pPage);
29285 sqlite3VdbeFifoInit(pFifo);
29288 /************** End of vdbefifo.c ********************************************/
29289 /************** Begin file vdbemem.c *****************************************/
29291 ** 2004 May 26
29293 ** The author disclaims copyright to this source code. In place of
29294 ** a legal notice, here is a blessing:
29296 ** May you do good and not evil.
29297 ** May you find forgiveness for yourself and forgive others.
29298 ** May you share freely, never taking more than you give.
29300 *************************************************************************
29302 ** This file contains code use to manipulate "Mem" structure. A "Mem"
29303 ** stores a single value in the VDBE. Mem is an opaque structure visible
29304 ** only within the VDBE. Interface routines refer to a Mem using the
29305 ** name sqlite_value
29309 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
29310 ** P if required.
29312 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
29315 ** If pMem is an object with a valid string representation, this routine
29316 ** ensures the internal encoding for the string representation is
29317 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
29319 ** If pMem is not a string object, or the encoding of the string
29320 ** representation is already stored using the requested encoding, then this
29321 ** routine is a no-op.
29323 ** SQLITE_OK is returned if the conversion is successful (or not required).
29324 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
29325 ** between formats.
29327 static int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
29328 int rc;
29329 if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
29330 return SQLITE_OK;
29332 #ifdef SQLITE_OMIT_UTF16
29333 return SQLITE_ERROR;
29334 #else
29337 /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
29338 ** then the encoding of the value may not have changed.
29340 rc = sqlite3VdbeMemTranslate(pMem, desiredEnc);
29341 assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
29342 assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
29343 assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
29344 return rc;
29345 #endif
29349 ** Make the given Mem object MEM_Dyn.
29351 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
29353 static int sqlite3VdbeMemDynamicify(Mem *pMem){
29354 int n;
29355 u8 *z;
29356 expandBlob(pMem);
29357 if( (pMem->flags & (MEM_Ephem|MEM_Static|MEM_Short))==0 ){
29358 return SQLITE_OK;
29360 assert( (pMem->flags & MEM_Dyn)==0 );
29361 n = pMem->n;
29362 assert( pMem->flags & (MEM_Str|MEM_Blob) );
29363 z = sqliteMallocRaw( n+2 );
29364 if( z==0 ){
29365 return SQLITE_NOMEM;
29367 pMem->flags |= MEM_Dyn|MEM_Term;
29368 pMem->xDel = 0;
29369 memcpy(z, pMem->z, n );
29370 z[n] = 0;
29371 z[n+1] = 0;
29372 pMem->z = (char*)z;
29373 pMem->flags &= ~(MEM_Ephem|MEM_Static|MEM_Short);
29374 return SQLITE_OK;
29378 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
29379 ** blob stored in dynamically allocated space.
29381 #ifndef SQLITE_OMIT_INCRBLOB
29382 static int sqlite3VdbeMemExpandBlob(Mem *pMem){
29383 if( pMem->flags & MEM_Zero ){
29384 char *pNew;
29385 int nByte;
29386 assert( (pMem->flags & MEM_Blob)!=0 );
29387 nByte = pMem->n + pMem->u.i;
29388 if( nByte<=0 ) nByte = 1;
29389 pNew = sqliteMalloc(nByte);
29390 if( pNew==0 ){
29391 return SQLITE_NOMEM;
29393 memcpy(pNew, pMem->z, pMem->n);
29394 memset(&pNew[pMem->n], 0, pMem->u.i);
29395 sqlite3VdbeMemRelease(pMem);
29396 pMem->z = pNew;
29397 pMem->n += pMem->u.i;
29398 pMem->u.i = 0;
29399 pMem->flags &= ~(MEM_Zero|MEM_Static|MEM_Ephem|MEM_Short|MEM_Term);
29400 pMem->flags |= MEM_Dyn;
29402 return SQLITE_OK;
29404 #endif
29408 ** Make the given Mem object either MEM_Short or MEM_Dyn so that bytes
29409 ** of the Mem.z[] array can be modified.
29411 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
29413 static int sqlite3VdbeMemMakeWriteable(Mem *pMem){
29414 int n;
29415 u8 *z;
29416 expandBlob(pMem);
29417 if( (pMem->flags & (MEM_Ephem|MEM_Static))==0 ){
29418 return SQLITE_OK;
29420 assert( (pMem->flags & MEM_Dyn)==0 );
29421 assert( pMem->flags & (MEM_Str|MEM_Blob) );
29422 if( (n = pMem->n)+2<sizeof(pMem->zShort) ){
29423 z = (u8*)pMem->zShort;
29424 pMem->flags |= MEM_Short|MEM_Term;
29425 }else{
29426 z = sqliteMallocRaw( n+2 );
29427 if( z==0 ){
29428 return SQLITE_NOMEM;
29430 pMem->flags |= MEM_Dyn|MEM_Term;
29431 pMem->xDel = 0;
29433 memcpy(z, pMem->z, n );
29434 z[n] = 0;
29435 z[n+1] = 0;
29436 pMem->z = (char*)z;
29437 pMem->flags &= ~(MEM_Ephem|MEM_Static);
29438 assert(0==(1&(int)pMem->z));
29439 return SQLITE_OK;
29443 ** Make sure the given Mem is \u0000 terminated.
29445 static int sqlite3VdbeMemNulTerminate(Mem *pMem){
29446 if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
29447 return SQLITE_OK; /* Nothing to do */
29449 if( pMem->flags & (MEM_Static|MEM_Ephem) ){
29450 return sqlite3VdbeMemMakeWriteable(pMem);
29451 }else{
29452 char *z;
29453 sqlite3VdbeMemExpandBlob(pMem);
29454 z = sqliteMalloc(pMem->n+2);
29456 if( !z ) return SQLITE_NOMEM;
29457 memcpy(z, pMem->z, pMem->n);
29458 z[pMem->n] = 0;
29459 z[pMem->n+1] = 0;
29460 if( pMem->xDel ){
29461 pMem->xDel(pMem->z);
29462 }else{
29463 sqliteFree(pMem->z);
29465 pMem->xDel = 0;
29466 pMem->z = z;
29467 pMem->flags |= MEM_Term;
29469 return SQLITE_OK;
29473 ** Add MEM_Str to the set of representations for the given Mem. Numbers
29474 ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
29475 ** is a no-op.
29477 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
29479 ** A MEM_Null value will never be passed to this function. This function is
29480 ** used for converting values to text for returning to the user (i.e. via
29481 ** sqlite3_value_text()), or for ensuring that values to be used as btree
29482 ** keys are strings. In the former case a NULL pointer is returned the
29483 ** user and the later is an internal programming error.
29485 static int sqlite3VdbeMemStringify(Mem *pMem, int enc){
29486 int rc = SQLITE_OK;
29487 int fg = pMem->flags;
29488 char *z = pMem->zShort;
29490 assert( !(fg&MEM_Zero) );
29491 assert( !(fg&(MEM_Str|MEM_Blob)) );
29492 assert( fg&(MEM_Int|MEM_Real) );
29494 /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
29495 ** string representation of the value. Then, if the required encoding
29496 ** is UTF-16le or UTF-16be do a translation.
29498 ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
29500 if( fg & MEM_Int ){
29501 sqlite3_snprintf(NBFS, z, "%lld", pMem->u.i);
29502 }else{
29503 assert( fg & MEM_Real );
29504 sqlite3_snprintf(NBFS, z, "%!.15g", pMem->r);
29506 pMem->n = strlen(z);
29507 pMem->z = z;
29508 pMem->enc = SQLITE_UTF8;
29509 pMem->flags |= MEM_Str | MEM_Short | MEM_Term;
29510 sqlite3VdbeChangeEncoding(pMem, enc);
29511 return rc;
29515 ** Memory cell pMem contains the context of an aggregate function.
29516 ** This routine calls the finalize method for that function. The
29517 ** result of the aggregate is stored back into pMem.
29519 ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
29520 ** otherwise.
29522 static int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
29523 int rc = SQLITE_OK;
29524 if( pFunc && pFunc->xFinalize ){
29525 sqlite3_context ctx;
29526 assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
29527 ctx.s.flags = MEM_Null;
29528 ctx.s.z = pMem->zShort;
29529 ctx.pMem = pMem;
29530 ctx.pFunc = pFunc;
29531 ctx.isError = 0;
29532 pFunc->xFinalize(&ctx);
29533 if( pMem->z && pMem->z!=pMem->zShort ){
29534 sqliteFree( pMem->z );
29536 *pMem = ctx.s;
29537 if( pMem->flags & MEM_Short ){
29538 pMem->z = pMem->zShort;
29540 if( ctx.isError ){
29541 rc = SQLITE_ERROR;
29544 return rc;
29548 ** Release any memory held by the Mem. This may leave the Mem in an
29549 ** inconsistent state, for example with (Mem.z==0) and
29550 ** (Mem.type==SQLITE_TEXT).
29552 static void sqlite3VdbeMemRelease(Mem *p){
29553 if( p->flags & (MEM_Dyn|MEM_Agg) ){
29554 if( p->xDel ){
29555 if( p->flags & MEM_Agg ){
29556 sqlite3VdbeMemFinalize(p, p->u.pDef);
29557 assert( (p->flags & MEM_Agg)==0 );
29558 sqlite3VdbeMemRelease(p);
29559 }else{
29560 p->xDel((void *)p->z);
29562 }else{
29563 sqliteFree(p->z);
29565 p->z = 0;
29566 p->xDel = 0;
29571 ** Return some kind of integer value which is the best we can do
29572 ** at representing the value that *pMem describes as an integer.
29573 ** If pMem is an integer, then the value is exact. If pMem is
29574 ** a floating-point then the value returned is the integer part.
29575 ** If pMem is a string or blob, then we make an attempt to convert
29576 ** it into a integer and return that. If pMem is NULL, return 0.
29578 ** If pMem is a string, its encoding might be changed.
29580 static i64 sqlite3VdbeIntValue(Mem *pMem){
29581 int flags = pMem->flags;
29582 if( flags & MEM_Int ){
29583 return pMem->u.i;
29584 }else if( flags & MEM_Real ){
29585 return (i64)pMem->r;
29586 }else if( flags & (MEM_Str|MEM_Blob) ){
29587 i64 value;
29588 pMem->flags |= MEM_Str;
29589 if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
29590 || sqlite3VdbeMemNulTerminate(pMem) ){
29591 return 0;
29593 assert( pMem->z );
29594 sqlite3Atoi64(pMem->z, &value);
29595 return value;
29596 }else{
29597 return 0;
29602 ** Return the best representation of pMem that we can get into a
29603 ** double. If pMem is already a double or an integer, return its
29604 ** value. If it is a string or blob, try to convert it to a double.
29605 ** If it is a NULL, return 0.0.
29607 static double sqlite3VdbeRealValue(Mem *pMem){
29608 if( pMem->flags & MEM_Real ){
29609 return pMem->r;
29610 }else if( pMem->flags & MEM_Int ){
29611 return (double)pMem->u.i;
29612 }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
29613 double val = 0.0;
29614 pMem->flags |= MEM_Str;
29615 if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
29616 || sqlite3VdbeMemNulTerminate(pMem) ){
29617 return 0.0;
29619 assert( pMem->z );
29620 sqlite3AtoF(pMem->z, &val);
29621 return val;
29622 }else{
29623 return 0.0;
29628 ** The MEM structure is already a MEM_Real. Try to also make it a
29629 ** MEM_Int if we can.
29631 static void sqlite3VdbeIntegerAffinity(Mem *pMem){
29632 assert( pMem->flags & MEM_Real );
29633 pMem->u.i = pMem->r;
29634 if( ((double)pMem->u.i)==pMem->r ){
29635 pMem->flags |= MEM_Int;
29640 ** Convert pMem to type integer. Invalidate any prior representations.
29642 static int sqlite3VdbeMemIntegerify(Mem *pMem){
29643 pMem->u.i = sqlite3VdbeIntValue(pMem);
29644 sqlite3VdbeMemRelease(pMem);
29645 pMem->flags = MEM_Int;
29646 return SQLITE_OK;
29650 ** Convert pMem so that it is of type MEM_Real.
29651 ** Invalidate any prior representations.
29653 static int sqlite3VdbeMemRealify(Mem *pMem){
29654 pMem->r = sqlite3VdbeRealValue(pMem);
29655 sqlite3VdbeMemRelease(pMem);
29656 pMem->flags = MEM_Real;
29657 return SQLITE_OK;
29661 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
29662 ** Invalidate any prior representations.
29664 static int sqlite3VdbeMemNumerify(Mem *pMem){
29665 double r1, r2;
29666 i64 i;
29667 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
29668 assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
29669 r1 = sqlite3VdbeRealValue(pMem);
29670 i = (i64)r1;
29671 r2 = (double)i;
29672 if( r1==r2 ){
29673 sqlite3VdbeMemIntegerify(pMem);
29674 }else{
29675 pMem->r = r1;
29676 pMem->flags = MEM_Real;
29677 sqlite3VdbeMemRelease(pMem);
29679 return SQLITE_OK;
29683 ** Delete any previous value and set the value stored in *pMem to NULL.
29685 static void sqlite3VdbeMemSetNull(Mem *pMem){
29686 sqlite3VdbeMemRelease(pMem);
29687 pMem->flags = MEM_Null;
29688 pMem->type = SQLITE_NULL;
29689 pMem->n = 0;
29693 ** Delete any previous value and set the value to be a BLOB of length
29694 ** n containing all zeros.
29696 static void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
29697 sqlite3VdbeMemRelease(pMem);
29698 pMem->flags = MEM_Blob|MEM_Zero|MEM_Short;
29699 pMem->type = SQLITE_BLOB;
29700 pMem->n = 0;
29701 if( n<0 ) n = 0;
29702 pMem->u.i = n;
29703 pMem->z = pMem->zShort;
29704 pMem->enc = SQLITE_UTF8;
29708 ** Delete any previous value and set the value stored in *pMem to val,
29709 ** manifest type INTEGER.
29711 static void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
29712 sqlite3VdbeMemRelease(pMem);
29713 pMem->u.i = val;
29714 pMem->flags = MEM_Int;
29715 pMem->type = SQLITE_INTEGER;
29719 ** Delete any previous value and set the value stored in *pMem to val,
29720 ** manifest type REAL.
29722 static void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
29723 if( isnan(val) ){
29724 sqlite3VdbeMemSetNull(pMem);
29725 }else{
29726 sqlite3VdbeMemRelease(pMem);
29727 pMem->r = val;
29728 pMem->flags = MEM_Real;
29729 pMem->type = SQLITE_FLOAT;
29734 ** Return true if the Mem object contains a TEXT or BLOB that is
29735 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
29737 static int sqlite3VdbeMemTooBig(Mem *p){
29738 if( p->flags & (MEM_Str|MEM_Blob) ){
29739 int n = p->n;
29740 if( p->flags & MEM_Zero ){
29741 n += p->u.i;
29743 return n>SQLITE_MAX_LENGTH;
29745 return 0;
29749 ** Make an shallow copy of pFrom into pTo. Prior contents of
29750 ** pTo are overwritten. The pFrom->z field is not duplicated. If
29751 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
29752 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
29754 static void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
29755 memcpy(pTo, pFrom, sizeof(*pFrom)-sizeof(pFrom->zShort));
29756 pTo->xDel = 0;
29757 if( pTo->flags & (MEM_Str|MEM_Blob) ){
29758 pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Short|MEM_Ephem);
29759 assert( srcType==MEM_Ephem || srcType==MEM_Static );
29760 pTo->flags |= srcType;
29765 ** Make a full copy of pFrom into pTo. Prior contents of pTo are
29766 ** freed before the copy is made.
29768 static int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
29769 int rc;
29770 if( pTo->flags & MEM_Dyn ){
29771 sqlite3VdbeMemRelease(pTo);
29773 sqlite3VdbeMemShallowCopy(pTo, pFrom, MEM_Ephem);
29774 if( pTo->flags & MEM_Ephem ){
29775 rc = sqlite3VdbeMemMakeWriteable(pTo);
29776 }else{
29777 rc = SQLITE_OK;
29779 return rc;
29783 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
29784 ** freed. If pFrom contains ephemeral data, a copy is made.
29786 ** pFrom contains an SQL NULL when this routine returns. SQLITE_NOMEM
29787 ** might be returned if pFrom held ephemeral data and we were unable
29788 ** to allocate enough space to make a copy.
29790 static int sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
29791 int rc;
29792 if( pTo->flags & MEM_Dyn ){
29793 sqlite3VdbeMemRelease(pTo);
29795 memcpy(pTo, pFrom, sizeof(Mem));
29796 if( pFrom->flags & MEM_Short ){
29797 pTo->z = pTo->zShort;
29799 pFrom->flags = MEM_Null;
29800 pFrom->xDel = 0;
29801 if( pTo->flags & MEM_Ephem ){
29802 rc = sqlite3VdbeMemMakeWriteable(pTo);
29803 }else{
29804 rc = SQLITE_OK;
29806 return rc;
29810 ** Change the value of a Mem to be a string or a BLOB.
29812 static int sqlite3VdbeMemSetStr(
29813 Mem *pMem, /* Memory cell to set to string value */
29814 const char *z, /* String pointer */
29815 int n, /* Bytes in string, or negative */
29816 u8 enc, /* Encoding of z. 0 for BLOBs */
29817 void (*xDel)(void*) /* Destructor function */
29819 sqlite3VdbeMemRelease(pMem);
29820 if( !z ){
29821 pMem->flags = MEM_Null;
29822 pMem->type = SQLITE_NULL;
29823 return SQLITE_OK;
29826 pMem->z = (char *)z;
29827 if( xDel==SQLITE_STATIC ){
29828 pMem->flags = MEM_Static;
29829 }else if( xDel==SQLITE_TRANSIENT ){
29830 pMem->flags = MEM_Ephem;
29831 }else{
29832 pMem->flags = MEM_Dyn;
29833 pMem->xDel = xDel;
29836 pMem->enc = enc;
29837 pMem->type = enc==0 ? SQLITE_BLOB : SQLITE_TEXT;
29838 pMem->n = n;
29840 assert( enc==0 || enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE
29841 || enc==SQLITE_UTF16BE );
29842 switch( enc ){
29843 case 0:
29844 pMem->flags |= MEM_Blob;
29845 pMem->enc = SQLITE_UTF8;
29846 break;
29848 case SQLITE_UTF8:
29849 pMem->flags |= MEM_Str;
29850 if( n<0 ){
29851 pMem->n = strlen(z);
29852 pMem->flags |= MEM_Term;
29854 break;
29856 #ifndef SQLITE_OMIT_UTF16
29857 case SQLITE_UTF16LE:
29858 case SQLITE_UTF16BE:
29859 pMem->flags |= MEM_Str;
29860 if( pMem->n<0 ){
29861 pMem->n = sqlite3Utf16ByteLen(pMem->z,-1);
29862 pMem->flags |= MEM_Term;
29864 if( sqlite3VdbeMemHandleBom(pMem) ){
29865 return SQLITE_NOMEM;
29867 #endif /* SQLITE_OMIT_UTF16 */
29869 if( pMem->flags&MEM_Ephem ){
29870 return sqlite3VdbeMemMakeWriteable(pMem);
29872 return SQLITE_OK;
29876 ** Compare the values contained by the two memory cells, returning
29877 ** negative, zero or positive if pMem1 is less than, equal to, or greater
29878 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
29879 ** and reals) sorted numerically, followed by text ordered by the collating
29880 ** sequence pColl and finally blob's ordered by memcmp().
29882 ** Two NULL values are considered equal by this function.
29884 static int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
29885 int rc;
29886 int f1, f2;
29887 int combined_flags;
29889 /* Interchange pMem1 and pMem2 if the collating sequence specifies
29890 ** DESC order.
29892 f1 = pMem1->flags;
29893 f2 = pMem2->flags;
29894 combined_flags = f1|f2;
29896 /* If one value is NULL, it is less than the other. If both values
29897 ** are NULL, return 0.
29899 if( combined_flags&MEM_Null ){
29900 return (f2&MEM_Null) - (f1&MEM_Null);
29903 /* If one value is a number and the other is not, the number is less.
29904 ** If both are numbers, compare as reals if one is a real, or as integers
29905 ** if both values are integers.
29907 if( combined_flags&(MEM_Int|MEM_Real) ){
29908 if( !(f1&(MEM_Int|MEM_Real)) ){
29909 return 1;
29911 if( !(f2&(MEM_Int|MEM_Real)) ){
29912 return -1;
29914 if( (f1 & f2 & MEM_Int)==0 ){
29915 double r1, r2;
29916 if( (f1&MEM_Real)==0 ){
29917 r1 = pMem1->u.i;
29918 }else{
29919 r1 = pMem1->r;
29921 if( (f2&MEM_Real)==0 ){
29922 r2 = pMem2->u.i;
29923 }else{
29924 r2 = pMem2->r;
29926 if( r1<r2 ) return -1;
29927 if( r1>r2 ) return 1;
29928 return 0;
29929 }else{
29930 assert( f1&MEM_Int );
29931 assert( f2&MEM_Int );
29932 if( pMem1->u.i < pMem2->u.i ) return -1;
29933 if( pMem1->u.i > pMem2->u.i ) return 1;
29934 return 0;
29938 /* If one value is a string and the other is a blob, the string is less.
29939 ** If both are strings, compare using the collating functions.
29941 if( combined_flags&MEM_Str ){
29942 if( (f1 & MEM_Str)==0 ){
29943 return 1;
29945 if( (f2 & MEM_Str)==0 ){
29946 return -1;
29949 assert( pMem1->enc==pMem2->enc );
29950 assert( pMem1->enc==SQLITE_UTF8 ||
29951 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
29953 /* The collation sequence must be defined at this point, even if
29954 ** the user deletes the collation sequence after the vdbe program is
29955 ** compiled (this was not always the case).
29957 assert( !pColl || pColl->xCmp );
29959 if( pColl ){
29960 if( pMem1->enc==pColl->enc ){
29961 /* The strings are already in the correct encoding. Call the
29962 ** comparison function directly */
29963 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
29964 }else{
29965 u8 origEnc = pMem1->enc;
29966 const void *v1, *v2;
29967 int n1, n2;
29968 /* Convert the strings into the encoding that the comparison
29969 ** function expects */
29970 v1 = sqlite3ValueText((sqlite3_value*)pMem1, pColl->enc);
29971 n1 = v1==0 ? 0 : pMem1->n;
29972 assert( n1==sqlite3ValueBytes((sqlite3_value*)pMem1, pColl->enc) );
29973 v2 = sqlite3ValueText((sqlite3_value*)pMem2, pColl->enc);
29974 n2 = v2==0 ? 0 : pMem2->n;
29975 assert( n2==sqlite3ValueBytes((sqlite3_value*)pMem2, pColl->enc) );
29976 /* Do the comparison */
29977 rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
29978 /* Convert the strings back into the database encoding */
29979 sqlite3ValueText((sqlite3_value*)pMem1, origEnc);
29980 sqlite3ValueText((sqlite3_value*)pMem2, origEnc);
29981 return rc;
29984 /* If a NULL pointer was passed as the collate function, fall through
29985 ** to the blob case and use memcmp(). */
29988 /* Both values must be blobs. Compare using memcmp(). */
29989 rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
29990 if( rc==0 ){
29991 rc = pMem1->n - pMem2->n;
29993 return rc;
29997 ** Move data out of a btree key or data field and into a Mem structure.
29998 ** The data or key is taken from the entry that pCur is currently pointing
29999 ** to. offset and amt determine what portion of the data or key to retrieve.
30000 ** key is true to get the key or false to get data. The result is written
30001 ** into the pMem element.
30003 ** The pMem structure is assumed to be uninitialized. Any prior content
30004 ** is overwritten without being freed.
30006 ** If this routine fails for any reason (malloc returns NULL or unable
30007 ** to read from the disk) then the pMem is left in an inconsistent state.
30009 static int sqlite3VdbeMemFromBtree(
30010 BtCursor *pCur, /* Cursor pointing at record to retrieve. */
30011 int offset, /* Offset from the start of data to return bytes from. */
30012 int amt, /* Number of bytes to return. */
30013 int key, /* If true, retrieve from the btree key, not data. */
30014 Mem *pMem /* OUT: Return data in this Mem structure. */
30016 char *zData; /* Data from the btree layer */
30017 int available = 0; /* Number of bytes available on the local btree page */
30019 if( key ){
30020 zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
30021 }else{
30022 zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
30024 assert( zData!=0 );
30026 pMem->n = amt;
30027 if( offset+amt<=available ){
30028 pMem->z = &zData[offset];
30029 pMem->flags = MEM_Blob|MEM_Ephem;
30030 }else{
30031 int rc;
30032 if( amt>NBFS-2 ){
30033 zData = (char *)sqliteMallocRaw(amt+2);
30034 if( !zData ){
30035 return SQLITE_NOMEM;
30037 pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
30038 pMem->xDel = 0;
30039 }else{
30040 zData = &(pMem->zShort[0]);
30041 pMem->flags = MEM_Blob|MEM_Short|MEM_Term;
30043 pMem->z = zData;
30044 pMem->enc = 0;
30045 pMem->type = SQLITE_BLOB;
30047 if( key ){
30048 rc = sqlite3BtreeKey(pCur, offset, amt, zData);
30049 }else{
30050 rc = sqlite3BtreeData(pCur, offset, amt, zData);
30052 zData[amt] = 0;
30053 zData[amt+1] = 0;
30054 if( rc!=SQLITE_OK ){
30055 if( amt>NBFS-2 ){
30056 assert( zData!=pMem->zShort );
30057 assert( pMem->flags & MEM_Dyn );
30058 sqliteFree(zData);
30059 } else {
30060 assert( zData==pMem->zShort );
30061 assert( pMem->flags & MEM_Short );
30063 return rc;
30067 return SQLITE_OK;
30070 #ifndef NDEBUG
30072 ** Perform various checks on the memory cell pMem. An assert() will
30073 ** fail if pMem is internally inconsistent.
30075 static void sqlite3VdbeMemSanity(Mem *pMem){
30076 int flags = pMem->flags;
30077 assert( flags!=0 ); /* Must define some type */
30078 if( flags & (MEM_Str|MEM_Blob) ){
30079 int x = flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
30080 assert( x!=0 ); /* Strings must define a string subtype */
30081 assert( (x & (x-1))==0 ); /* Only one string subtype can be defined */
30082 assert( pMem->z!=0 ); /* Strings must have a value */
30083 /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
30084 assert( (x & MEM_Short)==0 || pMem->z==pMem->zShort );
30085 assert( (x & MEM_Short)!=0 || pMem->z!=pMem->zShort );
30086 /* No destructor unless there is MEM_Dyn */
30087 assert( pMem->xDel==0 || (pMem->flags & MEM_Dyn)!=0 );
30089 if( (flags & MEM_Str) ){
30090 assert( pMem->enc==SQLITE_UTF8 ||
30091 pMem->enc==SQLITE_UTF16BE ||
30092 pMem->enc==SQLITE_UTF16LE
30094 /* If the string is UTF-8 encoded and nul terminated, then pMem->n
30095 ** must be the length of the string. (Later:) If the database file
30096 ** has been corrupted, '\000' characters might have been inserted
30097 ** into the middle of the string. In that case, the strlen() might
30098 ** be less.
30100 if( pMem->enc==SQLITE_UTF8 && (flags & MEM_Term) ){
30101 assert( strlen(pMem->z)<=pMem->n );
30102 assert( pMem->z[pMem->n]==0 );
30105 }else{
30106 /* Cannot define a string subtype for non-string objects */
30107 assert( (pMem->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
30108 assert( pMem->xDel==0 );
30110 /* MEM_Null excludes all other types */
30111 assert( (pMem->flags&(MEM_Str|MEM_Int|MEM_Real|MEM_Blob))==0
30112 || (pMem->flags&MEM_Null)==0 );
30113 /* If the MEM is both real and integer, the values are equal */
30114 assert( (pMem->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real)
30115 || pMem->r==pMem->u.i );
30117 #endif
30119 /* This function is only available internally, it is not part of the
30120 ** external API. It works in a similar way to sqlite3_value_text(),
30121 ** except the data returned is in the encoding specified by the second
30122 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
30123 ** SQLITE_UTF8.
30125 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
30126 ** If that is the case, then the result must be aligned on an even byte
30127 ** boundary.
30129 static const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
30130 if( !pVal ) return 0;
30131 assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
30133 if( pVal->flags&MEM_Null ){
30134 return 0;
30136 assert( (MEM_Blob>>3) == MEM_Str );
30137 pVal->flags |= (pVal->flags & MEM_Blob)>>3;
30138 expandBlob(pVal);
30139 if( pVal->flags&MEM_Str ){
30140 sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
30141 if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&(int)pVal->z) ){
30142 assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
30143 if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
30144 return 0;
30147 sqlite3VdbeMemNulTerminate(pVal);
30148 }else{
30149 assert( (pVal->flags&MEM_Blob)==0 );
30150 sqlite3VdbeMemStringify(pVal, enc);
30151 assert( 0==(1&(int)pVal->z) );
30153 assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || sqlite3MallocFailed() );
30154 if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
30155 return pVal->z;
30156 }else{
30157 return 0;
30162 ** Create a new sqlite3_value object.
30164 static sqlite3_value *sqlite3ValueNew(void){
30165 Mem *p = sqliteMalloc(sizeof(*p));
30166 if( p ){
30167 p->flags = MEM_Null;
30168 p->type = SQLITE_NULL;
30170 return p;
30174 ** Create a new sqlite3_value object, containing the value of pExpr.
30176 ** This only works for very simple expressions that consist of one constant
30177 ** token (i.e. "5", "5.1", "NULL", "'a string'"). If the expression can
30178 ** be converted directly into a value, then the value is allocated and
30179 ** a pointer written to *ppVal. The caller is responsible for deallocating
30180 ** the value by passing it to sqlite3ValueFree() later on. If the expression
30181 ** cannot be converted to a value, then *ppVal is set to NULL.
30183 static int sqlite3ValueFromExpr(
30184 Expr *pExpr,
30185 u8 enc,
30186 u8 affinity,
30187 sqlite3_value **ppVal
30189 int op;
30190 char *zVal = 0;
30191 sqlite3_value *pVal = 0;
30193 if( !pExpr ){
30194 *ppVal = 0;
30195 return SQLITE_OK;
30197 op = pExpr->op;
30199 if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
30200 zVal = sqliteStrNDup((char*)pExpr->token.z, pExpr->token.n);
30201 pVal = sqlite3ValueNew();
30202 if( !zVal || !pVal ) goto no_mem;
30203 sqlite3Dequote(zVal);
30204 sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, sqlite3FreeX);
30205 if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
30206 sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
30207 }else{
30208 sqlite3ValueApplyAffinity(pVal, affinity, enc);
30210 }else if( op==TK_UMINUS ) {
30211 if( SQLITE_OK==sqlite3ValueFromExpr(pExpr->pLeft, enc, affinity, &pVal) ){
30212 pVal->u.i = -1 * pVal->u.i;
30213 pVal->r = -1.0 * pVal->r;
30216 #ifndef SQLITE_OMIT_BLOB_LITERAL
30217 else if( op==TK_BLOB ){
30218 int nVal;
30219 pVal = sqlite3ValueNew();
30220 zVal = sqliteStrNDup((char*)pExpr->token.z+1, pExpr->token.n-1);
30221 if( !zVal || !pVal ) goto no_mem;
30222 sqlite3Dequote(zVal);
30223 nVal = strlen(zVal)/2;
30224 sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(zVal), nVal, 0, sqlite3FreeX);
30225 sqliteFree(zVal);
30227 #endif
30229 *ppVal = pVal;
30230 return SQLITE_OK;
30232 no_mem:
30233 sqliteFree(zVal);
30234 sqlite3ValueFree(pVal);
30235 *ppVal = 0;
30236 return SQLITE_NOMEM;
30240 ** Change the string value of an sqlite3_value object
30242 static void sqlite3ValueSetStr(
30243 sqlite3_value *v,
30244 int n,
30245 const void *z,
30246 u8 enc,
30247 void (*xDel)(void*)
30249 if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
30253 ** Free an sqlite3_value object
30255 static void sqlite3ValueFree(sqlite3_value *v){
30256 if( !v ) return;
30257 sqlite3ValueSetStr(v, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
30258 sqliteFree(v);
30262 ** Return the number of bytes in the sqlite3_value object assuming
30263 ** that it uses the encoding "enc"
30265 static int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
30266 Mem *p = (Mem*)pVal;
30267 if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
30268 if( p->flags & MEM_Zero ){
30269 return p->n+p->u.i;
30270 }else{
30271 return p->n;
30274 return 0;
30277 /************** End of vdbemem.c *********************************************/
30278 /************** Begin file vdbeaux.c *****************************************/
30280 ** 2003 September 6
30282 ** The author disclaims copyright to this source code. In place of
30283 ** a legal notice, here is a blessing:
30285 ** May you do good and not evil.
30286 ** May you find forgiveness for yourself and forgive others.
30287 ** May you share freely, never taking more than you give.
30289 *************************************************************************
30290 ** This file contains code used for creating, destroying, and populating
30291 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
30292 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
30293 ** But that file was getting too big so this subroutines were split out.
30298 ** When debugging the code generator in a symbolic debugger, one can
30299 ** set the sqlite3_vdbe_addop_trace to 1 and all opcodes will be printed
30300 ** as they are added to the instruction stream.
30302 #ifdef SQLITE_DEBUG
30303 int sqlite3_vdbe_addop_trace = 0;
30304 #endif
30308 ** Create a new virtual database engine.
30310 static Vdbe *sqlite3VdbeCreate(sqlite3 *db){
30311 Vdbe *p;
30312 p = sqliteMalloc( sizeof(Vdbe) );
30313 if( p==0 ) return 0;
30314 p->db = db;
30315 if( db->pVdbe ){
30316 db->pVdbe->pPrev = p;
30318 p->pNext = db->pVdbe;
30319 p->pPrev = 0;
30320 db->pVdbe = p;
30321 p->magic = VDBE_MAGIC_INIT;
30322 return p;
30326 ** Remember the SQL string for a prepared statement.
30328 static void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
30329 if( p==0 ) return;
30330 assert( p->zSql==0 );
30331 p->zSql = sqlite3StrNDup(z, n);
30335 ** Return the SQL associated with a prepared statement
30337 static const char *sqlite3VdbeGetSql(Vdbe *p){
30338 return p->zSql;
30342 ** Swap all content between two VDBE structures.
30344 static void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
30345 Vdbe tmp, *pTmp;
30346 char *zTmp;
30347 int nTmp;
30348 tmp = *pA;
30349 *pA = *pB;
30350 *pB = tmp;
30351 pTmp = pA->pNext;
30352 pA->pNext = pB->pNext;
30353 pB->pNext = pTmp;
30354 pTmp = pA->pPrev;
30355 pA->pPrev = pB->pPrev;
30356 pB->pPrev = pTmp;
30357 zTmp = pA->zSql;
30358 pA->zSql = pB->zSql;
30359 pB->zSql = zTmp;
30360 nTmp = pA->nSql;
30361 pA->nSql = pB->nSql;
30362 pB->nSql = nTmp;
30365 #ifdef SQLITE_DEBUG
30367 ** Turn tracing on or off
30369 static void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
30370 p->trace = trace;
30372 #endif
30375 ** Resize the Vdbe.aOp array so that it contains at least N
30376 ** elements. If the Vdbe is in VDBE_MAGIC_RUN state, then
30377 ** the Vdbe.aOp array will be sized to contain exactly N
30378 ** elements. Vdbe.nOpAlloc is set to reflect the new size of
30379 ** the array.
30381 ** If an out-of-memory error occurs while resizing the array,
30382 ** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
30383 ** any opcodes already allocated can be correctly deallocated
30384 ** along with the rest of the Vdbe).
30386 static void resizeOpArray(Vdbe *p, int N){
30387 int runMode = p->magic==VDBE_MAGIC_RUN;
30388 if( runMode || p->nOpAlloc<N ){
30389 VdbeOp *pNew;
30390 int nNew = N + 100*(!runMode);
30391 int oldSize = p->nOpAlloc;
30392 pNew = sqliteRealloc(p->aOp, nNew*sizeof(Op));
30393 if( pNew ){
30394 p->nOpAlloc = nNew;
30395 p->aOp = pNew;
30396 if( nNew>oldSize ){
30397 memset(&p->aOp[oldSize], 0, (nNew-oldSize)*sizeof(Op));
30404 ** Add a new instruction to the list of instructions current in the
30405 ** VDBE. Return the address of the new instruction.
30407 ** Parameters:
30409 ** p Pointer to the VDBE
30411 ** op The opcode for this instruction
30413 ** p1, p2 First two of the three possible operands.
30415 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
30416 ** the sqlite3VdbeChangeP3() function to change the value of the P3
30417 ** operand.
30419 static int sqlite3VdbeAddOp(Vdbe *p, int op, int p1, int p2){
30420 int i;
30421 VdbeOp *pOp;
30423 i = p->nOp;
30424 assert( p->magic==VDBE_MAGIC_INIT );
30425 if( p->nOpAlloc<=i ){
30426 resizeOpArray(p, i+1);
30427 if( sqlite3MallocFailed() ){
30428 return 0;
30431 p->nOp++;
30432 pOp = &p->aOp[i];
30433 pOp->opcode = op;
30434 pOp->p1 = p1;
30435 pOp->p2 = p2;
30436 pOp->p3 = 0;
30437 pOp->p3type = P3_NOTUSED;
30438 p->expired = 0;
30439 #ifdef SQLITE_DEBUG
30440 if( sqlite3_vdbe_addop_trace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
30441 #endif
30442 return i;
30446 ** Add an opcode that includes the p3 value.
30448 static int sqlite3VdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3,int p3type){
30449 int addr = sqlite3VdbeAddOp(p, op, p1, p2);
30450 sqlite3VdbeChangeP3(p, addr, zP3, p3type);
30451 return addr;
30455 ** Create a new symbolic label for an instruction that has yet to be
30456 ** coded. The symbolic label is really just a negative number. The
30457 ** label can be used as the P2 value of an operation. Later, when
30458 ** the label is resolved to a specific address, the VDBE will scan
30459 ** through its operation list and change all values of P2 which match
30460 ** the label into the resolved address.
30462 ** The VDBE knows that a P2 value is a label because labels are
30463 ** always negative and P2 values are suppose to be non-negative.
30464 ** Hence, a negative P2 value is a label that has yet to be resolved.
30466 ** Zero is returned if a malloc() fails.
30468 static int sqlite3VdbeMakeLabel(Vdbe *p){
30469 int i;
30470 i = p->nLabel++;
30471 assert( p->magic==VDBE_MAGIC_INIT );
30472 if( i>=p->nLabelAlloc ){
30473 p->nLabelAlloc = p->nLabelAlloc*2 + 10;
30474 p->aLabel = sqliteReallocOrFree(p->aLabel,
30475 p->nLabelAlloc*sizeof(p->aLabel[0]));
30477 if( p->aLabel ){
30478 p->aLabel[i] = -1;
30480 return -1-i;
30484 ** Resolve label "x" to be the address of the next instruction to
30485 ** be inserted. The parameter "x" must have been obtained from
30486 ** a prior call to sqlite3VdbeMakeLabel().
30488 static void sqlite3VdbeResolveLabel(Vdbe *p, int x){
30489 int j = -1-x;
30490 assert( p->magic==VDBE_MAGIC_INIT );
30491 assert( j>=0 && j<p->nLabel );
30492 if( p->aLabel ){
30493 p->aLabel[j] = p->nOp;
30498 ** Return non-zero if opcode 'op' is guarenteed not to push more values
30499 ** onto the VDBE stack than it pops off.
30501 static int opcodeNoPush(u8 op){
30502 /* The 10 NOPUSH_MASK_n constants are defined in the automatically
30503 ** generated header file opcodes.h. Each is a 16-bit bitmask, one
30504 ** bit corresponding to each opcode implemented by the virtual
30505 ** machine in vdbe.c. The bit is true if the word "no-push" appears
30506 ** in a comment on the same line as the "case OP_XXX:" in
30507 ** sqlite3VdbeExec() in vdbe.c.
30509 ** If the bit is true, then the corresponding opcode is guarenteed not
30510 ** to grow the stack when it is executed. Otherwise, it may grow the
30511 ** stack by at most one entry.
30513 ** NOPUSH_MASK_0 corresponds to opcodes 0 to 15. NOPUSH_MASK_1 contains
30514 ** one bit for opcodes 16 to 31, and so on.
30516 ** 16-bit bitmasks (rather than 32-bit) are specified in opcodes.h
30517 ** because the file is generated by an awk program. Awk manipulates
30518 ** all numbers as floating-point and we don't want to risk a rounding
30519 ** error if someone builds with an awk that uses (for example) 32-bit
30520 ** IEEE floats.
30522 static const u32 masks[5] = {
30523 NOPUSH_MASK_0 + (((unsigned)NOPUSH_MASK_1)<<16),
30524 NOPUSH_MASK_2 + (((unsigned)NOPUSH_MASK_3)<<16),
30525 NOPUSH_MASK_4 + (((unsigned)NOPUSH_MASK_5)<<16),
30526 NOPUSH_MASK_6 + (((unsigned)NOPUSH_MASK_7)<<16),
30527 NOPUSH_MASK_8 + (((unsigned)NOPUSH_MASK_9)<<16)
30529 assert( op<32*5 );
30530 return (masks[op>>5] & (1<<(op&0x1F)));
30533 #ifndef NDEBUG
30534 static int sqlite3VdbeOpcodeNoPush(u8 op){
30535 return opcodeNoPush(op);
30537 #endif
30540 ** Loop through the program looking for P2 values that are negative.
30541 ** Each such value is a label. Resolve the label by setting the P2
30542 ** value to its correct non-zero value.
30544 ** This routine is called once after all opcodes have been inserted.
30546 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
30547 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
30548 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
30550 ** The integer *pMaxStack is set to the maximum number of vdbe stack
30551 ** entries that static analysis reveals this program might need.
30553 ** This routine also does the following optimization: It scans for
30554 ** Halt instructions where P1==SQLITE_CONSTRAINT or P2==OE_Abort or for
30555 ** IdxInsert instructions where P2!=0. If no such instruction is
30556 ** found, then every Statement instruction is changed to a Noop. In
30557 ** this way, we avoid creating the statement journal file unnecessarily.
30559 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs, int *pMaxStack){
30560 int i;
30561 int nMaxArgs = 0;
30562 int nMaxStack = p->nOp;
30563 Op *pOp;
30564 int *aLabel = p->aLabel;
30565 int doesStatementRollback = 0;
30566 int hasStatementBegin = 0;
30567 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
30568 u8 opcode = pOp->opcode;
30570 if( opcode==OP_Function || opcode==OP_AggStep
30571 #ifndef SQLITE_OMIT_VIRTUALTABLE
30572 || opcode==OP_VUpdate
30573 #endif
30575 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
30576 }else if( opcode==OP_Halt ){
30577 if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
30578 doesStatementRollback = 1;
30580 }else if( opcode==OP_Statement ){
30581 hasStatementBegin = 1;
30582 }else if( opcode==OP_VFilter ){
30583 int n;
30584 assert( p->nOp - i >= 3 );
30585 assert( pOp[-2].opcode==OP_Integer );
30586 n = pOp[-2].p1;
30587 if( n>nMaxArgs ) nMaxArgs = n;
30589 if( opcodeNoPush(opcode) ){
30590 nMaxStack--;
30593 if( pOp->p2>=0 ) continue;
30594 assert( -1-pOp->p2<p->nLabel );
30595 pOp->p2 = aLabel[-1-pOp->p2];
30597 sqliteFree(p->aLabel);
30598 p->aLabel = 0;
30600 *pMaxFuncArgs = nMaxArgs;
30601 *pMaxStack = nMaxStack;
30603 /* If we never rollback a statement transaction, then statement
30604 ** transactions are not needed. So change every OP_Statement
30605 ** opcode into an OP_Noop. This avoid a call to sqlite3OsOpenExclusive()
30606 ** which can be expensive on some platforms.
30608 if( hasStatementBegin && !doesStatementRollback ){
30609 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
30610 if( pOp->opcode==OP_Statement ){
30611 pOp->opcode = OP_Noop;
30618 ** Return the address of the next instruction to be inserted.
30620 static int sqlite3VdbeCurrentAddr(Vdbe *p){
30621 assert( p->magic==VDBE_MAGIC_INIT );
30622 return p->nOp;
30626 ** Add a whole list of operations to the operation stack. Return the
30627 ** address of the first operation added.
30629 static int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
30630 int addr;
30631 assert( p->magic==VDBE_MAGIC_INIT );
30632 resizeOpArray(p, p->nOp + nOp);
30633 if( sqlite3MallocFailed() ){
30634 return 0;
30636 addr = p->nOp;
30637 if( nOp>0 ){
30638 int i;
30639 VdbeOpList const *pIn = aOp;
30640 for(i=0; i<nOp; i++, pIn++){
30641 int p2 = pIn->p2;
30642 VdbeOp *pOut = &p->aOp[i+addr];
30643 pOut->opcode = pIn->opcode;
30644 pOut->p1 = pIn->p1;
30645 pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
30646 pOut->p3 = pIn->p3;
30647 pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
30648 #ifdef SQLITE_DEBUG
30649 if( sqlite3_vdbe_addop_trace ){
30650 sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
30652 #endif
30654 p->nOp += nOp;
30656 return addr;
30660 ** Change the value of the P1 operand for a specific instruction.
30661 ** This routine is useful when a large program is loaded from a
30662 ** static array using sqlite3VdbeAddOpList but we want to make a
30663 ** few minor changes to the program.
30665 static void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
30666 assert( p==0 || p->magic==VDBE_MAGIC_INIT );
30667 if( p && addr>=0 && p->nOp>addr && p->aOp ){
30668 p->aOp[addr].p1 = val;
30673 ** Change the value of the P2 operand for a specific instruction.
30674 ** This routine is useful for setting a jump destination.
30676 static void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
30677 assert( val>=0 );
30678 assert( p==0 || p->magic==VDBE_MAGIC_INIT );
30679 if( p && addr>=0 && p->nOp>addr && p->aOp ){
30680 p->aOp[addr].p2 = val;
30685 ** Change the P2 operand of instruction addr so that it points to
30686 ** the address of the next instruction to be coded.
30688 static void sqlite3VdbeJumpHere(Vdbe *p, int addr){
30689 sqlite3VdbeChangeP2(p, addr, p->nOp);
30694 ** If the input FuncDef structure is ephemeral, then free it. If
30695 ** the FuncDef is not ephermal, then do nothing.
30697 static void freeEphemeralFunction(FuncDef *pDef){
30698 if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
30699 sqliteFree(pDef);
30704 ** Delete a P3 value if necessary.
30706 static void freeP3(int p3type, void *p3){
30707 if( p3 ){
30708 switch( p3type ){
30709 case P3_DYNAMIC:
30710 case P3_KEYINFO:
30711 case P3_KEYINFO_HANDOFF: {
30712 sqliteFree(p3);
30713 break;
30715 case P3_MPRINTF: {
30716 sqlite3_free(p3);
30717 break;
30719 case P3_VDBEFUNC: {
30720 VdbeFunc *pVdbeFunc = (VdbeFunc *)p3;
30721 freeEphemeralFunction(pVdbeFunc->pFunc);
30722 sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
30723 sqliteFree(pVdbeFunc);
30724 break;
30726 case P3_FUNCDEF: {
30727 freeEphemeralFunction((FuncDef*)p3);
30728 break;
30730 case P3_MEM: {
30731 sqlite3ValueFree((sqlite3_value*)p3);
30732 break;
30740 ** Change N opcodes starting at addr to No-ops.
30742 static void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
30743 if( p && p->aOp ){
30744 VdbeOp *pOp = &p->aOp[addr];
30745 while( N-- ){
30746 freeP3(pOp->p3type, pOp->p3);
30747 memset(pOp, 0, sizeof(pOp[0]));
30748 pOp->opcode = OP_Noop;
30749 pOp++;
30755 ** Change the value of the P3 operand for a specific instruction.
30756 ** This routine is useful when a large program is loaded from a
30757 ** static array using sqlite3VdbeAddOpList but we want to make a
30758 ** few minor changes to the program.
30760 ** If n>=0 then the P3 operand is dynamic, meaning that a copy of
30761 ** the string is made into memory obtained from sqliteMalloc().
30762 ** A value of n==0 means copy bytes of zP3 up to and including the
30763 ** first null byte. If n>0 then copy n+1 bytes of zP3.
30765 ** If n==P3_KEYINFO it means that zP3 is a pointer to a KeyInfo structure.
30766 ** A copy is made of the KeyInfo structure into memory obtained from
30767 ** sqliteMalloc, to be freed when the Vdbe is finalized.
30768 ** n==P3_KEYINFO_HANDOFF indicates that zP3 points to a KeyInfo structure
30769 ** stored in memory that the caller has obtained from sqliteMalloc. The
30770 ** caller should not free the allocation, it will be freed when the Vdbe is
30771 ** finalized.
30773 ** Other values of n (P3_STATIC, P3_COLLSEQ etc.) indicate that zP3 points
30774 ** to a string or structure that is guaranteed to exist for the lifetime of
30775 ** the Vdbe. In these cases we can just copy the pointer.
30777 ** If addr<0 then change P3 on the most recently inserted instruction.
30779 static void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
30780 Op *pOp;
30781 assert( p==0 || p->magic==VDBE_MAGIC_INIT );
30782 if( p==0 || p->aOp==0 || sqlite3MallocFailed() ){
30783 if (n != P3_KEYINFO) {
30784 freeP3(n, (void*)*(char**)&zP3);
30786 return;
30788 if( addr<0 || addr>=p->nOp ){
30789 addr = p->nOp - 1;
30790 if( addr<0 ) return;
30792 pOp = &p->aOp[addr];
30793 freeP3(pOp->p3type, pOp->p3);
30794 pOp->p3 = 0;
30795 if( zP3==0 ){
30796 pOp->p3 = 0;
30797 pOp->p3type = P3_NOTUSED;
30798 }else if( n==P3_KEYINFO ){
30799 KeyInfo *pKeyInfo;
30800 int nField, nByte;
30802 nField = ((KeyInfo*)zP3)->nField;
30803 nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
30804 pKeyInfo = sqliteMallocRaw( nByte );
30805 pOp->p3 = (char*)pKeyInfo;
30806 if( pKeyInfo ){
30807 unsigned char *aSortOrder;
30808 memcpy(pKeyInfo, zP3, nByte);
30809 aSortOrder = pKeyInfo->aSortOrder;
30810 if( aSortOrder ){
30811 pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
30812 memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
30814 pOp->p3type = P3_KEYINFO;
30815 }else{
30816 pOp->p3type = P3_NOTUSED;
30818 }else if( n==P3_KEYINFO_HANDOFF ){
30819 pOp->p3 = (char*)zP3;
30820 pOp->p3type = P3_KEYINFO;
30821 }else if( n<0 ){
30822 pOp->p3 = (char*)zP3;
30823 pOp->p3type = n;
30824 }else{
30825 if( n==0 ) n = strlen(zP3);
30826 pOp->p3 = sqliteStrNDup(zP3, n);
30827 pOp->p3type = P3_DYNAMIC;
30831 #ifndef NDEBUG
30833 ** Replace the P3 field of the most recently coded instruction with
30834 ** comment text.
30836 static void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
30837 va_list ap;
30838 assert( p->nOp>0 || p->aOp==0 );
30839 assert( p->aOp==0 || p->aOp[p->nOp-1].p3==0 || sqlite3MallocFailed() );
30840 va_start(ap, zFormat);
30841 sqlite3VdbeChangeP3(p, -1, sqlite3VMPrintf(zFormat, ap), P3_DYNAMIC);
30842 va_end(ap);
30844 #endif
30847 ** Return the opcode for a given address.
30849 static VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
30850 assert( p->magic==VDBE_MAGIC_INIT );
30851 assert( (addr>=0 && addr<p->nOp) || sqlite3MallocFailed() );
30852 return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
30855 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
30856 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
30858 ** Compute a string that describes the P3 parameter for an opcode.
30859 ** Use zTemp for any required temporary buffer space.
30861 static char *displayP3(Op *pOp, char *zTemp, int nTemp){
30862 char *zP3;
30863 assert( nTemp>=20 );
30864 switch( pOp->p3type ){
30865 case P3_KEYINFO: {
30866 int i, j;
30867 KeyInfo *pKeyInfo = (KeyInfo*)pOp->p3;
30868 sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
30869 i = strlen(zTemp);
30870 for(j=0; j<pKeyInfo->nField; j++){
30871 CollSeq *pColl = pKeyInfo->aColl[j];
30872 if( pColl ){
30873 int n = strlen(pColl->zName);
30874 if( i+n>nTemp-6 ){
30875 memcpy(&zTemp[i],",...",4);
30876 break;
30878 zTemp[i++] = ',';
30879 if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
30880 zTemp[i++] = '-';
30882 memcpy(&zTemp[i], pColl->zName,n+1);
30883 i += n;
30884 }else if( i+4<nTemp-6 ){
30885 memcpy(&zTemp[i],",nil",4);
30886 i += 4;
30889 zTemp[i++] = ')';
30890 zTemp[i] = 0;
30891 assert( i<nTemp );
30892 zP3 = zTemp;
30893 break;
30895 case P3_COLLSEQ: {
30896 CollSeq *pColl = (CollSeq*)pOp->p3;
30897 sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
30898 zP3 = zTemp;
30899 break;
30901 case P3_FUNCDEF: {
30902 FuncDef *pDef = (FuncDef*)pOp->p3;
30903 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
30904 zP3 = zTemp;
30905 break;
30907 #ifndef SQLITE_OMIT_VIRTUALTABLE
30908 case P3_VTAB: {
30909 sqlite3_vtab *pVtab = (sqlite3_vtab*)pOp->p3;
30910 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
30911 zP3 = zTemp;
30912 break;
30914 #endif
30915 default: {
30916 zP3 = pOp->p3;
30917 if( zP3==0 || pOp->opcode==OP_Noop ){
30918 zP3 = "";
30922 assert( zP3!=0 );
30923 return zP3;
30925 #endif
30928 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
30930 ** Print a single opcode. This routine is used for debugging only.
30932 static void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
30933 char *zP3;
30934 char zPtr[50];
30935 static const char *zFormat1 = "%4d %-13s %4d %4d %s\n";
30936 if( pOut==0 ) pOut = stdout;
30937 zP3 = displayP3(pOp, zPtr, sizeof(zPtr));
30938 fprintf(pOut, zFormat1,
30939 pc, sqlite3OpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3);
30940 fflush(pOut);
30942 #endif
30945 ** Release an array of N Mem elements
30947 static void releaseMemArray(Mem *p, int N){
30948 if( p ){
30949 while( N-->0 ){
30950 sqlite3VdbeMemRelease(p++);
30955 #ifndef SQLITE_OMIT_EXPLAIN
30957 ** Give a listing of the program in the virtual machine.
30959 ** The interface is the same as sqlite3VdbeExec(). But instead of
30960 ** running the code, it invokes the callback once for each instruction.
30961 ** This feature is used to implement "EXPLAIN".
30963 static int sqlite3VdbeList(
30964 Vdbe *p /* The VDBE */
30966 sqlite3 *db = p->db;
30967 int i;
30968 int rc = SQLITE_OK;
30970 assert( p->explain );
30971 if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
30972 assert( db->magic==SQLITE_MAGIC_BUSY );
30973 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
30975 /* Even though this opcode does not put dynamic strings onto the
30976 ** the stack, they may become dynamic if the user calls
30977 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
30979 if( p->pTos==&p->aStack[4] ){
30980 releaseMemArray(p->aStack, 5);
30982 p->resOnStack = 0;
30985 i = p->pc++;
30986 }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
30987 if( i>=p->nOp ){
30988 p->rc = SQLITE_OK;
30989 rc = SQLITE_DONE;
30990 }else if( db->u1.isInterrupted ){
30991 p->rc = SQLITE_INTERRUPT;
30992 rc = SQLITE_ERROR;
30993 sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0);
30994 }else{
30995 Op *pOp = &p->aOp[i];
30996 Mem *pMem = p->aStack;
30997 pMem->flags = MEM_Int;
30998 pMem->type = SQLITE_INTEGER;
30999 pMem->u.i = i; /* Program counter */
31000 pMem++;
31002 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
31003 pMem->z = (char*)sqlite3OpcodeNames[pOp->opcode]; /* Opcode */
31004 assert( pMem->z!=0 );
31005 pMem->n = strlen(pMem->z);
31006 pMem->type = SQLITE_TEXT;
31007 pMem->enc = SQLITE_UTF8;
31008 pMem++;
31010 pMem->flags = MEM_Int;
31011 pMem->u.i = pOp->p1; /* P1 */
31012 pMem->type = SQLITE_INTEGER;
31013 pMem++;
31015 pMem->flags = MEM_Int;
31016 pMem->u.i = pOp->p2; /* P2 */
31017 pMem->type = SQLITE_INTEGER;
31018 pMem++;
31020 pMem->flags = MEM_Ephem|MEM_Str|MEM_Term; /* P3 */
31021 pMem->z = displayP3(pOp, pMem->zShort, sizeof(pMem->zShort));
31022 assert( pMem->z!=0 );
31023 pMem->n = strlen(pMem->z);
31024 pMem->type = SQLITE_TEXT;
31025 pMem->enc = SQLITE_UTF8;
31027 p->nResColumn = 5 - 2*(p->explain-1);
31028 p->pTos = pMem;
31029 p->rc = SQLITE_OK;
31030 p->resOnStack = 1;
31031 rc = SQLITE_ROW;
31033 return rc;
31035 #endif /* SQLITE_OMIT_EXPLAIN */
31037 #ifdef SQLITE_DEBUG
31039 ** Print the SQL that was used to generate a VDBE program.
31041 static void sqlite3VdbePrintSql(Vdbe *p){
31042 int nOp = p->nOp;
31043 VdbeOp *pOp;
31044 if( nOp<1 ) return;
31045 pOp = &p->aOp[nOp-1];
31046 if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
31047 const char *z = pOp->p3;
31048 while( isspace(*(u8*)z) ) z++;
31049 printf("SQL: [%s]\n", z);
31052 #endif
31054 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
31056 ** Print an IOTRACE message showing SQL content.
31058 static void sqlite3VdbeIOTraceSql(Vdbe *p){
31059 int nOp = p->nOp;
31060 VdbeOp *pOp;
31061 if( sqlite3_io_trace==0 ) return;
31062 if( nOp<1 ) return;
31063 pOp = &p->aOp[nOp-1];
31064 if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
31065 char *z = sqlite3StrDup(pOp->p3);
31066 int i, j;
31067 for(i=0; isspace((unsigned char)z[i]); i++){}
31068 for(j=0; z[i]; i++){
31069 if( isspace((unsigned char)z[i]) ){
31070 if( z[i-1]!=' ' ){
31071 z[j++] = ' ';
31073 }else{
31074 z[j++] = z[i];
31077 z[j] = 0;
31078 sqlite3_io_trace("SQL %s\n", z);
31079 sqliteFree(z);
31082 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
31086 ** Prepare a virtual machine for execution. This involves things such
31087 ** as allocating stack space and initializing the program counter.
31088 ** After the VDBE has be prepped, it can be executed by one or more
31089 ** calls to sqlite3VdbeExec().
31091 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
31092 ** VDBE_MAGIC_RUN.
31094 static void sqlite3VdbeMakeReady(
31095 Vdbe *p, /* The VDBE */
31096 int nVar, /* Number of '?' see in the SQL statement */
31097 int nMem, /* Number of memory cells to allocate */
31098 int nCursor, /* Number of cursors to allocate */
31099 int isExplain /* True if the EXPLAIN keywords is present */
31101 int n;
31103 assert( p!=0 );
31104 assert( p->magic==VDBE_MAGIC_INIT );
31106 /* There should be at least one opcode.
31108 assert( p->nOp>0 );
31110 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
31111 * is because the call to resizeOpArray() below may shrink the
31112 * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN
31113 * state.
31115 p->magic = VDBE_MAGIC_RUN;
31117 /* No instruction ever pushes more than a single element onto the
31118 ** stack. And the stack never grows on successive executions of the
31119 ** same loop. So the total number of instructions is an upper bound
31120 ** on the maximum stack depth required. (Added later:) The
31121 ** resolveP2Values() call computes a tighter upper bound on the
31122 ** stack size.
31124 ** Allocation all the stack space we will ever need.
31126 if( p->aStack==0 ){
31127 int nArg; /* Maximum number of args passed to a user function. */
31128 int nStack; /* Maximum number of stack entries required */
31129 resolveP2Values(p, &nArg, &nStack);
31130 resizeOpArray(p, p->nOp);
31131 assert( nVar>=0 );
31132 assert( nStack<p->nOp );
31133 if( isExplain ){
31134 nStack = 10;
31136 p->aStack = sqliteMalloc(
31137 nStack*sizeof(p->aStack[0]) /* aStack */
31138 + nArg*sizeof(Mem*) /* apArg */
31139 + nVar*sizeof(Mem) /* aVar */
31140 + nVar*sizeof(char*) /* azVar */
31141 + nMem*sizeof(Mem) /* aMem */
31142 + nCursor*sizeof(Cursor*) /* apCsr */
31144 if( !sqlite3MallocFailed() ){
31145 p->aMem = &p->aStack[nStack];
31146 p->nMem = nMem;
31147 p->aVar = &p->aMem[nMem];
31148 p->nVar = nVar;
31149 p->okVar = 0;
31150 p->apArg = (Mem**)&p->aVar[nVar];
31151 p->azVar = (char**)&p->apArg[nArg];
31152 p->apCsr = (Cursor**)&p->azVar[nVar];
31153 p->nCursor = nCursor;
31154 for(n=0; n<nVar; n++){
31155 p->aVar[n].flags = MEM_Null;
31159 for(n=0; n<p->nMem; n++){
31160 p->aMem[n].flags = MEM_Null;
31163 p->pTos = &p->aStack[-1];
31164 p->pc = -1;
31165 p->rc = SQLITE_OK;
31166 p->uniqueCnt = 0;
31167 p->returnDepth = 0;
31168 p->errorAction = OE_Abort;
31169 p->popStack = 0;
31170 p->explain |= isExplain;
31171 p->magic = VDBE_MAGIC_RUN;
31172 p->nChange = 0;
31173 p->cacheCtr = 1;
31174 p->minWriteFileFormat = 255;
31175 #ifdef VDBE_PROFILE
31177 int i;
31178 for(i=0; i<p->nOp; i++){
31179 p->aOp[i].cnt = 0;
31180 p->aOp[i].cycles = 0;
31183 #endif
31187 ** Close a cursor and release all the resources that cursor happens
31188 ** to hold.
31190 static void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
31191 if( pCx==0 ){
31192 return;
31194 if( pCx->pCursor ){
31195 sqlite3BtreeCloseCursor(pCx->pCursor);
31197 if( pCx->pBt ){
31198 sqlite3BtreeClose(pCx->pBt);
31200 #ifndef SQLITE_OMIT_VIRTUALTABLE
31201 if( pCx->pVtabCursor ){
31202 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
31203 const sqlite3_module *pModule = pCx->pModule;
31204 p->inVtabMethod = 1;
31205 sqlite3SafetyOff(p->db);
31206 pModule->xClose(pVtabCursor);
31207 sqlite3SafetyOn(p->db);
31208 p->inVtabMethod = 0;
31210 #endif
31211 sqliteFree(pCx->pData);
31212 sqliteFree(pCx->aType);
31213 sqliteFree(pCx);
31217 ** Close all cursors
31219 static void closeAllCursors(Vdbe *p){
31220 int i;
31221 if( p->apCsr==0 ) return;
31222 for(i=0; i<p->nCursor; i++){
31223 if( !p->inVtabMethod || (p->apCsr[i] && !p->apCsr[i]->pVtabCursor) ){
31224 sqlite3VdbeFreeCursor(p, p->apCsr[i]);
31225 p->apCsr[i] = 0;
31231 ** Clean up the VM after execution.
31233 ** This routine will automatically close any cursors, lists, and/or
31234 ** sorters that were left open. It also deletes the values of
31235 ** variables in the aVar[] array.
31237 static void Cleanup(Vdbe *p){
31238 int i;
31239 if( p->aStack ){
31240 releaseMemArray(p->aStack, 1 + (p->pTos - p->aStack));
31241 p->pTos = &p->aStack[-1];
31243 closeAllCursors(p);
31244 releaseMemArray(p->aMem, p->nMem);
31245 sqlite3VdbeFifoClear(&p->sFifo);
31246 if( p->contextStack ){
31247 for(i=0; i<p->contextStackTop; i++){
31248 sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
31250 sqliteFree(p->contextStack);
31252 p->contextStack = 0;
31253 p->contextStackDepth = 0;
31254 p->contextStackTop = 0;
31255 sqliteFree(p->zErrMsg);
31256 p->zErrMsg = 0;
31260 ** Set the number of result columns that will be returned by this SQL
31261 ** statement. This is now set at compile time, rather than during
31262 ** execution of the vdbe program so that sqlite3_column_count() can
31263 ** be called on an SQL statement before sqlite3_step().
31265 static void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
31266 Mem *pColName;
31267 int n;
31268 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
31269 sqliteFree(p->aColName);
31270 n = nResColumn*COLNAME_N;
31271 p->nResColumn = nResColumn;
31272 p->aColName = pColName = (Mem*)sqliteMalloc( sizeof(Mem)*n );
31273 if( p->aColName==0 ) return;
31274 while( n-- > 0 ){
31275 (pColName++)->flags = MEM_Null;
31280 ** Set the name of the idx'th column to be returned by the SQL statement.
31281 ** zName must be a pointer to a nul terminated string.
31283 ** This call must be made after a call to sqlite3VdbeSetNumCols().
31285 ** If N==P3_STATIC it means that zName is a pointer to a constant static
31286 ** string and we can just copy the pointer. If it is P3_DYNAMIC, then
31287 ** the string is freed using sqliteFree() when the vdbe is finished with
31288 ** it. Otherwise, N bytes of zName are copied.
31290 static int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
31291 int rc;
31292 Mem *pColName;
31293 assert( idx<p->nResColumn );
31294 assert( var<COLNAME_N );
31295 if( sqlite3MallocFailed() ) return SQLITE_NOMEM;
31296 assert( p->aColName!=0 );
31297 pColName = &(p->aColName[idx+var*p->nResColumn]);
31298 if( N==P3_DYNAMIC || N==P3_STATIC ){
31299 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
31300 }else{
31301 rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
31303 if( rc==SQLITE_OK && N==P3_DYNAMIC ){
31304 pColName->flags = (pColName->flags&(~MEM_Static))|MEM_Dyn;
31305 pColName->xDel = 0;
31307 return rc;
31311 ** A read or write transaction may or may not be active on database handle
31312 ** db. If a transaction is active, commit it. If there is a
31313 ** write-transaction spanning more than one database file, this routine
31314 ** takes care of the master journal trickery.
31316 static int vdbeCommit(sqlite3 *db){
31317 int i;
31318 int nTrans = 0; /* Number of databases with an active write-transaction */
31319 int rc = SQLITE_OK;
31320 int needXcommit = 0;
31322 /* Before doing anything else, call the xSync() callback for any
31323 ** virtual module tables written in this transaction. This has to
31324 ** be done before determining whether a master journal file is
31325 ** required, as an xSync() callback may add an attached database
31326 ** to the transaction.
31328 rc = sqlite3VtabSync(db, rc);
31329 if( rc!=SQLITE_OK ){
31330 return rc;
31333 /* This loop determines (a) if the commit hook should be invoked and
31334 ** (b) how many database files have open write transactions, not
31335 ** including the temp database. (b) is important because if more than
31336 ** one database file has an open write transaction, a master journal
31337 ** file is required for an atomic commit.
31339 for(i=0; i<db->nDb; i++){
31340 Btree *pBt = db->aDb[i].pBt;
31341 if( pBt && sqlite3BtreeIsInTrans(pBt) ){
31342 needXcommit = 1;
31343 if( i!=1 ) nTrans++;
31347 /* If there are any write-transactions at all, invoke the commit hook */
31348 if( needXcommit && db->xCommitCallback ){
31349 sqlite3SafetyOff(db);
31350 rc = db->xCommitCallback(db->pCommitArg);
31351 sqlite3SafetyOn(db);
31352 if( rc ){
31353 return SQLITE_CONSTRAINT;
31357 /* The simple case - no more than one database file (not counting the
31358 ** TEMP database) has a transaction active. There is no need for the
31359 ** master-journal.
31361 ** If the return value of sqlite3BtreeGetFilename() is a zero length
31362 ** string, it means the main database is :memory:. In that case we do
31363 ** not support atomic multi-file commits, so use the simple case then
31364 ** too.
31366 if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
31367 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
31368 Btree *pBt = db->aDb[i].pBt;
31369 if( pBt ){
31370 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
31374 /* Do the commit only if all databases successfully complete phase 1.
31375 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
31376 ** IO error while deleting or truncating a journal file. It is unlikely,
31377 ** but could happen. In this case abandon processing and return the error.
31379 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
31380 Btree *pBt = db->aDb[i].pBt;
31381 if( pBt ){
31382 rc = sqlite3BtreeCommitPhaseTwo(pBt);
31385 if( rc==SQLITE_OK ){
31386 sqlite3VtabCommit(db);
31390 /* The complex case - There is a multi-file write-transaction active.
31391 ** This requires a master journal file to ensure the transaction is
31392 ** committed atomicly.
31394 #ifndef SQLITE_OMIT_DISKIO
31395 else{
31396 int needSync = 0;
31397 char *zMaster = 0; /* File-name for the master journal */
31398 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
31399 OsFile *master = 0;
31401 /* Select a master journal file name */
31402 do {
31403 u32 random;
31404 sqliteFree(zMaster);
31405 sqlite3Randomness(sizeof(random), &random);
31406 zMaster = sqlite3MPrintf("%s-mj%08X", zMainFile, random&0x7fffffff);
31407 if( !zMaster ){
31408 return SQLITE_NOMEM;
31410 }while( sqlite3OsFileExists(zMaster) );
31412 /* Open the master journal. */
31413 rc = sqlite3OsOpenExclusive(zMaster, &master, 0);
31414 if( rc!=SQLITE_OK ){
31415 sqliteFree(zMaster);
31416 return rc;
31419 /* Write the name of each database file in the transaction into the new
31420 ** master journal file. If an error occurs at this point close
31421 ** and delete the master journal file. All the individual journal files
31422 ** still have 'null' as the master journal pointer, so they will roll
31423 ** back independently if a failure occurs.
31425 for(i=0; i<db->nDb; i++){
31426 Btree *pBt = db->aDb[i].pBt;
31427 if( i==1 ) continue; /* Ignore the TEMP database */
31428 if( pBt && sqlite3BtreeIsInTrans(pBt) ){
31429 char const *zFile = sqlite3BtreeGetJournalname(pBt);
31430 if( zFile[0]==0 ) continue; /* Ignore :memory: databases */
31431 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
31432 needSync = 1;
31434 rc = sqlite3OsWrite(master, zFile, strlen(zFile)+1);
31435 if( rc!=SQLITE_OK ){
31436 sqlite3OsClose(&master);
31437 sqlite3OsDelete(zMaster);
31438 sqliteFree(zMaster);
31439 return rc;
31445 /* Sync the master journal file. Before doing this, open the directory
31446 ** the master journal file is store in so that it gets synced too.
31448 zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
31449 rc = sqlite3OsOpenDirectory(master, zMainFile);
31450 if( rc!=SQLITE_OK ||
31451 (needSync && (rc=sqlite3OsSync(master,0))!=SQLITE_OK) ){
31452 sqlite3OsClose(&master);
31453 sqlite3OsDelete(zMaster);
31454 sqliteFree(zMaster);
31455 return rc;
31458 /* Sync all the db files involved in the transaction. The same call
31459 ** sets the master journal pointer in each individual journal. If
31460 ** an error occurs here, do not delete the master journal file.
31462 ** If the error occurs during the first call to
31463 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
31464 ** master journal file will be orphaned. But we cannot delete it,
31465 ** in case the master journal file name was written into the journal
31466 ** file before the failure occured.
31468 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
31469 Btree *pBt = db->aDb[i].pBt;
31470 if( pBt && sqlite3BtreeIsInTrans(pBt) ){
31471 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
31474 sqlite3OsClose(&master);
31475 if( rc!=SQLITE_OK ){
31476 sqliteFree(zMaster);
31477 return rc;
31480 /* Delete the master journal file. This commits the transaction. After
31481 ** doing this the directory is synced again before any individual
31482 ** transaction files are deleted.
31484 rc = sqlite3OsDelete(zMaster);
31485 sqliteFree(zMaster);
31486 zMaster = 0;
31487 if( rc ){
31488 return rc;
31490 rc = sqlite3OsSyncDirectory(zMainFile);
31491 if( rc!=SQLITE_OK ){
31492 /* This is not good. The master journal file has been deleted, but
31493 ** the directory sync failed. There is no completely safe course of
31494 ** action from here. The individual journals contain the name of the
31495 ** master journal file, but there is no way of knowing if that
31496 ** master journal exists now or if it will exist after the operating
31497 ** system crash that may follow the fsync() failure.
31499 return rc;
31502 /* All files and directories have already been synced, so the following
31503 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
31504 ** deleting or truncating journals. If something goes wrong while
31505 ** this is happening we don't really care. The integrity of the
31506 ** transaction is already guaranteed, but some stray 'cold' journals
31507 ** may be lying around. Returning an error code won't help matters.
31509 disable_simulated_io_errors();
31510 for(i=0; i<db->nDb; i++){
31511 Btree *pBt = db->aDb[i].pBt;
31512 if( pBt ){
31513 sqlite3BtreeCommitPhaseTwo(pBt);
31516 enable_simulated_io_errors();
31518 sqlite3VtabCommit(db);
31520 #endif
31522 return rc;
31526 ** This routine checks that the sqlite3.activeVdbeCnt count variable
31527 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
31528 ** currently active. An assertion fails if the two counts do not match.
31529 ** This is an internal self-check only - it is not an essential processing
31530 ** step.
31532 ** This is a no-op if NDEBUG is defined.
31534 #ifndef NDEBUG
31535 static void checkActiveVdbeCnt(sqlite3 *db){
31536 Vdbe *p;
31537 int cnt = 0;
31538 p = db->pVdbe;
31539 while( p ){
31540 if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
31541 cnt++;
31543 p = p->pNext;
31545 assert( cnt==db->activeVdbeCnt );
31547 #else
31548 #define checkActiveVdbeCnt(x)
31549 #endif
31552 ** Find every active VM other than pVdbe and change its status to
31553 ** aborted. This happens when one VM causes a rollback due to an
31554 ** ON CONFLICT ROLLBACK clause (for example). The other VMs must be
31555 ** aborted so that they do not have data rolled out from underneath
31556 ** them leading to a segfault.
31558 static void sqlite3AbortOtherActiveVdbes(sqlite3 *db, Vdbe *pExcept){
31559 Vdbe *pOther;
31560 for(pOther=db->pVdbe; pOther; pOther=pOther->pNext){
31561 if( pOther==pExcept ) continue;
31562 if( pOther->magic!=VDBE_MAGIC_RUN || pOther->pc<0 ) continue;
31563 checkActiveVdbeCnt(db);
31564 closeAllCursors(pOther);
31565 checkActiveVdbeCnt(db);
31566 pOther->aborted = 1;
31571 ** This routine is called the when a VDBE tries to halt. If the VDBE
31572 ** has made changes and is in autocommit mode, then commit those
31573 ** changes. If a rollback is needed, then do the rollback.
31575 ** This routine is the only way to move the state of a VM from
31576 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.
31578 ** Return an error code. If the commit could not complete because of
31579 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
31580 ** means the close did not happen and needs to be repeated.
31582 static int sqlite3VdbeHalt(Vdbe *p){
31583 sqlite3 *db = p->db;
31584 int i;
31585 int (*xFunc)(Btree *pBt) = 0; /* Function to call on each btree backend */
31586 int isSpecialError; /* Set to true if SQLITE_NOMEM or IOERR */
31588 /* This function contains the logic that determines if a statement or
31589 ** transaction will be committed or rolled back as a result of the
31590 ** execution of this virtual machine.
31592 ** Special errors:
31594 ** If an SQLITE_NOMEM error has occured in a statement that writes to
31595 ** the database, then either a statement or transaction must be rolled
31596 ** back to ensure the tree-structures are in a consistent state. A
31597 ** statement transaction is rolled back if one is open, otherwise the
31598 ** entire transaction must be rolled back.
31600 ** If an SQLITE_IOERR error has occured in a statement that writes to
31601 ** the database, then the entire transaction must be rolled back. The
31602 ** I/O error may have caused garbage to be written to the journal
31603 ** file. Were the transaction to continue and eventually be rolled
31604 ** back that garbage might end up in the database file.
31606 ** In both of the above cases, the Vdbe.errorAction variable is
31607 ** ignored. If the sqlite3.autoCommit flag is false and a transaction
31608 ** is rolled back, it will be set to true.
31610 ** Other errors:
31612 ** No error:
31616 if( sqlite3MallocFailed() ){
31617 p->rc = SQLITE_NOMEM;
31619 if( p->magic!=VDBE_MAGIC_RUN ){
31620 /* Already halted. Nothing to do. */
31621 assert( p->magic==VDBE_MAGIC_HALT );
31622 #ifndef SQLITE_OMIT_VIRTUALTABLE
31623 closeAllCursors(p);
31624 #endif
31625 return SQLITE_OK;
31627 closeAllCursors(p);
31628 checkActiveVdbeCnt(db);
31630 /* No commit or rollback needed if the program never started */
31631 if( p->pc>=0 ){
31632 int mrc; /* Primary error code from p->rc */
31633 /* Check for one of the special errors - SQLITE_NOMEM or SQLITE_IOERR */
31634 mrc = p->rc & 0xff;
31635 isSpecialError = (
31636 (mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR || mrc==SQLITE_INTERRUPT)?1:0);
31637 if( isSpecialError ){
31638 /* This loop does static analysis of the query to see which of the
31639 ** following three categories it falls into:
31641 ** Read-only
31642 ** Query with statement journal
31643 ** Query without statement journal
31645 ** We could do something more elegant than this static analysis (i.e.
31646 ** store the type of query as part of the compliation phase), but
31647 ** handling malloc() or IO failure is a fairly obscure edge case so
31648 ** this is probably easier. Todo: Might be an opportunity to reduce
31649 ** code size a very small amount though...
31651 int isReadOnly = 1;
31652 int isStatement = 0;
31653 assert(p->aOp || p->nOp==0);
31654 for(i=0; i<p->nOp; i++){
31655 switch( p->aOp[i].opcode ){
31656 case OP_Transaction:
31657 /* This is a bit strange. If we hit a malloc() or IO error and
31658 ** the statement did not open a statement transaction, we will
31659 ** rollback any active transaction and abort all other active
31660 ** statements. Or, if this is an SQLITE_INTERRUPT error, we
31661 ** will only rollback if the interrupted statement was a write.
31663 ** It could be argued that read-only statements should never
31664 ** rollback anything. But careful analysis is required before
31665 ** making this change
31667 if( p->aOp[i].p2 || mrc!=SQLITE_INTERRUPT ){
31668 isReadOnly = 0;
31670 break;
31671 case OP_Statement:
31672 isStatement = 1;
31673 break;
31677 /* If the query was read-only, we need do no rollback at all. Otherwise,
31678 ** proceed with the special handling.
31680 if( !isReadOnly ){
31681 if( p->rc==SQLITE_IOERR_BLOCKED && isStatement ){
31682 xFunc = sqlite3BtreeRollbackStmt;
31683 p->rc = SQLITE_BUSY;
31684 } else if( p->rc==SQLITE_NOMEM && isStatement ){
31685 xFunc = sqlite3BtreeRollbackStmt;
31686 }else{
31687 /* We are forced to roll back the active transaction. Before doing
31688 ** so, abort any other statements this handle currently has active.
31690 sqlite3AbortOtherActiveVdbes(db, p);
31691 sqlite3RollbackAll(db);
31692 db->autoCommit = 1;
31697 /* If the auto-commit flag is set and this is the only active vdbe, then
31698 ** we do either a commit or rollback of the current transaction.
31700 ** Note: This block also runs if one of the special errors handled
31701 ** above has occured.
31703 if( db->autoCommit && db->activeVdbeCnt==1 ){
31704 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
31705 /* The auto-commit flag is true, and the vdbe program was
31706 ** successful or hit an 'OR FAIL' constraint. This means a commit
31707 ** is required.
31709 int rc = vdbeCommit(db);
31710 if( rc==SQLITE_BUSY ){
31711 return SQLITE_BUSY;
31712 }else if( rc!=SQLITE_OK ){
31713 p->rc = rc;
31714 sqlite3RollbackAll(db);
31715 }else{
31716 sqlite3CommitInternalChanges(db);
31718 }else{
31719 sqlite3RollbackAll(db);
31721 }else if( !xFunc ){
31722 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
31723 xFunc = sqlite3BtreeCommitStmt;
31724 }else if( p->errorAction==OE_Abort ){
31725 xFunc = sqlite3BtreeRollbackStmt;
31726 }else{
31727 sqlite3AbortOtherActiveVdbes(db, p);
31728 sqlite3RollbackAll(db);
31729 db->autoCommit = 1;
31733 /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
31734 ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
31735 ** and the return code is still SQLITE_OK, set the return code to the new
31736 ** error value.
31738 assert(!xFunc ||
31739 xFunc==sqlite3BtreeCommitStmt ||
31740 xFunc==sqlite3BtreeRollbackStmt
31742 for(i=0; xFunc && i<db->nDb; i++){
31743 int rc;
31744 Btree *pBt = db->aDb[i].pBt;
31745 if( pBt ){
31746 rc = xFunc(pBt);
31747 if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
31748 p->rc = rc;
31749 sqlite3SetString(&p->zErrMsg, 0);
31754 /* If this was an INSERT, UPDATE or DELETE and the statement was committed,
31755 ** set the change counter.
31757 if( p->changeCntOn && p->pc>=0 ){
31758 if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
31759 sqlite3VdbeSetChanges(db, p->nChange);
31760 }else{
31761 sqlite3VdbeSetChanges(db, 0);
31763 p->nChange = 0;
31766 /* Rollback or commit any schema changes that occurred. */
31767 if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
31768 sqlite3ResetInternalSchema(db, 0);
31769 db->flags = (db->flags | SQLITE_InternChanges);
31773 /* We have successfully halted and closed the VM. Record this fact. */
31774 if( p->pc>=0 ){
31775 db->activeVdbeCnt--;
31777 p->magic = VDBE_MAGIC_HALT;
31778 checkActiveVdbeCnt(db);
31780 return SQLITE_OK;
31784 ** Each VDBE holds the result of the most recent sqlite3_step() call
31785 ** in p->rc. This routine sets that result back to SQLITE_OK.
31787 static void sqlite3VdbeResetStepResult(Vdbe *p){
31788 p->rc = SQLITE_OK;
31792 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
31793 ** Write any error messages into *pzErrMsg. Return the result code.
31795 ** After this routine is run, the VDBE should be ready to be executed
31796 ** again.
31798 ** To look at it another way, this routine resets the state of the
31799 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
31800 ** VDBE_MAGIC_INIT.
31802 static int sqlite3VdbeReset(Vdbe *p){
31803 sqlite3 *db;
31804 db = p->db;
31806 /* If the VM did not run to completion or if it encountered an
31807 ** error, then it might not have been halted properly. So halt
31808 ** it now.
31810 sqlite3SafetyOn(db);
31811 sqlite3VdbeHalt(p);
31812 sqlite3SafetyOff(db);
31814 /* If the VDBE has be run even partially, then transfer the error code
31815 ** and error message from the VDBE into the main database structure. But
31816 ** if the VDBE has just been set to run but has not actually executed any
31817 ** instructions yet, leave the main database error information unchanged.
31819 if( p->pc>=0 ){
31820 if( p->zErrMsg ){
31821 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, sqlite3FreeX);
31822 db->errCode = p->rc;
31823 p->zErrMsg = 0;
31824 }else if( p->rc ){
31825 sqlite3Error(db, p->rc, 0);
31826 }else{
31827 sqlite3Error(db, SQLITE_OK, 0);
31829 }else if( p->rc && p->expired ){
31830 /* The expired flag was set on the VDBE before the first call
31831 ** to sqlite3_step(). For consistency (since sqlite3_step() was
31832 ** called), set the database error in this case as well.
31834 sqlite3Error(db, p->rc, 0);
31837 /* Reclaim all memory used by the VDBE
31839 Cleanup(p);
31841 /* Save profiling information from this VDBE run.
31843 assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || !p->aStack );
31844 #ifdef VDBE_PROFILE
31846 FILE *out = fopen("vdbe_profile.out", "a");
31847 if( out ){
31848 int i;
31849 fprintf(out, "---- ");
31850 for(i=0; i<p->nOp; i++){
31851 fprintf(out, "%02x", p->aOp[i].opcode);
31853 fprintf(out, "\n");
31854 for(i=0; i<p->nOp; i++){
31855 fprintf(out, "%6d %10lld %8lld ",
31856 p->aOp[i].cnt,
31857 p->aOp[i].cycles,
31858 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
31860 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
31862 fclose(out);
31865 #endif
31866 p->magic = VDBE_MAGIC_INIT;
31867 p->aborted = 0;
31868 if( p->rc==SQLITE_SCHEMA ){
31869 sqlite3ResetInternalSchema(db, 0);
31871 return p->rc & db->errMask;
31875 ** Clean up and delete a VDBE after execution. Return an integer which is
31876 ** the result code. Write any error message text into *pzErrMsg.
31878 static int sqlite3VdbeFinalize(Vdbe *p){
31879 int rc = SQLITE_OK;
31880 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
31881 rc = sqlite3VdbeReset(p);
31882 assert( (rc & p->db->errMask)==rc );
31883 }else if( p->magic!=VDBE_MAGIC_INIT ){
31884 return SQLITE_MISUSE;
31886 sqlite3VdbeDelete(p);
31887 return rc;
31891 ** Call the destructor for each auxdata entry in pVdbeFunc for which
31892 ** the corresponding bit in mask is clear. Auxdata entries beyond 31
31893 ** are always destroyed. To destroy all auxdata entries, call this
31894 ** routine with mask==0.
31896 static void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
31897 int i;
31898 for(i=0; i<pVdbeFunc->nAux; i++){
31899 struct AuxData *pAux = &pVdbeFunc->apAux[i];
31900 if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
31901 if( pAux->xDelete ){
31902 pAux->xDelete(pAux->pAux);
31904 pAux->pAux = 0;
31910 ** Delete an entire VDBE.
31912 static void sqlite3VdbeDelete(Vdbe *p){
31913 int i;
31914 if( p==0 ) return;
31915 Cleanup(p);
31916 if( p->pPrev ){
31917 p->pPrev->pNext = p->pNext;
31918 }else{
31919 assert( p->db->pVdbe==p );
31920 p->db->pVdbe = p->pNext;
31922 if( p->pNext ){
31923 p->pNext->pPrev = p->pPrev;
31925 if( p->aOp ){
31926 for(i=0; i<p->nOp; i++){
31927 Op *pOp = &p->aOp[i];
31928 freeP3(pOp->p3type, pOp->p3);
31930 sqliteFree(p->aOp);
31932 releaseMemArray(p->aVar, p->nVar);
31933 sqliteFree(p->aLabel);
31934 sqliteFree(p->aStack);
31935 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
31936 sqliteFree(p->aColName);
31937 sqliteFree(p->zSql);
31938 p->magic = VDBE_MAGIC_DEAD;
31939 sqliteFree(p);
31943 ** If a MoveTo operation is pending on the given cursor, then do that
31944 ** MoveTo now. Return an error code. If no MoveTo is pending, this
31945 ** routine does nothing and returns SQLITE_OK.
31947 static int sqlite3VdbeCursorMoveto(Cursor *p){
31948 if( p->deferredMoveto ){
31949 int res, rc;
31950 #ifdef SQLITE_TEST
31951 extern int sqlite3_search_count;
31952 #endif
31953 assert( p->isTable );
31954 rc = sqlite3BtreeMoveto(p->pCursor, 0, p->movetoTarget, 0, &res);
31955 if( rc ) return rc;
31956 *p->pIncrKey = 0;
31957 p->lastRowid = keyToInt(p->movetoTarget);
31958 p->rowidIsValid = res==0;
31959 if( res<0 ){
31960 rc = sqlite3BtreeNext(p->pCursor, &res);
31961 if( rc ) return rc;
31963 #ifdef SQLITE_TEST
31964 sqlite3_search_count++;
31965 #endif
31966 p->deferredMoveto = 0;
31967 p->cacheStatus = CACHE_STALE;
31969 return SQLITE_OK;
31973 ** The following functions:
31975 ** sqlite3VdbeSerialType()
31976 ** sqlite3VdbeSerialTypeLen()
31977 ** sqlite3VdbeSerialRead()
31978 ** sqlite3VdbeSerialLen()
31979 ** sqlite3VdbeSerialWrite()
31981 ** encapsulate the code that serializes values for storage in SQLite
31982 ** data and index records. Each serialized value consists of a
31983 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
31984 ** integer, stored as a varint.
31986 ** In an SQLite index record, the serial type is stored directly before
31987 ** the blob of data that it corresponds to. In a table record, all serial
31988 ** types are stored at the start of the record, and the blobs of data at
31989 ** the end. Hence these functions allow the caller to handle the
31990 ** serial-type and data blob seperately.
31992 ** The following table describes the various storage classes for data:
31994 ** serial type bytes of data type
31995 ** -------------- --------------- ---------------
31996 ** 0 0 NULL
31997 ** 1 1 signed integer
31998 ** 2 2 signed integer
31999 ** 3 3 signed integer
32000 ** 4 4 signed integer
32001 ** 5 6 signed integer
32002 ** 6 8 signed integer
32003 ** 7 8 IEEE float
32004 ** 8 0 Integer constant 0
32005 ** 9 0 Integer constant 1
32006 ** 10,11 reserved for expansion
32007 ** N>=12 and even (N-12)/2 BLOB
32008 ** N>=13 and odd (N-13)/2 text
32010 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
32011 ** of SQLite will not understand those serial types.
32015 ** Return the serial-type for the value stored in pMem.
32017 static u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
32018 int flags = pMem->flags;
32019 int n;
32021 if( flags&MEM_Null ){
32022 return 0;
32024 if( flags&MEM_Int ){
32025 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
32026 # define MAX_6BYTE ((((i64)0x00001000)<<32)-1)
32027 i64 i = pMem->u.i;
32028 u64 u;
32029 if( file_format>=4 && (i&1)==i ){
32030 return 8+i;
32032 u = i<0 ? -i : i;
32033 if( u<=127 ) return 1;
32034 if( u<=32767 ) return 2;
32035 if( u<=8388607 ) return 3;
32036 if( u<=2147483647 ) return 4;
32037 if( u<=MAX_6BYTE ) return 5;
32038 return 6;
32040 if( flags&MEM_Real ){
32041 return 7;
32043 assert( flags&(MEM_Str|MEM_Blob) );
32044 n = pMem->n;
32045 if( flags & MEM_Zero ){
32046 n += pMem->u.i;
32048 assert( n>=0 );
32049 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
32053 ** Return the length of the data corresponding to the supplied serial-type.
32055 static int sqlite3VdbeSerialTypeLen(u32 serial_type){
32056 if( serial_type>=12 ){
32057 return (serial_type-12)/2;
32058 }else{
32059 static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
32060 return aSize[serial_type];
32065 ** If we are on an architecture with mixed-endian floating
32066 ** points (ex: ARM7) then swap the lower 4 bytes with the
32067 ** upper 4 bytes. Return the result.
32069 ** For most architectures, this is a no-op.
32071 ** (later): It is reported to me that the mixed-endian problem
32072 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
32073 ** that early versions of GCC stored the two words of a 64-bit
32074 ** float in the wrong order. And that error has been propagated
32075 ** ever since. The blame is not necessarily with GCC, though.
32076 ** GCC might have just copying the problem from a prior compiler.
32077 ** I am also told that newer versions of GCC that follow a different
32078 ** ABI get the byte order right.
32080 ** Developers using SQLite on an ARM7 should compile and run their
32081 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
32082 ** enabled, some asserts below will ensure that the byte order of
32083 ** floating point values is correct.
32085 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
32086 static double floatSwap(double in){
32087 union {
32088 double r;
32089 u32 i[2];
32090 } u;
32091 u32 t;
32093 u.r = in;
32094 t = u.i[0];
32095 u.i[0] = u.i[1];
32096 u.i[1] = t;
32097 return u.r;
32099 # define swapMixedEndianFloat(X) X = floatSwap(X)
32100 #else
32101 # define swapMixedEndianFloat(X)
32102 #endif
32105 ** Write the serialized data blob for the value stored in pMem into
32106 ** buf. It is assumed that the caller has allocated sufficient space.
32107 ** Return the number of bytes written.
32109 ** nBuf is the amount of space left in buf[]. nBuf must always be
32110 ** large enough to hold the entire field. Except, if the field is
32111 ** a blob with a zero-filled tail, then buf[] might be just the right
32112 ** size to hold everything except for the zero-filled tail. If buf[]
32113 ** is only big enough to hold the non-zero prefix, then only write that
32114 ** prefix into buf[]. But if buf[] is large enough to hold both the
32115 ** prefix and the tail then write the prefix and set the tail to all
32116 ** zeros.
32118 ** Return the number of bytes actually written into buf[]. The number
32119 ** of bytes in the zero-filled tail is included in the return value only
32120 ** if those bytes were zeroed in buf[].
32122 static int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
32123 u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
32124 int len;
32126 /* Integer and Real */
32127 if( serial_type<=7 && serial_type>0 ){
32128 u64 v;
32129 int i;
32130 if( serial_type==7 ){
32131 assert( sizeof(v)==sizeof(pMem->r) );
32132 swapMixedEndianFloat(pMem->r);
32133 memcpy(&v, &pMem->r, sizeof(v));
32134 }else{
32135 v = pMem->u.i;
32137 len = i = sqlite3VdbeSerialTypeLen(serial_type);
32138 assert( len<=nBuf );
32139 while( i-- ){
32140 buf[i] = (v&0xFF);
32141 v >>= 8;
32143 return len;
32146 /* String or blob */
32147 if( serial_type>=12 ){
32148 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
32149 == sqlite3VdbeSerialTypeLen(serial_type) );
32150 assert( pMem->n<=nBuf );
32151 len = pMem->n;
32152 memcpy(buf, pMem->z, len);
32153 if( pMem->flags & MEM_Zero ){
32154 len += pMem->u.i;
32155 if( len>nBuf ){
32156 len = nBuf;
32158 memset(&buf[pMem->n], 0, len-pMem->n);
32160 return len;
32163 /* NULL or constants 0 or 1 */
32164 return 0;
32168 ** Deserialize the data blob pointed to by buf as serial type serial_type
32169 ** and store the result in pMem. Return the number of bytes read.
32171 static int sqlite3VdbeSerialGet(
32172 const unsigned char *buf, /* Buffer to deserialize from */
32173 u32 serial_type, /* Serial type to deserialize */
32174 Mem *pMem /* Memory cell to write value into */
32176 switch( serial_type ){
32177 case 10: /* Reserved for future use */
32178 case 11: /* Reserved for future use */
32179 case 0: { /* NULL */
32180 pMem->flags = MEM_Null;
32181 break;
32183 case 1: { /* 1-byte signed integer */
32184 pMem->u.i = (signed char)buf[0];
32185 pMem->flags = MEM_Int;
32186 return 1;
32188 case 2: { /* 2-byte signed integer */
32189 pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
32190 pMem->flags = MEM_Int;
32191 return 2;
32193 case 3: { /* 3-byte signed integer */
32194 pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
32195 pMem->flags = MEM_Int;
32196 return 3;
32198 case 4: { /* 4-byte signed integer */
32199 pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
32200 pMem->flags = MEM_Int;
32201 return 4;
32203 case 5: { /* 6-byte signed integer */
32204 u64 x = (((signed char)buf[0])<<8) | buf[1];
32205 u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
32206 x = (x<<32) | y;
32207 pMem->u.i = *(i64*)&x;
32208 pMem->flags = MEM_Int;
32209 return 6;
32211 case 6: /* 8-byte signed integer */
32212 case 7: { /* IEEE floating point */
32213 u64 x;
32214 u32 y;
32215 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
32216 /* Verify that integers and floating point values use the same
32217 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
32218 ** defined that 64-bit floating point values really are mixed
32219 ** endian.
32221 static const u64 t1 = ((u64)0x3ff00000)<<32;
32222 static const double r1 = 1.0;
32223 double r2 = r1;
32224 swapMixedEndianFloat(r2);
32225 assert( sizeof(r2)==sizeof(t1) && memcmp(&r2, &t1, sizeof(r1))==0 );
32226 #endif
32228 x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
32229 y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
32230 x = (x<<32) | y;
32231 if( serial_type==6 ){
32232 pMem->u.i = *(i64*)&x;
32233 pMem->flags = MEM_Int;
32234 }else{
32235 assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
32236 memcpy(&pMem->r, &x, sizeof(x));
32237 swapMixedEndianFloat(pMem->r);
32238 pMem->flags = MEM_Real;
32240 return 8;
32242 case 8: /* Integer 0 */
32243 case 9: { /* Integer 1 */
32244 pMem->u.i = serial_type-8;
32245 pMem->flags = MEM_Int;
32246 return 0;
32248 default: {
32249 int len = (serial_type-12)/2;
32250 pMem->z = (char *)buf;
32251 pMem->n = len;
32252 pMem->xDel = 0;
32253 if( serial_type&0x01 ){
32254 pMem->flags = MEM_Str | MEM_Ephem;
32255 }else{
32256 pMem->flags = MEM_Blob | MEM_Ephem;
32258 return len;
32261 return 0;
32265 ** The header of a record consists of a sequence variable-length integers.
32266 ** These integers are almost always small and are encoded as a single byte.
32267 ** The following macro takes advantage this fact to provide a fast decode
32268 ** of the integers in a record header. It is faster for the common case
32269 ** where the integer is a single byte. It is a little slower when the
32270 ** integer is two or more bytes. But overall it is faster.
32272 ** The following expressions are equivalent:
32274 ** x = sqlite3GetVarint32( A, &B );
32276 ** x = GetVarint( A, B );
32279 #define GetVarint(A,B) ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
32282 ** This function compares the two table rows or index records specified by
32283 ** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero
32284 ** or positive integer if {nKey1, pKey1} is less than, equal to or
32285 ** greater than {nKey2, pKey2}. Both Key1 and Key2 must be byte strings
32286 ** composed by the OP_MakeRecord opcode of the VDBE.
32288 static int sqlite3VdbeRecordCompare(
32289 void *userData,
32290 int nKey1, const void *pKey1,
32291 int nKey2, const void *pKey2
32293 KeyInfo *pKeyInfo = (KeyInfo*)userData;
32294 u32 d1, d2; /* Offset into aKey[] of next data element */
32295 u32 idx1, idx2; /* Offset into aKey[] of next header element */
32296 u32 szHdr1, szHdr2; /* Number of bytes in header */
32297 int i = 0;
32298 int nField;
32299 int rc = 0;
32300 const unsigned char *aKey1 = (const unsigned char *)pKey1;
32301 const unsigned char *aKey2 = (const unsigned char *)pKey2;
32303 Mem mem1;
32304 Mem mem2;
32305 mem1.enc = pKeyInfo->enc;
32306 mem2.enc = pKeyInfo->enc;
32308 idx1 = GetVarint(aKey1, szHdr1);
32309 d1 = szHdr1;
32310 idx2 = GetVarint(aKey2, szHdr2);
32311 d2 = szHdr2;
32312 nField = pKeyInfo->nField;
32313 while( idx1<szHdr1 && idx2<szHdr2 ){
32314 u32 serial_type1;
32315 u32 serial_type2;
32317 /* Read the serial types for the next element in each key. */
32318 idx1 += GetVarint( aKey1+idx1, serial_type1 );
32319 if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
32320 idx2 += GetVarint( aKey2+idx2, serial_type2 );
32321 if( d2>=nKey2 && sqlite3VdbeSerialTypeLen(serial_type2)>0 ) break;
32323 /* Extract the values to be compared.
32325 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
32326 d2 += sqlite3VdbeSerialGet(&aKey2[d2], serial_type2, &mem2);
32328 /* Do the comparison
32330 rc = sqlite3MemCompare(&mem1, &mem2, i<nField ? pKeyInfo->aColl[i] : 0);
32331 if( mem1.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem1);
32332 if( mem2.flags & MEM_Dyn ) sqlite3VdbeMemRelease(&mem2);
32333 if( rc!=0 ){
32334 break;
32336 i++;
32339 /* One of the keys ran out of fields, but all the fields up to that point
32340 ** were equal. If the incrKey flag is true, then the second key is
32341 ** treated as larger.
32343 if( rc==0 ){
32344 if( pKeyInfo->incrKey ){
32345 rc = -1;
32346 }else if( d1<nKey1 ){
32347 rc = 1;
32348 }else if( d2<nKey2 ){
32349 rc = -1;
32351 }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
32352 && pKeyInfo->aSortOrder[i] ){
32353 rc = -rc;
32356 return rc;
32360 ** The argument is an index entry composed using the OP_MakeRecord opcode.
32361 ** The last entry in this record should be an integer (specifically
32362 ** an integer rowid). This routine returns the number of bytes in
32363 ** that integer.
32365 static int sqlite3VdbeIdxRowidLen(const u8 *aKey){
32366 u32 szHdr; /* Size of the header */
32367 u32 typeRowid; /* Serial type of the rowid */
32369 sqlite3GetVarint32(aKey, &szHdr);
32370 sqlite3GetVarint32(&aKey[szHdr-1], &typeRowid);
32371 return sqlite3VdbeSerialTypeLen(typeRowid);
32376 ** pCur points at an index entry created using the OP_MakeRecord opcode.
32377 ** Read the rowid (the last field in the record) and store it in *rowid.
32378 ** Return SQLITE_OK if everything works, or an error code otherwise.
32380 static int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
32381 i64 nCellKey = 0;
32382 int rc;
32383 u32 szHdr; /* Size of the header */
32384 u32 typeRowid; /* Serial type of the rowid */
32385 u32 lenRowid; /* Size of the rowid */
32386 Mem m, v;
32388 sqlite3BtreeKeySize(pCur, &nCellKey);
32389 if( nCellKey<=0 ){
32390 return SQLITE_CORRUPT_BKPT;
32392 rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
32393 if( rc ){
32394 return rc;
32396 sqlite3GetVarint32((u8*)m.z, &szHdr);
32397 sqlite3GetVarint32((u8*)&m.z[szHdr-1], &typeRowid);
32398 lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
32399 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
32400 *rowid = v.u.i;
32401 sqlite3VdbeMemRelease(&m);
32402 return SQLITE_OK;
32406 ** Compare the key of the index entry that cursor pC is point to against
32407 ** the key string in pKey (of length nKey). Write into *pRes a number
32408 ** that is negative, zero, or positive if pC is less than, equal to,
32409 ** or greater than pKey. Return SQLITE_OK on success.
32411 ** pKey is either created without a rowid or is truncated so that it
32412 ** omits the rowid at the end. The rowid at the end of the index entry
32413 ** is ignored as well.
32415 static int sqlite3VdbeIdxKeyCompare(
32416 Cursor *pC, /* The cursor to compare against */
32417 int nKey, const u8 *pKey, /* The key to compare */
32418 int *res /* Write the comparison result here */
32420 i64 nCellKey = 0;
32421 int rc;
32422 BtCursor *pCur = pC->pCursor;
32423 int lenRowid;
32424 Mem m;
32426 sqlite3BtreeKeySize(pCur, &nCellKey);
32427 if( nCellKey<=0 ){
32428 *res = 0;
32429 return SQLITE_OK;
32431 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
32432 if( rc ){
32433 return rc;
32435 lenRowid = sqlite3VdbeIdxRowidLen((u8*)m.z);
32436 *res = sqlite3VdbeRecordCompare(pC->pKeyInfo, m.n-lenRowid, m.z, nKey, pKey);
32437 sqlite3VdbeMemRelease(&m);
32438 return SQLITE_OK;
32442 ** This routine sets the value to be returned by subsequent calls to
32443 ** sqlite3_changes() on the database handle 'db'.
32445 static void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
32446 db->nChange = nChange;
32447 db->nTotalChange += nChange;
32451 ** Set a flag in the vdbe to update the change counter when it is finalised
32452 ** or reset.
32454 static void sqlite3VdbeCountChanges(Vdbe *v){
32455 v->changeCntOn = 1;
32459 ** Mark every prepared statement associated with a database connection
32460 ** as expired.
32462 ** An expired statement means that recompilation of the statement is
32463 ** recommend. Statements expire when things happen that make their
32464 ** programs obsolete. Removing user-defined functions or collating
32465 ** sequences, or changing an authorization function are the types of
32466 ** things that make prepared statements obsolete.
32468 static void sqlite3ExpirePreparedStatements(sqlite3 *db){
32469 Vdbe *p;
32470 for(p = db->pVdbe; p; p=p->pNext){
32471 p->expired = 1;
32476 ** Return the database associated with the Vdbe.
32478 static sqlite3 *sqlite3VdbeDb(Vdbe *v){
32479 return v->db;
32482 /************** End of vdbeaux.c *********************************************/
32483 /************** Begin file vdbeapi.c *****************************************/
32485 ** 2004 May 26
32487 ** The author disclaims copyright to this source code. In place of
32488 ** a legal notice, here is a blessing:
32490 ** May you do good and not evil.
32491 ** May you find forgiveness for yourself and forgive others.
32492 ** May you share freely, never taking more than you give.
32494 *************************************************************************
32496 ** This file contains code use to implement APIs that are part of the
32497 ** VDBE.
32501 ** Return TRUE (non-zero) of the statement supplied as an argument needs
32502 ** to be recompiled. A statement needs to be recompiled whenever the
32503 ** execution environment changes in a way that would alter the program
32504 ** that sqlite3_prepare() generates. For example, if new functions or
32505 ** collating sequences are registered or if an authorizer function is
32506 ** added or changed.
32508 int sqlite3_expired(sqlite3_stmt *pStmt){
32509 Vdbe *p = (Vdbe*)pStmt;
32510 return p==0 || p->expired;
32513 /**************************** sqlite3_value_ *******************************
32514 ** The following routines extract information from a Mem or sqlite3_value
32515 ** structure.
32517 const void *sqlite3_value_blob(sqlite3_value *pVal){
32518 Mem *p = (Mem*)pVal;
32519 if( p->flags & (MEM_Blob|MEM_Str) ){
32520 sqlite3VdbeMemExpandBlob(p);
32521 p->flags &= ~MEM_Str;
32522 p->flags |= MEM_Blob;
32523 return p->z;
32524 }else{
32525 return sqlite3_value_text(pVal);
32528 int sqlite3_value_bytes(sqlite3_value *pVal){
32529 return sqlite3ValueBytes(pVal, SQLITE_UTF8);
32531 int sqlite3_value_bytes16(sqlite3_value *pVal){
32532 return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
32534 double sqlite3_value_double(sqlite3_value *pVal){
32535 return sqlite3VdbeRealValue((Mem*)pVal);
32537 int sqlite3_value_int(sqlite3_value *pVal){
32538 return sqlite3VdbeIntValue((Mem*)pVal);
32540 sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
32541 return sqlite3VdbeIntValue((Mem*)pVal);
32543 const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
32544 return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
32546 #ifndef SQLITE_OMIT_UTF16
32547 const void *sqlite3_value_text16(sqlite3_value* pVal){
32548 return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
32550 const void *sqlite3_value_text16be(sqlite3_value *pVal){
32551 return sqlite3ValueText(pVal, SQLITE_UTF16BE);
32553 const void *sqlite3_value_text16le(sqlite3_value *pVal){
32554 return sqlite3ValueText(pVal, SQLITE_UTF16LE);
32556 #endif /* SQLITE_OMIT_UTF16 */
32557 int sqlite3_value_type(sqlite3_value* pVal){
32558 return pVal->type;
32560 /* sqlite3_value_numeric_type() defined in vdbe.c */
32562 /**************************** sqlite3_result_ *******************************
32563 ** The following routines are used by user-defined functions to specify
32564 ** the function result.
32566 void sqlite3_result_blob(
32567 sqlite3_context *pCtx,
32568 const void *z,
32569 int n,
32570 void (*xDel)(void *)
32572 assert( n>=0 );
32573 sqlite3VdbeMemSetStr(&pCtx->s, z, n, 0, xDel);
32575 void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
32576 sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
32578 void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
32579 pCtx->isError = 1;
32580 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
32582 #ifndef SQLITE_OMIT_UTF16
32583 void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
32584 pCtx->isError = 1;
32585 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
32587 #endif
32588 void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
32589 sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
32591 void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
32592 sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
32594 void sqlite3_result_null(sqlite3_context *pCtx){
32595 sqlite3VdbeMemSetNull(&pCtx->s);
32597 void sqlite3_result_text(
32598 sqlite3_context *pCtx,
32599 const char *z,
32600 int n,
32601 void (*xDel)(void *)
32603 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, xDel);
32605 #ifndef SQLITE_OMIT_UTF16
32606 void sqlite3_result_text16(
32607 sqlite3_context *pCtx,
32608 const void *z,
32609 int n,
32610 void (*xDel)(void *)
32612 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, xDel);
32614 void sqlite3_result_text16be(
32615 sqlite3_context *pCtx,
32616 const void *z,
32617 int n,
32618 void (*xDel)(void *)
32620 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16BE, xDel);
32622 void sqlite3_result_text16le(
32623 sqlite3_context *pCtx,
32624 const void *z,
32625 int n,
32626 void (*xDel)(void *)
32628 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16LE, xDel);
32630 #endif /* SQLITE_OMIT_UTF16 */
32631 void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
32632 sqlite3VdbeMemCopy(&pCtx->s, pValue);
32634 void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
32635 sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
32638 /* Force an SQLITE_TOOBIG error. */
32639 void sqlite3_result_error_toobig(sqlite3_context *pCtx){
32640 sqlite3VdbeMemSetZeroBlob(&pCtx->s, SQLITE_MAX_LENGTH+1);
32645 ** Execute the statement pStmt, either until a row of data is ready, the
32646 ** statement is completely executed or an error occurs.
32648 ** This routine implements the bulk of the logic behind the sqlite_step()
32649 ** API. The only thing omitted is the automatic recompile if a
32650 ** schema change has occurred. That detail is handled by the
32651 ** outer sqlite3_step() wrapper procedure.
32653 static int sqlite3Step(Vdbe *p){
32654 sqlite3 *db;
32655 int rc;
32657 /* Assert that malloc() has not failed */
32658 assert( !sqlite3MallocFailed() );
32660 if( p==0 || p->magic!=VDBE_MAGIC_RUN ){
32661 return SQLITE_MISUSE;
32663 if( p->aborted ){
32664 return SQLITE_ABORT;
32666 if( p->pc<=0 && p->expired ){
32667 if( p->rc==SQLITE_OK ){
32668 p->rc = SQLITE_SCHEMA;
32670 rc = SQLITE_ERROR;
32671 goto end_of_step;
32673 db = p->db;
32674 if( sqlite3SafetyOn(db) ){
32675 p->rc = SQLITE_MISUSE;
32676 return SQLITE_MISUSE;
32678 if( p->pc<0 ){
32679 /* If there are no other statements currently running, then
32680 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
32681 ** from interrupting a statement that has not yet started.
32683 if( db->activeVdbeCnt==0 ){
32684 db->u1.isInterrupted = 0;
32687 #ifndef SQLITE_OMIT_TRACE
32688 /* Invoke the trace callback if there is one
32690 if( db->xTrace && !db->init.busy ){
32691 assert( p->nOp>0 );
32692 assert( p->aOp[p->nOp-1].opcode==OP_Noop );
32693 assert( p->aOp[p->nOp-1].p3!=0 );
32694 assert( p->aOp[p->nOp-1].p3type==P3_DYNAMIC );
32695 sqlite3SafetyOff(db);
32696 db->xTrace(db->pTraceArg, p->aOp[p->nOp-1].p3);
32697 if( sqlite3SafetyOn(db) ){
32698 p->rc = SQLITE_MISUSE;
32699 return SQLITE_MISUSE;
32702 if( db->xProfile && !db->init.busy ){
32703 double rNow;
32704 sqlite3OsCurrentTime(&rNow);
32705 p->startTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0;
32707 #endif
32709 /* Print a copy of SQL as it is executed if the SQL_TRACE pragma is turned
32710 ** on in debugging mode.
32712 #ifdef SQLITE_DEBUG
32713 if( (db->flags & SQLITE_SqlTrace)!=0 ){
32714 sqlite3DebugPrintf("SQL-trace: %s\n", p->aOp[p->nOp-1].p3);
32716 #endif /* SQLITE_DEBUG */
32718 db->activeVdbeCnt++;
32719 p->pc = 0;
32721 #ifndef SQLITE_OMIT_EXPLAIN
32722 if( p->explain ){
32723 rc = sqlite3VdbeList(p);
32724 }else
32725 #endif /* SQLITE_OMIT_EXPLAIN */
32727 rc = sqlite3VdbeExec(p);
32730 if( sqlite3SafetyOff(db) ){
32731 rc = SQLITE_MISUSE;
32734 #ifndef SQLITE_OMIT_TRACE
32735 /* Invoke the profile callback if there is one
32737 if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy ){
32738 double rNow;
32739 u64 elapseTime;
32741 sqlite3OsCurrentTime(&rNow);
32742 elapseTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0 - p->startTime;
32743 assert( p->nOp>0 );
32744 assert( p->aOp[p->nOp-1].opcode==OP_Noop );
32745 assert( p->aOp[p->nOp-1].p3!=0 );
32746 assert( p->aOp[p->nOp-1].p3type==P3_DYNAMIC );
32747 db->xProfile(db->pProfileArg, p->aOp[p->nOp-1].p3, elapseTime);
32749 #endif
32751 sqlite3Error(p->db, rc, 0);
32752 p->rc = sqlite3ApiExit(p->db, p->rc);
32753 end_of_step:
32754 assert( (rc&0xff)==rc );
32755 if( p->zSql && (rc&0xff)<SQLITE_ROW ){
32756 /* This behavior occurs if sqlite3_prepare_v2() was used to build
32757 ** the prepared statement. Return error codes directly */
32758 return p->rc;
32759 }else{
32760 /* This is for legacy sqlite3_prepare() builds and when the code
32761 ** is SQLITE_ROW or SQLITE_DONE */
32762 return rc;
32767 ** This is the top-level implementation of sqlite3_step(). Call
32768 ** sqlite3Step() to do most of the work. If a schema error occurs,
32769 ** call sqlite3Reprepare() and try again.
32771 #ifdef SQLITE_OMIT_PARSER
32772 int sqlite3_step(sqlite3_stmt *pStmt){
32773 return sqlite3Step((Vdbe*)pStmt);
32775 #else
32776 int sqlite3_step(sqlite3_stmt *pStmt){
32777 int cnt = 0;
32778 int rc;
32779 Vdbe *v = (Vdbe*)pStmt;
32780 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
32781 && cnt++ < 5
32782 && sqlite3Reprepare(v) ){
32783 sqlite3_reset(pStmt);
32784 v->expired = 0;
32786 return rc;
32788 #endif
32791 ** Extract the user data from a sqlite3_context structure and return a
32792 ** pointer to it.
32794 void *sqlite3_user_data(sqlite3_context *p){
32795 assert( p && p->pFunc );
32796 return p->pFunc->pUserData;
32800 ** The following is the implementation of an SQL function that always
32801 ** fails with an error message stating that the function is used in the
32802 ** wrong context. The sqlite3_overload_function() API might construct
32803 ** SQL function that use this routine so that the functions will exist
32804 ** for name resolution but are actually overloaded by the xFindFunction
32805 ** method of virtual tables.
32807 static void sqlite3InvalidFunction(
32808 sqlite3_context *context, /* The function calling context */
32809 int argc, /* Number of arguments to the function */
32810 sqlite3_value **argv /* Value of each argument */
32812 const char *zName = context->pFunc->zName;
32813 char *zErr;
32814 zErr = sqlite3MPrintf(
32815 "unable to use function %s in the requested context", zName);
32816 sqlite3_result_error(context, zErr, -1);
32817 sqliteFree(zErr);
32821 ** Allocate or return the aggregate context for a user function. A new
32822 ** context is allocated on the first call. Subsequent calls return the
32823 ** same context that was returned on prior calls.
32825 void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
32826 Mem *pMem = p->pMem;
32827 assert( p && p->pFunc && p->pFunc->xStep );
32828 if( (pMem->flags & MEM_Agg)==0 ){
32829 if( nByte==0 ){
32830 assert( pMem->flags==MEM_Null );
32831 pMem->z = 0;
32832 }else{
32833 pMem->flags = MEM_Agg;
32834 pMem->xDel = sqlite3FreeX;
32835 pMem->u.pDef = p->pFunc;
32836 if( nByte<=NBFS ){
32837 pMem->z = pMem->zShort;
32838 memset(pMem->z, 0, nByte);
32839 }else{
32840 pMem->z = sqliteMalloc( nByte );
32844 return (void*)pMem->z;
32848 ** Return the auxilary data pointer, if any, for the iArg'th argument to
32849 ** the user-function defined by pCtx.
32851 void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
32852 VdbeFunc *pVdbeFunc = pCtx->pVdbeFunc;
32853 if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
32854 return 0;
32856 return pVdbeFunc->apAux[iArg].pAux;
32860 ** Set the auxilary data pointer and delete function, for the iArg'th
32861 ** argument to the user-function defined by pCtx. Any previous value is
32862 ** deleted by calling the delete function specified when it was set.
32864 void sqlite3_set_auxdata(
32865 sqlite3_context *pCtx,
32866 int iArg,
32867 void *pAux,
32868 void (*xDelete)(void*)
32870 struct AuxData *pAuxData;
32871 VdbeFunc *pVdbeFunc;
32872 if( iArg<0 ) return;
32874 pVdbeFunc = pCtx->pVdbeFunc;
32875 if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
32876 int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
32877 pVdbeFunc = sqliteRealloc(pVdbeFunc, nMalloc);
32878 if( !pVdbeFunc ) return;
32879 pCtx->pVdbeFunc = pVdbeFunc;
32880 memset(&pVdbeFunc->apAux[pVdbeFunc->nAux], 0,
32881 sizeof(struct AuxData)*(iArg+1-pVdbeFunc->nAux));
32882 pVdbeFunc->nAux = iArg+1;
32883 pVdbeFunc->pFunc = pCtx->pFunc;
32886 pAuxData = &pVdbeFunc->apAux[iArg];
32887 if( pAuxData->pAux && pAuxData->xDelete ){
32888 pAuxData->xDelete(pAuxData->pAux);
32890 pAuxData->pAux = pAux;
32891 pAuxData->xDelete = xDelete;
32895 ** Return the number of times the Step function of a aggregate has been
32896 ** called.
32898 ** This function is deprecated. Do not use it for new code. It is
32899 ** provide only to avoid breaking legacy code. New aggregate function
32900 ** implementations should keep their own counts within their aggregate
32901 ** context.
32903 int sqlite3_aggregate_count(sqlite3_context *p){
32904 assert( p && p->pFunc && p->pFunc->xStep );
32905 return p->pMem->n;
32909 ** Return the number of columns in the result set for the statement pStmt.
32911 int sqlite3_column_count(sqlite3_stmt *pStmt){
32912 Vdbe *pVm = (Vdbe *)pStmt;
32913 return pVm ? pVm->nResColumn : 0;
32917 ** Return the number of values available from the current row of the
32918 ** currently executing statement pStmt.
32920 int sqlite3_data_count(sqlite3_stmt *pStmt){
32921 Vdbe *pVm = (Vdbe *)pStmt;
32922 if( pVm==0 || !pVm->resOnStack ) return 0;
32923 return pVm->nResColumn;
32928 ** Check to see if column iCol of the given statement is valid. If
32929 ** it is, return a pointer to the Mem for the value of that column.
32930 ** If iCol is not valid, return a pointer to a Mem which has a value
32931 ** of NULL.
32933 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
32934 Vdbe *pVm = (Vdbe *)pStmt;
32935 int vals = sqlite3_data_count(pStmt);
32936 if( i>=vals || i<0 ){
32937 static const Mem nullMem = {{0}, 0.0, "", 0, MEM_Null, SQLITE_NULL };
32938 sqlite3Error(pVm->db, SQLITE_RANGE, 0);
32939 return (Mem*)&nullMem;
32941 return &pVm->pTos[(1-vals)+i];
32945 ** This function is called after invoking an sqlite3_value_XXX function on a
32946 ** column value (i.e. a value returned by evaluating an SQL expression in the
32947 ** select list of a SELECT statement) that may cause a malloc() failure. If
32948 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
32949 ** code of statement pStmt set to SQLITE_NOMEM.
32951 ** Specificly, this is called from within:
32953 ** sqlite3_column_int()
32954 ** sqlite3_column_int64()
32955 ** sqlite3_column_text()
32956 ** sqlite3_column_text16()
32957 ** sqlite3_column_real()
32958 ** sqlite3_column_bytes()
32959 ** sqlite3_column_bytes16()
32961 ** But not for sqlite3_column_blob(), which never calls malloc().
32963 static void columnMallocFailure(sqlite3_stmt *pStmt)
32965 /* If malloc() failed during an encoding conversion within an
32966 ** sqlite3_column_XXX API, then set the return code of the statement to
32967 ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
32968 ** and _finalize() will return NOMEM.
32970 Vdbe *p = (Vdbe *)pStmt;
32971 p->rc = sqlite3ApiExit(0, p->rc);
32974 /**************************** sqlite3_column_ *******************************
32975 ** The following routines are used to access elements of the current row
32976 ** in the result set.
32978 const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
32979 const void *val;
32980 val = sqlite3_value_blob( columnMem(pStmt,i) );
32981 /* Even though there is no encoding conversion, value_blob() might
32982 ** need to call malloc() to expand the result of a zeroblob()
32983 ** expression.
32985 columnMallocFailure(pStmt);
32986 return val;
32988 int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
32989 int val = sqlite3_value_bytes( columnMem(pStmt,i) );
32990 columnMallocFailure(pStmt);
32991 return val;
32993 int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
32994 int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
32995 columnMallocFailure(pStmt);
32996 return val;
32998 double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
32999 double val = sqlite3_value_double( columnMem(pStmt,i) );
33000 columnMallocFailure(pStmt);
33001 return val;
33003 int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
33004 int val = sqlite3_value_int( columnMem(pStmt,i) );
33005 columnMallocFailure(pStmt);
33006 return val;
33008 sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
33009 sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
33010 columnMallocFailure(pStmt);
33011 return val;
33013 const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
33014 const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
33015 columnMallocFailure(pStmt);
33016 return val;
33018 sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
33019 return columnMem(pStmt, i);
33021 #ifndef SQLITE_OMIT_UTF16
33022 const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
33023 const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
33024 columnMallocFailure(pStmt);
33025 return val;
33027 #endif /* SQLITE_OMIT_UTF16 */
33028 int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
33029 return sqlite3_value_type( columnMem(pStmt,i) );
33032 /* The following function is experimental and subject to change or
33033 ** removal */
33034 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
33035 ** return sqlite3_value_numeric_type( columnMem(pStmt,i) );
33040 ** Convert the N-th element of pStmt->pColName[] into a string using
33041 ** xFunc() then return that string. If N is out of range, return 0.
33043 ** There are up to 5 names for each column. useType determines which
33044 ** name is returned. Here are the names:
33046 ** 0 The column name as it should be displayed for output
33047 ** 1 The datatype name for the column
33048 ** 2 The name of the database that the column derives from
33049 ** 3 The name of the table that the column derives from
33050 ** 4 The name of the table column that the result column derives from
33052 ** If the result is not a simple column reference (if it is an expression
33053 ** or a constant) then useTypes 2, 3, and 4 return NULL.
33055 static const void *columnName(
33056 sqlite3_stmt *pStmt,
33057 int N,
33058 const void *(*xFunc)(Mem*),
33059 int useType
33061 const void *ret;
33062 Vdbe *p = (Vdbe *)pStmt;
33063 int n = sqlite3_column_count(pStmt);
33065 if( p==0 || N>=n || N<0 ){
33066 return 0;
33068 N += useType*n;
33069 ret = xFunc(&p->aColName[N]);
33071 /* A malloc may have failed inside of the xFunc() call. If this is the case,
33072 ** clear the mallocFailed flag and return NULL.
33074 sqlite3ApiExit(0, 0);
33075 return ret;
33079 ** Return the name of the Nth column of the result set returned by SQL
33080 ** statement pStmt.
33082 const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
33083 return columnName(
33084 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
33086 #ifndef SQLITE_OMIT_UTF16
33087 const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
33088 return columnName(
33089 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
33091 #endif
33094 ** Return the column declaration type (if applicable) of the 'i'th column
33095 ** of the result set of SQL statement pStmt.
33097 const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
33098 return columnName(
33099 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
33101 #ifndef SQLITE_OMIT_UTF16
33102 const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
33103 return columnName(
33104 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
33106 #endif /* SQLITE_OMIT_UTF16 */
33108 #ifdef SQLITE_ENABLE_COLUMN_METADATA
33110 ** Return the name of the database from which a result column derives.
33111 ** NULL is returned if the result column is an expression or constant or
33112 ** anything else which is not an unabiguous reference to a database column.
33114 const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
33115 return columnName(
33116 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
33118 #ifndef SQLITE_OMIT_UTF16
33119 const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
33120 return columnName(
33121 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
33123 #endif /* SQLITE_OMIT_UTF16 */
33126 ** Return the name of the table from which a result column derives.
33127 ** NULL is returned if the result column is an expression or constant or
33128 ** anything else which is not an unabiguous reference to a database column.
33130 const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
33131 return columnName(
33132 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
33134 #ifndef SQLITE_OMIT_UTF16
33135 const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
33136 return columnName(
33137 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
33139 #endif /* SQLITE_OMIT_UTF16 */
33142 ** Return the name of the table column from which a result column derives.
33143 ** NULL is returned if the result column is an expression or constant or
33144 ** anything else which is not an unabiguous reference to a database column.
33146 const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
33147 return columnName(
33148 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
33150 #ifndef SQLITE_OMIT_UTF16
33151 const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
33152 return columnName(
33153 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
33155 #endif /* SQLITE_OMIT_UTF16 */
33156 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
33159 /******************************* sqlite3_bind_ ***************************
33161 ** Routines used to attach values to wildcards in a compiled SQL statement.
33164 ** Unbind the value bound to variable i in virtual machine p. This is the
33165 ** the same as binding a NULL value to the column. If the "i" parameter is
33166 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
33168 ** The error code stored in database p->db is overwritten with the return
33169 ** value in any case.
33171 static int vdbeUnbind(Vdbe *p, int i){
33172 Mem *pVar;
33173 if( p==0 || p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
33174 if( p ) sqlite3Error(p->db, SQLITE_MISUSE, 0);
33175 return SQLITE_MISUSE;
33177 if( i<1 || i>p->nVar ){
33178 sqlite3Error(p->db, SQLITE_RANGE, 0);
33179 return SQLITE_RANGE;
33181 i--;
33182 pVar = &p->aVar[i];
33183 sqlite3VdbeMemRelease(pVar);
33184 pVar->flags = MEM_Null;
33185 sqlite3Error(p->db, SQLITE_OK, 0);
33186 return SQLITE_OK;
33190 ** Bind a text or BLOB value.
33192 static int bindText(
33193 sqlite3_stmt *pStmt,
33194 int i,
33195 const void *zData,
33196 int nData,
33197 void (*xDel)(void*),
33198 int encoding
33200 Vdbe *p = (Vdbe *)pStmt;
33201 Mem *pVar;
33202 int rc;
33204 rc = vdbeUnbind(p, i);
33205 if( rc || zData==0 ){
33206 return rc;
33208 pVar = &p->aVar[i-1];
33209 rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
33210 if( rc==SQLITE_OK && encoding!=0 ){
33211 rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
33214 sqlite3Error(((Vdbe *)pStmt)->db, rc, 0);
33215 return sqlite3ApiExit(((Vdbe *)pStmt)->db, rc);
33220 ** Bind a blob value to an SQL statement variable.
33222 int sqlite3_bind_blob(
33223 sqlite3_stmt *pStmt,
33224 int i,
33225 const void *zData,
33226 int nData,
33227 void (*xDel)(void*)
33229 return bindText(pStmt, i, zData, nData, xDel, 0);
33231 int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
33232 int rc;
33233 Vdbe *p = (Vdbe *)pStmt;
33234 rc = vdbeUnbind(p, i);
33235 if( rc==SQLITE_OK ){
33236 sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
33238 return rc;
33240 int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
33241 return sqlite3_bind_int64(p, i, (i64)iValue);
33243 int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
33244 int rc;
33245 Vdbe *p = (Vdbe *)pStmt;
33246 rc = vdbeUnbind(p, i);
33247 if( rc==SQLITE_OK ){
33248 sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
33250 return rc;
33252 int sqlite3_bind_null(sqlite3_stmt* p, int i){
33253 return vdbeUnbind((Vdbe *)p, i);
33255 int sqlite3_bind_text(
33256 sqlite3_stmt *pStmt,
33257 int i,
33258 const char *zData,
33259 int nData,
33260 void (*xDel)(void*)
33262 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
33264 #ifndef SQLITE_OMIT_UTF16
33265 int sqlite3_bind_text16(
33266 sqlite3_stmt *pStmt,
33267 int i,
33268 const void *zData,
33269 int nData,
33270 void (*xDel)(void*)
33272 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
33274 #endif /* SQLITE_OMIT_UTF16 */
33275 int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
33276 int rc;
33277 Vdbe *p = (Vdbe *)pStmt;
33278 rc = vdbeUnbind(p, i);
33279 if( rc==SQLITE_OK ){
33280 sqlite3VdbeMemCopy(&p->aVar[i-1], pValue);
33282 return rc;
33284 int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
33285 int rc;
33286 Vdbe *p = (Vdbe *)pStmt;
33287 rc = vdbeUnbind(p, i);
33288 if( rc==SQLITE_OK ){
33289 sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
33291 return rc;
33295 ** Return the number of wildcards that can be potentially bound to.
33296 ** This routine is added to support DBD::SQLite.
33298 int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
33299 Vdbe *p = (Vdbe*)pStmt;
33300 return p ? p->nVar : 0;
33304 ** Create a mapping from variable numbers to variable names
33305 ** in the Vdbe.azVar[] array, if such a mapping does not already
33306 ** exist.
33308 static void createVarMap(Vdbe *p){
33309 if( !p->okVar ){
33310 int j;
33311 Op *pOp;
33312 for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
33313 if( pOp->opcode==OP_Variable ){
33314 assert( pOp->p1>0 && pOp->p1<=p->nVar );
33315 p->azVar[pOp->p1-1] = pOp->p3;
33318 p->okVar = 1;
33323 ** Return the name of a wildcard parameter. Return NULL if the index
33324 ** is out of range or if the wildcard is unnamed.
33326 ** The result is always UTF-8.
33328 const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
33329 Vdbe *p = (Vdbe*)pStmt;
33330 if( p==0 || i<1 || i>p->nVar ){
33331 return 0;
33333 createVarMap(p);
33334 return p->azVar[i-1];
33338 ** Given a wildcard parameter name, return the index of the variable
33339 ** with that name. If there is no variable with the given name,
33340 ** return 0.
33342 int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
33343 Vdbe *p = (Vdbe*)pStmt;
33344 int i;
33345 if( p==0 ){
33346 return 0;
33348 createVarMap(p);
33349 if( zName ){
33350 for(i=0; i<p->nVar; i++){
33351 const char *z = p->azVar[i];
33352 if( z && strcmp(z,zName)==0 ){
33353 return i+1;
33357 return 0;
33361 ** Transfer all bindings from the first statement over to the second.
33362 ** If the two statements contain a different number of bindings, then
33363 ** an SQLITE_ERROR is returned.
33365 int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
33366 Vdbe *pFrom = (Vdbe*)pFromStmt;
33367 Vdbe *pTo = (Vdbe*)pToStmt;
33368 int i, rc = SQLITE_OK;
33369 if( (pFrom->magic!=VDBE_MAGIC_RUN && pFrom->magic!=VDBE_MAGIC_HALT)
33370 || (pTo->magic!=VDBE_MAGIC_RUN && pTo->magic!=VDBE_MAGIC_HALT) ){
33371 return SQLITE_MISUSE;
33373 if( pFrom->nVar!=pTo->nVar ){
33374 return SQLITE_ERROR;
33376 for(i=0; rc==SQLITE_OK && i<pFrom->nVar; i++){
33377 sqlite3MallocDisallow();
33378 rc = sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
33379 sqlite3MallocAllow();
33381 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
33382 return rc;
33386 ** Return the sqlite3* database handle to which the prepared statement given
33387 ** in the argument belongs. This is the same database handle that was
33388 ** the first argument to the sqlite3_prepare() that was used to create
33389 ** the statement in the first place.
33391 sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
33392 return pStmt ? ((Vdbe*)pStmt)->db : 0;
33395 /************** End of vdbeapi.c *********************************************/
33396 /************** Begin file vdbe.c ********************************************/
33398 ** 2001 September 15
33400 ** The author disclaims copyright to this source code. In place of
33401 ** a legal notice, here is a blessing:
33403 ** May you do good and not evil.
33404 ** May you find forgiveness for yourself and forgive others.
33405 ** May you share freely, never taking more than you give.
33407 *************************************************************************
33408 ** The code in this file implements execution method of the
33409 ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
33410 ** handles housekeeping details such as creating and deleting
33411 ** VDBE instances. This file is solely interested in executing
33412 ** the VDBE program.
33414 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
33415 ** to a VDBE.
33417 ** The SQL parser generates a program which is then executed by
33418 ** the VDBE to do the work of the SQL statement. VDBE programs are
33419 ** similar in form to assembly language. The program consists of
33420 ** a linear sequence of operations. Each operation has an opcode
33421 ** and 3 operands. Operands P1 and P2 are integers. Operand P3
33422 ** is a null-terminated string. The P2 operand must be non-negative.
33423 ** Opcodes will typically ignore one or more operands. Many opcodes
33424 ** ignore all three operands.
33426 ** Computation results are stored on a stack. Each entry on the
33427 ** stack is either an integer, a null-terminated string, a floating point
33428 ** number, or the SQL "NULL" value. An inplicit conversion from one
33429 ** type to the other occurs as necessary.
33431 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
33432 ** function which does the work of interpreting a VDBE program.
33433 ** But other routines are also provided to help in building up
33434 ** a program instruction by instruction.
33436 ** Various scripts scan this source file in order to generate HTML
33437 ** documentation, headers files, or other derived files. The formatting
33438 ** of the code in this file is, therefore, important. See other comments
33439 ** in this file for details. If in doubt, do not deviate from existing
33440 ** commenting and indentation practices when changing or adding code.
33442 ** $Id: vdbe.c,v 1.626 2007/06/15 14:53:53 danielk1977 Exp $
33446 ** The following global variable is incremented every time a cursor
33447 ** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes. The test
33448 ** procedures use this information to make sure that indices are
33449 ** working correctly. This variable has no function other than to
33450 ** help verify the correct operation of the library.
33452 #ifdef SQLITE_TEST
33453 int sqlite3_search_count = 0;
33454 #endif
33457 ** When this global variable is positive, it gets decremented once before
33458 ** each instruction in the VDBE. When reaches zero, the u1.isInterrupted
33459 ** field of the sqlite3 structure is set in order to simulate and interrupt.
33461 ** This facility is used for testing purposes only. It does not function
33462 ** in an ordinary build.
33464 #ifdef SQLITE_TEST
33465 int sqlite3_interrupt_count = 0;
33466 #endif
33469 ** The next global variable is incremented each type the OP_Sort opcode
33470 ** is executed. The test procedures use this information to make sure that
33471 ** sorting is occurring or not occuring at appropriate times. This variable
33472 ** has no function other than to help verify the correct operation of the
33473 ** library.
33475 #ifdef SQLITE_TEST
33476 int sqlite3_sort_count = 0;
33477 #endif
33480 ** The next global variable records the size of the largest MEM_Blob
33481 ** or MEM_Str that has appeared on the VDBE stack. The test procedures
33482 ** use this information to make sure that the zero-blob functionality
33483 ** is working correctly. This variable has no function other than to
33484 ** help verify the correct operation of the library.
33486 #ifdef SQLITE_TEST
33487 int sqlite3_max_blobsize = 0;
33488 #endif
33491 ** Release the memory associated with the given stack level. This
33492 ** leaves the Mem.flags field in an inconsistent state.
33494 #define Release(P) if((P)->flags&MEM_Dyn){ sqlite3VdbeMemRelease(P); }
33497 ** Convert the given stack entity into a string if it isn't one
33498 ** already. Return non-zero if a malloc() fails.
33500 #define Stringify(P, enc) \
33501 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
33502 { goto no_mem; }
33505 ** Convert the given stack entity into a string that has been obtained
33506 ** from sqliteMalloc(). This is different from Stringify() above in that
33507 ** Stringify() will use the NBFS bytes of static string space if the string
33508 ** will fit but this routine always mallocs for space.
33509 ** Return non-zero if we run out of memory.
33511 #define Dynamicify(P,enc) sqlite3VdbeMemDynamicify(P)
33514 ** The header of a record consists of a sequence variable-length integers.
33515 ** These integers are almost always small and are encoded as a single byte.
33516 ** The following macro takes advantage this fact to provide a fast decode
33517 ** of the integers in a record header. It is faster for the common case
33518 ** where the integer is a single byte. It is a little slower when the
33519 ** integer is two or more bytes. But overall it is faster.
33521 ** The following expressions are equivalent:
33523 ** x = sqlite3GetVarint32( A, &B );
33525 ** x = GetVarint( A, B );
33528 #define GetVarint(A,B) ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B))
33531 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
33532 ** a pointer to a dynamically allocated string where some other entity
33533 ** is responsible for deallocating that string. Because the stack entry
33534 ** does not control the string, it might be deleted without the stack
33535 ** entry knowing it.
33537 ** This routine converts an ephemeral string into a dynamically allocated
33538 ** string that the stack entry itself controls. In other words, it
33539 ** converts an MEM_Ephem string into an MEM_Dyn string.
33541 #define Deephemeralize(P) \
33542 if( ((P)->flags&MEM_Ephem)!=0 \
33543 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
33546 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
33547 ** P if required.
33549 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
33552 ** Argument pMem points at a memory cell that will be passed to a
33553 ** user-defined function or returned to the user as the result of a query.
33554 ** The second argument, 'db_enc' is the text encoding used by the vdbe for
33555 ** stack variables. This routine sets the pMem->enc and pMem->type
33556 ** variables used by the sqlite3_value_*() routines.
33558 #define storeTypeInfo(A,B) _storeTypeInfo(A)
33559 static void _storeTypeInfo(Mem *pMem){
33560 int flags = pMem->flags;
33561 if( flags & MEM_Null ){
33562 pMem->type = SQLITE_NULL;
33564 else if( flags & MEM_Int ){
33565 pMem->type = SQLITE_INTEGER;
33567 else if( flags & MEM_Real ){
33568 pMem->type = SQLITE_FLOAT;
33570 else if( flags & MEM_Str ){
33571 pMem->type = SQLITE_TEXT;
33572 }else{
33573 pMem->type = SQLITE_BLOB;
33578 ** Pop the stack N times.
33580 static void popStack(Mem **ppTos, int N){
33581 Mem *pTos = *ppTos;
33582 while( N>0 ){
33583 N--;
33584 Release(pTos);
33585 pTos--;
33587 *ppTos = pTos;
33591 ** Allocate cursor number iCur. Return a pointer to it. Return NULL
33592 ** if we run out of memory.
33594 static Cursor *allocateCursor(Vdbe *p, int iCur, int iDb){
33595 Cursor *pCx;
33596 assert( iCur<p->nCursor );
33597 if( p->apCsr[iCur] ){
33598 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
33600 p->apCsr[iCur] = pCx = sqliteMalloc( sizeof(Cursor) );
33601 if( pCx ){
33602 pCx->iDb = iDb;
33604 return pCx;
33608 ** Try to convert a value into a numeric representation if we can
33609 ** do so without loss of information. In other words, if the string
33610 ** looks like a number, convert it into a number. If it does not
33611 ** look like a number, leave it alone.
33613 static void applyNumericAffinity(Mem *pRec){
33614 if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
33615 int realnum;
33616 sqlite3VdbeMemNulTerminate(pRec);
33617 if( (pRec->flags&MEM_Str)
33618 && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
33619 i64 value;
33620 sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
33621 if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
33622 sqlite3VdbeMemRelease(pRec);
33623 pRec->u.i = value;
33624 pRec->flags = MEM_Int;
33625 }else{
33626 sqlite3VdbeMemRealify(pRec);
33633 ** Processing is determine by the affinity parameter:
33635 ** SQLITE_AFF_INTEGER:
33636 ** SQLITE_AFF_REAL:
33637 ** SQLITE_AFF_NUMERIC:
33638 ** Try to convert pRec to an integer representation or a
33639 ** floating-point representation if an integer representation
33640 ** is not possible. Note that the integer representation is
33641 ** always preferred, even if the affinity is REAL, because
33642 ** an integer representation is more space efficient on disk.
33644 ** SQLITE_AFF_TEXT:
33645 ** Convert pRec to a text representation.
33647 ** SQLITE_AFF_NONE:
33648 ** No-op. pRec is unchanged.
33650 static void applyAffinity(Mem *pRec, char affinity, u8 enc){
33651 if( affinity==SQLITE_AFF_TEXT ){
33652 /* Only attempt the conversion to TEXT if there is an integer or real
33653 ** representation (blob and NULL do not get converted) but no string
33654 ** representation.
33656 if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
33657 sqlite3VdbeMemStringify(pRec, enc);
33659 pRec->flags &= ~(MEM_Real|MEM_Int);
33660 }else if( affinity!=SQLITE_AFF_NONE ){
33661 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
33662 || affinity==SQLITE_AFF_NUMERIC );
33663 applyNumericAffinity(pRec);
33664 if( pRec->flags & MEM_Real ){
33665 sqlite3VdbeIntegerAffinity(pRec);
33671 ** Try to convert the type of a function argument or a result column
33672 ** into a numeric representation. Use either INTEGER or REAL whichever
33673 ** is appropriate. But only do the conversion if it is possible without
33674 ** loss of information and return the revised type of the argument.
33676 ** This is an EXPERIMENTAL api and is subject to change or removal.
33678 int sqlite3_value_numeric_type(sqlite3_value *pVal){
33679 Mem *pMem = (Mem*)pVal;
33680 applyNumericAffinity(pMem);
33681 storeTypeInfo(pMem, 0);
33682 return pMem->type;
33686 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
33687 ** not the internal Mem* type.
33689 static void sqlite3ValueApplyAffinity(sqlite3_value *pVal, u8 affinity, u8 enc){
33690 applyAffinity((Mem *)pVal, affinity, enc);
33693 #ifdef SQLITE_DEBUG
33695 ** Write a nice string representation of the contents of cell pMem
33696 ** into buffer zBuf, length nBuf.
33698 static void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
33699 char *zCsr = zBuf;
33700 int f = pMem->flags;
33702 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
33704 if( f&MEM_Blob ){
33705 int i;
33706 char c;
33707 if( f & MEM_Dyn ){
33708 c = 'z';
33709 assert( (f & (MEM_Static|MEM_Ephem))==0 );
33710 }else if( f & MEM_Static ){
33711 c = 't';
33712 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
33713 }else if( f & MEM_Ephem ){
33714 c = 'e';
33715 assert( (f & (MEM_Static|MEM_Dyn))==0 );
33716 }else{
33717 c = 's';
33720 sqlite3_snprintf(100, zCsr, "%c", c);
33721 zCsr += strlen(zCsr);
33722 sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
33723 zCsr += strlen(zCsr);
33724 for(i=0; i<16 && i<pMem->n; i++){
33725 sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
33726 zCsr += strlen(zCsr);
33728 for(i=0; i<16 && i<pMem->n; i++){
33729 char z = pMem->z[i];
33730 if( z<32 || z>126 ) *zCsr++ = '.';
33731 else *zCsr++ = z;
33734 sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
33735 zCsr += strlen(zCsr);
33736 if( f & MEM_Zero ){
33737 sqlite3_snprintf(100, zCsr,"+%lldz",pMem->u.i);
33738 zCsr += strlen(zCsr);
33740 *zCsr = '\0';
33741 }else if( f & MEM_Str ){
33742 int j, k;
33743 zBuf[0] = ' ';
33744 if( f & MEM_Dyn ){
33745 zBuf[1] = 'z';
33746 assert( (f & (MEM_Static|MEM_Ephem))==0 );
33747 }else if( f & MEM_Static ){
33748 zBuf[1] = 't';
33749 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
33750 }else if( f & MEM_Ephem ){
33751 zBuf[1] = 'e';
33752 assert( (f & (MEM_Static|MEM_Dyn))==0 );
33753 }else{
33754 zBuf[1] = 's';
33756 k = 2;
33757 sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
33758 k += strlen(&zBuf[k]);
33759 zBuf[k++] = '[';
33760 for(j=0; j<15 && j<pMem->n; j++){
33761 u8 c = pMem->z[j];
33762 if( c>=0x20 && c<0x7f ){
33763 zBuf[k++] = c;
33764 }else{
33765 zBuf[k++] = '.';
33768 zBuf[k++] = ']';
33769 sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
33770 k += strlen(&zBuf[k]);
33771 zBuf[k++] = 0;
33774 #endif
33777 #ifdef VDBE_PROFILE
33779 ** The following routine only works on pentium-class processors.
33780 ** It uses the RDTSC opcode to read the cycle count value out of the
33781 ** processor and returns that value. This can be used for high-res
33782 ** profiling.
33784 __inline__ unsigned long long int hwtime(void){
33785 unsigned long long int x;
33786 __asm__("rdtsc\n\t"
33787 "mov %%edx, %%ecx\n\t"
33788 :"=A" (x));
33789 return x;
33791 #endif
33794 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
33795 ** sqlite3_interrupt() routine has been called. If it has been, then
33796 ** processing of the VDBE program is interrupted.
33798 ** This macro added to every instruction that does a jump in order to
33799 ** implement a loop. This test used to be on every single instruction,
33800 ** but that meant we more testing that we needed. By only testing the
33801 ** flag on jump instructions, we get a (small) speed improvement.
33803 #define CHECK_FOR_INTERRUPT \
33804 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
33808 ** Execute as much of a VDBE program as we can then return.
33810 ** sqlite3VdbeMakeReady() must be called before this routine in order to
33811 ** close the program with a final OP_Halt and to set up the callbacks
33812 ** and the error message pointer.
33814 ** Whenever a row or result data is available, this routine will either
33815 ** invoke the result callback (if there is one) or return with
33816 ** SQLITE_ROW.
33818 ** If an attempt is made to open a locked database, then this routine
33819 ** will either invoke the busy callback (if there is one) or it will
33820 ** return SQLITE_BUSY.
33822 ** If an error occurs, an error message is written to memory obtained
33823 ** from sqliteMalloc() and p->zErrMsg is made to point to that memory.
33824 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
33826 ** If the callback ever returns non-zero, then the program exits
33827 ** immediately. There will be no error message but the p->rc field is
33828 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
33830 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
33831 ** routine to return SQLITE_ERROR.
33833 ** Other fatal errors return SQLITE_ERROR.
33835 ** After this routine has finished, sqlite3VdbeFinalize() should be
33836 ** used to clean up the mess that was left behind.
33838 static int sqlite3VdbeExec(
33839 Vdbe *p /* The VDBE */
33841 int pc; /* The program counter */
33842 Op *pOp; /* Current operation */
33843 int rc = SQLITE_OK; /* Value to return */
33844 sqlite3 *db = p->db; /* The database */
33845 u8 encoding = ENC(db); /* The database encoding */
33846 Mem *pTos; /* Top entry in the operand stack */
33847 #ifdef VDBE_PROFILE
33848 unsigned long long start; /* CPU clock count at start of opcode */
33849 int origPc; /* Program counter at start of opcode */
33850 #endif
33851 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
33852 int nProgressOps = 0; /* Opcodes executed since progress callback. */
33853 #endif
33854 #ifndef NDEBUG
33855 Mem *pStackLimit;
33856 #endif
33858 if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
33859 assert( db->magic==SQLITE_MAGIC_BUSY );
33860 pTos = p->pTos;
33861 if( p->rc==SQLITE_NOMEM ){
33862 /* This happens if a malloc() inside a call to sqlite3_column_text() or
33863 ** sqlite3_column_text16() failed. */
33864 goto no_mem;
33866 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
33867 p->rc = SQLITE_OK;
33868 assert( p->explain==0 );
33869 if( p->popStack ){
33870 popStack(&pTos, p->popStack);
33871 p->popStack = 0;
33873 p->resOnStack = 0;
33874 db->busyHandler.nBusy = 0;
33875 CHECK_FOR_INTERRUPT;
33876 sqlite3VdbeIOTraceSql(p);
33877 #ifdef SQLITE_DEBUG
33878 if( (p->db->flags & SQLITE_VdbeListing)!=0
33879 || sqlite3OsFileExists("vdbe_explain")
33881 int i;
33882 printf("VDBE Program Listing:\n");
33883 sqlite3VdbePrintSql(p);
33884 for(i=0; i<p->nOp; i++){
33885 sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
33888 if( sqlite3OsFileExists("vdbe_trace") ){
33889 p->trace = stdout;
33891 #endif
33892 for(pc=p->pc; rc==SQLITE_OK; pc++){
33893 assert( pc>=0 && pc<p->nOp );
33894 assert( pTos<=&p->aStack[pc] );
33895 if( sqlite3MallocFailed() ) goto no_mem;
33896 #ifdef VDBE_PROFILE
33897 origPc = pc;
33898 start = hwtime();
33899 #endif
33900 pOp = &p->aOp[pc];
33902 /* Only allow tracing if SQLITE_DEBUG is defined.
33904 #ifdef SQLITE_DEBUG
33905 if( p->trace ){
33906 if( pc==0 ){
33907 printf("VDBE Execution Trace:\n");
33908 sqlite3VdbePrintSql(p);
33910 sqlite3VdbePrintOp(p->trace, pc, pOp);
33912 if( p->trace==0 && pc==0 && sqlite3OsFileExists("vdbe_sqltrace") ){
33913 sqlite3VdbePrintSql(p);
33915 #endif
33918 /* Check to see if we need to simulate an interrupt. This only happens
33919 ** if we have a special test build.
33921 #ifdef SQLITE_TEST
33922 if( sqlite3_interrupt_count>0 ){
33923 sqlite3_interrupt_count--;
33924 if( sqlite3_interrupt_count==0 ){
33925 sqlite3_interrupt(db);
33928 #endif
33930 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
33931 /* Call the progress callback if it is configured and the required number
33932 ** of VDBE ops have been executed (either since this invocation of
33933 ** sqlite3VdbeExec() or since last time the progress callback was called).
33934 ** If the progress callback returns non-zero, exit the virtual machine with
33935 ** a return code SQLITE_ABORT.
33937 if( db->xProgress ){
33938 if( db->nProgressOps==nProgressOps ){
33939 int prc;
33940 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
33941 prc =db->xProgress(db->pProgressArg);
33942 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
33943 if( prc!=0 ){
33944 rc = SQLITE_INTERRUPT;
33945 goto vdbe_halt;
33947 nProgressOps = 0;
33949 nProgressOps++;
33951 #endif
33953 #ifndef NDEBUG
33954 /* This is to check that the return value of static function
33955 ** opcodeNoPush() (see vdbeaux.c) returns values that match the
33956 ** implementation of the virtual machine in this file. If
33957 ** opcodeNoPush() returns non-zero, then the stack is guarenteed
33958 ** not to grow when the opcode is executed. If it returns zero, then
33959 ** the stack may grow by at most 1.
33961 ** The global wrapper function sqlite3VdbeOpcodeUsesStack() is not
33962 ** available if NDEBUG is defined at build time.
33964 pStackLimit = pTos;
33965 if( !sqlite3VdbeOpcodeNoPush(pOp->opcode) ){
33966 pStackLimit++;
33968 #endif
33970 switch( pOp->opcode ){
33972 /*****************************************************************************
33973 ** What follows is a massive switch statement where each case implements a
33974 ** separate instruction in the virtual machine. If we follow the usual
33975 ** indentation conventions, each case should be indented by 6 spaces. But
33976 ** that is a lot of wasted space on the left margin. So the code within
33977 ** the switch statement will break with convention and be flush-left. Another
33978 ** big comment (similar to this one) will mark the point in the code where
33979 ** we transition back to normal indentation.
33981 ** The formatting of each case is important. The makefile for SQLite
33982 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
33983 ** file looking for lines that begin with "case OP_". The opcodes.h files
33984 ** will be filled with #defines that give unique integer values to each
33985 ** opcode and the opcodes.c file is filled with an array of strings where
33986 ** each string is the symbolic name for the corresponding opcode. If the
33987 ** case statement is followed by a comment of the form "/# same as ... #/"
33988 ** that comment is used to determine the particular value of the opcode.
33990 ** If a comment on the same line as the "case OP_" construction contains
33991 ** the word "no-push", then the opcode is guarenteed not to grow the
33992 ** vdbe stack when it is executed. See function opcode() in
33993 ** vdbeaux.c for details.
33995 ** Documentation about VDBE opcodes is generated by scanning this file
33996 ** for lines of that contain "Opcode:". That line and all subsequent
33997 ** comment lines are used in the generation of the opcode.html documentation
33998 ** file.
34000 ** SUMMARY:
34002 ** Formatting is important to scripts that scan this file.
34003 ** Do not deviate from the formatting style currently in use.
34005 *****************************************************************************/
34007 /* Opcode: Goto * P2 *
34009 ** An unconditional jump to address P2.
34010 ** The next instruction executed will be
34011 ** the one at index P2 from the beginning of
34012 ** the program.
34014 case OP_Goto: { /* no-push */
34015 CHECK_FOR_INTERRUPT;
34016 pc = pOp->p2 - 1;
34017 break;
34020 /* Opcode: Gosub * P2 *
34022 ** Push the current address plus 1 onto the return address stack
34023 ** and then jump to address P2.
34025 ** The return address stack is of limited depth. If too many
34026 ** OP_Gosub operations occur without intervening OP_Returns, then
34027 ** the return address stack will fill up and processing will abort
34028 ** with a fatal error.
34030 case OP_Gosub: { /* no-push */
34031 assert( p->returnDepth<sizeof(p->returnStack)/sizeof(p->returnStack[0]) );
34032 p->returnStack[p->returnDepth++] = pc+1;
34033 pc = pOp->p2 - 1;
34034 break;
34037 /* Opcode: Return * * *
34039 ** Jump immediately to the next instruction after the last unreturned
34040 ** OP_Gosub. If an OP_Return has occurred for all OP_Gosubs, then
34041 ** processing aborts with a fatal error.
34043 case OP_Return: { /* no-push */
34044 assert( p->returnDepth>0 );
34045 p->returnDepth--;
34046 pc = p->returnStack[p->returnDepth] - 1;
34047 break;
34050 /* Opcode: Halt P1 P2 P3
34052 ** Exit immediately. All open cursors, Fifos, etc are closed
34053 ** automatically.
34055 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
34056 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
34057 ** For errors, it can be some other value. If P1!=0 then P2 will determine
34058 ** whether or not to rollback the current transaction. Do not rollback
34059 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
34060 ** then back out all changes that have occurred during this execution of the
34061 ** VDBE, but do not rollback the transaction.
34063 ** If P3 is not null then it is an error message string.
34065 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
34066 ** every program. So a jump past the last instruction of the program
34067 ** is the same as executing Halt.
34069 case OP_Halt: { /* no-push */
34070 p->pTos = pTos;
34071 p->rc = pOp->p1;
34072 p->pc = pc;
34073 p->errorAction = pOp->p2;
34074 if( pOp->p3 ){
34075 sqlite3SetString(&p->zErrMsg, pOp->p3, (char*)0);
34077 rc = sqlite3VdbeHalt(p);
34078 assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
34079 if( rc==SQLITE_BUSY ){
34080 p->rc = SQLITE_BUSY;
34081 return SQLITE_BUSY;
34083 return p->rc ? SQLITE_ERROR : SQLITE_DONE;
34086 /* Opcode: Integer P1 * *
34088 ** The 32-bit integer value P1 is pushed onto the stack.
34090 case OP_Integer: {
34091 pTos++;
34092 pTos->flags = MEM_Int;
34093 pTos->u.i = pOp->p1;
34094 break;
34097 /* Opcode: Int64 * * P3
34099 ** P3 is a string representation of an integer. Convert that integer
34100 ** to a 64-bit value and push it onto the stack.
34102 case OP_Int64: {
34103 pTos++;
34104 assert( pOp->p3!=0 );
34105 pTos->flags = MEM_Str|MEM_Static|MEM_Term;
34106 pTos->z = pOp->p3;
34107 pTos->n = strlen(pTos->z);
34108 pTos->enc = SQLITE_UTF8;
34109 pTos->u.i = sqlite3VdbeIntValue(pTos);
34110 pTos->flags |= MEM_Int;
34111 break;
34114 /* Opcode: Real * * P3
34116 ** The string value P3 is converted to a real and pushed on to the stack.
34118 case OP_Real: { /* same as TK_FLOAT, */
34119 pTos++;
34120 pTos->flags = MEM_Str|MEM_Static|MEM_Term;
34121 pTos->z = pOp->p3;
34122 pTos->n = strlen(pTos->z);
34123 pTos->enc = SQLITE_UTF8;
34124 pTos->r = sqlite3VdbeRealValue(pTos);
34125 pTos->flags |= MEM_Real;
34126 sqlite3VdbeChangeEncoding(pTos, encoding);
34127 break;
34130 /* Opcode: String8 * * P3
34132 ** P3 points to a nul terminated UTF-8 string. This opcode is transformed
34133 ** into an OP_String before it is executed for the first time.
34135 case OP_String8: { /* same as TK_STRING */
34136 assert( pOp->p3!=0 );
34137 pOp->opcode = OP_String;
34138 pOp->p1 = strlen(pOp->p3);
34139 assert( SQLITE_MAX_SQL_LENGTH < SQLITE_MAX_LENGTH );
34140 assert( pOp->p1 < SQLITE_MAX_LENGTH );
34142 #ifndef SQLITE_OMIT_UTF16
34143 if( encoding!=SQLITE_UTF8 ){
34144 pTos++;
34145 sqlite3VdbeMemSetStr(pTos, pOp->p3, -1, SQLITE_UTF8, SQLITE_STATIC);
34146 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pTos, encoding) ) goto no_mem;
34147 if( SQLITE_OK!=sqlite3VdbeMemDynamicify(pTos) ) goto no_mem;
34148 pTos->flags &= ~(MEM_Dyn);
34149 pTos->flags |= MEM_Static;
34150 if( pOp->p3type==P3_DYNAMIC ){
34151 sqliteFree(pOp->p3);
34153 pOp->p3type = P3_DYNAMIC;
34154 pOp->p3 = pTos->z;
34155 pOp->p1 = pTos->n;
34156 assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
34157 break;
34159 #endif
34160 /* Otherwise fall through to the next case, OP_String */
34163 /* Opcode: String P1 * P3
34165 ** The string value P3 of length P1 (bytes) is pushed onto the stack.
34167 case OP_String: {
34168 assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
34169 pTos++;
34170 assert( pOp->p3!=0 );
34171 pTos->flags = MEM_Str|MEM_Static|MEM_Term;
34172 pTos->z = pOp->p3;
34173 pTos->n = pOp->p1;
34174 pTos->enc = encoding;
34175 break;
34178 /* Opcode: Null * * *
34180 ** Push a NULL onto the stack.
34182 case OP_Null: {
34183 pTos++;
34184 pTos->flags = MEM_Null;
34185 pTos->n = 0;
34186 break;
34190 #ifndef SQLITE_OMIT_BLOB_LITERAL
34191 /* Opcode: HexBlob * * P3
34193 ** P3 is an UTF-8 SQL hex encoding of a blob. The blob is pushed onto the
34194 ** vdbe stack.
34196 ** The first time this instruction executes, in transforms itself into a
34197 ** 'Blob' opcode with a binary blob as P3.
34199 case OP_HexBlob: { /* same as TK_BLOB */
34200 pOp->opcode = OP_Blob;
34201 pOp->p1 = strlen(pOp->p3)/2;
34202 assert( SQLITE_MAX_SQL_LENGTH < SQLITE_MAX_LENGTH );
34203 assert( pOp->p1 < SQLITE_MAX_LENGTH );
34204 if( pOp->p1 ){
34205 char *zBlob = sqlite3HexToBlob(pOp->p3);
34206 if( !zBlob ) goto no_mem;
34207 if( pOp->p3type==P3_DYNAMIC ){
34208 sqliteFree(pOp->p3);
34210 pOp->p3 = zBlob;
34211 pOp->p3type = P3_DYNAMIC;
34212 }else{
34213 if( pOp->p3type==P3_DYNAMIC ){
34214 sqliteFree(pOp->p3);
34216 pOp->p3type = P3_STATIC;
34217 pOp->p3 = "";
34220 /* Fall through to the next case, OP_Blob. */
34223 /* Opcode: Blob P1 * P3
34225 ** P3 points to a blob of data P1 bytes long. Push this
34226 ** value onto the stack. This instruction is not coded directly
34227 ** by the compiler. Instead, the compiler layer specifies
34228 ** an OP_HexBlob opcode, with the hex string representation of
34229 ** the blob as P3. This opcode is transformed to an OP_Blob
34230 ** the first time it is executed.
34232 case OP_Blob: {
34233 pTos++;
34234 assert( pOp->p1 < SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */
34235 sqlite3VdbeMemSetStr(pTos, pOp->p3, pOp->p1, 0, 0);
34236 pTos->enc = encoding;
34237 break;
34239 #endif /* SQLITE_OMIT_BLOB_LITERAL */
34241 /* Opcode: Variable P1 * *
34243 ** Push the value of variable P1 onto the stack. A variable is
34244 ** an unknown in the original SQL string as handed to sqlite3_compile().
34245 ** Any occurance of the '?' character in the original SQL is considered
34246 ** a variable. Variables in the SQL string are number from left to
34247 ** right beginning with 1. The values of variables are set using the
34248 ** sqlite3_bind() API.
34250 case OP_Variable: {
34251 int j = pOp->p1 - 1;
34252 Mem *pVar;
34253 assert( j>=0 && j<p->nVar );
34255 pVar = &p->aVar[j];
34256 if( sqlite3VdbeMemTooBig(pVar) ){
34257 goto too_big;
34259 pTos++;
34260 sqlite3VdbeMemShallowCopy(pTos, &p->aVar[j], MEM_Static);
34261 break;
34264 /* Opcode: Pop P1 * *
34266 ** P1 elements are popped off of the top of stack and discarded.
34268 case OP_Pop: { /* no-push */
34269 assert( pOp->p1>=0 );
34270 popStack(&pTos, pOp->p1);
34271 assert( pTos>=&p->aStack[-1] );
34272 break;
34275 /* Opcode: Dup P1 P2 *
34277 ** A copy of the P1-th element of the stack
34278 ** is made and pushed onto the top of the stack.
34279 ** The top of the stack is element 0. So the
34280 ** instruction "Dup 0 0 0" will make a copy of the
34281 ** top of the stack.
34283 ** If the content of the P1-th element is a dynamically
34284 ** allocated string, then a new copy of that string
34285 ** is made if P2==0. If P2!=0, then just a pointer
34286 ** to the string is copied.
34288 ** Also see the Pull instruction.
34290 case OP_Dup: {
34291 Mem *pFrom = &pTos[-pOp->p1];
34292 assert( pFrom<=pTos && pFrom>=p->aStack );
34293 pTos++;
34294 sqlite3VdbeMemShallowCopy(pTos, pFrom, MEM_Ephem);
34295 if( pOp->p2 ){
34296 Deephemeralize(pTos);
34298 break;
34301 /* Opcode: Pull P1 * *
34303 ** The P1-th element is removed from its current location on
34304 ** the stack and pushed back on top of the stack. The
34305 ** top of the stack is element 0, so "Pull 0 0 0" is
34306 ** a no-op. "Pull 1 0 0" swaps the top two elements of
34307 ** the stack.
34309 ** See also the Dup instruction.
34311 case OP_Pull: { /* no-push */
34312 Mem *pFrom = &pTos[-pOp->p1];
34313 int i;
34314 Mem ts;
34316 ts = *pFrom;
34317 Deephemeralize(pTos);
34318 for(i=0; i<pOp->p1; i++, pFrom++){
34319 Deephemeralize(&pFrom[1]);
34320 assert( (pFrom[1].flags & MEM_Ephem)==0 );
34321 *pFrom = pFrom[1];
34322 if( pFrom->flags & MEM_Short ){
34323 assert( pFrom->flags & (MEM_Str|MEM_Blob) );
34324 assert( pFrom->z==pFrom[1].zShort );
34325 pFrom->z = pFrom->zShort;
34328 *pTos = ts;
34329 if( pTos->flags & MEM_Short ){
34330 assert( pTos->flags & (MEM_Str|MEM_Blob) );
34331 assert( pTos->z==pTos[-pOp->p1].zShort );
34332 pTos->z = pTos->zShort;
34334 break;
34337 /* Opcode: Push P1 * *
34339 ** Overwrite the value of the P1-th element down on the
34340 ** stack (P1==0 is the top of the stack) with the value
34341 ** of the top of the stack. Then pop the top of the stack.
34343 case OP_Push: { /* no-push */
34344 Mem *pTo = &pTos[-pOp->p1];
34346 assert( pTo>=p->aStack );
34347 sqlite3VdbeMemMove(pTo, pTos);
34348 pTos--;
34349 break;
34352 /* Opcode: Callback P1 * *
34354 ** The top P1 values on the stack represent a single result row from
34355 ** a query. This opcode causes the sqlite3_step() call to terminate
34356 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
34357 ** structure to provide access to the top P1 values as the result
34358 ** row. When the sqlite3_step() function is run again, the top P1
34359 ** values will be automatically popped from the stack before the next
34360 ** instruction executes.
34362 case OP_Callback: { /* no-push */
34363 Mem *pMem;
34364 Mem *pFirstColumn;
34365 assert( p->nResColumn==pOp->p1 );
34367 /* Data in the pager might be moved or changed out from under us
34368 ** in between the return from this sqlite3_step() call and the
34369 ** next call to sqlite3_step(). So deephermeralize everything on
34370 ** the stack. Note that ephemeral data is never stored in memory
34371 ** cells so we do not have to worry about them.
34373 pFirstColumn = &pTos[0-pOp->p1];
34374 for(pMem = p->aStack; pMem<pFirstColumn; pMem++){
34375 Deephemeralize(pMem);
34378 /* Invalidate all ephemeral cursor row caches */
34379 p->cacheCtr = (p->cacheCtr + 2)|1;
34381 /* Make sure the results of the current row are \000 terminated
34382 ** and have an assigned type. The results are deephemeralized as
34383 ** as side effect.
34385 for(; pMem<=pTos; pMem++ ){
34386 sqlite3VdbeMemNulTerminate(pMem);
34387 storeTypeInfo(pMem, encoding);
34390 /* Set up the statement structure so that it will pop the current
34391 ** results from the stack when the statement returns.
34393 p->resOnStack = 1;
34394 p->nCallback++;
34395 p->popStack = pOp->p1;
34396 p->pc = pc + 1;
34397 p->pTos = pTos;
34398 return SQLITE_ROW;
34401 /* Opcode: Concat P1 P2 *
34403 ** Look at the first P1+2 elements of the stack. Append them all
34404 ** together with the lowest element first. The original P1+2 elements
34405 ** are popped from the stack if P2==0 and retained if P2==1. If
34406 ** any element of the stack is NULL, then the result is NULL.
34408 ** When P1==1, this routine makes a copy of the top stack element
34409 ** into memory obtained from sqliteMalloc().
34411 case OP_Concat: { /* same as TK_CONCAT */
34412 char *zNew;
34413 i64 nByte;
34414 int nField;
34415 int i, j;
34416 Mem *pTerm;
34418 /* Loop through the stack elements to see how long the result will be. */
34419 nField = pOp->p1 + 2;
34420 pTerm = &pTos[1-nField];
34421 nByte = 0;
34422 for(i=0; i<nField; i++, pTerm++){
34423 assert( pOp->p2==0 || (pTerm->flags&MEM_Str) );
34424 if( pTerm->flags&MEM_Null ){
34425 nByte = -1;
34426 break;
34428 ExpandBlob(pTerm);
34429 Stringify(pTerm, encoding);
34430 nByte += pTerm->n;
34433 if( nByte<0 ){
34434 /* If nByte is less than zero, then there is a NULL value on the stack.
34435 ** In this case just pop the values off the stack (if required) and
34436 ** push on a NULL.
34438 if( pOp->p2==0 ){
34439 popStack(&pTos, nField);
34441 pTos++;
34442 pTos->flags = MEM_Null;
34443 }else{
34444 /* Otherwise malloc() space for the result and concatenate all the
34445 ** stack values.
34447 if( nByte+2>SQLITE_MAX_LENGTH ){
34448 goto too_big;
34450 zNew = sqliteMallocRaw( nByte+2 );
34451 if( zNew==0 ) goto no_mem;
34452 j = 0;
34453 pTerm = &pTos[1-nField];
34454 for(i=j=0; i<nField; i++, pTerm++){
34455 int n = pTerm->n;
34456 assert( pTerm->flags & (MEM_Str|MEM_Blob) );
34457 memcpy(&zNew[j], pTerm->z, n);
34458 j += n;
34460 zNew[j] = 0;
34461 zNew[j+1] = 0;
34462 assert( j==nByte );
34464 if( pOp->p2==0 ){
34465 popStack(&pTos, nField);
34467 pTos++;
34468 pTos->n = j;
34469 pTos->flags = MEM_Str|MEM_Dyn|MEM_Term;
34470 pTos->xDel = 0;
34471 pTos->enc = encoding;
34472 pTos->z = zNew;
34474 break;
34477 /* Opcode: Add * * *
34479 ** Pop the top two elements from the stack, add them together,
34480 ** and push the result back onto the stack. If either element
34481 ** is a string then it is converted to a double using the atof()
34482 ** function before the addition.
34483 ** If either operand is NULL, the result is NULL.
34485 /* Opcode: Multiply * * *
34487 ** Pop the top two elements from the stack, multiply them together,
34488 ** and push the result back onto the stack. If either element
34489 ** is a string then it is converted to a double using the atof()
34490 ** function before the multiplication.
34491 ** If either operand is NULL, the result is NULL.
34493 /* Opcode: Subtract * * *
34495 ** Pop the top two elements from the stack, subtract the
34496 ** first (what was on top of the stack) from the second (the
34497 ** next on stack)
34498 ** and push the result back onto the stack. If either element
34499 ** is a string then it is converted to a double using the atof()
34500 ** function before the subtraction.
34501 ** If either operand is NULL, the result is NULL.
34503 /* Opcode: Divide * * *
34505 ** Pop the top two elements from the stack, divide the
34506 ** first (what was on top of the stack) from the second (the
34507 ** next on stack)
34508 ** and push the result back onto the stack. If either element
34509 ** is a string then it is converted to a double using the atof()
34510 ** function before the division. Division by zero returns NULL.
34511 ** If either operand is NULL, the result is NULL.
34513 /* Opcode: Remainder * * *
34515 ** Pop the top two elements from the stack, divide the
34516 ** first (what was on top of the stack) from the second (the
34517 ** next on stack)
34518 ** and push the remainder after division onto the stack. If either element
34519 ** is a string then it is converted to a double using the atof()
34520 ** function before the division. Division by zero returns NULL.
34521 ** If either operand is NULL, the result is NULL.
34523 case OP_Add: /* same as TK_PLUS, no-push */
34524 case OP_Subtract: /* same as TK_MINUS, no-push */
34525 case OP_Multiply: /* same as TK_STAR, no-push */
34526 case OP_Divide: /* same as TK_SLASH, no-push */
34527 case OP_Remainder: { /* same as TK_REM, no-push */
34528 Mem *pNos = &pTos[-1];
34529 int flags;
34530 assert( pNos>=p->aStack );
34531 flags = pTos->flags | pNos->flags;
34532 if( (flags & MEM_Null)!=0 ){
34533 Release(pTos);
34534 pTos--;
34535 Release(pTos);
34536 pTos->flags = MEM_Null;
34537 }else if( (pTos->flags & pNos->flags & MEM_Int)==MEM_Int ){
34538 i64 a, b;
34539 a = pTos->u.i;
34540 b = pNos->u.i;
34541 switch( pOp->opcode ){
34542 case OP_Add: b += a; break;
34543 case OP_Subtract: b -= a; break;
34544 case OP_Multiply: b *= a; break;
34545 case OP_Divide: {
34546 if( a==0 ) goto divide_by_zero;
34547 b /= a;
34548 break;
34550 default: {
34551 if( a==0 ) goto divide_by_zero;
34552 b %= a;
34553 break;
34556 Release(pTos);
34557 pTos--;
34558 Release(pTos);
34559 pTos->u.i = b;
34560 pTos->flags = MEM_Int;
34561 }else{
34562 double a, b;
34563 a = sqlite3VdbeRealValue(pTos);
34564 b = sqlite3VdbeRealValue(pNos);
34565 switch( pOp->opcode ){
34566 case OP_Add: b += a; break;
34567 case OP_Subtract: b -= a; break;
34568 case OP_Multiply: b *= a; break;
34569 case OP_Divide: {
34570 if( a==0.0 ) goto divide_by_zero;
34571 b /= a;
34572 break;
34574 default: {
34575 i64 ia = (i64)a;
34576 i64 ib = (i64)b;
34577 if( ia==0 ) goto divide_by_zero;
34578 b = ib % ia;
34579 break;
34582 if( isnan(b) ){
34583 goto divide_by_zero;
34585 Release(pTos);
34586 pTos--;
34587 Release(pTos);
34588 pTos->r = b;
34589 pTos->flags = MEM_Real;
34590 if( (flags & MEM_Real)==0 ){
34591 sqlite3VdbeIntegerAffinity(pTos);
34594 break;
34596 divide_by_zero:
34597 Release(pTos);
34598 pTos--;
34599 Release(pTos);
34600 pTos->flags = MEM_Null;
34601 break;
34604 /* Opcode: CollSeq * * P3
34606 ** P3 is a pointer to a CollSeq struct. If the next call to a user function
34607 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
34608 ** be returned. This is used by the built-in min(), max() and nullif()
34609 ** functions.
34611 ** The interface used by the implementation of the aforementioned functions
34612 ** to retrieve the collation sequence set by this opcode is not available
34613 ** publicly, only to user functions defined in func.c.
34615 case OP_CollSeq: { /* no-push */
34616 assert( pOp->p3type==P3_COLLSEQ );
34617 break;
34620 /* Opcode: Function P1 P2 P3
34622 ** Invoke a user function (P3 is a pointer to a Function structure that
34623 ** defines the function) with P2 arguments taken from the stack. Pop all
34624 ** arguments from the stack and push back the result.
34626 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
34627 ** function was determined to be constant at compile time. If the first
34628 ** argument was constant then bit 0 of P1 is set. This is used to determine
34629 ** whether meta data associated with a user function argument using the
34630 ** sqlite3_set_auxdata() API may be safely retained until the next
34631 ** invocation of this opcode.
34633 ** See also: AggStep and AggFinal
34635 case OP_Function: {
34636 int i;
34637 Mem *pArg;
34638 sqlite3_context ctx;
34639 sqlite3_value **apVal;
34640 int n = pOp->p2;
34642 apVal = p->apArg;
34643 assert( apVal || n==0 );
34645 pArg = &pTos[1-n];
34646 for(i=0; i<n; i++, pArg++){
34647 apVal[i] = pArg;
34648 storeTypeInfo(pArg, encoding);
34651 assert( pOp->p3type==P3_FUNCDEF || pOp->p3type==P3_VDBEFUNC );
34652 if( pOp->p3type==P3_FUNCDEF ){
34653 ctx.pFunc = (FuncDef*)pOp->p3;
34654 ctx.pVdbeFunc = 0;
34655 }else{
34656 ctx.pVdbeFunc = (VdbeFunc*)pOp->p3;
34657 ctx.pFunc = ctx.pVdbeFunc->pFunc;
34660 ctx.s.flags = MEM_Null;
34661 ctx.s.z = 0;
34662 ctx.s.xDel = 0;
34663 ctx.isError = 0;
34664 if( ctx.pFunc->needCollSeq ){
34665 assert( pOp>p->aOp );
34666 assert( pOp[-1].p3type==P3_COLLSEQ );
34667 assert( pOp[-1].opcode==OP_CollSeq );
34668 ctx.pColl = (CollSeq *)pOp[-1].p3;
34670 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
34671 (*ctx.pFunc->xFunc)(&ctx, n, apVal);
34672 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
34673 if( sqlite3MallocFailed() ) goto no_mem;
34674 popStack(&pTos, n);
34676 /* If any auxilary data functions have been called by this user function,
34677 ** immediately call the destructor for any non-static values.
34679 if( ctx.pVdbeFunc ){
34680 sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
34681 pOp->p3 = (char *)ctx.pVdbeFunc;
34682 pOp->p3type = P3_VDBEFUNC;
34685 /* If the function returned an error, throw an exception */
34686 if( ctx.isError ){
34687 sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
34688 rc = SQLITE_ERROR;
34691 /* Copy the result of the function to the top of the stack */
34692 sqlite3VdbeChangeEncoding(&ctx.s, encoding);
34693 pTos++;
34694 pTos->flags = 0;
34695 sqlite3VdbeMemMove(pTos, &ctx.s);
34696 if( sqlite3VdbeMemTooBig(pTos) ){
34697 goto too_big;
34699 break;
34702 /* Opcode: BitAnd * * *
34704 ** Pop the top two elements from the stack. Convert both elements
34705 ** to integers. Push back onto the stack the bit-wise AND of the
34706 ** two elements.
34707 ** If either operand is NULL, the result is NULL.
34709 /* Opcode: BitOr * * *
34711 ** Pop the top two elements from the stack. Convert both elements
34712 ** to integers. Push back onto the stack the bit-wise OR of the
34713 ** two elements.
34714 ** If either operand is NULL, the result is NULL.
34716 /* Opcode: ShiftLeft * * *
34718 ** Pop the top two elements from the stack. Convert both elements
34719 ** to integers. Push back onto the stack the second element shifted
34720 ** left by N bits where N is the top element on the stack.
34721 ** If either operand is NULL, the result is NULL.
34723 /* Opcode: ShiftRight * * *
34725 ** Pop the top two elements from the stack. Convert both elements
34726 ** to integers. Push back onto the stack the second element shifted
34727 ** right by N bits where N is the top element on the stack.
34728 ** If either operand is NULL, the result is NULL.
34730 case OP_BitAnd: /* same as TK_BITAND, no-push */
34731 case OP_BitOr: /* same as TK_BITOR, no-push */
34732 case OP_ShiftLeft: /* same as TK_LSHIFT, no-push */
34733 case OP_ShiftRight: { /* same as TK_RSHIFT, no-push */
34734 Mem *pNos = &pTos[-1];
34735 i64 a, b;
34737 assert( pNos>=p->aStack );
34738 if( (pTos->flags | pNos->flags) & MEM_Null ){
34739 popStack(&pTos, 2);
34740 pTos++;
34741 pTos->flags = MEM_Null;
34742 break;
34744 a = sqlite3VdbeIntValue(pNos);
34745 b = sqlite3VdbeIntValue(pTos);
34746 switch( pOp->opcode ){
34747 case OP_BitAnd: a &= b; break;
34748 case OP_BitOr: a |= b; break;
34749 case OP_ShiftLeft: a <<= b; break;
34750 case OP_ShiftRight: a >>= b; break;
34751 default: /* CANT HAPPEN */ break;
34753 Release(pTos);
34754 pTos--;
34755 Release(pTos);
34756 pTos->u.i = a;
34757 pTos->flags = MEM_Int;
34758 break;
34761 /* Opcode: AddImm P1 * *
34763 ** Add the value P1 to whatever is on top of the stack. The result
34764 ** is always an integer.
34766 ** To force the top of the stack to be an integer, just add 0.
34768 case OP_AddImm: { /* no-push */
34769 assert( pTos>=p->aStack );
34770 sqlite3VdbeMemIntegerify(pTos);
34771 pTos->u.i += pOp->p1;
34772 break;
34775 /* Opcode: ForceInt P1 P2 *
34777 ** Convert the top of the stack into an integer. If the current top of
34778 ** the stack is not numeric (meaning that is is a NULL or a string that
34779 ** does not look like an integer or floating point number) then pop the
34780 ** stack and jump to P2. If the top of the stack is numeric then
34781 ** convert it into the least integer that is greater than or equal to its
34782 ** current value if P1==0, or to the least integer that is strictly
34783 ** greater than its current value if P1==1.
34785 case OP_ForceInt: { /* no-push */
34786 i64 v;
34787 assert( pTos>=p->aStack );
34788 applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
34789 if( (pTos->flags & (MEM_Int|MEM_Real))==0 ){
34790 Release(pTos);
34791 pTos--;
34792 pc = pOp->p2 - 1;
34793 break;
34795 if( pTos->flags & MEM_Int ){
34796 v = pTos->u.i + (pOp->p1!=0);
34797 }else{
34798 /* FIX ME: should this not be assert( pTos->flags & MEM_Real ) ??? */
34799 sqlite3VdbeMemRealify(pTos);
34800 v = (int)pTos->r;
34801 if( pTos->r>(double)v ) v++;
34802 if( pOp->p1 && pTos->r==(double)v ) v++;
34804 Release(pTos);
34805 pTos->u.i = v;
34806 pTos->flags = MEM_Int;
34807 break;
34810 /* Opcode: MustBeInt P1 P2 *
34812 ** Force the top of the stack to be an integer. If the top of the
34813 ** stack is not an integer and cannot be converted into an integer
34814 ** with out data loss, then jump immediately to P2, or if P2==0
34815 ** raise an SQLITE_MISMATCH exception.
34817 ** If the top of the stack is not an integer and P2 is not zero and
34818 ** P1 is 1, then the stack is popped. In all other cases, the depth
34819 ** of the stack is unchanged.
34821 case OP_MustBeInt: { /* no-push */
34822 assert( pTos>=p->aStack );
34823 applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding);
34824 if( (pTos->flags & MEM_Int)==0 ){
34825 if( pOp->p2==0 ){
34826 rc = SQLITE_MISMATCH;
34827 goto abort_due_to_error;
34828 }else{
34829 if( pOp->p1 ) popStack(&pTos, 1);
34830 pc = pOp->p2 - 1;
34832 }else{
34833 Release(pTos);
34834 pTos->flags = MEM_Int;
34836 break;
34839 /* Opcode: RealAffinity * * *
34841 ** If the top of the stack is an integer, convert it to a real value.
34843 ** This opcode is used when extracting information from a column that
34844 ** has REAL affinity. Such column values may still be stored as
34845 ** integers, for space efficiency, but after extraction we want them
34846 ** to have only a real value.
34848 case OP_RealAffinity: { /* no-push */
34849 assert( pTos>=p->aStack );
34850 if( pTos->flags & MEM_Int ){
34851 sqlite3VdbeMemRealify(pTos);
34853 break;
34856 #ifndef SQLITE_OMIT_CAST
34857 /* Opcode: ToText * * *
34859 ** Force the value on the top of the stack to be text.
34860 ** If the value is numeric, convert it to a string using the
34861 ** equivalent of printf(). Blob values are unchanged and
34862 ** are afterwards simply interpreted as text.
34864 ** A NULL value is not changed by this routine. It remains NULL.
34866 case OP_ToText: { /* same as TK_TO_TEXT, no-push */
34867 assert( pTos>=p->aStack );
34868 if( pTos->flags & MEM_Null ) break;
34869 assert( MEM_Str==(MEM_Blob>>3) );
34870 pTos->flags |= (pTos->flags&MEM_Blob)>>3;
34871 applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
34872 rc = ExpandBlob(pTos);
34873 assert( pTos->flags & MEM_Str );
34874 pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
34875 break;
34878 /* Opcode: ToBlob * * *
34880 ** Force the value on the top of the stack to be a BLOB.
34881 ** If the value is numeric, convert it to a string first.
34882 ** Strings are simply reinterpreted as blobs with no change
34883 ** to the underlying data.
34885 ** A NULL value is not changed by this routine. It remains NULL.
34887 case OP_ToBlob: { /* same as TK_TO_BLOB, no-push */
34888 assert( pTos>=p->aStack );
34889 if( pTos->flags & MEM_Null ) break;
34890 if( (pTos->flags & MEM_Blob)==0 ){
34891 applyAffinity(pTos, SQLITE_AFF_TEXT, encoding);
34892 assert( pTos->flags & MEM_Str );
34893 pTos->flags |= MEM_Blob;
34895 pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Str);
34896 break;
34899 /* Opcode: ToNumeric * * *
34901 ** Force the value on the top of the stack to be numeric (either an
34902 ** integer or a floating-point number.)
34903 ** If the value is text or blob, try to convert it to an using the
34904 ** equivalent of atoi() or atof() and store 0 if no such conversion
34905 ** is possible.
34907 ** A NULL value is not changed by this routine. It remains NULL.
34909 case OP_ToNumeric: { /* same as TK_TO_NUMERIC, no-push */
34910 assert( pTos>=p->aStack );
34911 if( (pTos->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
34912 sqlite3VdbeMemNumerify(pTos);
34914 break;
34916 #endif /* SQLITE_OMIT_CAST */
34918 /* Opcode: ToInt * * *
34920 ** Force the value on the top of the stack to be an integer. If
34921 ** The value is currently a real number, drop its fractional part.
34922 ** If the value is text or blob, try to convert it to an integer using the
34923 ** equivalent of atoi() and store 0 if no such conversion is possible.
34925 ** A NULL value is not changed by this routine. It remains NULL.
34927 case OP_ToInt: { /* same as TK_TO_INT, no-push */
34928 assert( pTos>=p->aStack );
34929 if( (pTos->flags & MEM_Null)==0 ){
34930 sqlite3VdbeMemIntegerify(pTos);
34932 break;
34935 #ifndef SQLITE_OMIT_CAST
34936 /* Opcode: ToReal * * *
34938 ** Force the value on the top of the stack to be a floating point number.
34939 ** If The value is currently an integer, convert it.
34940 ** If the value is text or blob, try to convert it to an integer using the
34941 ** equivalent of atoi() and store 0 if no such conversion is possible.
34943 ** A NULL value is not changed by this routine. It remains NULL.
34945 case OP_ToReal: { /* same as TK_TO_REAL, no-push */
34946 assert( pTos>=p->aStack );
34947 if( (pTos->flags & MEM_Null)==0 ){
34948 sqlite3VdbeMemRealify(pTos);
34950 break;
34952 #endif /* SQLITE_OMIT_CAST */
34954 /* Opcode: Eq P1 P2 P3
34956 ** Pop the top two elements from the stack. If they are equal, then
34957 ** jump to instruction P2. Otherwise, continue to the next instruction.
34959 ** If the 0x100 bit of P1 is true and either operand is NULL then take the
34960 ** jump. If the 0x100 bit of P1 is clear then fall thru if either operand
34961 ** is NULL.
34963 ** If the 0x200 bit of P1 is set and either operand is NULL then
34964 ** both operands are converted to integers prior to comparison.
34965 ** NULL operands are converted to zero and non-NULL operands are
34966 ** converted to 1. Thus, for example, with 0x200 set, NULL==NULL is true
34967 ** whereas it would normally be NULL. Similarly, NULL==123 is false when
34968 ** 0x200 is set but is NULL when the 0x200 bit of P1 is clear.
34970 ** The least significant byte of P1 (mask 0xff) must be an affinity character -
34971 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
34972 ** to coerce both values
34973 ** according to the affinity before the comparison is made. If the byte is
34974 ** 0x00, then numeric affinity is used.
34976 ** Once any conversions have taken place, and neither value is NULL,
34977 ** the values are compared. If both values are blobs, or both are text,
34978 ** then memcmp() is used to determine the results of the comparison. If
34979 ** both values are numeric, then a numeric comparison is used. If the
34980 ** two values are of different types, then they are inequal.
34982 ** If P2 is zero, do not jump. Instead, push an integer 1 onto the
34983 ** stack if the jump would have been taken, or a 0 if not. Push a
34984 ** NULL if either operand was NULL.
34986 ** If P3 is not NULL it is a pointer to a collating sequence (a CollSeq
34987 ** structure) that defines how to compare text.
34989 /* Opcode: Ne P1 P2 P3
34991 ** This works just like the Eq opcode except that the jump is taken if
34992 ** the operands from the stack are not equal. See the Eq opcode for
34993 ** additional information.
34995 /* Opcode: Lt P1 P2 P3
34997 ** This works just like the Eq opcode except that the jump is taken if
34998 ** the 2nd element down on the stack is less than the top of the stack.
34999 ** See the Eq opcode for additional information.
35001 /* Opcode: Le P1 P2 P3
35003 ** This works just like the Eq opcode except that the jump is taken if
35004 ** the 2nd element down on the stack is less than or equal to the
35005 ** top of the stack. See the Eq opcode for additional information.
35007 /* Opcode: Gt P1 P2 P3
35009 ** This works just like the Eq opcode except that the jump is taken if
35010 ** the 2nd element down on the stack is greater than the top of the stack.
35011 ** See the Eq opcode for additional information.
35013 /* Opcode: Ge P1 P2 P3
35015 ** This works just like the Eq opcode except that the jump is taken if
35016 ** the 2nd element down on the stack is greater than or equal to the
35017 ** top of the stack. See the Eq opcode for additional information.
35019 case OP_Eq: /* same as TK_EQ, no-push */
35020 case OP_Ne: /* same as TK_NE, no-push */
35021 case OP_Lt: /* same as TK_LT, no-push */
35022 case OP_Le: /* same as TK_LE, no-push */
35023 case OP_Gt: /* same as TK_GT, no-push */
35024 case OP_Ge: { /* same as TK_GE, no-push */
35025 Mem *pNos;
35026 int flags;
35027 int res;
35028 char affinity;
35030 pNos = &pTos[-1];
35031 flags = pTos->flags|pNos->flags;
35033 /* If either value is a NULL P2 is not zero, take the jump if the least
35034 ** significant byte of P1 is true. If P2 is zero, then push a NULL onto
35035 ** the stack.
35037 if( flags&MEM_Null ){
35038 if( (pOp->p1 & 0x200)!=0 ){
35039 /* The 0x200 bit of P1 means, roughly "do not treat NULL as the
35040 ** magic SQL value it normally is - treat it as if it were another
35041 ** integer".
35043 ** With 0x200 set, if either operand is NULL then both operands
35044 ** are converted to integers prior to being passed down into the
35045 ** normal comparison logic below. NULL operands are converted to
35046 ** zero and non-NULL operands are converted to 1. Thus, for example,
35047 ** with 0x200 set, NULL==NULL is true whereas it would normally
35048 ** be NULL. Similarly, NULL!=123 is true.
35050 sqlite3VdbeMemSetInt64(pTos, (pTos->flags & MEM_Null)==0);
35051 sqlite3VdbeMemSetInt64(pNos, (pNos->flags & MEM_Null)==0);
35052 }else{
35053 /* If the 0x200 bit of P1 is clear and either operand is NULL then
35054 ** the result is always NULL. The jump is taken if the 0x100 bit
35055 ** of P1 is set.
35057 popStack(&pTos, 2);
35058 if( pOp->p2 ){
35059 if( pOp->p1 & 0x100 ){
35060 pc = pOp->p2-1;
35062 }else{
35063 pTos++;
35064 pTos->flags = MEM_Null;
35066 break;
35070 affinity = pOp->p1 & 0xFF;
35071 if( affinity ){
35072 applyAffinity(pNos, affinity, encoding);
35073 applyAffinity(pTos, affinity, encoding);
35076 assert( pOp->p3type==P3_COLLSEQ || pOp->p3==0 );
35077 ExpandBlob(pNos);
35078 ExpandBlob(pTos);
35079 res = sqlite3MemCompare(pNos, pTos, (CollSeq*)pOp->p3);
35080 switch( pOp->opcode ){
35081 case OP_Eq: res = res==0; break;
35082 case OP_Ne: res = res!=0; break;
35083 case OP_Lt: res = res<0; break;
35084 case OP_Le: res = res<=0; break;
35085 case OP_Gt: res = res>0; break;
35086 default: res = res>=0; break;
35089 popStack(&pTos, 2);
35090 if( pOp->p2 ){
35091 if( res ){
35092 pc = pOp->p2-1;
35094 }else{
35095 pTos++;
35096 pTos->flags = MEM_Int;
35097 pTos->u.i = res;
35099 break;
35102 /* Opcode: And * * *
35104 ** Pop two values off the stack. Take the logical AND of the
35105 ** two values and push the resulting boolean value back onto the
35106 ** stack.
35108 /* Opcode: Or * * *
35110 ** Pop two values off the stack. Take the logical OR of the
35111 ** two values and push the resulting boolean value back onto the
35112 ** stack.
35114 case OP_And: /* same as TK_AND, no-push */
35115 case OP_Or: { /* same as TK_OR, no-push */
35116 Mem *pNos = &pTos[-1];
35117 int v1, v2; /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
35119 assert( pNos>=p->aStack );
35120 if( pTos->flags & MEM_Null ){
35121 v1 = 2;
35122 }else{
35123 sqlite3VdbeMemIntegerify(pTos);
35124 v1 = pTos->u.i==0;
35126 if( pNos->flags & MEM_Null ){
35127 v2 = 2;
35128 }else{
35129 sqlite3VdbeMemIntegerify(pNos);
35130 v2 = pNos->u.i==0;
35132 if( pOp->opcode==OP_And ){
35133 static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
35134 v1 = and_logic[v1*3+v2];
35135 }else{
35136 static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
35137 v1 = or_logic[v1*3+v2];
35139 popStack(&pTos, 2);
35140 pTos++;
35141 if( v1==2 ){
35142 pTos->flags = MEM_Null;
35143 }else{
35144 pTos->u.i = v1==0;
35145 pTos->flags = MEM_Int;
35147 break;
35150 /* Opcode: Negative * * *
35152 ** Treat the top of the stack as a numeric quantity. Replace it
35153 ** with its additive inverse. If the top of the stack is NULL
35154 ** its value is unchanged.
35156 /* Opcode: AbsValue * * *
35158 ** Treat the top of the stack as a numeric quantity. Replace it
35159 ** with its absolute value. If the top of the stack is NULL
35160 ** its value is unchanged.
35162 case OP_Negative: /* same as TK_UMINUS, no-push */
35163 case OP_AbsValue: {
35164 assert( pTos>=p->aStack );
35165 if( (pTos->flags & (MEM_Real|MEM_Int|MEM_Null))==0 ){
35166 sqlite3VdbeMemNumerify(pTos);
35168 if( pTos->flags & MEM_Real ){
35169 Release(pTos);
35170 if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
35171 pTos->r = -pTos->r;
35173 pTos->flags = MEM_Real;
35174 }else if( pTos->flags & MEM_Int ){
35175 Release(pTos);
35176 if( pOp->opcode==OP_Negative || pTos->u.i<0 ){
35177 pTos->u.i = -pTos->u.i;
35179 pTos->flags = MEM_Int;
35181 break;
35184 /* Opcode: Not * * *
35186 ** Interpret the top of the stack as a boolean value. Replace it
35187 ** with its complement. If the top of the stack is NULL its value
35188 ** is unchanged.
35190 case OP_Not: { /* same as TK_NOT, no-push */
35191 assert( pTos>=p->aStack );
35192 if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
35193 sqlite3VdbeMemIntegerify(pTos);
35194 assert( (pTos->flags & MEM_Dyn)==0 );
35195 pTos->u.i = !pTos->u.i;
35196 pTos->flags = MEM_Int;
35197 break;
35200 /* Opcode: BitNot * * *
35202 ** Interpret the top of the stack as an value. Replace it
35203 ** with its ones-complement. If the top of the stack is NULL its
35204 ** value is unchanged.
35206 case OP_BitNot: { /* same as TK_BITNOT, no-push */
35207 assert( pTos>=p->aStack );
35208 if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
35209 sqlite3VdbeMemIntegerify(pTos);
35210 assert( (pTos->flags & MEM_Dyn)==0 );
35211 pTos->u.i = ~pTos->u.i;
35212 pTos->flags = MEM_Int;
35213 break;
35216 /* Opcode: Noop * * *
35218 ** Do nothing. This instruction is often useful as a jump
35219 ** destination.
35222 ** The magic Explain opcode are only inserted when explain==2 (which
35223 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
35224 ** This opcode records information from the optimizer. It is the
35225 ** the same as a no-op. This opcodesnever appears in a real VM program.
35227 case OP_Explain:
35228 case OP_Noop: { /* no-push */
35229 break;
35232 /* Opcode: If P1 P2 *
35234 ** Pop a single boolean from the stack. If the boolean popped is
35235 ** true, then jump to p2. Otherwise continue to the next instruction.
35236 ** An integer is false if zero and true otherwise. A string is
35237 ** false if it has zero length and true otherwise.
35239 ** If the value popped of the stack is NULL, then take the jump if P1
35240 ** is true and fall through if P1 is false.
35242 /* Opcode: IfNot P1 P2 *
35244 ** Pop a single boolean from the stack. If the boolean popped is
35245 ** false, then jump to p2. Otherwise continue to the next instruction.
35246 ** An integer is false if zero and true otherwise. A string is
35247 ** false if it has zero length and true otherwise.
35249 ** If the value popped of the stack is NULL, then take the jump if P1
35250 ** is true and fall through if P1 is false.
35252 case OP_If: /* no-push */
35253 case OP_IfNot: { /* no-push */
35254 int c;
35255 assert( pTos>=p->aStack );
35256 if( pTos->flags & MEM_Null ){
35257 c = pOp->p1;
35258 }else{
35259 #ifdef SQLITE_OMIT_FLOATING_POINT
35260 c = sqlite3VdbeIntValue(pTos);
35261 #else
35262 c = sqlite3VdbeRealValue(pTos)!=0.0;
35263 #endif
35264 if( pOp->opcode==OP_IfNot ) c = !c;
35266 Release(pTos);
35267 pTos--;
35268 if( c ) pc = pOp->p2-1;
35269 break;
35272 /* Opcode: IsNull P1 P2 *
35274 ** Check the top of the stack and jump to P2 if the top of the stack
35275 ** is NULL. If P1 is positive, then pop P1 elements from the stack
35276 ** regardless of whether or not the jump is taken. If P1 is negative,
35277 ** pop -P1 elements from the stack only if the jump is taken and leave
35278 ** the stack unchanged if the jump is not taken.
35280 case OP_IsNull: { /* same as TK_ISNULL, no-push */
35281 if( pTos->flags & MEM_Null ){
35282 pc = pOp->p2-1;
35283 if( pOp->p1<0 ){
35284 popStack(&pTos, -pOp->p1);
35287 if( pOp->p1>0 ){
35288 popStack(&pTos, pOp->p1);
35290 break;
35293 /* Opcode: NotNull P1 P2 *
35295 ** Jump to P2 if the top abs(P1) values on the stack are all not NULL.
35296 ** Regardless of whether or not the jump is taken, pop the stack
35297 ** P1 times if P1 is greater than zero. But if P1 is negative,
35298 ** leave the stack unchanged.
35300 case OP_NotNull: { /* same as TK_NOTNULL, no-push */
35301 int i, cnt;
35302 cnt = pOp->p1;
35303 if( cnt<0 ) cnt = -cnt;
35304 assert( &pTos[1-cnt] >= p->aStack );
35305 for(i=0; i<cnt && (pTos[1+i-cnt].flags & MEM_Null)==0; i++){}
35306 if( i>=cnt ) pc = pOp->p2-1;
35307 if( pOp->p1>0 ) popStack(&pTos, cnt);
35308 break;
35311 /* Opcode: SetNumColumns P1 P2 *
35313 ** Before the OP_Column opcode can be executed on a cursor, this
35314 ** opcode must be called to set the number of fields in the table.
35316 ** This opcode sets the number of columns for cursor P1 to P2.
35318 ** If OP_KeyAsData is to be applied to cursor P1, it must be executed
35319 ** before this op-code.
35321 case OP_SetNumColumns: { /* no-push */
35322 Cursor *pC;
35323 assert( (pOp->p1)<p->nCursor );
35324 assert( p->apCsr[pOp->p1]!=0 );
35325 pC = p->apCsr[pOp->p1];
35326 pC->nField = pOp->p2;
35327 break;
35330 /* Opcode: Column P1 P2 P3
35332 ** Interpret the data that cursor P1 points to as a structure built using
35333 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
35334 ** information about the format of the data.) Push onto the stack the value
35335 ** of the P2-th column contained in the data. If there are less that (P2+1)
35336 ** values in the record, push a NULL onto the stack.
35338 ** If the KeyAsData opcode has previously executed on this cursor, then the
35339 ** field might be extracted from the key rather than the data.
35341 ** If the column contains fewer than P2 fields, then push a NULL. Or
35342 ** if P3 is of type P3_MEM, then push the P3 value. The P3 value will
35343 ** be default value for a column that has been added using the ALTER TABLE
35344 ** ADD COLUMN command. If P3 is an ordinary string, just push a NULL.
35345 ** When P3 is a string it is really just a comment describing the value
35346 ** to be pushed, not a default value.
35348 case OP_Column: {
35349 u32 payloadSize; /* Number of bytes in the record */
35350 int p1 = pOp->p1; /* P1 value of the opcode */
35351 int p2 = pOp->p2; /* column number to retrieve */
35352 Cursor *pC = 0; /* The VDBE cursor */
35353 char *zRec; /* Pointer to complete record-data */
35354 BtCursor *pCrsr; /* The BTree cursor */
35355 u32 *aType; /* aType[i] holds the numeric type of the i-th column */
35356 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
35357 u32 nField; /* number of fields in the record */
35358 int len; /* The length of the serialized data for the column */
35359 int i; /* Loop counter */
35360 char *zData; /* Part of the record being decoded */
35361 Mem sMem; /* For storing the record being decoded */
35363 sMem.flags = 0;
35364 assert( p1<p->nCursor );
35365 pTos++;
35366 pTos->flags = MEM_Null;
35368 /* This block sets the variable payloadSize to be the total number of
35369 ** bytes in the record.
35371 ** zRec is set to be the complete text of the record if it is available.
35372 ** The complete record text is always available for pseudo-tables
35373 ** If the record is stored in a cursor, the complete record text
35374 ** might be available in the pC->aRow cache. Or it might not be.
35375 ** If the data is unavailable, zRec is set to NULL.
35377 ** We also compute the number of columns in the record. For cursors,
35378 ** the number of columns is stored in the Cursor.nField element. For
35379 ** records on the stack, the next entry down on the stack is an integer
35380 ** which is the number of records.
35382 pC = p->apCsr[p1];
35383 #ifndef SQLITE_OMIT_VIRTUALTABLE
35384 assert( pC->pVtabCursor==0 );
35385 #endif
35386 assert( pC!=0 );
35387 if( pC->pCursor!=0 ){
35388 /* The record is stored in a B-Tree */
35389 rc = sqlite3VdbeCursorMoveto(pC);
35390 if( rc ) goto abort_due_to_error;
35391 zRec = 0;
35392 pCrsr = pC->pCursor;
35393 if( pC->nullRow ){
35394 payloadSize = 0;
35395 }else if( pC->cacheStatus==p->cacheCtr ){
35396 payloadSize = pC->payloadSize;
35397 zRec = (char*)pC->aRow;
35398 }else if( pC->isIndex ){
35399 i64 payloadSize64;
35400 sqlite3BtreeKeySize(pCrsr, &payloadSize64);
35401 payloadSize = payloadSize64;
35402 }else{
35403 sqlite3BtreeDataSize(pCrsr, &payloadSize);
35405 nField = pC->nField;
35406 }else if( pC->pseudoTable ){
35407 /* The record is the sole entry of a pseudo-table */
35408 payloadSize = pC->nData;
35409 zRec = pC->pData;
35410 pC->cacheStatus = CACHE_STALE;
35411 assert( payloadSize==0 || zRec!=0 );
35412 nField = pC->nField;
35413 pCrsr = 0;
35414 }else{
35415 zRec = 0;
35416 payloadSize = 0;
35417 pCrsr = 0;
35418 nField = 0;
35421 /* If payloadSize is 0, then just push a NULL onto the stack. */
35422 if( payloadSize==0 ){
35423 assert( pTos->flags==MEM_Null );
35424 break;
35426 if( payloadSize>SQLITE_MAX_LENGTH ){
35427 goto too_big;
35430 assert( p2<nField );
35432 /* Read and parse the table header. Store the results of the parse
35433 ** into the record header cache fields of the cursor.
35435 if( pC && pC->cacheStatus==p->cacheCtr ){
35436 aType = pC->aType;
35437 aOffset = pC->aOffset;
35438 }else{
35439 u8 *zIdx; /* Index into header */
35440 u8 *zEndHdr; /* Pointer to first byte after the header */
35441 u32 offset; /* Offset into the data */
35442 int szHdrSz; /* Size of the header size field at start of record */
35443 int avail; /* Number of bytes of available data */
35445 aType = pC->aType;
35446 if( aType==0 ){
35447 pC->aType = aType = sqliteMallocRaw( 2*nField*sizeof(aType) );
35449 if( aType==0 ){
35450 goto no_mem;
35452 pC->aOffset = aOffset = &aType[nField];
35453 pC->payloadSize = payloadSize;
35454 pC->cacheStatus = p->cacheCtr;
35456 /* Figure out how many bytes are in the header */
35457 if( zRec ){
35458 zData = zRec;
35459 }else{
35460 if( pC->isIndex ){
35461 zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
35462 }else{
35463 zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
35465 /* If KeyFetch()/DataFetch() managed to get the entire payload,
35466 ** save the payload in the pC->aRow cache. That will save us from
35467 ** having to make additional calls to fetch the content portion of
35468 ** the record.
35470 if( avail>=payloadSize ){
35471 zRec = zData;
35472 pC->aRow = (u8*)zData;
35473 }else{
35474 pC->aRow = 0;
35477 /* The following assert is true in all cases accept when
35478 ** the database file has been corrupted externally.
35479 ** assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
35480 szHdrSz = GetVarint((u8*)zData, offset);
35482 /* The KeyFetch() or DataFetch() above are fast and will get the entire
35483 ** record header in most cases. But they will fail to get the complete
35484 ** record header if the record header does not fit on a single page
35485 ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
35486 ** acquire the complete header text.
35488 if( !zRec && avail<offset ){
35489 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
35490 if( rc!=SQLITE_OK ){
35491 goto op_column_out;
35493 zData = sMem.z;
35495 zEndHdr = (u8 *)&zData[offset];
35496 zIdx = (u8 *)&zData[szHdrSz];
35498 /* Scan the header and use it to fill in the aType[] and aOffset[]
35499 ** arrays. aType[i] will contain the type integer for the i-th
35500 ** column and aOffset[i] will contain the offset from the beginning
35501 ** of the record to the start of the data for the i-th column
35503 for(i=0; i<nField; i++){
35504 if( zIdx<zEndHdr ){
35505 aOffset[i] = offset;
35506 zIdx += GetVarint(zIdx, aType[i]);
35507 offset += sqlite3VdbeSerialTypeLen(aType[i]);
35508 }else{
35509 /* If i is less that nField, then there are less fields in this
35510 ** record than SetNumColumns indicated there are columns in the
35511 ** table. Set the offset for any extra columns not present in
35512 ** the record to 0. This tells code below to push a NULL onto the
35513 ** stack instead of deserializing a value from the record.
35515 aOffset[i] = 0;
35518 Release(&sMem);
35519 sMem.flags = MEM_Null;
35521 /* If we have read more header data than was contained in the header,
35522 ** or if the end of the last field appears to be past the end of the
35523 ** record, then we must be dealing with a corrupt database.
35525 if( zIdx>zEndHdr || offset>payloadSize ){
35526 rc = SQLITE_CORRUPT_BKPT;
35527 goto op_column_out;
35531 /* Get the column information. If aOffset[p2] is non-zero, then
35532 ** deserialize the value from the record. If aOffset[p2] is zero,
35533 ** then there are not enough fields in the record to satisfy the
35534 ** request. In this case, set the value NULL or to P3 if P3 is
35535 ** a pointer to a Mem object.
35537 if( aOffset[p2] ){
35538 assert( rc==SQLITE_OK );
35539 if( zRec ){
35540 zData = &zRec[aOffset[p2]];
35541 }else{
35542 len = sqlite3VdbeSerialTypeLen(aType[p2]);
35543 rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex,&sMem);
35544 if( rc!=SQLITE_OK ){
35545 goto op_column_out;
35547 zData = sMem.z;
35549 sqlite3VdbeSerialGet((u8*)zData, aType[p2], pTos);
35550 pTos->enc = encoding;
35551 }else{
35552 if( pOp->p3type==P3_MEM ){
35553 sqlite3VdbeMemShallowCopy(pTos, (Mem *)(pOp->p3), MEM_Static);
35554 }else{
35555 pTos->flags = MEM_Null;
35559 /* If we dynamically allocated space to hold the data (in the
35560 ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
35561 ** dynamically allocated space over to the pTos structure.
35562 ** This prevents a memory copy.
35564 if( (sMem.flags & MEM_Dyn)!=0 ){
35565 assert( pTos->flags & MEM_Ephem );
35566 assert( pTos->flags & (MEM_Str|MEM_Blob) );
35567 assert( pTos->z==sMem.z );
35568 assert( sMem.flags & MEM_Term );
35569 pTos->flags &= ~MEM_Ephem;
35570 pTos->flags |= MEM_Dyn|MEM_Term;
35573 /* pTos->z might be pointing to sMem.zShort[]. Fix that so that we
35574 ** can abandon sMem */
35575 rc = sqlite3VdbeMemMakeWriteable(pTos);
35577 op_column_out:
35578 break;
35581 /* Opcode: MakeRecord P1 P2 P3
35583 ** Convert the top abs(P1) entries of the stack into a single entry
35584 ** suitable for use as a data record in a database table or as a key
35585 ** in an index. The details of the format are irrelavant as long as
35586 ** the OP_Column opcode can decode the record later and as long as the
35587 ** sqlite3VdbeRecordCompare function will correctly compare two encoded
35588 ** records. Refer to source code comments for the details of the record
35589 ** format.
35591 ** The original stack entries are popped from the stack if P1>0 but
35592 ** remain on the stack if P1<0.
35594 ** If P2 is not zero and one or more of the entries are NULL, then jump
35595 ** to the address given by P2. This feature can be used to skip a
35596 ** uniqueness test on indices.
35598 ** P3 may be a string that is P1 characters long. The nth character of the
35599 ** string indicates the column affinity that should be used for the nth
35600 ** field of the index key (i.e. the first character of P3 corresponds to the
35601 ** lowest element on the stack).
35603 ** The mapping from character to affinity is given by the SQLITE_AFF_
35604 ** macros defined in sqliteInt.h.
35606 ** If P3 is NULL then all index fields have the affinity NONE.
35608 ** See also OP_MakeIdxRec
35610 /* Opcode: MakeIdxRec P1 P2 P3
35612 ** This opcode works just OP_MakeRecord except that it reads an extra
35613 ** integer from the stack (thus reading a total of abs(P1+1) entries)
35614 ** and appends that extra integer to the end of the record as a varint.
35615 ** This results in an index key.
35617 case OP_MakeIdxRec:
35618 case OP_MakeRecord: {
35619 /* Assuming the record contains N fields, the record format looks
35620 ** like this:
35622 ** ------------------------------------------------------------------------
35623 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
35624 ** ------------------------------------------------------------------------
35626 ** Data(0) is taken from the lowest element of the stack and data(N-1) is
35627 ** the top of the stack.
35629 ** Each type field is a varint representing the serial type of the
35630 ** corresponding data element (see sqlite3VdbeSerialType()). The
35631 ** hdr-size field is also a varint which is the offset from the beginning
35632 ** of the record to data0.
35634 u8 *zNewRecord; /* A buffer to hold the data for the new record */
35635 Mem *pRec; /* The new record */
35636 Mem *pRowid = 0; /* Rowid appended to the new record */
35637 u64 nData = 0; /* Number of bytes of data space */
35638 int nHdr = 0; /* Number of bytes of header space */
35639 u64 nByte = 0; /* Data space required for this record */
35640 int nZero = 0; /* Number of zero bytes at the end of the record */
35641 int nVarint; /* Number of bytes in a varint */
35642 u32 serial_type; /* Type field */
35643 int containsNull = 0; /* True if any of the data fields are NULL */
35644 Mem *pData0; /* Bottom of the stack */
35645 int leaveOnStack; /* If true, leave the entries on the stack */
35646 int nField; /* Number of fields in the record */
35647 int jumpIfNull; /* Jump here if non-zero and any entries are NULL. */
35648 int addRowid; /* True to append a rowid column at the end */
35649 char *zAffinity; /* The affinity string for the record */
35650 int file_format; /* File format to use for encoding */
35651 int i; /* Space used in zNewRecord[] */
35652 char zTemp[NBFS]; /* Space to hold small records */
35654 leaveOnStack = ((pOp->p1<0)?1:0);
35655 nField = pOp->p1 * (leaveOnStack?-1:1);
35656 jumpIfNull = pOp->p2;
35657 addRowid = pOp->opcode==OP_MakeIdxRec;
35658 zAffinity = pOp->p3;
35660 pData0 = &pTos[1-nField];
35661 assert( pData0>=p->aStack );
35662 containsNull = 0;
35663 file_format = p->minWriteFileFormat;
35665 /* Loop through the elements that will make up the record to figure
35666 ** out how much space is required for the new record.
35668 for(pRec=pData0; pRec<=pTos; pRec++){
35669 int len;
35670 if( zAffinity ){
35671 applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
35673 if( pRec->flags&MEM_Null ){
35674 containsNull = 1;
35676 if( pRec->flags&MEM_Zero && pRec->n>0 ){
35677 ExpandBlob(pRec);
35679 serial_type = sqlite3VdbeSerialType(pRec, file_format);
35680 len = sqlite3VdbeSerialTypeLen(serial_type);
35681 nData += len;
35682 nHdr += sqlite3VarintLen(serial_type);
35683 if( pRec->flags & MEM_Zero ){
35684 /* Only pure zero-filled BLOBs can be input to this Opcode.
35685 ** We do not allow blobs with a prefix and a zero-filled tail. */
35686 nZero += pRec->u.i;
35687 }else if( len ){
35688 nZero = 0;
35692 /* If we have to append a varint rowid to this record, set pRowid
35693 ** to the value of the rowid and increase nByte by the amount of space
35694 ** required to store it.
35696 if( addRowid ){
35697 pRowid = &pTos[0-nField];
35698 assert( pRowid>=p->aStack );
35699 sqlite3VdbeMemIntegerify(pRowid);
35700 serial_type = sqlite3VdbeSerialType(pRowid, 0);
35701 nData += sqlite3VdbeSerialTypeLen(serial_type);
35702 nHdr += sqlite3VarintLen(serial_type);
35703 nZero = 0;
35706 /* Add the initial header varint and total the size */
35707 nHdr += nVarint = sqlite3VarintLen(nHdr);
35708 if( nVarint<sqlite3VarintLen(nHdr) ){
35709 nHdr++;
35711 nByte = nHdr+nData-nZero;
35712 if( nByte>SQLITE_MAX_LENGTH ){
35713 goto too_big;
35716 /* Allocate space for the new record. */
35717 if( nByte>sizeof(zTemp) ){
35718 zNewRecord = sqliteMallocRaw(nByte);
35719 if( !zNewRecord ){
35720 goto no_mem;
35722 }else{
35723 zNewRecord = (u8*)zTemp;
35726 /* Write the record */
35727 i = sqlite3PutVarint(zNewRecord, nHdr);
35728 for(pRec=pData0; pRec<=pTos; pRec++){
35729 serial_type = sqlite3VdbeSerialType(pRec, file_format);
35730 i += sqlite3PutVarint(&zNewRecord[i], serial_type); /* serial type */
35732 if( addRowid ){
35733 i += sqlite3PutVarint(&zNewRecord[i], sqlite3VdbeSerialType(pRowid, 0));
35735 for(pRec=pData0; pRec<=pTos; pRec++){ /* serial data */
35736 i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
35738 if( addRowid ){
35739 i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRowid, 0);
35741 assert( i==nByte );
35743 /* Pop entries off the stack if required. Push the new record on. */
35744 if( !leaveOnStack ){
35745 popStack(&pTos, nField+addRowid);
35747 pTos++;
35748 pTos->n = nByte;
35749 if( nByte<=sizeof(zTemp) ){
35750 assert( zNewRecord==(unsigned char *)zTemp );
35751 pTos->z = pTos->zShort;
35752 memcpy(pTos->zShort, zTemp, nByte);
35753 pTos->flags = MEM_Blob | MEM_Short;
35754 }else{
35755 assert( zNewRecord!=(unsigned char *)zTemp );
35756 pTos->z = (char*)zNewRecord;
35757 pTos->flags = MEM_Blob | MEM_Dyn;
35758 pTos->xDel = 0;
35760 if( nZero ){
35761 pTos->u.i = nZero;
35762 pTos->flags |= MEM_Zero;
35764 pTos->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
35766 /* If a NULL was encountered and jumpIfNull is non-zero, take the jump. */
35767 if( jumpIfNull && containsNull ){
35768 pc = jumpIfNull - 1;
35770 break;
35773 /* Opcode: Statement P1 * *
35775 ** Begin an individual statement transaction which is part of a larger
35776 ** BEGIN..COMMIT transaction. This is needed so that the statement
35777 ** can be rolled back after an error without having to roll back the
35778 ** entire transaction. The statement transaction will automatically
35779 ** commit when the VDBE halts.
35781 ** The statement is begun on the database file with index P1. The main
35782 ** database file has an index of 0 and the file used for temporary tables
35783 ** has an index of 1.
35785 case OP_Statement: { /* no-push */
35786 int i = pOp->p1;
35787 Btree *pBt;
35788 if( i>=0 && i<db->nDb && (pBt = db->aDb[i].pBt)!=0 && !(db->autoCommit) ){
35789 assert( sqlite3BtreeIsInTrans(pBt) );
35790 if( !sqlite3BtreeIsInStmt(pBt) ){
35791 rc = sqlite3BtreeBeginStmt(pBt);
35794 break;
35797 /* Opcode: AutoCommit P1 P2 *
35799 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
35800 ** back any currently active btree transactions. If there are any active
35801 ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
35803 ** This instruction causes the VM to halt.
35805 case OP_AutoCommit: { /* no-push */
35806 u8 i = pOp->p1;
35807 u8 rollback = pOp->p2;
35809 assert( i==1 || i==0 );
35810 assert( i==1 || rollback==0 );
35812 assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
35814 if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
35815 /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
35816 ** still running, and a transaction is active, return an error indicating
35817 ** that the other VMs must complete first.
35819 sqlite3SetString(&p->zErrMsg, "cannot ", rollback?"rollback":"commit",
35820 " transaction - SQL statements in progress", (char*)0);
35821 rc = SQLITE_ERROR;
35822 }else if( i!=db->autoCommit ){
35823 if( pOp->p2 ){
35824 assert( i==1 );
35825 sqlite3RollbackAll(db);
35826 db->autoCommit = 1;
35827 }else{
35828 db->autoCommit = i;
35829 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
35830 p->pTos = pTos;
35831 p->pc = pc;
35832 db->autoCommit = 1-i;
35833 p->rc = SQLITE_BUSY;
35834 return SQLITE_BUSY;
35837 if( p->rc==SQLITE_OK ){
35838 return SQLITE_DONE;
35839 }else{
35840 return SQLITE_ERROR;
35842 }else{
35843 sqlite3SetString(&p->zErrMsg,
35844 (!i)?"cannot start a transaction within a transaction":(
35845 (rollback)?"cannot rollback - no transaction is active":
35846 "cannot commit - no transaction is active"), (char*)0);
35848 rc = SQLITE_ERROR;
35850 break;
35853 /* Opcode: Transaction P1 P2 *
35855 ** Begin a transaction. The transaction ends when a Commit or Rollback
35856 ** opcode is encountered. Depending on the ON CONFLICT setting, the
35857 ** transaction might also be rolled back if an error is encountered.
35859 ** P1 is the index of the database file on which the transaction is
35860 ** started. Index 0 is the main database file and index 1 is the
35861 ** file used for temporary tables.
35863 ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
35864 ** obtained on the database file when a write-transaction is started. No
35865 ** other process can start another write transaction while this transaction is
35866 ** underway. Starting a write transaction also creates a rollback journal. A
35867 ** write transaction must be started before any changes can be made to the
35868 ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
35869 ** on the file.
35871 ** If P2 is zero, then a read-lock is obtained on the database file.
35873 case OP_Transaction: { /* no-push */
35874 int i = pOp->p1;
35875 Btree *pBt;
35877 assert( i>=0 && i<db->nDb );
35878 pBt = db->aDb[i].pBt;
35880 if( pBt ){
35881 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
35882 if( rc==SQLITE_BUSY ){
35883 p->pc = pc;
35884 p->rc = SQLITE_BUSY;
35885 p->pTos = pTos;
35886 return SQLITE_BUSY;
35888 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
35889 goto abort_due_to_error;
35892 break;
35895 /* Opcode: ReadCookie P1 P2 *
35897 ** Read cookie number P2 from database P1 and push it onto the stack.
35898 ** P2==0 is the schema version. P2==1 is the database format.
35899 ** P2==2 is the recommended pager cache size, and so forth. P1==0 is
35900 ** the main database file and P1==1 is the database file used to store
35901 ** temporary tables.
35903 ** There must be a read-lock on the database (either a transaction
35904 ** must be started or there must be an open cursor) before
35905 ** executing this instruction.
35907 case OP_ReadCookie: {
35908 int iMeta;
35909 assert( pOp->p2<SQLITE_N_BTREE_META );
35910 assert( pOp->p1>=0 && pOp->p1<db->nDb );
35911 assert( db->aDb[pOp->p1].pBt!=0 );
35912 /* The indexing of meta values at the schema layer is off by one from
35913 ** the indexing in the btree layer. The btree considers meta[0] to
35914 ** be the number of free pages in the database (a read-only value)
35915 ** and meta[1] to be the schema cookie. The schema layer considers
35916 ** meta[1] to be the schema cookie. So we have to shift the index
35917 ** by one in the following statement.
35919 rc = sqlite3BtreeGetMeta(db->aDb[pOp->p1].pBt, 1 + pOp->p2, (u32 *)&iMeta);
35920 pTos++;
35921 pTos->u.i = iMeta;
35922 pTos->flags = MEM_Int;
35923 break;
35926 /* Opcode: SetCookie P1 P2 *
35928 ** Write the top of the stack into cookie number P2 of database P1.
35929 ** P2==0 is the schema version. P2==1 is the database format.
35930 ** P2==2 is the recommended pager cache size, and so forth. P1==0 is
35931 ** the main database file and P1==1 is the database file used to store
35932 ** temporary tables.
35934 ** A transaction must be started before executing this opcode.
35936 case OP_SetCookie: { /* no-push */
35937 Db *pDb;
35938 assert( pOp->p2<SQLITE_N_BTREE_META );
35939 assert( pOp->p1>=0 && pOp->p1<db->nDb );
35940 pDb = &db->aDb[pOp->p1];
35941 assert( pDb->pBt!=0 );
35942 assert( pTos>=p->aStack );
35943 sqlite3VdbeMemIntegerify(pTos);
35944 /* See note about index shifting on OP_ReadCookie */
35945 rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pTos->u.i);
35946 if( pOp->p2==0 ){
35947 /* When the schema cookie changes, record the new cookie internally */
35948 pDb->pSchema->schema_cookie = pTos->u.i;
35949 db->flags |= SQLITE_InternChanges;
35950 }else if( pOp->p2==1 ){
35951 /* Record changes in the file format */
35952 pDb->pSchema->file_format = pTos->u.i;
35954 assert( (pTos->flags & MEM_Dyn)==0 );
35955 pTos--;
35956 if( pOp->p1==1 ){
35957 /* Invalidate all prepared statements whenever the TEMP database
35958 ** schema is changed. Ticket #1644 */
35959 sqlite3ExpirePreparedStatements(db);
35961 break;
35964 /* Opcode: VerifyCookie P1 P2 *
35966 ** Check the value of global database parameter number 0 (the
35967 ** schema version) and make sure it is equal to P2.
35968 ** P1 is the database number which is 0 for the main database file
35969 ** and 1 for the file holding temporary tables and some higher number
35970 ** for auxiliary databases.
35972 ** The cookie changes its value whenever the database schema changes.
35973 ** This operation is used to detect when that the cookie has changed
35974 ** and that the current process needs to reread the schema.
35976 ** Either a transaction needs to have been started or an OP_Open needs
35977 ** to be executed (to establish a read lock) before this opcode is
35978 ** invoked.
35980 case OP_VerifyCookie: { /* no-push */
35981 int iMeta;
35982 Btree *pBt;
35983 assert( pOp->p1>=0 && pOp->p1<db->nDb );
35984 pBt = db->aDb[pOp->p1].pBt;
35985 if( pBt ){
35986 rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
35987 }else{
35988 rc = SQLITE_OK;
35989 iMeta = 0;
35991 if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
35992 sqlite3SetString(&p->zErrMsg, "database schema has changed", (char*)0);
35993 /* If the schema-cookie from the database file matches the cookie
35994 ** stored with the in-memory representation of the schema, do
35995 ** not reload the schema from the database file.
35997 ** If virtual-tables are in use, this is not just an optimisation.
35998 ** Often, v-tables store their data in other SQLite tables, which
35999 ** are queried from within xNext() and other v-table methods using
36000 ** prepared queries. If such a query is out-of-date, we do not want to
36001 ** discard the database schema, as the user code implementing the
36002 ** v-table would have to be ready for the sqlite3_vtab structure itself
36003 ** to be invalidated whenever sqlite3_step() is called from within
36004 ** a v-table method.
36006 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
36007 sqlite3ResetInternalSchema(db, pOp->p1);
36010 sqlite3ExpirePreparedStatements(db);
36011 rc = SQLITE_SCHEMA;
36013 break;
36016 /* Opcode: OpenRead P1 P2 P3
36018 ** Open a read-only cursor for the database table whose root page is
36019 ** P2 in a database file. The database file is determined by an
36020 ** integer from the top of the stack. 0 means the main database and
36021 ** 1 means the database used for temporary tables. Give the new
36022 ** cursor an identifier of P1. The P1 values need not be contiguous
36023 ** but all P1 values should be small integers. It is an error for
36024 ** P1 to be negative.
36026 ** If P2==0 then take the root page number from the next of the stack.
36028 ** There will be a read lock on the database whenever there is an
36029 ** open cursor. If the database was unlocked prior to this instruction
36030 ** then a read lock is acquired as part of this instruction. A read
36031 ** lock allows other processes to read the database but prohibits
36032 ** any other process from modifying the database. The read lock is
36033 ** released when all cursors are closed. If this instruction attempts
36034 ** to get a read lock but fails, the script terminates with an
36035 ** SQLITE_BUSY error code.
36037 ** The P3 value is a pointer to a KeyInfo structure that defines the
36038 ** content and collating sequence of indices. P3 is NULL for cursors
36039 ** that are not pointing to indices.
36041 ** See also OpenWrite.
36043 /* Opcode: OpenWrite P1 P2 P3
36045 ** Open a read/write cursor named P1 on the table or index whose root
36046 ** page is P2. If P2==0 then take the root page number from the stack.
36048 ** The P3 value is a pointer to a KeyInfo structure that defines the
36049 ** content and collating sequence of indices. P3 is NULL for cursors
36050 ** that are not pointing to indices.
36052 ** This instruction works just like OpenRead except that it opens the cursor
36053 ** in read/write mode. For a given table, there can be one or more read-only
36054 ** cursors or a single read/write cursor but not both.
36056 ** See also OpenRead.
36058 case OP_OpenRead: /* no-push */
36059 case OP_OpenWrite: { /* no-push */
36060 int i = pOp->p1;
36061 int p2 = pOp->p2;
36062 int wrFlag;
36063 Btree *pX;
36064 int iDb;
36065 Cursor *pCur;
36066 Db *pDb;
36068 assert( pTos>=p->aStack );
36069 sqlite3VdbeMemIntegerify(pTos);
36070 iDb = pTos->u.i;
36071 assert( (pTos->flags & MEM_Dyn)==0 );
36072 pTos--;
36073 assert( iDb>=0 && iDb<db->nDb );
36074 pDb = &db->aDb[iDb];
36075 pX = pDb->pBt;
36076 assert( pX!=0 );
36077 if( pOp->opcode==OP_OpenWrite ){
36078 wrFlag = 1;
36079 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
36080 p->minWriteFileFormat = pDb->pSchema->file_format;
36082 }else{
36083 wrFlag = 0;
36085 if( p2<=0 ){
36086 assert( pTos>=p->aStack );
36087 sqlite3VdbeMemIntegerify(pTos);
36088 p2 = pTos->u.i;
36089 assert( (pTos->flags & MEM_Dyn)==0 );
36090 pTos--;
36091 assert( p2>=2 );
36093 assert( i>=0 );
36094 pCur = allocateCursor(p, i, iDb);
36095 if( pCur==0 ) goto no_mem;
36096 pCur->nullRow = 1;
36097 if( pX==0 ) break;
36098 /* We always provide a key comparison function. If the table being
36099 ** opened is of type INTKEY, the comparision function will be ignored. */
36100 rc = sqlite3BtreeCursor(pX, p2, wrFlag,
36101 sqlite3VdbeRecordCompare, pOp->p3,
36102 &pCur->pCursor);
36103 if( pOp->p3type==P3_KEYINFO ){
36104 pCur->pKeyInfo = (KeyInfo*)pOp->p3;
36105 pCur->pIncrKey = &pCur->pKeyInfo->incrKey;
36106 pCur->pKeyInfo->enc = ENC(p->db);
36107 }else{
36108 pCur->pKeyInfo = 0;
36109 pCur->pIncrKey = &pCur->bogusIncrKey;
36111 switch( rc ){
36112 case SQLITE_BUSY: {
36113 p->pc = pc;
36114 p->rc = SQLITE_BUSY;
36115 p->pTos = &pTos[1 + (pOp->p2<=0)]; /* Operands must remain on stack */
36116 return SQLITE_BUSY;
36118 case SQLITE_OK: {
36119 int flags = sqlite3BtreeFlags(pCur->pCursor);
36120 /* Sanity checking. Only the lower four bits of the flags byte should
36121 ** be used. Bit 3 (mask 0x08) is unpreditable. The lower 3 bits
36122 ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
36123 ** 2 (zerodata for indices). If these conditions are not met it can
36124 ** only mean that we are dealing with a corrupt database file
36126 if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
36127 rc = SQLITE_CORRUPT_BKPT;
36128 goto abort_due_to_error;
36130 pCur->isTable = (flags & BTREE_INTKEY)!=0;
36131 pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
36132 /* If P3==0 it means we are expected to open a table. If P3!=0 then
36133 ** we expect to be opening an index. If this is not what happened,
36134 ** then the database is corrupt
36136 if( (pCur->isTable && pOp->p3type==P3_KEYINFO)
36137 || (pCur->isIndex && pOp->p3type!=P3_KEYINFO) ){
36138 rc = SQLITE_CORRUPT_BKPT;
36139 goto abort_due_to_error;
36141 break;
36143 case SQLITE_EMPTY: {
36144 pCur->isTable = pOp->p3type!=P3_KEYINFO;
36145 pCur->isIndex = !pCur->isTable;
36146 rc = SQLITE_OK;
36147 break;
36149 default: {
36150 goto abort_due_to_error;
36153 break;
36156 /* Opcode: OpenEphemeral P1 P2 P3
36158 ** Open a new cursor P1 to a transient table.
36159 ** The cursor is always opened read/write even if
36160 ** the main database is read-only. The transient or virtual
36161 ** table is deleted automatically when the cursor is closed.
36163 ** P2 is the number of columns in the virtual table.
36164 ** The cursor points to a BTree table if P3==0 and to a BTree index
36165 ** if P3 is not 0. If P3 is not NULL, it points to a KeyInfo structure
36166 ** that defines the format of keys in the index.
36168 ** This opcode was once called OpenTemp. But that created
36169 ** confusion because the term "temp table", might refer either
36170 ** to a TEMP table at the SQL level, or to a table opened by
36171 ** this opcode. Then this opcode was call OpenVirtual. But
36172 ** that created confusion with the whole virtual-table idea.
36174 case OP_OpenEphemeral: { /* no-push */
36175 int i = pOp->p1;
36176 Cursor *pCx;
36177 assert( i>=0 );
36178 pCx = allocateCursor(p, i, -1);
36179 if( pCx==0 ) goto no_mem;
36180 pCx->nullRow = 1;
36181 rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, &pCx->pBt);
36182 if( rc==SQLITE_OK ){
36183 rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
36185 if( rc==SQLITE_OK ){
36186 /* If a transient index is required, create it by calling
36187 ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
36188 ** opening it. If a transient table is required, just use the
36189 ** automatically created table with root-page 1 (an INTKEY table).
36191 if( pOp->p3 ){
36192 int pgno;
36193 assert( pOp->p3type==P3_KEYINFO );
36194 rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA);
36195 if( rc==SQLITE_OK ){
36196 assert( pgno==MASTER_ROOT+1 );
36197 rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, sqlite3VdbeRecordCompare,
36198 pOp->p3, &pCx->pCursor);
36199 pCx->pKeyInfo = (KeyInfo*)pOp->p3;
36200 pCx->pKeyInfo->enc = ENC(p->db);
36201 pCx->pIncrKey = &pCx->pKeyInfo->incrKey;
36203 pCx->isTable = 0;
36204 }else{
36205 rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, 0, &pCx->pCursor);
36206 pCx->isTable = 1;
36207 pCx->pIncrKey = &pCx->bogusIncrKey;
36210 pCx->nField = pOp->p2;
36211 pCx->isIndex = !pCx->isTable;
36212 break;
36215 /* Opcode: OpenPseudo P1 * *
36217 ** Open a new cursor that points to a fake table that contains a single
36218 ** row of data. Any attempt to write a second row of data causes the
36219 ** first row to be deleted. All data is deleted when the cursor is
36220 ** closed.
36222 ** A pseudo-table created by this opcode is useful for holding the
36223 ** NEW or OLD tables in a trigger. Also used to hold the a single
36224 ** row output from the sorter so that the row can be decomposed into
36225 ** individual columns using the OP_Column opcode.
36227 case OP_OpenPseudo: { /* no-push */
36228 int i = pOp->p1;
36229 Cursor *pCx;
36230 assert( i>=0 );
36231 pCx = allocateCursor(p, i, -1);
36232 if( pCx==0 ) goto no_mem;
36233 pCx->nullRow = 1;
36234 pCx->pseudoTable = 1;
36235 pCx->pIncrKey = &pCx->bogusIncrKey;
36236 pCx->isTable = 1;
36237 pCx->isIndex = 0;
36238 break;
36241 /* Opcode: Close P1 * *
36243 ** Close a cursor previously opened as P1. If P1 is not
36244 ** currently open, this instruction is a no-op.
36246 case OP_Close: { /* no-push */
36247 int i = pOp->p1;
36248 if( i>=0 && i<p->nCursor ){
36249 sqlite3VdbeFreeCursor(p, p->apCsr[i]);
36250 p->apCsr[i] = 0;
36252 break;
36255 /* Opcode: MoveGe P1 P2 *
36257 ** Pop the top of the stack and use its value as a key. Reposition
36258 ** cursor P1 so that it points to the smallest entry that is greater
36259 ** than or equal to the key that was popped ffrom the stack.
36260 ** If there are no records greater than or equal to the key and P2
36261 ** is not zero, then jump to P2.
36263 ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
36265 /* Opcode: MoveGt P1 P2 *
36267 ** Pop the top of the stack and use its value as a key. Reposition
36268 ** cursor P1 so that it points to the smallest entry that is greater
36269 ** than the key from the stack.
36270 ** If there are no records greater than the key and P2 is not zero,
36271 ** then jump to P2.
36273 ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
36275 /* Opcode: MoveLt P1 P2 *
36277 ** Pop the top of the stack and use its value as a key. Reposition
36278 ** cursor P1 so that it points to the largest entry that is less
36279 ** than the key from the stack.
36280 ** If there are no records less than the key and P2 is not zero,
36281 ** then jump to P2.
36283 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
36285 /* Opcode: MoveLe P1 P2 *
36287 ** Pop the top of the stack and use its value as a key. Reposition
36288 ** cursor P1 so that it points to the largest entry that is less than
36289 ** or equal to the key that was popped from the stack.
36290 ** If there are no records less than or eqal to the key and P2 is not zero,
36291 ** then jump to P2.
36293 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
36295 case OP_MoveLt: /* no-push */
36296 case OP_MoveLe: /* no-push */
36297 case OP_MoveGe: /* no-push */
36298 case OP_MoveGt: { /* no-push */
36299 int i = pOp->p1;
36300 Cursor *pC;
36302 assert( pTos>=p->aStack );
36303 assert( i>=0 && i<p->nCursor );
36304 pC = p->apCsr[i];
36305 assert( pC!=0 );
36306 if( pC->pCursor!=0 ){
36307 int res, oc;
36308 oc = pOp->opcode;
36309 pC->nullRow = 0;
36310 *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe;
36311 if( pC->isTable ){
36312 i64 iKey;
36313 sqlite3VdbeMemIntegerify(pTos);
36314 iKey = intToKey(pTos->u.i);
36315 if( pOp->p2==0 && pOp->opcode==OP_MoveGe ){
36316 pC->movetoTarget = iKey;
36317 pC->deferredMoveto = 1;
36318 assert( (pTos->flags & MEM_Dyn)==0 );
36319 pTos--;
36320 break;
36322 rc = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)iKey, 0, &res);
36323 if( rc!=SQLITE_OK ){
36324 goto abort_due_to_error;
36326 pC->lastRowid = pTos->u.i;
36327 pC->rowidIsValid = res==0;
36328 }else{
36329 assert( pTos->flags & MEM_Blob );
36330 ExpandBlob(pTos);
36331 rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
36332 if( rc!=SQLITE_OK ){
36333 goto abort_due_to_error;
36335 pC->rowidIsValid = 0;
36337 pC->deferredMoveto = 0;
36338 pC->cacheStatus = CACHE_STALE;
36339 *pC->pIncrKey = 0;
36340 #ifdef SQLITE_TEST
36341 sqlite3_search_count++;
36342 #endif
36343 if( oc==OP_MoveGe || oc==OP_MoveGt ){
36344 if( res<0 ){
36345 rc = sqlite3BtreeNext(pC->pCursor, &res);
36346 if( rc!=SQLITE_OK ) goto abort_due_to_error;
36347 pC->rowidIsValid = 0;
36348 }else{
36349 res = 0;
36351 }else{
36352 assert( oc==OP_MoveLt || oc==OP_MoveLe );
36353 if( res>=0 ){
36354 rc = sqlite3BtreePrevious(pC->pCursor, &res);
36355 if( rc!=SQLITE_OK ) goto abort_due_to_error;
36356 pC->rowidIsValid = 0;
36357 }else{
36358 /* res might be negative because the table is empty. Check to
36359 ** see if this is the case.
36361 res = sqlite3BtreeEof(pC->pCursor);
36364 if( res ){
36365 if( pOp->p2>0 ){
36366 pc = pOp->p2 - 1;
36367 }else{
36368 pC->nullRow = 1;
36372 Release(pTos);
36373 pTos--;
36374 break;
36377 /* Opcode: Distinct P1 P2 *
36379 ** Use the top of the stack as a record created using MakeRecord. P1 is a
36380 ** cursor on a table that declared as an index. If that table contains an
36381 ** entry that matches the top of the stack fall thru. If the top of the stack
36382 ** matches no entry in P1 then jump to P2.
36384 ** The cursor is left pointing at the matching entry if it exists. The
36385 ** record on the top of the stack is not popped.
36387 ** This instruction is similar to NotFound except that this operation
36388 ** does not pop the key from the stack.
36390 ** The instruction is used to implement the DISTINCT operator on SELECT
36391 ** statements. The P1 table is not a true index but rather a record of
36392 ** all results that have produced so far.
36394 ** See also: Found, NotFound, MoveTo, IsUnique, NotExists
36396 /* Opcode: Found P1 P2 *
36398 ** Top of the stack holds a blob constructed by MakeRecord. P1 is an index.
36399 ** If an entry that matches the top of the stack exists in P1 then
36400 ** jump to P2. If the top of the stack does not match any entry in P1
36401 ** then fall thru. The P1 cursor is left pointing at the matching entry
36402 ** if it exists. The blob is popped off the top of the stack.
36404 ** This instruction is used to implement the IN operator where the
36405 ** left-hand side is a SELECT statement. P1 is not a true index but
36406 ** is instead a temporary index that holds the results of the SELECT
36407 ** statement. This instruction just checks to see if the left-hand side
36408 ** of the IN operator (stored on the top of the stack) exists in the
36409 ** result of the SELECT statement.
36411 ** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
36413 /* Opcode: NotFound P1 P2 *
36415 ** The top of the stack holds a blob constructed by MakeRecord. P1 is
36416 ** an index. If no entry exists in P1 that matches the blob then jump
36417 ** to P2. If an entry does existing, fall through. The cursor is left
36418 ** pointing to the entry that matches. The blob is popped from the stack.
36420 ** The difference between this operation and Distinct is that
36421 ** Distinct does not pop the key from the stack.
36423 ** See also: Distinct, Found, MoveTo, NotExists, IsUnique
36425 case OP_Distinct: /* no-push */
36426 case OP_NotFound: /* no-push */
36427 case OP_Found: { /* no-push */
36428 int i = pOp->p1;
36429 int alreadyExists = 0;
36430 Cursor *pC;
36431 assert( pTos>=p->aStack );
36432 assert( i>=0 && i<p->nCursor );
36433 assert( p->apCsr[i]!=0 );
36434 if( (pC = p->apCsr[i])->pCursor!=0 ){
36435 int res, rx;
36436 assert( pC->isTable==0 );
36437 assert( pTos->flags & MEM_Blob );
36438 Stringify(pTos, encoding);
36439 rx = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res);
36440 alreadyExists = rx==SQLITE_OK && res==0;
36441 pC->deferredMoveto = 0;
36442 pC->cacheStatus = CACHE_STALE;
36444 if( pOp->opcode==OP_Found ){
36445 if( alreadyExists ) pc = pOp->p2 - 1;
36446 }else{
36447 if( !alreadyExists ) pc = pOp->p2 - 1;
36449 if( pOp->opcode!=OP_Distinct ){
36450 Release(pTos);
36451 pTos--;
36453 break;
36456 /* Opcode: IsUnique P1 P2 *
36458 ** The top of the stack is an integer record number. Call this
36459 ** record number R. The next on the stack is an index key created
36460 ** using MakeIdxRec. Call it K. This instruction pops R from the
36461 ** stack but it leaves K unchanged.
36463 ** P1 is an index. So it has no data and its key consists of a
36464 ** record generated by OP_MakeRecord where the last field is the
36465 ** rowid of the entry that the index refers to.
36467 ** This instruction asks if there is an entry in P1 where the
36468 ** fields matches K but the rowid is different from R.
36469 ** If there is no such entry, then there is an immediate
36470 ** jump to P2. If any entry does exist where the index string
36471 ** matches K but the record number is not R, then the record
36472 ** number for that entry is pushed onto the stack and control
36473 ** falls through to the next instruction.
36475 ** See also: Distinct, NotFound, NotExists, Found
36477 case OP_IsUnique: { /* no-push */
36478 int i = pOp->p1;
36479 Mem *pNos = &pTos[-1];
36480 Cursor *pCx;
36481 BtCursor *pCrsr;
36482 i64 R;
36484 /* Pop the value R off the top of the stack
36486 assert( pNos>=p->aStack );
36487 sqlite3VdbeMemIntegerify(pTos);
36488 R = pTos->u.i;
36489 assert( (pTos->flags & MEM_Dyn)==0 );
36490 pTos--;
36491 assert( i>=0 && i<p->nCursor );
36492 pCx = p->apCsr[i];
36493 assert( pCx!=0 );
36494 pCrsr = pCx->pCursor;
36495 if( pCrsr!=0 ){
36496 int res;
36497 i64 v; /* The record number on the P1 entry that matches K */
36498 char *zKey; /* The value of K */
36499 int nKey; /* Number of bytes in K */
36500 int len; /* Number of bytes in K without the rowid at the end */
36501 int szRowid; /* Size of the rowid column at the end of zKey */
36503 /* Make sure K is a string and make zKey point to K
36505 assert( pNos->flags & MEM_Blob );
36506 Stringify(pNos, encoding);
36507 zKey = pNos->z;
36508 nKey = pNos->n;
36510 szRowid = sqlite3VdbeIdxRowidLen((u8*)zKey);
36511 len = nKey-szRowid;
36513 /* Search for an entry in P1 where all but the last four bytes match K.
36514 ** If there is no such entry, jump immediately to P2.
36516 assert( pCx->deferredMoveto==0 );
36517 pCx->cacheStatus = CACHE_STALE;
36518 rc = sqlite3BtreeMoveto(pCrsr, zKey, len, 0, &res);
36519 if( rc!=SQLITE_OK ){
36520 goto abort_due_to_error;
36522 if( res<0 ){
36523 rc = sqlite3BtreeNext(pCrsr, &res);
36524 if( res ){
36525 pc = pOp->p2 - 1;
36526 break;
36529 rc = sqlite3VdbeIdxKeyCompare(pCx, len, (u8*)zKey, &res);
36530 if( rc!=SQLITE_OK ) goto abort_due_to_error;
36531 if( res>0 ){
36532 pc = pOp->p2 - 1;
36533 break;
36536 /* At this point, pCrsr is pointing to an entry in P1 where all but
36537 ** the final entry (the rowid) matches K. Check to see if the
36538 ** final rowid column is different from R. If it equals R then jump
36539 ** immediately to P2.
36541 rc = sqlite3VdbeIdxRowid(pCrsr, &v);
36542 if( rc!=SQLITE_OK ){
36543 goto abort_due_to_error;
36545 if( v==R ){
36546 pc = pOp->p2 - 1;
36547 break;
36550 /* The final varint of the key is different from R. Push it onto
36551 ** the stack. (The record number of an entry that violates a UNIQUE
36552 ** constraint.)
36554 pTos++;
36555 pTos->u.i = v;
36556 pTos->flags = MEM_Int;
36558 break;
36561 /* Opcode: NotExists P1 P2 *
36563 ** Use the top of the stack as a integer key. If a record with that key
36564 ** does not exist in table of P1, then jump to P2. If the record
36565 ** does exist, then fall thru. The cursor is left pointing to the
36566 ** record if it exists. The integer key is popped from the stack.
36568 ** The difference between this operation and NotFound is that this
36569 ** operation assumes the key is an integer and that P1 is a table whereas
36570 ** NotFound assumes key is a blob constructed from MakeRecord and
36571 ** P1 is an index.
36573 ** See also: Distinct, Found, MoveTo, NotFound, IsUnique
36575 case OP_NotExists: { /* no-push */
36576 int i = pOp->p1;
36577 Cursor *pC;
36578 BtCursor *pCrsr;
36579 assert( pTos>=p->aStack );
36580 assert( i>=0 && i<p->nCursor );
36581 assert( p->apCsr[i]!=0 );
36582 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
36583 int res;
36584 u64 iKey;
36585 assert( pTos->flags & MEM_Int );
36586 assert( p->apCsr[i]->isTable );
36587 iKey = intToKey(pTos->u.i);
36588 rc = sqlite3BtreeMoveto(pCrsr, 0, iKey, 0,&res);
36589 pC->lastRowid = pTos->u.i;
36590 pC->rowidIsValid = res==0;
36591 pC->nullRow = 0;
36592 pC->cacheStatus = CACHE_STALE;
36593 /* res might be uninitialized if rc!=SQLITE_OK. But if rc!=SQLITE_OK
36594 ** processing is about to abort so we really do not care whether or not
36595 ** the following jump is taken. (In other words, do not stress over
36596 ** the error that valgrind sometimes shows on the next statement when
36597 ** running ioerr.test and similar failure-recovery test scripts.) */
36598 if( res!=0 ){
36599 pc = pOp->p2 - 1;
36600 pC->rowidIsValid = 0;
36603 Release(pTos);
36604 pTos--;
36605 break;
36608 /* Opcode: Sequence P1 * *
36610 ** Push an integer onto the stack which is the next available
36611 ** sequence number for cursor P1. The sequence number on the
36612 ** cursor is incremented after the push.
36614 case OP_Sequence: {
36615 int i = pOp->p1;
36616 assert( pTos>=p->aStack );
36617 assert( i>=0 && i<p->nCursor );
36618 assert( p->apCsr[i]!=0 );
36619 pTos++;
36620 pTos->u.i = p->apCsr[i]->seqCount++;
36621 pTos->flags = MEM_Int;
36622 break;
36626 /* Opcode: NewRowid P1 P2 *
36628 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
36629 ** The record number is not previously used as a key in the database
36630 ** table that cursor P1 points to. The new record number is pushed
36631 ** onto the stack.
36633 ** If P2>0 then P2 is a memory cell that holds the largest previously
36634 ** generated record number. No new record numbers are allowed to be less
36635 ** than this value. When this value reaches its maximum, a SQLITE_FULL
36636 ** error is generated. The P2 memory cell is updated with the generated
36637 ** record number. This P2 mechanism is used to help implement the
36638 ** AUTOINCREMENT feature.
36640 case OP_NewRowid: {
36641 int i = pOp->p1;
36642 i64 v = 0;
36643 Cursor *pC;
36644 assert( i>=0 && i<p->nCursor );
36645 assert( p->apCsr[i]!=0 );
36646 if( (pC = p->apCsr[i])->pCursor==0 ){
36647 /* The zero initialization above is all that is needed */
36648 }else{
36649 /* The next rowid or record number (different terms for the same
36650 ** thing) is obtained in a two-step algorithm.
36652 ** First we attempt to find the largest existing rowid and add one
36653 ** to that. But if the largest existing rowid is already the maximum
36654 ** positive integer, we have to fall through to the second
36655 ** probabilistic algorithm
36657 ** The second algorithm is to select a rowid at random and see if
36658 ** it already exists in the table. If it does not exist, we have
36659 ** succeeded. If the random rowid does exist, we select a new one
36660 ** and try again, up to 1000 times.
36662 ** For a table with less than 2 billion entries, the probability
36663 ** of not finding a unused rowid is about 1.0e-300. This is a
36664 ** non-zero probability, but it is still vanishingly small and should
36665 ** never cause a problem. You are much, much more likely to have a
36666 ** hardware failure than for this algorithm to fail.
36668 ** The analysis in the previous paragraph assumes that you have a good
36669 ** source of random numbers. Is a library function like lrand48()
36670 ** good enough? Maybe. Maybe not. It's hard to know whether there
36671 ** might be subtle bugs is some implementations of lrand48() that
36672 ** could cause problems. To avoid uncertainty, SQLite uses its own
36673 ** random number generator based on the RC4 algorithm.
36675 ** To promote locality of reference for repetitive inserts, the
36676 ** first few attempts at chosing a random rowid pick values just a little
36677 ** larger than the previous rowid. This has been shown experimentally
36678 ** to double the speed of the COPY operation.
36680 int res, rx=SQLITE_OK, cnt;
36681 i64 x;
36682 cnt = 0;
36683 if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
36684 BTREE_INTKEY ){
36685 rc = SQLITE_CORRUPT_BKPT;
36686 goto abort_due_to_error;
36688 assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
36689 assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
36691 #ifdef SQLITE_32BIT_ROWID
36692 # define MAX_ROWID 0x7fffffff
36693 #else
36694 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
36695 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
36696 ** to provide the constant while making all compilers happy.
36698 # define MAX_ROWID ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
36699 #endif
36701 if( !pC->useRandomRowid ){
36702 if( pC->nextRowidValid ){
36703 v = pC->nextRowid;
36704 }else{
36705 rc = sqlite3BtreeLast(pC->pCursor, &res);
36706 if( rc!=SQLITE_OK ){
36707 goto abort_due_to_error;
36709 if( res ){
36710 v = 1;
36711 }else{
36712 sqlite3BtreeKeySize(pC->pCursor, &v);
36713 v = keyToInt(v);
36714 if( v==MAX_ROWID ){
36715 pC->useRandomRowid = 1;
36716 }else{
36717 v++;
36722 #ifndef SQLITE_OMIT_AUTOINCREMENT
36723 if( pOp->p2 ){
36724 Mem *pMem;
36725 assert( pOp->p2>0 && pOp->p2<p->nMem ); /* P2 is a valid memory cell */
36726 pMem = &p->aMem[pOp->p2];
36727 sqlite3VdbeMemIntegerify(pMem);
36728 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P2) holds an integer */
36729 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
36730 rc = SQLITE_FULL;
36731 goto abort_due_to_error;
36733 if( v<pMem->u.i+1 ){
36734 v = pMem->u.i + 1;
36736 pMem->u.i = v;
36738 #endif
36740 if( v<MAX_ROWID ){
36741 pC->nextRowidValid = 1;
36742 pC->nextRowid = v+1;
36743 }else{
36744 pC->nextRowidValid = 0;
36747 if( pC->useRandomRowid ){
36748 assert( pOp->p2==0 ); /* SQLITE_FULL must have occurred prior to this */
36749 v = db->priorNewRowid;
36750 cnt = 0;
36752 if( v==0 || cnt>2 ){
36753 sqlite3Randomness(sizeof(v), &v);
36754 if( cnt<5 ) v &= 0xffffff;
36755 }else{
36756 unsigned char r;
36757 sqlite3Randomness(1, &r);
36758 v += r + 1;
36760 if( v==0 ) continue;
36761 x = intToKey(v);
36762 rx = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)x, 0, &res);
36763 cnt++;
36764 }while( cnt<1000 && rx==SQLITE_OK && res==0 );
36765 db->priorNewRowid = v;
36766 if( rx==SQLITE_OK && res==0 ){
36767 rc = SQLITE_FULL;
36768 goto abort_due_to_error;
36771 pC->rowidIsValid = 0;
36772 pC->deferredMoveto = 0;
36773 pC->cacheStatus = CACHE_STALE;
36775 pTos++;
36776 pTos->u.i = v;
36777 pTos->flags = MEM_Int;
36778 break;
36781 /* Opcode: Insert P1 P2 P3
36783 ** Write an entry into the table of cursor P1. A new entry is
36784 ** created if it doesn't already exist or the data for an existing
36785 ** entry is overwritten. The data is the value on the top of the
36786 ** stack. The key is the next value down on the stack. The key must
36787 ** be an integer. The stack is popped twice by this instruction.
36789 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
36790 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P2 is set,
36791 ** then rowid is stored for subsequent return by the
36792 ** sqlite3_last_insert_rowid() function (otherwise it's unmodified).
36794 ** Parameter P3 may point to a string containing the table-name, or
36795 ** may be NULL. If it is not NULL, then the update-hook
36796 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
36798 ** This instruction only works on tables. The equivalent instruction
36799 ** for indices is OP_IdxInsert.
36801 case OP_Insert: { /* no-push */
36802 Mem *pNos = &pTos[-1];
36803 int i = pOp->p1;
36804 Cursor *pC;
36805 assert( pNos>=p->aStack );
36806 assert( i>=0 && i<p->nCursor );
36807 assert( p->apCsr[i]!=0 );
36808 if( ((pC = p->apCsr[i])->pCursor!=0 || pC->pseudoTable) ){
36809 i64 iKey; /* The integer ROWID or key for the record to be inserted */
36811 assert( pNos->flags & MEM_Int );
36812 assert( pC->isTable );
36813 iKey = intToKey(pNos->u.i);
36815 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
36816 if( pOp->p2 & OPFLAG_LASTROWID ) db->lastRowid = pNos->u.i;
36817 if( pC->nextRowidValid && pNos->u.i>=pC->nextRowid ){
36818 pC->nextRowidValid = 0;
36820 if( pTos->flags & MEM_Null ){
36821 pTos->z = 0;
36822 pTos->n = 0;
36823 }else{
36824 assert( pTos->flags & (MEM_Blob|MEM_Str) );
36826 if( pC->pseudoTable ){
36827 sqliteFree(pC->pData);
36828 pC->iKey = iKey;
36829 pC->nData = pTos->n;
36830 if( pTos->flags & MEM_Dyn ){
36831 pC->pData = pTos->z;
36832 pTos->flags = MEM_Null;
36833 }else{
36834 pC->pData = sqliteMallocRaw( pC->nData+2 );
36835 if( !pC->pData ) goto no_mem;
36836 memcpy(pC->pData, pTos->z, pC->nData);
36837 pC->pData[pC->nData] = 0;
36838 pC->pData[pC->nData+1] = 0;
36840 pC->nullRow = 0;
36841 }else{
36842 int nZero;
36843 if( pTos->flags & MEM_Zero ){
36844 nZero = pTos->u.i;
36845 }else{
36846 nZero = 0;
36848 rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
36849 pTos->z, pTos->n, nZero,
36850 pOp->p2 & OPFLAG_APPEND);
36853 pC->rowidIsValid = 0;
36854 pC->deferredMoveto = 0;
36855 pC->cacheStatus = CACHE_STALE;
36857 /* Invoke the update-hook if required. */
36858 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
36859 const char *zDb = db->aDb[pC->iDb].zName;
36860 const char *zTbl = pOp->p3;
36861 int op = ((pOp->p2 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
36862 assert( pC->isTable );
36863 db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
36864 assert( pC->iDb>=0 );
36867 popStack(&pTos, 2);
36869 break;
36872 /* Opcode: Delete P1 P2 P3
36874 ** Delete the record at which the P1 cursor is currently pointing.
36876 ** The cursor will be left pointing at either the next or the previous
36877 ** record in the table. If it is left pointing at the next record, then
36878 ** the next Next instruction will be a no-op. Hence it is OK to delete
36879 ** a record from within an Next loop.
36881 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
36882 ** incremented (otherwise not).
36884 ** If P1 is a pseudo-table, then this instruction is a no-op.
36886 case OP_Delete: { /* no-push */
36887 int i = pOp->p1;
36888 Cursor *pC;
36889 assert( i>=0 && i<p->nCursor );
36890 pC = p->apCsr[i];
36891 assert( pC!=0 );
36892 if( pC->pCursor!=0 ){
36893 i64 iKey;
36895 /* If the update-hook will be invoked, set iKey to the rowid of the
36896 ** row being deleted.
36898 if( db->xUpdateCallback && pOp->p3 ){
36899 assert( pC->isTable );
36900 if( pC->rowidIsValid ){
36901 iKey = pC->lastRowid;
36902 }else{
36903 rc = sqlite3BtreeKeySize(pC->pCursor, &iKey);
36904 if( rc ){
36905 goto abort_due_to_error;
36907 iKey = keyToInt(iKey);
36911 rc = sqlite3VdbeCursorMoveto(pC);
36912 if( rc ) goto abort_due_to_error;
36913 rc = sqlite3BtreeDelete(pC->pCursor);
36914 pC->nextRowidValid = 0;
36915 pC->cacheStatus = CACHE_STALE;
36917 /* Invoke the update-hook if required. */
36918 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){
36919 const char *zDb = db->aDb[pC->iDb].zName;
36920 const char *zTbl = pOp->p3;
36921 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
36922 assert( pC->iDb>=0 );
36925 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
36926 break;
36929 /* Opcode: ResetCount P1 * *
36931 ** This opcode resets the VMs internal change counter to 0. If P1 is true,
36932 ** then the value of the change counter is copied to the database handle
36933 ** change counter (returned by subsequent calls to sqlite3_changes())
36934 ** before it is reset. This is used by trigger programs.
36936 case OP_ResetCount: { /* no-push */
36937 if( pOp->p1 ){
36938 sqlite3VdbeSetChanges(db, p->nChange);
36940 p->nChange = 0;
36941 break;
36944 /* Opcode: RowData P1 * *
36946 ** Push onto the stack the complete row data for cursor P1.
36947 ** There is no interpretation of the data. It is just copied
36948 ** onto the stack exactly as it is found in the database file.
36950 ** If the cursor is not pointing to a valid row, a NULL is pushed
36951 ** onto the stack.
36953 /* Opcode: RowKey P1 * *
36955 ** Push onto the stack the complete row key for cursor P1.
36956 ** There is no interpretation of the key. It is just copied
36957 ** onto the stack exactly as it is found in the database file.
36959 ** If the cursor is not pointing to a valid row, a NULL is pushed
36960 ** onto the stack.
36962 case OP_RowKey:
36963 case OP_RowData: {
36964 int i = pOp->p1;
36965 Cursor *pC;
36966 u32 n;
36968 /* Note that RowKey and RowData are really exactly the same instruction */
36969 pTos++;
36970 assert( i>=0 && i<p->nCursor );
36971 pC = p->apCsr[i];
36972 assert( pC->isTable || pOp->opcode==OP_RowKey );
36973 assert( pC->isIndex || pOp->opcode==OP_RowData );
36974 assert( pC!=0 );
36975 if( pC->nullRow ){
36976 pTos->flags = MEM_Null;
36977 }else if( pC->pCursor!=0 ){
36978 BtCursor *pCrsr = pC->pCursor;
36979 rc = sqlite3VdbeCursorMoveto(pC);
36980 if( rc ) goto abort_due_to_error;
36981 if( pC->nullRow ){
36982 pTos->flags = MEM_Null;
36983 break;
36984 }else if( pC->isIndex ){
36985 i64 n64;
36986 assert( !pC->isTable );
36987 sqlite3BtreeKeySize(pCrsr, &n64);
36988 if( n64>SQLITE_MAX_LENGTH ){
36989 goto too_big;
36991 n = n64;
36992 }else{
36993 sqlite3BtreeDataSize(pCrsr, &n);
36995 if( n>SQLITE_MAX_LENGTH ){
36996 goto too_big;
36998 pTos->n = n;
36999 if( n<=NBFS ){
37000 pTos->flags = MEM_Blob | MEM_Short;
37001 pTos->z = pTos->zShort;
37002 }else{
37003 char *z = sqliteMallocRaw( n );
37004 if( z==0 ) goto no_mem;
37005 pTos->flags = MEM_Blob | MEM_Dyn;
37006 pTos->xDel = 0;
37007 pTos->z = z;
37009 if( pC->isIndex ){
37010 rc = sqlite3BtreeKey(pCrsr, 0, n, pTos->z);
37011 }else{
37012 rc = sqlite3BtreeData(pCrsr, 0, n, pTos->z);
37014 }else if( pC->pseudoTable ){
37015 pTos->n = pC->nData;
37016 assert( pC->nData<=SQLITE_MAX_LENGTH );
37017 pTos->z = pC->pData;
37018 pTos->flags = MEM_Blob|MEM_Ephem;
37019 }else{
37020 pTos->flags = MEM_Null;
37022 pTos->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
37023 break;
37026 /* Opcode: Rowid P1 * *
37028 ** Push onto the stack an integer which is the key of the table entry that
37029 ** P1 is currently point to.
37031 case OP_Rowid: {
37032 int i = pOp->p1;
37033 Cursor *pC;
37034 i64 v;
37036 assert( i>=0 && i<p->nCursor );
37037 pC = p->apCsr[i];
37038 assert( pC!=0 );
37039 rc = sqlite3VdbeCursorMoveto(pC);
37040 if( rc ) goto abort_due_to_error;
37041 pTos++;
37042 if( pC->rowidIsValid ){
37043 v = pC->lastRowid;
37044 }else if( pC->pseudoTable ){
37045 v = keyToInt(pC->iKey);
37046 }else if( pC->nullRow || pC->pCursor==0 ){
37047 pTos->flags = MEM_Null;
37048 break;
37049 }else{
37050 assert( pC->pCursor!=0 );
37051 sqlite3BtreeKeySize(pC->pCursor, &v);
37052 v = keyToInt(v);
37054 pTos->u.i = v;
37055 pTos->flags = MEM_Int;
37056 break;
37059 /* Opcode: NullRow P1 * *
37061 ** Move the cursor P1 to a null row. Any OP_Column operations
37062 ** that occur while the cursor is on the null row will always push
37063 ** a NULL onto the stack.
37065 case OP_NullRow: { /* no-push */
37066 int i = pOp->p1;
37067 Cursor *pC;
37069 assert( i>=0 && i<p->nCursor );
37070 pC = p->apCsr[i];
37071 assert( pC!=0 );
37072 pC->nullRow = 1;
37073 pC->rowidIsValid = 0;
37074 break;
37077 /* Opcode: Last P1 P2 *
37079 ** The next use of the Rowid or Column or Next instruction for P1
37080 ** will refer to the last entry in the database table or index.
37081 ** If the table or index is empty and P2>0, then jump immediately to P2.
37082 ** If P2 is 0 or if the table or index is not empty, fall through
37083 ** to the following instruction.
37085 case OP_Last: { /* no-push */
37086 int i = pOp->p1;
37087 Cursor *pC;
37088 BtCursor *pCrsr;
37090 assert( i>=0 && i<p->nCursor );
37091 pC = p->apCsr[i];
37092 assert( pC!=0 );
37093 if( (pCrsr = pC->pCursor)!=0 ){
37094 int res;
37095 rc = sqlite3BtreeLast(pCrsr, &res);
37096 pC->nullRow = res;
37097 pC->deferredMoveto = 0;
37098 pC->cacheStatus = CACHE_STALE;
37099 if( res && pOp->p2>0 ){
37100 pc = pOp->p2 - 1;
37102 }else{
37103 pC->nullRow = 0;
37105 break;
37109 /* Opcode: Sort P1 P2 *
37111 ** This opcode does exactly the same thing as OP_Rewind except that
37112 ** it increments an undocumented global variable used for testing.
37114 ** Sorting is accomplished by writing records into a sorting index,
37115 ** then rewinding that index and playing it back from beginning to
37116 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
37117 ** rewinding so that the global variable will be incremented and
37118 ** regression tests can determine whether or not the optimizer is
37119 ** correctly optimizing out sorts.
37121 case OP_Sort: { /* no-push */
37122 #ifdef SQLITE_TEST
37123 sqlite3_sort_count++;
37124 sqlite3_search_count--;
37125 #endif
37126 /* Fall through into OP_Rewind */
37128 /* Opcode: Rewind P1 P2 *
37130 ** The next use of the Rowid or Column or Next instruction for P1
37131 ** will refer to the first entry in the database table or index.
37132 ** If the table or index is empty and P2>0, then jump immediately to P2.
37133 ** If P2 is 0 or if the table or index is not empty, fall through
37134 ** to the following instruction.
37136 case OP_Rewind: { /* no-push */
37137 int i = pOp->p1;
37138 Cursor *pC;
37139 BtCursor *pCrsr;
37140 int res;
37142 assert( i>=0 && i<p->nCursor );
37143 pC = p->apCsr[i];
37144 assert( pC!=0 );
37145 if( (pCrsr = pC->pCursor)!=0 ){
37146 rc = sqlite3BtreeFirst(pCrsr, &res);
37147 pC->atFirst = res==0;
37148 pC->deferredMoveto = 0;
37149 pC->cacheStatus = CACHE_STALE;
37150 }else{
37151 res = 1;
37153 pC->nullRow = res;
37154 if( res && pOp->p2>0 ){
37155 pc = pOp->p2 - 1;
37157 break;
37160 /* Opcode: Next P1 P2 *
37162 ** Advance cursor P1 so that it points to the next key/data pair in its
37163 ** table or index. If there are no more key/value pairs then fall through
37164 ** to the following instruction. But if the cursor advance was successful,
37165 ** jump immediately to P2.
37167 ** See also: Prev
37169 /* Opcode: Prev P1 P2 *
37171 ** Back up cursor P1 so that it points to the previous key/data pair in its
37172 ** table or index. If there is no previous key/value pairs then fall through
37173 ** to the following instruction. But if the cursor backup was successful,
37174 ** jump immediately to P2.
37176 case OP_Prev: /* no-push */
37177 case OP_Next: { /* no-push */
37178 Cursor *pC;
37179 BtCursor *pCrsr;
37181 CHECK_FOR_INTERRUPT;
37182 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
37183 pC = p->apCsr[pOp->p1];
37184 if( pC==0 ){
37185 break; /* See ticket #2273 */
37187 if( (pCrsr = pC->pCursor)!=0 ){
37188 int res;
37189 if( pC->nullRow ){
37190 res = 1;
37191 }else{
37192 assert( pC->deferredMoveto==0 );
37193 rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
37194 sqlite3BtreePrevious(pCrsr, &res);
37195 pC->nullRow = res;
37196 pC->cacheStatus = CACHE_STALE;
37198 if( res==0 ){
37199 pc = pOp->p2 - 1;
37200 #ifdef SQLITE_TEST
37201 sqlite3_search_count++;
37202 #endif
37204 }else{
37205 pC->nullRow = 1;
37207 pC->rowidIsValid = 0;
37208 break;
37211 /* Opcode: IdxInsert P1 P2 *
37213 ** The top of the stack holds a SQL index key made using either the
37214 ** MakeIdxRec or MakeRecord instructions. This opcode writes that key
37215 ** into the index P1. Data for the entry is nil.
37217 ** P2 is a flag that provides a hint to the b-tree layer that this
37218 ** insert is likely to be an append.
37220 ** This instruction only works for indices. The equivalent instruction
37221 ** for tables is OP_Insert.
37223 case OP_IdxInsert: { /* no-push */
37224 int i = pOp->p1;
37225 Cursor *pC;
37226 BtCursor *pCrsr;
37227 assert( pTos>=p->aStack );
37228 assert( i>=0 && i<p->nCursor );
37229 assert( p->apCsr[i]!=0 );
37230 assert( pTos->flags & MEM_Blob );
37231 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
37232 assert( pC->isTable==0 );
37233 rc = ExpandBlob(pTos);
37234 if( rc==SQLITE_OK ){
37235 int nKey = pTos->n;
37236 const char *zKey = pTos->z;
37237 rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p2);
37238 assert( pC->deferredMoveto==0 );
37239 pC->cacheStatus = CACHE_STALE;
37242 Release(pTos);
37243 pTos--;
37244 break;
37247 /* Opcode: IdxDelete P1 * *
37249 ** The top of the stack is an index key built using the either the
37250 ** MakeIdxRec or MakeRecord opcodes.
37251 ** This opcode removes that entry from the index.
37253 case OP_IdxDelete: { /* no-push */
37254 int i = pOp->p1;
37255 Cursor *pC;
37256 BtCursor *pCrsr;
37257 assert( pTos>=p->aStack );
37258 assert( pTos->flags & MEM_Blob );
37259 assert( i>=0 && i<p->nCursor );
37260 assert( p->apCsr[i]!=0 );
37261 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
37262 int res;
37263 rc = sqlite3BtreeMoveto(pCrsr, pTos->z, pTos->n, 0, &res);
37264 if( rc==SQLITE_OK && res==0 ){
37265 rc = sqlite3BtreeDelete(pCrsr);
37267 assert( pC->deferredMoveto==0 );
37268 pC->cacheStatus = CACHE_STALE;
37270 Release(pTos);
37271 pTos--;
37272 break;
37275 /* Opcode: IdxRowid P1 * *
37277 ** Push onto the stack an integer which is the last entry in the record at
37278 ** the end of the index key pointed to by cursor P1. This integer should be
37279 ** the rowid of the table entry to which this index entry points.
37281 ** See also: Rowid, MakeIdxRec.
37283 case OP_IdxRowid: {
37284 int i = pOp->p1;
37285 BtCursor *pCrsr;
37286 Cursor *pC;
37288 assert( i>=0 && i<p->nCursor );
37289 assert( p->apCsr[i]!=0 );
37290 pTos++;
37291 pTos->flags = MEM_Null;
37292 if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
37293 i64 rowid;
37295 assert( pC->deferredMoveto==0 );
37296 assert( pC->isTable==0 );
37297 if( pC->nullRow ){
37298 pTos->flags = MEM_Null;
37299 }else{
37300 rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
37301 if( rc!=SQLITE_OK ){
37302 goto abort_due_to_error;
37304 pTos->flags = MEM_Int;
37305 pTos->u.i = rowid;
37308 break;
37311 /* Opcode: IdxGT P1 P2 *
37313 ** The top of the stack is an index entry that omits the ROWID. Compare
37314 ** the top of stack against the index that P1 is currently pointing to.
37315 ** Ignore the ROWID on the P1 index.
37317 ** The top of the stack might have fewer columns that P1.
37319 ** If the P1 index entry is greater than the top of the stack
37320 ** then jump to P2. Otherwise fall through to the next instruction.
37321 ** In either case, the stack is popped once.
37323 /* Opcode: IdxGE P1 P2 P3
37325 ** The top of the stack is an index entry that omits the ROWID. Compare
37326 ** the top of stack against the index that P1 is currently pointing to.
37327 ** Ignore the ROWID on the P1 index.
37329 ** If the P1 index entry is greater than or equal to the top of the stack
37330 ** then jump to P2. Otherwise fall through to the next instruction.
37331 ** In either case, the stack is popped once.
37333 ** If P3 is the "+" string (or any other non-NULL string) then the
37334 ** index taken from the top of the stack is temporarily increased by
37335 ** an epsilon prior to the comparison. This make the opcode work
37336 ** like IdxGT except that if the key from the stack is a prefix of
37337 ** the key in the cursor, the result is false whereas it would be
37338 ** true with IdxGT.
37340 /* Opcode: IdxLT P1 P2 P3
37342 ** The top of the stack is an index entry that omits the ROWID. Compare
37343 ** the top of stack against the index that P1 is currently pointing to.
37344 ** Ignore the ROWID on the P1 index.
37346 ** If the P1 index entry is less than the top of the stack
37347 ** then jump to P2. Otherwise fall through to the next instruction.
37348 ** In either case, the stack is popped once.
37350 ** If P3 is the "+" string (or any other non-NULL string) then the
37351 ** index taken from the top of the stack is temporarily increased by
37352 ** an epsilon prior to the comparison. This makes the opcode work
37353 ** like IdxLE.
37355 case OP_IdxLT: /* no-push */
37356 case OP_IdxGT: /* no-push */
37357 case OP_IdxGE: { /* no-push */
37358 int i= pOp->p1;
37359 Cursor *pC;
37361 assert( i>=0 && i<p->nCursor );
37362 assert( p->apCsr[i]!=0 );
37363 assert( pTos>=p->aStack );
37364 if( (pC = p->apCsr[i])->pCursor!=0 ){
37365 int res;
37367 assert( pTos->flags & MEM_Blob ); /* Created using OP_MakeRecord */
37368 assert( pC->deferredMoveto==0 );
37369 ExpandBlob(pTos);
37370 *pC->pIncrKey = pOp->p3!=0;
37371 assert( pOp->p3==0 || pOp->opcode!=OP_IdxGT );
37372 rc = sqlite3VdbeIdxKeyCompare(pC, pTos->n, (u8*)pTos->z, &res);
37373 *pC->pIncrKey = 0;
37374 if( rc!=SQLITE_OK ){
37375 break;
37377 if( pOp->opcode==OP_IdxLT ){
37378 res = -res;
37379 }else if( pOp->opcode==OP_IdxGE ){
37380 res++;
37382 if( res>0 ){
37383 pc = pOp->p2 - 1 ;
37386 Release(pTos);
37387 pTos--;
37388 break;
37391 /* Opcode: Destroy P1 P2 *
37393 ** Delete an entire database table or index whose root page in the database
37394 ** file is given by P1.
37396 ** The table being destroyed is in the main database file if P2==0. If
37397 ** P2==1 then the table to be clear is in the auxiliary database file
37398 ** that is used to store tables create using CREATE TEMPORARY TABLE.
37400 ** If AUTOVACUUM is enabled then it is possible that another root page
37401 ** might be moved into the newly deleted root page in order to keep all
37402 ** root pages contiguous at the beginning of the database. The former
37403 ** value of the root page that moved - its value before the move occurred -
37404 ** is pushed onto the stack. If no page movement was required (because
37405 ** the table being dropped was already the last one in the database) then
37406 ** a zero is pushed onto the stack. If AUTOVACUUM is disabled
37407 ** then a zero is pushed onto the stack.
37409 ** See also: Clear
37411 case OP_Destroy: {
37412 int iMoved;
37413 int iCnt;
37414 #ifndef SQLITE_OMIT_VIRTUALTABLE
37415 Vdbe *pVdbe;
37416 iCnt = 0;
37417 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
37418 if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
37419 iCnt++;
37422 #else
37423 iCnt = db->activeVdbeCnt;
37424 #endif
37425 if( iCnt>1 ){
37426 rc = SQLITE_LOCKED;
37427 }else{
37428 assert( iCnt==1 );
37429 rc = sqlite3BtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1, &iMoved);
37430 pTos++;
37431 pTos->flags = MEM_Int;
37432 pTos->u.i = iMoved;
37433 #ifndef SQLITE_OMIT_AUTOVACUUM
37434 if( rc==SQLITE_OK && iMoved!=0 ){
37435 sqlite3RootPageMoved(&db->aDb[pOp->p2], iMoved, pOp->p1);
37437 #endif
37439 break;
37442 /* Opcode: Clear P1 P2 *
37444 ** Delete all contents of the database table or index whose root page
37445 ** in the database file is given by P1. But, unlike Destroy, do not
37446 ** remove the table or index from the database file.
37448 ** The table being clear is in the main database file if P2==0. If
37449 ** P2==1 then the table to be clear is in the auxiliary database file
37450 ** that is used to store tables create using CREATE TEMPORARY TABLE.
37452 ** See also: Destroy
37454 case OP_Clear: { /* no-push */
37456 /* For consistency with the way other features of SQLite operate
37457 ** with a truncate, we will also skip the update callback.
37459 #if 0
37460 Btree *pBt = db->aDb[pOp->p2].pBt;
37461 if( db->xUpdateCallback && pOp->p3 ){
37462 const char *zDb = db->aDb[pOp->p2].zName;
37463 const char *zTbl = pOp->p3;
37464 BtCursor *pCur = 0;
37465 int fin = 0;
37467 rc = sqlite3BtreeCursor(pBt, pOp->p1, 0, 0, 0, &pCur);
37468 if( rc!=SQLITE_OK ){
37469 goto abort_due_to_error;
37471 for(
37472 rc=sqlite3BtreeFirst(pCur, &fin);
37473 rc==SQLITE_OK && !fin;
37474 rc=sqlite3BtreeNext(pCur, &fin)
37476 i64 iKey;
37477 rc = sqlite3BtreeKeySize(pCur, &iKey);
37478 if( rc ){
37479 break;
37481 iKey = keyToInt(iKey);
37482 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
37484 sqlite3BtreeCloseCursor(pCur);
37485 if( rc!=SQLITE_OK ){
37486 goto abort_due_to_error;
37489 #endif
37490 rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
37491 break;
37494 /* Opcode: CreateTable P1 * *
37496 ** Allocate a new table in the main database file if P2==0 or in the
37497 ** auxiliary database file if P2==1. Push the page number
37498 ** for the root page of the new table onto the stack.
37500 ** The difference between a table and an index is this: A table must
37501 ** have a 4-byte integer key and can have arbitrary data. An index
37502 ** has an arbitrary key but no data.
37504 ** See also: CreateIndex
37506 /* Opcode: CreateIndex P1 * *
37508 ** Allocate a new index in the main database file if P2==0 or in the
37509 ** auxiliary database file if P2==1. Push the page number of the
37510 ** root page of the new index onto the stack.
37512 ** See documentation on OP_CreateTable for additional information.
37514 case OP_CreateIndex:
37515 case OP_CreateTable: {
37516 int pgno;
37517 int flags;
37518 Db *pDb;
37519 assert( pOp->p1>=0 && pOp->p1<db->nDb );
37520 pDb = &db->aDb[pOp->p1];
37521 assert( pDb->pBt!=0 );
37522 if( pOp->opcode==OP_CreateTable ){
37523 /* flags = BTREE_INTKEY; */
37524 flags = BTREE_LEAFDATA|BTREE_INTKEY;
37525 }else{
37526 flags = BTREE_ZERODATA;
37528 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
37529 pTos++;
37530 if( rc==SQLITE_OK ){
37531 pTos->u.i = pgno;
37532 pTos->flags = MEM_Int;
37533 }else{
37534 pTos->flags = MEM_Null;
37536 break;
37539 /* Opcode: ParseSchema P1 P2 P3
37541 ** Read and parse all entries from the SQLITE_MASTER table of database P1
37542 ** that match the WHERE clause P3. P2 is the "force" flag. Always do
37543 ** the parsing if P2 is true. If P2 is false, then this routine is a
37544 ** no-op if the schema is not currently loaded. In other words, if P2
37545 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
37546 ** schema is already loaded into the symbol table.
37548 ** This opcode invokes the parser to create a new virtual machine,
37549 ** then runs the new virtual machine. It is thus a reentrant opcode.
37551 case OP_ParseSchema: { /* no-push */
37552 char *zSql;
37553 int iDb = pOp->p1;
37554 const char *zMaster;
37555 InitData initData;
37557 assert( iDb>=0 && iDb<db->nDb );
37558 if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
37559 break;
37561 zMaster = SCHEMA_TABLE(iDb);
37562 initData.db = db;
37563 initData.iDb = pOp->p1;
37564 initData.pzErrMsg = &p->zErrMsg;
37565 zSql = sqlite3MPrintf(
37566 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
37567 db->aDb[iDb].zName, zMaster, pOp->p3);
37568 if( zSql==0 ) goto no_mem;
37569 sqlite3SafetyOff(db);
37570 assert( db->init.busy==0 );
37571 db->init.busy = 1;
37572 assert( !sqlite3MallocFailed() );
37573 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
37574 if( rc==SQLITE_ABORT ) rc = initData.rc;
37575 sqliteFree(zSql);
37576 db->init.busy = 0;
37577 sqlite3SafetyOn(db);
37578 if( rc==SQLITE_NOMEM ){
37579 sqlite3FailedMalloc();
37580 goto no_mem;
37582 break;
37585 #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
37586 /* Opcode: LoadAnalysis P1 * *
37588 ** Read the sqlite_stat1 table for database P1 and load the content
37589 ** of that table into the internal index hash table. This will cause
37590 ** the analysis to be used when preparing all subsequent queries.
37592 case OP_LoadAnalysis: { /* no-push */
37593 int iDb = pOp->p1;
37594 assert( iDb>=0 && iDb<db->nDb );
37595 rc = sqlite3AnalysisLoad(db, iDb);
37596 break;
37598 #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER) */
37600 /* Opcode: DropTable P1 * P3
37602 ** Remove the internal (in-memory) data structures that describe
37603 ** the table named P3 in database P1. This is called after a table
37604 ** is dropped in order to keep the internal representation of the
37605 ** schema consistent with what is on disk.
37607 case OP_DropTable: { /* no-push */
37608 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p3);
37609 break;
37612 /* Opcode: DropIndex P1 * P3
37614 ** Remove the internal (in-memory) data structures that describe
37615 ** the index named P3 in database P1. This is called after an index
37616 ** is dropped in order to keep the internal representation of the
37617 ** schema consistent with what is on disk.
37619 case OP_DropIndex: { /* no-push */
37620 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p3);
37621 break;
37624 /* Opcode: DropTrigger P1 * P3
37626 ** Remove the internal (in-memory) data structures that describe
37627 ** the trigger named P3 in database P1. This is called after a trigger
37628 ** is dropped in order to keep the internal representation of the
37629 ** schema consistent with what is on disk.
37631 case OP_DropTrigger: { /* no-push */
37632 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p3);
37633 break;
37637 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
37638 /* Opcode: IntegrityCk P1 P2 *
37640 ** Do an analysis of the currently open database. Push onto the
37641 ** stack the text of an error message describing any problems.
37642 ** If no problems are found, push a NULL onto the stack.
37644 ** P1 is the address of a memory cell that contains the maximum
37645 ** number of allowed errors. At most mem[P1] errors will be reported.
37646 ** In other words, the analysis stops as soon as mem[P1] errors are
37647 ** seen. Mem[P1] is updated with the number of errors remaining.
37649 ** The root page numbers of all tables in the database are integer
37650 ** values on the stack. This opcode pulls as many integers as it
37651 ** can off of the stack and uses those numbers as the root pages.
37653 ** If P2 is not zero, the check is done on the auxiliary database
37654 ** file, not the main database file.
37656 ** This opcode is used to implement the integrity_check pragma.
37658 case OP_IntegrityCk: {
37659 int nRoot;
37660 int *aRoot;
37661 int j;
37662 int nErr;
37663 char *z;
37664 Mem *pnErr;
37666 for(nRoot=0; &pTos[-nRoot]>=p->aStack; nRoot++){
37667 if( (pTos[-nRoot].flags & MEM_Int)==0 ) break;
37669 assert( nRoot>0 );
37670 aRoot = sqliteMallocRaw( sizeof(int*)*(nRoot+1) );
37671 if( aRoot==0 ) goto no_mem;
37672 j = pOp->p1;
37673 assert( j>=0 && j<p->nMem );
37674 pnErr = &p->aMem[j];
37675 assert( (pnErr->flags & MEM_Int)!=0 );
37676 for(j=0; j<nRoot; j++){
37677 Mem *pMem = &pTos[-j];
37678 aRoot[j] = pMem->u.i;
37680 aRoot[j] = 0;
37681 popStack(&pTos, nRoot);
37682 pTos++;
37683 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot,
37684 pnErr->u.i, &nErr);
37685 pnErr->u.i -= nErr;
37686 if( nErr==0 ){
37687 assert( z==0 );
37688 pTos->flags = MEM_Null;
37689 }else{
37690 pTos->z = z;
37691 pTos->n = strlen(z);
37692 pTos->flags = MEM_Str | MEM_Dyn | MEM_Term;
37693 pTos->xDel = 0;
37695 pTos->enc = SQLITE_UTF8;
37696 sqlite3VdbeChangeEncoding(pTos, encoding);
37697 sqliteFree(aRoot);
37698 break;
37700 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
37702 /* Opcode: FifoWrite * * *
37704 ** Write the integer on the top of the stack
37705 ** into the Fifo.
37707 case OP_FifoWrite: { /* no-push */
37708 assert( pTos>=p->aStack );
37709 sqlite3VdbeMemIntegerify(pTos);
37710 sqlite3VdbeFifoPush(&p->sFifo, pTos->u.i);
37711 assert( (pTos->flags & MEM_Dyn)==0 );
37712 pTos--;
37713 break;
37716 /* Opcode: FifoRead * P2 *
37718 ** Attempt to read a single integer from the Fifo
37719 ** and push it onto the stack. If the Fifo is empty
37720 ** push nothing but instead jump to P2.
37722 case OP_FifoRead: {
37723 i64 v;
37724 CHECK_FOR_INTERRUPT;
37725 if( sqlite3VdbeFifoPop(&p->sFifo, &v)==SQLITE_DONE ){
37726 pc = pOp->p2 - 1;
37727 }else{
37728 pTos++;
37729 pTos->u.i = v;
37730 pTos->flags = MEM_Int;
37732 break;
37735 #ifndef SQLITE_OMIT_TRIGGER
37736 /* Opcode: ContextPush * * *
37738 ** Save the current Vdbe context such that it can be restored by a ContextPop
37739 ** opcode. The context stores the last insert row id, the last statement change
37740 ** count, and the current statement change count.
37742 case OP_ContextPush: { /* no-push */
37743 int i = p->contextStackTop++;
37744 Context *pContext;
37746 assert( i>=0 );
37747 /* FIX ME: This should be allocated as part of the vdbe at compile-time */
37748 if( i>=p->contextStackDepth ){
37749 p->contextStackDepth = i+1;
37750 p->contextStack = sqliteReallocOrFree(p->contextStack,
37751 sizeof(Context)*(i+1));
37752 if( p->contextStack==0 ) goto no_mem;
37754 pContext = &p->contextStack[i];
37755 pContext->lastRowid = db->lastRowid;
37756 pContext->nChange = p->nChange;
37757 pContext->sFifo = p->sFifo;
37758 sqlite3VdbeFifoInit(&p->sFifo);
37759 break;
37762 /* Opcode: ContextPop * * *
37764 ** Restore the Vdbe context to the state it was in when contextPush was last
37765 ** executed. The context stores the last insert row id, the last statement
37766 ** change count, and the current statement change count.
37768 case OP_ContextPop: { /* no-push */
37769 Context *pContext = &p->contextStack[--p->contextStackTop];
37770 assert( p->contextStackTop>=0 );
37771 db->lastRowid = pContext->lastRowid;
37772 p->nChange = pContext->nChange;
37773 sqlite3VdbeFifoClear(&p->sFifo);
37774 p->sFifo = pContext->sFifo;
37775 break;
37777 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
37779 /* Opcode: MemStore P1 P2 *
37781 ** Write the top of the stack into memory location P1.
37782 ** P1 should be a small integer since space is allocated
37783 ** for all memory locations between 0 and P1 inclusive.
37785 ** After the data is stored in the memory location, the
37786 ** stack is popped once if P2 is 1. If P2 is zero, then
37787 ** the original data remains on the stack.
37789 case OP_MemStore: { /* no-push */
37790 assert( pTos>=p->aStack );
37791 assert( pOp->p1>=0 && pOp->p1<p->nMem );
37792 rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], pTos);
37793 pTos--;
37795 /* If P2 is 0 then fall thru to the next opcode, OP_MemLoad, that will
37796 ** restore the top of the stack to its original value.
37798 if( pOp->p2 ){
37799 break;
37802 /* Opcode: MemLoad P1 * *
37804 ** Push a copy of the value in memory location P1 onto the stack.
37806 ** If the value is a string, then the value pushed is a pointer to
37807 ** the string that is stored in the memory location. If the memory
37808 ** location is subsequently changed (using OP_MemStore) then the
37809 ** value pushed onto the stack will change too.
37811 case OP_MemLoad: {
37812 int i = pOp->p1;
37813 assert( i>=0 && i<p->nMem );
37814 pTos++;
37815 sqlite3VdbeMemShallowCopy(pTos, &p->aMem[i], MEM_Ephem);
37816 break;
37819 #ifndef SQLITE_OMIT_AUTOINCREMENT
37820 /* Opcode: MemMax P1 * *
37822 ** Set the value of memory cell P1 to the maximum of its current value
37823 ** and the value on the top of the stack. The stack is unchanged.
37825 ** This instruction throws an error if the memory cell is not initially
37826 ** an integer.
37828 case OP_MemMax: { /* no-push */
37829 int i = pOp->p1;
37830 Mem *pMem;
37831 assert( pTos>=p->aStack );
37832 assert( i>=0 && i<p->nMem );
37833 pMem = &p->aMem[i];
37834 sqlite3VdbeMemIntegerify(pMem);
37835 sqlite3VdbeMemIntegerify(pTos);
37836 if( pMem->u.i<pTos->u.i){
37837 pMem->u.i = pTos->u.i;
37839 break;
37841 #endif /* SQLITE_OMIT_AUTOINCREMENT */
37843 /* Opcode: MemIncr P1 P2 *
37845 ** Increment the integer valued memory cell P2 by the value in P1.
37847 ** It is illegal to use this instruction on a memory cell that does
37848 ** not contain an integer. An assertion fault will result if you try.
37850 case OP_MemIncr: { /* no-push */
37851 int i = pOp->p2;
37852 Mem *pMem;
37853 assert( i>=0 && i<p->nMem );
37854 pMem = &p->aMem[i];
37855 assert( pMem->flags==MEM_Int );
37856 pMem->u.i += pOp->p1;
37857 break;
37860 /* Opcode: IfMemPos P1 P2 *
37862 ** If the value of memory cell P1 is 1 or greater, jump to P2.
37864 ** It is illegal to use this instruction on a memory cell that does
37865 ** not contain an integer. An assertion fault will result if you try.
37867 case OP_IfMemPos: { /* no-push */
37868 int i = pOp->p1;
37869 Mem *pMem;
37870 assert( i>=0 && i<p->nMem );
37871 pMem = &p->aMem[i];
37872 assert( pMem->flags==MEM_Int );
37873 if( pMem->u.i>0 ){
37874 pc = pOp->p2 - 1;
37876 break;
37879 /* Opcode: IfMemNeg P1 P2 *
37881 ** If the value of memory cell P1 is less than zero, jump to P2.
37883 ** It is illegal to use this instruction on a memory cell that does
37884 ** not contain an integer. An assertion fault will result if you try.
37886 case OP_IfMemNeg: { /* no-push */
37887 int i = pOp->p1;
37888 Mem *pMem;
37889 assert( i>=0 && i<p->nMem );
37890 pMem = &p->aMem[i];
37891 assert( pMem->flags==MEM_Int );
37892 if( pMem->u.i<0 ){
37893 pc = pOp->p2 - 1;
37895 break;
37898 /* Opcode: IfMemZero P1 P2 *
37900 ** If the value of memory cell P1 is exactly 0, jump to P2.
37902 ** It is illegal to use this instruction on a memory cell that does
37903 ** not contain an integer. An assertion fault will result if you try.
37905 case OP_IfMemZero: { /* no-push */
37906 int i = pOp->p1;
37907 Mem *pMem;
37908 assert( i>=0 && i<p->nMem );
37909 pMem = &p->aMem[i];
37910 assert( pMem->flags==MEM_Int );
37911 if( pMem->u.i==0 ){
37912 pc = pOp->p2 - 1;
37914 break;
37917 /* Opcode: MemNull P1 * *
37919 ** Store a NULL in memory cell P1
37921 case OP_MemNull: {
37922 assert( pOp->p1>=0 && pOp->p1<p->nMem );
37923 sqlite3VdbeMemSetNull(&p->aMem[pOp->p1]);
37924 break;
37927 /* Opcode: MemInt P1 P2 *
37929 ** Store the integer value P1 in memory cell P2.
37931 case OP_MemInt: {
37932 assert( pOp->p2>=0 && pOp->p2<p->nMem );
37933 sqlite3VdbeMemSetInt64(&p->aMem[pOp->p2], pOp->p1);
37934 break;
37937 /* Opcode: MemMove P1 P2 *
37939 ** Move the content of memory cell P2 over to memory cell P1.
37940 ** Any prior content of P1 is erased. Memory cell P2 is left
37941 ** containing a NULL.
37943 case OP_MemMove: {
37944 assert( pOp->p1>=0 && pOp->p1<p->nMem );
37945 assert( pOp->p2>=0 && pOp->p2<p->nMem );
37946 rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], &p->aMem[pOp->p2]);
37947 break;
37950 /* Opcode: AggStep P1 P2 P3
37952 ** Execute the step function for an aggregate. The
37953 ** function has P2 arguments. P3 is a pointer to the FuncDef
37954 ** structure that specifies the function. Use memory location
37955 ** P1 as the accumulator.
37957 ** The P2 arguments are popped from the stack.
37959 case OP_AggStep: { /* no-push */
37960 int n = pOp->p2;
37961 int i;
37962 Mem *pMem, *pRec;
37963 sqlite3_context ctx;
37964 sqlite3_value **apVal;
37966 assert( n>=0 );
37967 pRec = &pTos[1-n];
37968 assert( pRec>=p->aStack );
37969 apVal = p->apArg;
37970 assert( apVal || n==0 );
37971 for(i=0; i<n; i++, pRec++){
37972 apVal[i] = pRec;
37973 storeTypeInfo(pRec, encoding);
37975 ctx.pFunc = (FuncDef*)pOp->p3;
37976 assert( pOp->p1>=0 && pOp->p1<p->nMem );
37977 ctx.pMem = pMem = &p->aMem[pOp->p1];
37978 pMem->n++;
37979 ctx.s.flags = MEM_Null;
37980 ctx.s.z = 0;
37981 ctx.s.xDel = 0;
37982 ctx.isError = 0;
37983 ctx.pColl = 0;
37984 if( ctx.pFunc->needCollSeq ){
37985 assert( pOp>p->aOp );
37986 assert( pOp[-1].p3type==P3_COLLSEQ );
37987 assert( pOp[-1].opcode==OP_CollSeq );
37988 ctx.pColl = (CollSeq *)pOp[-1].p3;
37990 (ctx.pFunc->xStep)(&ctx, n, apVal);
37991 popStack(&pTos, n);
37992 if( ctx.isError ){
37993 sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0);
37994 rc = SQLITE_ERROR;
37996 sqlite3VdbeMemRelease(&ctx.s);
37997 break;
38000 /* Opcode: AggFinal P1 P2 P3
38002 ** Execute the finalizer function for an aggregate. P1 is
38003 ** the memory location that is the accumulator for the aggregate.
38005 ** P2 is the number of arguments that the step function takes and
38006 ** P3 is a pointer to the FuncDef for this function. The P2
38007 ** argument is not used by this opcode. It is only there to disambiguate
38008 ** functions that can take varying numbers of arguments. The
38009 ** P3 argument is only needed for the degenerate case where
38010 ** the step function was not previously called.
38012 case OP_AggFinal: { /* no-push */
38013 Mem *pMem;
38014 assert( pOp->p1>=0 && pOp->p1<p->nMem );
38015 pMem = &p->aMem[pOp->p1];
38016 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
38017 rc = sqlite3VdbeMemFinalize(pMem, (FuncDef*)pOp->p3);
38018 if( rc==SQLITE_ERROR ){
38019 sqlite3SetString(&p->zErrMsg, sqlite3_value_text(pMem), (char*)0);
38021 if( sqlite3VdbeMemTooBig(pMem) ){
38022 goto too_big;
38024 break;
38028 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
38029 /* Opcode: Vacuum * * *
38031 ** Vacuum the entire database. This opcode will cause other virtual
38032 ** machines to be created and run. It may not be called from within
38033 ** a transaction.
38035 case OP_Vacuum: { /* no-push */
38036 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
38037 rc = sqlite3RunVacuum(&p->zErrMsg, db);
38038 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
38039 break;
38041 #endif
38043 #if !defined(SQLITE_OMIT_AUTOVACUUM)
38044 /* Opcode: IncrVacuum P1 P2 *
38046 ** Perform a single step of the incremental vacuum procedure on
38047 ** the P1 database. If the vacuum has finished, jump to instruction
38048 ** P2. Otherwise, fall through to the next instruction.
38050 case OP_IncrVacuum: { /* no-push */
38051 Btree *pBt;
38053 assert( pOp->p1>=0 && pOp->p1<db->nDb );
38054 pBt = db->aDb[pOp->p1].pBt;
38055 rc = sqlite3BtreeIncrVacuum(pBt);
38056 if( rc==SQLITE_DONE ){
38057 pc = pOp->p2 - 1;
38058 rc = SQLITE_OK;
38060 break;
38062 #endif
38064 /* Opcode: Expire P1 * *
38066 ** Cause precompiled statements to become expired. An expired statement
38067 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
38068 ** (via sqlite3_step()).
38070 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
38071 ** then only the currently executing statement is affected.
38073 case OP_Expire: { /* no-push */
38074 if( !pOp->p1 ){
38075 sqlite3ExpirePreparedStatements(db);
38076 }else{
38077 p->expired = 1;
38079 break;
38082 #ifndef SQLITE_OMIT_SHARED_CACHE
38083 /* Opcode: TableLock P1 P2 P3
38085 ** Obtain a lock on a particular table. This instruction is only used when
38086 ** the shared-cache feature is enabled.
38088 ** If P1 is not negative, then it is the index of the database
38089 ** in sqlite3.aDb[] and a read-lock is required. If P1 is negative, a
38090 ** write-lock is required. In this case the index of the database is the
38091 ** absolute value of P1 minus one (iDb = abs(P1) - 1;) and a write-lock is
38092 ** required.
38094 ** P2 contains the root-page of the table to lock.
38096 ** P3 contains a pointer to the name of the table being locked. This is only
38097 ** used to generate an error message if the lock cannot be obtained.
38099 case OP_TableLock: { /* no-push */
38100 int p1 = pOp->p1;
38101 u8 isWriteLock = (p1<0);
38102 if( isWriteLock ){
38103 p1 = (-1*p1)-1;
38105 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
38106 if( rc==SQLITE_LOCKED ){
38107 const char *z = (const char *)pOp->p3;
38108 sqlite3SetString(&p->zErrMsg, "database table is locked: ", z, (char*)0);
38110 break;
38112 #endif /* SQLITE_OMIT_SHARED_CACHE */
38114 #ifndef SQLITE_OMIT_VIRTUALTABLE
38115 /* Opcode: VBegin * * P3
38117 ** P3 a pointer to an sqlite3_vtab structure. Call the xBegin method
38118 ** for that table.
38120 case OP_VBegin: { /* no-push */
38121 rc = sqlite3VtabBegin(db, (sqlite3_vtab *)pOp->p3);
38122 break;
38124 #endif /* SQLITE_OMIT_VIRTUALTABLE */
38126 #ifndef SQLITE_OMIT_VIRTUALTABLE
38127 /* Opcode: VCreate P1 * P3
38129 ** P3 is the name of a virtual table in database P1. Call the xCreate method
38130 ** for that table.
38132 case OP_VCreate: { /* no-push */
38133 rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p3, &p->zErrMsg);
38134 break;
38136 #endif /* SQLITE_OMIT_VIRTUALTABLE */
38138 #ifndef SQLITE_OMIT_VIRTUALTABLE
38139 /* Opcode: VDestroy P1 * P3
38141 ** P3 is the name of a virtual table in database P1. Call the xDestroy method
38142 ** of that table.
38144 case OP_VDestroy: { /* no-push */
38145 p->inVtabMethod = 2;
38146 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p3);
38147 p->inVtabMethod = 0;
38148 break;
38150 #endif /* SQLITE_OMIT_VIRTUALTABLE */
38152 #ifndef SQLITE_OMIT_VIRTUALTABLE
38153 /* Opcode: VOpen P1 * P3
38155 ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
38156 ** P1 is a cursor number. This opcode opens a cursor to the virtual
38157 ** table and stores that cursor in P1.
38159 case OP_VOpen: { /* no-push */
38160 Cursor *pCur = 0;
38161 sqlite3_vtab_cursor *pVtabCursor = 0;
38163 sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
38164 sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
38166 assert(pVtab && pModule);
38167 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
38168 rc = pModule->xOpen(pVtab, &pVtabCursor);
38169 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
38170 if( SQLITE_OK==rc ){
38171 /* Initialise sqlite3_vtab_cursor base class */
38172 pVtabCursor->pVtab = pVtab;
38174 /* Initialise vdbe cursor object */
38175 pCur = allocateCursor(p, pOp->p1, -1);
38176 if( pCur ){
38177 pCur->pVtabCursor = pVtabCursor;
38178 pCur->pModule = pVtabCursor->pVtab->pModule;
38179 }else{
38180 pModule->xClose(pVtabCursor);
38183 break;
38185 #endif /* SQLITE_OMIT_VIRTUALTABLE */
38187 #ifndef SQLITE_OMIT_VIRTUALTABLE
38188 /* Opcode: VFilter P1 P2 P3
38190 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
38191 ** the filtered result set is empty.
38193 ** P3 is either NULL or a string that was generated by the xBestIndex
38194 ** method of the module. The interpretation of the P3 string is left
38195 ** to the module implementation.
38197 ** This opcode invokes the xFilter method on the virtual table specified
38198 ** by P1. The integer query plan parameter to xFilter is the top of the
38199 ** stack. Next down on the stack is the argc parameter. Beneath the
38200 ** next of stack are argc additional parameters which are passed to
38201 ** xFilter as argv. The topmost parameter (i.e. 3rd element popped from
38202 ** the stack) becomes argv[argc-1] when passed to xFilter.
38204 ** The integer query plan parameter, argc, and all argv stack values
38205 ** are popped from the stack before this instruction completes.
38207 ** A jump is made to P2 if the result set after filtering would be
38208 ** empty.
38210 case OP_VFilter: { /* no-push */
38211 int nArg;
38213 const sqlite3_module *pModule;
38215 Cursor *pCur = p->apCsr[pOp->p1];
38216 assert( pCur->pVtabCursor );
38217 pModule = pCur->pVtabCursor->pVtab->pModule;
38219 /* Grab the index number and argc parameters off the top of the stack. */
38220 assert( (&pTos[-1])>=p->aStack );
38221 assert( (pTos[0].flags&MEM_Int)!=0 && pTos[-1].flags==MEM_Int );
38222 nArg = pTos[-1].u.i;
38224 /* Invoke the xFilter method */
38226 int res = 0;
38227 int i;
38228 Mem **apArg = p->apArg;
38229 for(i = 0; i<nArg; i++){
38230 apArg[i] = &pTos[i+1-2-nArg];
38231 storeTypeInfo(apArg[i], 0);
38234 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
38235 p->inVtabMethod = 1;
38236 rc = pModule->xFilter(pCur->pVtabCursor, pTos->u.i, pOp->p3, nArg, apArg);
38237 p->inVtabMethod = 0;
38238 if( rc==SQLITE_OK ){
38239 res = pModule->xEof(pCur->pVtabCursor);
38241 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
38243 if( res ){
38244 pc = pOp->p2 - 1;
38248 /* Pop the index number, argc value and parameters off the stack */
38249 popStack(&pTos, 2+nArg);
38250 break;
38252 #endif /* SQLITE_OMIT_VIRTUALTABLE */
38254 #ifndef SQLITE_OMIT_VIRTUALTABLE
38255 /* Opcode: VRowid P1 * *
38257 ** Push an integer onto the stack which is the rowid of
38258 ** the virtual-table that the P1 cursor is pointing to.
38260 case OP_VRowid: {
38261 const sqlite3_module *pModule;
38263 Cursor *pCur = p->apCsr[pOp->p1];
38264 assert( pCur->pVtabCursor );
38265 pModule = pCur->pVtabCursor->pVtab->pModule;
38266 if( pModule->xRowid==0 ){
38267 sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xRowid", 0);
38268 rc = SQLITE_ERROR;
38269 } else {
38270 sqlite_int64 iRow;
38272 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
38273 rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
38274 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
38276 pTos++;
38277 pTos->flags = MEM_Int;
38278 pTos->u.i = iRow;
38281 break;
38283 #endif /* SQLITE_OMIT_VIRTUALTABLE */
38285 #ifndef SQLITE_OMIT_VIRTUALTABLE
38286 /* Opcode: VColumn P1 P2 *
38288 ** Push onto the stack the value of the P2-th column of
38289 ** the row of the virtual-table that the P1 cursor is pointing to.
38291 case OP_VColumn: {
38292 const sqlite3_module *pModule;
38294 Cursor *pCur = p->apCsr[pOp->p1];
38295 assert( pCur->pVtabCursor );
38296 pModule = pCur->pVtabCursor->pVtab->pModule;
38297 if( pModule->xColumn==0 ){
38298 sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xColumn", 0);
38299 rc = SQLITE_ERROR;
38300 } else {
38301 sqlite3_context sContext;
38302 memset(&sContext, 0, sizeof(sContext));
38303 sContext.s.flags = MEM_Null;
38304 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
38305 rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
38307 /* Copy the result of the function to the top of the stack. We
38308 ** do this regardless of whether or not an error occured to ensure any
38309 ** dynamic allocation in sContext.s (a Mem struct) is released.
38311 sqlite3VdbeChangeEncoding(&sContext.s, encoding);
38312 pTos++;
38313 pTos->flags = 0;
38314 sqlite3VdbeMemMove(pTos, &sContext.s);
38316 if( sqlite3SafetyOn(db) ){
38317 goto abort_due_to_misuse;
38319 if( sqlite3VdbeMemTooBig(pTos) ){
38320 goto too_big;
38324 break;
38326 #endif /* SQLITE_OMIT_VIRTUALTABLE */
38328 #ifndef SQLITE_OMIT_VIRTUALTABLE
38329 /* Opcode: VNext P1 P2 *
38331 ** Advance virtual table P1 to the next row in its result set and
38332 ** jump to instruction P2. Or, if the virtual table has reached
38333 ** the end of its result set, then fall through to the next instruction.
38335 case OP_VNext: { /* no-push */
38336 const sqlite3_module *pModule;
38337 int res = 0;
38339 Cursor *pCur = p->apCsr[pOp->p1];
38340 assert( pCur->pVtabCursor );
38341 pModule = pCur->pVtabCursor->pVtab->pModule;
38342 if( pModule->xNext==0 ){
38343 sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xNext", 0);
38344 rc = SQLITE_ERROR;
38345 } else {
38346 /* Invoke the xNext() method of the module. There is no way for the
38347 ** underlying implementation to return an error if one occurs during
38348 ** xNext(). Instead, if an error occurs, true is returned (indicating that
38349 ** data is available) and the error code returned when xColumn or
38350 ** some other method is next invoked on the save virtual table cursor.
38352 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
38353 p->inVtabMethod = 1;
38354 rc = pModule->xNext(pCur->pVtabCursor);
38355 p->inVtabMethod = 0;
38356 if( rc==SQLITE_OK ){
38357 res = pModule->xEof(pCur->pVtabCursor);
38359 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
38361 if( !res ){
38362 /* If there is data, jump to P2 */
38363 pc = pOp->p2 - 1;
38367 break;
38369 #endif /* SQLITE_OMIT_VIRTUALTABLE */
38372 #ifndef SQLITE_OMIT_VIRTUALTABLE
38373 /* Opcode: VUpdate P1 P2 P3
38375 ** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
38376 ** This opcode invokes the corresponding xUpdate method. P2 values
38377 ** are taken from the stack to pass to the xUpdate invocation. The
38378 ** value on the top of the stack corresponds to the p2th element
38379 ** of the argv array passed to xUpdate.
38381 ** The xUpdate method will do a DELETE or an INSERT or both.
38382 ** The argv[0] element (which corresponds to the P2-th element down
38383 ** on the stack) is the rowid of a row to delete. If argv[0] is
38384 ** NULL then no deletion occurs. The argv[1] element is the rowid
38385 ** of the new row. This can be NULL to have the virtual table
38386 ** select the new rowid for itself. The higher elements in the
38387 ** stack are the values of columns in the new row.
38389 ** If P2==1 then no insert is performed. argv[0] is the rowid of
38390 ** a row to delete.
38392 ** P1 is a boolean flag. If it is set to true and the xUpdate call
38393 ** is successful, then the value returned by sqlite3_last_insert_rowid()
38394 ** is set to the value of the rowid for the row just inserted.
38396 case OP_VUpdate: { /* no-push */
38397 sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
38398 sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
38399 int nArg = pOp->p2;
38400 assert( pOp->p3type==P3_VTAB );
38401 if( pModule->xUpdate==0 ){
38402 sqlite3SetString(&p->zErrMsg, "read-only table", 0);
38403 rc = SQLITE_ERROR;
38404 }else{
38405 int i;
38406 sqlite_int64 rowid;
38407 Mem **apArg = p->apArg;
38408 Mem *pX = &pTos[1-nArg];
38409 for(i = 0; i<nArg; i++, pX++){
38410 storeTypeInfo(pX, 0);
38411 apArg[i] = pX;
38413 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
38414 sqlite3VtabLock(pVtab);
38415 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
38416 sqlite3VtabUnlock(db, pVtab);
38417 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
38418 if( pOp->p1 && rc==SQLITE_OK ){
38419 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
38420 db->lastRowid = rowid;
38423 popStack(&pTos, nArg);
38424 break;
38426 #endif /* SQLITE_OMIT_VIRTUALTABLE */
38428 /* An other opcode is illegal...
38430 default: {
38431 assert( 0 );
38432 break;
38435 /*****************************************************************************
38436 ** The cases of the switch statement above this line should all be indented
38437 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
38438 ** readability. From this point on down, the normal indentation rules are
38439 ** restored.
38440 *****************************************************************************/
38443 /* Make sure the stack limit was not exceeded */
38444 assert( pTos<=pStackLimit );
38446 #ifdef VDBE_PROFILE
38448 long long elapse = hwtime() - start;
38449 pOp->cycles += elapse;
38450 pOp->cnt++;
38451 #if 0
38452 fprintf(stdout, "%10lld ", elapse);
38453 sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
38454 #endif
38456 #endif
38458 #ifdef SQLITE_TEST
38459 /* Keep track of the size of the largest BLOB or STR that has appeared
38460 ** on the top of the VDBE stack.
38462 if( pTos>=p->aStack && (pTos->flags & (MEM_Blob|MEM_Str))!=0
38463 && pTos->n>sqlite3_max_blobsize ){
38464 sqlite3_max_blobsize = pTos->n;
38466 #endif
38468 /* The following code adds nothing to the actual functionality
38469 ** of the program. It is only here for testing and debugging.
38470 ** On the other hand, it does burn CPU cycles every time through
38471 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
38473 #ifndef NDEBUG
38474 /* Sanity checking on the top element of the stack. If the previous
38475 ** instruction was VNoChange, then the flags field of the top
38476 ** of the stack is set to 0. This is technically invalid for a memory
38477 ** cell, so avoid calling MemSanity() in this case.
38479 if( pTos>=p->aStack && pTos->flags ){
38480 sqlite3VdbeMemSanity(pTos);
38481 assert( !sqlite3VdbeMemTooBig(pTos) );
38483 assert( pc>=-1 && pc<p->nOp );
38485 #ifdef SQLITE_DEBUG
38486 /* Code for tracing the vdbe stack. */
38487 if( p->trace && pTos>=p->aStack ){
38488 int i;
38489 fprintf(p->trace, "Stack:");
38490 for(i=0; i>-5 && &pTos[i]>=p->aStack; i--){
38491 if( pTos[i].flags & MEM_Null ){
38492 fprintf(p->trace, " NULL");
38493 }else if( (pTos[i].flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
38494 fprintf(p->trace, " si:%lld", pTos[i].u.i);
38495 }else if( pTos[i].flags & MEM_Int ){
38496 fprintf(p->trace, " i:%lld", pTos[i].u.i);
38497 }else if( pTos[i].flags & MEM_Real ){
38498 fprintf(p->trace, " r:%g", pTos[i].r);
38499 }else{
38500 char zBuf[200];
38501 sqlite3VdbeMemPrettyPrint(&pTos[i], zBuf);
38502 fprintf(p->trace, " ");
38503 fprintf(p->trace, "%s", zBuf);
38506 if( rc!=0 ) fprintf(p->trace," rc=%d",rc);
38507 fprintf(p->trace,"\n");
38509 #endif /* SQLITE_DEBUG */
38510 #endif /* NDEBUG */
38511 } /* The end of the for(;;) loop the loops through opcodes */
38513 /* If we reach this point, it means that execution is finished.
38515 vdbe_halt:
38516 if( rc ){
38517 p->rc = rc;
38518 rc = SQLITE_ERROR;
38519 }else{
38520 rc = SQLITE_DONE;
38522 sqlite3VdbeHalt(p);
38523 p->pTos = pTos;
38524 return rc;
38526 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
38527 ** is encountered.
38529 too_big:
38530 sqlite3SetString(&p->zErrMsg, "string or blob too big", (char*)0);
38531 rc = SQLITE_TOOBIG;
38532 goto vdbe_halt;
38534 /* Jump to here if a malloc() fails.
38536 no_mem:
38537 sqlite3SetString(&p->zErrMsg, "out of memory", (char*)0);
38538 rc = SQLITE_NOMEM;
38539 goto vdbe_halt;
38541 /* Jump to here for an SQLITE_MISUSE error.
38543 abort_due_to_misuse:
38544 rc = SQLITE_MISUSE;
38545 /* Fall thru into abort_due_to_error */
38547 /* Jump to here for any other kind of fatal error. The "rc" variable
38548 ** should hold the error number.
38550 abort_due_to_error:
38551 if( p->zErrMsg==0 ){
38552 if( sqlite3MallocFailed() ) rc = SQLITE_NOMEM;
38553 sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
38555 goto vdbe_halt;
38557 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
38558 ** flag.
38560 abort_due_to_interrupt:
38561 assert( db->u1.isInterrupted );
38562 if( db->magic!=SQLITE_MAGIC_BUSY ){
38563 rc = SQLITE_MISUSE;
38564 }else{
38565 rc = SQLITE_INTERRUPT;
38567 p->rc = rc;
38568 sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
38569 goto vdbe_halt;
38572 /************** End of vdbe.c ************************************************/
38573 /************** Begin file vdbeblob.c ****************************************/
38575 ** 2007 May 1
38577 ** The author disclaims copyright to this source code. In place of
38578 ** a legal notice, here is a blessing:
38580 ** May you do good and not evil.
38581 ** May you find forgiveness for yourself and forgive others.
38582 ** May you share freely, never taking more than you give.
38584 *************************************************************************
38586 ** This file contains code used to implement incremental BLOB I/O.
38588 ** $Id: vdbeblob.c,v 1.10 2007/05/08 20:37:40 drh Exp $
38592 #ifndef SQLITE_OMIT_INCRBLOB
38595 ** Valid sqlite3_blob* handles point to Incrblob structures.
38597 typedef struct Incrblob Incrblob;
38598 struct Incrblob {
38599 int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
38600 int nByte; /* Size of open blob, in bytes */
38601 int iOffset; /* Byte offset of blob in cursor data */
38602 BtCursor *pCsr; /* Cursor pointing at blob row */
38603 sqlite3_stmt *pStmt; /* Statement holding cursor open */
38607 ** Open a blob handle.
38609 int sqlite3_blob_open(
38610 sqlite3* db, /* The database connection */
38611 const char *zDb, /* The attached database containing the blob */
38612 const char *zTable, /* The table containing the blob */
38613 const char *zColumn, /* The column containing the blob */
38614 sqlite_int64 iRow, /* The row containing the glob */
38615 int flags, /* True -> read/write access, false -> read-only */
38616 sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
38618 int nAttempt = 0;
38619 int iCol; /* Index of zColumn in row-record */
38621 /* This VDBE program seeks a btree cursor to the identified
38622 ** db/table/row entry. The reason for using a vdbe program instead
38623 ** of writing code to use the b-tree layer directly is that the
38624 ** vdbe program will take advantage of the various transaction,
38625 ** locking and error handling infrastructure built into the vdbe.
38627 ** After seeking the cursor, the vdbe executes an OP_Callback.
38628 ** Code external to the Vdbe then "borrows" the b-tree cursor and
38629 ** uses it to implement the blob_read(), blob_write() and
38630 ** blob_bytes() functions.
38632 ** The sqlite3_blob_close() function finalizes the vdbe program,
38633 ** which closes the b-tree cursor and (possibly) commits the
38634 ** transaction.
38636 static const VdbeOpList openBlob[] = {
38637 {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
38638 {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
38639 {OP_Integer, 0, 0, 0}, /* 2: Database number */
38641 /* One of the following two instructions is replaced by an
38642 ** OP_Noop before exection.
38644 {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
38645 {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
38646 {OP_SetNumColumns, 0, 0, 0}, /* 5: Num cols for cursor */
38648 {OP_Variable, 1, 0, 0}, /* 6: Push the rowid to the stack */
38649 {OP_NotExists, 0, 10, 0}, /* 7: Seek the cursor */
38650 {OP_Column, 0, 0, 0}, /* 8 */
38651 {OP_Callback, 0, 0, 0}, /* 9 */
38652 {OP_Close, 0, 0, 0}, /* 10 */
38653 {OP_Halt, 0, 0, 0}, /* 11 */
38656 Vdbe *v = 0;
38657 int rc = SQLITE_OK;
38658 char zErr[128];
38660 zErr[0] = 0;
38661 do {
38662 Parse sParse;
38663 Table *pTab;
38665 memset(&sParse, 0, sizeof(Parse));
38666 sParse.db = db;
38668 rc = sqlite3SafetyOn(db);
38669 if( rc!=SQLITE_OK ){
38670 return rc;
38673 pTab = sqlite3LocateTable(&sParse, zTable, zDb);
38674 if( !pTab ){
38675 if( sParse.zErrMsg ){
38676 sqlite3_snprintf(sizeof(zErr), zErr, "%s", sParse.zErrMsg);
38678 sqliteFree(sParse.zErrMsg);
38679 rc = SQLITE_ERROR;
38680 sqlite3SafetyOff(db);
38681 goto blob_open_out;
38684 /* Now search pTab for the exact column. */
38685 for(iCol=0; iCol < pTab->nCol; iCol++) {
38686 if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
38687 break;
38690 if( iCol==pTab->nCol ){
38691 sqlite3_snprintf(sizeof(zErr), zErr, "no such column: \"%s\"", zColumn);
38692 rc = SQLITE_ERROR;
38693 sqlite3SafetyOff(db);
38694 goto blob_open_out;
38697 /* If the value is being opened for writing, check that the
38698 ** column is not indexed. It is against the rules to open an
38699 ** indexed column for writing.
38701 if( flags ){
38702 Index *pIdx;
38703 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
38704 int j;
38705 for(j=0; j<pIdx->nColumn; j++){
38706 if( pIdx->aiColumn[j]==iCol ){
38707 sqlite3_snprintf(sizeof(zErr), zErr,
38708 "cannot open indexed column for writing");
38709 rc = SQLITE_ERROR;
38710 sqlite3SafetyOff(db);
38711 goto blob_open_out;
38717 v = sqlite3VdbeCreate(db);
38718 if( v ){
38719 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
38720 sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
38722 /* Configure the OP_Transaction */
38723 sqlite3VdbeChangeP1(v, 0, iDb);
38724 sqlite3VdbeChangeP2(v, 0, (flags ? 1 : 0));
38726 /* Configure the OP_VerifyCookie */
38727 sqlite3VdbeChangeP1(v, 1, iDb);
38728 sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
38730 /* Configure the db number pushed onto the stack */
38731 sqlite3VdbeChangeP1(v, 2, iDb);
38733 /* Remove either the OP_OpenWrite or OpenRead. Set the P2
38734 ** parameter of the other to pTab->tnum.
38736 sqlite3VdbeChangeToNoop(v, (flags ? 3 : 4), 1);
38737 sqlite3VdbeChangeP2(v, (flags ? 4 : 3), pTab->tnum);
38739 /* Configure the OP_SetNumColumns. Configure the cursor to
38740 ** think that the table has one more column than it really
38741 ** does. An OP_Column to retrieve this imaginary column will
38742 ** always return an SQL NULL. This is useful because it means
38743 ** we can invoke OP_Column to fill in the vdbe cursors type
38744 ** and offset cache without causing any IO.
38746 sqlite3VdbeChangeP2(v, 5, pTab->nCol+1);
38747 if( !sqlite3MallocFailed() ){
38748 sqlite3VdbeMakeReady(v, 1, 0, 1, 0);
38752 rc = sqlite3SafetyOff(db);
38753 if( rc!=SQLITE_OK || sqlite3MallocFailed() ){
38754 goto blob_open_out;
38757 sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
38758 rc = sqlite3_step((sqlite3_stmt *)v);
38759 if( rc!=SQLITE_ROW ){
38760 nAttempt++;
38761 rc = sqlite3_finalize((sqlite3_stmt *)v);
38762 sqlite3_snprintf(sizeof(zErr), zErr, sqlite3_errmsg(db));
38763 v = 0;
38765 } while( nAttempt<5 && rc==SQLITE_SCHEMA );
38767 if( rc==SQLITE_ROW ){
38768 /* The row-record has been opened successfully. Check that the
38769 ** column in question contains text or a blob. If it contains
38770 ** text, it is up to the caller to get the encoding right.
38772 Incrblob *pBlob;
38773 u32 type = v->apCsr[0]->aType[iCol];
38775 if( type<12 ){
38776 sqlite3_snprintf(sizeof(zErr), zErr, "cannot open value of type %s",
38777 type==0?"null": type==7?"real": "integer"
38779 rc = SQLITE_ERROR;
38780 goto blob_open_out;
38782 pBlob = (Incrblob *)sqliteMalloc(sizeof(Incrblob));
38783 if( sqlite3MallocFailed() ){
38784 sqliteFree(pBlob);
38785 goto blob_open_out;
38787 pBlob->flags = flags;
38788 pBlob->pCsr = v->apCsr[0]->pCursor;
38789 sqlite3BtreeCacheOverflow(pBlob->pCsr);
38790 pBlob->pStmt = (sqlite3_stmt *)v;
38791 pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
38792 pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
38793 *ppBlob = (sqlite3_blob *)pBlob;
38794 rc = SQLITE_OK;
38795 }else if( rc==SQLITE_OK ){
38796 sqlite3_snprintf(sizeof(zErr), zErr, "no such rowid: %lld", iRow);
38797 rc = SQLITE_ERROR;
38800 blob_open_out:
38801 zErr[sizeof(zErr)-1] = '\0';
38802 if( rc!=SQLITE_OK || sqlite3MallocFailed() ){
38803 sqlite3_finalize((sqlite3_stmt *)v);
38805 sqlite3Error(db, rc, (rc==SQLITE_OK?0:zErr));
38806 return sqlite3ApiExit(db, rc);
38810 ** Close a blob handle that was previously created using
38811 ** sqlite3_blob_open().
38813 int sqlite3_blob_close(sqlite3_blob *pBlob){
38814 Incrblob *p = (Incrblob *)pBlob;
38815 sqlite3_stmt *pStmt = p->pStmt;
38816 sqliteFree(p);
38817 return sqlite3_finalize(pStmt);
38821 static int blobReadWrite(
38822 sqlite3_blob *pBlob,
38823 void *z,
38824 int n,
38825 int iOffset,
38826 int (*xCall)(BtCursor*, u32, u32, void*)
38828 int rc;
38829 Incrblob *p = (Incrblob *)pBlob;
38830 Vdbe *v = (Vdbe *)(p->pStmt);
38831 sqlite3 *db;
38833 /* If there is no statement handle, then the blob-handle has
38834 ** already been invalidated. Return SQLITE_ABORT in this case.
38836 if( !v ) return SQLITE_ABORT;
38838 /* Request is out of range. Return a transient error. */
38839 if( (iOffset+n)>p->nByte ){
38840 return SQLITE_ERROR;
38843 /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
38844 ** returned, clean-up the statement handle.
38846 db = v->db;
38847 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
38848 if( rc==SQLITE_ABORT ){
38849 sqlite3VdbeFinalize(v);
38850 p->pStmt = 0;
38851 }else{
38852 v->rc = rc;
38855 return sqlite3ApiExit(db, rc);
38859 ** Read data from a blob handle.
38861 int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
38862 return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
38866 ** Write data to a blob handle.
38868 int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
38869 return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
38873 ** Query a blob handle for the size of the data.
38875 int sqlite3_blob_bytes(sqlite3_blob *pBlob){
38876 Incrblob *p = (Incrblob *)pBlob;
38877 return p->nByte;
38880 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
38882 /************** End of vdbeblob.c ********************************************/
38883 /************** Begin file expr.c ********************************************/
38885 ** 2001 September 15
38887 ** The author disclaims copyright to this source code. In place of
38888 ** a legal notice, here is a blessing:
38890 ** May you do good and not evil.
38891 ** May you find forgiveness for yourself and forgive others.
38892 ** May you share freely, never taking more than you give.
38894 *************************************************************************
38895 ** This file contains routines used for analyzing expressions and
38896 ** for generating VDBE code that evaluates expressions in SQLite.
38898 ** $Id: expr.c,v 1.298 2007/06/15 16:37:29 danielk1977 Exp $
38902 ** Return the 'affinity' of the expression pExpr if any.
38904 ** If pExpr is a column, a reference to a column via an 'AS' alias,
38905 ** or a sub-select with a column as the return value, then the
38906 ** affinity of that column is returned. Otherwise, 0x00 is returned,
38907 ** indicating no affinity for the expression.
38909 ** i.e. the WHERE clause expresssions in the following statements all
38910 ** have an affinity:
38912 ** CREATE TABLE t1(a);
38913 ** SELECT * FROM t1 WHERE a;
38914 ** SELECT a AS b FROM t1 WHERE b;
38915 ** SELECT * FROM t1 WHERE (select a from t1);
38917 static char sqlite3ExprAffinity(Expr *pExpr){
38918 int op = pExpr->op;
38919 if( op==TK_SELECT ){
38920 return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
38922 #ifndef SQLITE_OMIT_CAST
38923 if( op==TK_CAST ){
38924 return sqlite3AffinityType(&pExpr->token);
38926 #endif
38927 return pExpr->affinity;
38931 ** Set the collating sequence for expression pExpr to be the collating
38932 ** sequence named by pToken. Return a pointer to the revised expression.
38933 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
38934 ** flag. An explicit collating sequence will override implicit
38935 ** collating sequences.
38937 static Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
38938 CollSeq *pColl;
38939 if( pExpr==0 ) return 0;
38940 pColl = sqlite3LocateCollSeq(pParse, (char*)pName->z, pName->n);
38941 if( pColl ){
38942 pExpr->pColl = pColl;
38943 pExpr->flags |= EP_ExpCollate;
38945 return pExpr;
38949 ** Return the default collation sequence for the expression pExpr. If
38950 ** there is no default collation type, return 0.
38952 static CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
38953 CollSeq *pColl = 0;
38954 if( pExpr ){
38955 pColl = pExpr->pColl;
38956 if( pExpr->op==TK_CAST && !pColl ){
38957 return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
38960 if( sqlite3CheckCollSeq(pParse, pColl) ){
38961 pColl = 0;
38963 return pColl;
38967 ** pExpr is an operand of a comparison operator. aff2 is the
38968 ** type affinity of the other operand. This routine returns the
38969 ** type affinity that should be used for the comparison operator.
38971 static char sqlite3CompareAffinity(Expr *pExpr, char aff2){
38972 char aff1 = sqlite3ExprAffinity(pExpr);
38973 if( aff1 && aff2 ){
38974 /* Both sides of the comparison are columns. If one has numeric
38975 ** affinity, use that. Otherwise use no affinity.
38977 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
38978 return SQLITE_AFF_NUMERIC;
38979 }else{
38980 return SQLITE_AFF_NONE;
38982 }else if( !aff1 && !aff2 ){
38983 /* Neither side of the comparison is a column. Compare the
38984 ** results directly.
38986 return SQLITE_AFF_NONE;
38987 }else{
38988 /* One side is a column, the other is not. Use the columns affinity. */
38989 assert( aff1==0 || aff2==0 );
38990 return (aff1 + aff2);
38995 ** pExpr is a comparison operator. Return the type affinity that should
38996 ** be applied to both operands prior to doing the comparison.
38998 static char comparisonAffinity(Expr *pExpr){
38999 char aff;
39000 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
39001 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
39002 pExpr->op==TK_NE );
39003 assert( pExpr->pLeft );
39004 aff = sqlite3ExprAffinity(pExpr->pLeft);
39005 if( pExpr->pRight ){
39006 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
39008 else if( pExpr->pSelect ){
39009 aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
39011 else if( !aff ){
39012 aff = SQLITE_AFF_NONE;
39014 return aff;
39018 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
39019 ** idx_affinity is the affinity of an indexed column. Return true
39020 ** if the index with affinity idx_affinity may be used to implement
39021 ** the comparison in pExpr.
39023 static int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
39024 char aff = comparisonAffinity(pExpr);
39025 switch( aff ){
39026 case SQLITE_AFF_NONE:
39027 return 1;
39028 case SQLITE_AFF_TEXT:
39029 return idx_affinity==SQLITE_AFF_TEXT;
39030 default:
39031 return sqlite3IsNumericAffinity(idx_affinity);
39036 ** Return the P1 value that should be used for a binary comparison
39037 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
39038 ** If jumpIfNull is true, then set the low byte of the returned
39039 ** P1 value to tell the opcode to jump if either expression
39040 ** evaluates to NULL.
39042 static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
39043 char aff = sqlite3ExprAffinity(pExpr2);
39044 return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0);
39048 ** Return a pointer to the collation sequence that should be used by
39049 ** a binary comparison operator comparing pLeft and pRight.
39051 ** If the left hand expression has a collating sequence type, then it is
39052 ** used. Otherwise the collation sequence for the right hand expression
39053 ** is used, or the default (BINARY) if neither expression has a collating
39054 ** type.
39056 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
39057 ** it is not considered.
39059 CollSeq* sqlite3BinaryCompareCollSeq(
39060 Parse *pParse,
39061 Expr *pLeft,
39062 Expr *pRight
39064 CollSeq *pColl;
39065 assert( pLeft );
39066 if( pLeft->flags & EP_ExpCollate ){
39067 assert( pLeft->pColl );
39068 pColl = pLeft->pColl;
39069 }else if( pRight && pRight->flags & EP_ExpCollate ){
39070 assert( pRight->pColl );
39071 pColl = pRight->pColl;
39072 }else{
39073 pColl = sqlite3ExprCollSeq(pParse, pLeft);
39074 if( !pColl ){
39075 pColl = sqlite3ExprCollSeq(pParse, pRight);
39078 return pColl;
39082 ** Generate code for a comparison operator.
39084 static int codeCompare(
39085 Parse *pParse, /* The parsing (and code generating) context */
39086 Expr *pLeft, /* The left operand */
39087 Expr *pRight, /* The right operand */
39088 int opcode, /* The comparison opcode */
39089 int dest, /* Jump here if true. */
39090 int jumpIfNull /* If true, jump if either operand is NULL */
39092 int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
39093 CollSeq *p3 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
39094 return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ);
39098 ** Construct a new expression node and return a pointer to it. Memory
39099 ** for this node is obtained from sqliteMalloc(). The calling function
39100 ** is responsible for making sure the node eventually gets freed.
39102 static Expr *sqlite3Expr(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
39103 Expr *pNew;
39104 pNew = sqliteMalloc( sizeof(Expr) );
39105 if( pNew==0 ){
39106 /* When malloc fails, delete pLeft and pRight. Expressions passed to
39107 ** this function must always be allocated with sqlite3Expr() for this
39108 ** reason.
39110 sqlite3ExprDelete(pLeft);
39111 sqlite3ExprDelete(pRight);
39112 return 0;
39114 pNew->op = op;
39115 pNew->pLeft = pLeft;
39116 pNew->pRight = pRight;
39117 pNew->iAgg = -1;
39118 if( pToken ){
39119 assert( pToken->dyn==0 );
39120 pNew->span = pNew->token = *pToken;
39121 }else if( pLeft ){
39122 if( pRight ){
39123 sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
39124 if( pRight->flags & EP_ExpCollate ){
39125 pNew->flags |= EP_ExpCollate;
39126 pNew->pColl = pRight->pColl;
39129 if( pLeft->flags & EP_ExpCollate ){
39130 pNew->flags |= EP_ExpCollate;
39131 pNew->pColl = pLeft->pColl;
39135 sqlite3ExprSetHeight(pNew);
39136 return pNew;
39140 ** Works like sqlite3Expr() but frees its pLeft and pRight arguments
39141 ** if it fails due to a malloc problem.
39143 static Expr *sqlite3ExprOrFree(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
39144 Expr *pNew = sqlite3Expr(op, pLeft, pRight, pToken);
39145 if( pNew==0 ){
39146 sqlite3ExprDelete(pLeft);
39147 sqlite3ExprDelete(pRight);
39149 return pNew;
39153 ** When doing a nested parse, you can include terms in an expression
39154 ** that look like this: #0 #1 #2 ... These terms refer to elements
39155 ** on the stack. "#0" means the top of the stack.
39156 ** "#1" means the next down on the stack. And so forth.
39158 ** This routine is called by the parser to deal with on of those terms.
39159 ** It immediately generates code to store the value in a memory location.
39160 ** The returns an expression that will code to extract the value from
39161 ** that memory location as needed.
39163 static Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
39164 Vdbe *v = pParse->pVdbe;
39165 Expr *p;
39166 int depth;
39167 if( pParse->nested==0 ){
39168 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
39169 return sqlite3Expr(TK_NULL, 0, 0, 0);
39171 if( v==0 ) return 0;
39172 p = sqlite3Expr(TK_REGISTER, 0, 0, pToken);
39173 if( p==0 ){
39174 return 0; /* Malloc failed */
39176 depth = atoi((char*)&pToken->z[1]);
39177 p->iTable = pParse->nMem++;
39178 sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
39179 sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
39180 return p;
39184 ** Join two expressions using an AND operator. If either expression is
39185 ** NULL, then just return the other expression.
39187 static Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
39188 if( pLeft==0 ){
39189 return pRight;
39190 }else if( pRight==0 ){
39191 return pLeft;
39192 }else{
39193 return sqlite3Expr(TK_AND, pLeft, pRight, 0);
39198 ** Set the Expr.span field of the given expression to span all
39199 ** text between the two given tokens.
39201 static void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
39202 assert( pRight!=0 );
39203 assert( pLeft!=0 );
39204 if( !sqlite3MallocFailed() && pRight->z && pLeft->z ){
39205 assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
39206 if( pLeft->dyn==0 && pRight->dyn==0 ){
39207 pExpr->span.z = pLeft->z;
39208 pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
39209 }else{
39210 pExpr->span.z = 0;
39216 ** Construct a new expression node for a function with multiple
39217 ** arguments.
39219 static Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
39220 Expr *pNew;
39221 assert( pToken );
39222 pNew = sqliteMalloc( sizeof(Expr) );
39223 if( pNew==0 ){
39224 sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
39225 return 0;
39227 pNew->op = TK_FUNCTION;
39228 pNew->pList = pList;
39229 assert( pToken->dyn==0 );
39230 pNew->token = *pToken;
39231 pNew->span = pNew->token;
39233 sqlite3ExprSetHeight(pNew);
39234 return pNew;
39238 ** Assign a variable number to an expression that encodes a wildcard
39239 ** in the original SQL statement.
39241 ** Wildcards consisting of a single "?" are assigned the next sequential
39242 ** variable number.
39244 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
39245 ** sure "nnn" is not too be to avoid a denial of service attack when
39246 ** the SQL statement comes from an external source.
39248 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
39249 ** as the previous instance of the same wildcard. Or if this is the first
39250 ** instance of the wildcard, the next sequenial variable number is
39251 ** assigned.
39253 static void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
39254 Token *pToken;
39255 if( pExpr==0 ) return;
39256 pToken = &pExpr->token;
39257 assert( pToken->n>=1 );
39258 assert( pToken->z!=0 );
39259 assert( pToken->z[0]!=0 );
39260 if( pToken->n==1 ){
39261 /* Wildcard of the form "?". Assign the next variable number */
39262 pExpr->iTable = ++pParse->nVar;
39263 }else if( pToken->z[0]=='?' ){
39264 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
39265 ** use it as the variable number */
39266 int i;
39267 pExpr->iTable = i = atoi((char*)&pToken->z[1]);
39268 if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
39269 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
39270 SQLITE_MAX_VARIABLE_NUMBER);
39272 if( i>pParse->nVar ){
39273 pParse->nVar = i;
39275 }else{
39276 /* Wildcards of the form ":aaa" or "$aaa". Reuse the same variable
39277 ** number as the prior appearance of the same name, or if the name
39278 ** has never appeared before, reuse the same variable number
39280 int i, n;
39281 n = pToken->n;
39282 for(i=0; i<pParse->nVarExpr; i++){
39283 Expr *pE;
39284 if( (pE = pParse->apVarExpr[i])!=0
39285 && pE->token.n==n
39286 && memcmp(pE->token.z, pToken->z, n)==0 ){
39287 pExpr->iTable = pE->iTable;
39288 break;
39291 if( i>=pParse->nVarExpr ){
39292 pExpr->iTable = ++pParse->nVar;
39293 if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
39294 pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
39295 pParse->apVarExpr = sqliteReallocOrFree(pParse->apVarExpr,
39296 pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
39298 if( !sqlite3MallocFailed() ){
39299 assert( pParse->apVarExpr!=0 );
39300 pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
39304 if( !pParse->nErr && pParse->nVar>SQLITE_MAX_VARIABLE_NUMBER ){
39305 sqlite3ErrorMsg(pParse, "too many SQL variables");
39310 ** Recursively delete an expression tree.
39312 static void sqlite3ExprDelete(Expr *p){
39313 if( p==0 ) return;
39314 if( p->span.dyn ) sqliteFree((char*)p->span.z);
39315 if( p->token.dyn ) sqliteFree((char*)p->token.z);
39316 sqlite3ExprDelete(p->pLeft);
39317 sqlite3ExprDelete(p->pRight);
39318 sqlite3ExprListDelete(p->pList);
39319 sqlite3SelectDelete(p->pSelect);
39320 sqliteFree(p);
39324 ** The Expr.token field might be a string literal that is quoted.
39325 ** If so, remove the quotation marks.
39327 static void sqlite3DequoteExpr(Expr *p){
39328 if( ExprHasAnyProperty(p, EP_Dequoted) ){
39329 return;
39331 ExprSetProperty(p, EP_Dequoted);
39332 if( p->token.dyn==0 ){
39333 sqlite3TokenCopy(&p->token, &p->token);
39335 sqlite3Dequote((char*)p->token.z);
39340 ** The following group of routines make deep copies of expressions,
39341 ** expression lists, ID lists, and select statements. The copies can
39342 ** be deleted (by being passed to their respective ...Delete() routines)
39343 ** without effecting the originals.
39345 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
39346 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
39347 ** by subsequent calls to sqlite*ListAppend() routines.
39349 ** Any tables that the SrcList might point to are not duplicated.
39351 static Expr *sqlite3ExprDup(Expr *p){
39352 Expr *pNew;
39353 if( p==0 ) return 0;
39354 pNew = sqliteMallocRaw( sizeof(*p) );
39355 if( pNew==0 ) return 0;
39356 memcpy(pNew, p, sizeof(*pNew));
39357 if( p->token.z!=0 ){
39358 pNew->token.z = (u8*)sqliteStrNDup((char*)p->token.z, p->token.n);
39359 pNew->token.dyn = 1;
39360 }else{
39361 assert( pNew->token.z==0 );
39363 pNew->span.z = 0;
39364 pNew->pLeft = sqlite3ExprDup(p->pLeft);
39365 pNew->pRight = sqlite3ExprDup(p->pRight);
39366 pNew->pList = sqlite3ExprListDup(p->pList);
39367 pNew->pSelect = sqlite3SelectDup(p->pSelect);
39368 return pNew;
39370 static void sqlite3TokenCopy(Token *pTo, Token *pFrom){
39371 if( pTo->dyn ) sqliteFree((char*)pTo->z);
39372 if( pFrom->z ){
39373 pTo->n = pFrom->n;
39374 pTo->z = (u8*)sqliteStrNDup((char*)pFrom->z, pFrom->n);
39375 pTo->dyn = 1;
39376 }else{
39377 pTo->z = 0;
39380 static ExprList *sqlite3ExprListDup(ExprList *p){
39381 ExprList *pNew;
39382 struct ExprList_item *pItem, *pOldItem;
39383 int i;
39384 if( p==0 ) return 0;
39385 pNew = sqliteMalloc( sizeof(*pNew) );
39386 if( pNew==0 ) return 0;
39387 pNew->nExpr = pNew->nAlloc = p->nExpr;
39388 pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
39389 if( pItem==0 ){
39390 sqliteFree(pNew);
39391 return 0;
39393 pOldItem = p->a;
39394 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
39395 Expr *pNewExpr, *pOldExpr;
39396 pItem->pExpr = pNewExpr = sqlite3ExprDup(pOldExpr = pOldItem->pExpr);
39397 if( pOldExpr->span.z!=0 && pNewExpr ){
39398 /* Always make a copy of the span for top-level expressions in the
39399 ** expression list. The logic in SELECT processing that determines
39400 ** the names of columns in the result set needs this information */
39401 sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
39403 assert( pNewExpr==0 || pNewExpr->span.z!=0
39404 || pOldExpr->span.z==0
39405 || sqlite3MallocFailed() );
39406 pItem->zName = sqliteStrDup(pOldItem->zName);
39407 pItem->sortOrder = pOldItem->sortOrder;
39408 pItem->isAgg = pOldItem->isAgg;
39409 pItem->done = 0;
39411 return pNew;
39415 ** If cursors, triggers, views and subqueries are all omitted from
39416 ** the build, then none of the following routines, except for
39417 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
39418 ** called with a NULL argument.
39420 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
39421 || !defined(SQLITE_OMIT_SUBQUERY)
39422 static SrcList *sqlite3SrcListDup(SrcList *p){
39423 SrcList *pNew;
39424 int i;
39425 int nByte;
39426 if( p==0 ) return 0;
39427 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
39428 pNew = sqliteMallocRaw( nByte );
39429 if( pNew==0 ) return 0;
39430 pNew->nSrc = pNew->nAlloc = p->nSrc;
39431 for(i=0; i<p->nSrc; i++){
39432 struct SrcList_item *pNewItem = &pNew->a[i];
39433 struct SrcList_item *pOldItem = &p->a[i];
39434 Table *pTab;
39435 pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
39436 pNewItem->zName = sqliteStrDup(pOldItem->zName);
39437 pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
39438 pNewItem->jointype = pOldItem->jointype;
39439 pNewItem->iCursor = pOldItem->iCursor;
39440 pNewItem->isPopulated = pOldItem->isPopulated;
39441 pTab = pNewItem->pTab = pOldItem->pTab;
39442 if( pTab ){
39443 pTab->nRef++;
39445 pNewItem->pSelect = sqlite3SelectDup(pOldItem->pSelect);
39446 pNewItem->pOn = sqlite3ExprDup(pOldItem->pOn);
39447 pNewItem->pUsing = sqlite3IdListDup(pOldItem->pUsing);
39448 pNewItem->colUsed = pOldItem->colUsed;
39450 return pNew;
39452 static IdList *sqlite3IdListDup(IdList *p){
39453 IdList *pNew;
39454 int i;
39455 if( p==0 ) return 0;
39456 pNew = sqliteMallocRaw( sizeof(*pNew) );
39457 if( pNew==0 ) return 0;
39458 pNew->nId = pNew->nAlloc = p->nId;
39459 pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
39460 if( pNew->a==0 ){
39461 sqliteFree(pNew);
39462 return 0;
39464 for(i=0; i<p->nId; i++){
39465 struct IdList_item *pNewItem = &pNew->a[i];
39466 struct IdList_item *pOldItem = &p->a[i];
39467 pNewItem->zName = sqliteStrDup(pOldItem->zName);
39468 pNewItem->idx = pOldItem->idx;
39470 return pNew;
39472 static Select *sqlite3SelectDup(Select *p){
39473 Select *pNew;
39474 if( p==0 ) return 0;
39475 pNew = sqliteMallocRaw( sizeof(*p) );
39476 if( pNew==0 ) return 0;
39477 pNew->isDistinct = p->isDistinct;
39478 pNew->pEList = sqlite3ExprListDup(p->pEList);
39479 pNew->pSrc = sqlite3SrcListDup(p->pSrc);
39480 pNew->pWhere = sqlite3ExprDup(p->pWhere);
39481 pNew->pGroupBy = sqlite3ExprListDup(p->pGroupBy);
39482 pNew->pHaving = sqlite3ExprDup(p->pHaving);
39483 pNew->pOrderBy = sqlite3ExprListDup(p->pOrderBy);
39484 pNew->op = p->op;
39485 pNew->pPrior = sqlite3SelectDup(p->pPrior);
39486 pNew->pLimit = sqlite3ExprDup(p->pLimit);
39487 pNew->pOffset = sqlite3ExprDup(p->pOffset);
39488 pNew->iLimit = -1;
39489 pNew->iOffset = -1;
39490 pNew->isResolved = p->isResolved;
39491 pNew->isAgg = p->isAgg;
39492 pNew->usesEphm = 0;
39493 pNew->disallowOrderBy = 0;
39494 pNew->pRightmost = 0;
39495 pNew->addrOpenEphm[0] = -1;
39496 pNew->addrOpenEphm[1] = -1;
39497 pNew->addrOpenEphm[2] = -1;
39498 return pNew;
39500 #else
39501 static Select *sqlite3SelectDup(Select *p){
39502 assert( p==0 );
39503 return 0;
39505 #endif
39509 ** Add a new element to the end of an expression list. If pList is
39510 ** initially NULL, then create a new expression list.
39512 static ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
39513 if( pList==0 ){
39514 pList = sqliteMalloc( sizeof(ExprList) );
39515 if( pList==0 ){
39516 goto no_mem;
39518 assert( pList->nAlloc==0 );
39520 if( pList->nAlloc<=pList->nExpr ){
39521 struct ExprList_item *a;
39522 int n = pList->nAlloc*2 + 4;
39523 a = sqliteRealloc(pList->a, n*sizeof(pList->a[0]));
39524 if( a==0 ){
39525 goto no_mem;
39527 pList->a = a;
39528 pList->nAlloc = n;
39530 assert( pList->a!=0 );
39531 if( pExpr || pName ){
39532 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
39533 memset(pItem, 0, sizeof(*pItem));
39534 pItem->zName = sqlite3NameFromToken(pName);
39535 pItem->pExpr = pExpr;
39537 return pList;
39539 no_mem:
39540 /* Avoid leaking memory if malloc has failed. */
39541 sqlite3ExprDelete(pExpr);
39542 sqlite3ExprListDelete(pList);
39543 return 0;
39547 ** If the expression list pEList contains more than iLimit elements,
39548 ** leave an error message in pParse.
39550 static void sqlite3ExprListCheckLength(
39551 Parse *pParse,
39552 ExprList *pEList,
39553 int iLimit,
39554 const char *zObject
39556 if( pEList && pEList->nExpr>iLimit ){
39557 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
39562 #if SQLITE_MAX_EXPR_DEPTH>0
39563 /* The following three functions, heightOfExpr(), heightOfExprList()
39564 ** and heightOfSelect(), are used to determine the maximum height
39565 ** of any expression tree referenced by the structure passed as the
39566 ** first argument.
39568 ** If this maximum height is greater than the current value pointed
39569 ** to by pnHeight, the second parameter, then set *pnHeight to that
39570 ** value.
39572 static void heightOfExpr(Expr *p, int *pnHeight){
39573 if( p ){
39574 if( p->nHeight>*pnHeight ){
39575 *pnHeight = p->nHeight;
39579 static void heightOfExprList(ExprList *p, int *pnHeight){
39580 if( p ){
39581 int i;
39582 for(i=0; i<p->nExpr; i++){
39583 heightOfExpr(p->a[i].pExpr, pnHeight);
39587 static void heightOfSelect(Select *p, int *pnHeight){
39588 if( p ){
39589 heightOfExpr(p->pWhere, pnHeight);
39590 heightOfExpr(p->pHaving, pnHeight);
39591 heightOfExpr(p->pLimit, pnHeight);
39592 heightOfExpr(p->pOffset, pnHeight);
39593 heightOfExprList(p->pEList, pnHeight);
39594 heightOfExprList(p->pGroupBy, pnHeight);
39595 heightOfExprList(p->pOrderBy, pnHeight);
39596 heightOfSelect(p->pPrior, pnHeight);
39601 ** Set the Expr.nHeight variable in the structure passed as an
39602 ** argument. An expression with no children, Expr.pList or
39603 ** Expr.pSelect member has a height of 1. Any other expression
39604 ** has a height equal to the maximum height of any other
39605 ** referenced Expr plus one.
39607 static void sqlite3ExprSetHeight(Expr *p){
39608 int nHeight = 0;
39609 heightOfExpr(p->pLeft, &nHeight);
39610 heightOfExpr(p->pRight, &nHeight);
39611 heightOfExprList(p->pList, &nHeight);
39612 heightOfSelect(p->pSelect, &nHeight);
39613 p->nHeight = nHeight + 1;
39617 ** Return the maximum height of any expression tree referenced
39618 ** by the select statement passed as an argument.
39620 static int sqlite3SelectExprHeight(Select *p){
39621 int nHeight = 0;
39622 heightOfSelect(p, &nHeight);
39623 return nHeight;
39625 #endif
39628 ** Delete an entire expression list.
39630 static void sqlite3ExprListDelete(ExprList *pList){
39631 int i;
39632 struct ExprList_item *pItem;
39633 if( pList==0 ) return;
39634 assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
39635 assert( pList->nExpr<=pList->nAlloc );
39636 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
39637 sqlite3ExprDelete(pItem->pExpr);
39638 sqliteFree(pItem->zName);
39640 sqliteFree(pList->a);
39641 sqliteFree(pList);
39645 ** Walk an expression tree. Call xFunc for each node visited.
39647 ** The return value from xFunc determines whether the tree walk continues.
39648 ** 0 means continue walking the tree. 1 means do not walk children
39649 ** of the current node but continue with siblings. 2 means abandon
39650 ** the tree walk completely.
39652 ** The return value from this routine is 1 to abandon the tree walk
39653 ** and 0 to continue.
39655 ** NOTICE: This routine does *not* descend into subqueries.
39657 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
39658 static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
39659 int rc;
39660 if( pExpr==0 ) return 0;
39661 rc = (*xFunc)(pArg, pExpr);
39662 if( rc==0 ){
39663 if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
39664 if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
39665 if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
39667 return rc>1;
39671 ** Call walkExprTree() for every expression in list p.
39673 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
39674 int i;
39675 struct ExprList_item *pItem;
39676 if( !p ) return 0;
39677 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
39678 if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
39680 return 0;
39684 ** Call walkExprTree() for every expression in Select p, not including
39685 ** expressions that are part of sub-selects in any FROM clause or the LIMIT
39686 ** or OFFSET expressions..
39688 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
39689 walkExprList(p->pEList, xFunc, pArg);
39690 walkExprTree(p->pWhere, xFunc, pArg);
39691 walkExprList(p->pGroupBy, xFunc, pArg);
39692 walkExprTree(p->pHaving, xFunc, pArg);
39693 walkExprList(p->pOrderBy, xFunc, pArg);
39694 if( p->pPrior ){
39695 walkSelectExpr(p->pPrior, xFunc, pArg);
39697 return 0;
39702 ** This routine is designed as an xFunc for walkExprTree().
39704 ** pArg is really a pointer to an integer. If we can tell by looking
39705 ** at pExpr that the expression that contains pExpr is not a constant
39706 ** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
39707 ** If pExpr does does not disqualify the expression from being a constant
39708 ** then do nothing.
39710 ** After walking the whole tree, if no nodes are found that disqualify
39711 ** the expression as constant, then we assume the whole expression
39712 ** is constant. See sqlite3ExprIsConstant() for additional information.
39714 static int exprNodeIsConstant(void *pArg, Expr *pExpr){
39715 int *pN = (int*)pArg;
39717 /* If *pArg is 3 then any term of the expression that comes from
39718 ** the ON or USING clauses of a join disqualifies the expression
39719 ** from being considered constant. */
39720 if( (*pN)==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
39721 *pN = 0;
39722 return 2;
39725 switch( pExpr->op ){
39726 /* Consider functions to be constant if all their arguments are constant
39727 ** and *pArg==2 */
39728 case TK_FUNCTION:
39729 if( (*pN)==2 ) return 0;
39730 /* Fall through */
39731 case TK_ID:
39732 case TK_COLUMN:
39733 case TK_DOT:
39734 case TK_AGG_FUNCTION:
39735 case TK_AGG_COLUMN:
39736 #ifndef SQLITE_OMIT_SUBQUERY
39737 case TK_SELECT:
39738 case TK_EXISTS:
39739 #endif
39740 *pN = 0;
39741 return 2;
39742 case TK_IN:
39743 if( pExpr->pSelect ){
39744 *pN = 0;
39745 return 2;
39747 default:
39748 return 0;
39753 ** Walk an expression tree. Return 1 if the expression is constant
39754 ** and 0 if it involves variables or function calls.
39756 ** For the purposes of this function, a double-quoted string (ex: "abc")
39757 ** is considered a variable but a single-quoted string (ex: 'abc') is
39758 ** a constant.
39760 static int sqlite3ExprIsConstant(Expr *p){
39761 int isConst = 1;
39762 walkExprTree(p, exprNodeIsConstant, &isConst);
39763 return isConst;
39767 ** Walk an expression tree. Return 1 if the expression is constant
39768 ** that does no originate from the ON or USING clauses of a join.
39769 ** Return 0 if it involves variables or function calls or terms from
39770 ** an ON or USING clause.
39772 static int sqlite3ExprIsConstantNotJoin(Expr *p){
39773 int isConst = 3;
39774 walkExprTree(p, exprNodeIsConstant, &isConst);
39775 return isConst!=0;
39779 ** Walk an expression tree. Return 1 if the expression is constant
39780 ** or a function call with constant arguments. Return and 0 if there
39781 ** are any variables.
39783 ** For the purposes of this function, a double-quoted string (ex: "abc")
39784 ** is considered a variable but a single-quoted string (ex: 'abc') is
39785 ** a constant.
39787 static int sqlite3ExprIsConstantOrFunction(Expr *p){
39788 int isConst = 2;
39789 walkExprTree(p, exprNodeIsConstant, &isConst);
39790 return isConst!=0;
39794 ** If the expression p codes a constant integer that is small enough
39795 ** to fit in a 32-bit integer, return 1 and put the value of the integer
39796 ** in *pValue. If the expression is not an integer or if it is too big
39797 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
39799 static int sqlite3ExprIsInteger(Expr *p, int *pValue){
39800 switch( p->op ){
39801 case TK_INTEGER: {
39802 if( sqlite3GetInt32((char*)p->token.z, pValue) ){
39803 return 1;
39805 break;
39807 case TK_UPLUS: {
39808 return sqlite3ExprIsInteger(p->pLeft, pValue);
39810 case TK_UMINUS: {
39811 int v;
39812 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
39813 *pValue = -v;
39814 return 1;
39816 break;
39818 default: break;
39820 return 0;
39824 ** Return TRUE if the given string is a row-id column name.
39826 static int sqlite3IsRowid(const char *z){
39827 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
39828 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
39829 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
39830 return 0;
39834 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
39835 ** that name in the set of source tables in pSrcList and make the pExpr
39836 ** expression node refer back to that source column. The following changes
39837 ** are made to pExpr:
39839 ** pExpr->iDb Set the index in db->aDb[] of the database holding
39840 ** the table.
39841 ** pExpr->iTable Set to the cursor number for the table obtained
39842 ** from pSrcList.
39843 ** pExpr->iColumn Set to the column number within the table.
39844 ** pExpr->op Set to TK_COLUMN.
39845 ** pExpr->pLeft Any expression this points to is deleted
39846 ** pExpr->pRight Any expression this points to is deleted.
39848 ** The pDbToken is the name of the database (the "X"). This value may be
39849 ** NULL meaning that name is of the form Y.Z or Z. Any available database
39850 ** can be used. The pTableToken is the name of the table (the "Y"). This
39851 ** value can be NULL if pDbToken is also NULL. If pTableToken is NULL it
39852 ** means that the form of the name is Z and that columns from any table
39853 ** can be used.
39855 ** If the name cannot be resolved unambiguously, leave an error message
39856 ** in pParse and return non-zero. Return zero on success.
39858 static int lookupName(
39859 Parse *pParse, /* The parsing context */
39860 Token *pDbToken, /* Name of the database containing table, or NULL */
39861 Token *pTableToken, /* Name of table containing column, or NULL */
39862 Token *pColumnToken, /* Name of the column. */
39863 NameContext *pNC, /* The name context used to resolve the name */
39864 Expr *pExpr /* Make this EXPR node point to the selected column */
39866 char *zDb = 0; /* Name of the database. The "X" in X.Y.Z */
39867 char *zTab = 0; /* Name of the table. The "Y" in X.Y.Z or Y.Z */
39868 char *zCol = 0; /* Name of the column. The "Z" */
39869 int i, j; /* Loop counters */
39870 int cnt = 0; /* Number of matching column names */
39871 int cntTab = 0; /* Number of matching table names */
39872 sqlite3 *db = pParse->db; /* The database */
39873 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
39874 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
39875 NameContext *pTopNC = pNC; /* First namecontext in the list */
39877 assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
39878 zDb = sqlite3NameFromToken(pDbToken);
39879 zTab = sqlite3NameFromToken(pTableToken);
39880 zCol = sqlite3NameFromToken(pColumnToken);
39881 if( sqlite3MallocFailed() ){
39882 goto lookupname_end;
39885 pExpr->iTable = -1;
39886 while( pNC && cnt==0 ){
39887 ExprList *pEList;
39888 SrcList *pSrcList = pNC->pSrcList;
39890 if( pSrcList ){
39891 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
39892 Table *pTab;
39893 int iDb;
39894 Column *pCol;
39896 pTab = pItem->pTab;
39897 assert( pTab!=0 );
39898 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
39899 assert( pTab->nCol>0 );
39900 if( zTab ){
39901 if( pItem->zAlias ){
39902 char *zTabName = pItem->zAlias;
39903 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
39904 }else{
39905 char *zTabName = pTab->zName;
39906 if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
39907 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
39908 continue;
39912 if( 0==(cntTab++) ){
39913 pExpr->iTable = pItem->iCursor;
39914 pExpr->pSchema = pTab->pSchema;
39915 pMatch = pItem;
39917 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
39918 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
39919 const char *zColl = pTab->aCol[j].zColl;
39920 IdList *pUsing;
39921 cnt++;
39922 pExpr->iTable = pItem->iCursor;
39923 pMatch = pItem;
39924 pExpr->pSchema = pTab->pSchema;
39925 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
39926 pExpr->iColumn = j==pTab->iPKey ? -1 : j;
39927 pExpr->affinity = pTab->aCol[j].affinity;
39928 if( (pExpr->flags & EP_ExpCollate)==0 ){
39929 pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
39931 if( i<pSrcList->nSrc-1 ){
39932 if( pItem[1].jointype & JT_NATURAL ){
39933 /* If this match occurred in the left table of a natural join,
39934 ** then skip the right table to avoid a duplicate match */
39935 pItem++;
39936 i++;
39937 }else if( (pUsing = pItem[1].pUsing)!=0 ){
39938 /* If this match occurs on a column that is in the USING clause
39939 ** of a join, skip the search of the right table of the join
39940 ** to avoid a duplicate match there. */
39941 int k;
39942 for(k=0; k<pUsing->nId; k++){
39943 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
39944 pItem++;
39945 i++;
39946 break;
39951 break;
39957 #ifndef SQLITE_OMIT_TRIGGER
39958 /* If we have not already resolved the name, then maybe
39959 ** it is a new.* or old.* trigger argument reference
39961 if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
39962 TriggerStack *pTriggerStack = pParse->trigStack;
39963 Table *pTab = 0;
39964 if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
39965 pExpr->iTable = pTriggerStack->newIdx;
39966 assert( pTriggerStack->pTab );
39967 pTab = pTriggerStack->pTab;
39968 }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
39969 pExpr->iTable = pTriggerStack->oldIdx;
39970 assert( pTriggerStack->pTab );
39971 pTab = pTriggerStack->pTab;
39974 if( pTab ){
39975 int iCol;
39976 Column *pCol = pTab->aCol;
39978 pExpr->pSchema = pTab->pSchema;
39979 cntTab++;
39980 for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
39981 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
39982 const char *zColl = pTab->aCol[iCol].zColl;
39983 cnt++;
39984 pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
39985 pExpr->affinity = pTab->aCol[iCol].affinity;
39986 if( (pExpr->flags & EP_ExpCollate)==0 ){
39987 pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
39989 pExpr->pTab = pTab;
39990 break;
39995 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
39998 ** Perhaps the name is a reference to the ROWID
40000 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
40001 cnt = 1;
40002 pExpr->iColumn = -1;
40003 pExpr->affinity = SQLITE_AFF_INTEGER;
40007 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
40008 ** might refer to an result-set alias. This happens, for example, when
40009 ** we are resolving names in the WHERE clause of the following command:
40011 ** SELECT a+b AS x FROM table WHERE x<10;
40013 ** In cases like this, replace pExpr with a copy of the expression that
40014 ** forms the result set entry ("a+b" in the example) and return immediately.
40015 ** Note that the expression in the result set should have already been
40016 ** resolved by the time the WHERE clause is resolved.
40018 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
40019 for(j=0; j<pEList->nExpr; j++){
40020 char *zAs = pEList->a[j].zName;
40021 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
40022 Expr *pDup;
40023 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
40024 assert( pExpr->pList==0 );
40025 assert( pExpr->pSelect==0 );
40026 pDup = sqlite3ExprDup(pEList->a[j].pExpr);
40027 if( pExpr->flags & EP_ExpCollate ){
40028 pDup->pColl = pExpr->pColl;
40029 pDup->flags |= EP_ExpCollate;
40031 if( pExpr->span.dyn ) sqliteFree((char*)pExpr->span.z);
40032 if( pExpr->token.dyn ) sqliteFree((char*)pExpr->token.z);
40033 memcpy(pExpr, pDup, sizeof(*pExpr));
40034 sqliteFree(pDup);
40035 cnt = 1;
40036 assert( zTab==0 && zDb==0 );
40037 goto lookupname_end_2;
40042 /* Advance to the next name context. The loop will exit when either
40043 ** we have a match (cnt>0) or when we run out of name contexts.
40045 if( cnt==0 ){
40046 pNC = pNC->pNext;
40051 ** If X and Y are NULL (in other words if only the column name Z is
40052 ** supplied) and the value of Z is enclosed in double-quotes, then
40053 ** Z is a string literal if it doesn't match any column names. In that
40054 ** case, we need to return right away and not make any changes to
40055 ** pExpr.
40057 ** Because no reference was made to outer contexts, the pNC->nRef
40058 ** fields are not changed in any context.
40060 if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
40061 sqliteFree(zCol);
40062 return 0;
40066 ** cnt==0 means there was not match. cnt>1 means there were two or
40067 ** more matches. Either way, we have an error.
40069 if( cnt!=1 ){
40070 char *z = 0;
40071 char *zErr;
40072 zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
40073 if( zDb ){
40074 sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
40075 }else if( zTab ){
40076 sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
40077 }else{
40078 z = sqliteStrDup(zCol);
40080 sqlite3ErrorMsg(pParse, zErr, z);
40081 sqliteFree(z);
40082 pTopNC->nErr++;
40085 /* If a column from a table in pSrcList is referenced, then record
40086 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
40087 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
40088 ** column number is greater than the number of bits in the bitmask
40089 ** then set the high-order bit of the bitmask.
40091 if( pExpr->iColumn>=0 && pMatch!=0 ){
40092 int n = pExpr->iColumn;
40093 if( n>=sizeof(Bitmask)*8 ){
40094 n = sizeof(Bitmask)*8-1;
40096 assert( pMatch->iCursor==pExpr->iTable );
40097 pMatch->colUsed |= ((Bitmask)1)<<n;
40100 lookupname_end:
40101 /* Clean up and return
40103 sqliteFree(zDb);
40104 sqliteFree(zTab);
40105 sqlite3ExprDelete(pExpr->pLeft);
40106 pExpr->pLeft = 0;
40107 sqlite3ExprDelete(pExpr->pRight);
40108 pExpr->pRight = 0;
40109 pExpr->op = TK_COLUMN;
40110 lookupname_end_2:
40111 sqliteFree(zCol);
40112 if( cnt==1 ){
40113 assert( pNC!=0 );
40114 sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
40115 if( pMatch && !pMatch->pSelect ){
40116 pExpr->pTab = pMatch->pTab;
40118 /* Increment the nRef value on all name contexts from TopNC up to
40119 ** the point where the name matched. */
40120 for(;;){
40121 assert( pTopNC!=0 );
40122 pTopNC->nRef++;
40123 if( pTopNC==pNC ) break;
40124 pTopNC = pTopNC->pNext;
40126 return 0;
40127 } else {
40128 return 1;
40133 ** This routine is designed as an xFunc for walkExprTree().
40135 ** Resolve symbolic names into TK_COLUMN operators for the current
40136 ** node in the expression tree. Return 0 to continue the search down
40137 ** the tree or 2 to abort the tree walk.
40139 ** This routine also does error checking and name resolution for
40140 ** function names. The operator for aggregate functions is changed
40141 ** to TK_AGG_FUNCTION.
40143 static int nameResolverStep(void *pArg, Expr *pExpr){
40144 NameContext *pNC = (NameContext*)pArg;
40145 Parse *pParse;
40147 if( pExpr==0 ) return 1;
40148 assert( pNC!=0 );
40149 pParse = pNC->pParse;
40151 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
40152 ExprSetProperty(pExpr, EP_Resolved);
40153 #ifndef NDEBUG
40154 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
40155 SrcList *pSrcList = pNC->pSrcList;
40156 int i;
40157 for(i=0; i<pNC->pSrcList->nSrc; i++){
40158 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
40161 #endif
40162 switch( pExpr->op ){
40163 /* Double-quoted strings (ex: "abc") are used as identifiers if
40164 ** possible. Otherwise they remain as strings. Single-quoted
40165 ** strings (ex: 'abc') are always string literals.
40167 case TK_STRING: {
40168 if( pExpr->token.z[0]=='\'' ) break;
40169 /* Fall thru into the TK_ID case if this is a double-quoted string */
40171 /* A lone identifier is the name of a column.
40173 case TK_ID: {
40174 lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
40175 return 1;
40178 /* A table name and column name: ID.ID
40179 ** Or a database, table and column: ID.ID.ID
40181 case TK_DOT: {
40182 Token *pColumn;
40183 Token *pTable;
40184 Token *pDb;
40185 Expr *pRight;
40187 /* if( pSrcList==0 ) break; */
40188 pRight = pExpr->pRight;
40189 if( pRight->op==TK_ID ){
40190 pDb = 0;
40191 pTable = &pExpr->pLeft->token;
40192 pColumn = &pRight->token;
40193 }else{
40194 assert( pRight->op==TK_DOT );
40195 pDb = &pExpr->pLeft->token;
40196 pTable = &pRight->pLeft->token;
40197 pColumn = &pRight->pRight->token;
40199 lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
40200 return 1;
40203 /* Resolve function names
40205 case TK_CONST_FUNC:
40206 case TK_FUNCTION: {
40207 ExprList *pList = pExpr->pList; /* The argument list */
40208 int n = pList ? pList->nExpr : 0; /* Number of arguments */
40209 int no_such_func = 0; /* True if no such function exists */
40210 int wrong_num_args = 0; /* True if wrong number of arguments */
40211 int is_agg = 0; /* True if is an aggregate function */
40212 int i;
40213 int auth; /* Authorization to use the function */
40214 int nId; /* Number of characters in function name */
40215 const char *zId; /* The function name. */
40216 FuncDef *pDef; /* Information about the function */
40217 int enc = ENC(pParse->db); /* The database encoding */
40219 zId = (char*)pExpr->token.z;
40220 nId = pExpr->token.n;
40221 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
40222 if( pDef==0 ){
40223 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
40224 if( pDef==0 ){
40225 no_such_func = 1;
40226 }else{
40227 wrong_num_args = 1;
40229 }else{
40230 is_agg = pDef->xFunc==0;
40232 #ifndef SQLITE_OMIT_AUTHORIZATION
40233 if( pDef ){
40234 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
40235 if( auth!=SQLITE_OK ){
40236 if( auth==SQLITE_DENY ){
40237 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
40238 pDef->zName);
40239 pNC->nErr++;
40241 pExpr->op = TK_NULL;
40242 return 1;
40245 #endif
40246 if( is_agg && !pNC->allowAgg ){
40247 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
40248 pNC->nErr++;
40249 is_agg = 0;
40250 }else if( no_such_func ){
40251 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
40252 pNC->nErr++;
40253 }else if( wrong_num_args ){
40254 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
40255 nId, zId);
40256 pNC->nErr++;
40258 if( is_agg ){
40259 pExpr->op = TK_AGG_FUNCTION;
40260 pNC->hasAgg = 1;
40262 if( is_agg ) pNC->allowAgg = 0;
40263 for(i=0; pNC->nErr==0 && i<n; i++){
40264 walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
40266 if( is_agg ) pNC->allowAgg = 1;
40267 /* FIX ME: Compute pExpr->affinity based on the expected return
40268 ** type of the function
40270 return is_agg;
40272 #ifndef SQLITE_OMIT_SUBQUERY
40273 case TK_SELECT:
40274 case TK_EXISTS:
40275 #endif
40276 case TK_IN: {
40277 if( pExpr->pSelect ){
40278 int nRef = pNC->nRef;
40279 #ifndef SQLITE_OMIT_CHECK
40280 if( pNC->isCheck ){
40281 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
40283 #endif
40284 sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
40285 assert( pNC->nRef>=nRef );
40286 if( nRef!=pNC->nRef ){
40287 ExprSetProperty(pExpr, EP_VarSelect);
40290 break;
40292 #ifndef SQLITE_OMIT_CHECK
40293 case TK_VARIABLE: {
40294 if( pNC->isCheck ){
40295 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
40297 break;
40299 #endif
40301 return 0;
40305 ** This routine walks an expression tree and resolves references to
40306 ** table columns. Nodes of the form ID.ID or ID resolve into an
40307 ** index to the table in the table list and a column offset. The
40308 ** Expr.opcode for such nodes is changed to TK_COLUMN. The Expr.iTable
40309 ** value is changed to the index of the referenced table in pTabList
40310 ** plus the "base" value. The base value will ultimately become the
40311 ** VDBE cursor number for a cursor that is pointing into the referenced
40312 ** table. The Expr.iColumn value is changed to the index of the column
40313 ** of the referenced table. The Expr.iColumn value for the special
40314 ** ROWID column is -1. Any INTEGER PRIMARY KEY column is tried as an
40315 ** alias for ROWID.
40317 ** Also resolve function names and check the functions for proper
40318 ** usage. Make sure all function names are recognized and all functions
40319 ** have the correct number of arguments. Leave an error message
40320 ** in pParse->zErrMsg if anything is amiss. Return the number of errors.
40322 ** If the expression contains aggregate functions then set the EP_Agg
40323 ** property on the expression.
40325 static int sqlite3ExprResolveNames(
40326 NameContext *pNC, /* Namespace to resolve expressions in. */
40327 Expr *pExpr /* The expression to be analyzed. */
40329 int savedHasAgg;
40330 if( pExpr==0 ) return 0;
40331 #if SQLITE_MAX_EXPR_DEPTH>0
40332 if( (pExpr->nHeight+pNC->pParse->nHeight)>SQLITE_MAX_EXPR_DEPTH ){
40333 sqlite3ErrorMsg(pNC->pParse,
40334 "Expression tree is too large (maximum depth %d)",
40335 SQLITE_MAX_EXPR_DEPTH
40337 return 1;
40339 pNC->pParse->nHeight += pExpr->nHeight;
40340 #endif
40341 savedHasAgg = pNC->hasAgg;
40342 pNC->hasAgg = 0;
40343 walkExprTree(pExpr, nameResolverStep, pNC);
40344 #if SQLITE_MAX_EXPR_DEPTH>0
40345 pNC->pParse->nHeight -= pExpr->nHeight;
40346 #endif
40347 if( pNC->nErr>0 ){
40348 ExprSetProperty(pExpr, EP_Error);
40350 if( pNC->hasAgg ){
40351 ExprSetProperty(pExpr, EP_Agg);
40352 }else if( savedHasAgg ){
40353 pNC->hasAgg = 1;
40355 return ExprHasProperty(pExpr, EP_Error);
40359 ** A pointer instance of this structure is used to pass information
40360 ** through walkExprTree into codeSubqueryStep().
40362 typedef struct QueryCoder QueryCoder;
40363 struct QueryCoder {
40364 Parse *pParse; /* The parsing context */
40365 NameContext *pNC; /* Namespace of first enclosing query */
40370 ** Generate code for scalar subqueries used as an expression
40371 ** and IN operators. Examples:
40373 ** (SELECT a FROM b) -- subquery
40374 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
40375 ** x IN (4,5,11) -- IN operator with list on right-hand side
40376 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
40378 ** The pExpr parameter describes the expression that contains the IN
40379 ** operator or subquery.
40381 #ifndef SQLITE_OMIT_SUBQUERY
40382 static void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
40383 int testAddr = 0; /* One-time test address */
40384 Vdbe *v = sqlite3GetVdbe(pParse);
40385 if( v==0 ) return;
40388 /* This code must be run in its entirety every time it is encountered
40389 ** if any of the following is true:
40391 ** * The right-hand side is a correlated subquery
40392 ** * The right-hand side is an expression list containing variables
40393 ** * We are inside a trigger
40395 ** If all of the above are false, then we can run this code just once
40396 ** save the results, and reuse the same result on subsequent invocations.
40398 if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
40399 int mem = pParse->nMem++;
40400 sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
40401 testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
40402 assert( testAddr>0 || sqlite3MallocFailed() );
40403 sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
40406 switch( pExpr->op ){
40407 case TK_IN: {
40408 char affinity;
40409 KeyInfo keyInfo;
40410 int addr; /* Address of OP_OpenEphemeral instruction */
40412 affinity = sqlite3ExprAffinity(pExpr->pLeft);
40414 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
40415 ** expression it is handled the same way. A virtual table is
40416 ** filled with single-field index keys representing the results
40417 ** from the SELECT or the <exprlist>.
40419 ** If the 'x' expression is a column value, or the SELECT...
40420 ** statement returns a column value, then the affinity of that
40421 ** column is used to build the index keys. If both 'x' and the
40422 ** SELECT... statement are columns, then numeric affinity is used
40423 ** if either column has NUMERIC or INTEGER affinity. If neither
40424 ** 'x' nor the SELECT... statement are columns, then numeric affinity
40425 ** is used.
40427 pExpr->iTable = pParse->nTab++;
40428 addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0);
40429 memset(&keyInfo, 0, sizeof(keyInfo));
40430 keyInfo.nField = 1;
40431 sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
40433 if( pExpr->pSelect ){
40434 /* Case 1: expr IN (SELECT ...)
40436 ** Generate code to write the results of the select into the temporary
40437 ** table allocated and opened above.
40439 int iParm = pExpr->iTable + (((int)affinity)<<16);
40440 ExprList *pEList;
40441 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
40442 if( sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0) ){
40443 return;
40445 pEList = pExpr->pSelect->pEList;
40446 if( pEList && pEList->nExpr>0 ){
40447 keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
40448 pEList->a[0].pExpr);
40450 }else if( pExpr->pList ){
40451 /* Case 2: expr IN (exprlist)
40453 ** For each expression, build an index key from the evaluation and
40454 ** store it in the temporary table. If <expr> is a column, then use
40455 ** that columns affinity when building index keys. If <expr> is not
40456 ** a column, use numeric affinity.
40458 int i;
40459 ExprList *pList = pExpr->pList;
40460 struct ExprList_item *pItem;
40462 if( !affinity ){
40463 affinity = SQLITE_AFF_NONE;
40465 keyInfo.aColl[0] = pExpr->pLeft->pColl;
40467 /* Loop through each expression in <exprlist>. */
40468 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
40469 Expr *pE2 = pItem->pExpr;
40471 /* If the expression is not constant then we will need to
40472 ** disable the test that was generated above that makes sure
40473 ** this code only executes once. Because for a non-constant
40474 ** expression we need to rerun this code each time.
40476 if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
40477 sqlite3VdbeChangeToNoop(v, testAddr-1, 3);
40478 testAddr = 0;
40481 /* Evaluate the expression and insert it into the temp table */
40482 sqlite3ExprCode(pParse, pE2);
40483 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
40484 sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
40487 sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
40488 break;
40491 case TK_EXISTS:
40492 case TK_SELECT: {
40493 /* This has to be a scalar SELECT. Generate code to put the
40494 ** value of this select in a memory cell and record the number
40495 ** of the memory cell in iColumn.
40497 static const Token one = { (u8*)"1", 0, 1 };
40498 Select *pSel;
40499 int iMem;
40500 int sop;
40502 pExpr->iColumn = iMem = pParse->nMem++;
40503 pSel = pExpr->pSelect;
40504 if( pExpr->op==TK_SELECT ){
40505 sop = SRT_Mem;
40506 sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
40507 VdbeComment((v, "# Init subquery result"));
40508 }else{
40509 sop = SRT_Exists;
40510 sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
40511 VdbeComment((v, "# Init EXISTS result"));
40513 sqlite3ExprDelete(pSel->pLimit);
40514 pSel->pLimit = sqlite3Expr(TK_INTEGER, 0, 0, &one);
40515 if( sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0) ){
40516 return;
40518 break;
40522 if( testAddr ){
40523 sqlite3VdbeJumpHere(v, testAddr);
40526 return;
40528 #endif /* SQLITE_OMIT_SUBQUERY */
40531 ** Generate an instruction that will put the integer describe by
40532 ** text z[0..n-1] on the stack.
40534 static void codeInteger(Vdbe *v, const char *z, int n){
40535 assert( z || sqlite3MallocFailed() );
40536 if( z ){
40537 int i;
40538 if( sqlite3GetInt32(z, &i) ){
40539 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
40540 }else if( sqlite3FitsIn64Bits(z) ){
40541 sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n);
40542 }else{
40543 sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
40550 ** Generate code that will extract the iColumn-th column from
40551 ** table pTab and push that column value on the stack. There
40552 ** is an open cursor to pTab in iTable. If iColumn<0 then
40553 ** code is generated that extracts the rowid.
40555 static void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){
40556 if( iColumn<0 ){
40557 int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
40558 sqlite3VdbeAddOp(v, op, iTable, 0);
40559 }else if( pTab==0 ){
40560 sqlite3VdbeAddOp(v, OP_Column, iTable, iColumn);
40561 }else{
40562 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
40563 sqlite3VdbeAddOp(v, op, iTable, iColumn);
40564 sqlite3ColumnDefault(v, pTab, iColumn);
40565 #ifndef SQLITE_OMIT_FLOATING_POINT
40566 if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
40567 sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
40569 #endif
40574 ** Generate code into the current Vdbe to evaluate the given
40575 ** expression and leave the result on the top of stack.
40577 ** This code depends on the fact that certain token values (ex: TK_EQ)
40578 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
40579 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
40580 ** the make process cause these values to align. Assert()s in the code
40581 ** below verify that the numbers are aligned correctly.
40583 static void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
40584 Vdbe *v = pParse->pVdbe;
40585 int op;
40586 int stackChng = 1; /* Amount of change to stack depth */
40588 if( v==0 ) return;
40589 if( pExpr==0 ){
40590 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
40591 return;
40593 op = pExpr->op;
40594 switch( op ){
40595 case TK_AGG_COLUMN: {
40596 AggInfo *pAggInfo = pExpr->pAggInfo;
40597 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
40598 if( !pAggInfo->directMode ){
40599 sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
40600 break;
40601 }else if( pAggInfo->useSortingIdx ){
40602 sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
40603 pCol->iSorterColumn);
40604 break;
40606 /* Otherwise, fall thru into the TK_COLUMN case */
40608 case TK_COLUMN: {
40609 if( pExpr->iTable<0 ){
40610 /* This only happens when coding check constraints */
40611 assert( pParse->ckOffset>0 );
40612 sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
40613 }else{
40614 sqlite3ExprCodeGetColumn(v, pExpr->pTab, pExpr->iColumn, pExpr->iTable);
40616 break;
40618 case TK_INTEGER: {
40619 codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
40620 break;
40622 case TK_FLOAT:
40623 case TK_STRING: {
40624 assert( TK_FLOAT==OP_Real );
40625 assert( TK_STRING==OP_String8 );
40626 sqlite3DequoteExpr(pExpr);
40627 sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
40628 break;
40630 case TK_NULL: {
40631 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
40632 break;
40634 #ifndef SQLITE_OMIT_BLOB_LITERAL
40635 case TK_BLOB: {
40636 int n;
40637 const char *z;
40638 assert( TK_BLOB==OP_HexBlob );
40639 n = pExpr->token.n - 3;
40640 z = (char*)pExpr->token.z + 2;
40641 assert( n>=0 );
40642 if( n==0 ){
40643 z = "";
40645 sqlite3VdbeOp3(v, op, 0, 0, z, n);
40646 break;
40648 #endif
40649 case TK_VARIABLE: {
40650 sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
40651 if( pExpr->token.n>1 ){
40652 sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
40654 break;
40656 case TK_REGISTER: {
40657 sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
40658 break;
40660 #ifndef SQLITE_OMIT_CAST
40661 case TK_CAST: {
40662 /* Expressions of the form: CAST(pLeft AS token) */
40663 int aff, to_op;
40664 sqlite3ExprCode(pParse, pExpr->pLeft);
40665 aff = sqlite3AffinityType(&pExpr->token);
40666 to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
40667 assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
40668 assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
40669 assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
40670 assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
40671 assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
40672 sqlite3VdbeAddOp(v, to_op, 0, 0);
40673 stackChng = 0;
40674 break;
40676 #endif /* SQLITE_OMIT_CAST */
40677 case TK_LT:
40678 case TK_LE:
40679 case TK_GT:
40680 case TK_GE:
40681 case TK_NE:
40682 case TK_EQ: {
40683 assert( TK_LT==OP_Lt );
40684 assert( TK_LE==OP_Le );
40685 assert( TK_GT==OP_Gt );
40686 assert( TK_GE==OP_Ge );
40687 assert( TK_EQ==OP_Eq );
40688 assert( TK_NE==OP_Ne );
40689 sqlite3ExprCode(pParse, pExpr->pLeft);
40690 sqlite3ExprCode(pParse, pExpr->pRight);
40691 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
40692 stackChng = -1;
40693 break;
40695 case TK_AND:
40696 case TK_OR:
40697 case TK_PLUS:
40698 case TK_STAR:
40699 case TK_MINUS:
40700 case TK_REM:
40701 case TK_BITAND:
40702 case TK_BITOR:
40703 case TK_SLASH:
40704 case TK_LSHIFT:
40705 case TK_RSHIFT:
40706 case TK_CONCAT: {
40707 assert( TK_AND==OP_And );
40708 assert( TK_OR==OP_Or );
40709 assert( TK_PLUS==OP_Add );
40710 assert( TK_MINUS==OP_Subtract );
40711 assert( TK_REM==OP_Remainder );
40712 assert( TK_BITAND==OP_BitAnd );
40713 assert( TK_BITOR==OP_BitOr );
40714 assert( TK_SLASH==OP_Divide );
40715 assert( TK_LSHIFT==OP_ShiftLeft );
40716 assert( TK_RSHIFT==OP_ShiftRight );
40717 assert( TK_CONCAT==OP_Concat );
40718 sqlite3ExprCode(pParse, pExpr->pLeft);
40719 sqlite3ExprCode(pParse, pExpr->pRight);
40720 sqlite3VdbeAddOp(v, op, 0, 0);
40721 stackChng = -1;
40722 break;
40724 case TK_UMINUS: {
40725 Expr *pLeft = pExpr->pLeft;
40726 assert( pLeft );
40727 if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
40728 Token *p = &pLeft->token;
40729 char *z = sqlite3MPrintf("-%.*s", p->n, p->z);
40730 if( pLeft->op==TK_FLOAT ){
40731 sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
40732 }else{
40733 codeInteger(v, z, p->n+1);
40735 sqliteFree(z);
40736 break;
40738 /* Fall through into TK_NOT */
40740 case TK_BITNOT:
40741 case TK_NOT: {
40742 assert( TK_BITNOT==OP_BitNot );
40743 assert( TK_NOT==OP_Not );
40744 sqlite3ExprCode(pParse, pExpr->pLeft);
40745 sqlite3VdbeAddOp(v, op, 0, 0);
40746 stackChng = 0;
40747 break;
40749 case TK_ISNULL:
40750 case TK_NOTNULL: {
40751 int dest;
40752 assert( TK_ISNULL==OP_IsNull );
40753 assert( TK_NOTNULL==OP_NotNull );
40754 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
40755 sqlite3ExprCode(pParse, pExpr->pLeft);
40756 dest = sqlite3VdbeCurrentAddr(v) + 2;
40757 sqlite3VdbeAddOp(v, op, 1, dest);
40758 sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
40759 stackChng = 0;
40760 break;
40762 case TK_AGG_FUNCTION: {
40763 AggInfo *pInfo = pExpr->pAggInfo;
40764 if( pInfo==0 ){
40765 sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
40766 &pExpr->span);
40767 }else{
40768 sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
40770 break;
40772 case TK_CONST_FUNC:
40773 case TK_FUNCTION: {
40774 ExprList *pList = pExpr->pList;
40775 int nExpr = pList ? pList->nExpr : 0;
40776 FuncDef *pDef;
40777 int nId;
40778 const char *zId;
40779 int constMask = 0;
40780 int i;
40781 u8 enc = ENC(pParse->db);
40782 CollSeq *pColl = 0;
40783 zId = (char*)pExpr->token.z;
40784 nId = pExpr->token.n;
40785 pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
40786 assert( pDef!=0 );
40787 nExpr = sqlite3ExprCodeExprList(pParse, pList);
40788 #ifndef SQLITE_OMIT_VIRTUALTABLE
40789 /* Possibly overload the function if the first argument is
40790 ** a virtual table column.
40792 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
40793 ** second argument, not the first, as the argument to test to
40794 ** see if it is a column in a virtual table. This is done because
40795 ** the left operand of infix functions (the operand we want to
40796 ** control overloading) ends up as the second argument to the
40797 ** function. The expression "A glob B" is equivalent to
40798 ** "glob(B,A). We want to use the A in "A glob B" to test
40799 ** for function overloading. But we use the B term in "glob(B,A)".
40801 if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
40802 pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[1].pExpr);
40803 }else if( nExpr>0 ){
40804 pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[0].pExpr);
40806 #endif
40807 for(i=0; i<nExpr && i<32; i++){
40808 if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
40809 constMask |= (1<<i);
40811 if( pDef->needCollSeq && !pColl ){
40812 pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
40815 if( pDef->needCollSeq ){
40816 if( !pColl ) pColl = pParse->db->pDfltColl;
40817 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
40819 sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
40820 stackChng = 1-nExpr;
40821 break;
40823 #ifndef SQLITE_OMIT_SUBQUERY
40824 case TK_EXISTS:
40825 case TK_SELECT: {
40826 if( pExpr->iColumn==0 ){
40827 sqlite3CodeSubselect(pParse, pExpr);
40829 sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
40830 VdbeComment((v, "# load subquery result"));
40831 break;
40833 case TK_IN: {
40834 int addr;
40835 char affinity;
40836 int ckOffset = pParse->ckOffset;
40837 sqlite3CodeSubselect(pParse, pExpr);
40839 /* Figure out the affinity to use to create a key from the results
40840 ** of the expression. affinityStr stores a static string suitable for
40841 ** P3 of OP_MakeRecord.
40843 affinity = comparisonAffinity(pExpr);
40845 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
40846 pParse->ckOffset = (ckOffset ? (ckOffset+1) : 0);
40848 /* Code the <expr> from "<expr> IN (...)". The temporary table
40849 ** pExpr->iTable contains the values that make up the (...) set.
40851 sqlite3ExprCode(pParse, pExpr->pLeft);
40852 addr = sqlite3VdbeCurrentAddr(v);
40853 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4); /* addr + 0 */
40854 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
40855 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
40856 sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
40857 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1); /* addr + 4 */
40858 sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
40859 sqlite3VdbeAddOp(v, OP_AddImm, -1, 0); /* addr + 6 */
40861 break;
40863 #endif
40864 case TK_BETWEEN: {
40865 Expr *pLeft = pExpr->pLeft;
40866 struct ExprList_item *pLItem = pExpr->pList->a;
40867 Expr *pRight = pLItem->pExpr;
40868 sqlite3ExprCode(pParse, pLeft);
40869 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
40870 sqlite3ExprCode(pParse, pRight);
40871 codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
40872 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
40873 pLItem++;
40874 pRight = pLItem->pExpr;
40875 sqlite3ExprCode(pParse, pRight);
40876 codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
40877 sqlite3VdbeAddOp(v, OP_And, 0, 0);
40878 break;
40880 case TK_UPLUS: {
40881 sqlite3ExprCode(pParse, pExpr->pLeft);
40882 stackChng = 0;
40883 break;
40885 case TK_CASE: {
40886 int expr_end_label;
40887 int jumpInst;
40888 int nExpr;
40889 int i;
40890 ExprList *pEList;
40891 struct ExprList_item *aListelem;
40893 assert(pExpr->pList);
40894 assert((pExpr->pList->nExpr % 2) == 0);
40895 assert(pExpr->pList->nExpr > 0);
40896 pEList = pExpr->pList;
40897 aListelem = pEList->a;
40898 nExpr = pEList->nExpr;
40899 expr_end_label = sqlite3VdbeMakeLabel(v);
40900 if( pExpr->pLeft ){
40901 sqlite3ExprCode(pParse, pExpr->pLeft);
40903 for(i=0; i<nExpr; i=i+2){
40904 sqlite3ExprCode(pParse, aListelem[i].pExpr);
40905 if( pExpr->pLeft ){
40906 sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
40907 jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
40908 OP_Ne, 0, 1);
40909 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
40910 }else{
40911 jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
40913 sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
40914 sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
40915 sqlite3VdbeJumpHere(v, jumpInst);
40917 if( pExpr->pLeft ){
40918 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
40920 if( pExpr->pRight ){
40921 sqlite3ExprCode(pParse, pExpr->pRight);
40922 }else{
40923 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
40925 sqlite3VdbeResolveLabel(v, expr_end_label);
40926 break;
40928 #ifndef SQLITE_OMIT_TRIGGER
40929 case TK_RAISE: {
40930 if( !pParse->trigStack ){
40931 sqlite3ErrorMsg(pParse,
40932 "RAISE() may only be used within a trigger-program");
40933 return;
40935 if( pExpr->iColumn!=OE_Ignore ){
40936 assert( pExpr->iColumn==OE_Rollback ||
40937 pExpr->iColumn == OE_Abort ||
40938 pExpr->iColumn == OE_Fail );
40939 sqlite3DequoteExpr(pExpr);
40940 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
40941 (char*)pExpr->token.z, pExpr->token.n);
40942 } else {
40943 assert( pExpr->iColumn == OE_Ignore );
40944 sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
40945 sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
40946 VdbeComment((v, "# raise(IGNORE)"));
40948 stackChng = 0;
40949 break;
40951 #endif
40954 if( pParse->ckOffset ){
40955 pParse->ckOffset += stackChng;
40956 assert( pParse->ckOffset );
40960 #ifndef SQLITE_OMIT_TRIGGER
40962 ** Generate code that evalutes the given expression and leaves the result
40963 ** on the stack. See also sqlite3ExprCode().
40965 ** This routine might also cache the result and modify the pExpr tree
40966 ** so that it will make use of the cached result on subsequent evaluations
40967 ** rather than evaluate the whole expression again. Trivial expressions are
40968 ** not cached. If the expression is cached, its result is stored in a
40969 ** memory location.
40971 static void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
40972 Vdbe *v = pParse->pVdbe;
40973 int iMem;
40974 int addr1, addr2;
40975 if( v==0 ) return;
40976 addr1 = sqlite3VdbeCurrentAddr(v);
40977 sqlite3ExprCode(pParse, pExpr);
40978 addr2 = sqlite3VdbeCurrentAddr(v);
40979 if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
40980 iMem = pExpr->iTable = pParse->nMem++;
40981 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
40982 pExpr->op = TK_REGISTER;
40985 #endif
40988 ** Generate code that pushes the value of every element of the given
40989 ** expression list onto the stack.
40991 ** Return the number of elements pushed onto the stack.
40993 static int sqlite3ExprCodeExprList(
40994 Parse *pParse, /* Parsing context */
40995 ExprList *pList /* The expression list to be coded */
40997 struct ExprList_item *pItem;
40998 int i, n;
40999 if( pList==0 ) return 0;
41000 n = pList->nExpr;
41001 for(pItem=pList->a, i=n; i>0; i--, pItem++){
41002 sqlite3ExprCode(pParse, pItem->pExpr);
41004 return n;
41008 ** Generate code for a boolean expression such that a jump is made
41009 ** to the label "dest" if the expression is true but execution
41010 ** continues straight thru if the expression is false.
41012 ** If the expression evaluates to NULL (neither true nor false), then
41013 ** take the jump if the jumpIfNull flag is true.
41015 ** This code depends on the fact that certain token values (ex: TK_EQ)
41016 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
41017 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
41018 ** the make process cause these values to align. Assert()s in the code
41019 ** below verify that the numbers are aligned correctly.
41021 static void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
41022 Vdbe *v = pParse->pVdbe;
41023 int op = 0;
41024 int ckOffset = pParse->ckOffset;
41025 if( v==0 || pExpr==0 ) return;
41026 op = pExpr->op;
41027 switch( op ){
41028 case TK_AND: {
41029 int d2 = sqlite3VdbeMakeLabel(v);
41030 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
41031 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
41032 sqlite3VdbeResolveLabel(v, d2);
41033 break;
41035 case TK_OR: {
41036 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
41037 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
41038 break;
41040 case TK_NOT: {
41041 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
41042 break;
41044 case TK_LT:
41045 case TK_LE:
41046 case TK_GT:
41047 case TK_GE:
41048 case TK_NE:
41049 case TK_EQ: {
41050 assert( TK_LT==OP_Lt );
41051 assert( TK_LE==OP_Le );
41052 assert( TK_GT==OP_Gt );
41053 assert( TK_GE==OP_Ge );
41054 assert( TK_EQ==OP_Eq );
41055 assert( TK_NE==OP_Ne );
41056 sqlite3ExprCode(pParse, pExpr->pLeft);
41057 sqlite3ExprCode(pParse, pExpr->pRight);
41058 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
41059 break;
41061 case TK_ISNULL:
41062 case TK_NOTNULL: {
41063 assert( TK_ISNULL==OP_IsNull );
41064 assert( TK_NOTNULL==OP_NotNull );
41065 sqlite3ExprCode(pParse, pExpr->pLeft);
41066 sqlite3VdbeAddOp(v, op, 1, dest);
41067 break;
41069 case TK_BETWEEN: {
41070 /* The expression "x BETWEEN y AND z" is implemented as:
41072 ** 1 IF (x < y) GOTO 3
41073 ** 2 IF (x <= z) GOTO <dest>
41074 ** 3 ...
41076 int addr;
41077 Expr *pLeft = pExpr->pLeft;
41078 Expr *pRight = pExpr->pList->a[0].pExpr;
41079 sqlite3ExprCode(pParse, pLeft);
41080 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
41081 sqlite3ExprCode(pParse, pRight);
41082 addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
41084 pRight = pExpr->pList->a[1].pExpr;
41085 sqlite3ExprCode(pParse, pRight);
41086 codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
41088 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
41089 sqlite3VdbeJumpHere(v, addr);
41090 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
41091 break;
41093 default: {
41094 sqlite3ExprCode(pParse, pExpr);
41095 sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
41096 break;
41099 pParse->ckOffset = ckOffset;
41103 ** Generate code for a boolean expression such that a jump is made
41104 ** to the label "dest" if the expression is false but execution
41105 ** continues straight thru if the expression is true.
41107 ** If the expression evaluates to NULL (neither true nor false) then
41108 ** jump if jumpIfNull is true or fall through if jumpIfNull is false.
41110 static void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
41111 Vdbe *v = pParse->pVdbe;
41112 int op = 0;
41113 int ckOffset = pParse->ckOffset;
41114 if( v==0 || pExpr==0 ) return;
41116 /* The value of pExpr->op and op are related as follows:
41118 ** pExpr->op op
41119 ** --------- ----------
41120 ** TK_ISNULL OP_NotNull
41121 ** TK_NOTNULL OP_IsNull
41122 ** TK_NE OP_Eq
41123 ** TK_EQ OP_Ne
41124 ** TK_GT OP_Le
41125 ** TK_LE OP_Gt
41126 ** TK_GE OP_Lt
41127 ** TK_LT OP_Ge
41129 ** For other values of pExpr->op, op is undefined and unused.
41130 ** The value of TK_ and OP_ constants are arranged such that we
41131 ** can compute the mapping above using the following expression.
41132 ** Assert()s verify that the computation is correct.
41134 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
41136 /* Verify correct alignment of TK_ and OP_ constants
41138 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
41139 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
41140 assert( pExpr->op!=TK_NE || op==OP_Eq );
41141 assert( pExpr->op!=TK_EQ || op==OP_Ne );
41142 assert( pExpr->op!=TK_LT || op==OP_Ge );
41143 assert( pExpr->op!=TK_LE || op==OP_Gt );
41144 assert( pExpr->op!=TK_GT || op==OP_Le );
41145 assert( pExpr->op!=TK_GE || op==OP_Lt );
41147 switch( pExpr->op ){
41148 case TK_AND: {
41149 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
41150 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
41151 break;
41153 case TK_OR: {
41154 int d2 = sqlite3VdbeMakeLabel(v);
41155 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
41156 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
41157 sqlite3VdbeResolveLabel(v, d2);
41158 break;
41160 case TK_NOT: {
41161 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
41162 break;
41164 case TK_LT:
41165 case TK_LE:
41166 case TK_GT:
41167 case TK_GE:
41168 case TK_NE:
41169 case TK_EQ: {
41170 sqlite3ExprCode(pParse, pExpr->pLeft);
41171 sqlite3ExprCode(pParse, pExpr->pRight);
41172 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
41173 break;
41175 case TK_ISNULL:
41176 case TK_NOTNULL: {
41177 sqlite3ExprCode(pParse, pExpr->pLeft);
41178 sqlite3VdbeAddOp(v, op, 1, dest);
41179 break;
41181 case TK_BETWEEN: {
41182 /* The expression is "x BETWEEN y AND z". It is implemented as:
41184 ** 1 IF (x >= y) GOTO 3
41185 ** 2 GOTO <dest>
41186 ** 3 IF (x > z) GOTO <dest>
41188 int addr;
41189 Expr *pLeft = pExpr->pLeft;
41190 Expr *pRight = pExpr->pList->a[0].pExpr;
41191 sqlite3ExprCode(pParse, pLeft);
41192 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
41193 sqlite3ExprCode(pParse, pRight);
41194 addr = sqlite3VdbeCurrentAddr(v);
41195 codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
41197 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
41198 sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
41199 pRight = pExpr->pList->a[1].pExpr;
41200 sqlite3ExprCode(pParse, pRight);
41201 codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
41202 break;
41204 default: {
41205 sqlite3ExprCode(pParse, pExpr);
41206 sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
41207 break;
41210 pParse->ckOffset = ckOffset;
41214 ** Do a deep comparison of two expression trees. Return TRUE (non-zero)
41215 ** if they are identical and return FALSE if they differ in any way.
41217 ** Sometimes this routine will return FALSE even if the two expressions
41218 ** really are equivalent. If we cannot prove that the expressions are
41219 ** identical, we return FALSE just to be safe. So if this routine
41220 ** returns false, then you do not really know for certain if the two
41221 ** expressions are the same. But if you get a TRUE return, then you
41222 ** can be sure the expressions are the same. In the places where
41223 ** this routine is used, it does not hurt to get an extra FALSE - that
41224 ** just might result in some slightly slower code. But returning
41225 ** an incorrect TRUE could lead to a malfunction.
41227 static int sqlite3ExprCompare(Expr *pA, Expr *pB){
41228 int i;
41229 if( pA==0||pB==0 ){
41230 return pB==pA;
41232 if( pA->op!=pB->op ) return 0;
41233 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
41234 if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
41235 if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
41236 if( pA->pList ){
41237 if( pB->pList==0 ) return 0;
41238 if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
41239 for(i=0; i<pA->pList->nExpr; i++){
41240 if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
41241 return 0;
41244 }else if( pB->pList ){
41245 return 0;
41247 if( pA->pSelect || pB->pSelect ) return 0;
41248 if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
41249 if( pA->op!=TK_COLUMN && pA->token.z ){
41250 if( pB->token.z==0 ) return 0;
41251 if( pB->token.n!=pA->token.n ) return 0;
41252 if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
41253 return 0;
41256 return 1;
41261 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
41262 ** the new element. Return a negative number if malloc fails.
41264 static int addAggInfoColumn(AggInfo *pInfo){
41265 int i;
41266 pInfo->aCol = sqlite3ArrayAllocate(
41267 pInfo->aCol,
41268 sizeof(pInfo->aCol[0]),
41270 &pInfo->nColumn,
41271 &pInfo->nColumnAlloc,
41274 return i;
41278 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
41279 ** the new element. Return a negative number if malloc fails.
41281 static int addAggInfoFunc(AggInfo *pInfo){
41282 int i;
41283 pInfo->aFunc = sqlite3ArrayAllocate(
41284 pInfo->aFunc,
41285 sizeof(pInfo->aFunc[0]),
41287 &pInfo->nFunc,
41288 &pInfo->nFuncAlloc,
41291 return i;
41295 ** This is an xFunc for walkExprTree() used to implement
41296 ** sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
41297 ** for additional information.
41299 ** This routine analyzes the aggregate function at pExpr.
41301 static int analyzeAggregate(void *pArg, Expr *pExpr){
41302 int i;
41303 NameContext *pNC = (NameContext *)pArg;
41304 Parse *pParse = pNC->pParse;
41305 SrcList *pSrcList = pNC->pSrcList;
41306 AggInfo *pAggInfo = pNC->pAggInfo;
41309 switch( pExpr->op ){
41310 case TK_AGG_COLUMN:
41311 case TK_COLUMN: {
41312 /* Check to see if the column is in one of the tables in the FROM
41313 ** clause of the aggregate query */
41314 if( pSrcList ){
41315 struct SrcList_item *pItem = pSrcList->a;
41316 for(i=0; i<pSrcList->nSrc; i++, pItem++){
41317 struct AggInfo_col *pCol;
41318 if( pExpr->iTable==pItem->iCursor ){
41319 /* If we reach this point, it means that pExpr refers to a table
41320 ** that is in the FROM clause of the aggregate query.
41322 ** Make an entry for the column in pAggInfo->aCol[] if there
41323 ** is not an entry there already.
41325 int k;
41326 pCol = pAggInfo->aCol;
41327 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
41328 if( pCol->iTable==pExpr->iTable &&
41329 pCol->iColumn==pExpr->iColumn ){
41330 break;
41333 if( k>=pAggInfo->nColumn && (k = addAggInfoColumn(pAggInfo))>=0 ){
41334 pCol = &pAggInfo->aCol[k];
41335 pCol->pTab = pExpr->pTab;
41336 pCol->iTable = pExpr->iTable;
41337 pCol->iColumn = pExpr->iColumn;
41338 pCol->iMem = pParse->nMem++;
41339 pCol->iSorterColumn = -1;
41340 pCol->pExpr = pExpr;
41341 if( pAggInfo->pGroupBy ){
41342 int j, n;
41343 ExprList *pGB = pAggInfo->pGroupBy;
41344 struct ExprList_item *pTerm = pGB->a;
41345 n = pGB->nExpr;
41346 for(j=0; j<n; j++, pTerm++){
41347 Expr *pE = pTerm->pExpr;
41348 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
41349 pE->iColumn==pExpr->iColumn ){
41350 pCol->iSorterColumn = j;
41351 break;
41355 if( pCol->iSorterColumn<0 ){
41356 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
41359 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
41360 ** because it was there before or because we just created it).
41361 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
41362 ** pAggInfo->aCol[] entry.
41364 pExpr->pAggInfo = pAggInfo;
41365 pExpr->op = TK_AGG_COLUMN;
41366 pExpr->iAgg = k;
41367 break;
41368 } /* endif pExpr->iTable==pItem->iCursor */
41369 } /* end loop over pSrcList */
41371 return 1;
41373 case TK_AGG_FUNCTION: {
41374 /* The pNC->nDepth==0 test causes aggregate functions in subqueries
41375 ** to be ignored */
41376 if( pNC->nDepth==0 ){
41377 /* Check to see if pExpr is a duplicate of another aggregate
41378 ** function that is already in the pAggInfo structure
41380 struct AggInfo_func *pItem = pAggInfo->aFunc;
41381 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
41382 if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
41383 break;
41386 if( i>=pAggInfo->nFunc ){
41387 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
41389 u8 enc = ENC(pParse->db);
41390 i = addAggInfoFunc(pAggInfo);
41391 if( i>=0 ){
41392 pItem = &pAggInfo->aFunc[i];
41393 pItem->pExpr = pExpr;
41394 pItem->iMem = pParse->nMem++;
41395 pItem->pFunc = sqlite3FindFunction(pParse->db,
41396 (char*)pExpr->token.z, pExpr->token.n,
41397 pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
41398 if( pExpr->flags & EP_Distinct ){
41399 pItem->iDistinct = pParse->nTab++;
41400 }else{
41401 pItem->iDistinct = -1;
41405 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
41407 pExpr->iAgg = i;
41408 pExpr->pAggInfo = pAggInfo;
41409 return 1;
41414 /* Recursively walk subqueries looking for TK_COLUMN nodes that need
41415 ** to be changed to TK_AGG_COLUMN. But increment nDepth so that
41416 ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
41418 if( pExpr->pSelect ){
41419 pNC->nDepth++;
41420 walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
41421 pNC->nDepth--;
41423 return 0;
41427 ** Analyze the given expression looking for aggregate functions and
41428 ** for variables that need to be added to the pParse->aAgg[] array.
41429 ** Make additional entries to the pParse->aAgg[] array as necessary.
41431 ** This routine should only be called after the expression has been
41432 ** analyzed by sqlite3ExprResolveNames().
41434 ** If errors are seen, leave an error message in zErrMsg and return
41435 ** the number of errors.
41437 static int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
41438 int nErr = pNC->pParse->nErr;
41439 walkExprTree(pExpr, analyzeAggregate, pNC);
41440 return pNC->pParse->nErr - nErr;
41444 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
41445 ** expression list. Return the number of errors.
41447 ** If an error is found, the analysis is cut short.
41449 static int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
41450 struct ExprList_item *pItem;
41451 int i;
41452 int nErr = 0;
41453 if( pList ){
41454 for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
41455 nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
41458 return nErr;
41461 /************** End of expr.c ************************************************/
41462 /************** Begin file alter.c *******************************************/
41464 ** 2005 February 15
41466 ** The author disclaims copyright to this source code. In place of
41467 ** a legal notice, here is a blessing:
41469 ** May you do good and not evil.
41470 ** May you find forgiveness for yourself and forgive others.
41471 ** May you share freely, never taking more than you give.
41473 *************************************************************************
41474 ** This file contains C code routines that used to generate VDBE code
41475 ** that implements the ALTER TABLE command.
41477 ** $Id: alter.c,v 1.25 2007/05/15 14:34:32 drh Exp $
41481 ** The code in this file only exists if we are not omitting the
41482 ** ALTER TABLE logic from the build.
41484 #ifndef SQLITE_OMIT_ALTERTABLE
41488 ** This function is used by SQL generated to implement the
41489 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
41490 ** CREATE INDEX command. The second is a table name. The table name in
41491 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
41492 ** argument and the result returned. Examples:
41494 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
41495 ** -> 'CREATE TABLE def(a, b, c)'
41497 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
41498 ** -> 'CREATE INDEX i ON def(a, b, c)'
41500 static void renameTableFunc(
41501 sqlite3_context *context,
41502 int argc,
41503 sqlite3_value **argv
41505 unsigned char const *zSql = sqlite3_value_text(argv[0]);
41506 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
41508 int token;
41509 Token tname;
41510 unsigned char const *zCsr = zSql;
41511 int len = 0;
41512 char *zRet;
41514 /* The principle used to locate the table name in the CREATE TABLE
41515 ** statement is that the table name is the first token that is immediatedly
41516 ** followed by a left parenthesis - TK_LP.
41518 if( zSql ){
41519 do {
41520 if( !*zCsr ){
41521 /* Ran out of input before finding an opening bracket. Return NULL. */
41522 return;
41525 /* Store the token that zCsr points to in tname. */
41526 tname.z = zCsr;
41527 tname.n = len;
41529 /* Advance zCsr to the next token. Store that token type in 'token',
41530 ** and it's length in 'len' (to be used next iteration of this loop).
41532 do {
41533 zCsr += len;
41534 len = sqlite3GetToken(zCsr, &token);
41535 } while( token==TK_SPACE );
41536 assert( len>0 );
41537 } while( token!=TK_LP );
41539 zRet = sqlite3MPrintf("%.*s%Q%s", tname.z - zSql, zSql,
41540 zTableName, tname.z+tname.n);
41541 sqlite3_result_text(context, zRet, -1, sqlite3FreeX);
41545 #ifndef SQLITE_OMIT_TRIGGER
41546 /* This function is used by SQL generated to implement the
41547 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
41548 ** statement. The second is a table name. The table name in the CREATE
41549 ** TRIGGER statement is replaced with the third argument and the result
41550 ** returned. This is analagous to renameTableFunc() above, except for CREATE
41551 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
41553 static void renameTriggerFunc(
41554 sqlite3_context *context,
41555 int argc,
41556 sqlite3_value **argv
41558 unsigned char const *zSql = sqlite3_value_text(argv[0]);
41559 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
41561 int token;
41562 Token tname;
41563 int dist = 3;
41564 unsigned char const *zCsr = zSql;
41565 int len = 0;
41566 char *zRet;
41568 /* The principle used to locate the table name in the CREATE TRIGGER
41569 ** statement is that the table name is the first token that is immediatedly
41570 ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
41571 ** of TK_WHEN, TK_BEGIN or TK_FOR.
41573 if( zSql ){
41574 do {
41576 if( !*zCsr ){
41577 /* Ran out of input before finding the table name. Return NULL. */
41578 return;
41581 /* Store the token that zCsr points to in tname. */
41582 tname.z = zCsr;
41583 tname.n = len;
41585 /* Advance zCsr to the next token. Store that token type in 'token',
41586 ** and it's length in 'len' (to be used next iteration of this loop).
41588 do {
41589 zCsr += len;
41590 len = sqlite3GetToken(zCsr, &token);
41591 }while( token==TK_SPACE );
41592 assert( len>0 );
41594 /* Variable 'dist' stores the number of tokens read since the most
41595 ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
41596 ** token is read and 'dist' equals 2, the condition stated above
41597 ** to be met.
41599 ** Note that ON cannot be a database, table or column name, so
41600 ** there is no need to worry about syntax like
41601 ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
41603 dist++;
41604 if( token==TK_DOT || token==TK_ON ){
41605 dist = 0;
41607 } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
41609 /* Variable tname now contains the token that is the old table-name
41610 ** in the CREATE TRIGGER statement.
41612 zRet = sqlite3MPrintf("%.*s%Q%s", tname.z - zSql, zSql,
41613 zTableName, tname.z+tname.n);
41614 sqlite3_result_text(context, zRet, -1, sqlite3FreeX);
41617 #endif /* !SQLITE_OMIT_TRIGGER */
41620 ** Register built-in functions used to help implement ALTER TABLE
41622 static void sqlite3AlterFunctions(sqlite3 *db){
41623 static const struct {
41624 char *zName;
41625 signed char nArg;
41626 void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
41627 } aFuncs[] = {
41628 { "sqlite_rename_table", 2, renameTableFunc},
41629 #ifndef SQLITE_OMIT_TRIGGER
41630 { "sqlite_rename_trigger", 2, renameTriggerFunc},
41631 #endif
41633 int i;
41635 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
41636 sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
41637 SQLITE_UTF8, 0, aFuncs[i].xFunc, 0, 0);
41642 ** Generate the text of a WHERE expression which can be used to select all
41643 ** temporary triggers on table pTab from the sqlite_temp_master table. If
41644 ** table pTab has no temporary triggers, or is itself stored in the
41645 ** temporary database, NULL is returned.
41647 static char *whereTempTriggers(Parse *pParse, Table *pTab){
41648 Trigger *pTrig;
41649 char *zWhere = 0;
41650 char *tmp = 0;
41651 const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
41653 /* If the table is not located in the temp-db (in which case NULL is
41654 ** returned, loop through the tables list of triggers. For each trigger
41655 ** that is not part of the temp-db schema, add a clause to the WHERE
41656 ** expression being built up in zWhere.
41658 if( pTab->pSchema!=pTempSchema ){
41659 for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
41660 if( pTrig->pSchema==pTempSchema ){
41661 if( !zWhere ){
41662 zWhere = sqlite3MPrintf("name=%Q", pTrig->name);
41663 }else{
41664 tmp = zWhere;
41665 zWhere = sqlite3MPrintf("%s OR name=%Q", zWhere, pTrig->name);
41666 sqliteFree(tmp);
41671 return zWhere;
41675 ** Generate code to drop and reload the internal representation of table
41676 ** pTab from the database, including triggers and temporary triggers.
41677 ** Argument zName is the name of the table in the database schema at
41678 ** the time the generated code is executed. This can be different from
41679 ** pTab->zName if this function is being called to code part of an
41680 ** "ALTER TABLE RENAME TO" statement.
41682 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
41683 Vdbe *v;
41684 char *zWhere;
41685 int iDb; /* Index of database containing pTab */
41686 #ifndef SQLITE_OMIT_TRIGGER
41687 Trigger *pTrig;
41688 #endif
41690 v = sqlite3GetVdbe(pParse);
41691 if( !v ) return;
41692 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
41693 assert( iDb>=0 );
41695 #ifndef SQLITE_OMIT_TRIGGER
41696 /* Drop any table triggers from the internal schema. */
41697 for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
41698 int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
41699 assert( iTrigDb==iDb || iTrigDb==1 );
41700 sqlite3VdbeOp3(v, OP_DropTrigger, iTrigDb, 0, pTrig->name, 0);
41702 #endif
41704 /* Drop the table and index from the internal schema */
41705 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
41707 /* Reload the table, index and permanent trigger schemas. */
41708 zWhere = sqlite3MPrintf("tbl_name=%Q", zName);
41709 if( !zWhere ) return;
41710 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, zWhere, P3_DYNAMIC);
41712 #ifndef SQLITE_OMIT_TRIGGER
41713 /* Now, if the table is not stored in the temp database, reload any temp
41714 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
41716 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
41717 sqlite3VdbeOp3(v, OP_ParseSchema, 1, 0, zWhere, P3_DYNAMIC);
41719 #endif
41723 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
41724 ** command.
41726 static void sqlite3AlterRenameTable(
41727 Parse *pParse, /* Parser context. */
41728 SrcList *pSrc, /* The table to rename. */
41729 Token *pName /* The new table name. */
41731 int iDb; /* Database that contains the table */
41732 char *zDb; /* Name of database iDb */
41733 Table *pTab; /* Table being renamed */
41734 char *zName = 0; /* NULL-terminated version of pName */
41735 sqlite3 *db = pParse->db; /* Database connection */
41736 int nTabName; /* Number of UTF-8 characters in zTabName */
41737 const char *zTabName; /* Original name of the table */
41738 Vdbe *v;
41739 #ifndef SQLITE_OMIT_TRIGGER
41740 char *zWhere = 0; /* Where clause to locate temp triggers */
41741 #endif
41743 if( sqlite3MallocFailed() ) goto exit_rename_table;
41744 assert( pSrc->nSrc==1 );
41746 pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
41747 if( !pTab ) goto exit_rename_table;
41748 #ifndef SQLITE_OMIT_VIRTUALTABLE
41749 if( IsVirtual(pTab) ){
41750 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
41751 goto exit_rename_table;
41753 #endif
41754 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
41755 zDb = db->aDb[iDb].zName;
41757 /* Get a NULL terminated version of the new table name. */
41758 zName = sqlite3NameFromToken(pName);
41759 if( !zName ) goto exit_rename_table;
41761 /* Check that a table or index named 'zName' does not already exist
41762 ** in database iDb. If so, this is an error.
41764 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
41765 sqlite3ErrorMsg(pParse,
41766 "there is already another table or index with this name: %s", zName);
41767 goto exit_rename_table;
41770 /* Make sure it is not a system table being altered, or a reserved name
41771 ** that the table is being renamed to.
41773 if( strlen(pTab->zName)>6 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ){
41774 sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
41775 goto exit_rename_table;
41777 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
41778 goto exit_rename_table;
41781 #ifndef SQLITE_OMIT_AUTHORIZATION
41782 /* Invoke the authorization callback. */
41783 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
41784 goto exit_rename_table;
41786 #endif
41788 /* Begin a transaction and code the VerifyCookie for database iDb.
41789 ** Then modify the schema cookie (since the ALTER TABLE modifies the
41790 ** schema).
41792 v = sqlite3GetVdbe(pParse);
41793 if( v==0 ){
41794 goto exit_rename_table;
41796 sqlite3BeginWriteOperation(pParse, 0, iDb);
41797 sqlite3ChangeCookie(db, v, iDb);
41799 /* figure out how many UTF-8 characters are in zName */
41800 zTabName = pTab->zName;
41801 nTabName = sqlite3Utf8CharLen(zTabName, -1);
41803 /* Modify the sqlite_master table to use the new table name. */
41804 sqlite3NestedParse(pParse,
41805 "UPDATE %Q.%s SET "
41806 #ifdef SQLITE_OMIT_TRIGGER
41807 "sql = sqlite_rename_table(sql, %Q), "
41808 #else
41809 "sql = CASE "
41810 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
41811 "ELSE sqlite_rename_table(sql, %Q) END, "
41812 #endif
41813 "tbl_name = %Q, "
41814 "name = CASE "
41815 "WHEN type='table' THEN %Q "
41816 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
41817 "'sqlite_autoindex_' || %Q || substr(name,%d+18,10) "
41818 "ELSE name END "
41819 "WHERE tbl_name=%Q AND "
41820 "(type='table' OR type='index' OR type='trigger');",
41821 zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
41822 #ifndef SQLITE_OMIT_TRIGGER
41823 zName,
41824 #endif
41825 zName, nTabName, zTabName
41828 #ifndef SQLITE_OMIT_AUTOINCREMENT
41829 /* If the sqlite_sequence table exists in this database, then update
41830 ** it with the new table name.
41832 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
41833 sqlite3NestedParse(pParse,
41834 "UPDATE %Q.sqlite_sequence set name = %Q WHERE name = %Q",
41835 zDb, zName, pTab->zName);
41837 #endif
41839 #ifndef SQLITE_OMIT_TRIGGER
41840 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
41841 ** table. Don't do this if the table being ALTERed is itself located in
41842 ** the temp database.
41844 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
41845 sqlite3NestedParse(pParse,
41846 "UPDATE sqlite_temp_master SET "
41847 "sql = sqlite_rename_trigger(sql, %Q), "
41848 "tbl_name = %Q "
41849 "WHERE %s;", zName, zName, zWhere);
41850 sqliteFree(zWhere);
41852 #endif
41854 /* Drop and reload the internal table schema. */
41855 reloadTableSchema(pParse, pTab, zName);
41857 exit_rename_table:
41858 sqlite3SrcListDelete(pSrc);
41859 sqliteFree(zName);
41864 ** This function is called after an "ALTER TABLE ... ADD" statement
41865 ** has been parsed. Argument pColDef contains the text of the new
41866 ** column definition.
41868 ** The Table structure pParse->pNewTable was extended to include
41869 ** the new column during parsing.
41871 static void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
41872 Table *pNew; /* Copy of pParse->pNewTable */
41873 Table *pTab; /* Table being altered */
41874 int iDb; /* Database number */
41875 const char *zDb; /* Database name */
41876 const char *zTab; /* Table name */
41877 char *zCol; /* Null-terminated column definition */
41878 Column *pCol; /* The new column */
41879 Expr *pDflt; /* Default value for the new column */
41881 if( pParse->nErr ) return;
41882 pNew = pParse->pNewTable;
41883 assert( pNew );
41885 iDb = sqlite3SchemaToIndex(pParse->db, pNew->pSchema);
41886 zDb = pParse->db->aDb[iDb].zName;
41887 zTab = pNew->zName;
41888 pCol = &pNew->aCol[pNew->nCol-1];
41889 pDflt = pCol->pDflt;
41890 pTab = sqlite3FindTable(pParse->db, zTab, zDb);
41891 assert( pTab );
41893 #ifndef SQLITE_OMIT_AUTHORIZATION
41894 /* Invoke the authorization callback. */
41895 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
41896 return;
41898 #endif
41900 /* If the default value for the new column was specified with a
41901 ** literal NULL, then set pDflt to 0. This simplifies checking
41902 ** for an SQL NULL default below.
41904 if( pDflt && pDflt->op==TK_NULL ){
41905 pDflt = 0;
41908 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
41909 ** If there is a NOT NULL constraint, then the default value for the
41910 ** column must not be NULL.
41912 if( pCol->isPrimKey ){
41913 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
41914 return;
41916 if( pNew->pIndex ){
41917 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
41918 return;
41920 if( pCol->notNull && !pDflt ){
41921 sqlite3ErrorMsg(pParse,
41922 "Cannot add a NOT NULL column with default value NULL");
41923 return;
41926 /* Ensure the default expression is something that sqlite3ValueFromExpr()
41927 ** can handle (i.e. not CURRENT_TIME etc.)
41929 if( pDflt ){
41930 sqlite3_value *pVal;
41931 if( sqlite3ValueFromExpr(pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
41932 /* malloc() has failed */
41933 return;
41935 if( !pVal ){
41936 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
41937 return;
41939 sqlite3ValueFree(pVal);
41942 /* Modify the CREATE TABLE statement. */
41943 zCol = sqliteStrNDup((char*)pColDef->z, pColDef->n);
41944 if( zCol ){
41945 char *zEnd = &zCol[pColDef->n-1];
41946 while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
41947 *zEnd-- = '\0';
41949 sqlite3NestedParse(pParse,
41950 "UPDATE %Q.%s SET "
41951 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d,length(sql)) "
41952 "WHERE type = 'table' AND name = %Q",
41953 zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
41954 zTab
41956 sqliteFree(zCol);
41959 /* If the default value of the new column is NULL, then set the file
41960 ** format to 2. If the default value of the new column is not NULL,
41961 ** the file format becomes 3.
41963 sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
41965 /* Reload the schema of the modified table. */
41966 reloadTableSchema(pParse, pTab, pTab->zName);
41970 ** This function is called by the parser after the table-name in
41971 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
41972 ** pSrc is the full-name of the table being altered.
41974 ** This routine makes a (partial) copy of the Table structure
41975 ** for the table being altered and sets Parse.pNewTable to point
41976 ** to it. Routines called by the parser as the column definition
41977 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
41978 ** the copy. The copy of the Table structure is deleted by tokenize.c
41979 ** after parsing is finished.
41981 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
41982 ** coding the "ALTER TABLE ... ADD" statement.
41984 static void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
41985 Table *pNew;
41986 Table *pTab;
41987 Vdbe *v;
41988 int iDb;
41989 int i;
41990 int nAlloc;
41992 /* Look up the table being altered. */
41993 assert( pParse->pNewTable==0 );
41994 if( sqlite3MallocFailed() ) goto exit_begin_add_column;
41995 pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
41996 if( !pTab ) goto exit_begin_add_column;
41998 #ifndef SQLITE_OMIT_VIRTUALTABLE
41999 if( IsVirtual(pTab) ){
42000 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
42001 goto exit_begin_add_column;
42003 #endif
42005 /* Make sure this is not an attempt to ALTER a view. */
42006 if( pTab->pSelect ){
42007 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
42008 goto exit_begin_add_column;
42011 assert( pTab->addColOffset>0 );
42012 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
42014 /* Put a copy of the Table struct in Parse.pNewTable for the
42015 ** sqlite3AddColumn() function and friends to modify.
42017 pNew = (Table *)sqliteMalloc(sizeof(Table));
42018 if( !pNew ) goto exit_begin_add_column;
42019 pParse->pNewTable = pNew;
42020 pNew->nRef = 1;
42021 pNew->nCol = pTab->nCol;
42022 assert( pNew->nCol>0 );
42023 nAlloc = (((pNew->nCol-1)/8)*8)+8;
42024 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
42025 pNew->aCol = (Column *)sqliteMalloc(sizeof(Column)*nAlloc);
42026 pNew->zName = sqliteStrDup(pTab->zName);
42027 if( !pNew->aCol || !pNew->zName ){
42028 goto exit_begin_add_column;
42030 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
42031 for(i=0; i<pNew->nCol; i++){
42032 Column *pCol = &pNew->aCol[i];
42033 pCol->zName = sqliteStrDup(pCol->zName);
42034 pCol->zColl = 0;
42035 pCol->zType = 0;
42036 pCol->pDflt = 0;
42038 pNew->pSchema = pParse->db->aDb[iDb].pSchema;
42039 pNew->addColOffset = pTab->addColOffset;
42040 pNew->nRef = 1;
42042 /* Begin a transaction and increment the schema cookie. */
42043 sqlite3BeginWriteOperation(pParse, 0, iDb);
42044 v = sqlite3GetVdbe(pParse);
42045 if( !v ) goto exit_begin_add_column;
42046 sqlite3ChangeCookie(pParse->db, v, iDb);
42048 exit_begin_add_column:
42049 sqlite3SrcListDelete(pSrc);
42050 return;
42052 #endif /* SQLITE_ALTER_TABLE */
42054 /************** End of alter.c ***********************************************/
42055 /************** Begin file analyze.c *****************************************/
42057 ** 2005 July 8
42059 ** The author disclaims copyright to this source code. In place of
42060 ** a legal notice, here is a blessing:
42062 ** May you do good and not evil.
42063 ** May you find forgiveness for yourself and forgive others.
42064 ** May you share freely, never taking more than you give.
42066 *************************************************************************
42067 ** This file contains code associated with the ANALYZE command.
42069 ** @(#) $Id: analyze.c,v 1.18 2007/05/12 12:08:51 drh Exp $
42071 #ifndef SQLITE_OMIT_ANALYZE
42074 ** This routine generates code that opens the sqlite_stat1 table on cursor
42075 ** iStatCur.
42077 ** If the sqlite_stat1 tables does not previously exist, it is created.
42078 ** If it does previously exist, all entires associated with table zWhere
42079 ** are removed. If zWhere==0 then all entries are removed.
42081 static void openStatTable(
42082 Parse *pParse, /* Parsing context */
42083 int iDb, /* The database we are looking in */
42084 int iStatCur, /* Open the sqlite_stat1 table on this cursor */
42085 const char *zWhere /* Delete entries associated with this table */
42087 sqlite3 *db = pParse->db;
42088 Db *pDb;
42089 int iRootPage;
42090 Table *pStat;
42091 Vdbe *v = sqlite3GetVdbe(pParse);
42093 if( v==0 ) return;
42094 pDb = &db->aDb[iDb];
42095 if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
42096 /* The sqlite_stat1 tables does not exist. Create it.
42097 ** Note that a side-effect of the CREATE TABLE statement is to leave
42098 ** the rootpage of the new table on the top of the stack. This is
42099 ** important because the OpenWrite opcode below will be needing it. */
42100 sqlite3NestedParse(pParse,
42101 "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
42102 pDb->zName
42104 iRootPage = 0; /* Cause rootpage to be taken from top of stack */
42105 }else if( zWhere ){
42106 /* The sqlite_stat1 table exists. Delete all entries associated with
42107 ** the table zWhere. */
42108 sqlite3NestedParse(pParse,
42109 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
42110 pDb->zName, zWhere
42112 iRootPage = pStat->tnum;
42113 }else{
42114 /* The sqlite_stat1 table already exists. Delete all rows. */
42115 iRootPage = pStat->tnum;
42116 sqlite3VdbeAddOp(v, OP_Clear, pStat->tnum, iDb);
42119 /* Open the sqlite_stat1 table for writing. Unless it was created
42120 ** by this vdbe program, lock it for writing at the shared-cache level.
42121 ** If this vdbe did create the sqlite_stat1 table, then it must have
42122 ** already obtained a schema-lock, making the write-lock redundant.
42124 if( iRootPage>0 ){
42125 sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
42127 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
42128 sqlite3VdbeAddOp(v, OP_OpenWrite, iStatCur, iRootPage);
42129 sqlite3VdbeAddOp(v, OP_SetNumColumns, iStatCur, 3);
42133 ** Generate code to do an analysis of all indices associated with
42134 ** a single table.
42136 static void analyzeOneTable(
42137 Parse *pParse, /* Parser context */
42138 Table *pTab, /* Table whose indices are to be analyzed */
42139 int iStatCur, /* Cursor that writes to the sqlite_stat1 table */
42140 int iMem /* Available memory locations begin here */
42142 Index *pIdx; /* An index to being analyzed */
42143 int iIdxCur; /* Cursor number for index being analyzed */
42144 int nCol; /* Number of columns in the index */
42145 Vdbe *v; /* The virtual machine being built up */
42146 int i; /* Loop counter */
42147 int topOfLoop; /* The top of the loop */
42148 int endOfLoop; /* The end of the loop */
42149 int addr; /* The address of an instruction */
42150 int iDb; /* Index of database containing pTab */
42152 v = sqlite3GetVdbe(pParse);
42153 if( v==0 || pTab==0 || pTab->pIndex==0 ){
42154 /* Do no analysis for tables that have no indices */
42155 return;
42158 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
42159 assert( iDb>=0 );
42160 #ifndef SQLITE_OMIT_AUTHORIZATION
42161 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
42162 pParse->db->aDb[iDb].zName ) ){
42163 return;
42165 #endif
42167 /* Establish a read-lock on the table at the shared-cache level. */
42168 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
42170 iIdxCur = pParse->nTab;
42171 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
42172 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
42174 /* Open a cursor to the index to be analyzed
42176 assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
42177 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
42178 VdbeComment((v, "# %s", pIdx->zName));
42179 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum,
42180 (char *)pKey, P3_KEYINFO_HANDOFF);
42181 nCol = pIdx->nColumn;
42182 if( iMem+nCol*2>=pParse->nMem ){
42183 pParse->nMem = iMem+nCol*2+1;
42185 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, nCol+1);
42187 /* Memory cells are used as follows:
42189 ** mem[iMem]: The total number of rows in the table.
42190 ** mem[iMem+1]: Number of distinct values in column 1
42191 ** ...
42192 ** mem[iMem+nCol]: Number of distinct values in column N
42193 ** mem[iMem+nCol+1] Last observed value of column 1
42194 ** ...
42195 ** mem[iMem+nCol+nCol]: Last observed value of column N
42197 ** Cells iMem through iMem+nCol are initialized to 0. The others
42198 ** are initialized to NULL.
42200 for(i=0; i<=nCol; i++){
42201 sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem+i);
42203 for(i=0; i<nCol; i++){
42204 sqlite3VdbeAddOp(v, OP_MemNull, iMem+nCol+i+1, 0);
42207 /* Do the analysis.
42209 endOfLoop = sqlite3VdbeMakeLabel(v);
42210 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, endOfLoop);
42211 topOfLoop = sqlite3VdbeCurrentAddr(v);
42212 sqlite3VdbeAddOp(v, OP_MemIncr, 1, iMem);
42213 for(i=0; i<nCol; i++){
42214 sqlite3VdbeAddOp(v, OP_Column, iIdxCur, i);
42215 sqlite3VdbeAddOp(v, OP_MemLoad, iMem+nCol+i+1, 0);
42216 sqlite3VdbeAddOp(v, OP_Ne, 0x100, 0);
42218 sqlite3VdbeAddOp(v, OP_Goto, 0, endOfLoop);
42219 for(i=0; i<nCol; i++){
42220 addr = sqlite3VdbeAddOp(v, OP_MemIncr, 1, iMem+i+1);
42221 sqlite3VdbeChangeP2(v, topOfLoop + 3*i + 3, addr);
42222 sqlite3VdbeAddOp(v, OP_Column, iIdxCur, i);
42223 sqlite3VdbeAddOp(v, OP_MemStore, iMem+nCol+i+1, 1);
42225 sqlite3VdbeResolveLabel(v, endOfLoop);
42226 sqlite3VdbeAddOp(v, OP_Next, iIdxCur, topOfLoop);
42227 sqlite3VdbeAddOp(v, OP_Close, iIdxCur, 0);
42229 /* Store the results.
42231 ** The result is a single row of the sqlite_stmt1 table. The first
42232 ** two columns are the names of the table and index. The third column
42233 ** is a string composed of a list of integer statistics about the
42234 ** index. The first integer in the list is the total number of entires
42235 ** in the index. There is one additional integer in the list for each
42236 ** column of the table. This additional integer is a guess of how many
42237 ** rows of the table the index will select. If D is the count of distinct
42238 ** values and K is the total number of rows, then the integer is computed
42239 ** as:
42241 ** I = (K+D-1)/D
42243 ** If K==0 then no entry is made into the sqlite_stat1 table.
42244 ** If K>0 then it is always the case the D>0 so division by zero
42245 ** is never possible.
42247 sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
42248 addr = sqlite3VdbeAddOp(v, OP_IfNot, 0, 0);
42249 sqlite3VdbeAddOp(v, OP_NewRowid, iStatCur, 0);
42250 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
42251 sqlite3VdbeOp3(v, OP_String8, 0, 0, pIdx->zName, 0);
42252 sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
42253 sqlite3VdbeOp3(v, OP_String8, 0, 0, " ", 0);
42254 for(i=0; i<nCol; i++){
42255 sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
42256 sqlite3VdbeAddOp(v, OP_MemLoad, iMem+i+1, 0);
42257 sqlite3VdbeAddOp(v, OP_Add, 0, 0);
42258 sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
42259 sqlite3VdbeAddOp(v, OP_MemLoad, iMem+i+1, 0);
42260 sqlite3VdbeAddOp(v, OP_Divide, 0, 0);
42261 sqlite3VdbeAddOp(v, OP_ToInt, 0, 0);
42262 if( i==nCol-1 ){
42263 sqlite3VdbeAddOp(v, OP_Concat, nCol*2-1, 0);
42264 }else{
42265 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
42268 sqlite3VdbeOp3(v, OP_MakeRecord, 3, 0, "aaa", 0);
42269 sqlite3VdbeAddOp(v, OP_Insert, iStatCur, OPFLAG_APPEND);
42270 sqlite3VdbeJumpHere(v, addr);
42275 ** Generate code that will cause the most recent index analysis to
42276 ** be laoded into internal hash tables where is can be used.
42278 static void loadAnalysis(Parse *pParse, int iDb){
42279 Vdbe *v = sqlite3GetVdbe(pParse);
42280 if( v ){
42281 sqlite3VdbeAddOp(v, OP_LoadAnalysis, iDb, 0);
42286 ** Generate code that will do an analysis of an entire database
42288 static void analyzeDatabase(Parse *pParse, int iDb){
42289 sqlite3 *db = pParse->db;
42290 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
42291 HashElem *k;
42292 int iStatCur;
42293 int iMem;
42295 sqlite3BeginWriteOperation(pParse, 0, iDb);
42296 iStatCur = pParse->nTab++;
42297 openStatTable(pParse, iDb, iStatCur, 0);
42298 iMem = pParse->nMem;
42299 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
42300 Table *pTab = (Table*)sqliteHashData(k);
42301 analyzeOneTable(pParse, pTab, iStatCur, iMem);
42303 loadAnalysis(pParse, iDb);
42307 ** Generate code that will do an analysis of a single table in
42308 ** a database.
42310 static void analyzeTable(Parse *pParse, Table *pTab){
42311 int iDb;
42312 int iStatCur;
42314 assert( pTab!=0 );
42315 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
42316 sqlite3BeginWriteOperation(pParse, 0, iDb);
42317 iStatCur = pParse->nTab++;
42318 openStatTable(pParse, iDb, iStatCur, pTab->zName);
42319 analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem);
42320 loadAnalysis(pParse, iDb);
42324 ** Generate code for the ANALYZE command. The parser calls this routine
42325 ** when it recognizes an ANALYZE command.
42327 ** ANALYZE -- 1
42328 ** ANALYZE <database> -- 2
42329 ** ANALYZE ?<database>.?<tablename> -- 3
42331 ** Form 1 causes all indices in all attached databases to be analyzed.
42332 ** Form 2 analyzes all indices the single database named.
42333 ** Form 3 analyzes all indices associated with the named table.
42335 static void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
42336 sqlite3 *db = pParse->db;
42337 int iDb;
42338 int i;
42339 char *z, *zDb;
42340 Table *pTab;
42341 Token *pTableName;
42343 /* Read the database schema. If an error occurs, leave an error message
42344 ** and code in pParse and return NULL. */
42345 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
42346 return;
42349 if( pName1==0 ){
42350 /* Form 1: Analyze everything */
42351 for(i=0; i<db->nDb; i++){
42352 if( i==1 ) continue; /* Do not analyze the TEMP database */
42353 analyzeDatabase(pParse, i);
42355 }else if( pName2==0 || pName2->n==0 ){
42356 /* Form 2: Analyze the database or table named */
42357 iDb = sqlite3FindDb(db, pName1);
42358 if( iDb>=0 ){
42359 analyzeDatabase(pParse, iDb);
42360 }else{
42361 z = sqlite3NameFromToken(pName1);
42362 pTab = sqlite3LocateTable(pParse, z, 0);
42363 sqliteFree(z);
42364 if( pTab ){
42365 analyzeTable(pParse, pTab);
42368 }else{
42369 /* Form 3: Analyze the fully qualified table name */
42370 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
42371 if( iDb>=0 ){
42372 zDb = db->aDb[iDb].zName;
42373 z = sqlite3NameFromToken(pTableName);
42374 if( z ){
42375 pTab = sqlite3LocateTable(pParse, z, zDb);
42376 sqliteFree(z);
42377 if( pTab ){
42378 analyzeTable(pParse, pTab);
42386 ** Used to pass information from the analyzer reader through to the
42387 ** callback routine.
42389 typedef struct analysisInfo analysisInfo;
42390 struct analysisInfo {
42391 sqlite3 *db;
42392 const char *zDatabase;
42396 ** This callback is invoked once for each index when reading the
42397 ** sqlite_stat1 table.
42399 ** argv[0] = name of the index
42400 ** argv[1] = results of analysis - on integer for each column
42402 static int analysisLoader(void *pData, int argc, char **argv, char **azNotUsed){
42403 analysisInfo *pInfo = (analysisInfo*)pData;
42404 Index *pIndex;
42405 int i, c;
42406 unsigned int v;
42407 const char *z;
42409 assert( argc==2 );
42410 if( argv==0 || argv[0]==0 || argv[1]==0 ){
42411 return 0;
42413 pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
42414 if( pIndex==0 ){
42415 return 0;
42417 z = argv[1];
42418 for(i=0; *z && i<=pIndex->nColumn; i++){
42419 v = 0;
42420 while( (c=z[0])>='0' && c<='9' ){
42421 v = v*10 + c - '0';
42422 z++;
42424 pIndex->aiRowEst[i] = v;
42425 if( *z==' ' ) z++;
42427 return 0;
42431 ** Load the content of the sqlite_stat1 table into the index hash tables.
42433 static int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
42434 analysisInfo sInfo;
42435 HashElem *i;
42436 char *zSql;
42437 int rc;
42439 /* Clear any prior statistics */
42440 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
42441 Index *pIdx = sqliteHashData(i);
42442 sqlite3DefaultRowEst(pIdx);
42445 /* Check to make sure the sqlite_stat1 table existss */
42446 sInfo.db = db;
42447 sInfo.zDatabase = db->aDb[iDb].zName;
42448 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
42449 return SQLITE_ERROR;
42453 /* Load new statistics out of the sqlite_stat1 table */
42454 zSql = sqlite3MPrintf("SELECT idx, stat FROM %Q.sqlite_stat1",
42455 sInfo.zDatabase);
42456 sqlite3SafetyOff(db);
42457 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
42458 sqlite3SafetyOn(db);
42459 sqliteFree(zSql);
42460 return rc;
42464 #endif /* SQLITE_OMIT_ANALYZE */
42466 /************** End of analyze.c *********************************************/
42467 /************** Begin file attach.c ******************************************/
42469 ** 2003 April 6
42471 ** The author disclaims copyright to this source code. In place of
42472 ** a legal notice, here is a blessing:
42474 ** May you do good and not evil.
42475 ** May you find forgiveness for yourself and forgive others.
42476 ** May you share freely, never taking more than you give.
42478 *************************************************************************
42479 ** This file contains code used to implement the ATTACH and DETACH commands.
42481 ** $Id: attach.c,v 1.60 2007/05/09 20:31:30 drh Exp $
42484 #ifndef SQLITE_OMIT_ATTACH
42486 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
42487 ** is slightly different from resolving a normal SQL expression, because simple
42488 ** identifiers are treated as strings, not possible column names or aliases.
42490 ** i.e. if the parser sees:
42492 ** ATTACH DATABASE abc AS def
42494 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
42495 ** looking for columns of the same name.
42497 ** This only applies to the root node of pExpr, so the statement:
42499 ** ATTACH DATABASE abc||def AS 'db2'
42501 ** will fail because neither abc or def can be resolved.
42503 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
42505 int rc = SQLITE_OK;
42506 if( pExpr ){
42507 if( pExpr->op!=TK_ID ){
42508 rc = sqlite3ExprResolveNames(pName, pExpr);
42509 if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
42510 sqlite3ErrorMsg(pName->pParse, "invalid name: \"%T\"", &pExpr->span);
42511 return SQLITE_ERROR;
42513 }else{
42514 pExpr->op = TK_STRING;
42517 return rc;
42521 ** An SQL user-function registered to do the work of an ATTACH statement. The
42522 ** three arguments to the function come directly from an attach statement:
42524 ** ATTACH DATABASE x AS y KEY z
42526 ** SELECT sqlite_attach(x, y, z)
42528 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
42529 ** third argument.
42531 static void attachFunc(
42532 sqlite3_context *context,
42533 int argc,
42534 sqlite3_value **argv
42536 int i;
42537 int rc = 0;
42538 sqlite3 *db = sqlite3_user_data(context);
42539 const char *zName;
42540 const char *zFile;
42541 Db *aNew;
42542 char zErr[128];
42543 char *zErrDyn = 0;
42545 zFile = (const char *)sqlite3_value_text(argv[0]);
42546 zName = (const char *)sqlite3_value_text(argv[1]);
42547 if( zFile==0 ) zFile = "";
42548 if( zName==0 ) zName = "";
42550 /* Check for the following errors:
42552 ** * Too many attached databases,
42553 ** * Transaction currently open
42554 ** * Specified database name already being used.
42556 if( db->nDb>=SQLITE_MAX_ATTACHED+2 ){
42557 sqlite3_snprintf(
42558 sizeof(zErr), zErr, "too many attached databases - max %d",
42559 SQLITE_MAX_ATTACHED
42561 goto attach_error;
42563 if( !db->autoCommit ){
42564 sqlite3_snprintf(sizeof(zErr), zErr,
42565 "cannot ATTACH database within transaction");
42566 goto attach_error;
42568 for(i=0; i<db->nDb; i++){
42569 char *z = db->aDb[i].zName;
42570 if( z && zName && sqlite3StrICmp(z, zName)==0 ){
42571 sqlite3_snprintf(sizeof(zErr), zErr, "database %s is already in use", zName);
42572 goto attach_error;
42576 /* Allocate the new entry in the db->aDb[] array and initialise the schema
42577 ** hash tables.
42579 if( db->aDb==db->aDbStatic ){
42580 aNew = sqliteMalloc( sizeof(db->aDb[0])*3 );
42581 if( aNew==0 ){
42582 return;
42584 memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
42585 }else{
42586 aNew = sqliteRealloc(db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
42587 if( aNew==0 ){
42588 return;
42591 db->aDb = aNew;
42592 aNew = &db->aDb[db->nDb++];
42593 memset(aNew, 0, sizeof(*aNew));
42595 /* Open the database file. If the btree is successfully opened, use
42596 ** it to obtain the database schema. At this point the schema may
42597 ** or may not be initialised.
42599 rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE, &aNew->pBt);
42600 if( rc==SQLITE_OK ){
42601 aNew->pSchema = sqlite3SchemaGet(aNew->pBt);
42602 if( !aNew->pSchema ){
42603 rc = SQLITE_NOMEM;
42604 }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
42605 sqlite3_snprintf(sizeof(zErr), zErr,
42606 "attached databases must use the same text encoding as main database");
42607 goto attach_error;
42609 sqlite3PagerLockingMode(sqlite3BtreePager(aNew->pBt), db->dfltLockMode);
42611 aNew->zName = sqliteStrDup(zName);
42612 aNew->safety_level = 3;
42614 #if SQLITE_HAS_CODEC
42616 extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
42617 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
42618 int nKey;
42619 char *zKey;
42620 int t = sqlite3_value_type(argv[2]);
42621 switch( t ){
42622 case SQLITE_INTEGER:
42623 case SQLITE_FLOAT:
42624 zErrDyn = sqliteStrDup("Invalid key value");
42625 rc = SQLITE_ERROR;
42626 break;
42628 case SQLITE_TEXT:
42629 case SQLITE_BLOB:
42630 nKey = sqlite3_value_bytes(argv[2]);
42631 zKey = (char *)sqlite3_value_blob(argv[2]);
42632 sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
42633 break;
42635 case SQLITE_NULL:
42636 /* No key specified. Use the key from the main database */
42637 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
42638 sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
42639 break;
42642 #endif
42644 /* If the file was opened successfully, read the schema for the new database.
42645 ** If this fails, or if opening the file failed, then close the file and
42646 ** remove the entry from the db->aDb[] array. i.e. put everything back the way
42647 ** we found it.
42649 if( rc==SQLITE_OK ){
42650 sqlite3SafetyOn(db);
42651 rc = sqlite3Init(db, &zErrDyn);
42652 sqlite3SafetyOff(db);
42654 if( rc ){
42655 int iDb = db->nDb - 1;
42656 assert( iDb>=2 );
42657 if( db->aDb[iDb].pBt ){
42658 sqlite3BtreeClose(db->aDb[iDb].pBt);
42659 db->aDb[iDb].pBt = 0;
42660 db->aDb[iDb].pSchema = 0;
42662 sqlite3ResetInternalSchema(db, 0);
42663 db->nDb = iDb;
42664 if( rc==SQLITE_NOMEM ){
42665 sqlite3FailedMalloc();
42666 sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
42667 }else{
42668 sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
42670 goto attach_error;
42673 return;
42675 attach_error:
42676 /* Return an error if we get here */
42677 if( zErrDyn ){
42678 sqlite3_result_error(context, zErrDyn, -1);
42679 sqliteFree(zErrDyn);
42680 }else{
42681 zErr[sizeof(zErr)-1] = 0;
42682 sqlite3_result_error(context, zErr, -1);
42687 ** An SQL user-function registered to do the work of an DETACH statement. The
42688 ** three arguments to the function come directly from a detach statement:
42690 ** DETACH DATABASE x
42692 ** SELECT sqlite_detach(x)
42694 static void detachFunc(
42695 sqlite3_context *context,
42696 int argc,
42697 sqlite3_value **argv
42699 const char *zName = (const char *)sqlite3_value_text(argv[0]);
42700 sqlite3 *db = sqlite3_user_data(context);
42701 int i;
42702 Db *pDb = 0;
42703 char zErr[128];
42705 if( zName==0 ) zName = "";
42706 for(i=0; i<db->nDb; i++){
42707 pDb = &db->aDb[i];
42708 if( pDb->pBt==0 ) continue;
42709 if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
42712 if( i>=db->nDb ){
42713 sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
42714 goto detach_error;
42716 if( i<2 ){
42717 sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
42718 goto detach_error;
42720 if( !db->autoCommit ){
42721 sqlite3_snprintf(sizeof(zErr), zErr,
42722 "cannot DETACH database within transaction");
42723 goto detach_error;
42725 if( sqlite3BtreeIsInReadTrans(pDb->pBt) ){
42726 sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
42727 goto detach_error;
42730 sqlite3BtreeClose(pDb->pBt);
42731 pDb->pBt = 0;
42732 pDb->pSchema = 0;
42733 sqlite3ResetInternalSchema(db, 0);
42734 return;
42736 detach_error:
42737 sqlite3_result_error(context, zErr, -1);
42741 ** This procedure generates VDBE code for a single invocation of either the
42742 ** sqlite_detach() or sqlite_attach() SQL user functions.
42744 static void codeAttach(
42745 Parse *pParse, /* The parser context */
42746 int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
42747 const char *zFunc, /* Either "sqlite_attach" or "sqlite_detach */
42748 int nFunc, /* Number of args to pass to zFunc */
42749 Expr *pAuthArg, /* Expression to pass to authorization callback */
42750 Expr *pFilename, /* Name of database file */
42751 Expr *pDbname, /* Name of the database to use internally */
42752 Expr *pKey /* Database key for encryption extension */
42754 int rc;
42755 NameContext sName;
42756 Vdbe *v;
42757 FuncDef *pFunc;
42758 sqlite3* db = pParse->db;
42760 #ifndef SQLITE_OMIT_AUTHORIZATION
42761 assert( sqlite3MallocFailed() || pAuthArg );
42762 if( pAuthArg ){
42763 char *zAuthArg = sqlite3NameFromToken(&pAuthArg->span);
42764 if( !zAuthArg ){
42765 goto attach_end;
42767 rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
42768 sqliteFree(zAuthArg);
42769 if(rc!=SQLITE_OK ){
42770 goto attach_end;
42773 #endif /* SQLITE_OMIT_AUTHORIZATION */
42775 memset(&sName, 0, sizeof(NameContext));
42776 sName.pParse = pParse;
42778 if(
42779 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
42780 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
42781 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
42783 pParse->nErr++;
42784 goto attach_end;
42787 v = sqlite3GetVdbe(pParse);
42788 sqlite3ExprCode(pParse, pFilename);
42789 sqlite3ExprCode(pParse, pDbname);
42790 sqlite3ExprCode(pParse, pKey);
42792 assert( v || sqlite3MallocFailed() );
42793 if( v ){
42794 sqlite3VdbeAddOp(v, OP_Function, 0, nFunc);
42795 pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0);
42796 sqlite3VdbeChangeP3(v, -1, (char *)pFunc, P3_FUNCDEF);
42798 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
42799 ** statement only). For DETACH, set it to false (expire all existing
42800 ** statements).
42802 sqlite3VdbeAddOp(v, OP_Expire, (type==SQLITE_ATTACH), 0);
42805 attach_end:
42806 sqlite3ExprDelete(pFilename);
42807 sqlite3ExprDelete(pDbname);
42808 sqlite3ExprDelete(pKey);
42812 ** Called by the parser to compile a DETACH statement.
42814 ** DETACH pDbname
42816 static void sqlite3Detach(Parse *pParse, Expr *pDbname){
42817 codeAttach(pParse, SQLITE_DETACH, "sqlite_detach", 1, pDbname, 0, 0, pDbname);
42821 ** Called by the parser to compile an ATTACH statement.
42823 ** ATTACH p AS pDbname KEY pKey
42825 static void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
42826 codeAttach(pParse, SQLITE_ATTACH, "sqlite_attach", 3, p, p, pDbname, pKey);
42828 #endif /* SQLITE_OMIT_ATTACH */
42831 ** Register the functions sqlite_attach and sqlite_detach.
42833 static void sqlite3AttachFunctions(sqlite3 *db){
42834 #ifndef SQLITE_OMIT_ATTACH
42835 static const int enc = SQLITE_UTF8;
42836 sqlite3CreateFunc(db, "sqlite_attach", 3, enc, db, attachFunc, 0, 0);
42837 sqlite3CreateFunc(db, "sqlite_detach", 1, enc, db, detachFunc, 0, 0);
42838 #endif
42842 ** Initialize a DbFixer structure. This routine must be called prior
42843 ** to passing the structure to one of the sqliteFixAAAA() routines below.
42845 ** The return value indicates whether or not fixation is required. TRUE
42846 ** means we do need to fix the database references, FALSE means we do not.
42848 static int sqlite3FixInit(
42849 DbFixer *pFix, /* The fixer to be initialized */
42850 Parse *pParse, /* Error messages will be written here */
42851 int iDb, /* This is the database that must be used */
42852 const char *zType, /* "view", "trigger", or "index" */
42853 const Token *pName /* Name of the view, trigger, or index */
42855 sqlite3 *db;
42857 if( iDb<0 || iDb==1 ) return 0;
42858 db = pParse->db;
42859 assert( db->nDb>iDb );
42860 pFix->pParse = pParse;
42861 pFix->zDb = db->aDb[iDb].zName;
42862 pFix->zType = zType;
42863 pFix->pName = pName;
42864 return 1;
42868 ** The following set of routines walk through the parse tree and assign
42869 ** a specific database to all table references where the database name
42870 ** was left unspecified in the original SQL statement. The pFix structure
42871 ** must have been initialized by a prior call to sqlite3FixInit().
42873 ** These routines are used to make sure that an index, trigger, or
42874 ** view in one database does not refer to objects in a different database.
42875 ** (Exception: indices, triggers, and views in the TEMP database are
42876 ** allowed to refer to anything.) If a reference is explicitly made
42877 ** to an object in a different database, an error message is added to
42878 ** pParse->zErrMsg and these routines return non-zero. If everything
42879 ** checks out, these routines return 0.
42881 static int sqlite3FixSrcList(
42882 DbFixer *pFix, /* Context of the fixation */
42883 SrcList *pList /* The Source list to check and modify */
42885 int i;
42886 const char *zDb;
42887 struct SrcList_item *pItem;
42889 if( pList==0 ) return 0;
42890 zDb = pFix->zDb;
42891 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
42892 if( pItem->zDatabase==0 ){
42893 pItem->zDatabase = sqliteStrDup(zDb);
42894 }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
42895 sqlite3ErrorMsg(pFix->pParse,
42896 "%s %T cannot reference objects in database %s",
42897 pFix->zType, pFix->pName, pItem->zDatabase);
42898 return 1;
42900 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
42901 if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
42902 if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
42903 #endif
42905 return 0;
42907 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
42908 static int sqlite3FixSelect(
42909 DbFixer *pFix, /* Context of the fixation */
42910 Select *pSelect /* The SELECT statement to be fixed to one database */
42912 while( pSelect ){
42913 if( sqlite3FixExprList(pFix, pSelect->pEList) ){
42914 return 1;
42916 if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
42917 return 1;
42919 if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
42920 return 1;
42922 if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
42923 return 1;
42925 pSelect = pSelect->pPrior;
42927 return 0;
42929 static int sqlite3FixExpr(
42930 DbFixer *pFix, /* Context of the fixation */
42931 Expr *pExpr /* The expression to be fixed to one database */
42933 while( pExpr ){
42934 if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
42935 return 1;
42937 if( sqlite3FixExprList(pFix, pExpr->pList) ){
42938 return 1;
42940 if( sqlite3FixExpr(pFix, pExpr->pRight) ){
42941 return 1;
42943 pExpr = pExpr->pLeft;
42945 return 0;
42947 static int sqlite3FixExprList(
42948 DbFixer *pFix, /* Context of the fixation */
42949 ExprList *pList /* The expression to be fixed to one database */
42951 int i;
42952 struct ExprList_item *pItem;
42953 if( pList==0 ) return 0;
42954 for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
42955 if( sqlite3FixExpr(pFix, pItem->pExpr) ){
42956 return 1;
42959 return 0;
42961 #endif
42963 #ifndef SQLITE_OMIT_TRIGGER
42964 static int sqlite3FixTriggerStep(
42965 DbFixer *pFix, /* Context of the fixation */
42966 TriggerStep *pStep /* The trigger step be fixed to one database */
42968 while( pStep ){
42969 if( sqlite3FixSelect(pFix, pStep->pSelect) ){
42970 return 1;
42972 if( sqlite3FixExpr(pFix, pStep->pWhere) ){
42973 return 1;
42975 if( sqlite3FixExprList(pFix, pStep->pExprList) ){
42976 return 1;
42978 pStep = pStep->pNext;
42980 return 0;
42982 #endif
42984 /************** End of attach.c **********************************************/
42985 /************** Begin file auth.c ********************************************/
42987 ** 2003 January 11
42989 ** The author disclaims copyright to this source code. In place of
42990 ** a legal notice, here is a blessing:
42992 ** May you do good and not evil.
42993 ** May you find forgiveness for yourself and forgive others.
42994 ** May you share freely, never taking more than you give.
42996 *************************************************************************
42997 ** This file contains code used to implement the sqlite3_set_authorizer()
42998 ** API. This facility is an optional feature of the library. Embedded
42999 ** systems that do not need this facility may omit it by recompiling
43000 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
43002 ** $Id: auth.c,v 1.26 2007/05/14 11:34:47 drh Exp $
43006 ** All of the code in this file may be omitted by defining a single
43007 ** macro.
43009 #ifndef SQLITE_OMIT_AUTHORIZATION
43012 ** Set or clear the access authorization function.
43014 ** The access authorization function is be called during the compilation
43015 ** phase to verify that the user has read and/or write access permission on
43016 ** various fields of the database. The first argument to the auth function
43017 ** is a copy of the 3rd argument to this routine. The second argument
43018 ** to the auth function is one of these constants:
43020 ** SQLITE_CREATE_INDEX
43021 ** SQLITE_CREATE_TABLE
43022 ** SQLITE_CREATE_TEMP_INDEX
43023 ** SQLITE_CREATE_TEMP_TABLE
43024 ** SQLITE_CREATE_TEMP_TRIGGER
43025 ** SQLITE_CREATE_TEMP_VIEW
43026 ** SQLITE_CREATE_TRIGGER
43027 ** SQLITE_CREATE_VIEW
43028 ** SQLITE_DELETE
43029 ** SQLITE_DROP_INDEX
43030 ** SQLITE_DROP_TABLE
43031 ** SQLITE_DROP_TEMP_INDEX
43032 ** SQLITE_DROP_TEMP_TABLE
43033 ** SQLITE_DROP_TEMP_TRIGGER
43034 ** SQLITE_DROP_TEMP_VIEW
43035 ** SQLITE_DROP_TRIGGER
43036 ** SQLITE_DROP_VIEW
43037 ** SQLITE_INSERT
43038 ** SQLITE_PRAGMA
43039 ** SQLITE_READ
43040 ** SQLITE_SELECT
43041 ** SQLITE_TRANSACTION
43042 ** SQLITE_UPDATE
43044 ** The third and fourth arguments to the auth function are the name of
43045 ** the table and the column that are being accessed. The auth function
43046 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
43047 ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
43048 ** means that the SQL statement will never-run - the sqlite3_exec() call
43049 ** will return with an error. SQLITE_IGNORE means that the SQL statement
43050 ** should run but attempts to read the specified column will return NULL
43051 ** and attempts to write the column will be ignored.
43053 ** Setting the auth function to NULL disables this hook. The default
43054 ** setting of the auth function is NULL.
43056 int sqlite3_set_authorizer(
43057 sqlite3 *db,
43058 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
43059 void *pArg
43061 db->xAuth = xAuth;
43062 db->pAuthArg = pArg;
43063 sqlite3ExpirePreparedStatements(db);
43064 return SQLITE_OK;
43068 ** Write an error message into pParse->zErrMsg that explains that the
43069 ** user-supplied authorization function returned an illegal value.
43071 static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
43072 sqlite3ErrorMsg(pParse, "illegal return value (%d) from the "
43073 "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
43074 "or SQLITE_DENY", rc);
43075 pParse->rc = SQLITE_ERROR;
43079 ** The pExpr should be a TK_COLUMN expression. The table referred to
43080 ** is in pTabList or else it is the NEW or OLD table of a trigger.
43081 ** Check to see if it is OK to read this particular column.
43083 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
43084 ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
43085 ** then generate an error.
43087 static void sqlite3AuthRead(
43088 Parse *pParse, /* The parser context */
43089 Expr *pExpr, /* The expression to check authorization on */
43090 SrcList *pTabList /* All table that pExpr might refer to */
43092 sqlite3 *db = pParse->db;
43093 int rc;
43094 Table *pTab; /* The table being read */
43095 const char *zCol; /* Name of the column of the table */
43096 int iSrc; /* Index in pTabList->a[] of table being read */
43097 const char *zDBase; /* Name of database being accessed */
43098 TriggerStack *pStack; /* The stack of current triggers */
43099 int iDb; /* The index of the database the expression refers to */
43101 if( db->xAuth==0 ) return;
43102 if( pExpr->op!=TK_COLUMN ) return;
43103 iDb = sqlite3SchemaToIndex(pParse->db, pExpr->pSchema);
43104 if( iDb<0 ){
43105 /* An attempt to read a column out of a subquery or other
43106 ** temporary table. */
43107 return;
43109 for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
43110 if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
43112 if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
43113 pTab = pTabList->a[iSrc].pTab;
43114 }else if( (pStack = pParse->trigStack)!=0 ){
43115 /* This must be an attempt to read the NEW or OLD pseudo-tables
43116 ** of a trigger.
43118 assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
43119 pTab = pStack->pTab;
43120 }else{
43121 return;
43123 if( pTab==0 ) return;
43124 if( pExpr->iColumn>=0 ){
43125 assert( pExpr->iColumn<pTab->nCol );
43126 zCol = pTab->aCol[pExpr->iColumn].zName;
43127 }else if( pTab->iPKey>=0 ){
43128 assert( pTab->iPKey<pTab->nCol );
43129 zCol = pTab->aCol[pTab->iPKey].zName;
43130 }else{
43131 zCol = "ROWID";
43133 assert( iDb>=0 && iDb<db->nDb );
43134 zDBase = db->aDb[iDb].zName;
43135 rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase,
43136 pParse->zAuthContext);
43137 if( rc==SQLITE_IGNORE ){
43138 pExpr->op = TK_NULL;
43139 }else if( rc==SQLITE_DENY ){
43140 if( db->nDb>2 || iDb!=0 ){
43141 sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",
43142 zDBase, pTab->zName, zCol);
43143 }else{
43144 sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
43146 pParse->rc = SQLITE_AUTH;
43147 }else if( rc!=SQLITE_OK ){
43148 sqliteAuthBadReturnCode(pParse, rc);
43153 ** Do an authorization check using the code and arguments given. Return
43154 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
43155 ** is returned, then the error count and error message in pParse are
43156 ** modified appropriately.
43158 static int sqlite3AuthCheck(
43159 Parse *pParse,
43160 int code,
43161 const char *zArg1,
43162 const char *zArg2,
43163 const char *zArg3
43165 sqlite3 *db = pParse->db;
43166 int rc;
43168 /* Don't do any authorization checks if the database is initialising
43169 ** or if the parser is being invoked from within sqlite3_declare_vtab.
43171 if( db->init.busy || IN_DECLARE_VTAB ){
43172 return SQLITE_OK;
43175 if( db->xAuth==0 ){
43176 return SQLITE_OK;
43178 rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
43179 if( rc==SQLITE_DENY ){
43180 sqlite3ErrorMsg(pParse, "not authorized");
43181 pParse->rc = SQLITE_AUTH;
43182 }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
43183 rc = SQLITE_DENY;
43184 sqliteAuthBadReturnCode(pParse, rc);
43186 return rc;
43190 ** Push an authorization context. After this routine is called, the
43191 ** zArg3 argument to authorization callbacks will be zContext until
43192 ** popped. Or if pParse==0, this routine is a no-op.
43194 static void sqlite3AuthContextPush(
43195 Parse *pParse,
43196 AuthContext *pContext,
43197 const char *zContext
43199 pContext->pParse = pParse;
43200 if( pParse ){
43201 pContext->zAuthContext = pParse->zAuthContext;
43202 pParse->zAuthContext = zContext;
43207 ** Pop an authorization context that was previously pushed
43208 ** by sqlite3AuthContextPush
43210 static void sqlite3AuthContextPop(AuthContext *pContext){
43211 if( pContext->pParse ){
43212 pContext->pParse->zAuthContext = pContext->zAuthContext;
43213 pContext->pParse = 0;
43217 #endif /* SQLITE_OMIT_AUTHORIZATION */
43219 /************** End of auth.c ************************************************/
43220 /************** Begin file build.c *******************************************/
43222 ** 2001 September 15
43224 ** The author disclaims copyright to this source code. In place of
43225 ** a legal notice, here is a blessing:
43227 ** May you do good and not evil.
43228 ** May you find forgiveness for yourself and forgive others.
43229 ** May you share freely, never taking more than you give.
43231 *************************************************************************
43232 ** This file contains C code routines that are called by the SQLite parser
43233 ** when syntax rules are reduced. The routines in this file handle the
43234 ** following kinds of SQL syntax:
43236 ** CREATE TABLE
43237 ** DROP TABLE
43238 ** CREATE INDEX
43239 ** DROP INDEX
43240 ** creating ID lists
43241 ** BEGIN TRANSACTION
43242 ** COMMIT
43243 ** ROLLBACK
43245 ** $Id: build.c,v 1.432 2007/05/15 14:34:32 drh Exp $
43249 ** This routine is called when a new SQL statement is beginning to
43250 ** be parsed. Initialize the pParse structure as needed.
43252 static void sqlite3BeginParse(Parse *pParse, int explainFlag){
43253 pParse->explain = explainFlag;
43254 pParse->nVar = 0;
43257 #ifndef SQLITE_OMIT_SHARED_CACHE
43259 ** The TableLock structure is only used by the sqlite3TableLock() and
43260 ** codeTableLocks() functions.
43262 struct TableLock {
43263 int iDb; /* The database containing the table to be locked */
43264 int iTab; /* The root page of the table to be locked */
43265 u8 isWriteLock; /* True for write lock. False for a read lock */
43266 const char *zName; /* Name of the table */
43270 ** Record the fact that we want to lock a table at run-time.
43272 ** The table to be locked has root page iTab and is found in database iDb.
43273 ** A read or a write lock can be taken depending on isWritelock.
43275 ** This routine just records the fact that the lock is desired. The
43276 ** code to make the lock occur is generated by a later call to
43277 ** codeTableLocks() which occurs during sqlite3FinishCoding().
43279 static void sqlite3TableLock(
43280 Parse *pParse, /* Parsing context */
43281 int iDb, /* Index of the database containing the table to lock */
43282 int iTab, /* Root page number of the table to be locked */
43283 u8 isWriteLock, /* True for a write lock */
43284 const char *zName /* Name of the table to be locked */
43286 int i;
43287 int nBytes;
43288 TableLock *p;
43290 if( 0==sqlite3ThreadDataReadOnly()->useSharedData || iDb<0 ){
43291 return;
43294 for(i=0; i<pParse->nTableLock; i++){
43295 p = &pParse->aTableLock[i];
43296 if( p->iDb==iDb && p->iTab==iTab ){
43297 p->isWriteLock = (p->isWriteLock || isWriteLock);
43298 return;
43302 nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
43303 pParse->aTableLock = sqliteReallocOrFree(pParse->aTableLock, nBytes);
43304 if( pParse->aTableLock ){
43305 p = &pParse->aTableLock[pParse->nTableLock++];
43306 p->iDb = iDb;
43307 p->iTab = iTab;
43308 p->isWriteLock = isWriteLock;
43309 p->zName = zName;
43314 ** Code an OP_TableLock instruction for each table locked by the
43315 ** statement (configured by calls to sqlite3TableLock()).
43317 static void codeTableLocks(Parse *pParse){
43318 int i;
43319 Vdbe *pVdbe;
43320 assert( sqlite3ThreadDataReadOnly()->useSharedData || pParse->nTableLock==0 );
43322 if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
43323 return;
43326 for(i=0; i<pParse->nTableLock; i++){
43327 TableLock *p = &pParse->aTableLock[i];
43328 int p1 = p->iDb;
43329 if( p->isWriteLock ){
43330 p1 = -1*(p1+1);
43332 sqlite3VdbeOp3(pVdbe, OP_TableLock, p1, p->iTab, p->zName, P3_STATIC);
43335 #else
43336 #define codeTableLocks(x)
43337 #endif
43340 ** This routine is called after a single SQL statement has been
43341 ** parsed and a VDBE program to execute that statement has been
43342 ** prepared. This routine puts the finishing touches on the
43343 ** VDBE program and resets the pParse structure for the next
43344 ** parse.
43346 ** Note that if an error occurred, it might be the case that
43347 ** no VDBE code was generated.
43349 static void sqlite3FinishCoding(Parse *pParse){
43350 sqlite3 *db;
43351 Vdbe *v;
43353 if( sqlite3MallocFailed() ) return;
43354 if( pParse->nested ) return;
43355 if( !pParse->pVdbe ){
43356 if( pParse->rc==SQLITE_OK && pParse->nErr ){
43357 pParse->rc = SQLITE_ERROR;
43358 return;
43362 /* Begin by generating some termination code at the end of the
43363 ** vdbe program
43365 db = pParse->db;
43366 v = sqlite3GetVdbe(pParse);
43367 if( v ){
43368 sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
43370 /* The cookie mask contains one bit for each database file open.
43371 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
43372 ** set for each database that is used. Generate code to start a
43373 ** transaction on each used database and to verify the schema cookie
43374 ** on each used database.
43376 if( pParse->cookieGoto>0 ){
43377 u32 mask;
43378 int iDb;
43379 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
43380 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
43381 if( (mask & pParse->cookieMask)==0 ) continue;
43382 sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
43383 sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
43385 #ifndef SQLITE_OMIT_VIRTUALTABLE
43386 if( pParse->pVirtualLock ){
43387 char *vtab = (char *)pParse->pVirtualLock->pVtab;
43388 sqlite3VdbeOp3(v, OP_VBegin, 0, 0, vtab, P3_VTAB);
43390 #endif
43392 /* Once all the cookies have been verified and transactions opened,
43393 ** obtain the required table-locks. This is a no-op unless the
43394 ** shared-cache feature is enabled.
43396 codeTableLocks(pParse);
43397 sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto);
43400 #ifndef SQLITE_OMIT_TRACE
43401 /* Add a No-op that contains the complete text of the compiled SQL
43402 ** statement as its P3 argument. This does not change the functionality
43403 ** of the program.
43405 ** This is used to implement sqlite3_trace().
43407 sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql);
43408 #endif /* SQLITE_OMIT_TRACE */
43412 /* Get the VDBE program ready for execution
43414 if( v && pParse->nErr==0 && !sqlite3MallocFailed() ){
43415 #ifdef SQLITE_DEBUG
43416 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
43417 sqlite3VdbeTrace(v, trace);
43418 #endif
43419 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
43420 pParse->nTab+3, pParse->explain);
43421 pParse->rc = SQLITE_DONE;
43422 pParse->colNamesSet = 0;
43423 }else if( pParse->rc==SQLITE_OK ){
43424 pParse->rc = SQLITE_ERROR;
43426 pParse->nTab = 0;
43427 pParse->nMem = 0;
43428 pParse->nSet = 0;
43429 pParse->nVar = 0;
43430 pParse->cookieMask = 0;
43431 pParse->cookieGoto = 0;
43435 ** Run the parser and code generator recursively in order to generate
43436 ** code for the SQL statement given onto the end of the pParse context
43437 ** currently under construction. When the parser is run recursively
43438 ** this way, the final OP_Halt is not appended and other initialization
43439 ** and finalization steps are omitted because those are handling by the
43440 ** outermost parser.
43442 ** Not everything is nestable. This facility is designed to permit
43443 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
43444 ** care if you decide to try to use this routine for some other purposes.
43446 static void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
43447 va_list ap;
43448 char *zSql;
43449 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
43450 char saveBuf[SAVE_SZ];
43452 if( pParse->nErr ) return;
43453 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
43454 va_start(ap, zFormat);
43455 zSql = sqlite3VMPrintf(zFormat, ap);
43456 va_end(ap);
43457 if( zSql==0 ){
43458 return; /* A malloc must have failed */
43460 pParse->nested++;
43461 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
43462 memset(&pParse->nVar, 0, SAVE_SZ);
43463 sqlite3RunParser(pParse, zSql, 0);
43464 sqliteFree(zSql);
43465 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
43466 pParse->nested--;
43470 ** Locate the in-memory structure that describes a particular database
43471 ** table given the name of that table and (optionally) the name of the
43472 ** database containing the table. Return NULL if not found.
43474 ** If zDatabase is 0, all databases are searched for the table and the
43475 ** first matching table is returned. (No checking for duplicate table
43476 ** names is done.) The search order is TEMP first, then MAIN, then any
43477 ** auxiliary databases added using the ATTACH command.
43479 ** See also sqlite3LocateTable().
43481 static Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
43482 Table *p = 0;
43483 int i;
43484 assert( zName!=0 );
43485 for(i=OMIT_TEMPDB; i<db->nDb; i++){
43486 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
43487 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
43488 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1);
43489 if( p ) break;
43491 return p;
43495 ** Locate the in-memory structure that describes a particular database
43496 ** table given the name of that table and (optionally) the name of the
43497 ** database containing the table. Return NULL if not found. Also leave an
43498 ** error message in pParse->zErrMsg.
43500 ** The difference between this routine and sqlite3FindTable() is that this
43501 ** routine leaves an error message in pParse->zErrMsg where
43502 ** sqlite3FindTable() does not.
43504 static Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
43505 Table *p;
43507 /* Read the database schema. If an error occurs, leave an error message
43508 ** and code in pParse and return NULL. */
43509 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
43510 return 0;
43513 p = sqlite3FindTable(pParse->db, zName, zDbase);
43514 if( p==0 ){
43515 if( zDbase ){
43516 sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
43517 }else{
43518 sqlite3ErrorMsg(pParse, "no such table: %s", zName);
43520 pParse->checkSchema = 1;
43522 return p;
43526 ** Locate the in-memory structure that describes
43527 ** a particular index given the name of that index
43528 ** and the name of the database that contains the index.
43529 ** Return NULL if not found.
43531 ** If zDatabase is 0, all databases are searched for the
43532 ** table and the first matching index is returned. (No checking
43533 ** for duplicate index names is done.) The search order is
43534 ** TEMP first, then MAIN, then any auxiliary databases added
43535 ** using the ATTACH command.
43537 static Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
43538 Index *p = 0;
43539 int i;
43540 for(i=OMIT_TEMPDB; i<db->nDb; i++){
43541 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
43542 Schema *pSchema = db->aDb[j].pSchema;
43543 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
43544 assert( pSchema || (j==1 && !db->aDb[1].pBt) );
43545 if( pSchema ){
43546 p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1);
43548 if( p ) break;
43550 return p;
43554 ** Reclaim the memory used by an index
43556 static void freeIndex(Index *p){
43557 sqliteFree(p->zColAff);
43558 sqliteFree(p);
43562 ** Remove the given index from the index hash table, and free
43563 ** its memory structures.
43565 ** The index is removed from the database hash tables but
43566 ** it is not unlinked from the Table that it indexes.
43567 ** Unlinking from the Table must be done by the calling function.
43569 static void sqliteDeleteIndex(Index *p){
43570 Index *pOld;
43571 const char *zName = p->zName;
43573 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0);
43574 assert( pOld==0 || pOld==p );
43575 freeIndex(p);
43579 ** For the index called zIdxName which is found in the database iDb,
43580 ** unlike that index from its Table then remove the index from
43581 ** the index hash table and free all memory structures associated
43582 ** with the index.
43584 static void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
43585 Index *pIndex;
43586 int len;
43587 Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
43589 len = strlen(zIdxName);
43590 pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
43591 if( pIndex ){
43592 if( pIndex->pTable->pIndex==pIndex ){
43593 pIndex->pTable->pIndex = pIndex->pNext;
43594 }else{
43595 Index *p;
43596 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
43597 if( p && p->pNext==pIndex ){
43598 p->pNext = pIndex->pNext;
43601 freeIndex(pIndex);
43603 db->flags |= SQLITE_InternChanges;
43607 ** Erase all schema information from the in-memory hash tables of
43608 ** a single database. This routine is called to reclaim memory
43609 ** before the database closes. It is also called during a rollback
43610 ** if there were schema changes during the transaction or if a
43611 ** schema-cookie mismatch occurs.
43613 ** If iDb<=0 then reset the internal schema tables for all database
43614 ** files. If iDb>=2 then reset the internal schema for only the
43615 ** single file indicated.
43617 static void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
43618 int i, j;
43620 assert( iDb>=0 && iDb<db->nDb );
43621 for(i=iDb; i<db->nDb; i++){
43622 Db *pDb = &db->aDb[i];
43623 if( pDb->pSchema ){
43624 sqlite3SchemaFree(pDb->pSchema);
43626 if( iDb>0 ) return;
43628 assert( iDb==0 );
43629 db->flags &= ~SQLITE_InternChanges;
43631 /* If one or more of the auxiliary database files has been closed,
43632 ** then remove them from the auxiliary database list. We take the
43633 ** opportunity to do this here since we have just deleted all of the
43634 ** schema hash tables and therefore do not have to make any changes
43635 ** to any of those tables.
43637 for(i=0; i<db->nDb; i++){
43638 struct Db *pDb = &db->aDb[i];
43639 if( pDb->pBt==0 ){
43640 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
43641 pDb->pAux = 0;
43644 for(i=j=2; i<db->nDb; i++){
43645 struct Db *pDb = &db->aDb[i];
43646 if( pDb->pBt==0 ){
43647 sqliteFree(pDb->zName);
43648 pDb->zName = 0;
43649 continue;
43651 if( j<i ){
43652 db->aDb[j] = db->aDb[i];
43654 j++;
43656 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
43657 db->nDb = j;
43658 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
43659 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
43660 sqliteFree(db->aDb);
43661 db->aDb = db->aDbStatic;
43666 ** This routine is called when a commit occurs.
43668 static void sqlite3CommitInternalChanges(sqlite3 *db){
43669 db->flags &= ~SQLITE_InternChanges;
43673 ** Clear the column names from a table or view.
43675 static void sqliteResetColumnNames(Table *pTable){
43676 int i;
43677 Column *pCol;
43678 assert( pTable!=0 );
43679 if( (pCol = pTable->aCol)!=0 ){
43680 for(i=0; i<pTable->nCol; i++, pCol++){
43681 sqliteFree(pCol->zName);
43682 sqlite3ExprDelete(pCol->pDflt);
43683 sqliteFree(pCol->zType);
43684 sqliteFree(pCol->zColl);
43686 sqliteFree(pTable->aCol);
43688 pTable->aCol = 0;
43689 pTable->nCol = 0;
43693 ** Remove the memory data structures associated with the given
43694 ** Table. No changes are made to disk by this routine.
43696 ** This routine just deletes the data structure. It does not unlink
43697 ** the table data structure from the hash table. Nor does it remove
43698 ** foreign keys from the sqlite.aFKey hash table. But it does destroy
43699 ** memory structures of the indices and foreign keys associated with
43700 ** the table.
43702 static void sqlite3DeleteTable(Table *pTable){
43703 Index *pIndex, *pNext;
43704 FKey *pFKey, *pNextFKey;
43706 if( pTable==0 ) return;
43708 /* Do not delete the table until the reference count reaches zero. */
43709 pTable->nRef--;
43710 if( pTable->nRef>0 ){
43711 return;
43713 assert( pTable->nRef==0 );
43715 /* Delete all indices associated with this table
43717 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
43718 pNext = pIndex->pNext;
43719 assert( pIndex->pSchema==pTable->pSchema );
43720 sqliteDeleteIndex(pIndex);
43723 #ifndef SQLITE_OMIT_FOREIGN_KEY
43724 /* Delete all foreign keys associated with this table. The keys
43725 ** should have already been unlinked from the pSchema->aFKey hash table
43727 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
43728 pNextFKey = pFKey->pNextFrom;
43729 assert( sqlite3HashFind(&pTable->pSchema->aFKey,
43730 pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
43731 sqliteFree(pFKey);
43733 #endif
43735 /* Delete the Table structure itself.
43737 sqliteResetColumnNames(pTable);
43738 sqliteFree(pTable->zName);
43739 sqliteFree(pTable->zColAff);
43740 sqlite3SelectDelete(pTable->pSelect);
43741 #ifndef SQLITE_OMIT_CHECK
43742 sqlite3ExprDelete(pTable->pCheck);
43743 #endif
43744 sqlite3VtabClear(pTable);
43745 sqliteFree(pTable);
43749 ** Unlink the given table from the hash tables and the delete the
43750 ** table structure with all its indices and foreign keys.
43752 static void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
43753 Table *p;
43754 FKey *pF1, *pF2;
43755 Db *pDb;
43757 assert( db!=0 );
43758 assert( iDb>=0 && iDb<db->nDb );
43759 assert( zTabName && zTabName[0] );
43760 pDb = &db->aDb[iDb];
43761 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
43762 if( p ){
43763 #ifndef SQLITE_OMIT_FOREIGN_KEY
43764 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
43765 int nTo = strlen(pF1->zTo) + 1;
43766 pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
43767 if( pF2==pF1 ){
43768 sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
43769 }else{
43770 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
43771 if( pF2 ){
43772 pF2->pNextTo = pF1->pNextTo;
43776 #endif
43777 sqlite3DeleteTable(p);
43779 db->flags |= SQLITE_InternChanges;
43783 ** Given a token, return a string that consists of the text of that
43784 ** token with any quotations removed. Space to hold the returned string
43785 ** is obtained from sqliteMalloc() and must be freed by the calling
43786 ** function.
43788 ** Tokens are often just pointers into the original SQL text and so
43789 ** are not \000 terminated and are not persistent. The returned string
43790 ** is \000 terminated and is persistent.
43792 static char *sqlite3NameFromToken(Token *pName){
43793 char *zName;
43794 if( pName ){
43795 zName = sqliteStrNDup((char*)pName->z, pName->n);
43796 sqlite3Dequote(zName);
43797 }else{
43798 zName = 0;
43800 return zName;
43804 ** Open the sqlite_master table stored in database number iDb for
43805 ** writing. The table is opened using cursor 0.
43807 static void sqlite3OpenMasterTable(Parse *p, int iDb){
43808 Vdbe *v = sqlite3GetVdbe(p);
43809 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
43810 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
43811 sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
43812 sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
43816 ** The token *pName contains the name of a database (either "main" or
43817 ** "temp" or the name of an attached db). This routine returns the
43818 ** index of the named database in db->aDb[], or -1 if the named db
43819 ** does not exist.
43821 static int sqlite3FindDb(sqlite3 *db, Token *pName){
43822 int i = -1; /* Database number */
43823 int n; /* Number of characters in the name */
43824 Db *pDb; /* A database whose name space is being searched */
43825 char *zName; /* Name we are searching for */
43827 zName = sqlite3NameFromToken(pName);
43828 if( zName ){
43829 n = strlen(zName);
43830 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
43831 if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) &&
43832 0==sqlite3StrICmp(pDb->zName, zName) ){
43833 break;
43836 sqliteFree(zName);
43838 return i;
43841 /* The table or view or trigger name is passed to this routine via tokens
43842 ** pName1 and pName2. If the table name was fully qualified, for example:
43844 ** CREATE TABLE xxx.yyy (...);
43846 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
43847 ** the table name is not fully qualified, i.e.:
43849 ** CREATE TABLE yyy(...);
43851 ** Then pName1 is set to "yyy" and pName2 is "".
43853 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
43854 ** pName2) that stores the unqualified table name. The index of the
43855 ** database "xxx" is returned.
43857 static int sqlite3TwoPartName(
43858 Parse *pParse, /* Parsing and code generating context */
43859 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
43860 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
43861 Token **pUnqual /* Write the unqualified object name here */
43863 int iDb; /* Database holding the object */
43864 sqlite3 *db = pParse->db;
43866 if( pName2 && pName2->n>0 ){
43867 assert( !db->init.busy );
43868 *pUnqual = pName2;
43869 iDb = sqlite3FindDb(db, pName1);
43870 if( iDb<0 ){
43871 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
43872 pParse->nErr++;
43873 return -1;
43875 }else{
43876 assert( db->init.iDb==0 || db->init.busy );
43877 iDb = db->init.iDb;
43878 *pUnqual = pName1;
43880 return iDb;
43884 ** This routine is used to check if the UTF-8 string zName is a legal
43885 ** unqualified name for a new schema object (table, index, view or
43886 ** trigger). All names are legal except those that begin with the string
43887 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
43888 ** is reserved for internal use.
43890 static int sqlite3CheckObjectName(Parse *pParse, const char *zName){
43891 if( !pParse->db->init.busy && pParse->nested==0
43892 && (pParse->db->flags & SQLITE_WriteSchema)==0
43893 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
43894 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
43895 return SQLITE_ERROR;
43897 return SQLITE_OK;
43901 ** Begin constructing a new table representation in memory. This is
43902 ** the first of several action routines that get called in response
43903 ** to a CREATE TABLE statement. In particular, this routine is called
43904 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
43905 ** flag is true if the table should be stored in the auxiliary database
43906 ** file instead of in the main database file. This is normally the case
43907 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
43908 ** CREATE and TABLE.
43910 ** The new table record is initialized and put in pParse->pNewTable.
43911 ** As more of the CREATE TABLE statement is parsed, additional action
43912 ** routines will be called to add more information to this record.
43913 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
43914 ** is called to complete the construction of the new table record.
43916 static void sqlite3StartTable(
43917 Parse *pParse, /* Parser context */
43918 Token *pName1, /* First part of the name of the table or view */
43919 Token *pName2, /* Second part of the name of the table or view */
43920 int isTemp, /* True if this is a TEMP table */
43921 int isView, /* True if this is a VIEW */
43922 int isVirtual, /* True if this is a VIRTUAL table */
43923 int noErr /* Do nothing if table already exists */
43925 Table *pTable;
43926 char *zName = 0; /* The name of the new table */
43927 sqlite3 *db = pParse->db;
43928 Vdbe *v;
43929 int iDb; /* Database number to create the table in */
43930 Token *pName; /* Unqualified name of the table to create */
43932 /* The table or view name to create is passed to this routine via tokens
43933 ** pName1 and pName2. If the table name was fully qualified, for example:
43935 ** CREATE TABLE xxx.yyy (...);
43937 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
43938 ** the table name is not fully qualified, i.e.:
43940 ** CREATE TABLE yyy(...);
43942 ** Then pName1 is set to "yyy" and pName2 is "".
43944 ** The call below sets the pName pointer to point at the token (pName1 or
43945 ** pName2) that stores the unqualified table name. The variable iDb is
43946 ** set to the index of the database that the table or view is to be
43947 ** created in.
43949 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
43950 if( iDb<0 ) return;
43951 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
43952 /* If creating a temp table, the name may not be qualified */
43953 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
43954 return;
43956 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
43958 pParse->sNameToken = *pName;
43959 zName = sqlite3NameFromToken(pName);
43960 if( zName==0 ) return;
43961 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
43962 goto begin_table_error;
43964 if( db->init.iDb==1 ) isTemp = 1;
43965 #ifndef SQLITE_OMIT_AUTHORIZATION
43966 assert( (isTemp & 1)==isTemp );
43968 int code;
43969 char *zDb = db->aDb[iDb].zName;
43970 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
43971 goto begin_table_error;
43973 if( isView ){
43974 if( !OMIT_TEMPDB && isTemp ){
43975 code = SQLITE_CREATE_TEMP_VIEW;
43976 }else{
43977 code = SQLITE_CREATE_VIEW;
43979 }else{
43980 if( !OMIT_TEMPDB && isTemp ){
43981 code = SQLITE_CREATE_TEMP_TABLE;
43982 }else{
43983 code = SQLITE_CREATE_TABLE;
43986 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
43987 goto begin_table_error;
43990 #endif
43992 /* Make sure the new table name does not collide with an existing
43993 ** index or table name in the same database. Issue an error message if
43994 ** it does. The exception is if the statement being parsed was passed
43995 ** to an sqlite3_declare_vtab() call. In that case only the column names
43996 ** and types will be used, so there is no need to test for namespace
43997 ** collisions.
43999 if( !IN_DECLARE_VTAB ){
44000 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
44001 goto begin_table_error;
44003 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
44004 if( pTable ){
44005 if( !noErr ){
44006 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
44008 goto begin_table_error;
44010 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
44011 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
44012 goto begin_table_error;
44016 pTable = sqliteMalloc( sizeof(Table) );
44017 if( pTable==0 ){
44018 pParse->rc = SQLITE_NOMEM;
44019 pParse->nErr++;
44020 goto begin_table_error;
44022 pTable->zName = zName;
44023 pTable->iPKey = -1;
44024 pTable->pSchema = db->aDb[iDb].pSchema;
44025 pTable->nRef = 1;
44026 if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
44027 pParse->pNewTable = pTable;
44029 /* If this is the magic sqlite_sequence table used by autoincrement,
44030 ** then record a pointer to this table in the main database structure
44031 ** so that INSERT can find the table easily.
44033 #ifndef SQLITE_OMIT_AUTOINCREMENT
44034 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
44035 pTable->pSchema->pSeqTab = pTable;
44037 #endif
44039 /* Begin generating the code that will insert the table record into
44040 ** the SQLITE_MASTER table. Note in particular that we must go ahead
44041 ** and allocate the record number for the table entry now. Before any
44042 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
44043 ** indices to be created and the table record must come before the
44044 ** indices. Hence, the record number for the table must be allocated
44045 ** now.
44047 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
44048 int lbl;
44049 int fileFormat;
44050 sqlite3BeginWriteOperation(pParse, 0, iDb);
44052 #ifndef SQLITE_OMIT_VIRTUALTABLE
44053 if( isVirtual ){
44054 sqlite3VdbeAddOp(v, OP_VBegin, 0, 0);
44056 #endif
44058 /* If the file format and encoding in the database have not been set,
44059 ** set them now.
44061 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */
44062 lbl = sqlite3VdbeMakeLabel(v);
44063 sqlite3VdbeAddOp(v, OP_If, 0, lbl);
44064 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
44065 1 : SQLITE_MAX_FILE_FORMAT;
44066 sqlite3VdbeAddOp(v, OP_Integer, fileFormat, 0);
44067 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
44068 sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0);
44069 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
44070 sqlite3VdbeResolveLabel(v, lbl);
44072 /* This just creates a place-holder record in the sqlite_master table.
44073 ** The record created does not contain anything yet. It will be replaced
44074 ** by the real entry in code generated at sqlite3EndTable().
44076 ** The rowid for the new entry is left on the top of the stack.
44077 ** The rowid value is needed by the code that sqlite3EndTable will
44078 ** generate.
44080 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
44081 if( isView || isVirtual ){
44082 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
44083 }else
44084 #endif
44086 sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
44088 sqlite3OpenMasterTable(pParse, iDb);
44089 sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
44090 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
44091 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
44092 sqlite3VdbeAddOp(v, OP_Insert, 0, OPFLAG_APPEND);
44093 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
44094 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
44097 /* Normal (non-error) return. */
44098 return;
44100 /* If an error occurs, we jump here */
44101 begin_table_error:
44102 sqliteFree(zName);
44103 return;
44107 ** This macro is used to compare two strings in a case-insensitive manner.
44108 ** It is slightly faster than calling sqlite3StrICmp() directly, but
44109 ** produces larger code.
44111 ** WARNING: This macro is not compatible with the strcmp() family. It
44112 ** returns true if the two strings are equal, otherwise false.
44114 #define STRICMP(x, y) (\
44115 sqlite3UpperToLower[*(unsigned char *)(x)]== \
44116 sqlite3UpperToLower[*(unsigned char *)(y)] \
44117 && sqlite3StrICmp((x)+1,(y)+1)==0 )
44120 ** Add a new column to the table currently being constructed.
44122 ** The parser calls this routine once for each column declaration
44123 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
44124 ** first to get things going. Then this routine is called for each
44125 ** column.
44127 static void sqlite3AddColumn(Parse *pParse, Token *pName){
44128 Table *p;
44129 int i;
44130 char *z;
44131 Column *pCol;
44132 if( (p = pParse->pNewTable)==0 ) return;
44133 if( p->nCol+1>SQLITE_MAX_COLUMN ){
44134 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
44135 return;
44137 z = sqlite3NameFromToken(pName);
44138 if( z==0 ) return;
44139 for(i=0; i<p->nCol; i++){
44140 if( STRICMP(z, p->aCol[i].zName) ){
44141 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
44142 sqliteFree(z);
44143 return;
44146 if( (p->nCol & 0x7)==0 ){
44147 Column *aNew;
44148 aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
44149 if( aNew==0 ){
44150 sqliteFree(z);
44151 return;
44153 p->aCol = aNew;
44155 pCol = &p->aCol[p->nCol];
44156 memset(pCol, 0, sizeof(p->aCol[0]));
44157 pCol->zName = z;
44159 /* If there is no type specified, columns have the default affinity
44160 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
44161 ** be called next to set pCol->affinity correctly.
44163 pCol->affinity = SQLITE_AFF_NONE;
44164 p->nCol++;
44168 ** This routine is called by the parser while in the middle of
44169 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
44170 ** been seen on a column. This routine sets the notNull flag on
44171 ** the column currently under construction.
44173 static void sqlite3AddNotNull(Parse *pParse, int onError){
44174 Table *p;
44175 int i;
44176 if( (p = pParse->pNewTable)==0 ) return;
44177 i = p->nCol-1;
44178 if( i>=0 ) p->aCol[i].notNull = onError;
44182 ** Scan the column type name zType (length nType) and return the
44183 ** associated affinity type.
44185 ** This routine does a case-independent search of zType for the
44186 ** substrings in the following table. If one of the substrings is
44187 ** found, the corresponding affinity is returned. If zType contains
44188 ** more than one of the substrings, entries toward the top of
44189 ** the table take priority. For example, if zType is 'BLOBINT',
44190 ** SQLITE_AFF_INTEGER is returned.
44192 ** Substring | Affinity
44193 ** --------------------------------
44194 ** 'INT' | SQLITE_AFF_INTEGER
44195 ** 'CHAR' | SQLITE_AFF_TEXT
44196 ** 'CLOB' | SQLITE_AFF_TEXT
44197 ** 'TEXT' | SQLITE_AFF_TEXT
44198 ** 'BLOB' | SQLITE_AFF_NONE
44199 ** 'REAL' | SQLITE_AFF_REAL
44200 ** 'FLOA' | SQLITE_AFF_REAL
44201 ** 'DOUB' | SQLITE_AFF_REAL
44203 ** If none of the substrings in the above table are found,
44204 ** SQLITE_AFF_NUMERIC is returned.
44206 static char sqlite3AffinityType(const Token *pType){
44207 u32 h = 0;
44208 char aff = SQLITE_AFF_NUMERIC;
44209 const unsigned char *zIn = pType->z;
44210 const unsigned char *zEnd = &pType->z[pType->n];
44212 while( zIn!=zEnd ){
44213 h = (h<<8) + sqlite3UpperToLower[*zIn];
44214 zIn++;
44215 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
44216 aff = SQLITE_AFF_TEXT;
44217 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
44218 aff = SQLITE_AFF_TEXT;
44219 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
44220 aff = SQLITE_AFF_TEXT;
44221 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
44222 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
44223 aff = SQLITE_AFF_NONE;
44224 #ifndef SQLITE_OMIT_FLOATING_POINT
44225 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
44226 && aff==SQLITE_AFF_NUMERIC ){
44227 aff = SQLITE_AFF_REAL;
44228 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
44229 && aff==SQLITE_AFF_NUMERIC ){
44230 aff = SQLITE_AFF_REAL;
44231 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
44232 && aff==SQLITE_AFF_NUMERIC ){
44233 aff = SQLITE_AFF_REAL;
44234 #endif
44235 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
44236 aff = SQLITE_AFF_INTEGER;
44237 break;
44241 return aff;
44245 ** This routine is called by the parser while in the middle of
44246 ** parsing a CREATE TABLE statement. The pFirst token is the first
44247 ** token in the sequence of tokens that describe the type of the
44248 ** column currently under construction. pLast is the last token
44249 ** in the sequence. Use this information to construct a string
44250 ** that contains the typename of the column and store that string
44251 ** in zType.
44253 static void sqlite3AddColumnType(Parse *pParse, Token *pType){
44254 Table *p;
44255 int i;
44256 Column *pCol;
44258 if( (p = pParse->pNewTable)==0 ) return;
44259 i = p->nCol-1;
44260 if( i<0 ) return;
44261 pCol = &p->aCol[i];
44262 sqliteFree(pCol->zType);
44263 pCol->zType = sqlite3NameFromToken(pType);
44264 pCol->affinity = sqlite3AffinityType(pType);
44268 ** The expression is the default value for the most recently added column
44269 ** of the table currently under construction.
44271 ** Default value expressions must be constant. Raise an exception if this
44272 ** is not the case.
44274 ** This routine is called by the parser while in the middle of
44275 ** parsing a CREATE TABLE statement.
44277 static void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
44278 Table *p;
44279 Column *pCol;
44280 if( (p = pParse->pNewTable)!=0 ){
44281 pCol = &(p->aCol[p->nCol-1]);
44282 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
44283 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
44284 pCol->zName);
44285 }else{
44286 Expr *pCopy;
44287 sqlite3ExprDelete(pCol->pDflt);
44288 pCol->pDflt = pCopy = sqlite3ExprDup(pExpr);
44289 if( pCopy ){
44290 sqlite3TokenCopy(&pCopy->span, &pExpr->span);
44294 sqlite3ExprDelete(pExpr);
44298 ** Designate the PRIMARY KEY for the table. pList is a list of names
44299 ** of columns that form the primary key. If pList is NULL, then the
44300 ** most recently added column of the table is the primary key.
44302 ** A table can have at most one primary key. If the table already has
44303 ** a primary key (and this is the second primary key) then create an
44304 ** error.
44306 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
44307 ** then we will try to use that column as the rowid. Set the Table.iPKey
44308 ** field of the table under construction to be the index of the
44309 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
44310 ** no INTEGER PRIMARY KEY.
44312 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
44313 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
44315 static void sqlite3AddPrimaryKey(
44316 Parse *pParse, /* Parsing context */
44317 ExprList *pList, /* List of field names to be indexed */
44318 int onError, /* What to do with a uniqueness conflict */
44319 int autoInc, /* True if the AUTOINCREMENT keyword is present */
44320 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
44322 Table *pTab = pParse->pNewTable;
44323 char *zType = 0;
44324 int iCol = -1, i;
44325 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
44326 if( pTab->hasPrimKey ){
44327 sqlite3ErrorMsg(pParse,
44328 "table \"%s\" has more than one primary key", pTab->zName);
44329 goto primary_key_exit;
44331 pTab->hasPrimKey = 1;
44332 if( pList==0 ){
44333 iCol = pTab->nCol - 1;
44334 pTab->aCol[iCol].isPrimKey = 1;
44335 }else{
44336 for(i=0; i<pList->nExpr; i++){
44337 for(iCol=0; iCol<pTab->nCol; iCol++){
44338 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
44339 break;
44342 if( iCol<pTab->nCol ){
44343 pTab->aCol[iCol].isPrimKey = 1;
44346 if( pList->nExpr>1 ) iCol = -1;
44348 if( iCol>=0 && iCol<pTab->nCol ){
44349 zType = pTab->aCol[iCol].zType;
44351 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
44352 && sortOrder==SQLITE_SO_ASC ){
44353 pTab->iPKey = iCol;
44354 pTab->keyConf = onError;
44355 pTab->autoInc = autoInc;
44356 }else if( autoInc ){
44357 #ifndef SQLITE_OMIT_AUTOINCREMENT
44358 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
44359 "INTEGER PRIMARY KEY");
44360 #endif
44361 }else{
44362 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
44363 pList = 0;
44366 primary_key_exit:
44367 sqlite3ExprListDelete(pList);
44368 return;
44372 ** Add a new CHECK constraint to the table currently under construction.
44374 static void sqlite3AddCheckConstraint(
44375 Parse *pParse, /* Parsing context */
44376 Expr *pCheckExpr /* The check expression */
44378 #ifndef SQLITE_OMIT_CHECK
44379 Table *pTab = pParse->pNewTable;
44380 if( pTab && !IN_DECLARE_VTAB ){
44381 /* The CHECK expression must be duplicated so that tokens refer
44382 ** to malloced space and not the (ephemeral) text of the CREATE TABLE
44383 ** statement */
44384 pTab->pCheck = sqlite3ExprAnd(pTab->pCheck, sqlite3ExprDup(pCheckExpr));
44386 #endif
44387 sqlite3ExprDelete(pCheckExpr);
44391 ** Set the collation function of the most recently parsed table column
44392 ** to the CollSeq given.
44394 static void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
44395 Table *p;
44396 int i;
44398 if( (p = pParse->pNewTable)==0 ) return;
44399 i = p->nCol-1;
44401 if( sqlite3LocateCollSeq(pParse, zType, nType) ){
44402 Index *pIdx;
44403 p->aCol[i].zColl = sqliteStrNDup(zType, nType);
44405 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
44406 ** then an index may have been created on this column before the
44407 ** collation type was added. Correct this if it is the case.
44409 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
44410 assert( pIdx->nColumn==1 );
44411 if( pIdx->aiColumn[0]==i ){
44412 pIdx->azColl[0] = p->aCol[i].zColl;
44419 ** This function returns the collation sequence for database native text
44420 ** encoding identified by the string zName, length nName.
44422 ** If the requested collation sequence is not available, or not available
44423 ** in the database native encoding, the collation factory is invoked to
44424 ** request it. If the collation factory does not supply such a sequence,
44425 ** and the sequence is available in another text encoding, then that is
44426 ** returned instead.
44428 ** If no versions of the requested collations sequence are available, or
44429 ** another error occurs, NULL is returned and an error message written into
44430 ** pParse.
44432 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
44433 ** invokes the collation factory if the named collation cannot be found
44434 ** and generates an error message.
44436 static CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
44437 sqlite3 *db = pParse->db;
44438 u8 enc = ENC(db);
44439 u8 initbusy = db->init.busy;
44440 CollSeq *pColl;
44442 pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
44443 if( !initbusy && (!pColl || !pColl->xCmp) ){
44444 pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
44445 if( !pColl ){
44446 if( nName<0 ){
44447 nName = strlen(zName);
44449 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
44450 pColl = 0;
44454 return pColl;
44459 ** Generate code that will increment the schema cookie.
44461 ** The schema cookie is used to determine when the schema for the
44462 ** database changes. After each schema change, the cookie value
44463 ** changes. When a process first reads the schema it records the
44464 ** cookie. Thereafter, whenever it goes to access the database,
44465 ** it checks the cookie to make sure the schema has not changed
44466 ** since it was last read.
44468 ** This plan is not completely bullet-proof. It is possible for
44469 ** the schema to change multiple times and for the cookie to be
44470 ** set back to prior value. But schema changes are infrequent
44471 ** and the probability of hitting the same cookie value is only
44472 ** 1 chance in 2^32. So we're safe enough.
44474 static void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
44475 sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0);
44476 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
44480 ** Measure the number of characters needed to output the given
44481 ** identifier. The number returned includes any quotes used
44482 ** but does not include the null terminator.
44484 ** The estimate is conservative. It might be larger that what is
44485 ** really needed.
44487 static int identLength(const char *z){
44488 int n;
44489 for(n=0; *z; n++, z++){
44490 if( *z=='"' ){ n++; }
44492 return n + 2;
44496 ** Write an identifier onto the end of the given string. Add
44497 ** quote characters as needed.
44499 static void identPut(char *z, int *pIdx, char *zSignedIdent){
44500 unsigned char *zIdent = (unsigned char*)zSignedIdent;
44501 int i, j, needQuote;
44502 i = *pIdx;
44503 for(j=0; zIdent[j]; j++){
44504 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
44506 needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
44507 || sqlite3KeywordCode(zIdent, j)!=TK_ID;
44508 if( needQuote ) z[i++] = '"';
44509 for(j=0; zIdent[j]; j++){
44510 z[i++] = zIdent[j];
44511 if( zIdent[j]=='"' ) z[i++] = '"';
44513 if( needQuote ) z[i++] = '"';
44514 z[i] = 0;
44515 *pIdx = i;
44519 ** Generate a CREATE TABLE statement appropriate for the given
44520 ** table. Memory to hold the text of the statement is obtained
44521 ** from sqliteMalloc() and must be freed by the calling function.
44523 static char *createTableStmt(Table *p, int isTemp){
44524 int i, k, n;
44525 char *zStmt;
44526 char *zSep, *zSep2, *zEnd, *z;
44527 Column *pCol;
44528 n = 0;
44529 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
44530 n += identLength(pCol->zName);
44531 z = pCol->zType;
44532 if( z ){
44533 n += (strlen(z) + 1);
44536 n += identLength(p->zName);
44537 if( n<50 ){
44538 zSep = "";
44539 zSep2 = ",";
44540 zEnd = ")";
44541 }else{
44542 zSep = "\n ";
44543 zSep2 = ",\n ";
44544 zEnd = "\n)";
44546 n += 35 + 6*p->nCol;
44547 zStmt = sqliteMallocRaw( n );
44548 if( zStmt==0 ) return 0;
44549 sqlite3_snprintf(n, zStmt,
44550 !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
44551 k = strlen(zStmt);
44552 identPut(zStmt, &k, p->zName);
44553 zStmt[k++] = '(';
44554 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
44555 sqlite3_snprintf(n-k, &zStmt[k], zSep);
44556 k += strlen(&zStmt[k]);
44557 zSep = zSep2;
44558 identPut(zStmt, &k, pCol->zName);
44559 if( (z = pCol->zType)!=0 ){
44560 zStmt[k++] = ' ';
44561 assert( strlen(z)+k+1<=n );
44562 sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
44563 k += strlen(z);
44566 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
44567 return zStmt;
44571 ** This routine is called to report the final ")" that terminates
44572 ** a CREATE TABLE statement.
44574 ** The table structure that other action routines have been building
44575 ** is added to the internal hash tables, assuming no errors have
44576 ** occurred.
44578 ** An entry for the table is made in the master table on disk, unless
44579 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
44580 ** it means we are reading the sqlite_master table because we just
44581 ** connected to the database or because the sqlite_master table has
44582 ** recently changed, so the entry for this table already exists in
44583 ** the sqlite_master table. We do not want to create it again.
44585 ** If the pSelect argument is not NULL, it means that this routine
44586 ** was called to create a table generated from a
44587 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
44588 ** the new table will match the result set of the SELECT.
44590 static void sqlite3EndTable(
44591 Parse *pParse, /* Parse context */
44592 Token *pCons, /* The ',' token after the last column defn. */
44593 Token *pEnd, /* The final ')' token in the CREATE TABLE */
44594 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
44596 Table *p;
44597 sqlite3 *db = pParse->db;
44598 int iDb;
44600 if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3MallocFailed() ) {
44601 return;
44603 p = pParse->pNewTable;
44604 if( p==0 ) return;
44606 assert( !db->init.busy || !pSelect );
44608 iDb = sqlite3SchemaToIndex(db, p->pSchema);
44610 #ifndef SQLITE_OMIT_CHECK
44611 /* Resolve names in all CHECK constraint expressions.
44613 if( p->pCheck ){
44614 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
44615 NameContext sNC; /* Name context for pParse->pNewTable */
44617 memset(&sNC, 0, sizeof(sNC));
44618 memset(&sSrc, 0, sizeof(sSrc));
44619 sSrc.nSrc = 1;
44620 sSrc.a[0].zName = p->zName;
44621 sSrc.a[0].pTab = p;
44622 sSrc.a[0].iCursor = -1;
44623 sNC.pParse = pParse;
44624 sNC.pSrcList = &sSrc;
44625 sNC.isCheck = 1;
44626 if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
44627 return;
44630 #endif /* !defined(SQLITE_OMIT_CHECK) */
44632 /* If the db->init.busy is 1 it means we are reading the SQL off the
44633 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
44634 ** So do not write to the disk again. Extract the root page number
44635 ** for the table from the db->init.newTnum field. (The page number
44636 ** should have been put there by the sqliteOpenCb routine.)
44638 if( db->init.busy ){
44639 p->tnum = db->init.newTnum;
44642 /* If not initializing, then create a record for the new table
44643 ** in the SQLITE_MASTER table of the database. The record number
44644 ** for the new table entry should already be on the stack.
44646 ** If this is a TEMPORARY table, write the entry into the auxiliary
44647 ** file instead of into the main database file.
44649 if( !db->init.busy ){
44650 int n;
44651 Vdbe *v;
44652 char *zType; /* "view" or "table" */
44653 char *zType2; /* "VIEW" or "TABLE" */
44654 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
44656 v = sqlite3GetVdbe(pParse);
44657 if( v==0 ) return;
44659 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
44661 /* Create the rootpage for the new table and push it onto the stack.
44662 ** A view has no rootpage, so just push a zero onto the stack for
44663 ** views. Initialize zType at the same time.
44665 if( p->pSelect==0 ){
44666 /* A regular table */
44667 zType = "table";
44668 zType2 = "TABLE";
44669 #ifndef SQLITE_OMIT_VIEW
44670 }else{
44671 /* A view */
44672 zType = "view";
44673 zType2 = "VIEW";
44674 #endif
44677 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
44678 ** statement to populate the new table. The root-page number for the
44679 ** new table is on the top of the vdbe stack.
44681 ** Once the SELECT has been coded by sqlite3Select(), it is in a
44682 ** suitable state to query for the column names and types to be used
44683 ** by the new table.
44685 ** A shared-cache write-lock is not required to write to the new table,
44686 ** as a schema-lock must have already been obtained to create it. Since
44687 ** a schema-lock excludes all other database users, the write-lock would
44688 ** be redundant.
44690 if( pSelect ){
44691 Table *pSelTab;
44692 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
44693 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
44694 sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
44695 pParse->nTab = 2;
44696 sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
44697 sqlite3VdbeAddOp(v, OP_Close, 1, 0);
44698 if( pParse->nErr==0 ){
44699 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
44700 if( pSelTab==0 ) return;
44701 assert( p->aCol==0 );
44702 p->nCol = pSelTab->nCol;
44703 p->aCol = pSelTab->aCol;
44704 pSelTab->nCol = 0;
44705 pSelTab->aCol = 0;
44706 sqlite3DeleteTable(pSelTab);
44710 /* Compute the complete text of the CREATE statement */
44711 if( pSelect ){
44712 zStmt = createTableStmt(p, p->pSchema==pParse->db->aDb[1].pSchema);
44713 }else{
44714 n = pEnd->z - pParse->sNameToken.z + 1;
44715 zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z);
44718 /* A slot for the record has already been allocated in the
44719 ** SQLITE_MASTER table. We just need to update that slot with all
44720 ** the information we've collected. The rowid for the preallocated
44721 ** slot is the 2nd item on the stack. The top of the stack is the
44722 ** root page for the new table (or a 0 if this is a view).
44724 sqlite3NestedParse(pParse,
44725 "UPDATE %Q.%s "
44726 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
44727 "WHERE rowid=#1",
44728 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
44729 zType,
44730 p->zName,
44731 p->zName,
44732 zStmt
44734 sqliteFree(zStmt);
44735 sqlite3ChangeCookie(db, v, iDb);
44737 #ifndef SQLITE_OMIT_AUTOINCREMENT
44738 /* Check to see if we need to create an sqlite_sequence table for
44739 ** keeping track of autoincrement keys.
44741 if( p->autoInc ){
44742 Db *pDb = &db->aDb[iDb];
44743 if( pDb->pSchema->pSeqTab==0 ){
44744 sqlite3NestedParse(pParse,
44745 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
44746 pDb->zName
44750 #endif
44752 /* Reparse everything to update our internal data structures */
44753 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
44754 sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC);
44758 /* Add the table to the in-memory representation of the database.
44760 if( db->init.busy && pParse->nErr==0 ){
44761 Table *pOld;
44762 FKey *pFKey;
44763 Schema *pSchema = p->pSchema;
44764 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
44765 if( pOld ){
44766 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
44767 return;
44769 #ifndef SQLITE_OMIT_FOREIGN_KEY
44770 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
44771 int nTo = strlen(pFKey->zTo) + 1;
44772 pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
44773 sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
44775 #endif
44776 pParse->pNewTable = 0;
44777 db->nTable++;
44778 db->flags |= SQLITE_InternChanges;
44780 #ifndef SQLITE_OMIT_ALTERTABLE
44781 if( !p->pSelect ){
44782 const char *zName = (const char *)pParse->sNameToken.z;
44783 int nName;
44784 assert( !pSelect && pCons && pEnd );
44785 if( pCons->z==0 ){
44786 pCons = pEnd;
44788 nName = (const char *)pCons->z - zName;
44789 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
44791 #endif
44795 #ifndef SQLITE_OMIT_VIEW
44797 ** The parser calls this routine in order to create a new VIEW
44799 static void sqlite3CreateView(
44800 Parse *pParse, /* The parsing context */
44801 Token *pBegin, /* The CREATE token that begins the statement */
44802 Token *pName1, /* The token that holds the name of the view */
44803 Token *pName2, /* The token that holds the name of the view */
44804 Select *pSelect, /* A SELECT statement that will become the new view */
44805 int isTemp, /* TRUE for a TEMPORARY view */
44806 int noErr /* Suppress error messages if VIEW already exists */
44808 Table *p;
44809 int n;
44810 const unsigned char *z;
44811 Token sEnd;
44812 DbFixer sFix;
44813 Token *pName;
44814 int iDb;
44816 if( pParse->nVar>0 ){
44817 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
44818 sqlite3SelectDelete(pSelect);
44819 return;
44821 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
44822 p = pParse->pNewTable;
44823 if( p==0 || pParse->nErr ){
44824 sqlite3SelectDelete(pSelect);
44825 return;
44827 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
44828 iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
44829 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
44830 && sqlite3FixSelect(&sFix, pSelect)
44832 sqlite3SelectDelete(pSelect);
44833 return;
44836 /* Make a copy of the entire SELECT statement that defines the view.
44837 ** This will force all the Expr.token.z values to be dynamically
44838 ** allocated rather than point to the input string - which means that
44839 ** they will persist after the current sqlite3_exec() call returns.
44841 p->pSelect = sqlite3SelectDup(pSelect);
44842 sqlite3SelectDelete(pSelect);
44843 if( sqlite3MallocFailed() ){
44844 return;
44846 if( !pParse->db->init.busy ){
44847 sqlite3ViewGetColumnNames(pParse, p);
44850 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
44851 ** the end.
44853 sEnd = pParse->sLastToken;
44854 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
44855 sEnd.z += sEnd.n;
44857 sEnd.n = 0;
44858 n = sEnd.z - pBegin->z;
44859 z = (const unsigned char*)pBegin->z;
44860 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
44861 sEnd.z = &z[n-1];
44862 sEnd.n = 1;
44864 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
44865 sqlite3EndTable(pParse, 0, &sEnd, 0);
44866 return;
44868 #endif /* SQLITE_OMIT_VIEW */
44870 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
44872 ** The Table structure pTable is really a VIEW. Fill in the names of
44873 ** the columns of the view in the pTable structure. Return the number
44874 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
44876 static int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
44877 Table *pSelTab; /* A fake table from which we get the result set */
44878 Select *pSel; /* Copy of the SELECT that implements the view */
44879 int nErr = 0; /* Number of errors encountered */
44880 int n; /* Temporarily holds the number of cursors assigned */
44882 assert( pTable );
44884 #ifndef SQLITE_OMIT_VIRTUALTABLE
44885 if( sqlite3VtabCallConnect(pParse, pTable) ){
44886 return SQLITE_ERROR;
44888 if( IsVirtual(pTable) ) return 0;
44889 #endif
44891 #ifndef SQLITE_OMIT_VIEW
44892 /* A positive nCol means the columns names for this view are
44893 ** already known.
44895 if( pTable->nCol>0 ) return 0;
44897 /* A negative nCol is a special marker meaning that we are currently
44898 ** trying to compute the column names. If we enter this routine with
44899 ** a negative nCol, it means two or more views form a loop, like this:
44901 ** CREATE VIEW one AS SELECT * FROM two;
44902 ** CREATE VIEW two AS SELECT * FROM one;
44904 ** Actually, this error is caught previously and so the following test
44905 ** should always fail. But we will leave it in place just to be safe.
44907 if( pTable->nCol<0 ){
44908 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
44909 return 1;
44911 assert( pTable->nCol>=0 );
44913 /* If we get this far, it means we need to compute the table names.
44914 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
44915 ** "*" elements in the results set of the view and will assign cursors
44916 ** to the elements of the FROM clause. But we do not want these changes
44917 ** to be permanent. So the computation is done on a copy of the SELECT
44918 ** statement that defines the view.
44920 assert( pTable->pSelect );
44921 pSel = sqlite3SelectDup(pTable->pSelect);
44922 if( pSel ){
44923 n = pParse->nTab;
44924 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
44925 pTable->nCol = -1;
44926 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
44927 pParse->nTab = n;
44928 if( pSelTab ){
44929 assert( pTable->aCol==0 );
44930 pTable->nCol = pSelTab->nCol;
44931 pTable->aCol = pSelTab->aCol;
44932 pSelTab->nCol = 0;
44933 pSelTab->aCol = 0;
44934 sqlite3DeleteTable(pSelTab);
44935 pTable->pSchema->flags |= DB_UnresetViews;
44936 }else{
44937 pTable->nCol = 0;
44938 nErr++;
44940 sqlite3SelectDelete(pSel);
44941 } else {
44942 nErr++;
44944 #endif /* SQLITE_OMIT_VIEW */
44945 return nErr;
44947 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
44949 #ifndef SQLITE_OMIT_VIEW
44951 ** Clear the column names from every VIEW in database idx.
44953 static void sqliteViewResetAll(sqlite3 *db, int idx){
44954 HashElem *i;
44955 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
44956 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
44957 Table *pTab = sqliteHashData(i);
44958 if( pTab->pSelect ){
44959 sqliteResetColumnNames(pTab);
44962 DbClearProperty(db, idx, DB_UnresetViews);
44964 #else
44965 # define sqliteViewResetAll(A,B)
44966 #endif /* SQLITE_OMIT_VIEW */
44969 ** This function is called by the VDBE to adjust the internal schema
44970 ** used by SQLite when the btree layer moves a table root page. The
44971 ** root-page of a table or index in database iDb has changed from iFrom
44972 ** to iTo.
44974 ** Ticket #1728: The symbol table might still contain information
44975 ** on tables and/or indices that are the process of being deleted.
44976 ** If you are unlucky, one of those deleted indices or tables might
44977 ** have the same rootpage number as the real table or index that is
44978 ** being moved. So we cannot stop searching after the first match
44979 ** because the first match might be for one of the deleted indices
44980 ** or tables and not the table/index that is actually being moved.
44981 ** We must continue looping until all tables and indices with
44982 ** rootpage==iFrom have been converted to have a rootpage of iTo
44983 ** in order to be certain that we got the right one.
44985 #ifndef SQLITE_OMIT_AUTOVACUUM
44986 static void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
44987 HashElem *pElem;
44988 Hash *pHash;
44990 pHash = &pDb->pSchema->tblHash;
44991 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
44992 Table *pTab = sqliteHashData(pElem);
44993 if( pTab->tnum==iFrom ){
44994 pTab->tnum = iTo;
44997 pHash = &pDb->pSchema->idxHash;
44998 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
44999 Index *pIdx = sqliteHashData(pElem);
45000 if( pIdx->tnum==iFrom ){
45001 pIdx->tnum = iTo;
45005 #endif
45008 ** Write code to erase the table with root-page iTable from database iDb.
45009 ** Also write code to modify the sqlite_master table and internal schema
45010 ** if a root-page of another table is moved by the btree-layer whilst
45011 ** erasing iTable (this can happen with an auto-vacuum database).
45013 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
45014 Vdbe *v = sqlite3GetVdbe(pParse);
45015 sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
45016 #ifndef SQLITE_OMIT_AUTOVACUUM
45017 /* OP_Destroy pushes an integer onto the stack. If this integer
45018 ** is non-zero, then it is the root page number of a table moved to
45019 ** location iTable. The following code modifies the sqlite_master table to
45020 ** reflect this.
45022 ** The "#0" in the SQL is a special constant that means whatever value
45023 ** is on the top of the stack. See sqlite3RegisterExpr().
45025 sqlite3NestedParse(pParse,
45026 "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
45027 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
45028 #endif
45032 ** Write VDBE code to erase table pTab and all associated indices on disk.
45033 ** Code to update the sqlite_master tables and internal schema definitions
45034 ** in case a root-page belonging to another table is moved by the btree layer
45035 ** is also added (this can happen with an auto-vacuum database).
45037 static void destroyTable(Parse *pParse, Table *pTab){
45038 #ifdef SQLITE_OMIT_AUTOVACUUM
45039 Index *pIdx;
45040 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
45041 destroyRootPage(pParse, pTab->tnum, iDb);
45042 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
45043 destroyRootPage(pParse, pIdx->tnum, iDb);
45045 #else
45046 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
45047 ** is not defined), then it is important to call OP_Destroy on the
45048 ** table and index root-pages in order, starting with the numerically
45049 ** largest root-page number. This guarantees that none of the root-pages
45050 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
45051 ** following were coded:
45053 ** OP_Destroy 4 0
45054 ** ...
45055 ** OP_Destroy 5 0
45057 ** and root page 5 happened to be the largest root-page number in the
45058 ** database, then root page 5 would be moved to page 4 by the
45059 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
45060 ** a free-list page.
45062 int iTab = pTab->tnum;
45063 int iDestroyed = 0;
45065 while( 1 ){
45066 Index *pIdx;
45067 int iLargest = 0;
45069 if( iDestroyed==0 || iTab<iDestroyed ){
45070 iLargest = iTab;
45072 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
45073 int iIdx = pIdx->tnum;
45074 assert( pIdx->pSchema==pTab->pSchema );
45075 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
45076 iLargest = iIdx;
45079 if( iLargest==0 ){
45080 return;
45081 }else{
45082 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
45083 destroyRootPage(pParse, iLargest, iDb);
45084 iDestroyed = iLargest;
45087 #endif
45091 ** This routine is called to do the work of a DROP TABLE statement.
45092 ** pName is the name of the table to be dropped.
45094 static void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
45095 Table *pTab;
45096 Vdbe *v;
45097 sqlite3 *db = pParse->db;
45098 int iDb;
45100 if( pParse->nErr || sqlite3MallocFailed() ){
45101 goto exit_drop_table;
45103 assert( pName->nSrc==1 );
45104 pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
45106 if( pTab==0 ){
45107 if( noErr ){
45108 sqlite3ErrorClear(pParse);
45110 goto exit_drop_table;
45112 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
45113 assert( iDb>=0 && iDb<db->nDb );
45114 #ifndef SQLITE_OMIT_AUTHORIZATION
45116 int code;
45117 const char *zTab = SCHEMA_TABLE(iDb);
45118 const char *zDb = db->aDb[iDb].zName;
45119 const char *zArg2 = 0;
45120 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
45121 goto exit_drop_table;
45123 if( isView ){
45124 if( !OMIT_TEMPDB && iDb==1 ){
45125 code = SQLITE_DROP_TEMP_VIEW;
45126 }else{
45127 code = SQLITE_DROP_VIEW;
45129 #ifndef SQLITE_OMIT_VIRTUALTABLE
45130 }else if( IsVirtual(pTab) ){
45131 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
45132 goto exit_drop_table;
45134 code = SQLITE_DROP_VTABLE;
45135 zArg2 = pTab->pMod->zName;
45136 #endif
45137 }else{
45138 if( !OMIT_TEMPDB && iDb==1 ){
45139 code = SQLITE_DROP_TEMP_TABLE;
45140 }else{
45141 code = SQLITE_DROP_TABLE;
45144 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
45145 goto exit_drop_table;
45147 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
45148 goto exit_drop_table;
45151 #endif
45152 if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
45153 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
45154 goto exit_drop_table;
45157 #ifndef SQLITE_OMIT_VIEW
45158 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
45159 ** on a table.
45161 if( isView && pTab->pSelect==0 ){
45162 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
45163 goto exit_drop_table;
45165 if( !isView && pTab->pSelect ){
45166 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
45167 goto exit_drop_table;
45169 #endif
45171 /* Generate code to remove the table from the master table
45172 ** on disk.
45174 v = sqlite3GetVdbe(pParse);
45175 if( v ){
45176 Trigger *pTrigger;
45177 Db *pDb = &db->aDb[iDb];
45178 sqlite3BeginWriteOperation(pParse, 0, iDb);
45180 #ifndef SQLITE_OMIT_VIRTUALTABLE
45181 if( IsVirtual(pTab) ){
45182 Vdbe *v = sqlite3GetVdbe(pParse);
45183 if( v ){
45184 sqlite3VdbeAddOp(v, OP_VBegin, 0, 0);
45187 #endif
45189 /* Drop all triggers associated with the table being dropped. Code
45190 ** is generated to remove entries from sqlite_master and/or
45191 ** sqlite_temp_master if required.
45193 pTrigger = pTab->pTrigger;
45194 while( pTrigger ){
45195 assert( pTrigger->pSchema==pTab->pSchema ||
45196 pTrigger->pSchema==db->aDb[1].pSchema );
45197 sqlite3DropTriggerPtr(pParse, pTrigger);
45198 pTrigger = pTrigger->pNext;
45201 #ifndef SQLITE_OMIT_AUTOINCREMENT
45202 /* Remove any entries of the sqlite_sequence table associated with
45203 ** the table being dropped. This is done before the table is dropped
45204 ** at the btree level, in case the sqlite_sequence table needs to
45205 ** move as a result of the drop (can happen in auto-vacuum mode).
45207 if( pTab->autoInc ){
45208 sqlite3NestedParse(pParse,
45209 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
45210 pDb->zName, pTab->zName
45213 #endif
45215 /* Drop all SQLITE_MASTER table and index entries that refer to the
45216 ** table. The program name loops through the master table and deletes
45217 ** every row that refers to a table of the same name as the one being
45218 ** dropped. Triggers are handled seperately because a trigger can be
45219 ** created in the temp database that refers to a table in another
45220 ** database.
45222 sqlite3NestedParse(pParse,
45223 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
45224 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
45225 if( !isView && !IsVirtual(pTab) ){
45226 destroyTable(pParse, pTab);
45229 /* Remove the table entry from SQLite's internal schema and modify
45230 ** the schema cookie.
45232 if( IsVirtual(pTab) ){
45233 sqlite3VdbeOp3(v, OP_VDestroy, iDb, 0, pTab->zName, 0);
45235 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
45236 sqlite3ChangeCookie(db, v, iDb);
45238 sqliteViewResetAll(db, iDb);
45240 exit_drop_table:
45241 sqlite3SrcListDelete(pName);
45245 ** This routine is called to create a new foreign key on the table
45246 ** currently under construction. pFromCol determines which columns
45247 ** in the current table point to the foreign key. If pFromCol==0 then
45248 ** connect the key to the last column inserted. pTo is the name of
45249 ** the table referred to. pToCol is a list of tables in the other
45250 ** pTo table that the foreign key points to. flags contains all
45251 ** information about the conflict resolution algorithms specified
45252 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
45254 ** An FKey structure is created and added to the table currently
45255 ** under construction in the pParse->pNewTable field. The new FKey
45256 ** is not linked into db->aFKey at this point - that does not happen
45257 ** until sqlite3EndTable().
45259 ** The foreign key is set for IMMEDIATE processing. A subsequent call
45260 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
45262 static void sqlite3CreateForeignKey(
45263 Parse *pParse, /* Parsing context */
45264 ExprList *pFromCol, /* Columns in this table that point to other table */
45265 Token *pTo, /* Name of the other table */
45266 ExprList *pToCol, /* Columns in the other table */
45267 int flags /* Conflict resolution algorithms. */
45269 #ifndef SQLITE_OMIT_FOREIGN_KEY
45270 FKey *pFKey = 0;
45271 Table *p = pParse->pNewTable;
45272 int nByte;
45273 int i;
45274 int nCol;
45275 char *z;
45277 assert( pTo!=0 );
45278 if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
45279 if( pFromCol==0 ){
45280 int iCol = p->nCol-1;
45281 if( iCol<0 ) goto fk_end;
45282 if( pToCol && pToCol->nExpr!=1 ){
45283 sqlite3ErrorMsg(pParse, "foreign key on %s"
45284 " should reference only one column of table %T",
45285 p->aCol[iCol].zName, pTo);
45286 goto fk_end;
45288 nCol = 1;
45289 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
45290 sqlite3ErrorMsg(pParse,
45291 "number of columns in foreign key does not match the number of "
45292 "columns in the referenced table");
45293 goto fk_end;
45294 }else{
45295 nCol = pFromCol->nExpr;
45297 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
45298 if( pToCol ){
45299 for(i=0; i<pToCol->nExpr; i++){
45300 nByte += strlen(pToCol->a[i].zName) + 1;
45303 pFKey = sqliteMalloc( nByte );
45304 if( pFKey==0 ) goto fk_end;
45305 pFKey->pFrom = p;
45306 pFKey->pNextFrom = p->pFKey;
45307 z = (char*)&pFKey[1];
45308 pFKey->aCol = (struct sColMap*)z;
45309 z += sizeof(struct sColMap)*nCol;
45310 pFKey->zTo = z;
45311 memcpy(z, pTo->z, pTo->n);
45312 z[pTo->n] = 0;
45313 z += pTo->n+1;
45314 pFKey->pNextTo = 0;
45315 pFKey->nCol = nCol;
45316 if( pFromCol==0 ){
45317 pFKey->aCol[0].iFrom = p->nCol-1;
45318 }else{
45319 for(i=0; i<nCol; i++){
45320 int j;
45321 for(j=0; j<p->nCol; j++){
45322 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
45323 pFKey->aCol[i].iFrom = j;
45324 break;
45327 if( j>=p->nCol ){
45328 sqlite3ErrorMsg(pParse,
45329 "unknown column \"%s\" in foreign key definition",
45330 pFromCol->a[i].zName);
45331 goto fk_end;
45335 if( pToCol ){
45336 for(i=0; i<nCol; i++){
45337 int n = strlen(pToCol->a[i].zName);
45338 pFKey->aCol[i].zCol = z;
45339 memcpy(z, pToCol->a[i].zName, n);
45340 z[n] = 0;
45341 z += n+1;
45344 pFKey->isDeferred = 0;
45345 pFKey->deleteConf = flags & 0xff;
45346 pFKey->updateConf = (flags >> 8 ) & 0xff;
45347 pFKey->insertConf = (flags >> 16 ) & 0xff;
45349 /* Link the foreign key to the table as the last step.
45351 p->pFKey = pFKey;
45352 pFKey = 0;
45354 fk_end:
45355 sqliteFree(pFKey);
45356 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
45357 sqlite3ExprListDelete(pFromCol);
45358 sqlite3ExprListDelete(pToCol);
45362 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
45363 ** clause is seen as part of a foreign key definition. The isDeferred
45364 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
45365 ** The behavior of the most recently created foreign key is adjusted
45366 ** accordingly.
45368 static void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
45369 #ifndef SQLITE_OMIT_FOREIGN_KEY
45370 Table *pTab;
45371 FKey *pFKey;
45372 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
45373 pFKey->isDeferred = isDeferred;
45374 #endif
45378 ** Generate code that will erase and refill index *pIdx. This is
45379 ** used to initialize a newly created index or to recompute the
45380 ** content of an index in response to a REINDEX command.
45382 ** if memRootPage is not negative, it means that the index is newly
45383 ** created. The memory cell specified by memRootPage contains the
45384 ** root page number of the index. If memRootPage is negative, then
45385 ** the index already exists and must be cleared before being refilled and
45386 ** the root page number of the index is taken from pIndex->tnum.
45388 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
45389 Table *pTab = pIndex->pTable; /* The table that is indexed */
45390 int iTab = pParse->nTab; /* Btree cursor used for pTab */
45391 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
45392 int addr1; /* Address of top of loop */
45393 int tnum; /* Root page of index */
45394 Vdbe *v; /* Generate code into this virtual machine */
45395 KeyInfo *pKey; /* KeyInfo for index */
45396 int iDb = sqlite3SchemaToIndex(pParse->db, pIndex->pSchema);
45398 #ifndef SQLITE_OMIT_AUTHORIZATION
45399 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
45400 pParse->db->aDb[iDb].zName ) ){
45401 return;
45403 #endif
45405 /* Require a write-lock on the table to perform this operation */
45406 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
45408 v = sqlite3GetVdbe(pParse);
45409 if( v==0 ) return;
45410 if( memRootPage>=0 ){
45411 sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
45412 tnum = 0;
45413 }else{
45414 tnum = pIndex->tnum;
45415 sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb);
45417 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
45418 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
45419 sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, (char *)pKey, P3_KEYINFO_HANDOFF);
45420 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
45421 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
45422 sqlite3GenerateIndexKey(v, pIndex, iTab);
45423 if( pIndex->onError!=OE_None ){
45424 int curaddr = sqlite3VdbeCurrentAddr(v);
45425 int addr2 = curaddr+4;
45426 sqlite3VdbeChangeP2(v, curaddr-1, addr2);
45427 sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0);
45428 sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
45429 sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2);
45430 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort,
45431 "indexed columns are not unique", P3_STATIC);
45432 assert( sqlite3MallocFailed() || addr2==sqlite3VdbeCurrentAddr(v) );
45434 sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0);
45435 sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
45436 sqlite3VdbeJumpHere(v, addr1);
45437 sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
45438 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
45442 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
45443 ** and pTblList is the name of the table that is to be indexed. Both will
45444 ** be NULL for a primary key or an index that is created to satisfy a
45445 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
45446 ** as the table to be indexed. pParse->pNewTable is a table that is
45447 ** currently being constructed by a CREATE TABLE statement.
45449 ** pList is a list of columns to be indexed. pList will be NULL if this
45450 ** is a primary key or unique-constraint on the most recent column added
45451 ** to the table currently under construction.
45453 static void sqlite3CreateIndex(
45454 Parse *pParse, /* All information about this parse */
45455 Token *pName1, /* First part of index name. May be NULL */
45456 Token *pName2, /* Second part of index name. May be NULL */
45457 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
45458 ExprList *pList, /* A list of columns to be indexed */
45459 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
45460 Token *pStart, /* The CREATE token that begins a CREATE TABLE statement */
45461 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
45462 int sortOrder, /* Sort order of primary key when pList==NULL */
45463 int ifNotExist /* Omit error if index already exists */
45465 Table *pTab = 0; /* Table to be indexed */
45466 Index *pIndex = 0; /* The index to be created */
45467 char *zName = 0; /* Name of the index */
45468 int nName; /* Number of characters in zName */
45469 int i, j;
45470 Token nullId; /* Fake token for an empty ID list */
45471 DbFixer sFix; /* For assigning database names to pTable */
45472 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
45473 sqlite3 *db = pParse->db;
45474 Db *pDb; /* The specific table containing the indexed database */
45475 int iDb; /* Index of the database that is being written */
45476 Token *pName = 0; /* Unqualified name of the index to create */
45477 struct ExprList_item *pListItem; /* For looping over pList */
45478 int nCol;
45479 int nExtra = 0;
45480 char *zExtra;
45482 if( pParse->nErr || sqlite3MallocFailed() || IN_DECLARE_VTAB ){
45483 goto exit_create_index;
45487 ** Find the table that is to be indexed. Return early if not found.
45489 if( pTblName!=0 ){
45491 /* Use the two-part index name to determine the database
45492 ** to search for the table. 'Fix' the table name to this db
45493 ** before looking up the table.
45495 assert( pName1 && pName2 );
45496 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
45497 if( iDb<0 ) goto exit_create_index;
45499 #ifndef SQLITE_OMIT_TEMPDB
45500 /* If the index name was unqualified, check if the the table
45501 ** is a temp table. If so, set the database to 1.
45503 pTab = sqlite3SrcListLookup(pParse, pTblName);
45504 if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
45505 iDb = 1;
45507 #endif
45509 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
45510 sqlite3FixSrcList(&sFix, pTblName)
45512 /* Because the parser constructs pTblName from a single identifier,
45513 ** sqlite3FixSrcList can never fail. */
45514 assert(0);
45516 pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName,
45517 pTblName->a[0].zDatabase);
45518 if( !pTab ) goto exit_create_index;
45519 assert( db->aDb[iDb].pSchema==pTab->pSchema );
45520 }else{
45521 assert( pName==0 );
45522 pTab = pParse->pNewTable;
45523 if( !pTab ) goto exit_create_index;
45524 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
45526 pDb = &db->aDb[iDb];
45528 if( pTab==0 || pParse->nErr ) goto exit_create_index;
45529 if( pTab->readOnly ){
45530 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
45531 goto exit_create_index;
45533 #ifndef SQLITE_OMIT_VIEW
45534 if( pTab->pSelect ){
45535 sqlite3ErrorMsg(pParse, "views may not be indexed");
45536 goto exit_create_index;
45538 #endif
45539 #ifndef SQLITE_OMIT_VIRTUALTABLE
45540 if( IsVirtual(pTab) ){
45541 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
45542 goto exit_create_index;
45544 #endif
45547 ** Find the name of the index. Make sure there is not already another
45548 ** index or table with the same name.
45550 ** Exception: If we are reading the names of permanent indices from the
45551 ** sqlite_master table (because some other process changed the schema) and
45552 ** one of the index names collides with the name of a temporary table or
45553 ** index, then we will continue to process this index.
45555 ** If pName==0 it means that we are
45556 ** dealing with a primary key or UNIQUE constraint. We have to invent our
45557 ** own name.
45559 if( pName ){
45560 zName = sqlite3NameFromToken(pName);
45561 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
45562 if( zName==0 ) goto exit_create_index;
45563 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
45564 goto exit_create_index;
45566 if( !db->init.busy ){
45567 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
45568 if( sqlite3FindTable(db, zName, 0)!=0 ){
45569 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
45570 goto exit_create_index;
45573 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
45574 if( !ifNotExist ){
45575 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
45577 goto exit_create_index;
45579 }else{
45580 char zBuf[30];
45581 int n;
45582 Index *pLoop;
45583 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
45584 sqlite3_snprintf(sizeof(zBuf),zBuf,"_%d",n);
45585 zName = 0;
45586 sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
45587 if( zName==0 ) goto exit_create_index;
45590 /* Check for authorization to create an index.
45592 #ifndef SQLITE_OMIT_AUTHORIZATION
45594 const char *zDb = pDb->zName;
45595 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
45596 goto exit_create_index;
45598 i = SQLITE_CREATE_INDEX;
45599 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
45600 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
45601 goto exit_create_index;
45604 #endif
45606 /* If pList==0, it means this routine was called to make a primary
45607 ** key out of the last column added to the table under construction.
45608 ** So create a fake list to simulate this.
45610 if( pList==0 ){
45611 nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
45612 nullId.n = strlen((char*)nullId.z);
45613 pList = sqlite3ExprListAppend(0, 0, &nullId);
45614 if( pList==0 ) goto exit_create_index;
45615 pList->a[0].sortOrder = sortOrder;
45618 /* Figure out how many bytes of space are required to store explicitly
45619 ** specified collation sequence names.
45621 for(i=0; i<pList->nExpr; i++){
45622 Expr *pExpr = pList->a[i].pExpr;
45623 if( pExpr ){
45624 nExtra += (1 + strlen(pExpr->pColl->zName));
45629 ** Allocate the index structure.
45631 nName = strlen(zName);
45632 nCol = pList->nExpr;
45633 pIndex = sqliteMalloc(
45634 sizeof(Index) + /* Index structure */
45635 sizeof(int)*nCol + /* Index.aiColumn */
45636 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
45637 sizeof(char *)*nCol + /* Index.azColl */
45638 sizeof(u8)*nCol + /* Index.aSortOrder */
45639 nName + 1 + /* Index.zName */
45640 nExtra /* Collation sequence names */
45642 if( sqlite3MallocFailed() ) goto exit_create_index;
45643 pIndex->azColl = (char**)(&pIndex[1]);
45644 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
45645 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
45646 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
45647 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
45648 zExtra = (char *)(&pIndex->zName[nName+1]);
45649 memcpy(pIndex->zName, zName, nName+1);
45650 pIndex->pTable = pTab;
45651 pIndex->nColumn = pList->nExpr;
45652 pIndex->onError = onError;
45653 pIndex->autoIndex = pName==0;
45654 pIndex->pSchema = db->aDb[iDb].pSchema;
45656 /* Check to see if we should honor DESC requests on index columns
45658 if( pDb->pSchema->file_format>=4 ){
45659 sortOrderMask = -1; /* Honor DESC */
45660 }else{
45661 sortOrderMask = 0; /* Ignore DESC */
45664 /* Scan the names of the columns of the table to be indexed and
45665 ** load the column indices into the Index structure. Report an error
45666 ** if any column is not found.
45668 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
45669 const char *zColName = pListItem->zName;
45670 Column *pTabCol;
45671 int requestedSortOrder;
45672 char *zColl; /* Collation sequence name */
45674 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
45675 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
45677 if( j>=pTab->nCol ){
45678 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
45679 pTab->zName, zColName);
45680 goto exit_create_index;
45682 /* TODO: Add a test to make sure that the same column is not named
45683 ** more than once within the same index. Only the first instance of
45684 ** the column will ever be used by the optimizer. Note that using the
45685 ** same column more than once cannot be an error because that would
45686 ** break backwards compatibility - it needs to be a warning.
45688 pIndex->aiColumn[i] = j;
45689 if( pListItem->pExpr ){
45690 assert( pListItem->pExpr->pColl );
45691 zColl = zExtra;
45692 sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
45693 zExtra += (strlen(zColl) + 1);
45694 }else{
45695 zColl = pTab->aCol[j].zColl;
45696 if( !zColl ){
45697 zColl = db->pDfltColl->zName;
45700 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
45701 goto exit_create_index;
45703 pIndex->azColl[i] = zColl;
45704 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
45705 pIndex->aSortOrder[i] = requestedSortOrder;
45707 sqlite3DefaultRowEst(pIndex);
45709 if( pTab==pParse->pNewTable ){
45710 /* This routine has been called to create an automatic index as a
45711 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
45712 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
45713 ** i.e. one of:
45715 ** CREATE TABLE t(x PRIMARY KEY, y);
45716 ** CREATE TABLE t(x, y, UNIQUE(x, y));
45718 ** Either way, check to see if the table already has such an index. If
45719 ** so, don't bother creating this one. This only applies to
45720 ** automatically created indices. Users can do as they wish with
45721 ** explicit indices.
45723 Index *pIdx;
45724 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
45725 int k;
45726 assert( pIdx->onError!=OE_None );
45727 assert( pIdx->autoIndex );
45728 assert( pIndex->onError!=OE_None );
45730 if( pIdx->nColumn!=pIndex->nColumn ) continue;
45731 for(k=0; k<pIdx->nColumn; k++){
45732 const char *z1 = pIdx->azColl[k];
45733 const char *z2 = pIndex->azColl[k];
45734 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
45735 if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
45736 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
45738 if( k==pIdx->nColumn ){
45739 if( pIdx->onError!=pIndex->onError ){
45740 /* This constraint creates the same index as a previous
45741 ** constraint specified somewhere in the CREATE TABLE statement.
45742 ** However the ON CONFLICT clauses are different. If both this
45743 ** constraint and the previous equivalent constraint have explicit
45744 ** ON CONFLICT clauses this is an error. Otherwise, use the
45745 ** explicitly specified behaviour for the index.
45747 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
45748 sqlite3ErrorMsg(pParse,
45749 "conflicting ON CONFLICT clauses specified", 0);
45751 if( pIdx->onError==OE_Default ){
45752 pIdx->onError = pIndex->onError;
45755 goto exit_create_index;
45760 /* Link the new Index structure to its table and to the other
45761 ** in-memory database structures.
45763 if( db->init.busy ){
45764 Index *p;
45765 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
45766 pIndex->zName, strlen(pIndex->zName)+1, pIndex);
45767 if( p ){
45768 assert( p==pIndex ); /* Malloc must have failed */
45769 goto exit_create_index;
45771 db->flags |= SQLITE_InternChanges;
45772 if( pTblName!=0 ){
45773 pIndex->tnum = db->init.newTnum;
45777 /* If the db->init.busy is 0 then create the index on disk. This
45778 ** involves writing the index into the master table and filling in the
45779 ** index with the current table contents.
45781 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
45782 ** command. db->init.busy is 1 when a database is opened and
45783 ** CREATE INDEX statements are read out of the master table. In
45784 ** the latter case the index already exists on disk, which is why
45785 ** we don't want to recreate it.
45787 ** If pTblName==0 it means this index is generated as a primary key
45788 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
45789 ** has just been created, it contains no data and the index initialization
45790 ** step can be skipped.
45792 else if( db->init.busy==0 ){
45793 Vdbe *v;
45794 char *zStmt;
45795 int iMem = pParse->nMem++;
45797 v = sqlite3GetVdbe(pParse);
45798 if( v==0 ) goto exit_create_index;
45801 /* Create the rootpage for the index
45803 sqlite3BeginWriteOperation(pParse, 1, iDb);
45804 sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
45805 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
45807 /* Gather the complete text of the CREATE INDEX statement into
45808 ** the zStmt variable
45810 if( pStart && pEnd ){
45811 /* A named index with an explicit CREATE INDEX statement */
45812 zStmt = sqlite3MPrintf("CREATE%s INDEX %.*s",
45813 onError==OE_None ? "" : " UNIQUE",
45814 pEnd->z - pName->z + 1,
45815 pName->z);
45816 }else{
45817 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
45818 /* zStmt = sqlite3MPrintf(""); */
45819 zStmt = 0;
45822 /* Add an entry in sqlite_master for this index
45824 sqlite3NestedParse(pParse,
45825 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
45826 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
45827 pIndex->zName,
45828 pTab->zName,
45829 zStmt
45831 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
45832 sqliteFree(zStmt);
45834 /* Fill the index with data and reparse the schema. Code an OP_Expire
45835 ** to invalidate all pre-compiled statements.
45837 if( pTblName ){
45838 sqlite3RefillIndex(pParse, pIndex, iMem);
45839 sqlite3ChangeCookie(db, v, iDb);
45840 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
45841 sqlite3MPrintf("name='%q'", pIndex->zName), P3_DYNAMIC);
45842 sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
45846 /* When adding an index to the list of indices for a table, make
45847 ** sure all indices labeled OE_Replace come after all those labeled
45848 ** OE_Ignore. This is necessary for the correct operation of UPDATE
45849 ** and INSERT.
45851 if( db->init.busy || pTblName==0 ){
45852 if( onError!=OE_Replace || pTab->pIndex==0
45853 || pTab->pIndex->onError==OE_Replace){
45854 pIndex->pNext = pTab->pIndex;
45855 pTab->pIndex = pIndex;
45856 }else{
45857 Index *pOther = pTab->pIndex;
45858 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
45859 pOther = pOther->pNext;
45861 pIndex->pNext = pOther->pNext;
45862 pOther->pNext = pIndex;
45864 pIndex = 0;
45867 /* Clean up before exiting */
45868 exit_create_index:
45869 if( pIndex ){
45870 freeIndex(pIndex);
45872 sqlite3ExprListDelete(pList);
45873 sqlite3SrcListDelete(pTblName);
45874 sqliteFree(zName);
45875 return;
45879 ** Generate code to make sure the file format number is at least minFormat.
45880 ** The generated code will increase the file format number if necessary.
45882 static void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
45883 Vdbe *v;
45884 v = sqlite3GetVdbe(pParse);
45885 if( v ){
45886 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
45887 sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
45888 sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
45889 sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
45890 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
45895 ** Fill the Index.aiRowEst[] array with default information - information
45896 ** to be used when we have not run the ANALYZE command.
45898 ** aiRowEst[0] is suppose to contain the number of elements in the index.
45899 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
45900 ** number of rows in the table that match any particular value of the
45901 ** first column of the index. aiRowEst[2] is an estimate of the number
45902 ** of rows that match any particular combiniation of the first 2 columns
45903 ** of the index. And so forth. It must always be the case that
45905 ** aiRowEst[N]<=aiRowEst[N-1]
45906 ** aiRowEst[N]>=1
45908 ** Apart from that, we have little to go on besides intuition as to
45909 ** how aiRowEst[] should be initialized. The numbers generated here
45910 ** are based on typical values found in actual indices.
45912 static void sqlite3DefaultRowEst(Index *pIdx){
45913 unsigned *a = pIdx->aiRowEst;
45914 int i;
45915 assert( a!=0 );
45916 a[0] = 1000000;
45917 for(i=pIdx->nColumn; i>=5; i--){
45918 a[i] = 5;
45920 while( i>=1 ){
45921 a[i] = 11 - i;
45922 i--;
45924 if( pIdx->onError!=OE_None ){
45925 a[pIdx->nColumn] = 1;
45930 ** This routine will drop an existing named index. This routine
45931 ** implements the DROP INDEX statement.
45933 static void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
45934 Index *pIndex;
45935 Vdbe *v;
45936 sqlite3 *db = pParse->db;
45937 int iDb;
45939 if( pParse->nErr || sqlite3MallocFailed() ){
45940 goto exit_drop_index;
45942 assert( pName->nSrc==1 );
45943 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
45944 goto exit_drop_index;
45946 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
45947 if( pIndex==0 ){
45948 if( !ifExists ){
45949 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
45951 pParse->checkSchema = 1;
45952 goto exit_drop_index;
45954 if( pIndex->autoIndex ){
45955 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
45956 "or PRIMARY KEY constraint cannot be dropped", 0);
45957 goto exit_drop_index;
45959 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
45960 #ifndef SQLITE_OMIT_AUTHORIZATION
45962 int code = SQLITE_DROP_INDEX;
45963 Table *pTab = pIndex->pTable;
45964 const char *zDb = db->aDb[iDb].zName;
45965 const char *zTab = SCHEMA_TABLE(iDb);
45966 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
45967 goto exit_drop_index;
45969 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
45970 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
45971 goto exit_drop_index;
45974 #endif
45976 /* Generate code to remove the index and from the master table */
45977 v = sqlite3GetVdbe(pParse);
45978 if( v ){
45979 sqlite3NestedParse(pParse,
45980 "DELETE FROM %Q.%s WHERE name=%Q",
45981 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
45982 pIndex->zName
45984 sqlite3ChangeCookie(db, v, iDb);
45985 destroyRootPage(pParse, pIndex->tnum, iDb);
45986 sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
45989 exit_drop_index:
45990 sqlite3SrcListDelete(pName);
45994 ** pArray is a pointer to an array of objects. Each object in the
45995 ** array is szEntry bytes in size. This routine allocates a new
45996 ** object on the end of the array.
45998 ** *pnEntry is the number of entries already in use. *pnAlloc is
45999 ** the previously allocated size of the array. initSize is the
46000 ** suggested initial array size allocation.
46002 ** The index of the new entry is returned in *pIdx.
46004 ** This routine returns a pointer to the array of objects. This
46005 ** might be the same as the pArray parameter or it might be a different
46006 ** pointer if the array was resized.
46008 static void *sqlite3ArrayAllocate(
46009 void *pArray, /* Array of objects. Might be reallocated */
46010 int szEntry, /* Size of each object in the array */
46011 int initSize, /* Suggested initial allocation, in elements */
46012 int *pnEntry, /* Number of objects currently in use */
46013 int *pnAlloc, /* Current size of the allocation, in elements */
46014 int *pIdx /* Write the index of a new slot here */
46016 char *z;
46017 if( *pnEntry >= *pnAlloc ){
46018 void *pNew;
46019 int newSize;
46020 newSize = (*pnAlloc)*2 + initSize;
46021 pNew = sqliteRealloc(pArray, newSize*szEntry);
46022 if( pNew==0 ){
46023 *pIdx = -1;
46024 return pArray;
46026 *pnAlloc = newSize;
46027 pArray = pNew;
46029 z = (char*)pArray;
46030 memset(&z[*pnEntry * szEntry], 0, szEntry);
46031 *pIdx = *pnEntry;
46032 ++*pnEntry;
46033 return pArray;
46037 ** Append a new element to the given IdList. Create a new IdList if
46038 ** need be.
46040 ** A new IdList is returned, or NULL if malloc() fails.
46042 static IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
46043 int i;
46044 if( pList==0 ){
46045 pList = sqliteMalloc( sizeof(IdList) );
46046 if( pList==0 ) return 0;
46047 pList->nAlloc = 0;
46049 pList->a = sqlite3ArrayAllocate(
46050 pList->a,
46051 sizeof(pList->a[0]),
46053 &pList->nId,
46054 &pList->nAlloc,
46057 if( i<0 ){
46058 sqlite3IdListDelete(pList);
46059 return 0;
46061 pList->a[i].zName = sqlite3NameFromToken(pToken);
46062 return pList;
46066 ** Delete an IdList.
46068 static void sqlite3IdListDelete(IdList *pList){
46069 int i;
46070 if( pList==0 ) return;
46071 for(i=0; i<pList->nId; i++){
46072 sqliteFree(pList->a[i].zName);
46074 sqliteFree(pList->a);
46075 sqliteFree(pList);
46079 ** Return the index in pList of the identifier named zId. Return -1
46080 ** if not found.
46082 static int sqlite3IdListIndex(IdList *pList, const char *zName){
46083 int i;
46084 if( pList==0 ) return -1;
46085 for(i=0; i<pList->nId; i++){
46086 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
46088 return -1;
46092 ** Append a new table name to the given SrcList. Create a new SrcList if
46093 ** need be. A new entry is created in the SrcList even if pToken is NULL.
46095 ** A new SrcList is returned, or NULL if malloc() fails.
46097 ** If pDatabase is not null, it means that the table has an optional
46098 ** database name prefix. Like this: "database.table". The pDatabase
46099 ** points to the table name and the pTable points to the database name.
46100 ** The SrcList.a[].zName field is filled with the table name which might
46101 ** come from pTable (if pDatabase is NULL) or from pDatabase.
46102 ** SrcList.a[].zDatabase is filled with the database name from pTable,
46103 ** or with NULL if no database is specified.
46105 ** In other words, if call like this:
46107 ** sqlite3SrcListAppend(A,B,0);
46109 ** Then B is a table name and the database name is unspecified. If called
46110 ** like this:
46112 ** sqlite3SrcListAppend(A,B,C);
46114 ** Then C is the table name and B is the database name.
46116 static SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
46117 struct SrcList_item *pItem;
46118 if( pList==0 ){
46119 pList = sqliteMalloc( sizeof(SrcList) );
46120 if( pList==0 ) return 0;
46121 pList->nAlloc = 1;
46123 if( pList->nSrc>=pList->nAlloc ){
46124 SrcList *pNew;
46125 pList->nAlloc *= 2;
46126 pNew = sqliteRealloc(pList,
46127 sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
46128 if( pNew==0 ){
46129 sqlite3SrcListDelete(pList);
46130 return 0;
46132 pList = pNew;
46134 pItem = &pList->a[pList->nSrc];
46135 memset(pItem, 0, sizeof(pList->a[0]));
46136 if( pDatabase && pDatabase->z==0 ){
46137 pDatabase = 0;
46139 if( pDatabase && pTable ){
46140 Token *pTemp = pDatabase;
46141 pDatabase = pTable;
46142 pTable = pTemp;
46144 pItem->zName = sqlite3NameFromToken(pTable);
46145 pItem->zDatabase = sqlite3NameFromToken(pDatabase);
46146 pItem->iCursor = -1;
46147 pItem->isPopulated = 0;
46148 pList->nSrc++;
46149 return pList;
46153 ** Assign cursors to all tables in a SrcList
46155 static void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
46156 int i;
46157 struct SrcList_item *pItem;
46158 assert(pList || sqlite3MallocFailed() );
46159 if( pList ){
46160 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
46161 if( pItem->iCursor>=0 ) break;
46162 pItem->iCursor = pParse->nTab++;
46163 if( pItem->pSelect ){
46164 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
46171 ** Delete an entire SrcList including all its substructure.
46173 static void sqlite3SrcListDelete(SrcList *pList){
46174 int i;
46175 struct SrcList_item *pItem;
46176 if( pList==0 ) return;
46177 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
46178 sqliteFree(pItem->zDatabase);
46179 sqliteFree(pItem->zName);
46180 sqliteFree(pItem->zAlias);
46181 sqlite3DeleteTable(pItem->pTab);
46182 sqlite3SelectDelete(pItem->pSelect);
46183 sqlite3ExprDelete(pItem->pOn);
46184 sqlite3IdListDelete(pItem->pUsing);
46186 sqliteFree(pList);
46190 ** This routine is called by the parser to add a new term to the
46191 ** end of a growing FROM clause. The "p" parameter is the part of
46192 ** the FROM clause that has already been constructed. "p" is NULL
46193 ** if this is the first term of the FROM clause. pTable and pDatabase
46194 ** are the name of the table and database named in the FROM clause term.
46195 ** pDatabase is NULL if the database name qualifier is missing - the
46196 ** usual case. If the term has a alias, then pAlias points to the
46197 ** alias token. If the term is a subquery, then pSubquery is the
46198 ** SELECT statement that the subquery encodes. The pTable and
46199 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
46200 ** parameters are the content of the ON and USING clauses.
46202 ** Return a new SrcList which encodes is the FROM with the new
46203 ** term added.
46205 static SrcList *sqlite3SrcListAppendFromTerm(
46206 SrcList *p, /* The left part of the FROM clause already seen */
46207 Token *pTable, /* Name of the table to add to the FROM clause */
46208 Token *pDatabase, /* Name of the database containing pTable */
46209 Token *pAlias, /* The right-hand side of the AS subexpression */
46210 Select *pSubquery, /* A subquery used in place of a table name */
46211 Expr *pOn, /* The ON clause of a join */
46212 IdList *pUsing /* The USING clause of a join */
46214 struct SrcList_item *pItem;
46215 p = sqlite3SrcListAppend(p, pTable, pDatabase);
46216 if( p==0 || p->nSrc==0 ){
46217 sqlite3ExprDelete(pOn);
46218 sqlite3IdListDelete(pUsing);
46219 sqlite3SelectDelete(pSubquery);
46220 return p;
46222 pItem = &p->a[p->nSrc-1];
46223 if( pAlias && pAlias->n ){
46224 pItem->zAlias = sqlite3NameFromToken(pAlias);
46226 pItem->pSelect = pSubquery;
46227 pItem->pOn = pOn;
46228 pItem->pUsing = pUsing;
46229 return p;
46233 ** When building up a FROM clause in the parser, the join operator
46234 ** is initially attached to the left operand. But the code generator
46235 ** expects the join operator to be on the right operand. This routine
46236 ** Shifts all join operators from left to right for an entire FROM
46237 ** clause.
46239 ** Example: Suppose the join is like this:
46241 ** A natural cross join B
46243 ** The operator is "natural cross join". The A and B operands are stored
46244 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
46245 ** operator with A. This routine shifts that operator over to B.
46247 static void sqlite3SrcListShiftJoinType(SrcList *p){
46248 if( p && p->a ){
46249 int i;
46250 for(i=p->nSrc-1; i>0; i--){
46251 p->a[i].jointype = p->a[i-1].jointype;
46253 p->a[0].jointype = 0;
46258 ** Begin a transaction
46260 static void sqlite3BeginTransaction(Parse *pParse, int type){
46261 sqlite3 *db;
46262 Vdbe *v;
46263 int i;
46265 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
46266 if( pParse->nErr || sqlite3MallocFailed() ) return;
46267 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
46269 v = sqlite3GetVdbe(pParse);
46270 if( !v ) return;
46271 if( type!=TK_DEFERRED ){
46272 for(i=0; i<db->nDb; i++){
46273 sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
46276 sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
46280 ** Commit a transaction
46282 static void sqlite3CommitTransaction(Parse *pParse){
46283 sqlite3 *db;
46284 Vdbe *v;
46286 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
46287 if( pParse->nErr || sqlite3MallocFailed() ) return;
46288 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
46290 v = sqlite3GetVdbe(pParse);
46291 if( v ){
46292 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
46297 ** Rollback a transaction
46299 static void sqlite3RollbackTransaction(Parse *pParse){
46300 sqlite3 *db;
46301 Vdbe *v;
46303 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
46304 if( pParse->nErr || sqlite3MallocFailed() ) return;
46305 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
46307 v = sqlite3GetVdbe(pParse);
46308 if( v ){
46309 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
46314 ** Make sure the TEMP database is open and available for use. Return
46315 ** the number of errors. Leave any error messages in the pParse structure.
46317 static int sqlite3OpenTempDatabase(Parse *pParse){
46318 sqlite3 *db = pParse->db;
46319 if( db->aDb[1].pBt==0 && !pParse->explain ){
46320 int rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE,
46321 &db->aDb[1].pBt);
46322 if( rc!=SQLITE_OK ){
46323 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
46324 "file for storing temporary tables");
46325 pParse->rc = rc;
46326 return 1;
46328 if( db->flags & !db->autoCommit ){
46329 rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
46330 if( rc!=SQLITE_OK ){
46331 sqlite3ErrorMsg(pParse, "unable to get a write lock on "
46332 "the temporary database file");
46333 pParse->rc = rc;
46334 return 1;
46337 assert( db->aDb[1].pSchema );
46339 return 0;
46343 ** Generate VDBE code that will verify the schema cookie and start
46344 ** a read-transaction for all named database files.
46346 ** It is important that all schema cookies be verified and all
46347 ** read transactions be started before anything else happens in
46348 ** the VDBE program. But this routine can be called after much other
46349 ** code has been generated. So here is what we do:
46351 ** The first time this routine is called, we code an OP_Goto that
46352 ** will jump to a subroutine at the end of the program. Then we
46353 ** record every database that needs its schema verified in the
46354 ** pParse->cookieMask field. Later, after all other code has been
46355 ** generated, the subroutine that does the cookie verifications and
46356 ** starts the transactions will be coded and the OP_Goto P2 value
46357 ** will be made to point to that subroutine. The generation of the
46358 ** cookie verification subroutine code happens in sqlite3FinishCoding().
46360 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
46361 ** schema on any databases. This can be used to position the OP_Goto
46362 ** early in the code, before we know if any database tables will be used.
46364 static void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
46365 sqlite3 *db;
46366 Vdbe *v;
46367 int mask;
46369 v = sqlite3GetVdbe(pParse);
46370 if( v==0 ) return; /* This only happens if there was a prior error */
46371 db = pParse->db;
46372 if( pParse->cookieGoto==0 ){
46373 pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
46375 if( iDb>=0 ){
46376 assert( iDb<db->nDb );
46377 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
46378 assert( iDb<SQLITE_MAX_ATTACHED+2 );
46379 mask = 1<<iDb;
46380 if( (pParse->cookieMask & mask)==0 ){
46381 pParse->cookieMask |= mask;
46382 pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
46383 if( !OMIT_TEMPDB && iDb==1 ){
46384 sqlite3OpenTempDatabase(pParse);
46391 ** Generate VDBE code that prepares for doing an operation that
46392 ** might change the database.
46394 ** This routine starts a new transaction if we are not already within
46395 ** a transaction. If we are already within a transaction, then a checkpoint
46396 ** is set if the setStatement parameter is true. A checkpoint should
46397 ** be set for operations that might fail (due to a constraint) part of
46398 ** the way through and which will need to undo some writes without having to
46399 ** rollback the whole transaction. For operations where all constraints
46400 ** can be checked before any changes are made to the database, it is never
46401 ** necessary to undo a write and the checkpoint should not be set.
46403 ** Only database iDb and the temp database are made writable by this call.
46404 ** If iDb==0, then the main and temp databases are made writable. If
46405 ** iDb==1 then only the temp database is made writable. If iDb>1 then the
46406 ** specified auxiliary database and the temp database are made writable.
46408 static void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
46409 Vdbe *v = sqlite3GetVdbe(pParse);
46410 if( v==0 ) return;
46411 sqlite3CodeVerifySchema(pParse, iDb);
46412 pParse->writeMask |= 1<<iDb;
46413 if( setStatement && pParse->nested==0 ){
46414 sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
46416 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
46417 sqlite3BeginWriteOperation(pParse, setStatement, 1);
46422 ** Check to see if pIndex uses the collating sequence pColl. Return
46423 ** true if it does and false if it does not.
46425 #ifndef SQLITE_OMIT_REINDEX
46426 static int collationMatch(const char *zColl, Index *pIndex){
46427 int i;
46428 for(i=0; i<pIndex->nColumn; i++){
46429 const char *z = pIndex->azColl[i];
46430 if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
46431 return 1;
46434 return 0;
46436 #endif
46439 ** Recompute all indices of pTab that use the collating sequence pColl.
46440 ** If pColl==0 then recompute all indices of pTab.
46442 #ifndef SQLITE_OMIT_REINDEX
46443 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
46444 Index *pIndex; /* An index associated with pTab */
46446 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
46447 if( zColl==0 || collationMatch(zColl, pIndex) ){
46448 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
46449 sqlite3BeginWriteOperation(pParse, 0, iDb);
46450 sqlite3RefillIndex(pParse, pIndex, -1);
46454 #endif
46457 ** Recompute all indices of all tables in all databases where the
46458 ** indices use the collating sequence pColl. If pColl==0 then recompute
46459 ** all indices everywhere.
46461 #ifndef SQLITE_OMIT_REINDEX
46462 static void reindexDatabases(Parse *pParse, char const *zColl){
46463 Db *pDb; /* A single database */
46464 int iDb; /* The database index number */
46465 sqlite3 *db = pParse->db; /* The database connection */
46466 HashElem *k; /* For looping over tables in pDb */
46467 Table *pTab; /* A table in the database */
46469 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
46470 assert( pDb!=0 );
46471 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
46472 pTab = (Table*)sqliteHashData(k);
46473 reindexTable(pParse, pTab, zColl);
46477 #endif
46480 ** Generate code for the REINDEX command.
46482 ** REINDEX -- 1
46483 ** REINDEX <collation> -- 2
46484 ** REINDEX ?<database>.?<tablename> -- 3
46485 ** REINDEX ?<database>.?<indexname> -- 4
46487 ** Form 1 causes all indices in all attached databases to be rebuilt.
46488 ** Form 2 rebuilds all indices in all databases that use the named
46489 ** collating function. Forms 3 and 4 rebuild the named index or all
46490 ** indices associated with the named table.
46492 #ifndef SQLITE_OMIT_REINDEX
46493 static void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
46494 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
46495 char *z; /* Name of a table or index */
46496 const char *zDb; /* Name of the database */
46497 Table *pTab; /* A table in the database */
46498 Index *pIndex; /* An index associated with pTab */
46499 int iDb; /* The database index number */
46500 sqlite3 *db = pParse->db; /* The database connection */
46501 Token *pObjName; /* Name of the table or index to be reindexed */
46503 /* Read the database schema. If an error occurs, leave an error message
46504 ** and code in pParse and return NULL. */
46505 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
46506 return;
46509 if( pName1==0 || pName1->z==0 ){
46510 reindexDatabases(pParse, 0);
46511 return;
46512 }else if( pName2==0 || pName2->z==0 ){
46513 assert( pName1->z );
46514 pColl = sqlite3FindCollSeq(db, ENC(db), (char*)pName1->z, pName1->n, 0);
46515 if( pColl ){
46516 char *zColl = sqliteStrNDup((const char *)pName1->z, pName1->n);
46517 if( zColl ){
46518 reindexDatabases(pParse, zColl);
46519 sqliteFree(zColl);
46521 return;
46524 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
46525 if( iDb<0 ) return;
46526 z = sqlite3NameFromToken(pObjName);
46527 if( z==0 ) return;
46528 zDb = db->aDb[iDb].zName;
46529 pTab = sqlite3FindTable(db, z, zDb);
46530 if( pTab ){
46531 reindexTable(pParse, pTab, 0);
46532 sqliteFree(z);
46533 return;
46535 pIndex = sqlite3FindIndex(db, z, zDb);
46536 sqliteFree(z);
46537 if( pIndex ){
46538 sqlite3BeginWriteOperation(pParse, 0, iDb);
46539 sqlite3RefillIndex(pParse, pIndex, -1);
46540 return;
46542 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
46544 #endif
46547 ** Return a dynamicly allocated KeyInfo structure that can be used
46548 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
46550 ** If successful, a pointer to the new structure is returned. In this case
46551 ** the caller is responsible for calling sqliteFree() on the returned
46552 ** pointer. If an error occurs (out of memory or missing collation
46553 ** sequence), NULL is returned and the state of pParse updated to reflect
46554 ** the error.
46556 static KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
46557 int i;
46558 int nCol = pIdx->nColumn;
46559 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
46560 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(nBytes);
46562 if( pKey ){
46563 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
46564 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
46565 for(i=0; i<nCol; i++){
46566 char *zColl = pIdx->azColl[i];
46567 assert( zColl );
46568 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
46569 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
46571 pKey->nField = nCol;
46574 if( pParse->nErr ){
46575 sqliteFree(pKey);
46576 pKey = 0;
46578 return pKey;
46581 /************** End of build.c ***********************************************/
46582 /************** Begin file callback.c ****************************************/
46584 ** 2005 May 23
46586 ** The author disclaims copyright to this source code. In place of
46587 ** a legal notice, here is a blessing:
46589 ** May you do good and not evil.
46590 ** May you find forgiveness for yourself and forgive others.
46591 ** May you share freely, never taking more than you give.
46593 *************************************************************************
46595 ** This file contains functions used to access the internal hash tables
46596 ** of user defined functions and collation sequences.
46598 ** $Id: callback.c,v 1.18 2007/05/07 09:32:45 danielk1977 Exp $
46603 ** Invoke the 'collation needed' callback to request a collation sequence
46604 ** in the database text encoding of name zName, length nName.
46605 ** If the collation sequence
46607 static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
46608 assert( !db->xCollNeeded || !db->xCollNeeded16 );
46609 if( nName<0 ) nName = strlen(zName);
46610 if( db->xCollNeeded ){
46611 char *zExternal = sqliteStrNDup(zName, nName);
46612 if( !zExternal ) return;
46613 db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
46614 sqliteFree(zExternal);
46616 #ifndef SQLITE_OMIT_UTF16
46617 if( db->xCollNeeded16 ){
46618 char const *zExternal;
46619 sqlite3_value *pTmp = sqlite3ValueNew();
46620 sqlite3ValueSetStr(pTmp, nName, zName, SQLITE_UTF8, SQLITE_STATIC);
46621 zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
46622 if( zExternal ){
46623 db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
46625 sqlite3ValueFree(pTmp);
46627 #endif
46631 ** This routine is called if the collation factory fails to deliver a
46632 ** collation function in the best encoding but there may be other versions
46633 ** of this collation function (for other text encodings) available. Use one
46634 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
46635 ** possible.
46637 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
46638 CollSeq *pColl2;
46639 char *z = pColl->zName;
46640 int n = strlen(z);
46641 int i;
46642 static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
46643 for(i=0; i<3; i++){
46644 pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, n, 0);
46645 if( pColl2->xCmp!=0 ){
46646 memcpy(pColl, pColl2, sizeof(CollSeq));
46647 pColl->xDel = 0; /* Do not copy the destructor */
46648 return SQLITE_OK;
46651 return SQLITE_ERROR;
46655 ** This function is responsible for invoking the collation factory callback
46656 ** or substituting a collation sequence of a different encoding when the
46657 ** requested collation sequence is not available in the database native
46658 ** encoding.
46660 ** If it is not NULL, then pColl must point to the database native encoding
46661 ** collation sequence with name zName, length nName.
46663 ** The return value is either the collation sequence to be used in database
46664 ** db for collation type name zName, length nName, or NULL, if no collation
46665 ** sequence can be found.
46667 static CollSeq *sqlite3GetCollSeq(
46668 sqlite3* db,
46669 CollSeq *pColl,
46670 const char *zName,
46671 int nName
46673 CollSeq *p;
46675 p = pColl;
46676 if( !p ){
46677 p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
46679 if( !p || !p->xCmp ){
46680 /* No collation sequence of this type for this encoding is registered.
46681 ** Call the collation factory to see if it can supply us with one.
46683 callCollNeeded(db, zName, nName);
46684 p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
46686 if( p && !p->xCmp && synthCollSeq(db, p) ){
46687 p = 0;
46689 assert( !p || p->xCmp );
46690 return p;
46694 ** This routine is called on a collation sequence before it is used to
46695 ** check that it is defined. An undefined collation sequence exists when
46696 ** a database is loaded that contains references to collation sequences
46697 ** that have not been defined by sqlite3_create_collation() etc.
46699 ** If required, this routine calls the 'collation needed' callback to
46700 ** request a definition of the collating sequence. If this doesn't work,
46701 ** an equivalent collating sequence that uses a text encoding different
46702 ** from the main database is substituted, if one is available.
46704 static int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
46705 if( pColl ){
46706 const char *zName = pColl->zName;
46707 CollSeq *p = sqlite3GetCollSeq(pParse->db, pColl, zName, -1);
46708 if( !p ){
46709 if( pParse->nErr==0 ){
46710 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
46712 pParse->nErr++;
46713 return SQLITE_ERROR;
46715 assert( p==pColl );
46717 return SQLITE_OK;
46723 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
46724 ** specified by zName and nName is not found and parameter 'create' is
46725 ** true, then create a new entry. Otherwise return NULL.
46727 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
46728 ** array of three CollSeq structures. The first is the collation sequence
46729 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
46731 ** Stored immediately after the three collation sequences is a copy of
46732 ** the collation sequence name. A pointer to this string is stored in
46733 ** each collation sequence structure.
46735 static CollSeq *findCollSeqEntry(
46736 sqlite3 *db,
46737 const char *zName,
46738 int nName,
46739 int create
46741 CollSeq *pColl;
46742 if( nName<0 ) nName = strlen(zName);
46743 pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
46745 if( 0==pColl && create ){
46746 pColl = sqliteMalloc( 3*sizeof(*pColl) + nName + 1 );
46747 if( pColl ){
46748 CollSeq *pDel = 0;
46749 pColl[0].zName = (char*)&pColl[3];
46750 pColl[0].enc = SQLITE_UTF8;
46751 pColl[1].zName = (char*)&pColl[3];
46752 pColl[1].enc = SQLITE_UTF16LE;
46753 pColl[2].zName = (char*)&pColl[3];
46754 pColl[2].enc = SQLITE_UTF16BE;
46755 memcpy(pColl[0].zName, zName, nName);
46756 pColl[0].zName[nName] = 0;
46757 pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
46759 /* If a malloc() failure occured in sqlite3HashInsert(), it will
46760 ** return the pColl pointer to be deleted (because it wasn't added
46761 ** to the hash table).
46763 assert( !pDel || (sqlite3MallocFailed() && pDel==pColl) );
46764 if( pDel ){
46765 sqliteFree(pDel);
46766 pColl = 0;
46770 return pColl;
46774 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
46775 ** Return the CollSeq* pointer for the collation sequence named zName
46776 ** for the encoding 'enc' from the database 'db'.
46778 ** If the entry specified is not found and 'create' is true, then create a
46779 ** new entry. Otherwise return NULL.
46781 ** A separate function sqlite3LocateCollSeq() is a wrapper around
46782 ** this routine. sqlite3LocateCollSeq() invokes the collation factory
46783 ** if necessary and generates an error message if the collating sequence
46784 ** cannot be found.
46786 static CollSeq *sqlite3FindCollSeq(
46787 sqlite3 *db,
46788 u8 enc,
46789 const char *zName,
46790 int nName,
46791 int create
46793 CollSeq *pColl;
46794 if( zName ){
46795 pColl = findCollSeqEntry(db, zName, nName, create);
46796 }else{
46797 pColl = db->pDfltColl;
46799 assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
46800 assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
46801 if( pColl ) pColl += enc-1;
46802 return pColl;
46806 ** Locate a user function given a name, a number of arguments and a flag
46807 ** indicating whether the function prefers UTF-16 over UTF-8. Return a
46808 ** pointer to the FuncDef structure that defines that function, or return
46809 ** NULL if the function does not exist.
46811 ** If the createFlag argument is true, then a new (blank) FuncDef
46812 ** structure is created and liked into the "db" structure if a
46813 ** no matching function previously existed. When createFlag is true
46814 ** and the nArg parameter is -1, then only a function that accepts
46815 ** any number of arguments will be returned.
46817 ** If createFlag is false and nArg is -1, then the first valid
46818 ** function found is returned. A function is valid if either xFunc
46819 ** or xStep is non-zero.
46821 ** If createFlag is false, then a function with the required name and
46822 ** number of arguments may be returned even if the eTextRep flag does not
46823 ** match that requested.
46825 static FuncDef *sqlite3FindFunction(
46826 sqlite3 *db, /* An open database */
46827 const char *zName, /* Name of the function. Not null-terminated */
46828 int nName, /* Number of characters in the name */
46829 int nArg, /* Number of arguments. -1 means any number */
46830 u8 enc, /* Preferred text encoding */
46831 int createFlag /* Create new entry if true and does not otherwise exist */
46833 FuncDef *p; /* Iterator variable */
46834 FuncDef *pFirst; /* First function with this name */
46835 FuncDef *pBest = 0; /* Best match found so far */
46836 int bestmatch = 0;
46839 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
46840 if( nArg<-1 ) nArg = -1;
46842 pFirst = (FuncDef*)sqlite3HashFind(&db->aFunc, zName, nName);
46843 for(p=pFirst; p; p=p->pNext){
46844 /* During the search for the best function definition, bestmatch is set
46845 ** as follows to indicate the quality of the match with the definition
46846 ** pointed to by pBest:
46848 ** 0: pBest is NULL. No match has been found.
46849 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
46850 ** encoding is requested, or vice versa.
46851 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
46852 ** requested, or vice versa.
46853 ** 3: A variable arguments function using the same text encoding.
46854 ** 4: A function with the exact number of arguments requested that
46855 ** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
46856 ** 5: A function with the exact number of arguments requested that
46857 ** prefers UTF-16LE when UTF-16BE is requested, or vice versa.
46858 ** 6: An exact match.
46860 ** A larger value of 'matchqual' indicates a more desirable match.
46862 if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){
46863 int match = 1; /* Quality of this match */
46864 if( p->nArg==nArg || nArg==-1 ){
46865 match = 4;
46867 if( enc==p->iPrefEnc ){
46868 match += 2;
46870 else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
46871 (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
46872 match += 1;
46875 if( match>bestmatch ){
46876 pBest = p;
46877 bestmatch = match;
46882 /* If the createFlag parameter is true, and the seach did not reveal an
46883 ** exact match for the name, number of arguments and encoding, then add a
46884 ** new entry to the hash table and return it.
46886 if( createFlag && bestmatch<6 &&
46887 (pBest = sqliteMalloc(sizeof(*pBest)+nName))!=0 ){
46888 pBest->nArg = nArg;
46889 pBest->pNext = pFirst;
46890 pBest->iPrefEnc = enc;
46891 memcpy(pBest->zName, zName, nName);
46892 pBest->zName[nName] = 0;
46893 if( pBest==sqlite3HashInsert(&db->aFunc,pBest->zName,nName,(void*)pBest) ){
46894 sqliteFree(pBest);
46895 return 0;
46899 if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
46900 return pBest;
46902 return 0;
46906 ** Free all resources held by the schema structure. The void* argument points
46907 ** at a Schema struct. This function does not call sqliteFree() on the
46908 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
46909 ** of the schema hash tables).
46911 static void sqlite3SchemaFree(void *p){
46912 Hash temp1;
46913 Hash temp2;
46914 HashElem *pElem;
46915 Schema *pSchema = (Schema *)p;
46917 temp1 = pSchema->tblHash;
46918 temp2 = pSchema->trigHash;
46919 sqlite3HashInit(&pSchema->trigHash, SQLITE_HASH_STRING, 0);
46920 sqlite3HashClear(&pSchema->aFKey);
46921 sqlite3HashClear(&pSchema->idxHash);
46922 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
46923 sqlite3DeleteTrigger((Trigger*)sqliteHashData(pElem));
46925 sqlite3HashClear(&temp2);
46926 sqlite3HashInit(&pSchema->tblHash, SQLITE_HASH_STRING, 0);
46927 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
46928 Table *pTab = sqliteHashData(pElem);
46929 sqlite3DeleteTable(pTab);
46931 sqlite3HashClear(&temp1);
46932 pSchema->pSeqTab = 0;
46933 pSchema->flags &= ~DB_SchemaLoaded;
46937 ** Find and return the schema associated with a BTree. Create
46938 ** a new one if necessary.
46940 static Schema *sqlite3SchemaGet(Btree *pBt){
46941 Schema * p;
46942 if( pBt ){
46943 p = (Schema *)sqlite3BtreeSchema(pBt,sizeof(Schema),sqlite3SchemaFree);
46944 }else{
46945 p = (Schema *)sqliteMalloc(sizeof(Schema));
46947 if( p && 0==p->file_format ){
46948 sqlite3HashInit(&p->tblHash, SQLITE_HASH_STRING, 0);
46949 sqlite3HashInit(&p->idxHash, SQLITE_HASH_STRING, 0);
46950 sqlite3HashInit(&p->trigHash, SQLITE_HASH_STRING, 0);
46951 sqlite3HashInit(&p->aFKey, SQLITE_HASH_STRING, 1);
46952 p->enc = SQLITE_UTF8;
46954 return p;
46957 /************** End of callback.c ********************************************/
46958 /************** Begin file complete.c ****************************************/
46960 ** 2001 September 15
46962 ** The author disclaims copyright to this source code. In place of
46963 ** a legal notice, here is a blessing:
46965 ** May you do good and not evil.
46966 ** May you find forgiveness for yourself and forgive others.
46967 ** May you share freely, never taking more than you give.
46969 *************************************************************************
46970 ** An tokenizer for SQL
46972 ** This file contains C code that implements the sqlite3_complete() API.
46973 ** This code used to be part of the tokenizer.c source file. But by
46974 ** separating it out, the code will be automatically omitted from
46975 ** static links that do not use it.
46977 ** $Id: complete.c,v 1.3 2006/01/18 15:25:17 danielk1977 Exp $
46979 #ifndef SQLITE_OMIT_COMPLETE
46982 ** This is defined in tokenize.c. We just have to import the definition.
46984 extern const char sqlite3IsIdChar[];
46985 #define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsIdChar[c-0x20]))
46989 ** Token types used by the sqlite3_complete() routine. See the header
46990 ** comments on that procedure for additional information.
46992 #define tkSEMI 0
46993 #define tkWS 1
46994 #define tkOTHER 2
46995 #define tkEXPLAIN 3
46996 #define tkCREATE 4
46997 #define tkTEMP 5
46998 #define tkTRIGGER 6
46999 #define tkEND 7
47002 ** Return TRUE if the given SQL string ends in a semicolon.
47004 ** Special handling is require for CREATE TRIGGER statements.
47005 ** Whenever the CREATE TRIGGER keywords are seen, the statement
47006 ** must end with ";END;".
47008 ** This implementation uses a state machine with 7 states:
47010 ** (0) START At the beginning or end of an SQL statement. This routine
47011 ** returns 1 if it ends in the START state and 0 if it ends
47012 ** in any other state.
47014 ** (1) NORMAL We are in the middle of statement which ends with a single
47015 ** semicolon.
47017 ** (2) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
47018 ** a statement.
47020 ** (3) CREATE The keyword CREATE has been seen at the beginning of a
47021 ** statement, possibly preceeded by EXPLAIN and/or followed by
47022 ** TEMP or TEMPORARY
47024 ** (4) TRIGGER We are in the middle of a trigger definition that must be
47025 ** ended by a semicolon, the keyword END, and another semicolon.
47027 ** (5) SEMI We've seen the first semicolon in the ";END;" that occurs at
47028 ** the end of a trigger definition.
47030 ** (6) END We've seen the ";END" of the ";END;" that occurs at the end
47031 ** of a trigger difinition.
47033 ** Transitions between states above are determined by tokens extracted
47034 ** from the input. The following tokens are significant:
47036 ** (0) tkSEMI A semicolon.
47037 ** (1) tkWS Whitespace
47038 ** (2) tkOTHER Any other SQL token.
47039 ** (3) tkEXPLAIN The "explain" keyword.
47040 ** (4) tkCREATE The "create" keyword.
47041 ** (5) tkTEMP The "temp" or "temporary" keyword.
47042 ** (6) tkTRIGGER The "trigger" keyword.
47043 ** (7) tkEND The "end" keyword.
47045 ** Whitespace never causes a state transition and is always ignored.
47047 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
47048 ** to recognize the end of a trigger can be omitted. All we have to do
47049 ** is look for a semicolon that is not part of an string or comment.
47051 int sqlite3_complete(const char *zSql){
47052 u8 state = 0; /* Current state, using numbers defined in header comment */
47053 u8 token; /* Value of the next token */
47055 #ifndef SQLITE_OMIT_TRIGGER
47056 /* A complex statement machine used to detect the end of a CREATE TRIGGER
47057 ** statement. This is the normal case.
47059 static const u8 trans[7][8] = {
47060 /* Token: */
47061 /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
47062 /* 0 START: */ { 0, 0, 1, 2, 3, 1, 1, 1, },
47063 /* 1 NORMAL: */ { 0, 1, 1, 1, 1, 1, 1, 1, },
47064 /* 2 EXPLAIN: */ { 0, 2, 1, 1, 3, 1, 1, 1, },
47065 /* 3 CREATE: */ { 0, 3, 1, 1, 1, 3, 4, 1, },
47066 /* 4 TRIGGER: */ { 5, 4, 4, 4, 4, 4, 4, 4, },
47067 /* 5 SEMI: */ { 5, 5, 4, 4, 4, 4, 4, 6, },
47068 /* 6 END: */ { 0, 6, 4, 4, 4, 4, 4, 4, },
47070 #else
47071 /* If triggers are not suppored by this compile then the statement machine
47072 ** used to detect the end of a statement is much simplier
47074 static const u8 trans[2][3] = {
47075 /* Token: */
47076 /* State: ** SEMI WS OTHER */
47077 /* 0 START: */ { 0, 0, 1, },
47078 /* 1 NORMAL: */ { 0, 1, 1, },
47080 #endif /* SQLITE_OMIT_TRIGGER */
47082 while( *zSql ){
47083 switch( *zSql ){
47084 case ';': { /* A semicolon */
47085 token = tkSEMI;
47086 break;
47088 case ' ':
47089 case '\r':
47090 case '\t':
47091 case '\n':
47092 case '\f': { /* White space is ignored */
47093 token = tkWS;
47094 break;
47096 case '/': { /* C-style comments */
47097 if( zSql[1]!='*' ){
47098 token = tkOTHER;
47099 break;
47101 zSql += 2;
47102 while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
47103 if( zSql[0]==0 ) return 0;
47104 zSql++;
47105 token = tkWS;
47106 break;
47108 case '-': { /* SQL-style comments from "--" to end of line */
47109 if( zSql[1]!='-' ){
47110 token = tkOTHER;
47111 break;
47113 while( *zSql && *zSql!='\n' ){ zSql++; }
47114 if( *zSql==0 ) return state==0;
47115 token = tkWS;
47116 break;
47118 case '[': { /* Microsoft-style identifiers in [...] */
47119 zSql++;
47120 while( *zSql && *zSql!=']' ){ zSql++; }
47121 if( *zSql==0 ) return 0;
47122 token = tkOTHER;
47123 break;
47125 case '`': /* Grave-accent quoted symbols used by MySQL */
47126 case '"': /* single- and double-quoted strings */
47127 case '\'': {
47128 int c = *zSql;
47129 zSql++;
47130 while( *zSql && *zSql!=c ){ zSql++; }
47131 if( *zSql==0 ) return 0;
47132 token = tkOTHER;
47133 break;
47135 default: {
47136 int c;
47137 if( IdChar((u8)*zSql) ){
47138 /* Keywords and unquoted identifiers */
47139 int nId;
47140 for(nId=1; IdChar(zSql[nId]); nId++){}
47141 #ifdef SQLITE_OMIT_TRIGGER
47142 token = tkOTHER;
47143 #else
47144 switch( *zSql ){
47145 case 'c': case 'C': {
47146 if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
47147 token = tkCREATE;
47148 }else{
47149 token = tkOTHER;
47151 break;
47153 case 't': case 'T': {
47154 if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
47155 token = tkTRIGGER;
47156 }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
47157 token = tkTEMP;
47158 }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
47159 token = tkTEMP;
47160 }else{
47161 token = tkOTHER;
47163 break;
47165 case 'e': case 'E': {
47166 if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
47167 token = tkEND;
47168 }else
47169 #ifndef SQLITE_OMIT_EXPLAIN
47170 if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
47171 token = tkEXPLAIN;
47172 }else
47173 #endif
47175 token = tkOTHER;
47177 break;
47179 default: {
47180 token = tkOTHER;
47181 break;
47184 #endif /* SQLITE_OMIT_TRIGGER */
47185 zSql += nId-1;
47186 }else{
47187 /* Operators and special symbols */
47188 token = tkOTHER;
47190 break;
47193 state = trans[state][token];
47194 zSql++;
47196 return state==0;
47199 #ifndef SQLITE_OMIT_UTF16
47201 ** This routine is the same as the sqlite3_complete() routine described
47202 ** above, except that the parameter is required to be UTF-16 encoded, not
47203 ** UTF-8.
47205 int sqlite3_complete16(const void *zSql){
47206 sqlite3_value *pVal;
47207 char const *zSql8;
47208 int rc = 0;
47210 pVal = sqlite3ValueNew();
47211 sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
47212 zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
47213 if( zSql8 ){
47214 rc = sqlite3_complete(zSql8);
47216 sqlite3ValueFree(pVal);
47217 return sqlite3ApiExit(0, rc);
47219 #endif /* SQLITE_OMIT_UTF16 */
47220 #endif /* SQLITE_OMIT_COMPLETE */
47222 /************** End of complete.c ********************************************/
47223 /************** Begin file delete.c ******************************************/
47225 ** 2001 September 15
47227 ** The author disclaims copyright to this source code. In place of
47228 ** a legal notice, here is a blessing:
47230 ** May you do good and not evil.
47231 ** May you find forgiveness for yourself and forgive others.
47232 ** May you share freely, never taking more than you give.
47234 *************************************************************************
47235 ** This file contains C code routines that are called by the parser
47236 ** in order to generate code for DELETE FROM statements.
47238 ** $Id: delete.c,v 1.129 2007/04/16 15:06:25 danielk1977 Exp $
47242 ** Look up every table that is named in pSrc. If any table is not found,
47243 ** add an error message to pParse->zErrMsg and return NULL. If all tables
47244 ** are found, return a pointer to the last table.
47246 static Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
47247 Table *pTab = 0;
47248 int i;
47249 struct SrcList_item *pItem;
47250 for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
47251 pTab = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
47252 sqlite3DeleteTable(pItem->pTab);
47253 pItem->pTab = pTab;
47254 if( pTab ){
47255 pTab->nRef++;
47258 return pTab;
47262 ** Check to make sure the given table is writable. If it is not
47263 ** writable, generate an error message and return 1. If it is
47264 ** writable return 0;
47266 static int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
47267 if( (pTab->readOnly && (pParse->db->flags & SQLITE_WriteSchema)==0
47268 && pParse->nested==0)
47269 #ifndef SQLITE_OMIT_VIRTUALTABLE
47270 || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
47271 #endif
47273 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
47274 return 1;
47276 #ifndef SQLITE_OMIT_VIEW
47277 if( !viewOk && pTab->pSelect ){
47278 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
47279 return 1;
47281 #endif
47282 return 0;
47286 ** Generate code that will open a table for reading.
47288 static void sqlite3OpenTable(
47289 Parse *p, /* Generate code into this VDBE */
47290 int iCur, /* The cursor number of the table */
47291 int iDb, /* The database index in sqlite3.aDb[] */
47292 Table *pTab, /* The table to be opened */
47293 int opcode /* OP_OpenRead or OP_OpenWrite */
47295 Vdbe *v;
47296 if( IsVirtual(pTab) ) return;
47297 v = sqlite3GetVdbe(p);
47298 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
47299 sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), pTab->zName);
47300 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
47301 VdbeComment((v, "# %s", pTab->zName));
47302 sqlite3VdbeAddOp(v, opcode, iCur, pTab->tnum);
47303 sqlite3VdbeAddOp(v, OP_SetNumColumns, iCur, pTab->nCol);
47308 ** Generate code for a DELETE FROM statement.
47310 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
47311 ** \________/ \________________/
47312 ** pTabList pWhere
47314 static void sqlite3DeleteFrom(
47315 Parse *pParse, /* The parser context */
47316 SrcList *pTabList, /* The table from which we should delete things */
47317 Expr *pWhere /* The WHERE clause. May be null */
47319 Vdbe *v; /* The virtual database engine */
47320 Table *pTab; /* The table from which records will be deleted */
47321 const char *zDb; /* Name of database holding pTab */
47322 int end, addr = 0; /* A couple addresses of generated code */
47323 int i; /* Loop counter */
47324 WhereInfo *pWInfo; /* Information about the WHERE clause */
47325 Index *pIdx; /* For looping over indices of the table */
47326 int iCur; /* VDBE Cursor number for pTab */
47327 sqlite3 *db; /* Main database structure */
47328 AuthContext sContext; /* Authorization context */
47329 int oldIdx = -1; /* Cursor for the OLD table of AFTER triggers */
47330 NameContext sNC; /* Name context to resolve expressions in */
47331 int iDb; /* Database number */
47332 int memCnt = 0; /* Memory cell used for change counting */
47334 #ifndef SQLITE_OMIT_TRIGGER
47335 int isView; /* True if attempting to delete from a view */
47336 int triggers_exist = 0; /* True if any triggers exist */
47337 #endif
47339 sContext.pParse = 0;
47340 if( pParse->nErr || sqlite3MallocFailed() ){
47341 goto delete_from_cleanup;
47343 db = pParse->db;
47344 assert( pTabList->nSrc==1 );
47346 /* Locate the table which we want to delete. This table has to be
47347 ** put in an SrcList structure because some of the subroutines we
47348 ** will be calling are designed to work with multiple tables and expect
47349 ** an SrcList* parameter instead of just a Table* parameter.
47351 pTab = sqlite3SrcListLookup(pParse, pTabList);
47352 if( pTab==0 ) goto delete_from_cleanup;
47354 /* Figure out if we have any triggers and if the table being
47355 ** deleted from is a view
47357 #ifndef SQLITE_OMIT_TRIGGER
47358 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0);
47359 isView = pTab->pSelect!=0;
47360 #else
47361 # define triggers_exist 0
47362 # define isView 0
47363 #endif
47364 #ifdef SQLITE_OMIT_VIEW
47365 # undef isView
47366 # define isView 0
47367 #endif
47369 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
47370 goto delete_from_cleanup;
47372 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
47373 assert( iDb<db->nDb );
47374 zDb = db->aDb[iDb].zName;
47375 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
47376 goto delete_from_cleanup;
47379 /* If pTab is really a view, make sure it has been initialized.
47381 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
47382 goto delete_from_cleanup;
47385 /* Allocate a cursor used to store the old.* data for a trigger.
47387 if( triggers_exist ){
47388 oldIdx = pParse->nTab++;
47391 /* Resolve the column names in the WHERE clause.
47393 assert( pTabList->nSrc==1 );
47394 iCur = pTabList->a[0].iCursor = pParse->nTab++;
47395 memset(&sNC, 0, sizeof(sNC));
47396 sNC.pParse = pParse;
47397 sNC.pSrcList = pTabList;
47398 if( sqlite3ExprResolveNames(&sNC, pWhere) ){
47399 goto delete_from_cleanup;
47402 /* Start the view context
47404 if( isView ){
47405 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
47408 /* Begin generating code.
47410 v = sqlite3GetVdbe(pParse);
47411 if( v==0 ){
47412 goto delete_from_cleanup;
47414 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
47415 sqlite3BeginWriteOperation(pParse, triggers_exist, iDb);
47417 /* If we are trying to delete from a view, realize that view into
47418 ** a ephemeral table.
47420 if( isView ){
47421 Select *pView = sqlite3SelectDup(pTab->pSelect);
47422 sqlite3Select(pParse, pView, SRT_EphemTab, iCur, 0, 0, 0, 0);
47423 sqlite3SelectDelete(pView);
47426 /* Initialize the counter of the number of rows deleted, if
47427 ** we are counting rows.
47429 if( db->flags & SQLITE_CountRows ){
47430 memCnt = pParse->nMem++;
47431 sqlite3VdbeAddOp(v, OP_MemInt, 0, memCnt);
47434 /* Special case: A DELETE without a WHERE clause deletes everything.
47435 ** It is easier just to erase the whole table. Note, however, that
47436 ** this means that the row change count will be incorrect.
47438 if( pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){
47439 if( db->flags & SQLITE_CountRows ){
47440 /* If counting rows deleted, just count the total number of
47441 ** entries in the table. */
47442 int endOfLoop = sqlite3VdbeMakeLabel(v);
47443 int addr2;
47444 if( !isView ){
47445 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
47447 sqlite3VdbeAddOp(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2);
47448 addr2 = sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt);
47449 sqlite3VdbeAddOp(v, OP_Next, iCur, addr2);
47450 sqlite3VdbeResolveLabel(v, endOfLoop);
47451 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
47453 if( !isView ){
47454 sqlite3VdbeAddOp(v, OP_Clear, pTab->tnum, iDb);
47455 if( !pParse->nested ){
47456 sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
47458 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
47459 assert( pIdx->pSchema==pTab->pSchema );
47460 sqlite3VdbeAddOp(v, OP_Clear, pIdx->tnum, iDb);
47464 /* The usual case: There is a WHERE clause so we have to scan through
47465 ** the table and pick which records to delete.
47467 else{
47468 /* Begin the database scan
47470 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
47471 if( pWInfo==0 ) goto delete_from_cleanup;
47473 /* Remember the rowid of every item to be deleted.
47475 sqlite3VdbeAddOp(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, 0);
47476 sqlite3VdbeAddOp(v, OP_FifoWrite, 0, 0);
47477 if( db->flags & SQLITE_CountRows ){
47478 sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt);
47481 /* End the database scan loop.
47483 sqlite3WhereEnd(pWInfo);
47485 /* Open the pseudo-table used to store OLD if there are triggers.
47487 if( triggers_exist ){
47488 sqlite3VdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
47489 sqlite3VdbeAddOp(v, OP_SetNumColumns, oldIdx, pTab->nCol);
47492 /* Delete every item whose key was written to the list during the
47493 ** database scan. We have to delete items after the scan is complete
47494 ** because deleting an item can change the scan order.
47496 end = sqlite3VdbeMakeLabel(v);
47498 /* This is the beginning of the delete loop when there are
47499 ** row triggers.
47501 if( triggers_exist ){
47502 addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, end);
47503 if( !isView ){
47504 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
47505 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
47507 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
47508 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
47509 sqlite3VdbeAddOp(v, OP_RowData, iCur, 0);
47510 sqlite3VdbeAddOp(v, OP_Insert, oldIdx, 0);
47511 if( !isView ){
47512 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
47515 (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
47516 -1, oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
47517 addr);
47520 if( !isView ){
47521 /* Open cursors for the table we are deleting from and all its
47522 ** indices. If there are row triggers, this happens inside the
47523 ** OP_FifoRead loop because the cursor have to all be closed
47524 ** before the trigger fires. If there are no row triggers, the
47525 ** cursors are opened only once on the outside the loop.
47527 sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
47529 /* This is the beginning of the delete loop when there are no
47530 ** row triggers */
47531 if( !triggers_exist ){
47532 addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, end);
47535 /* Delete the row */
47536 #ifndef SQLITE_OMIT_VIRTUALTABLE
47537 if( IsVirtual(pTab) ){
47538 pParse->pVirtualLock = pTab;
47539 sqlite3VdbeOp3(v, OP_VUpdate, 0, 1, (const char*)pTab->pVtab, P3_VTAB);
47540 }else
47541 #endif
47543 sqlite3GenerateRowDelete(db, v, pTab, iCur, pParse->nested==0);
47547 /* If there are row triggers, close all cursors then invoke
47548 ** the AFTER triggers
47550 if( triggers_exist ){
47551 if( !isView ){
47552 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
47553 sqlite3VdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
47555 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
47557 (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
47558 oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
47559 addr);
47562 /* End of the delete loop */
47563 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
47564 sqlite3VdbeResolveLabel(v, end);
47566 /* Close the cursors after the loop if there are no row triggers */
47567 if( !triggers_exist && !IsVirtual(pTab) ){
47568 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
47569 sqlite3VdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
47571 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
47576 ** Return the number of rows that were deleted. If this routine is
47577 ** generating code because of a call to sqlite3NestedParse(), do not
47578 ** invoke the callback function.
47580 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
47581 sqlite3VdbeAddOp(v, OP_MemLoad, memCnt, 0);
47582 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
47583 sqlite3VdbeSetNumCols(v, 1);
47584 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P3_STATIC);
47587 delete_from_cleanup:
47588 sqlite3AuthContextPop(&sContext);
47589 sqlite3SrcListDelete(pTabList);
47590 sqlite3ExprDelete(pWhere);
47591 return;
47595 ** This routine generates VDBE code that causes a single row of a
47596 ** single table to be deleted.
47598 ** The VDBE must be in a particular state when this routine is called.
47599 ** These are the requirements:
47601 ** 1. A read/write cursor pointing to pTab, the table containing the row
47602 ** to be deleted, must be opened as cursor number "base".
47604 ** 2. Read/write cursors for all indices of pTab must be open as
47605 ** cursor number base+i for the i-th index.
47607 ** 3. The record number of the row to be deleted must be on the top
47608 ** of the stack.
47610 ** This routine pops the top of the stack to remove the record number
47611 ** and then generates code to remove both the table record and all index
47612 ** entries that point to that record.
47614 static void sqlite3GenerateRowDelete(
47615 sqlite3 *db, /* The database containing the index */
47616 Vdbe *v, /* Generate code into this VDBE */
47617 Table *pTab, /* Table containing the row to be deleted */
47618 int iCur, /* Cursor number for the table */
47619 int count /* Increment the row change counter */
47621 int addr;
47622 addr = sqlite3VdbeAddOp(v, OP_NotExists, iCur, 0);
47623 sqlite3GenerateRowIndexDelete(v, pTab, iCur, 0);
47624 sqlite3VdbeAddOp(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
47625 if( count ){
47626 sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
47628 sqlite3VdbeJumpHere(v, addr);
47632 ** This routine generates VDBE code that causes the deletion of all
47633 ** index entries associated with a single row of a single table.
47635 ** The VDBE must be in a particular state when this routine is called.
47636 ** These are the requirements:
47638 ** 1. A read/write cursor pointing to pTab, the table containing the row
47639 ** to be deleted, must be opened as cursor number "iCur".
47641 ** 2. Read/write cursors for all indices of pTab must be open as
47642 ** cursor number iCur+i for the i-th index.
47644 ** 3. The "iCur" cursor must be pointing to the row that is to be
47645 ** deleted.
47647 static void sqlite3GenerateRowIndexDelete(
47648 Vdbe *v, /* Generate code into this VDBE */
47649 Table *pTab, /* Table containing the row to be deleted */
47650 int iCur, /* Cursor number for the table */
47651 char *aIdxUsed /* Only delete if aIdxUsed!=0 && aIdxUsed[i]!=0 */
47653 int i;
47654 Index *pIdx;
47656 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
47657 if( aIdxUsed!=0 && aIdxUsed[i-1]==0 ) continue;
47658 sqlite3GenerateIndexKey(v, pIdx, iCur);
47659 sqlite3VdbeAddOp(v, OP_IdxDelete, iCur+i, 0);
47664 ** Generate code that will assemble an index key and put it on the top
47665 ** of the tack. The key with be for index pIdx which is an index on pTab.
47666 ** iCur is the index of a cursor open on the pTab table and pointing to
47667 ** the entry that needs indexing.
47669 static void sqlite3GenerateIndexKey(
47670 Vdbe *v, /* Generate code into this VDBE */
47671 Index *pIdx, /* The index for which to generate a key */
47672 int iCur /* Cursor number for the pIdx->pTable table */
47674 int j;
47675 Table *pTab = pIdx->pTable;
47677 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
47678 for(j=0; j<pIdx->nColumn; j++){
47679 int idx = pIdx->aiColumn[j];
47680 if( idx==pTab->iPKey ){
47681 sqlite3VdbeAddOp(v, OP_Dup, j, 0);
47682 }else{
47683 sqlite3VdbeAddOp(v, OP_Column, iCur, idx);
47684 sqlite3ColumnDefault(v, pTab, idx);
47687 sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
47688 sqlite3IndexAffinityStr(v, pIdx);
47691 /************** End of delete.c **********************************************/
47692 /************** Begin file func.c ********************************************/
47694 ** 2002 February 23
47696 ** The author disclaims copyright to this source code. In place of
47697 ** a legal notice, here is a blessing:
47699 ** May you do good and not evil.
47700 ** May you find forgiveness for yourself and forgive others.
47701 ** May you share freely, never taking more than you give.
47703 *************************************************************************
47704 ** This file contains the C functions that implement various SQL
47705 ** functions of SQLite.
47707 ** There is only one exported symbol in this file - the function
47708 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
47709 ** All other code has file scope.
47711 ** $Id: func.c,v 1.160 2007/06/07 19:08:33 drh Exp $
47713 /* #include <math.h> */
47716 ** Return the collating function associated with a function.
47718 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
47719 return context->pColl;
47723 ** Implementation of the non-aggregate min() and max() functions
47725 static void minmaxFunc(
47726 sqlite3_context *context,
47727 int argc,
47728 sqlite3_value **argv
47730 int i;
47731 int mask; /* 0 for min() or 0xffffffff for max() */
47732 int iBest;
47733 CollSeq *pColl;
47735 if( argc==0 ) return;
47736 mask = sqlite3_user_data(context)==0 ? 0 : -1;
47737 pColl = sqlite3GetFuncCollSeq(context);
47738 assert( pColl );
47739 assert( mask==-1 || mask==0 );
47740 iBest = 0;
47741 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
47742 for(i=1; i<argc; i++){
47743 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
47744 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
47745 iBest = i;
47748 sqlite3_result_value(context, argv[iBest]);
47752 ** Return the type of the argument.
47754 static void typeofFunc(
47755 sqlite3_context *context,
47756 int argc,
47757 sqlite3_value **argv
47759 const char *z = 0;
47760 switch( sqlite3_value_type(argv[0]) ){
47761 case SQLITE_NULL: z = "null"; break;
47762 case SQLITE_INTEGER: z = "integer"; break;
47763 case SQLITE_TEXT: z = "text"; break;
47764 case SQLITE_FLOAT: z = "real"; break;
47765 case SQLITE_BLOB: z = "blob"; break;
47767 sqlite3_result_text(context, z, -1, SQLITE_STATIC);
47772 ** Implementation of the length() function
47774 static void lengthFunc(
47775 sqlite3_context *context,
47776 int argc,
47777 sqlite3_value **argv
47779 int len;
47781 assert( argc==1 );
47782 switch( sqlite3_value_type(argv[0]) ){
47783 case SQLITE_BLOB:
47784 case SQLITE_INTEGER:
47785 case SQLITE_FLOAT: {
47786 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
47787 break;
47789 case SQLITE_TEXT: {
47790 const unsigned char *z = sqlite3_value_text(argv[0]);
47791 if( z==0 ) return;
47792 len = 0;
47793 while( *z ){
47794 len++;
47795 SQLITE_SKIP_UTF8(z);
47797 sqlite3_result_int(context, len);
47798 break;
47800 default: {
47801 sqlite3_result_null(context);
47802 break;
47808 ** Implementation of the abs() function
47810 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
47811 assert( argc==1 );
47812 switch( sqlite3_value_type(argv[0]) ){
47813 case SQLITE_INTEGER: {
47814 i64 iVal = sqlite3_value_int64(argv[0]);
47815 if( iVal<0 ){
47816 if( (iVal<<1)==0 ){
47817 sqlite3_result_error(context, "integer overflow", -1);
47818 return;
47820 iVal = -iVal;
47822 sqlite3_result_int64(context, iVal);
47823 break;
47825 case SQLITE_NULL: {
47826 sqlite3_result_null(context);
47827 break;
47829 default: {
47830 double rVal = sqlite3_value_double(argv[0]);
47831 if( rVal<0 ) rVal = -rVal;
47832 sqlite3_result_double(context, rVal);
47833 break;
47839 ** Implementation of the substr() function.
47841 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
47842 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
47843 ** of x. If x is text, then we actually count UTF-8 characters.
47844 ** If x is a blob, then we count bytes.
47846 ** If p1 is negative, then we begin abs(p1) from the end of x[].
47848 static void substrFunc(
47849 sqlite3_context *context,
47850 int argc,
47851 sqlite3_value **argv
47853 const unsigned char *z;
47854 const unsigned char *z2;
47855 int len;
47856 int p0type;
47857 i64 p1, p2;
47859 assert( argc==3 );
47860 p0type = sqlite3_value_type(argv[0]);
47861 if( p0type==SQLITE_BLOB ){
47862 len = sqlite3_value_bytes(argv[0]);
47863 z = sqlite3_value_blob(argv[0]);
47864 if( z==0 ) return;
47865 assert( len==sqlite3_value_bytes(argv[0]) );
47866 }else{
47867 z = sqlite3_value_text(argv[0]);
47868 if( z==0 ) return;
47869 len = 0;
47870 for(z2=z; *z2; len++){
47871 SQLITE_SKIP_UTF8(z2);
47874 p1 = sqlite3_value_int(argv[1]);
47875 p2 = sqlite3_value_int(argv[2]);
47876 if( p1<0 ){
47877 p1 += len;
47878 if( p1<0 ){
47879 p2 += p1;
47880 p1 = 0;
47882 }else if( p1>0 ){
47883 p1--;
47885 if( p1+p2>len ){
47886 p2 = len-p1;
47888 if( p0type!=SQLITE_BLOB ){
47889 while( *z && p1 ){
47890 SQLITE_SKIP_UTF8(z);
47891 p1--;
47893 for(z2=z; *z2 && p2; p2--){
47894 SQLITE_SKIP_UTF8(z2);
47896 sqlite3_result_text(context, (char*)z, z2-z, SQLITE_TRANSIENT);
47897 }else{
47898 if( p2<0 ) p2 = 0;
47899 sqlite3_result_blob(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
47904 ** Implementation of the round() function
47906 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
47907 int n = 0;
47908 double r;
47909 char zBuf[500]; /* larger than the %f representation of the largest double */
47910 assert( argc==1 || argc==2 );
47911 if( argc==2 ){
47912 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
47913 n = sqlite3_value_int(argv[1]);
47914 if( n>30 ) n = 30;
47915 if( n<0 ) n = 0;
47917 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
47918 r = sqlite3_value_double(argv[0]);
47919 sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
47920 sqlite3AtoF(zBuf, &r);
47921 sqlite3_result_double(context, r);
47925 ** Implementation of the upper() and lower() SQL functions.
47927 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
47928 char *z1;
47929 const char *z2;
47930 int i, n;
47931 if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
47932 z2 = (char*)sqlite3_value_text(argv[0]);
47933 n = sqlite3_value_bytes(argv[0]);
47934 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
47935 assert( z2==(char*)sqlite3_value_text(argv[0]) );
47936 if( z2 ){
47937 z1 = sqlite3_malloc(n+1);
47938 if( z1 ){
47939 memcpy(z1, z2, n+1);
47940 for(i=0; z1[i]; i++){
47941 z1[i] = toupper(z1[i]);
47943 sqlite3_result_text(context, z1, -1, sqlite3_free);
47947 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
47948 char *z1;
47949 const char *z2;
47950 int i, n;
47951 if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
47952 z2 = (char*)sqlite3_value_text(argv[0]);
47953 n = sqlite3_value_bytes(argv[0]);
47954 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
47955 assert( z2==(char*)sqlite3_value_text(argv[0]) );
47956 if( z2 ){
47957 z1 = sqlite3_malloc(n+1);
47958 if( z1 ){
47959 memcpy(z1, z2, n+1);
47960 for(i=0; z1[i]; i++){
47961 z1[i] = tolower(z1[i]);
47963 sqlite3_result_text(context, z1, -1, sqlite3_free);
47969 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
47970 ** All three do the same thing. They return the first non-NULL
47971 ** argument.
47973 static void ifnullFunc(
47974 sqlite3_context *context,
47975 int argc,
47976 sqlite3_value **argv
47978 int i;
47979 for(i=0; i<argc; i++){
47980 if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
47981 sqlite3_result_value(context, argv[i]);
47982 break;
47988 ** Implementation of random(). Return a random integer.
47990 static void randomFunc(
47991 sqlite3_context *context,
47992 int argc,
47993 sqlite3_value **argv
47995 sqlite_int64 r;
47996 sqlite3Randomness(sizeof(r), &r);
47997 if( (r<<1)==0 ) r = 0; /* Prevent 0x8000.... as the result so that we */
47998 /* can always do abs() of the result */
47999 sqlite3_result_int64(context, r);
48003 ** Implementation of randomblob(N). Return a random blob
48004 ** that is N bytes long.
48006 static void randomBlob(
48007 sqlite3_context *context,
48008 int argc,
48009 sqlite3_value **argv
48011 int n;
48012 unsigned char *p;
48013 assert( argc==1 );
48014 n = sqlite3_value_int(argv[0]);
48015 if( n<1 ){
48016 n = 1;
48018 if( n>SQLITE_MAX_LENGTH ){
48019 sqlite3_result_error_toobig(context);
48020 return;
48022 p = sqliteMalloc(n);
48023 if( p ){
48024 sqlite3Randomness(n, p);
48025 sqlite3_result_blob(context, (char*)p, n, sqlite3FreeX);
48030 ** Implementation of the last_insert_rowid() SQL function. The return
48031 ** value is the same as the sqlite3_last_insert_rowid() API function.
48033 static void last_insert_rowid(
48034 sqlite3_context *context,
48035 int arg,
48036 sqlite3_value **argv
48038 sqlite3 *db = sqlite3_user_data(context);
48039 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
48043 ** Implementation of the changes() SQL function. The return value is the
48044 ** same as the sqlite3_changes() API function.
48046 static void changes(
48047 sqlite3_context *context,
48048 int arg,
48049 sqlite3_value **argv
48051 sqlite3 *db = sqlite3_user_data(context);
48052 sqlite3_result_int(context, sqlite3_changes(db));
48056 ** Implementation of the total_changes() SQL function. The return value is
48057 ** the same as the sqlite3_total_changes() API function.
48059 static void total_changes(
48060 sqlite3_context *context,
48061 int arg,
48062 sqlite3_value **argv
48064 sqlite3 *db = sqlite3_user_data(context);
48065 sqlite3_result_int(context, sqlite3_total_changes(db));
48069 ** A structure defining how to do GLOB-style comparisons.
48071 struct compareInfo {
48072 u8 matchAll;
48073 u8 matchOne;
48074 u8 matchSet;
48075 u8 noCase;
48078 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
48079 /* The correct SQL-92 behavior is for the LIKE operator to ignore
48080 ** case. Thus 'a' LIKE 'A' would be true. */
48081 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
48082 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
48083 ** is case sensitive causing 'a' LIKE 'A' to be false */
48084 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
48087 ** Read a single UTF-8 character and return its value.
48089 static u32 sqlite3ReadUtf8(const unsigned char *z){
48090 u32 c;
48091 SQLITE_READ_UTF8(z, c);
48092 return c;
48096 ** Compare two UTF-8 strings for equality where the first string can
48097 ** potentially be a "glob" expression. Return true (1) if they
48098 ** are the same and false (0) if they are different.
48100 ** Globbing rules:
48102 ** '*' Matches any sequence of zero or more characters.
48104 ** '?' Matches exactly one character.
48106 ** [...] Matches one character from the enclosed list of
48107 ** characters.
48109 ** [^...] Matches one character not in the enclosed list.
48111 ** With the [...] and [^...] matching, a ']' character can be included
48112 ** in the list by making it the first character after '[' or '^'. A
48113 ** range of characters can be specified using '-'. Example:
48114 ** "[a-z]" matches any single lower-case letter. To match a '-', make
48115 ** it the last character in the list.
48117 ** This routine is usually quick, but can be N**2 in the worst case.
48119 ** Hints: to match '*' or '?', put them in "[]". Like this:
48121 ** abc[*]xyz Matches "abc*xyz" only
48123 static int patternCompare(
48124 const u8 *zPattern, /* The glob pattern */
48125 const u8 *zString, /* The string to compare against the glob */
48126 const struct compareInfo *pInfo, /* Information about how to do the compare */
48127 const int esc /* The escape character */
48129 register int c;
48130 int invert;
48131 int seen;
48132 int c2;
48133 u8 matchOne = pInfo->matchOne;
48134 u8 matchAll = pInfo->matchAll;
48135 u8 matchSet = pInfo->matchSet;
48136 u8 noCase = pInfo->noCase;
48137 int prevEscape = 0; /* True if the previous character was 'escape' */
48139 while( (c = *zPattern)!=0 ){
48140 if( !prevEscape && c==matchAll ){
48141 while( (c=zPattern[1]) == matchAll || c == matchOne ){
48142 if( c==matchOne ){
48143 if( *zString==0 ) return 0;
48144 SQLITE_SKIP_UTF8(zString);
48146 zPattern++;
48148 if( c && esc && sqlite3ReadUtf8(&zPattern[1])==esc ){
48149 u8 const *zTemp = &zPattern[1];
48150 SQLITE_SKIP_UTF8(zTemp);
48151 c = *zTemp;
48153 if( c==0 ) return 1;
48154 if( c==matchSet ){
48155 assert( esc==0 ); /* This is GLOB, not LIKE */
48156 while( *zString && patternCompare(&zPattern[1],zString,pInfo,esc)==0 ){
48157 SQLITE_SKIP_UTF8(zString);
48159 return *zString!=0;
48160 }else{
48161 while( (c2 = *zString)!=0 ){
48162 if( noCase ){
48163 c2 = sqlite3UpperToLower[c2];
48164 c = sqlite3UpperToLower[c];
48165 while( c2 != 0 && c2 != c ){ c2 = sqlite3UpperToLower[*++zString]; }
48166 }else{
48167 while( c2 != 0 && c2 != c ){ c2 = *++zString; }
48169 if( c2==0 ) return 0;
48170 if( patternCompare(&zPattern[1],zString,pInfo,esc) ) return 1;
48171 SQLITE_SKIP_UTF8(zString);
48173 return 0;
48175 }else if( !prevEscape && c==matchOne ){
48176 if( *zString==0 ) return 0;
48177 SQLITE_SKIP_UTF8(zString);
48178 zPattern++;
48179 }else if( c==matchSet ){
48180 int prior_c = 0;
48181 assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
48182 seen = 0;
48183 invert = 0;
48184 c = sqlite3ReadUtf8(zString);
48185 if( c==0 ) return 0;
48186 c2 = *++zPattern;
48187 if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
48188 if( c2==']' ){
48189 if( c==']' ) seen = 1;
48190 c2 = *++zPattern;
48192 while( (c2 = sqlite3ReadUtf8(zPattern))!=0 && c2!=']' ){
48193 if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
48194 zPattern++;
48195 c2 = sqlite3ReadUtf8(zPattern);
48196 if( c>=prior_c && c<=c2 ) seen = 1;
48197 prior_c = 0;
48198 }else if( c==c2 ){
48199 seen = 1;
48200 prior_c = c2;
48201 }else{
48202 prior_c = c2;
48204 SQLITE_SKIP_UTF8(zPattern);
48206 if( c2==0 || (seen ^ invert)==0 ) return 0;
48207 SQLITE_SKIP_UTF8(zString);
48208 zPattern++;
48209 }else if( esc && !prevEscape && sqlite3ReadUtf8(zPattern)==esc){
48210 prevEscape = 1;
48211 SQLITE_SKIP_UTF8(zPattern);
48212 }else{
48213 if( noCase ){
48214 if( sqlite3UpperToLower[c] != sqlite3UpperToLower[*zString] ) return 0;
48215 }else{
48216 if( c != *zString ) return 0;
48218 zPattern++;
48219 zString++;
48220 prevEscape = 0;
48223 return *zString==0;
48227 ** Count the number of times that the LIKE operator (or GLOB which is
48228 ** just a variation of LIKE) gets called. This is used for testing
48229 ** only.
48231 #ifdef SQLITE_TEST
48232 int sqlite3_like_count = 0;
48233 #endif
48237 ** Implementation of the like() SQL function. This function implements
48238 ** the build-in LIKE operator. The first argument to the function is the
48239 ** pattern and the second argument is the string. So, the SQL statements:
48241 ** A LIKE B
48243 ** is implemented as like(B,A).
48245 ** This same function (with a different compareInfo structure) computes
48246 ** the GLOB operator.
48248 static void likeFunc(
48249 sqlite3_context *context,
48250 int argc,
48251 sqlite3_value **argv
48253 const unsigned char *zA, *zB;
48254 int escape = 0;
48256 zB = sqlite3_value_text(argv[0]);
48257 zA = sqlite3_value_text(argv[1]);
48259 /* Limit the length of the LIKE or GLOB pattern to avoid problems
48260 ** of deep recursion and N*N behavior in patternCompare().
48262 if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
48263 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
48264 return;
48266 assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
48268 if( argc==3 ){
48269 /* The escape character string must consist of a single UTF-8 character.
48270 ** Otherwise, return an error.
48272 const unsigned char *zEsc = sqlite3_value_text(argv[2]);
48273 if( zEsc==0 ) return;
48274 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
48275 sqlite3_result_error(context,
48276 "ESCAPE expression must be a single character", -1);
48277 return;
48279 escape = sqlite3ReadUtf8(zEsc);
48281 if( zA && zB ){
48282 struct compareInfo *pInfo = sqlite3_user_data(context);
48283 #ifdef SQLITE_TEST
48284 sqlite3_like_count++;
48285 #endif
48287 sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
48292 ** Implementation of the NULLIF(x,y) function. The result is the first
48293 ** argument if the arguments are different. The result is NULL if the
48294 ** arguments are equal to each other.
48296 static void nullifFunc(
48297 sqlite3_context *context,
48298 int argc,
48299 sqlite3_value **argv
48301 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
48302 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
48303 sqlite3_result_value(context, argv[0]);
48308 ** Implementation of the VERSION(*) function. The result is the version
48309 ** of the SQLite library that is running.
48311 static void versionFunc(
48312 sqlite3_context *context,
48313 int argc,
48314 sqlite3_value **argv
48316 sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
48319 /* Array for converting from half-bytes (nybbles) into ASCII hex
48320 ** digits. */
48321 static const char hexdigits[] = {
48322 '0', '1', '2', '3', '4', '5', '6', '7',
48323 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
48327 ** EXPERIMENTAL - This is not an official function. The interface may
48328 ** change. This function may disappear. Do not write code that depends
48329 ** on this function.
48331 ** Implementation of the QUOTE() function. This function takes a single
48332 ** argument. If the argument is numeric, the return value is the same as
48333 ** the argument. If the argument is NULL, the return value is the string
48334 ** "NULL". Otherwise, the argument is enclosed in single quotes with
48335 ** single-quote escapes.
48337 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
48338 if( argc<1 ) return;
48339 switch( sqlite3_value_type(argv[0]) ){
48340 case SQLITE_NULL: {
48341 sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
48342 break;
48344 case SQLITE_INTEGER:
48345 case SQLITE_FLOAT: {
48346 sqlite3_result_value(context, argv[0]);
48347 break;
48349 case SQLITE_BLOB: {
48350 char *zText = 0;
48351 char const *zBlob = sqlite3_value_blob(argv[0]);
48352 int nBlob = sqlite3_value_bytes(argv[0]);
48353 assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
48355 if( 2*nBlob+4>SQLITE_MAX_LENGTH ){
48356 sqlite3_result_error_toobig(context);
48357 return;
48359 zText = (char *)sqliteMalloc((2*nBlob)+4);
48360 if( !zText ){
48361 sqlite3_result_error(context, "out of memory", -1);
48362 }else{
48363 int i;
48364 for(i=0; i<nBlob; i++){
48365 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
48366 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
48368 zText[(nBlob*2)+2] = '\'';
48369 zText[(nBlob*2)+3] = '\0';
48370 zText[0] = 'X';
48371 zText[1] = '\'';
48372 sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
48373 sqliteFree(zText);
48375 break;
48377 case SQLITE_TEXT: {
48378 int i,j;
48379 u64 n;
48380 const unsigned char *zArg = sqlite3_value_text(argv[0]);
48381 char *z;
48383 if( zArg==0 ) return;
48384 for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
48385 if( i+n+3>SQLITE_MAX_LENGTH ){
48386 sqlite3_result_error_toobig(context);
48387 return;
48389 z = sqliteMalloc( i+n+3 );
48390 if( z==0 ) return;
48391 z[0] = '\'';
48392 for(i=0, j=1; zArg[i]; i++){
48393 z[j++] = zArg[i];
48394 if( zArg[i]=='\'' ){
48395 z[j++] = '\'';
48398 z[j++] = '\'';
48399 z[j] = 0;
48400 sqlite3_result_text(context, z, j, SQLITE_TRANSIENT);
48401 sqliteFree(z);
48407 ** The hex() function. Interpret the argument as a blob. Return
48408 ** a hexadecimal rendering as text.
48410 static void hexFunc(
48411 sqlite3_context *context,
48412 int argc,
48413 sqlite3_value **argv
48415 int i, n;
48416 const unsigned char *pBlob;
48417 char *zHex, *z;
48418 assert( argc==1 );
48419 pBlob = sqlite3_value_blob(argv[0]);
48420 n = sqlite3_value_bytes(argv[0]);
48421 if( n*2+1>SQLITE_MAX_LENGTH ){
48422 sqlite3_result_error_toobig(context);
48423 return;
48425 assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
48426 z = zHex = sqlite3_malloc(n*2 + 1);
48427 if( zHex==0 ) return;
48428 for(i=0; i<n; i++, pBlob++){
48429 unsigned char c = *pBlob;
48430 *(z++) = hexdigits[(c>>4)&0xf];
48431 *(z++) = hexdigits[c&0xf];
48433 *z = 0;
48434 sqlite3_result_text(context, zHex, n*2, sqlite3_free);
48438 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
48440 static void zeroblobFunc(
48441 sqlite3_context *context,
48442 int argc,
48443 sqlite3_value **argv
48445 i64 n;
48446 assert( argc==1 );
48447 n = sqlite3_value_int64(argv[0]);
48448 if( n>SQLITE_MAX_LENGTH ){
48449 sqlite3_result_error_toobig(context);
48450 }else{
48451 sqlite3_result_zeroblob(context, n);
48456 ** The replace() function. Three arguments are all strings: call
48457 ** them A, B, and C. The result is also a string which is derived
48458 ** from A by replacing every occurance of B with C. The match
48459 ** must be exact. Collating sequences are not used.
48461 static void replaceFunc(
48462 sqlite3_context *context,
48463 int argc,
48464 sqlite3_value **argv
48466 const unsigned char *zStr; /* The input string A */
48467 const unsigned char *zPattern; /* The pattern string B */
48468 const unsigned char *zRep; /* The replacement string C */
48469 unsigned char *zOut; /* The output */
48470 int nStr; /* Size of zStr */
48471 int nPattern; /* Size of zPattern */
48472 int nRep; /* Size of zRep */
48473 i64 nOut; /* Maximum size of zOut */
48474 int loopLimit; /* Last zStr[] that might match zPattern[] */
48475 int i, j; /* Loop counters */
48477 assert( argc==3 );
48478 zStr = sqlite3_value_text(argv[0]);
48479 if( zStr==0 ) return;
48480 nStr = sqlite3_value_bytes(argv[0]);
48481 assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
48482 zPattern = sqlite3_value_text(argv[1]);
48483 if( zPattern==0 || zPattern[0]==0 ) return;
48484 nPattern = sqlite3_value_bytes(argv[1]);
48485 assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
48486 zRep = sqlite3_value_text(argv[2]);
48487 if( zRep==0 ) return;
48488 nRep = sqlite3_value_bytes(argv[2]);
48489 assert( zRep==sqlite3_value_text(argv[2]) );
48490 nOut = nStr + 1;
48491 assert( nOut<SQLITE_MAX_LENGTH );
48492 zOut = sqlite3_malloc((int)nOut);
48493 if( zOut==0 ){
48494 return;
48496 loopLimit = nStr - nPattern;
48497 for(i=j=0; i<=loopLimit; i++){
48498 if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
48499 zOut[j++] = zStr[i];
48500 }else{
48501 nOut += nRep - nPattern;
48502 if( nOut>=SQLITE_MAX_LENGTH ){
48503 sqlite3_result_error_toobig(context);
48504 sqlite3_free(zOut);
48505 return;
48507 zOut = sqlite3_realloc(zOut, (int)nOut);
48508 if( zOut==0 ){
48509 return;
48511 memcpy(&zOut[j], zRep, nRep);
48512 j += nRep;
48513 i += nPattern-1;
48516 assert( j+nStr-i+1==nOut );
48517 memcpy(&zOut[j], &zStr[i], nStr-i);
48518 j += nStr - i;
48519 assert( j<=nOut );
48520 zOut[j] = 0;
48521 sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
48525 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
48526 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
48528 static void trimFunc(
48529 sqlite3_context *context,
48530 int argc,
48531 sqlite3_value **argv
48533 const unsigned char *zIn; /* Input string */
48534 const unsigned char *zCharSet; /* Set of characters to trim */
48535 int nIn; /* Number of bytes in input */
48536 int flags; /* 1: trimleft 2: trimright 3: trim */
48537 int i; /* Loop counter */
48538 unsigned char *aLen; /* Length of each character in zCharSet */
48539 const unsigned char **azChar; /* Individual characters in zCharSet */
48540 int nChar; /* Number of characters in zCharSet */
48542 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
48543 return;
48545 zIn = sqlite3_value_text(argv[0]);
48546 if( zIn==0 ) return;
48547 nIn = sqlite3_value_bytes(argv[0]);
48548 assert( zIn==sqlite3_value_text(argv[0]) );
48549 if( argc==1 ){
48550 static const unsigned char lenOne[] = { 1 };
48551 static const unsigned char *azOne[] = { (u8*)" " };
48552 nChar = 1;
48553 aLen = (u8*)lenOne;
48554 azChar = azOne;
48555 zCharSet = 0;
48556 }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
48557 return;
48558 }else{
48559 const unsigned char *z;
48560 for(z=zCharSet, nChar=0; *z; nChar++){
48561 SQLITE_SKIP_UTF8(z);
48563 if( nChar>0 ){
48564 azChar = sqlite3_malloc( nChar*(sizeof(char*)+1) );
48565 if( azChar==0 ){
48566 return;
48568 aLen = (unsigned char*)&azChar[nChar];
48569 for(z=zCharSet, nChar=0; *z; nChar++){
48570 azChar[nChar] = z;
48571 SQLITE_SKIP_UTF8(z);
48572 aLen[nChar] = z - azChar[nChar];
48576 if( nChar>0 ){
48577 flags = (int)sqlite3_user_data(context);
48578 if( flags & 1 ){
48579 while( nIn>0 ){
48580 int len;
48581 for(i=0; i<nChar; i++){
48582 len = aLen[i];
48583 if( memcmp(zIn, azChar[i], len)==0 ) break;
48585 if( i>=nChar ) break;
48586 zIn += len;
48587 nIn -= len;
48590 if( flags & 2 ){
48591 while( nIn>0 ){
48592 int len;
48593 for(i=0; i<nChar; i++){
48594 len = aLen[i];
48595 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
48597 if( i>=nChar ) break;
48598 nIn -= len;
48601 if( zCharSet ){
48602 sqlite3_free(azChar);
48605 sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
48608 #ifdef SQLITE_SOUNDEX
48610 ** Compute the soundex encoding of a word.
48612 static void soundexFunc(
48613 sqlite3_context *context,
48614 int argc,
48615 sqlite3_value **argv
48617 char zResult[8];
48618 const u8 *zIn;
48619 int i, j;
48620 static const unsigned char iCode[] = {
48621 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
48622 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
48623 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
48624 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
48625 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
48626 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
48627 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
48628 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
48630 assert( argc==1 );
48631 zIn = (u8*)sqlite3_value_text(argv[0]);
48632 if( zIn==0 ) zIn = (u8*)"";
48633 for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
48634 if( zIn[i] ){
48635 u8 prevcode = iCode[zIn[i]&0x7f];
48636 zResult[0] = toupper(zIn[i]);
48637 for(j=1; j<4 && zIn[i]; i++){
48638 int code = iCode[zIn[i]&0x7f];
48639 if( code>0 ){
48640 if( code!=prevcode ){
48641 prevcode = code;
48642 zResult[j++] = code + '0';
48644 }else{
48645 prevcode = 0;
48648 while( j<4 ){
48649 zResult[j++] = '0';
48651 zResult[j] = 0;
48652 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
48653 }else{
48654 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
48657 #endif
48659 #ifndef SQLITE_OMIT_LOAD_EXTENSION
48661 ** A function that loads a shared-library extension then returns NULL.
48663 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
48664 const char *zFile = (const char *)sqlite3_value_text(argv[0]);
48665 const char *zProc;
48666 sqlite3 *db = sqlite3_user_data(context);
48667 char *zErrMsg = 0;
48669 if( argc==2 ){
48670 zProc = (const char *)sqlite3_value_text(argv[1]);
48671 }else{
48672 zProc = 0;
48674 if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
48675 sqlite3_result_error(context, zErrMsg, -1);
48676 sqlite3_free(zErrMsg);
48679 #endif
48681 #ifdef SQLITE_TEST
48683 ** This function generates a string of random characters. Used for
48684 ** generating test data.
48686 static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){
48687 static const unsigned char zSrc[] =
48688 "abcdefghijklmnopqrstuvwxyz"
48689 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
48690 "0123456789"
48691 ".-!,:*^+=_|?/<> ";
48692 int iMin, iMax, n, r, i;
48693 unsigned char zBuf[1000];
48694 if( argc>=1 ){
48695 iMin = sqlite3_value_int(argv[0]);
48696 if( iMin<0 ) iMin = 0;
48697 if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
48698 }else{
48699 iMin = 1;
48701 if( argc>=2 ){
48702 iMax = sqlite3_value_int(argv[1]);
48703 if( iMax<iMin ) iMax = iMin;
48704 if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
48705 }else{
48706 iMax = 50;
48708 n = iMin;
48709 if( iMax>iMin ){
48710 sqlite3Randomness(sizeof(r), &r);
48711 r &= 0x7fffffff;
48712 n += r%(iMax + 1 - iMin);
48714 assert( n<sizeof(zBuf) );
48715 sqlite3Randomness(n, zBuf);
48716 for(i=0; i<n; i++){
48717 zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
48719 zBuf[n] = 0;
48720 sqlite3_result_text(context, (char*)zBuf, n, SQLITE_TRANSIENT);
48722 #endif /* SQLITE_TEST */
48724 #ifdef SQLITE_TEST
48726 ** The following two SQL functions are used to test returning a text
48727 ** result with a destructor. Function 'test_destructor' takes one argument
48728 ** and returns the same argument interpreted as TEXT. A destructor is
48729 ** passed with the sqlite3_result_text() call.
48731 ** SQL function 'test_destructor_count' returns the number of outstanding
48732 ** allocations made by 'test_destructor';
48734 ** WARNING: Not threadsafe.
48736 static int test_destructor_count_var = 0;
48737 static void destructor(void *p){
48738 char *zVal = (char *)p;
48739 assert(zVal);
48740 zVal--;
48741 sqliteFree(zVal);
48742 test_destructor_count_var--;
48744 static void test_destructor(
48745 sqlite3_context *pCtx,
48746 int nArg,
48747 sqlite3_value **argv
48749 char *zVal;
48750 int len;
48751 sqlite3 *db = sqlite3_user_data(pCtx);
48753 test_destructor_count_var++;
48754 assert( nArg==1 );
48755 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
48756 len = sqlite3ValueBytes(argv[0], ENC(db));
48757 zVal = sqliteMalloc(len+3);
48758 zVal[len] = 0;
48759 zVal[len-1] = 0;
48760 assert( zVal );
48761 zVal++;
48762 memcpy(zVal, sqlite3ValueText(argv[0], ENC(db)), len);
48763 if( ENC(db)==SQLITE_UTF8 ){
48764 sqlite3_result_text(pCtx, zVal, -1, destructor);
48765 #ifndef SQLITE_OMIT_UTF16
48766 }else if( ENC(db)==SQLITE_UTF16LE ){
48767 sqlite3_result_text16le(pCtx, zVal, -1, destructor);
48768 }else{
48769 sqlite3_result_text16be(pCtx, zVal, -1, destructor);
48770 #endif /* SQLITE_OMIT_UTF16 */
48773 static void test_destructor_count(
48774 sqlite3_context *pCtx,
48775 int nArg,
48776 sqlite3_value **argv
48778 sqlite3_result_int(pCtx, test_destructor_count_var);
48780 #endif /* SQLITE_TEST */
48782 #ifdef SQLITE_TEST
48784 ** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
48785 ** interface.
48787 ** The test_auxdata() SQL function attempts to register each of its arguments
48788 ** as auxiliary data. If there are no prior registrations of aux data for
48789 ** that argument (meaning the argument is not a constant or this is its first
48790 ** call) then the result for that argument is 0. If there is a prior
48791 ** registration, the result for that argument is 1. The overall result
48792 ** is the individual argument results separated by spaces.
48794 static void free_test_auxdata(void *p) {sqliteFree(p);}
48795 static void test_auxdata(
48796 sqlite3_context *pCtx,
48797 int nArg,
48798 sqlite3_value **argv
48800 int i;
48801 char *zRet = sqliteMalloc(nArg*2);
48802 if( !zRet ) return;
48803 for(i=0; i<nArg; i++){
48804 char const *z = (char*)sqlite3_value_text(argv[i]);
48805 if( z ){
48806 char *zAux = sqlite3_get_auxdata(pCtx, i);
48807 if( zAux ){
48808 zRet[i*2] = '1';
48809 if( strcmp(zAux, z) ){
48810 sqlite3_result_error(pCtx, "Auxilary data corruption", -1);
48811 return;
48813 }else{
48814 zRet[i*2] = '0';
48815 zAux = sqliteStrDup(z);
48816 sqlite3_set_auxdata(pCtx, i, zAux, free_test_auxdata);
48818 zRet[i*2+1] = ' ';
48821 sqlite3_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);
48823 #endif /* SQLITE_TEST */
48825 #ifdef SQLITE_TEST
48827 ** A function to test error reporting from user functions. This function
48828 ** returns a copy of it's first argument as an error.
48830 static void test_error(
48831 sqlite3_context *pCtx,
48832 int nArg,
48833 sqlite3_value **argv
48835 sqlite3_result_error(pCtx, (char*)sqlite3_value_text(argv[0]), 0);
48837 #endif /* SQLITE_TEST */
48840 ** An instance of the following structure holds the context of a
48841 ** sum() or avg() aggregate computation.
48843 typedef struct SumCtx SumCtx;
48844 struct SumCtx {
48845 double rSum; /* Floating point sum */
48846 i64 iSum; /* Integer sum */
48847 i64 cnt; /* Number of elements summed */
48848 u8 overflow; /* True if integer overflow seen */
48849 u8 approx; /* True if non-integer value was input to the sum */
48853 ** Routines used to compute the sum, average, and total.
48855 ** The SUM() function follows the (broken) SQL standard which means
48856 ** that it returns NULL if it sums over no inputs. TOTAL returns
48857 ** 0.0 in that case. In addition, TOTAL always returns a float where
48858 ** SUM might return an integer if it never encounters a floating point
48859 ** value. TOTAL never fails, but SUM might through an exception if
48860 ** it overflows an integer.
48862 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
48863 SumCtx *p;
48864 int type;
48865 assert( argc==1 );
48866 p = sqlite3_aggregate_context(context, sizeof(*p));
48867 type = sqlite3_value_numeric_type(argv[0]);
48868 if( p && type!=SQLITE_NULL ){
48869 p->cnt++;
48870 if( type==SQLITE_INTEGER ){
48871 i64 v = sqlite3_value_int64(argv[0]);
48872 p->rSum += v;
48873 if( (p->approx|p->overflow)==0 ){
48874 i64 iNewSum = p->iSum + v;
48875 int s1 = p->iSum >> (sizeof(i64)*8-1);
48876 int s2 = v >> (sizeof(i64)*8-1);
48877 int s3 = iNewSum >> (sizeof(i64)*8-1);
48878 p->overflow = (s1&s2&~s3) | (~s1&~s2&s3);
48879 p->iSum = iNewSum;
48881 }else{
48882 p->rSum += sqlite3_value_double(argv[0]);
48883 p->approx = 1;
48887 static void sumFinalize(sqlite3_context *context){
48888 SumCtx *p;
48889 p = sqlite3_aggregate_context(context, 0);
48890 if( p && p->cnt>0 ){
48891 if( p->overflow ){
48892 sqlite3_result_error(context,"integer overflow",-1);
48893 }else if( p->approx ){
48894 sqlite3_result_double(context, p->rSum);
48895 }else{
48896 sqlite3_result_int64(context, p->iSum);
48900 static void avgFinalize(sqlite3_context *context){
48901 SumCtx *p;
48902 p = sqlite3_aggregate_context(context, 0);
48903 if( p && p->cnt>0 ){
48904 sqlite3_result_double(context, p->rSum/(double)p->cnt);
48907 static void totalFinalize(sqlite3_context *context){
48908 SumCtx *p;
48909 p = sqlite3_aggregate_context(context, 0);
48910 sqlite3_result_double(context, p ? p->rSum : 0.0);
48914 ** The following structure keeps track of state information for the
48915 ** count() aggregate function.
48917 typedef struct CountCtx CountCtx;
48918 struct CountCtx {
48919 i64 n;
48923 ** Routines to implement the count() aggregate function.
48925 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
48926 CountCtx *p;
48927 p = sqlite3_aggregate_context(context, sizeof(*p));
48928 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
48929 p->n++;
48932 static void countFinalize(sqlite3_context *context){
48933 CountCtx *p;
48934 p = sqlite3_aggregate_context(context, 0);
48935 sqlite3_result_int64(context, p ? p->n : 0);
48939 ** Routines to implement min() and max() aggregate functions.
48941 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
48942 Mem *pArg = (Mem *)argv[0];
48943 Mem *pBest;
48945 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
48946 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
48947 if( !pBest ) return;
48949 if( pBest->flags ){
48950 int max;
48951 int cmp;
48952 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
48953 /* This step function is used for both the min() and max() aggregates,
48954 ** the only difference between the two being that the sense of the
48955 ** comparison is inverted. For the max() aggregate, the
48956 ** sqlite3_user_data() function returns (void *)-1. For min() it
48957 ** returns (void *)db, where db is the sqlite3* database pointer.
48958 ** Therefore the next statement sets variable 'max' to 1 for the max()
48959 ** aggregate, or 0 for min().
48961 max = sqlite3_user_data(context)!=0;
48962 cmp = sqlite3MemCompare(pBest, pArg, pColl);
48963 if( (max && cmp<0) || (!max && cmp>0) ){
48964 sqlite3VdbeMemCopy(pBest, pArg);
48966 }else{
48967 sqlite3VdbeMemCopy(pBest, pArg);
48970 static void minMaxFinalize(sqlite3_context *context){
48971 sqlite3_value *pRes;
48972 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
48973 if( pRes ){
48974 if( pRes->flags ){
48975 sqlite3_result_value(context, pRes);
48977 sqlite3VdbeMemRelease(pRes);
48983 ** This function registered all of the above C functions as SQL
48984 ** functions. This should be the only routine in this file with
48985 ** external linkage.
48987 static void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
48988 static const struct {
48989 char *zName;
48990 signed char nArg;
48991 u8 argType; /* ff: db 1: 0, 2: 1, 3: 2,... N: N-1. */
48992 u8 eTextRep; /* 1: UTF-16. 0: UTF-8 */
48993 u8 needCollSeq;
48994 void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
48995 } aFuncs[] = {
48996 { "min", -1, 0, SQLITE_UTF8, 1, minmaxFunc },
48997 { "min", 0, 0, SQLITE_UTF8, 1, 0 },
48998 { "max", -1, 1, SQLITE_UTF8, 1, minmaxFunc },
48999 { "max", 0, 1, SQLITE_UTF8, 1, 0 },
49000 { "typeof", 1, 0, SQLITE_UTF8, 0, typeofFunc },
49001 { "length", 1, 0, SQLITE_UTF8, 0, lengthFunc },
49002 { "substr", 3, 0, SQLITE_UTF8, 0, substrFunc },
49003 { "abs", 1, 0, SQLITE_UTF8, 0, absFunc },
49004 { "round", 1, 0, SQLITE_UTF8, 0, roundFunc },
49005 { "round", 2, 0, SQLITE_UTF8, 0, roundFunc },
49006 { "upper", 1, 0, SQLITE_UTF8, 0, upperFunc },
49007 { "lower", 1, 0, SQLITE_UTF8, 0, lowerFunc },
49008 { "coalesce", -1, 0, SQLITE_UTF8, 0, ifnullFunc },
49009 { "coalesce", 0, 0, SQLITE_UTF8, 0, 0 },
49010 { "coalesce", 1, 0, SQLITE_UTF8, 0, 0 },
49011 { "hex", 1, 0, SQLITE_UTF8, 0, hexFunc },
49012 { "ifnull", 2, 0, SQLITE_UTF8, 1, ifnullFunc },
49013 { "random", -1, 0, SQLITE_UTF8, 0, randomFunc },
49014 { "randomblob", 1, 0, SQLITE_UTF8, 0, randomBlob },
49015 { "nullif", 2, 0, SQLITE_UTF8, 1, nullifFunc },
49016 { "sqlite_version", 0, 0, SQLITE_UTF8, 0, versionFunc},
49017 { "quote", 1, 0, SQLITE_UTF8, 0, quoteFunc },
49018 { "last_insert_rowid", 0, 0xff, SQLITE_UTF8, 0, last_insert_rowid },
49019 { "changes", 0, 0xff, SQLITE_UTF8, 0, changes },
49020 { "total_changes", 0, 0xff, SQLITE_UTF8, 0, total_changes },
49021 { "replace", 3, 0, SQLITE_UTF8, 0, replaceFunc },
49022 { "ltrim", 1, 1, SQLITE_UTF8, 0, trimFunc },
49023 { "ltrim", 2, 1, SQLITE_UTF8, 0, trimFunc },
49024 { "rtrim", 1, 2, SQLITE_UTF8, 0, trimFunc },
49025 { "rtrim", 2, 2, SQLITE_UTF8, 0, trimFunc },
49026 { "trim", 1, 3, SQLITE_UTF8, 0, trimFunc },
49027 { "trim", 2, 3, SQLITE_UTF8, 0, trimFunc },
49028 { "zeroblob", 1, 0, SQLITE_UTF8, 0, zeroblobFunc },
49029 #ifdef SQLITE_SOUNDEX
49030 { "soundex", 1, 0, SQLITE_UTF8, 0, soundexFunc},
49031 #endif
49032 #ifndef SQLITE_OMIT_LOAD_EXTENSION
49033 { "load_extension", 1, 0xff, SQLITE_UTF8, 0, loadExt },
49034 { "load_extension", 2, 0xff, SQLITE_UTF8, 0, loadExt },
49035 #endif
49036 #ifdef SQLITE_TEST
49037 { "randstr", 2, 0, SQLITE_UTF8, 0, randStr },
49038 { "test_destructor", 1, 0xff, SQLITE_UTF8, 0, test_destructor},
49039 { "test_destructor_count", 0, 0, SQLITE_UTF8, 0, test_destructor_count},
49040 { "test_auxdata", -1, 0, SQLITE_UTF8, 0, test_auxdata},
49041 { "test_error", 1, 0, SQLITE_UTF8, 0, test_error},
49042 #endif
49044 static const struct {
49045 char *zName;
49046 signed char nArg;
49047 u8 argType;
49048 u8 needCollSeq;
49049 void (*xStep)(sqlite3_context*,int,sqlite3_value**);
49050 void (*xFinalize)(sqlite3_context*);
49051 } aAggs[] = {
49052 { "min", 1, 0, 1, minmaxStep, minMaxFinalize },
49053 { "max", 1, 1, 1, minmaxStep, minMaxFinalize },
49054 { "sum", 1, 0, 0, sumStep, sumFinalize },
49055 { "total", 1, 0, 0, sumStep, totalFinalize },
49056 { "avg", 1, 0, 0, sumStep, avgFinalize },
49057 { "count", 0, 0, 0, countStep, countFinalize },
49058 { "count", 1, 0, 0, countStep, countFinalize },
49060 int i;
49062 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
49063 void *pArg;
49064 u8 argType = aFuncs[i].argType;
49065 if( argType==0xff ){
49066 pArg = db;
49067 }else{
49068 pArg = (void*)(int)argType;
49070 sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
49071 aFuncs[i].eTextRep, pArg, aFuncs[i].xFunc, 0, 0);
49072 if( aFuncs[i].needCollSeq ){
49073 FuncDef *pFunc = sqlite3FindFunction(db, aFuncs[i].zName,
49074 strlen(aFuncs[i].zName), aFuncs[i].nArg, aFuncs[i].eTextRep, 0);
49075 if( pFunc && aFuncs[i].needCollSeq ){
49076 pFunc->needCollSeq = 1;
49080 #ifndef SQLITE_OMIT_ALTERTABLE
49081 sqlite3AlterFunctions(db);
49082 #endif
49083 #ifndef SQLITE_OMIT_PARSER
49084 sqlite3AttachFunctions(db);
49085 #endif
49086 for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
49087 void *pArg = (void*)(int)aAggs[i].argType;
49088 sqlite3CreateFunc(db, aAggs[i].zName, aAggs[i].nArg, SQLITE_UTF8,
49089 pArg, 0, aAggs[i].xStep, aAggs[i].xFinalize);
49090 if( aAggs[i].needCollSeq ){
49091 FuncDef *pFunc = sqlite3FindFunction( db, aAggs[i].zName,
49092 strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
49093 if( pFunc && aAggs[i].needCollSeq ){
49094 pFunc->needCollSeq = 1;
49098 sqlite3RegisterDateTimeFunctions(db);
49099 sqlite3_overload_function(db, "MATCH", 2);
49100 #ifdef SQLITE_SSE
49101 (void)sqlite3SseFunctions(db);
49102 #endif
49103 #ifdef SQLITE_CASE_SENSITIVE_LIKE
49104 sqlite3RegisterLikeFunctions(db, 1);
49105 #else
49106 sqlite3RegisterLikeFunctions(db, 0);
49107 #endif
49111 ** Set the LIKEOPT flag on the 2-argument function with the given name.
49113 static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
49114 FuncDef *pDef;
49115 pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
49116 if( pDef ){
49117 pDef->flags = flagVal;
49122 ** Register the built-in LIKE and GLOB functions. The caseSensitive
49123 ** parameter determines whether or not the LIKE operator is case
49124 ** sensitive. GLOB is always case sensitive.
49126 static void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
49127 struct compareInfo *pInfo;
49128 if( caseSensitive ){
49129 pInfo = (struct compareInfo*)&likeInfoAlt;
49130 }else{
49131 pInfo = (struct compareInfo*)&likeInfoNorm;
49133 sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
49134 sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
49135 sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
49136 (struct compareInfo*)&globInfo, likeFunc, 0,0);
49137 setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
49138 setLikeOptFlag(db, "like",
49139 caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
49143 ** pExpr points to an expression which implements a function. If
49144 ** it is appropriate to apply the LIKE optimization to that function
49145 ** then set aWc[0] through aWc[2] to the wildcard characters and
49146 ** return TRUE. If the function is not a LIKE-style function then
49147 ** return FALSE.
49149 static int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
49150 FuncDef *pDef;
49151 if( pExpr->op!=TK_FUNCTION || !pExpr->pList ){
49152 return 0;
49154 if( pExpr->pList->nExpr!=2 ){
49155 return 0;
49157 pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
49158 SQLITE_UTF8, 0);
49159 if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
49160 return 0;
49163 /* The memcpy() statement assumes that the wildcard characters are
49164 ** the first three statements in the compareInfo structure. The
49165 ** asserts() that follow verify that assumption
49167 memcpy(aWc, pDef->pUserData, 3);
49168 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
49169 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
49170 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
49171 *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
49172 return 1;
49175 /************** End of func.c ************************************************/
49176 /************** Begin file insert.c ******************************************/
49178 ** 2001 September 15
49180 ** The author disclaims copyright to this source code. In place of
49181 ** a legal notice, here is a blessing:
49183 ** May you do good and not evil.
49184 ** May you find forgiveness for yourself and forgive others.
49185 ** May you share freely, never taking more than you give.
49187 *************************************************************************
49188 ** This file contains C code routines that are called by the parser
49189 ** to handle INSERT statements in SQLite.
49191 ** $Id: insert.c,v 1.186 2007/05/04 13:15:56 drh Exp $
49195 ** Set P3 of the most recently inserted opcode to a column affinity
49196 ** string for index pIdx. A column affinity string has one character
49197 ** for each column in the table, according to the affinity of the column:
49199 ** Character Column affinity
49200 ** ------------------------------
49201 ** 'a' TEXT
49202 ** 'b' NONE
49203 ** 'c' NUMERIC
49204 ** 'd' INTEGER
49205 ** 'e' REAL
49207 static void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
49208 if( !pIdx->zColAff ){
49209 /* The first time a column affinity string for a particular index is
49210 ** required, it is allocated and populated here. It is then stored as
49211 ** a member of the Index structure for subsequent use.
49213 ** The column affinity string will eventually be deleted by
49214 ** sqliteDeleteIndex() when the Index structure itself is cleaned
49215 ** up.
49217 int n;
49218 Table *pTab = pIdx->pTable;
49219 pIdx->zColAff = (char *)sqliteMalloc(pIdx->nColumn+1);
49220 if( !pIdx->zColAff ){
49221 return;
49223 for(n=0; n<pIdx->nColumn; n++){
49224 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
49226 pIdx->zColAff[pIdx->nColumn] = '\0';
49229 sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0);
49233 ** Set P3 of the most recently inserted opcode to a column affinity
49234 ** string for table pTab. A column affinity string has one character
49235 ** for each column indexed by the index, according to the affinity of the
49236 ** column:
49238 ** Character Column affinity
49239 ** ------------------------------
49240 ** 'a' TEXT
49241 ** 'b' NONE
49242 ** 'c' NUMERIC
49243 ** 'd' INTEGER
49244 ** 'e' REAL
49246 static void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
49247 /* The first time a column affinity string for a particular table
49248 ** is required, it is allocated and populated here. It is then
49249 ** stored as a member of the Table structure for subsequent use.
49251 ** The column affinity string will eventually be deleted by
49252 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
49254 if( !pTab->zColAff ){
49255 char *zColAff;
49256 int i;
49258 zColAff = (char *)sqliteMalloc(pTab->nCol+1);
49259 if( !zColAff ){
49260 return;
49263 for(i=0; i<pTab->nCol; i++){
49264 zColAff[i] = pTab->aCol[i].affinity;
49266 zColAff[pTab->nCol] = '\0';
49268 pTab->zColAff = zColAff;
49271 sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0);
49275 ** Return non-zero if SELECT statement p opens the table with rootpage
49276 ** iTab in database iDb. This is used to see if a statement of the form
49277 ** "INSERT INTO <iDb, iTab> SELECT ..." can run without using temporary
49278 ** table for the results of the SELECT.
49280 ** No checking is done for sub-selects that are part of expressions.
49282 static int selectReadsTable(Select *p, Schema *pSchema, int iTab){
49283 int i;
49284 struct SrcList_item *pItem;
49285 if( p->pSrc==0 ) return 0;
49286 for(i=0, pItem=p->pSrc->a; i<p->pSrc->nSrc; i++, pItem++){
49287 if( pItem->pSelect ){
49288 if( selectReadsTable(pItem->pSelect, pSchema, iTab) ) return 1;
49289 }else{
49290 if( pItem->pTab->pSchema==pSchema && pItem->pTab->tnum==iTab ) return 1;
49293 return 0;
49296 #ifndef SQLITE_OMIT_AUTOINCREMENT
49298 ** Write out code to initialize the autoincrement logic. This code
49299 ** looks up the current autoincrement value in the sqlite_sequence
49300 ** table and stores that value in a memory cell. Code generated by
49301 ** autoIncStep() will keep that memory cell holding the largest
49302 ** rowid value. Code generated by autoIncEnd() will write the new
49303 ** largest value of the counter back into the sqlite_sequence table.
49305 ** This routine returns the index of the mem[] cell that contains
49306 ** the maximum rowid counter.
49308 ** Two memory cells are allocated. The next memory cell after the
49309 ** one returned holds the rowid in sqlite_sequence where we will
49310 ** write back the revised maximum rowid.
49312 static int autoIncBegin(
49313 Parse *pParse, /* Parsing context */
49314 int iDb, /* Index of the database holding pTab */
49315 Table *pTab /* The table we are writing to */
49317 int memId = 0;
49318 if( pTab->autoInc ){
49319 Vdbe *v = pParse->pVdbe;
49320 Db *pDb = &pParse->db->aDb[iDb];
49321 int iCur = pParse->nTab;
49322 int addr;
49323 assert( v );
49324 addr = sqlite3VdbeCurrentAddr(v);
49325 memId = pParse->nMem+1;
49326 pParse->nMem += 2;
49327 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
49328 sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13);
49329 sqlite3VdbeAddOp(v, OP_Column, iCur, 0);
49330 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
49331 sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12);
49332 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
49333 sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1);
49334 sqlite3VdbeAddOp(v, OP_Column, iCur, 1);
49335 sqlite3VdbeAddOp(v, OP_MemStore, memId, 1);
49336 sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13);
49337 sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4);
49338 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
49340 return memId;
49344 ** Update the maximum rowid for an autoincrement calculation.
49346 ** This routine should be called when the top of the stack holds a
49347 ** new rowid that is about to be inserted. If that new rowid is
49348 ** larger than the maximum rowid in the memId memory cell, then the
49349 ** memory cell is updated. The stack is unchanged.
49351 static void autoIncStep(Parse *pParse, int memId){
49352 if( memId>0 ){
49353 sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0);
49358 ** After doing one or more inserts, the maximum rowid is stored
49359 ** in mem[memId]. Generate code to write this value back into the
49360 ** the sqlite_sequence table.
49362 static void autoIncEnd(
49363 Parse *pParse, /* The parsing context */
49364 int iDb, /* Index of the database holding pTab */
49365 Table *pTab, /* Table we are inserting into */
49366 int memId /* Memory cell holding the maximum rowid */
49368 if( pTab->autoInc ){
49369 int iCur = pParse->nTab;
49370 Vdbe *v = pParse->pVdbe;
49371 Db *pDb = &pParse->db->aDb[iDb];
49372 int addr;
49373 assert( v );
49374 addr = sqlite3VdbeCurrentAddr(v);
49375 sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
49376 sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0);
49377 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7);
49378 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
49379 sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0);
49380 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
49381 sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0);
49382 sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0);
49383 sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND);
49384 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
49387 #else
49389 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
49390 ** above are all no-ops
49392 # define autoIncBegin(A,B,C) (0)
49393 # define autoIncStep(A,B)
49394 # define autoIncEnd(A,B,C,D)
49395 #endif /* SQLITE_OMIT_AUTOINCREMENT */
49398 /* Forward declaration */
49399 static int xferOptimization(
49400 Parse *pParse, /* Parser context */
49401 Table *pDest, /* The table we are inserting into */
49402 Select *pSelect, /* A SELECT statement to use as the data source */
49403 int onError, /* How to handle constraint errors */
49404 int iDbDest /* The database of pDest */
49408 ** This routine is call to handle SQL of the following forms:
49410 ** insert into TABLE (IDLIST) values(EXPRLIST)
49411 ** insert into TABLE (IDLIST) select
49413 ** The IDLIST following the table name is always optional. If omitted,
49414 ** then a list of all columns for the table is substituted. The IDLIST
49415 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
49417 ** The pList parameter holds EXPRLIST in the first form of the INSERT
49418 ** statement above, and pSelect is NULL. For the second form, pList is
49419 ** NULL and pSelect is a pointer to the select statement used to generate
49420 ** data for the insert.
49422 ** The code generated follows one of four templates. For a simple
49423 ** select with data coming from a VALUES clause, the code executes
49424 ** once straight down through. The template looks like this:
49426 ** open write cursor to <table> and its indices
49427 ** puts VALUES clause expressions onto the stack
49428 ** write the resulting record into <table>
49429 ** cleanup
49431 ** The three remaining templates assume the statement is of the form
49433 ** INSERT INTO <table> SELECT ...
49435 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
49436 ** in other words if the SELECT pulls all columns from a single table
49437 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
49438 ** if <table2> and <table1> are distinct tables but have identical
49439 ** schemas, including all the same indices, then a special optimization
49440 ** is invoked that copies raw records from <table2> over to <table1>.
49441 ** See the xferOptimization() function for the implementation of this
49442 ** template. This is the second template.
49444 ** open a write cursor to <table>
49445 ** open read cursor on <table2>
49446 ** transfer all records in <table2> over to <table>
49447 ** close cursors
49448 ** foreach index on <table>
49449 ** open a write cursor on the <table> index
49450 ** open a read cursor on the corresponding <table2> index
49451 ** transfer all records from the read to the write cursors
49452 ** close cursors
49453 ** end foreach
49455 ** The third template is for when the second template does not apply
49456 ** and the SELECT clause does not read from <table> at any time.
49457 ** The generated code follows this template:
49459 ** goto B
49460 ** A: setup for the SELECT
49461 ** loop over the rows in the SELECT
49462 ** gosub C
49463 ** end loop
49464 ** cleanup after the SELECT
49465 ** goto D
49466 ** B: open write cursor to <table> and its indices
49467 ** goto A
49468 ** C: insert the select result into <table>
49469 ** return
49470 ** D: cleanup
49472 ** The fourth template is used if the insert statement takes its
49473 ** values from a SELECT but the data is being inserted into a table
49474 ** that is also read as part of the SELECT. In the third form,
49475 ** we have to use a intermediate table to store the results of
49476 ** the select. The template is like this:
49478 ** goto B
49479 ** A: setup for the SELECT
49480 ** loop over the tables in the SELECT
49481 ** gosub C
49482 ** end loop
49483 ** cleanup after the SELECT
49484 ** goto D
49485 ** C: insert the select result into the intermediate table
49486 ** return
49487 ** B: open a cursor to an intermediate table
49488 ** goto A
49489 ** D: open write cursor to <table> and its indices
49490 ** loop over the intermediate table
49491 ** transfer values form intermediate table into <table>
49492 ** end the loop
49493 ** cleanup
49495 static void sqlite3Insert(
49496 Parse *pParse, /* Parser context */
49497 SrcList *pTabList, /* Name of table into which we are inserting */
49498 ExprList *pList, /* List of values to be inserted */
49499 Select *pSelect, /* A SELECT statement to use as the data source */
49500 IdList *pColumn, /* Column names corresponding to IDLIST. */
49501 int onError /* How to handle constraint errors */
49503 Table *pTab; /* The table to insert into */
49504 char *zTab; /* Name of the table into which we are inserting */
49505 const char *zDb; /* Name of the database holding this table */
49506 int i, j, idx; /* Loop counters */
49507 Vdbe *v; /* Generate code into this virtual machine */
49508 Index *pIdx; /* For looping over indices of the table */
49509 int nColumn; /* Number of columns in the data */
49510 int base = 0; /* VDBE Cursor number for pTab */
49511 int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */
49512 sqlite3 *db; /* The main database structure */
49513 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
49514 int endOfLoop; /* Label for the end of the insertion loop */
49515 int useTempTable = 0; /* Store SELECT results in intermediate table */
49516 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
49517 int iSelectLoop = 0; /* Address of code that implements the SELECT */
49518 int iCleanup = 0; /* Address of the cleanup code */
49519 int iInsertBlock = 0; /* Address of the subroutine used to insert data */
49520 int iCntMem = 0; /* Memory cell used for the row counter */
49521 int newIdx = -1; /* Cursor for the NEW table */
49522 Db *pDb; /* The database containing table being inserted into */
49523 int counterMem = 0; /* Memory cell holding AUTOINCREMENT counter */
49524 int appendFlag = 0; /* True if the insert is likely to be an append */
49525 int iDb;
49527 #ifndef SQLITE_OMIT_TRIGGER
49528 int isView; /* True if attempting to insert into a view */
49529 int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
49530 #endif
49532 if( pParse->nErr || sqlite3MallocFailed() ){
49533 goto insert_cleanup;
49535 db = pParse->db;
49537 /* Locate the table into which we will be inserting new information.
49539 assert( pTabList->nSrc==1 );
49540 zTab = pTabList->a[0].zName;
49541 if( zTab==0 ) goto insert_cleanup;
49542 pTab = sqlite3SrcListLookup(pParse, pTabList);
49543 if( pTab==0 ){
49544 goto insert_cleanup;
49546 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
49547 assert( iDb<db->nDb );
49548 pDb = &db->aDb[iDb];
49549 zDb = pDb->zName;
49550 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
49551 goto insert_cleanup;
49554 /* Figure out if we have any triggers and if the table being
49555 ** inserted into is a view
49557 #ifndef SQLITE_OMIT_TRIGGER
49558 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
49559 isView = pTab->pSelect!=0;
49560 #else
49561 # define triggers_exist 0
49562 # define isView 0
49563 #endif
49564 #ifdef SQLITE_OMIT_VIEW
49565 # undef isView
49566 # define isView 0
49567 #endif
49569 /* Ensure that:
49570 * (a) the table is not read-only,
49571 * (b) that if it is a view then ON INSERT triggers exist
49573 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
49574 goto insert_cleanup;
49576 assert( pTab!=0 );
49578 /* If pTab is really a view, make sure it has been initialized.
49579 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
49580 ** module table).
49582 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
49583 goto insert_cleanup;
49586 /* Allocate a VDBE
49588 v = sqlite3GetVdbe(pParse);
49589 if( v==0 ) goto insert_cleanup;
49590 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
49591 sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
49593 /* if there are row triggers, allocate a temp table for new.* references. */
49594 if( triggers_exist ){
49595 newIdx = pParse->nTab++;
49598 #ifndef SQLITE_OMIT_XFER_OPT
49599 /* If the statement is of the form
49601 ** INSERT INTO <table1> SELECT * FROM <table2>;
49603 ** Then special optimizations can be applied that make the transfer
49604 ** very fast and which reduce fragmentation of indices.
49606 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
49607 assert( !triggers_exist );
49608 assert( pList==0 );
49609 goto insert_cleanup;
49611 #endif /* SQLITE_OMIT_XFER_OPT */
49613 /* If this is an AUTOINCREMENT table, look up the sequence number in the
49614 ** sqlite_sequence table and store it in memory cell counterMem. Also
49615 ** remember the rowid of the sqlite_sequence table entry in memory cell
49616 ** counterRowid.
49618 counterMem = autoIncBegin(pParse, iDb, pTab);
49620 /* Figure out how many columns of data are supplied. If the data
49621 ** is coming from a SELECT statement, then this step also generates
49622 ** all the code to implement the SELECT statement and invoke a subroutine
49623 ** to process each row of the result. (Template 2.) If the SELECT
49624 ** statement uses the the table that is being inserted into, then the
49625 ** subroutine is also coded here. That subroutine stores the SELECT
49626 ** results in a temporary table. (Template 3.)
49628 if( pSelect ){
49629 /* Data is coming from a SELECT. Generate code to implement that SELECT
49631 int rc, iInitCode;
49632 iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
49633 iSelectLoop = sqlite3VdbeCurrentAddr(v);
49634 iInsertBlock = sqlite3VdbeMakeLabel(v);
49636 /* Resolve the expressions in the SELECT statement and execute it. */
49637 rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
49638 if( rc || pParse->nErr || sqlite3MallocFailed() ){
49639 goto insert_cleanup;
49642 iCleanup = sqlite3VdbeMakeLabel(v);
49643 sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
49644 assert( pSelect->pEList );
49645 nColumn = pSelect->pEList->nExpr;
49647 /* Set useTempTable to TRUE if the result of the SELECT statement
49648 ** should be written into a temporary table. Set to FALSE if each
49649 ** row of the SELECT can be written directly into the result table.
49651 ** A temp table must be used if the table being updated is also one
49652 ** of the tables being read by the SELECT statement. Also use a
49653 ** temp table in the case of row triggers.
49655 if( triggers_exist || selectReadsTable(pSelect,pTab->pSchema,pTab->tnum) ){
49656 useTempTable = 1;
49659 if( useTempTable ){
49660 /* Generate the subroutine that SELECT calls to process each row of
49661 ** the result. Store the result in a temporary table
49663 srcTab = pParse->nTab++;
49664 sqlite3VdbeResolveLabel(v, iInsertBlock);
49665 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
49666 sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0);
49667 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
49668 sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND);
49669 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
49671 /* The following code runs first because the GOTO at the very top
49672 ** of the program jumps to it. Create the temporary table, then jump
49673 ** back up and execute the SELECT code above.
49675 sqlite3VdbeJumpHere(v, iInitCode);
49676 sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0);
49677 sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn);
49678 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
49679 sqlite3VdbeResolveLabel(v, iCleanup);
49680 }else{
49681 sqlite3VdbeJumpHere(v, iInitCode);
49683 }else{
49684 /* This is the case if the data for the INSERT is coming from a VALUES
49685 ** clause
49687 NameContext sNC;
49688 memset(&sNC, 0, sizeof(sNC));
49689 sNC.pParse = pParse;
49690 srcTab = -1;
49691 useTempTable = 0;
49692 nColumn = pList ? pList->nExpr : 0;
49693 for(i=0; i<nColumn; i++){
49694 if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
49695 goto insert_cleanup;
49700 /* Make sure the number of columns in the source data matches the number
49701 ** of columns to be inserted into the table.
49703 if( pColumn==0 && nColumn && nColumn!=pTab->nCol ){
49704 sqlite3ErrorMsg(pParse,
49705 "table %S has %d columns but %d values were supplied",
49706 pTabList, 0, pTab->nCol, nColumn);
49707 goto insert_cleanup;
49709 if( pColumn!=0 && nColumn!=pColumn->nId ){
49710 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
49711 goto insert_cleanup;
49714 /* If the INSERT statement included an IDLIST term, then make sure
49715 ** all elements of the IDLIST really are columns of the table and
49716 ** remember the column indices.
49718 ** If the table has an INTEGER PRIMARY KEY column and that column
49719 ** is named in the IDLIST, then record in the keyColumn variable
49720 ** the index into IDLIST of the primary key column. keyColumn is
49721 ** the index of the primary key as it appears in IDLIST, not as
49722 ** is appears in the original table. (The index of the primary
49723 ** key in the original table is pTab->iPKey.)
49725 if( pColumn ){
49726 for(i=0; i<pColumn->nId; i++){
49727 pColumn->a[i].idx = -1;
49729 for(i=0; i<pColumn->nId; i++){
49730 for(j=0; j<pTab->nCol; j++){
49731 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
49732 pColumn->a[i].idx = j;
49733 if( j==pTab->iPKey ){
49734 keyColumn = i;
49736 break;
49739 if( j>=pTab->nCol ){
49740 if( sqlite3IsRowid(pColumn->a[i].zName) ){
49741 keyColumn = i;
49742 }else{
49743 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
49744 pTabList, 0, pColumn->a[i].zName);
49745 pParse->nErr++;
49746 goto insert_cleanup;
49752 /* If there is no IDLIST term but the table has an integer primary
49753 ** key, the set the keyColumn variable to the primary key column index
49754 ** in the original table definition.
49756 if( pColumn==0 && nColumn>0 ){
49757 keyColumn = pTab->iPKey;
49760 /* Open the temp table for FOR EACH ROW triggers
49762 if( triggers_exist ){
49763 sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
49764 sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
49767 /* Initialize the count of rows to be inserted
49769 if( db->flags & SQLITE_CountRows ){
49770 iCntMem = pParse->nMem++;
49771 sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem);
49774 /* Open tables and indices if there are no row triggers */
49775 if( !triggers_exist ){
49776 base = pParse->nTab;
49777 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
49780 /* If the data source is a temporary table, then we have to create
49781 ** a loop because there might be multiple rows of data. If the data
49782 ** source is a subroutine call from the SELECT statement, then we need
49783 ** to launch the SELECT statement processing.
49785 if( useTempTable ){
49786 iBreak = sqlite3VdbeMakeLabel(v);
49787 sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak);
49788 iCont = sqlite3VdbeCurrentAddr(v);
49789 }else if( pSelect ){
49790 sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop);
49791 sqlite3VdbeResolveLabel(v, iInsertBlock);
49794 /* Run the BEFORE and INSTEAD OF triggers, if there are any
49796 endOfLoop = sqlite3VdbeMakeLabel(v);
49797 if( triggers_exist & TRIGGER_BEFORE ){
49799 /* build the NEW.* reference row. Note that if there is an INTEGER
49800 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
49801 ** translated into a unique ID for the row. But on a BEFORE trigger,
49802 ** we do not know what the unique ID will be (because the insert has
49803 ** not happened yet) so we substitute a rowid of -1
49805 if( keyColumn<0 ){
49806 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
49807 }else if( useTempTable ){
49808 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
49809 }else{
49810 assert( pSelect==0 ); /* Otherwise useTempTable is true */
49811 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
49812 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
49813 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
49814 sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
49815 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
49818 /* Create the new column data
49820 for(i=0; i<pTab->nCol; i++){
49821 if( pColumn==0 ){
49822 j = i;
49823 }else{
49824 for(j=0; j<pColumn->nId; j++){
49825 if( pColumn->a[j].idx==i ) break;
49828 if( pColumn && j>=pColumn->nId ){
49829 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
49830 }else if( useTempTable ){
49831 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
49832 }else{
49833 assert( pSelect==0 ); /* Otherwise useTempTable is true */
49834 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr);
49837 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
49839 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
49840 ** do not attempt any conversions before assembling the record.
49841 ** If this is a real table, attempt conversions as required by the
49842 ** table column affinities.
49844 if( !isView ){
49845 sqlite3TableAffinityStr(v, pTab);
49847 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
49849 /* Fire BEFORE or INSTEAD OF triggers */
49850 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab,
49851 newIdx, -1, onError, endOfLoop) ){
49852 goto insert_cleanup;
49856 /* If any triggers exists, the opening of tables and indices is deferred
49857 ** until now.
49859 if( triggers_exist && !isView ){
49860 base = pParse->nTab;
49861 sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite);
49864 /* Push the record number for the new entry onto the stack. The
49865 ** record number is a randomly generate integer created by NewRowid
49866 ** except when the table has an INTEGER PRIMARY KEY column, in which
49867 ** case the record number is the same as that column.
49869 if( !isView ){
49870 if( IsVirtual(pTab) ){
49871 /* The row that the VUpdate opcode will delete: none */
49872 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
49874 if( keyColumn>=0 ){
49875 if( useTempTable ){
49876 sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn);
49877 }else if( pSelect ){
49878 sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
49879 }else{
49880 VdbeOp *pOp;
49881 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
49882 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
49883 if( pOp && pOp->opcode==OP_Null ){
49884 appendFlag = 1;
49885 pOp->opcode = OP_NewRowid;
49886 pOp->p1 = base;
49887 pOp->p2 = counterMem;
49890 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
49891 ** to generate a unique primary key value.
49893 if( !appendFlag ){
49894 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
49895 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
49896 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
49897 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
49899 }else if( IsVirtual(pTab) ){
49900 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
49901 }else{
49902 sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem);
49903 appendFlag = 1;
49905 autoIncStep(pParse, counterMem);
49907 /* Push onto the stack, data for all columns of the new entry, beginning
49908 ** with the first column.
49910 for(i=0; i<pTab->nCol; i++){
49911 if( i==pTab->iPKey ){
49912 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
49913 ** Whenever this column is read, the record number will be substituted
49914 ** in its place. So will fill this column with a NULL to avoid
49915 ** taking up data space with information that will never be used. */
49916 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
49917 continue;
49919 if( pColumn==0 ){
49920 j = i;
49921 }else{
49922 for(j=0; j<pColumn->nId; j++){
49923 if( pColumn->a[j].idx==i ) break;
49926 if( nColumn==0 || (pColumn && j>=pColumn->nId) ){
49927 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
49928 }else if( useTempTable ){
49929 sqlite3VdbeAddOp(v, OP_Column, srcTab, j);
49930 }else if( pSelect ){
49931 sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
49932 }else{
49933 sqlite3ExprCode(pParse, pList->a[j].pExpr);
49937 /* Generate code to check constraints and generate index keys and
49938 ** do the insertion.
49940 #ifndef SQLITE_OMIT_VIRTUALTABLE
49941 if( IsVirtual(pTab) ){
49942 pParse->pVirtualLock = pTab;
49943 sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2,
49944 (const char*)pTab->pVtab, P3_VTAB);
49945 }else
49946 #endif
49948 sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
49949 0, onError, endOfLoop);
49950 sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0,
49951 (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
49952 appendFlag);
49956 /* Update the count of rows that are inserted
49958 if( (db->flags & SQLITE_CountRows)!=0 ){
49959 sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem);
49962 if( triggers_exist ){
49963 /* Close all tables opened */
49964 if( !isView ){
49965 sqlite3VdbeAddOp(v, OP_Close, base, 0);
49966 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
49967 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
49971 /* Code AFTER triggers */
49972 if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
49973 newIdx, -1, onError, endOfLoop) ){
49974 goto insert_cleanup;
49978 /* The bottom of the loop, if the data source is a SELECT statement
49980 sqlite3VdbeResolveLabel(v, endOfLoop);
49981 if( useTempTable ){
49982 sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont);
49983 sqlite3VdbeResolveLabel(v, iBreak);
49984 sqlite3VdbeAddOp(v, OP_Close, srcTab, 0);
49985 }else if( pSelect ){
49986 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
49987 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
49988 sqlite3VdbeResolveLabel(v, iCleanup);
49991 if( !triggers_exist && !IsVirtual(pTab) ){
49992 /* Close all tables opened */
49993 sqlite3VdbeAddOp(v, OP_Close, base, 0);
49994 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
49995 sqlite3VdbeAddOp(v, OP_Close, idx+base, 0);
49999 /* Update the sqlite_sequence table by storing the content of the
50000 ** counter value in memory counterMem back into the sqlite_sequence
50001 ** table.
50003 autoIncEnd(pParse, iDb, pTab, counterMem);
50006 ** Return the number of rows inserted. If this routine is
50007 ** generating code because of a call to sqlite3NestedParse(), do not
50008 ** invoke the callback function.
50010 if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
50011 sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0);
50012 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
50013 sqlite3VdbeSetNumCols(v, 1);
50014 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC);
50017 insert_cleanup:
50018 sqlite3SrcListDelete(pTabList);
50019 sqlite3ExprListDelete(pList);
50020 sqlite3SelectDelete(pSelect);
50021 sqlite3IdListDelete(pColumn);
50025 ** Generate code to do a constraint check prior to an INSERT or an UPDATE.
50027 ** When this routine is called, the stack contains (from bottom to top)
50028 ** the following values:
50030 ** 1. The rowid of the row to be updated before the update. This
50031 ** value is omitted unless we are doing an UPDATE that involves a
50032 ** change to the record number.
50034 ** 2. The rowid of the row after the update.
50036 ** 3. The data in the first column of the entry after the update.
50038 ** i. Data from middle columns...
50040 ** N. The data in the last column of the entry after the update.
50042 ** The old rowid shown as entry (1) above is omitted unless both isUpdate
50043 ** and rowidChng are 1. isUpdate is true for UPDATEs and false for
50044 ** INSERTs and rowidChng is true if the record number is being changed.
50046 ** The code generated by this routine pushes additional entries onto
50047 ** the stack which are the keys for new index entries for the new record.
50048 ** The order of index keys is the same as the order of the indices on
50049 ** the pTable->pIndex list. A key is only created for index i if
50050 ** aIdxUsed!=0 and aIdxUsed[i]!=0.
50052 ** This routine also generates code to check constraints. NOT NULL,
50053 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
50054 ** then the appropriate action is performed. There are five possible
50055 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
50057 ** Constraint type Action What Happens
50058 ** --------------- ---------- ----------------------------------------
50059 ** any ROLLBACK The current transaction is rolled back and
50060 ** sqlite3_exec() returns immediately with a
50061 ** return code of SQLITE_CONSTRAINT.
50063 ** any ABORT Back out changes from the current command
50064 ** only (do not do a complete rollback) then
50065 ** cause sqlite3_exec() to return immediately
50066 ** with SQLITE_CONSTRAINT.
50068 ** any FAIL Sqlite_exec() returns immediately with a
50069 ** return code of SQLITE_CONSTRAINT. The
50070 ** transaction is not rolled back and any
50071 ** prior changes are retained.
50073 ** any IGNORE The record number and data is popped from
50074 ** the stack and there is an immediate jump
50075 ** to label ignoreDest.
50077 ** NOT NULL REPLACE The NULL value is replace by the default
50078 ** value for that column. If the default value
50079 ** is NULL, the action is the same as ABORT.
50081 ** UNIQUE REPLACE The other row that conflicts with the row
50082 ** being inserted is removed.
50084 ** CHECK REPLACE Illegal. The results in an exception.
50086 ** Which action to take is determined by the overrideError parameter.
50087 ** Or if overrideError==OE_Default, then the pParse->onError parameter
50088 ** is used. Or if pParse->onError==OE_Default then the onError value
50089 ** for the constraint is used.
50091 ** The calling routine must open a read/write cursor for pTab with
50092 ** cursor number "base". All indices of pTab must also have open
50093 ** read/write cursors with cursor number base+i for the i-th cursor.
50094 ** Except, if there is no possibility of a REPLACE action then
50095 ** cursors do not need to be open for indices where aIdxUsed[i]==0.
50097 ** If the isUpdate flag is true, it means that the "base" cursor is
50098 ** initially pointing to an entry that is being updated. The isUpdate
50099 ** flag causes extra code to be generated so that the "base" cursor
50100 ** is still pointing at the same entry after the routine returns.
50101 ** Without the isUpdate flag, the "base" cursor might be moved.
50103 static void sqlite3GenerateConstraintChecks(
50104 Parse *pParse, /* The parser context */
50105 Table *pTab, /* the table into which we are inserting */
50106 int base, /* Index of a read/write cursor pointing at pTab */
50107 char *aIdxUsed, /* Which indices are used. NULL means all are used */
50108 int rowidChng, /* True if the record number will change */
50109 int isUpdate, /* True for UPDATE, False for INSERT */
50110 int overrideError, /* Override onError to this if not OE_Default */
50111 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
50113 int i;
50114 Vdbe *v;
50115 int nCol;
50116 int onError;
50117 int addr;
50118 int extra;
50119 int iCur;
50120 Index *pIdx;
50121 int seenReplace = 0;
50122 int jumpInst1=0, jumpInst2;
50123 int hasTwoRowids = (isUpdate && rowidChng);
50125 v = sqlite3GetVdbe(pParse);
50126 assert( v!=0 );
50127 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
50128 nCol = pTab->nCol;
50130 /* Test all NOT NULL constraints.
50132 for(i=0; i<nCol; i++){
50133 if( i==pTab->iPKey ){
50134 continue;
50136 onError = pTab->aCol[i].notNull;
50137 if( onError==OE_None ) continue;
50138 if( overrideError!=OE_Default ){
50139 onError = overrideError;
50140 }else if( onError==OE_Default ){
50141 onError = OE_Abort;
50143 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
50144 onError = OE_Abort;
50146 sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1);
50147 addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0);
50148 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
50149 || onError==OE_Ignore || onError==OE_Replace );
50150 switch( onError ){
50151 case OE_Rollback:
50152 case OE_Abort:
50153 case OE_Fail: {
50154 char *zMsg = 0;
50155 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
50156 sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
50157 " may not be NULL", (char*)0);
50158 sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
50159 break;
50161 case OE_Ignore: {
50162 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
50163 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
50164 break;
50166 case OE_Replace: {
50167 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
50168 sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0);
50169 break;
50172 sqlite3VdbeJumpHere(v, addr);
50175 /* Test all CHECK constraints
50177 #ifndef SQLITE_OMIT_CHECK
50178 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
50179 int allOk = sqlite3VdbeMakeLabel(v);
50180 assert( pParse->ckOffset==0 );
50181 pParse->ckOffset = nCol;
50182 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1);
50183 assert( pParse->ckOffset==nCol );
50184 pParse->ckOffset = 0;
50185 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
50186 if( onError==OE_Ignore || onError==OE_Replace ){
50187 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
50188 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
50189 }else{
50190 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
50192 sqlite3VdbeResolveLabel(v, allOk);
50194 #endif /* !defined(SQLITE_OMIT_CHECK) */
50196 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
50197 ** of the new record does not previously exist. Except, if this
50198 ** is an UPDATE and the primary key is not changing, that is OK.
50200 if( rowidChng ){
50201 onError = pTab->keyConf;
50202 if( overrideError!=OE_Default ){
50203 onError = overrideError;
50204 }else if( onError==OE_Default ){
50205 onError = OE_Abort;
50208 if( isUpdate ){
50209 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
50210 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
50211 jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0);
50213 sqlite3VdbeAddOp(v, OP_Dup, nCol, 1);
50214 jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0);
50215 switch( onError ){
50216 default: {
50217 onError = OE_Abort;
50218 /* Fall thru into the next case */
50220 case OE_Rollback:
50221 case OE_Abort:
50222 case OE_Fail: {
50223 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
50224 "PRIMARY KEY must be unique", P3_STATIC);
50225 break;
50227 case OE_Replace: {
50228 sqlite3GenerateRowIndexDelete(v, pTab, base, 0);
50229 if( isUpdate ){
50230 sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1);
50231 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
50233 seenReplace = 1;
50234 break;
50236 case OE_Ignore: {
50237 assert( seenReplace==0 );
50238 sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0);
50239 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
50240 break;
50243 sqlite3VdbeJumpHere(v, jumpInst2);
50244 if( isUpdate ){
50245 sqlite3VdbeJumpHere(v, jumpInst1);
50246 sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1);
50247 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
50251 /* Test all UNIQUE constraints by creating entries for each UNIQUE
50252 ** index and making sure that duplicate entries do not already exist.
50253 ** Add the new records to the indices as we go.
50255 extra = -1;
50256 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
50257 if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
50258 extra++;
50260 /* Create a key for accessing the index entry */
50261 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1);
50262 for(i=0; i<pIdx->nColumn; i++){
50263 int idx = pIdx->aiColumn[i];
50264 if( idx==pTab->iPKey ){
50265 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
50266 }else{
50267 sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
50270 jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0);
50271 sqlite3IndexAffinityStr(v, pIdx);
50273 /* Find out what action to take in case there is an indexing conflict */
50274 onError = pIdx->onError;
50275 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
50276 if( overrideError!=OE_Default ){
50277 onError = overrideError;
50278 }else if( onError==OE_Default ){
50279 onError = OE_Abort;
50281 if( seenReplace ){
50282 if( onError==OE_Ignore ) onError = OE_Replace;
50283 else if( onError==OE_Fail ) onError = OE_Abort;
50287 /* Check to see if the new index entry will be unique */
50288 sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1);
50289 jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
50291 /* Generate code that executes if the new index entry is not unique */
50292 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
50293 || onError==OE_Ignore || onError==OE_Replace );
50294 switch( onError ){
50295 case OE_Rollback:
50296 case OE_Abort:
50297 case OE_Fail: {
50298 int j, n1, n2;
50299 char zErrMsg[200];
50300 sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
50301 pIdx->nColumn>1 ? "columns " : "column ");
50302 n1 = strlen(zErrMsg);
50303 for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
50304 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
50305 n2 = strlen(zCol);
50306 if( j>0 ){
50307 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
50308 n1 += 2;
50310 if( n1+n2>sizeof(zErrMsg)-30 ){
50311 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
50312 n1 += 3;
50313 break;
50314 }else{
50315 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
50316 n1 += n2;
50319 sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1],
50320 pIdx->nColumn>1 ? " are not unique" : " is not unique");
50321 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
50322 break;
50324 case OE_Ignore: {
50325 assert( seenReplace==0 );
50326 sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0);
50327 sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest);
50328 break;
50330 case OE_Replace: {
50331 sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0);
50332 if( isUpdate ){
50333 sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1);
50334 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
50336 seenReplace = 1;
50337 break;
50340 #if NULL_DISTINCT_FOR_UNIQUE
50341 sqlite3VdbeJumpHere(v, jumpInst1);
50342 #endif
50343 sqlite3VdbeJumpHere(v, jumpInst2);
50348 ** This routine generates code to finish the INSERT or UPDATE operation
50349 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
50350 ** The stack must contain keys for all active indices followed by data
50351 ** and the rowid for the new entry. This routine creates the new
50352 ** entries in all indices and in the main table.
50354 ** The arguments to this routine should be the same as the first six
50355 ** arguments to sqlite3GenerateConstraintChecks.
50357 static void sqlite3CompleteInsertion(
50358 Parse *pParse, /* The parser context */
50359 Table *pTab, /* the table into which we are inserting */
50360 int base, /* Index of a read/write cursor pointing at pTab */
50361 char *aIdxUsed, /* Which indices are used. NULL means all are used */
50362 int rowidChng, /* True if the record number will change */
50363 int isUpdate, /* True for UPDATE, False for INSERT */
50364 int newIdx, /* Index of NEW table for triggers. -1 if none */
50365 int appendBias /* True if this is likely to be an append */
50367 int i;
50368 Vdbe *v;
50369 int nIdx;
50370 Index *pIdx;
50371 int pik_flags;
50373 v = sqlite3GetVdbe(pParse);
50374 assert( v!=0 );
50375 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
50376 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
50377 for(i=nIdx-1; i>=0; i--){
50378 if( aIdxUsed && aIdxUsed[i]==0 ) continue;
50379 sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0);
50381 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
50382 sqlite3TableAffinityStr(v, pTab);
50383 #ifndef SQLITE_OMIT_TRIGGER
50384 if( newIdx>=0 ){
50385 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
50386 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
50387 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
50389 #endif
50390 if( pParse->nested ){
50391 pik_flags = 0;
50392 }else{
50393 pik_flags = OPFLAG_NCHANGE;
50394 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
50396 if( appendBias ){
50397 pik_flags |= OPFLAG_APPEND;
50399 sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags);
50400 if( !pParse->nested ){
50401 sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC);
50404 if( isUpdate && rowidChng ){
50405 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
50410 ** Generate code that will open cursors for a table and for all
50411 ** indices of that table. The "base" parameter is the cursor number used
50412 ** for the table. Indices are opened on subsequent cursors.
50414 static void sqlite3OpenTableAndIndices(
50415 Parse *pParse, /* Parsing context */
50416 Table *pTab, /* Table to be opened */
50417 int base, /* Cursor number assigned to the table */
50418 int op /* OP_OpenRead or OP_OpenWrite */
50420 int i;
50421 int iDb;
50422 Index *pIdx;
50423 Vdbe *v;
50425 if( IsVirtual(pTab) ) return;
50426 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
50427 v = sqlite3GetVdbe(pParse);
50428 assert( v!=0 );
50429 sqlite3OpenTable(pParse, base, iDb, pTab, op);
50430 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
50431 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
50432 assert( pIdx->pSchema==pTab->pSchema );
50433 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
50434 VdbeComment((v, "# %s", pIdx->zName));
50435 sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF);
50437 if( pParse->nTab<=base+i ){
50438 pParse->nTab = base+i;
50443 #ifdef SQLITE_TEST
50445 ** The following global variable is incremented whenever the
50446 ** transfer optimization is used. This is used for testing
50447 ** purposes only - to make sure the transfer optimization really
50448 ** is happening when it is suppose to.
50450 int sqlite3_xferopt_count;
50451 #endif /* SQLITE_TEST */
50454 #ifndef SQLITE_OMIT_XFER_OPT
50456 ** Check to collation names to see if they are compatible.
50458 static int xferCompatibleCollation(const char *z1, const char *z2){
50459 if( z1==0 ){
50460 return z2==0;
50462 if( z2==0 ){
50463 return 0;
50465 return sqlite3StrICmp(z1, z2)==0;
50470 ** Check to see if index pSrc is compatible as a source of data
50471 ** for index pDest in an insert transfer optimization. The rules
50472 ** for a compatible index:
50474 ** * The index is over the same set of columns
50475 ** * The same DESC and ASC markings occurs on all columns
50476 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
50477 ** * The same collating sequence on each column
50479 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
50480 int i;
50481 assert( pDest && pSrc );
50482 assert( pDest->pTable!=pSrc->pTable );
50483 if( pDest->nColumn!=pSrc->nColumn ){
50484 return 0; /* Different number of columns */
50486 if( pDest->onError!=pSrc->onError ){
50487 return 0; /* Different conflict resolution strategies */
50489 for(i=0; i<pSrc->nColumn; i++){
50490 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
50491 return 0; /* Different columns indexed */
50493 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
50494 return 0; /* Different sort orders */
50496 if( pSrc->azColl[i]!=pDest->azColl[i] ){
50497 return 0; /* Different sort orders */
50501 /* If no test above fails then the indices must be compatible */
50502 return 1;
50506 ** Attempt the transfer optimization on INSERTs of the form
50508 ** INSERT INTO tab1 SELECT * FROM tab2;
50510 ** This optimization is only attempted if
50512 ** (1) tab1 and tab2 have identical schemas including all the
50513 ** same indices and constraints
50515 ** (2) tab1 and tab2 are different tables
50517 ** (3) There must be no triggers on tab1
50519 ** (4) The result set of the SELECT statement is "*"
50521 ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
50522 ** or LIMIT clause.
50524 ** (6) The SELECT statement is a simple (not a compound) select that
50525 ** contains only tab2 in its FROM clause
50527 ** This method for implementing the INSERT transfers raw records from
50528 ** tab2 over to tab1. The columns are not decoded. Raw records from
50529 ** the indices of tab2 are transfered to tab1 as well. In so doing,
50530 ** the resulting tab1 has much less fragmentation.
50532 ** This routine returns TRUE if the optimization is attempted. If any
50533 ** of the conditions above fail so that the optimization should not
50534 ** be attempted, then this routine returns FALSE.
50536 static int xferOptimization(
50537 Parse *pParse, /* Parser context */
50538 Table *pDest, /* The table we are inserting into */
50539 Select *pSelect, /* A SELECT statement to use as the data source */
50540 int onError, /* How to handle constraint errors */
50541 int iDbDest /* The database of pDest */
50543 ExprList *pEList; /* The result set of the SELECT */
50544 Table *pSrc; /* The table in the FROM clause of SELECT */
50545 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
50546 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
50547 int i; /* Loop counter */
50548 int iDbSrc; /* The database of pSrc */
50549 int iSrc, iDest; /* Cursors from source and destination */
50550 int addr1, addr2; /* Loop addresses */
50551 int emptyDestTest; /* Address of test for empty pDest */
50552 int emptySrcTest; /* Address of test for empty pSrc */
50553 Vdbe *v; /* The VDBE we are building */
50554 KeyInfo *pKey; /* Key information for an index */
50555 int counterMem; /* Memory register used by AUTOINC */
50556 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
50558 if( pSelect==0 ){
50559 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
50561 if( pDest->pTrigger ){
50562 return 0; /* tab1 must not have triggers */
50564 #ifndef SQLITE_OMIT_VIRTUALTABLE
50565 if( pDest->isVirtual ){
50566 return 0; /* tab1 must not be a virtual table */
50568 #endif
50569 if( onError==OE_Default ){
50570 onError = OE_Abort;
50572 if( onError!=OE_Abort && onError!=OE_Rollback ){
50573 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
50575 if( pSelect->pSrc==0 ){
50576 return 0; /* SELECT must have a FROM clause */
50578 if( pSelect->pSrc->nSrc!=1 ){
50579 return 0; /* FROM clause must have exactly one term */
50581 if( pSelect->pSrc->a[0].pSelect ){
50582 return 0; /* FROM clause cannot contain a subquery */
50584 if( pSelect->pWhere ){
50585 return 0; /* SELECT may not have a WHERE clause */
50587 if( pSelect->pOrderBy ){
50588 return 0; /* SELECT may not have an ORDER BY clause */
50590 /* Do not need to test for a HAVING clause. If HAVING is present but
50591 ** there is no ORDER BY, we will get an error. */
50592 if( pSelect->pGroupBy ){
50593 return 0; /* SELECT may not have a GROUP BY clause */
50595 if( pSelect->pLimit ){
50596 return 0; /* SELECT may not have a LIMIT clause */
50598 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
50599 if( pSelect->pPrior ){
50600 return 0; /* SELECT may not be a compound query */
50602 if( pSelect->isDistinct ){
50603 return 0; /* SELECT may not be DISTINCT */
50605 pEList = pSelect->pEList;
50606 assert( pEList!=0 );
50607 if( pEList->nExpr!=1 ){
50608 return 0; /* The result set must have exactly one column */
50610 assert( pEList->a[0].pExpr );
50611 if( pEList->a[0].pExpr->op!=TK_ALL ){
50612 return 0; /* The result set must be the special operator "*" */
50615 /* At this point we have established that the statement is of the
50616 ** correct syntactic form to participate in this optimization. Now
50617 ** we have to check the semantics.
50619 pItem = pSelect->pSrc->a;
50620 pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
50621 if( pSrc==0 ){
50622 return 0; /* FROM clause does not contain a real table */
50624 if( pSrc==pDest ){
50625 return 0; /* tab1 and tab2 may not be the same table */
50627 #ifndef SQLITE_OMIT_VIRTUALTABLE
50628 if( pSrc->isVirtual ){
50629 return 0; /* tab2 must not be a virtual table */
50631 #endif
50632 if( pSrc->pSelect ){
50633 return 0; /* tab2 may not be a view */
50635 if( pDest->nCol!=pSrc->nCol ){
50636 return 0; /* Number of columns must be the same in tab1 and tab2 */
50638 if( pDest->iPKey!=pSrc->iPKey ){
50639 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
50641 for(i=0; i<pDest->nCol; i++){
50642 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
50643 return 0; /* Affinity must be the same on all columns */
50645 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
50646 return 0; /* Collating sequence must be the same on all columns */
50648 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
50649 return 0; /* tab2 must be NOT NULL if tab1 is */
50652 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
50653 if( pDestIdx->onError!=OE_None ){
50654 destHasUniqueIdx = 1;
50656 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
50657 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
50659 if( pSrcIdx==0 ){
50660 return 0; /* pDestIdx has no corresponding index in pSrc */
50663 #ifndef SQLITE_OMIT_CHECK
50664 if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
50665 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
50667 #endif
50669 /* If we get this far, it means either:
50671 ** * We can always do the transfer if the table contains an
50672 ** an integer primary key
50674 ** * We can conditionally do the transfer if the destination
50675 ** table is empty.
50677 #ifdef SQLITE_TEST
50678 sqlite3_xferopt_count++;
50679 #endif
50680 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
50681 v = sqlite3GetVdbe(pParse);
50682 iSrc = pParse->nTab++;
50683 iDest = pParse->nTab++;
50684 counterMem = autoIncBegin(pParse, iDbDest, pDest);
50685 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
50686 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
50687 /* If tables do not have an INTEGER PRIMARY KEY and there
50688 ** are indices to be copied and the destination is not empty,
50689 ** we have to disallow the transfer optimization because the
50690 ** the rowids might change which will mess up indexing.
50692 ** Or if the destination has a UNIQUE index and is not empty,
50693 ** we also disallow the transfer optimization because we cannot
50694 ** insure that all entries in the union of DEST and SRC will be
50695 ** unique.
50697 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0);
50698 emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
50699 sqlite3VdbeJumpHere(v, addr1);
50700 }else{
50701 emptyDestTest = 0;
50703 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
50704 emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
50705 if( pDest->iPKey>=0 ){
50706 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
50707 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
50708 addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0);
50709 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
50710 "PRIMARY KEY must be unique", P3_STATIC);
50711 sqlite3VdbeJumpHere(v, addr2);
50712 autoIncStep(pParse, counterMem);
50713 }else if( pDest->pIndex==0 ){
50714 addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0);
50715 }else{
50716 addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0);
50717 assert( pDest->autoInc==0 );
50719 sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0);
50720 sqlite3VdbeOp3(v, OP_Insert, iDest,
50721 OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND,
50722 pDest->zName, 0);
50723 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1);
50724 autoIncEnd(pParse, iDbDest, pDest, counterMem);
50725 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
50726 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
50727 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
50729 assert( pSrcIdx );
50730 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
50731 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
50732 sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0);
50733 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
50734 VdbeComment((v, "# %s", pSrcIdx->zName));
50735 sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum,
50736 (char*)pKey, P3_KEYINFO_HANDOFF);
50737 sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0);
50738 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
50739 VdbeComment((v, "# %s", pDestIdx->zName));
50740 sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum,
50741 (char*)pKey, P3_KEYINFO_HANDOFF);
50742 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0);
50743 sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0);
50744 sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1);
50745 sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1);
50746 sqlite3VdbeJumpHere(v, addr1);
50748 sqlite3VdbeJumpHere(v, emptySrcTest);
50749 sqlite3VdbeAddOp(v, OP_Close, iSrc, 0);
50750 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
50751 if( emptyDestTest ){
50752 sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0);
50753 sqlite3VdbeJumpHere(v, emptyDestTest);
50754 sqlite3VdbeAddOp(v, OP_Close, iDest, 0);
50755 return 0;
50756 }else{
50757 return 1;
50760 #endif /* SQLITE_OMIT_XFER_OPT */
50762 /************** End of insert.c **********************************************/
50763 /************** Begin file legacy.c ******************************************/
50765 ** 2001 September 15
50767 ** The author disclaims copyright to this source code. In place of
50768 ** a legal notice, here is a blessing:
50770 ** May you do good and not evil.
50771 ** May you find forgiveness for yourself and forgive others.
50772 ** May you share freely, never taking more than you give.
50774 *************************************************************************
50775 ** Main file for the SQLite library. The routines in this file
50776 ** implement the programmer interface to the library. Routines in
50777 ** other files are for internal use by SQLite and should not be
50778 ** accessed by users of the library.
50780 ** $Id: legacy.c,v 1.18 2007/05/04 13:15:56 drh Exp $
50785 ** Execute SQL code. Return one of the SQLITE_ success/failure
50786 ** codes. Also write an error message into memory obtained from
50787 ** malloc() and make *pzErrMsg point to that message.
50789 ** If the SQL is a query, then for each row in the query result
50790 ** the xCallback() function is called. pArg becomes the first
50791 ** argument to xCallback(). If xCallback=NULL then no callback
50792 ** is invoked, even for queries.
50794 int sqlite3_exec(
50795 sqlite3 *db, /* The database on which the SQL executes */
50796 const char *zSql, /* The SQL to be executed */
50797 sqlite3_callback xCallback, /* Invoke this callback routine */
50798 void *pArg, /* First argument to xCallback() */
50799 char **pzErrMsg /* Write error messages here */
50801 int rc = SQLITE_OK;
50802 const char *zLeftover;
50803 sqlite3_stmt *pStmt = 0;
50804 char **azCols = 0;
50806 int nRetry = 0;
50807 int nCallback;
50809 if( zSql==0 ) return SQLITE_OK;
50810 while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
50811 int nCol;
50812 char **azVals = 0;
50814 pStmt = 0;
50815 rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
50816 assert( rc==SQLITE_OK || pStmt==0 );
50817 if( rc!=SQLITE_OK ){
50818 continue;
50820 if( !pStmt ){
50821 /* this happens for a comment or white-space */
50822 zSql = zLeftover;
50823 continue;
50826 nCallback = 0;
50828 nCol = sqlite3_column_count(pStmt);
50829 azCols = sqliteMalloc(2*nCol*sizeof(const char *) + 1);
50830 if( azCols==0 ){
50831 goto exec_out;
50834 while( 1 ){
50835 int i;
50836 rc = sqlite3_step(pStmt);
50838 /* Invoke the callback function if required */
50839 if( xCallback && (SQLITE_ROW==rc ||
50840 (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
50841 if( 0==nCallback ){
50842 for(i=0; i<nCol; i++){
50843 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
50845 nCallback++;
50847 if( rc==SQLITE_ROW ){
50848 azVals = &azCols[nCol];
50849 for(i=0; i<nCol; i++){
50850 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
50853 if( xCallback(pArg, nCol, azVals, azCols) ){
50854 rc = SQLITE_ABORT;
50855 goto exec_out;
50859 if( rc!=SQLITE_ROW ){
50860 rc = sqlite3_finalize(pStmt);
50861 pStmt = 0;
50862 if( rc!=SQLITE_SCHEMA ){
50863 nRetry = 0;
50864 zSql = zLeftover;
50865 while( isspace((unsigned char)zSql[0]) ) zSql++;
50867 break;
50871 sqliteFree(azCols);
50872 azCols = 0;
50875 exec_out:
50876 if( pStmt ) sqlite3_finalize(pStmt);
50877 if( azCols ) sqliteFree(azCols);
50879 rc = sqlite3ApiExit(0, rc);
50880 if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
50881 int nErrMsg = 1 + strlen(sqlite3_errmsg(db));
50882 *pzErrMsg = sqlite3_malloc(nErrMsg);
50883 if( *pzErrMsg ){
50884 memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
50886 }else if( pzErrMsg ){
50887 *pzErrMsg = 0;
50890 assert( (rc&db->errMask)==rc );
50891 return rc;
50894 /************** End of legacy.c **********************************************/
50895 /************** Begin file loadext.c *****************************************/
50897 ** 2006 June 7
50899 ** The author disclaims copyright to this source code. In place of
50900 ** a legal notice, here is a blessing:
50902 ** May you do good and not evil.
50903 ** May you find forgiveness for yourself and forgive others.
50904 ** May you share freely, never taking more than you give.
50906 *************************************************************************
50907 ** This file contains code used to dynamically load extensions into
50908 ** the SQLite library.
50910 #ifndef SQLITE_OMIT_LOAD_EXTENSION
50912 #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
50913 /************** Include sqlite3ext.h in the middle of loadext.c **************/
50914 /************** Begin file sqlite3ext.h **************************************/
50916 ** 2006 June 7
50918 ** The author disclaims copyright to this source code. In place of
50919 ** a legal notice, here is a blessing:
50921 ** May you do good and not evil.
50922 ** May you find forgiveness for yourself and forgive others.
50923 ** May you share freely, never taking more than you give.
50925 *************************************************************************
50926 ** This header file defines the SQLite interface for use by
50927 ** shared libraries that want to be imported as extensions into
50928 ** an SQLite instance. Shared libraries that intend to be loaded
50929 ** as extensions by SQLite should #include this file instead of
50930 ** sqlite3.h.
50932 ** @(#) $Id: sqlite3ext.h,v 1.10 2007/03/29 18:46:01 drh Exp $
50934 #ifndef _SQLITE3EXT_H_
50935 #define _SQLITE3EXT_H_
50937 typedef struct sqlite3_api_routines sqlite3_api_routines;
50940 ** The following structure hold pointers to all of the SQLite API
50941 ** routines.
50943 struct sqlite3_api_routines {
50944 void * (*aggregate_context)(sqlite3_context*,int nBytes);
50945 int (*aggregate_count)(sqlite3_context*);
50946 int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
50947 int (*bind_double)(sqlite3_stmt*,int,double);
50948 int (*bind_int)(sqlite3_stmt*,int,int);
50949 int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
50950 int (*bind_null)(sqlite3_stmt*,int);
50951 int (*bind_parameter_count)(sqlite3_stmt*);
50952 int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
50953 const char * (*bind_parameter_name)(sqlite3_stmt*,int);
50954 int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
50955 int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
50956 int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
50957 int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
50958 int (*busy_timeout)(sqlite3*,int ms);
50959 int (*changes)(sqlite3*);
50960 int (*close)(sqlite3*);
50961 int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
50962 int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
50963 const void * (*column_blob)(sqlite3_stmt*,int iCol);
50964 int (*column_bytes)(sqlite3_stmt*,int iCol);
50965 int (*column_bytes16)(sqlite3_stmt*,int iCol);
50966 int (*column_count)(sqlite3_stmt*pStmt);
50967 const char * (*column_database_name)(sqlite3_stmt*,int);
50968 const void * (*column_database_name16)(sqlite3_stmt*,int);
50969 const char * (*column_decltype)(sqlite3_stmt*,int i);
50970 const void * (*column_decltype16)(sqlite3_stmt*,int);
50971 double (*column_double)(sqlite3_stmt*,int iCol);
50972 int (*column_int)(sqlite3_stmt*,int iCol);
50973 sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
50974 const char * (*column_name)(sqlite3_stmt*,int);
50975 const void * (*column_name16)(sqlite3_stmt*,int);
50976 const char * (*column_origin_name)(sqlite3_stmt*,int);
50977 const void * (*column_origin_name16)(sqlite3_stmt*,int);
50978 const char * (*column_table_name)(sqlite3_stmt*,int);
50979 const void * (*column_table_name16)(sqlite3_stmt*,int);
50980 const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
50981 const void * (*column_text16)(sqlite3_stmt*,int iCol);
50982 int (*column_type)(sqlite3_stmt*,int iCol);
50983 sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
50984 void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
50985 int (*complete)(const char*sql);
50986 int (*complete16)(const void*sql);
50987 int (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
50988 int (*create_collation16)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
50989 int (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
50990 int (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
50991 int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
50992 int (*data_count)(sqlite3_stmt*pStmt);
50993 sqlite3 * (*db_handle)(sqlite3_stmt*);
50994 int (*declare_vtab)(sqlite3*,const char*);
50995 int (*enable_shared_cache)(int);
50996 int (*errcode)(sqlite3*db);
50997 const char * (*errmsg)(sqlite3*);
50998 const void * (*errmsg16)(sqlite3*);
50999 int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
51000 int (*expired)(sqlite3_stmt*);
51001 int (*finalize)(sqlite3_stmt*pStmt);
51002 void (*free)(void*);
51003 void (*free_table)(char**result);
51004 int (*get_autocommit)(sqlite3*);
51005 void * (*get_auxdata)(sqlite3_context*,int);
51006 int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
51007 int (*global_recover)(void);
51008 void (*interruptx)(sqlite3*);
51009 sqlite_int64 (*last_insert_rowid)(sqlite3*);
51010 const char * (*libversion)(void);
51011 int (*libversion_number)(void);
51012 void *(*malloc)(int);
51013 char * (*mprintf)(const char*,...);
51014 int (*open)(const char*,sqlite3**);
51015 int (*open16)(const void*,sqlite3**);
51016 int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
51017 int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
51018 void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
51019 void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
51020 void *(*realloc)(void*,int);
51021 int (*reset)(sqlite3_stmt*pStmt);
51022 void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
51023 void (*result_double)(sqlite3_context*,double);
51024 void (*result_error)(sqlite3_context*,const char*,int);
51025 void (*result_error16)(sqlite3_context*,const void*,int);
51026 void (*result_int)(sqlite3_context*,int);
51027 void (*result_int64)(sqlite3_context*,sqlite_int64);
51028 void (*result_null)(sqlite3_context*);
51029 void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
51030 void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
51031 void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
51032 void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
51033 void (*result_value)(sqlite3_context*,sqlite3_value*);
51034 void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
51035 int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
51036 void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
51037 char * (*snprintf)(int,char*,const char*,...);
51038 int (*step)(sqlite3_stmt*);
51039 int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
51040 void (*thread_cleanup)(void);
51041 int (*total_changes)(sqlite3*);
51042 void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
51043 int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
51044 void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
51045 void * (*user_data)(sqlite3_context*);
51046 const void * (*value_blob)(sqlite3_value*);
51047 int (*value_bytes)(sqlite3_value*);
51048 int (*value_bytes16)(sqlite3_value*);
51049 double (*value_double)(sqlite3_value*);
51050 int (*value_int)(sqlite3_value*);
51051 sqlite_int64 (*value_int64)(sqlite3_value*);
51052 int (*value_numeric_type)(sqlite3_value*);
51053 const unsigned char * (*value_text)(sqlite3_value*);
51054 const void * (*value_text16)(sqlite3_value*);
51055 const void * (*value_text16be)(sqlite3_value*);
51056 const void * (*value_text16le)(sqlite3_value*);
51057 int (*value_type)(sqlite3_value*);
51058 char *(*vmprintf)(const char*,va_list);
51059 int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
51060 int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
51061 int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
51062 int (*clear_bindings)(sqlite3_stmt*);
51066 ** The following macros redefine the API routines so that they are
51067 ** redirected throught the global sqlite3_api structure.
51069 ** This header file is also used by the loadext.c source file
51070 ** (part of the main SQLite library - not an extension) so that
51071 ** it can get access to the sqlite3_api_routines structure
51072 ** definition. But the main library does not want to redefine
51073 ** the API. So the redefinition macros are only valid if the
51074 ** SQLITE_CORE macros is undefined.
51076 #ifndef SQLITE_CORE
51077 #define sqlite3_aggregate_context sqlite3_api->aggregate_context
51078 #define sqlite3_aggregate_count sqlite3_api->aggregate_count
51079 #define sqlite3_bind_blob sqlite3_api->bind_blob
51080 #define sqlite3_bind_double sqlite3_api->bind_double
51081 #define sqlite3_bind_int sqlite3_api->bind_int
51082 #define sqlite3_bind_int64 sqlite3_api->bind_int64
51083 #define sqlite3_bind_null sqlite3_api->bind_null
51084 #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
51085 #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
51086 #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
51087 #define sqlite3_bind_text sqlite3_api->bind_text
51088 #define sqlite3_bind_text16 sqlite3_api->bind_text16
51089 #define sqlite3_bind_value sqlite3_api->bind_value
51090 #define sqlite3_busy_handler sqlite3_api->busy_handler
51091 #define sqlite3_busy_timeout sqlite3_api->busy_timeout
51092 #define sqlite3_changes sqlite3_api->changes
51093 #define sqlite3_close sqlite3_api->close
51094 #define sqlite3_collation_needed sqlite3_api->collation_needed
51095 #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
51096 #define sqlite3_column_blob sqlite3_api->column_blob
51097 #define sqlite3_column_bytes sqlite3_api->column_bytes
51098 #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
51099 #define sqlite3_column_count sqlite3_api->column_count
51100 #define sqlite3_column_database_name sqlite3_api->column_database_name
51101 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
51102 #define sqlite3_column_decltype sqlite3_api->column_decltype
51103 #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
51104 #define sqlite3_column_double sqlite3_api->column_double
51105 #define sqlite3_column_int sqlite3_api->column_int
51106 #define sqlite3_column_int64 sqlite3_api->column_int64
51107 #define sqlite3_column_name sqlite3_api->column_name
51108 #define sqlite3_column_name16 sqlite3_api->column_name16
51109 #define sqlite3_column_origin_name sqlite3_api->column_origin_name
51110 #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
51111 #define sqlite3_column_table_name sqlite3_api->column_table_name
51112 #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
51113 #define sqlite3_column_text sqlite3_api->column_text
51114 #define sqlite3_column_text16 sqlite3_api->column_text16
51115 #define sqlite3_column_type sqlite3_api->column_type
51116 #define sqlite3_column_value sqlite3_api->column_value
51117 #define sqlite3_commit_hook sqlite3_api->commit_hook
51118 #define sqlite3_complete sqlite3_api->complete
51119 #define sqlite3_complete16 sqlite3_api->complete16
51120 #define sqlite3_create_collation sqlite3_api->create_collation
51121 #define sqlite3_create_collation16 sqlite3_api->create_collation16
51122 #define sqlite3_create_function sqlite3_api->create_function
51123 #define sqlite3_create_function16 sqlite3_api->create_function16
51124 #define sqlite3_create_module sqlite3_api->create_module
51125 #define sqlite3_data_count sqlite3_api->data_count
51126 #define sqlite3_db_handle sqlite3_api->db_handle
51127 #define sqlite3_declare_vtab sqlite3_api->declare_vtab
51128 #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
51129 #define sqlite3_errcode sqlite3_api->errcode
51130 #define sqlite3_errmsg sqlite3_api->errmsg
51131 #define sqlite3_errmsg16 sqlite3_api->errmsg16
51132 #define sqlite3_exec sqlite3_api->exec
51133 #define sqlite3_expired sqlite3_api->expired
51134 #define sqlite3_finalize sqlite3_api->finalize
51135 #define sqlite3_free sqlite3_api->free
51136 #define sqlite3_free_table sqlite3_api->free_table
51137 #define sqlite3_get_autocommit sqlite3_api->get_autocommit
51138 #define sqlite3_get_auxdata sqlite3_api->get_auxdata
51139 #define sqlite3_get_table sqlite3_api->get_table
51140 #define sqlite3_global_recover sqlite3_api->global_recover
51141 #define sqlite3_interrupt sqlite3_api->interruptx
51142 #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
51143 #define sqlite3_libversion sqlite3_api->libversion
51144 #define sqlite3_libversion_number sqlite3_api->libversion_number
51145 #define sqlite3_malloc sqlite3_api->malloc
51146 #define sqlite3_mprintf sqlite3_api->mprintf
51147 #define sqlite3_open sqlite3_api->open
51148 #define sqlite3_open16 sqlite3_api->open16
51149 #define sqlite3_prepare sqlite3_api->prepare
51150 #define sqlite3_prepare16 sqlite3_api->prepare16
51151 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
51152 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
51153 #define sqlite3_profile sqlite3_api->profile
51154 #define sqlite3_progress_handler sqlite3_api->progress_handler
51155 #define sqlite3_realloc sqlite3_api->realloc
51156 #define sqlite3_reset sqlite3_api->reset
51157 #define sqlite3_result_blob sqlite3_api->result_blob
51158 #define sqlite3_result_double sqlite3_api->result_double
51159 #define sqlite3_result_error sqlite3_api->result_error
51160 #define sqlite3_result_error16 sqlite3_api->result_error16
51161 #define sqlite3_result_int sqlite3_api->result_int
51162 #define sqlite3_result_int64 sqlite3_api->result_int64
51163 #define sqlite3_result_null sqlite3_api->result_null
51164 #define sqlite3_result_text sqlite3_api->result_text
51165 #define sqlite3_result_text16 sqlite3_api->result_text16
51166 #define sqlite3_result_text16be sqlite3_api->result_text16be
51167 #define sqlite3_result_text16le sqlite3_api->result_text16le
51168 #define sqlite3_result_value sqlite3_api->result_value
51169 #define sqlite3_rollback_hook sqlite3_api->rollback_hook
51170 #define sqlite3_set_authorizer sqlite3_api->set_authorizer
51171 #define sqlite3_set_auxdata sqlite3_api->set_auxdata
51172 #define sqlite3_snprintf sqlite3_api->snprintf
51173 #define sqlite3_step sqlite3_api->step
51174 #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
51175 #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
51176 #define sqlite3_total_changes sqlite3_api->total_changes
51177 #define sqlite3_trace sqlite3_api->trace
51178 #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
51179 #define sqlite3_update_hook sqlite3_api->update_hook
51180 #define sqlite3_user_data sqlite3_api->user_data
51181 #define sqlite3_value_blob sqlite3_api->value_blob
51182 #define sqlite3_value_bytes sqlite3_api->value_bytes
51183 #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
51184 #define sqlite3_value_double sqlite3_api->value_double
51185 #define sqlite3_value_int sqlite3_api->value_int
51186 #define sqlite3_value_int64 sqlite3_api->value_int64
51187 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
51188 #define sqlite3_value_text sqlite3_api->value_text
51189 #define sqlite3_value_text16 sqlite3_api->value_text16
51190 #define sqlite3_value_text16be sqlite3_api->value_text16be
51191 #define sqlite3_value_text16le sqlite3_api->value_text16le
51192 #define sqlite3_value_type sqlite3_api->value_type
51193 #define sqlite3_vmprintf sqlite3_api->vmprintf
51194 #define sqlite3_overload_function sqlite3_api->overload_function
51195 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
51196 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
51197 #define sqlite3_clear_bindings sqlite3_api->clear_bindings
51198 #endif /* SQLITE_CORE */
51200 #define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api;
51201 #define SQLITE_EXTENSION_INIT2(v) sqlite3_api = v;
51203 #endif /* _SQLITE3EXT_H_ */
51205 /************** End of sqlite3ext.h ******************************************/
51206 /************** Continuing where we left off in loadext.c ********************/
51209 ** Some API routines are omitted when various features are
51210 ** excluded from a build of SQLite. Substitute a NULL pointer
51211 ** for any missing APIs.
51213 #ifndef SQLITE_ENABLE_COLUMN_METADATA
51214 # define sqlite3_column_database_name 0
51215 # define sqlite3_column_database_name16 0
51216 # define sqlite3_column_table_name 0
51217 # define sqlite3_column_table_name16 0
51218 # define sqlite3_column_origin_name 0
51219 # define sqlite3_column_origin_name16 0
51220 # define sqlite3_table_column_metadata 0
51221 #endif
51223 #ifdef SQLITE_OMIT_AUTHORIZATION
51224 # define sqlite3_set_authorizer 0
51225 #endif
51227 #ifdef SQLITE_OMIT_UTF16
51228 # define sqlite3_bind_text16 0
51229 # define sqlite3_collation_needed16 0
51230 # define sqlite3_column_decltype16 0
51231 # define sqlite3_column_name16 0
51232 # define sqlite3_column_text16 0
51233 # define sqlite3_complete16 0
51234 # define sqlite3_create_collation16 0
51235 # define sqlite3_create_function16 0
51236 # define sqlite3_errmsg16 0
51237 # define sqlite3_open16 0
51238 # define sqlite3_prepare16 0
51239 # define sqlite3_prepare16_v2 0
51240 # define sqlite3_result_error16 0
51241 # define sqlite3_result_text16 0
51242 # define sqlite3_result_text16be 0
51243 # define sqlite3_result_text16le 0
51244 # define sqlite3_value_text16 0
51245 # define sqlite3_value_text16be 0
51246 # define sqlite3_value_text16le 0
51247 # define sqlite3_column_database_name16 0
51248 # define sqlite3_column_table_name16 0
51249 # define sqlite3_column_origin_name16 0
51250 #endif
51252 #ifdef SQLITE_OMIT_COMPLETE
51253 # define sqlite3_complete 0
51254 # define sqlite3_complete16 0
51255 #endif
51257 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
51258 # define sqlite3_progress_handler 0
51259 #endif
51261 #ifdef SQLITE_OMIT_VIRTUALTABLE
51262 # define sqlite3_create_module 0
51263 # define sqlite3_declare_vtab 0
51264 #endif
51266 #ifdef SQLITE_OMIT_SHARED_CACHE
51267 # define sqlite3_enable_shared_cache 0
51268 #endif
51270 #ifdef SQLITE_OMIT_TRACE
51271 # define sqlite3_profile 0
51272 # define sqlite3_trace 0
51273 #endif
51275 #ifdef SQLITE_OMIT_GET_TABLE
51276 # define sqlite3_free_table 0
51277 # define sqlite3_get_table 0
51278 #endif
51281 ** The following structure contains pointers to all SQLite API routines.
51282 ** A pointer to this structure is passed into extensions when they are
51283 ** loaded so that the extension can make calls back into the SQLite
51284 ** library.
51286 ** When adding new APIs, add them to the bottom of this structure
51287 ** in order to preserve backwards compatibility.
51289 ** Extensions that use newer APIs should first call the
51290 ** sqlite3_libversion_number() to make sure that the API they
51291 ** intend to use is supported by the library. Extensions should
51292 ** also check to make sure that the pointer to the function is
51293 ** not NULL before calling it.
51295 const sqlite3_api_routines sqlite3_apis = {
51296 sqlite3_aggregate_context,
51297 sqlite3_aggregate_count,
51298 sqlite3_bind_blob,
51299 sqlite3_bind_double,
51300 sqlite3_bind_int,
51301 sqlite3_bind_int64,
51302 sqlite3_bind_null,
51303 sqlite3_bind_parameter_count,
51304 sqlite3_bind_parameter_index,
51305 sqlite3_bind_parameter_name,
51306 sqlite3_bind_text,
51307 sqlite3_bind_text16,
51308 sqlite3_bind_value,
51309 sqlite3_busy_handler,
51310 sqlite3_busy_timeout,
51311 sqlite3_changes,
51312 sqlite3_close,
51313 sqlite3_collation_needed,
51314 sqlite3_collation_needed16,
51315 sqlite3_column_blob,
51316 sqlite3_column_bytes,
51317 sqlite3_column_bytes16,
51318 sqlite3_column_count,
51319 sqlite3_column_database_name,
51320 sqlite3_column_database_name16,
51321 sqlite3_column_decltype,
51322 sqlite3_column_decltype16,
51323 sqlite3_column_double,
51324 sqlite3_column_int,
51325 sqlite3_column_int64,
51326 sqlite3_column_name,
51327 sqlite3_column_name16,
51328 sqlite3_column_origin_name,
51329 sqlite3_column_origin_name16,
51330 sqlite3_column_table_name,
51331 sqlite3_column_table_name16,
51332 sqlite3_column_text,
51333 sqlite3_column_text16,
51334 sqlite3_column_type,
51335 sqlite3_column_value,
51336 sqlite3_commit_hook,
51337 sqlite3_complete,
51338 sqlite3_complete16,
51339 sqlite3_create_collation,
51340 sqlite3_create_collation16,
51341 sqlite3_create_function,
51342 sqlite3_create_function16,
51343 sqlite3_create_module,
51344 sqlite3_data_count,
51345 sqlite3_db_handle,
51346 sqlite3_declare_vtab,
51347 sqlite3_enable_shared_cache,
51348 sqlite3_errcode,
51349 sqlite3_errmsg,
51350 sqlite3_errmsg16,
51351 sqlite3_exec,
51352 sqlite3_expired,
51353 sqlite3_finalize,
51354 sqlite3_free,
51355 sqlite3_free_table,
51356 sqlite3_get_autocommit,
51357 sqlite3_get_auxdata,
51358 sqlite3_get_table,
51359 0, /* Was sqlite3_global_recover(), but that function is deprecated */
51360 sqlite3_interrupt,
51361 sqlite3_last_insert_rowid,
51362 sqlite3_libversion,
51363 sqlite3_libversion_number,
51364 sqlite3_malloc,
51365 sqlite3_mprintf,
51366 sqlite3_open,
51367 sqlite3_open16,
51368 sqlite3_prepare,
51369 sqlite3_prepare16,
51370 sqlite3_profile,
51371 sqlite3_progress_handler,
51372 sqlite3_realloc,
51373 sqlite3_reset,
51374 sqlite3_result_blob,
51375 sqlite3_result_double,
51376 sqlite3_result_error,
51377 sqlite3_result_error16,
51378 sqlite3_result_int,
51379 sqlite3_result_int64,
51380 sqlite3_result_null,
51381 sqlite3_result_text,
51382 sqlite3_result_text16,
51383 sqlite3_result_text16be,
51384 sqlite3_result_text16le,
51385 sqlite3_result_value,
51386 sqlite3_rollback_hook,
51387 sqlite3_set_authorizer,
51388 sqlite3_set_auxdata,
51389 sqlite3_snprintf,
51390 sqlite3_step,
51391 sqlite3_table_column_metadata,
51392 sqlite3_thread_cleanup,
51393 sqlite3_total_changes,
51394 sqlite3_trace,
51395 sqlite3_transfer_bindings,
51396 sqlite3_update_hook,
51397 sqlite3_user_data,
51398 sqlite3_value_blob,
51399 sqlite3_value_bytes,
51400 sqlite3_value_bytes16,
51401 sqlite3_value_double,
51402 sqlite3_value_int,
51403 sqlite3_value_int64,
51404 sqlite3_value_numeric_type,
51405 sqlite3_value_text,
51406 sqlite3_value_text16,
51407 sqlite3_value_text16be,
51408 sqlite3_value_text16le,
51409 sqlite3_value_type,
51410 sqlite3_vmprintf,
51412 ** The original API set ends here. All extensions can call any
51413 ** of the APIs above provided that the pointer is not NULL. But
51414 ** before calling APIs that follow, extension should check the
51415 ** sqlite3_libversion_number() to make sure they are dealing with
51416 ** a library that is new enough to support that API.
51417 *************************************************************************
51419 sqlite3_overload_function,
51422 ** Added after 3.3.13
51424 sqlite3_prepare_v2,
51425 sqlite3_prepare16_v2,
51426 sqlite3_clear_bindings,
51430 ** Attempt to load an SQLite extension library contained in the file
51431 ** zFile. The entry point is zProc. zProc may be 0 in which case a
51432 ** default entry point name (sqlite3_extension_init) is used. Use
51433 ** of the default name is recommended.
51435 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
51437 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
51438 ** error message text. The calling function should free this memory
51439 ** by calling sqlite3_free().
51441 int sqlite3_load_extension(
51442 sqlite3 *db, /* Load the extension into this database connection */
51443 const char *zFile, /* Name of the shared library containing extension */
51444 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
51445 char **pzErrMsg /* Put error message here if not 0 */
51447 void *handle;
51448 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
51449 char *zErrmsg = 0;
51450 void **aHandle;
51452 /* Ticket #1863. To avoid a creating security problems for older
51453 ** applications that relink against newer versions of SQLite, the
51454 ** ability to run load_extension is turned off by default. One
51455 ** must call sqlite3_enable_load_extension() to turn on extension
51456 ** loading. Otherwise you get the following error.
51458 if( (db->flags & SQLITE_LoadExtension)==0 ){
51459 if( pzErrMsg ){
51460 *pzErrMsg = sqlite3_mprintf("not authorized");
51462 return SQLITE_ERROR;
51465 if( zProc==0 ){
51466 zProc = "sqlite3_extension_init";
51469 handle = sqlite3OsDlopen(zFile);
51470 if( handle==0 ){
51471 if( pzErrMsg ){
51472 *pzErrMsg = sqlite3_mprintf("unable to open shared library [%s]", zFile);
51474 return SQLITE_ERROR;
51476 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
51477 sqlite3OsDlsym(handle, zProc);
51478 if( xInit==0 ){
51479 if( pzErrMsg ){
51480 *pzErrMsg = sqlite3_mprintf("no entry point [%s] in shared library [%s]",
51481 zProc, zFile);
51483 sqlite3OsDlclose(handle);
51484 return SQLITE_ERROR;
51485 }else if( xInit(db, &zErrmsg, &sqlite3_apis) ){
51486 if( pzErrMsg ){
51487 *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
51489 sqlite3_free(zErrmsg);
51490 sqlite3OsDlclose(handle);
51491 return SQLITE_ERROR;
51494 /* Append the new shared library handle to the db->aExtension array. */
51495 db->nExtension++;
51496 aHandle = sqliteMalloc(sizeof(handle)*db->nExtension);
51497 if( aHandle==0 ){
51498 return SQLITE_NOMEM;
51500 if( db->nExtension>0 ){
51501 memcpy(aHandle, db->aExtension, sizeof(handle)*(db->nExtension-1));
51503 sqliteFree(db->aExtension);
51504 db->aExtension = aHandle;
51506 db->aExtension[db->nExtension-1] = handle;
51507 return SQLITE_OK;
51511 ** Call this routine when the database connection is closing in order
51512 ** to clean up loaded extensions
51514 static void sqlite3CloseExtensions(sqlite3 *db){
51515 int i;
51516 for(i=0; i<db->nExtension; i++){
51517 sqlite3OsDlclose(db->aExtension[i]);
51519 sqliteFree(db->aExtension);
51523 ** Enable or disable extension loading. Extension loading is disabled by
51524 ** default so as not to open security holes in older applications.
51526 int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
51527 if( onoff ){
51528 db->flags |= SQLITE_LoadExtension;
51529 }else{
51530 db->flags &= ~SQLITE_LoadExtension;
51532 return SQLITE_OK;
51536 ** A list of automatically loaded extensions.
51538 ** This list is shared across threads, so be sure to hold the
51539 ** mutex while accessing or changing it.
51541 static int nAutoExtension = 0;
51542 static void **aAutoExtension = 0;
51546 ** Register a statically linked extension that is automatically
51547 ** loaded by every new database connection.
51549 int sqlite3_auto_extension(void *xInit){
51550 int i;
51551 int rc = SQLITE_OK;
51552 sqlite3OsEnterMutex();
51553 for(i=0; i<nAutoExtension; i++){
51554 if( aAutoExtension[i]==xInit ) break;
51556 if( i==nAutoExtension ){
51557 nAutoExtension++;
51558 aAutoExtension = sqlite3Realloc( aAutoExtension,
51559 nAutoExtension*sizeof(aAutoExtension[0]) );
51560 if( aAutoExtension==0 ){
51561 nAutoExtension = 0;
51562 rc = SQLITE_NOMEM;
51563 }else{
51564 aAutoExtension[nAutoExtension-1] = xInit;
51567 sqlite3OsLeaveMutex();
51568 assert( (rc&0xff)==rc );
51569 return rc;
51573 ** Reset the automatic extension loading mechanism.
51575 void sqlite3_reset_auto_extension(void){
51576 sqlite3OsEnterMutex();
51577 sqliteFree(aAutoExtension);
51578 aAutoExtension = 0;
51579 nAutoExtension = 0;
51580 sqlite3OsLeaveMutex();
51584 ** Load all automatic extensions.
51586 static int sqlite3AutoLoadExtensions(sqlite3 *db){
51587 int i;
51588 int go = 1;
51589 int rc = SQLITE_OK;
51590 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
51592 if( nAutoExtension==0 ){
51593 /* Common case: early out without every having to acquire a mutex */
51594 return SQLITE_OK;
51596 for(i=0; go; i++){
51597 char *zErrmsg = 0;
51598 sqlite3OsEnterMutex();
51599 if( i>=nAutoExtension ){
51600 xInit = 0;
51601 go = 0;
51602 }else{
51603 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
51604 aAutoExtension[i];
51606 sqlite3OsLeaveMutex();
51607 if( xInit && xInit(db, &zErrmsg, &sqlite3_apis) ){
51608 sqlite3Error(db, SQLITE_ERROR,
51609 "automatic extension loading failed: %s", zErrmsg);
51610 go = 0;
51611 rc = SQLITE_ERROR;
51614 return rc;
51617 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
51619 /************** End of loadext.c *********************************************/
51620 /************** Begin file pragma.c ******************************************/
51622 ** 2003 April 6
51624 ** The author disclaims copyright to this source code. In place of
51625 ** a legal notice, here is a blessing:
51627 ** May you do good and not evil.
51628 ** May you find forgiveness for yourself and forgive others.
51629 ** May you share freely, never taking more than you give.
51631 *************************************************************************
51632 ** This file contains code used to implement the PRAGMA command.
51634 ** $Id: pragma.c,v 1.139 2007/05/23 13:50:24 danielk1977 Exp $
51637 /* Ignore this whole file if pragmas are disabled
51639 #if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)
51641 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
51642 #endif
51645 ** Interpret the given string as a safety level. Return 0 for OFF,
51646 ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
51647 ** unrecognized string argument.
51649 ** Note that the values returned are one less that the values that
51650 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
51651 ** to support legacy SQL code. The safety level used to be boolean
51652 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
51654 static int getSafetyLevel(const char *z){
51655 /* 123456789 123456789 */
51656 static const char zText[] = "onoffalseyestruefull";
51657 static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
51658 static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
51659 static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
51660 int i, n;
51661 if( isdigit(*z) ){
51662 return atoi(z);
51664 n = strlen(z);
51665 for(i=0; i<sizeof(iLength); i++){
51666 if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
51667 return iValue[i];
51670 return 1;
51674 ** Interpret the given string as a boolean value.
51676 static int getBoolean(const char *z){
51677 return getSafetyLevel(z)&1;
51681 ** Interpret the given string as a locking mode value.
51683 static int getLockingMode(const char *z){
51684 if( z ){
51685 if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
51686 if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
51688 return PAGER_LOCKINGMODE_QUERY;
51691 #ifndef SQLITE_OMIT_AUTOVACUUM
51693 ** Interpret the given string as an auto-vacuum mode value.
51695 ** The following strings, "none", "full" and "incremental" are
51696 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
51698 static int getAutoVacuum(const char *z){
51699 int i;
51700 if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
51701 if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
51702 if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
51703 i = atoi(z);
51704 return ((i>=0&&i<=2)?i:0);
51706 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
51708 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
51710 ** Interpret the given string as a temp db location. Return 1 for file
51711 ** backed temporary databases, 2 for the Red-Black tree in memory database
51712 ** and 0 to use the compile-time default.
51714 static int getTempStore(const char *z){
51715 if( z[0]>='0' && z[0]<='2' ){
51716 return z[0] - '0';
51717 }else if( sqlite3StrICmp(z, "file")==0 ){
51718 return 1;
51719 }else if( sqlite3StrICmp(z, "memory")==0 ){
51720 return 2;
51721 }else{
51722 return 0;
51725 #endif /* SQLITE_PAGER_PRAGMAS */
51727 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
51729 ** Invalidate temp storage, either when the temp storage is changed
51730 ** from default, or when 'file' and the temp_store_directory has changed
51732 static int invalidateTempStorage(Parse *pParse){
51733 sqlite3 *db = pParse->db;
51734 if( db->aDb[1].pBt!=0 ){
51735 if( !db->autoCommit ){
51736 sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
51737 "from within a transaction");
51738 return SQLITE_ERROR;
51740 sqlite3BtreeClose(db->aDb[1].pBt);
51741 db->aDb[1].pBt = 0;
51742 sqlite3ResetInternalSchema(db, 0);
51744 return SQLITE_OK;
51746 #endif /* SQLITE_PAGER_PRAGMAS */
51748 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
51750 ** If the TEMP database is open, close it and mark the database schema
51751 ** as needing reloading. This must be done when using the TEMP_STORE
51752 ** or DEFAULT_TEMP_STORE pragmas.
51754 static int changeTempStorage(Parse *pParse, const char *zStorageType){
51755 int ts = getTempStore(zStorageType);
51756 sqlite3 *db = pParse->db;
51757 if( db->temp_store==ts ) return SQLITE_OK;
51758 if( invalidateTempStorage( pParse ) != SQLITE_OK ){
51759 return SQLITE_ERROR;
51761 db->temp_store = ts;
51762 return SQLITE_OK;
51764 #endif /* SQLITE_PAGER_PRAGMAS */
51767 ** Generate code to return a single integer value.
51769 static void returnSingleInt(Parse *pParse, const char *zLabel, int value){
51770 Vdbe *v = sqlite3GetVdbe(pParse);
51771 sqlite3VdbeAddOp(v, OP_Integer, value, 0);
51772 if( pParse->explain==0 ){
51773 sqlite3VdbeSetNumCols(v, 1);
51774 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, P3_STATIC);
51776 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
51779 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
51781 ** Check to see if zRight and zLeft refer to a pragma that queries
51782 ** or changes one of the flags in db->flags. Return 1 if so and 0 if not.
51783 ** Also, implement the pragma.
51785 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
51786 static const struct sPragmaType {
51787 const char *zName; /* Name of the pragma */
51788 int mask; /* Mask for the db->flags value */
51789 } aPragma[] = {
51790 { "full_column_names", SQLITE_FullColNames },
51791 { "short_column_names", SQLITE_ShortColNames },
51792 { "count_changes", SQLITE_CountRows },
51793 { "empty_result_callbacks", SQLITE_NullCallback },
51794 { "legacy_file_format", SQLITE_LegacyFileFmt },
51795 { "fullfsync", SQLITE_FullFSync },
51796 #ifdef SQLITE_DEBUG
51797 { "sql_trace", SQLITE_SqlTrace },
51798 { "vdbe_listing", SQLITE_VdbeListing },
51799 { "vdbe_trace", SQLITE_VdbeTrace },
51800 #endif
51801 #ifndef SQLITE_OMIT_CHECK
51802 { "ignore_check_constraints", SQLITE_IgnoreChecks },
51803 #endif
51804 /* The following is VERY experimental */
51805 { "writable_schema", SQLITE_WriteSchema|SQLITE_RecoveryMode },
51806 { "omit_readlock", SQLITE_NoReadlock },
51808 /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
51809 ** flag if there are any active statements. */
51810 { "read_uncommitted", SQLITE_ReadUncommitted },
51812 int i;
51813 const struct sPragmaType *p;
51814 for(i=0, p=aPragma; i<sizeof(aPragma)/sizeof(aPragma[0]); i++, p++){
51815 if( sqlite3StrICmp(zLeft, p->zName)==0 ){
51816 sqlite3 *db = pParse->db;
51817 Vdbe *v;
51818 v = sqlite3GetVdbe(pParse);
51819 if( v ){
51820 if( zRight==0 ){
51821 returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
51822 }else{
51823 if( getBoolean(zRight) ){
51824 db->flags |= p->mask;
51825 }else{
51826 db->flags &= ~p->mask;
51830 return 1;
51833 return 0;
51835 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
51838 ** Process a pragma statement.
51840 ** Pragmas are of this form:
51842 ** PRAGMA [database.]id [= value]
51844 ** The identifier might also be a string. The value is a string, and
51845 ** identifier, or a number. If minusFlag is true, then the value is
51846 ** a number that was preceded by a minus sign.
51848 ** If the left side is "database.id" then pId1 is the database name
51849 ** and pId2 is the id. If the left side is just "id" then pId1 is the
51850 ** id and pId2 is any empty string.
51852 static void sqlite3Pragma(
51853 Parse *pParse,
51854 Token *pId1, /* First part of [database.]id field */
51855 Token *pId2, /* Second part of [database.]id field, or NULL */
51856 Token *pValue, /* Token for <value>, or NULL */
51857 int minusFlag /* True if a '-' sign preceded <value> */
51859 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
51860 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
51861 const char *zDb = 0; /* The database name */
51862 Token *pId; /* Pointer to <id> token */
51863 int iDb; /* Database index for <database> */
51864 sqlite3 *db = pParse->db;
51865 Db *pDb;
51866 Vdbe *v = sqlite3GetVdbe(pParse);
51867 if( v==0 ) return;
51869 /* Interpret the [database.] part of the pragma statement. iDb is the
51870 ** index of the database this pragma is being applied to in db.aDb[]. */
51871 iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
51872 if( iDb<0 ) return;
51873 pDb = &db->aDb[iDb];
51875 /* If the temp database has been explicitly named as part of the
51876 ** pragma, make sure it is open.
51878 if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
51879 return;
51882 zLeft = sqlite3NameFromToken(pId);
51883 if( !zLeft ) return;
51884 if( minusFlag ){
51885 zRight = sqlite3MPrintf("-%T", pValue);
51886 }else{
51887 zRight = sqlite3NameFromToken(pValue);
51890 zDb = ((iDb>0)?pDb->zName:0);
51891 if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
51892 goto pragma_out;
51895 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
51897 ** PRAGMA [database.]default_cache_size
51898 ** PRAGMA [database.]default_cache_size=N
51900 ** The first form reports the current persistent setting for the
51901 ** page cache size. The value returned is the maximum number of
51902 ** pages in the page cache. The second form sets both the current
51903 ** page cache size value and the persistent page cache size value
51904 ** stored in the database file.
51906 ** The default cache size is stored in meta-value 2 of page 1 of the
51907 ** database file. The cache size is actually the absolute value of
51908 ** this memory location. The sign of meta-value 2 determines the
51909 ** synchronous setting. A negative value means synchronous is off
51910 ** and a positive value means synchronous is on.
51912 if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
51913 static const VdbeOpList getCacheSize[] = {
51914 { OP_ReadCookie, 0, 2, 0}, /* 0 */
51915 { OP_AbsValue, 0, 0, 0},
51916 { OP_Dup, 0, 0, 0},
51917 { OP_Integer, 0, 0, 0},
51918 { OP_Ne, 0, 6, 0},
51919 { OP_Integer, 0, 0, 0}, /* 5 */
51920 { OP_Callback, 1, 0, 0},
51922 int addr;
51923 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
51924 if( !zRight ){
51925 sqlite3VdbeSetNumCols(v, 1);
51926 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", P3_STATIC);
51927 addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
51928 sqlite3VdbeChangeP1(v, addr, iDb);
51929 sqlite3VdbeChangeP1(v, addr+5, SQLITE_DEFAULT_CACHE_SIZE);
51930 }else{
51931 int size = atoi(zRight);
51932 if( size<0 ) size = -size;
51933 sqlite3BeginWriteOperation(pParse, 0, iDb);
51934 sqlite3VdbeAddOp(v, OP_Integer, size, 0);
51935 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 2);
51936 addr = sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
51937 sqlite3VdbeAddOp(v, OP_Ge, 0, addr+3);
51938 sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
51939 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 2);
51940 pDb->pSchema->cache_size = size;
51941 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
51943 }else
51946 ** PRAGMA [database.]page_size
51947 ** PRAGMA [database.]page_size=N
51949 ** The first form reports the current setting for the
51950 ** database page size in bytes. The second form sets the
51951 ** database page size value. The value can only be set if
51952 ** the database has not yet been created.
51954 if( sqlite3StrICmp(zLeft,"page_size")==0 ){
51955 Btree *pBt = pDb->pBt;
51956 if( !zRight ){
51957 int size = pBt ? sqlite3BtreeGetPageSize(pBt) : 0;
51958 returnSingleInt(pParse, "page_size", size);
51959 }else{
51960 sqlite3BtreeSetPageSize(pBt, atoi(zRight), -1);
51962 }else
51965 ** PRAGMA [database.]max_page_count
51966 ** PRAGMA [database.]max_page_count=N
51968 ** The first form reports the current setting for the
51969 ** maximum number of pages in the database file. The
51970 ** second form attempts to change this setting. Both
51971 ** forms return the current setting.
51973 if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
51974 Btree *pBt = pDb->pBt;
51975 int newMax = 0;
51976 if( zRight ){
51977 newMax = atoi(zRight);
51979 if( pBt ){
51980 newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
51982 returnSingleInt(pParse, "max_page_count", newMax);
51983 }else
51986 ** PRAGMA [database.]locking_mode
51987 ** PRAGMA [database.]locking_mode = (normal|exclusive)
51989 if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
51990 const char *zRet = "normal";
51991 int eMode = getLockingMode(zRight);
51993 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
51994 /* Simple "PRAGMA locking_mode;" statement. This is a query for
51995 ** the current default locking mode (which may be different to
51996 ** the locking-mode of the main database).
51998 eMode = db->dfltLockMode;
51999 }else{
52000 Pager *pPager;
52001 if( pId2->n==0 ){
52002 /* This indicates that no database name was specified as part
52003 ** of the PRAGMA command. In this case the locking-mode must be
52004 ** set on all attached databases, as well as the main db file.
52006 ** Also, the sqlite3.dfltLockMode variable is set so that
52007 ** any subsequently attached databases also use the specified
52008 ** locking mode.
52010 int ii;
52011 assert(pDb==&db->aDb[0]);
52012 for(ii=2; ii<db->nDb; ii++){
52013 pPager = sqlite3BtreePager(db->aDb[ii].pBt);
52014 sqlite3PagerLockingMode(pPager, eMode);
52016 db->dfltLockMode = eMode;
52018 pPager = sqlite3BtreePager(pDb->pBt);
52019 eMode = sqlite3PagerLockingMode(pPager, eMode);
52022 assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
52023 if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
52024 zRet = "exclusive";
52026 sqlite3VdbeSetNumCols(v, 1);
52027 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", P3_STATIC);
52028 sqlite3VdbeOp3(v, OP_String8, 0, 0, zRet, 0);
52029 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
52030 }else
52031 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
52034 ** PRAGMA [database.]auto_vacuum
52035 ** PRAGMA [database.]auto_vacuum=N
52037 ** Get or set the (boolean) value of the database 'auto-vacuum' parameter.
52039 #ifndef SQLITE_OMIT_AUTOVACUUM
52040 if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
52041 Btree *pBt = pDb->pBt;
52042 if( !zRight ){
52043 int auto_vacuum =
52044 pBt ? sqlite3BtreeGetAutoVacuum(pBt) : SQLITE_DEFAULT_AUTOVACUUM;
52045 returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
52046 }else{
52047 int eAuto = getAutoVacuum(zRight);
52048 if( eAuto>=0 ){
52049 sqlite3BtreeSetAutoVacuum(pBt, eAuto);
52052 }else
52053 #endif
52056 ** PRAGMA [database.]incremental_vacuum(N)
52058 ** Do N steps of incremental vacuuming on a database.
52060 #ifndef SQLITE_OMIT_AUTOVACUUM
52061 if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
52062 int iLimit, addr;
52063 if( sqlite3ReadSchema(pParse) ){
52064 goto pragma_out;
52066 if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
52067 iLimit = 0x7fffffff;
52069 sqlite3BeginWriteOperation(pParse, 0, iDb);
52070 sqlite3VdbeAddOp(v, OP_MemInt, iLimit, 0);
52071 addr = sqlite3VdbeAddOp(v, OP_IncrVacuum, iDb, 0);
52072 sqlite3VdbeAddOp(v, OP_Callback, 0, 0);
52073 sqlite3VdbeAddOp(v, OP_MemIncr, -1, 0);
52074 sqlite3VdbeAddOp(v, OP_IfMemPos, 0, addr);
52075 sqlite3VdbeJumpHere(v, addr);
52076 }else
52077 #endif
52079 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
52081 ** PRAGMA [database.]cache_size
52082 ** PRAGMA [database.]cache_size=N
52084 ** The first form reports the current local setting for the
52085 ** page cache size. The local setting can be different from
52086 ** the persistent cache size value that is stored in the database
52087 ** file itself. The value returned is the maximum number of
52088 ** pages in the page cache. The second form sets the local
52089 ** page cache size value. It does not change the persistent
52090 ** cache size stored on the disk so the cache size will revert
52091 ** to its default value when the database is closed and reopened.
52092 ** N should be a positive integer.
52094 if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
52095 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
52096 if( !zRight ){
52097 returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
52098 }else{
52099 int size = atoi(zRight);
52100 if( size<0 ) size = -size;
52101 pDb->pSchema->cache_size = size;
52102 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
52104 }else
52107 ** PRAGMA temp_store
52108 ** PRAGMA temp_store = "default"|"memory"|"file"
52110 ** Return or set the local value of the temp_store flag. Changing
52111 ** the local value does not make changes to the disk file and the default
52112 ** value will be restored the next time the database is opened.
52114 ** Note that it is possible for the library compile-time options to
52115 ** override this setting
52117 if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
52118 if( !zRight ){
52119 returnSingleInt(pParse, "temp_store", db->temp_store);
52120 }else{
52121 changeTempStorage(pParse, zRight);
52123 }else
52126 ** PRAGMA temp_store_directory
52127 ** PRAGMA temp_store_directory = ""|"directory_name"
52129 ** Return or set the local value of the temp_store_directory flag. Changing
52130 ** the value sets a specific directory to be used for temporary files.
52131 ** Setting to a null string reverts to the default temporary directory search.
52132 ** If temporary directory is changed, then invalidateTempStorage.
52135 if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
52136 if( !zRight ){
52137 if( sqlite3_temp_directory ){
52138 sqlite3VdbeSetNumCols(v, 1);
52139 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
52140 "temp_store_directory", P3_STATIC);
52141 sqlite3VdbeOp3(v, OP_String8, 0, 0, sqlite3_temp_directory, 0);
52142 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
52144 }else{
52145 if( zRight[0] && !sqlite3OsIsDirWritable(zRight) ){
52146 sqlite3ErrorMsg(pParse, "not a writable directory");
52147 goto pragma_out;
52149 if( TEMP_STORE==0
52150 || (TEMP_STORE==1 && db->temp_store<=1)
52151 || (TEMP_STORE==2 && db->temp_store==1)
52153 invalidateTempStorage(pParse);
52155 sqliteFree(sqlite3_temp_directory);
52156 if( zRight[0] ){
52157 sqlite3_temp_directory = zRight;
52158 zRight = 0;
52159 }else{
52160 sqlite3_temp_directory = 0;
52163 }else
52166 ** PRAGMA [database.]synchronous
52167 ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
52169 ** Return or set the local value of the synchronous flag. Changing
52170 ** the local value does not make changes to the disk file and the
52171 ** default value will be restored the next time the database is
52172 ** opened.
52174 if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
52175 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
52176 if( !zRight ){
52177 returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
52178 }else{
52179 if( !db->autoCommit ){
52180 sqlite3ErrorMsg(pParse,
52181 "Safety level may not be changed inside a transaction");
52182 }else{
52183 pDb->safety_level = getSafetyLevel(zRight)+1;
52186 }else
52187 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
52189 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
52190 if( flagPragma(pParse, zLeft, zRight) ){
52191 /* The flagPragma() subroutine also generates any necessary code
52192 ** there is nothing more to do here */
52193 }else
52194 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
52196 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
52198 ** PRAGMA table_info(<table>)
52200 ** Return a single row for each column of the named table. The columns of
52201 ** the returned data set are:
52203 ** cid: Column id (numbered from left to right, starting at 0)
52204 ** name: Column name
52205 ** type: Column declaration type.
52206 ** notnull: True if 'NOT NULL' is part of column declaration
52207 ** dflt_value: The default value for the column, if any.
52209 if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
52210 Table *pTab;
52211 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
52212 pTab = sqlite3FindTable(db, zRight, zDb);
52213 if( pTab ){
52214 int i;
52215 Column *pCol;
52216 sqlite3VdbeSetNumCols(v, 6);
52217 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", P3_STATIC);
52218 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC);
52219 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", P3_STATIC);
52220 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", P3_STATIC);
52221 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", P3_STATIC);
52222 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", P3_STATIC);
52223 sqlite3ViewGetColumnNames(pParse, pTab);
52224 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
52225 const Token *pDflt;
52226 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
52227 sqlite3VdbeOp3(v, OP_String8, 0, 0, pCol->zName, 0);
52228 sqlite3VdbeOp3(v, OP_String8, 0, 0,
52229 pCol->zType ? pCol->zType : "", 0);
52230 sqlite3VdbeAddOp(v, OP_Integer, pCol->notNull, 0);
52231 if( pCol->pDflt && (pDflt = &pCol->pDflt->span)->z ){
52232 sqlite3VdbeOp3(v, OP_String8, 0, 0, (char*)pDflt->z, pDflt->n);
52233 }else{
52234 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
52236 sqlite3VdbeAddOp(v, OP_Integer, pCol->isPrimKey, 0);
52237 sqlite3VdbeAddOp(v, OP_Callback, 6, 0);
52240 }else
52242 if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
52243 Index *pIdx;
52244 Table *pTab;
52245 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
52246 pIdx = sqlite3FindIndex(db, zRight, zDb);
52247 if( pIdx ){
52248 int i;
52249 pTab = pIdx->pTable;
52250 sqlite3VdbeSetNumCols(v, 3);
52251 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", P3_STATIC);
52252 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", P3_STATIC);
52253 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", P3_STATIC);
52254 for(i=0; i<pIdx->nColumn; i++){
52255 int cnum = pIdx->aiColumn[i];
52256 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
52257 sqlite3VdbeAddOp(v, OP_Integer, cnum, 0);
52258 assert( pTab->nCol>cnum );
52259 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->aCol[cnum].zName, 0);
52260 sqlite3VdbeAddOp(v, OP_Callback, 3, 0);
52263 }else
52265 if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
52266 Index *pIdx;
52267 Table *pTab;
52268 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
52269 pTab = sqlite3FindTable(db, zRight, zDb);
52270 if( pTab ){
52271 v = sqlite3GetVdbe(pParse);
52272 pIdx = pTab->pIndex;
52273 if( pIdx ){
52274 int i = 0;
52275 sqlite3VdbeSetNumCols(v, 3);
52276 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC);
52277 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC);
52278 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", P3_STATIC);
52279 while(pIdx){
52280 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
52281 sqlite3VdbeOp3(v, OP_String8, 0, 0, pIdx->zName, 0);
52282 sqlite3VdbeAddOp(v, OP_Integer, pIdx->onError!=OE_None, 0);
52283 sqlite3VdbeAddOp(v, OP_Callback, 3, 0);
52284 ++i;
52285 pIdx = pIdx->pNext;
52289 }else
52291 if( sqlite3StrICmp(zLeft, "database_list")==0 ){
52292 int i;
52293 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
52294 sqlite3VdbeSetNumCols(v, 3);
52295 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC);
52296 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC);
52297 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", P3_STATIC);
52298 for(i=0; i<db->nDb; i++){
52299 if( db->aDb[i].pBt==0 ) continue;
52300 assert( db->aDb[i].zName!=0 );
52301 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
52302 sqlite3VdbeOp3(v, OP_String8, 0, 0, db->aDb[i].zName, 0);
52303 sqlite3VdbeOp3(v, OP_String8, 0, 0,
52304 sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
52305 sqlite3VdbeAddOp(v, OP_Callback, 3, 0);
52307 }else
52309 if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
52310 int i = 0;
52311 HashElem *p;
52312 sqlite3VdbeSetNumCols(v, 2);
52313 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC);
52314 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC);
52315 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
52316 CollSeq *pColl = (CollSeq *)sqliteHashData(p);
52317 sqlite3VdbeAddOp(v, OP_Integer, i++, 0);
52318 sqlite3VdbeOp3(v, OP_String8, 0, 0, pColl->zName, 0);
52319 sqlite3VdbeAddOp(v, OP_Callback, 2, 0);
52321 }else
52322 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
52324 #ifndef SQLITE_OMIT_FOREIGN_KEY
52325 if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
52326 FKey *pFK;
52327 Table *pTab;
52328 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
52329 pTab = sqlite3FindTable(db, zRight, zDb);
52330 if( pTab ){
52331 v = sqlite3GetVdbe(pParse);
52332 pFK = pTab->pFKey;
52333 if( pFK ){
52334 int i = 0;
52335 sqlite3VdbeSetNumCols(v, 5);
52336 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", P3_STATIC);
52337 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", P3_STATIC);
52338 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", P3_STATIC);
52339 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", P3_STATIC);
52340 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", P3_STATIC);
52341 while(pFK){
52342 int j;
52343 for(j=0; j<pFK->nCol; j++){
52344 char *zCol = pFK->aCol[j].zCol;
52345 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
52346 sqlite3VdbeAddOp(v, OP_Integer, j, 0);
52347 sqlite3VdbeOp3(v, OP_String8, 0, 0, pFK->zTo, 0);
52348 sqlite3VdbeOp3(v, OP_String8, 0, 0,
52349 pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
52350 sqlite3VdbeOp3(v, zCol ? OP_String8 : OP_Null, 0, 0, zCol, 0);
52351 sqlite3VdbeAddOp(v, OP_Callback, 5, 0);
52353 ++i;
52354 pFK = pFK->pNextFrom;
52358 }else
52359 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
52361 #ifndef NDEBUG
52362 if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
52363 if( zRight ){
52364 if( getBoolean(zRight) ){
52365 sqlite3ParserTrace(stderr, "parser: ");
52366 }else{
52367 sqlite3ParserTrace(0, 0);
52370 }else
52371 #endif
52373 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
52374 ** used will be case sensitive or not depending on the RHS.
52376 if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
52377 if( zRight ){
52378 sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
52380 }else
52382 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
52383 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
52384 #endif
52386 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
52387 if( sqlite3StrICmp(zLeft, "integrity_check")==0 ){
52388 int i, j, addr, mxErr;
52390 /* Code that appears at the end of the integrity check. If no error
52391 ** messages have been generated, output OK. Otherwise output the
52392 ** error message
52394 static const VdbeOpList endCode[] = {
52395 { OP_MemLoad, 0, 0, 0},
52396 { OP_Integer, 0, 0, 0},
52397 { OP_Ne, 0, 0, 0}, /* 2 */
52398 { OP_String8, 0, 0, "ok"},
52399 { OP_Callback, 1, 0, 0},
52402 /* Initialize the VDBE program */
52403 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
52404 sqlite3VdbeSetNumCols(v, 1);
52405 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", P3_STATIC);
52407 /* Set the maximum error count */
52408 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
52409 if( zRight ){
52410 mxErr = atoi(zRight);
52411 if( mxErr<=0 ){
52412 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
52415 sqlite3VdbeAddOp(v, OP_MemInt, mxErr, 0);
52417 /* Do an integrity check on each database file */
52418 for(i=0; i<db->nDb; i++){
52419 HashElem *x;
52420 Hash *pTbls;
52421 int cnt = 0;
52423 if( OMIT_TEMPDB && i==1 ) continue;
52425 sqlite3CodeVerifySchema(pParse, i);
52426 addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0);
52427 sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
52428 sqlite3VdbeJumpHere(v, addr);
52430 /* Do an integrity check of the B-Tree
52432 pTbls = &db->aDb[i].pSchema->tblHash;
52433 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
52434 Table *pTab = sqliteHashData(x);
52435 Index *pIdx;
52436 sqlite3VdbeAddOp(v, OP_Integer, pTab->tnum, 0);
52437 cnt++;
52438 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
52439 sqlite3VdbeAddOp(v, OP_Integer, pIdx->tnum, 0);
52440 cnt++;
52443 if( cnt==0 ) continue;
52444 sqlite3VdbeAddOp(v, OP_IntegrityCk, 0, i);
52445 addr = sqlite3VdbeAddOp(v, OP_IsNull, -1, 0);
52446 sqlite3VdbeOp3(v, OP_String8, 0, 0,
52447 sqlite3MPrintf("*** in database %s ***\n", db->aDb[i].zName),
52448 P3_DYNAMIC);
52449 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
52450 sqlite3VdbeAddOp(v, OP_Concat, 0, 0);
52451 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
52452 sqlite3VdbeJumpHere(v, addr);
52454 /* Make sure all the indices are constructed correctly.
52456 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
52457 Table *pTab = sqliteHashData(x);
52458 Index *pIdx;
52459 int loopTop;
52461 if( pTab->pIndex==0 ) continue;
52462 addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0);
52463 sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
52464 sqlite3VdbeJumpHere(v, addr);
52465 sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
52466 sqlite3VdbeAddOp(v, OP_MemInt, 0, 1);
52467 loopTop = sqlite3VdbeAddOp(v, OP_Rewind, 1, 0);
52468 sqlite3VdbeAddOp(v, OP_MemIncr, 1, 1);
52469 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
52470 int jmp2;
52471 static const VdbeOpList idxErr[] = {
52472 { OP_MemIncr, -1, 0, 0},
52473 { OP_String8, 0, 0, "rowid "},
52474 { OP_Rowid, 1, 0, 0},
52475 { OP_String8, 0, 0, " missing from index "},
52476 { OP_String8, 0, 0, 0}, /* 4 */
52477 { OP_Concat, 2, 0, 0},
52478 { OP_Callback, 1, 0, 0},
52480 sqlite3GenerateIndexKey(v, pIdx, 1);
52481 jmp2 = sqlite3VdbeAddOp(v, OP_Found, j+2, 0);
52482 addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
52483 sqlite3VdbeChangeP3(v, addr+4, pIdx->zName, P3_STATIC);
52484 sqlite3VdbeJumpHere(v, jmp2);
52486 sqlite3VdbeAddOp(v, OP_Next, 1, loopTop+1);
52487 sqlite3VdbeJumpHere(v, loopTop);
52488 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
52489 static const VdbeOpList cntIdx[] = {
52490 { OP_MemInt, 0, 2, 0},
52491 { OP_Rewind, 0, 0, 0}, /* 1 */
52492 { OP_MemIncr, 1, 2, 0},
52493 { OP_Next, 0, 0, 0}, /* 3 */
52494 { OP_MemLoad, 1, 0, 0},
52495 { OP_MemLoad, 2, 0, 0},
52496 { OP_Eq, 0, 0, 0}, /* 6 */
52497 { OP_MemIncr, -1, 0, 0},
52498 { OP_String8, 0, 0, "wrong # of entries in index "},
52499 { OP_String8, 0, 0, 0}, /* 9 */
52500 { OP_Concat, 0, 0, 0},
52501 { OP_Callback, 1, 0, 0},
52503 if( pIdx->tnum==0 ) continue;
52504 addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0);
52505 sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
52506 sqlite3VdbeJumpHere(v, addr);
52507 addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
52508 sqlite3VdbeChangeP1(v, addr+1, j+2);
52509 sqlite3VdbeChangeP2(v, addr+1, addr+4);
52510 sqlite3VdbeChangeP1(v, addr+3, j+2);
52511 sqlite3VdbeChangeP2(v, addr+3, addr+2);
52512 sqlite3VdbeJumpHere(v, addr+6);
52513 sqlite3VdbeChangeP3(v, addr+9, pIdx->zName, P3_STATIC);
52517 addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
52518 sqlite3VdbeChangeP1(v, addr+1, mxErr);
52519 sqlite3VdbeJumpHere(v, addr+2);
52520 }else
52521 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
52523 #ifndef SQLITE_OMIT_UTF16
52525 ** PRAGMA encoding
52526 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
52528 ** In it's first form, this pragma returns the encoding of the main
52529 ** database. If the database is not initialized, it is initialized now.
52531 ** The second form of this pragma is a no-op if the main database file
52532 ** has not already been initialized. In this case it sets the default
52533 ** encoding that will be used for the main database file if a new file
52534 ** is created. If an existing main database file is opened, then the
52535 ** default text encoding for the existing database is used.
52537 ** In all cases new databases created using the ATTACH command are
52538 ** created to use the same default text encoding as the main database. If
52539 ** the main database has not been initialized and/or created when ATTACH
52540 ** is executed, this is done before the ATTACH operation.
52542 ** In the second form this pragma sets the text encoding to be used in
52543 ** new database files created using this database handle. It is only
52544 ** useful if invoked immediately after the main database i
52546 if( sqlite3StrICmp(zLeft, "encoding")==0 ){
52547 static const struct EncName {
52548 char *zName;
52549 u8 enc;
52550 } encnames[] = {
52551 { "UTF-8", SQLITE_UTF8 },
52552 { "UTF8", SQLITE_UTF8 },
52553 { "UTF-16le", SQLITE_UTF16LE },
52554 { "UTF16le", SQLITE_UTF16LE },
52555 { "UTF-16be", SQLITE_UTF16BE },
52556 { "UTF16be", SQLITE_UTF16BE },
52557 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
52558 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
52559 { 0, 0 }
52561 const struct EncName *pEnc;
52562 if( !zRight ){ /* "PRAGMA encoding" */
52563 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
52564 sqlite3VdbeSetNumCols(v, 1);
52565 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", P3_STATIC);
52566 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
52567 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
52568 if( pEnc->enc==ENC(pParse->db) ){
52569 sqlite3VdbeChangeP3(v, -1, pEnc->zName, P3_STATIC);
52570 break;
52573 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
52574 }else{ /* "PRAGMA encoding = XXX" */
52575 /* Only change the value of sqlite.enc if the database handle is not
52576 ** initialized. If the main database exists, the new sqlite.enc value
52577 ** will be overwritten when the schema is next loaded. If it does not
52578 ** already exists, it will be created to use the new encoding value.
52580 if(
52581 !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
52582 DbHasProperty(db, 0, DB_Empty)
52584 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
52585 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
52586 ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
52587 break;
52590 if( !pEnc->zName ){
52591 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
52595 }else
52596 #endif /* SQLITE_OMIT_UTF16 */
52598 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
52600 ** PRAGMA [database.]schema_version
52601 ** PRAGMA [database.]schema_version = <integer>
52603 ** PRAGMA [database.]user_version
52604 ** PRAGMA [database.]user_version = <integer>
52606 ** The pragma's schema_version and user_version are used to set or get
52607 ** the value of the schema-version and user-version, respectively. Both
52608 ** the schema-version and the user-version are 32-bit signed integers
52609 ** stored in the database header.
52611 ** The schema-cookie is usually only manipulated internally by SQLite. It
52612 ** is incremented by SQLite whenever the database schema is modified (by
52613 ** creating or dropping a table or index). The schema version is used by
52614 ** SQLite each time a query is executed to ensure that the internal cache
52615 ** of the schema used when compiling the SQL query matches the schema of
52616 ** the database against which the compiled query is actually executed.
52617 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
52618 ** the schema-version is potentially dangerous and may lead to program
52619 ** crashes or database corruption. Use with caution!
52621 ** The user-version is not used internally by SQLite. It may be used by
52622 ** applications for any purpose.
52624 if( sqlite3StrICmp(zLeft, "schema_version")==0 ||
52625 sqlite3StrICmp(zLeft, "user_version")==0 ){
52627 int iCookie; /* Cookie index. 0 for schema-cookie, 6 for user-cookie. */
52628 if( zLeft[0]=='s' || zLeft[0]=='S' ){
52629 iCookie = 0;
52630 }else{
52631 iCookie = 5;
52634 if( zRight ){
52635 /* Write the specified cookie value */
52636 static const VdbeOpList setCookie[] = {
52637 { OP_Transaction, 0, 1, 0}, /* 0 */
52638 { OP_Integer, 0, 0, 0}, /* 1 */
52639 { OP_SetCookie, 0, 0, 0}, /* 2 */
52641 int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
52642 sqlite3VdbeChangeP1(v, addr, iDb);
52643 sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
52644 sqlite3VdbeChangeP1(v, addr+2, iDb);
52645 sqlite3VdbeChangeP2(v, addr+2, iCookie);
52646 }else{
52647 /* Read the specified cookie value */
52648 static const VdbeOpList readCookie[] = {
52649 { OP_ReadCookie, 0, 0, 0}, /* 0 */
52650 { OP_Callback, 1, 0, 0}
52652 int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
52653 sqlite3VdbeChangeP1(v, addr, iDb);
52654 sqlite3VdbeChangeP2(v, addr, iCookie);
52655 sqlite3VdbeSetNumCols(v, 1);
52656 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, P3_TRANSIENT);
52658 }else
52659 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
52661 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
52663 ** Report the current state of file logs for all databases
52665 if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
52666 static const char *const azLockName[] = {
52667 "unlocked", "shared", "reserved", "pending", "exclusive"
52669 int i;
52670 Vdbe *v = sqlite3GetVdbe(pParse);
52671 sqlite3VdbeSetNumCols(v, 2);
52672 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", P3_STATIC);
52673 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", P3_STATIC);
52674 for(i=0; i<db->nDb; i++){
52675 Btree *pBt;
52676 Pager *pPager;
52677 if( db->aDb[i].zName==0 ) continue;
52678 sqlite3VdbeOp3(v, OP_String8, 0, 0, db->aDb[i].zName, P3_STATIC);
52679 pBt = db->aDb[i].pBt;
52680 if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
52681 sqlite3VdbeOp3(v, OP_String8, 0, 0, "closed", P3_STATIC);
52682 }else{
52683 int j = sqlite3PagerLockstate(pPager);
52684 sqlite3VdbeOp3(v, OP_String8, 0, 0,
52685 (j>=0 && j<=4) ? azLockName[j] : "unknown", P3_STATIC);
52687 sqlite3VdbeAddOp(v, OP_Callback, 2, 0);
52689 }else
52690 #endif
52692 #ifdef SQLITE_SSE
52694 ** Check to see if the sqlite_statements table exists. Create it
52695 ** if it does not.
52697 if( sqlite3StrICmp(zLeft, "create_sqlite_statement_table")==0 ){
52698 extern int sqlite3CreateStatementsTable(Parse*);
52699 sqlite3CreateStatementsTable(pParse);
52700 }else
52701 #endif
52703 #if SQLITE_HAS_CODEC
52704 if( sqlite3StrICmp(zLeft, "key")==0 ){
52705 sqlite3_key(db, zRight, strlen(zRight));
52706 }else
52707 #endif
52708 #if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
52709 if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
52710 #if SQLITE_HAS_CODEC
52711 if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
52712 extern void sqlite3_activate_see(const char*);
52713 sqlite3_activate_see(&zRight[4]);
52715 #endif
52716 #ifdef SQLITE_ENABLE_CEROD
52717 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
52718 extern void sqlite3_activate_cerod(const char*);
52719 sqlite3_activate_cerod(&zRight[6]);
52721 #endif
52723 #endif
52727 if( v ){
52728 /* Code an OP_Expire at the end of each PRAGMA program to cause
52729 ** the VDBE implementing the pragma to expire. Most (all?) pragmas
52730 ** are only valid for a single execution.
52732 sqlite3VdbeAddOp(v, OP_Expire, 1, 0);
52735 ** Reset the safety level, in case the fullfsync flag or synchronous
52736 ** setting changed.
52738 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
52739 if( db->autoCommit ){
52740 sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
52741 (db->flags&SQLITE_FullFSync)!=0);
52743 #endif
52745 pragma_out:
52746 sqliteFree(zLeft);
52747 sqliteFree(zRight);
52750 #endif /* SQLITE_OMIT_PRAGMA || SQLITE_OMIT_PARSER */
52752 /************** End of pragma.c **********************************************/
52753 /************** Begin file prepare.c *****************************************/
52755 ** 2005 May 25
52757 ** The author disclaims copyright to this source code. In place of
52758 ** a legal notice, here is a blessing:
52760 ** May you do good and not evil.
52761 ** May you find forgiveness for yourself and forgive others.
52762 ** May you share freely, never taking more than you give.
52764 *************************************************************************
52765 ** This file contains the implementation of the sqlite3_prepare()
52766 ** interface, and routines that contribute to loading the database schema
52767 ** from disk.
52769 ** $Id: prepare.c,v 1.50 2007/05/08 20:37:39 drh Exp $
52773 ** Fill the InitData structure with an error message that indicates
52774 ** that the database is corrupt.
52776 static void corruptSchema(InitData *pData, const char *zExtra){
52777 if( !sqlite3MallocFailed() ){
52778 sqlite3SetString(pData->pzErrMsg, "malformed database schema",
52779 zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0);
52781 pData->rc = SQLITE_CORRUPT;
52785 ** This is the callback routine for the code that initializes the
52786 ** database. See sqlite3Init() below for additional information.
52787 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
52789 ** Each callback contains the following information:
52791 ** argv[0] = name of thing being created
52792 ** argv[1] = root page number for table or index. 0 for trigger or view.
52793 ** argv[2] = SQL text for the CREATE statement.
52796 static int sqlite3InitCallback(void *pInit, int argc, char **argv, char **azColName){
52797 InitData *pData = (InitData*)pInit;
52798 sqlite3 *db = pData->db;
52799 int iDb = pData->iDb;
52801 pData->rc = SQLITE_OK;
52802 DbClearProperty(db, iDb, DB_Empty);
52803 if( sqlite3MallocFailed() ){
52804 corruptSchema(pData, 0);
52805 return SQLITE_NOMEM;
52808 assert( argc==3 );
52809 if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
52810 if( argv[1]==0 ){
52811 corruptSchema(pData, 0);
52812 return 1;
52814 assert( iDb>=0 && iDb<db->nDb );
52815 if( argv[2] && argv[2][0] ){
52816 /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
52817 ** But because db->init.busy is set to 1, no VDBE code is generated
52818 ** or executed. All the parser does is build the internal data
52819 ** structures that describe the table, index, or view.
52821 char *zErr;
52822 int rc;
52823 assert( db->init.busy );
52824 db->init.iDb = iDb;
52825 db->init.newTnum = atoi(argv[1]);
52826 rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
52827 db->init.iDb = 0;
52828 assert( rc!=SQLITE_OK || zErr==0 );
52829 if( SQLITE_OK!=rc ){
52830 pData->rc = rc;
52831 if( rc==SQLITE_NOMEM ){
52832 sqlite3FailedMalloc();
52833 }else if( rc!=SQLITE_INTERRUPT ){
52834 corruptSchema(pData, zErr);
52836 sqlite3_free(zErr);
52837 return 1;
52839 }else{
52840 /* If the SQL column is blank it means this is an index that
52841 ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
52842 ** constraint for a CREATE TABLE. The index should have already
52843 ** been created when we processed the CREATE TABLE. All we have
52844 ** to do here is record the root page number for that index.
52846 Index *pIndex;
52847 pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
52848 if( pIndex==0 || pIndex->tnum!=0 ){
52849 /* This can occur if there exists an index on a TEMP table which
52850 ** has the same name as another index on a permanent index. Since
52851 ** the permanent table is hidden by the TEMP table, we can also
52852 ** safely ignore the index on the permanent table.
52854 /* Do Nothing */;
52855 }else{
52856 pIndex->tnum = atoi(argv[1]);
52859 return 0;
52863 ** Attempt to read the database schema and initialize internal
52864 ** data structures for a single database file. The index of the
52865 ** database file is given by iDb. iDb==0 is used for the main
52866 ** database. iDb==1 should never be used. iDb>=2 is used for
52867 ** auxiliary databases. Return one of the SQLITE_ error codes to
52868 ** indicate success or failure.
52870 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
52871 int rc;
52872 BtCursor *curMain;
52873 int size;
52874 Table *pTab;
52875 Db *pDb;
52876 char const *azArg[4];
52877 int meta[10];
52878 InitData initData;
52879 char const *zMasterSchema;
52880 char const *zMasterName = SCHEMA_TABLE(iDb);
52883 ** The master database table has a structure like this
52885 static const char master_schema[] =
52886 "CREATE TABLE sqlite_master(\n"
52887 " type text,\n"
52888 " name text,\n"
52889 " tbl_name text,\n"
52890 " rootpage integer,\n"
52891 " sql text\n"
52894 #ifndef SQLITE_OMIT_TEMPDB
52895 static const char temp_master_schema[] =
52896 "CREATE TEMP TABLE sqlite_temp_master(\n"
52897 " type text,\n"
52898 " name text,\n"
52899 " tbl_name text,\n"
52900 " rootpage integer,\n"
52901 " sql text\n"
52904 #else
52905 #define temp_master_schema 0
52906 #endif
52908 assert( iDb>=0 && iDb<db->nDb );
52909 assert( db->aDb[iDb].pSchema );
52911 /* zMasterSchema and zInitScript are set to point at the master schema
52912 ** and initialisation script appropriate for the database being
52913 ** initialised. zMasterName is the name of the master table.
52915 if( !OMIT_TEMPDB && iDb==1 ){
52916 zMasterSchema = temp_master_schema;
52917 }else{
52918 zMasterSchema = master_schema;
52920 zMasterName = SCHEMA_TABLE(iDb);
52922 /* Construct the schema tables. */
52923 sqlite3SafetyOff(db);
52924 azArg[0] = zMasterName;
52925 azArg[1] = "1";
52926 azArg[2] = zMasterSchema;
52927 azArg[3] = 0;
52928 initData.db = db;
52929 initData.iDb = iDb;
52930 initData.pzErrMsg = pzErrMsg;
52931 rc = sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
52932 if( rc ){
52933 sqlite3SafetyOn(db);
52934 return initData.rc;
52936 pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
52937 if( pTab ){
52938 pTab->readOnly = 1;
52940 sqlite3SafetyOn(db);
52942 /* Create a cursor to hold the database open
52944 pDb = &db->aDb[iDb];
52945 if( pDb->pBt==0 ){
52946 if( !OMIT_TEMPDB && iDb==1 ){
52947 DbSetProperty(db, 1, DB_SchemaLoaded);
52949 return SQLITE_OK;
52951 rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, 0, &curMain);
52952 if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
52953 sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
52954 return rc;
52957 /* Get the database meta information.
52959 ** Meta values are as follows:
52960 ** meta[0] Schema cookie. Changes with each schema change.
52961 ** meta[1] File format of schema layer.
52962 ** meta[2] Size of the page cache.
52963 ** meta[3] Use freelist if 0. Autovacuum if greater than zero.
52964 ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
52965 ** meta[5] The user cookie. Used by the application.
52966 ** meta[6]
52967 ** meta[7]
52968 ** meta[8]
52969 ** meta[9]
52971 ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
52972 ** the possible values of meta[4].
52974 if( rc==SQLITE_OK ){
52975 int i;
52976 for(i=0; rc==SQLITE_OK && i<sizeof(meta)/sizeof(meta[0]); i++){
52977 rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
52979 if( rc ){
52980 sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
52981 sqlite3BtreeCloseCursor(curMain);
52982 return rc;
52984 }else{
52985 memset(meta, 0, sizeof(meta));
52987 pDb->pSchema->schema_cookie = meta[0];
52989 /* If opening a non-empty database, check the text encoding. For the
52990 ** main database, set sqlite3.enc to the encoding of the main database.
52991 ** For an attached db, it is an error if the encoding is not the same
52992 ** as sqlite3.enc.
52994 if( meta[4] ){ /* text encoding */
52995 if( iDb==0 ){
52996 /* If opening the main database, set ENC(db). */
52997 ENC(db) = (u8)meta[4];
52998 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
52999 }else{
53000 /* If opening an attached database, the encoding much match ENC(db) */
53001 if( meta[4]!=ENC(db) ){
53002 sqlite3BtreeCloseCursor(curMain);
53003 sqlite3SetString(pzErrMsg, "attached databases must use the same"
53004 " text encoding as main database", (char*)0);
53005 return SQLITE_ERROR;
53008 }else{
53009 DbSetProperty(db, iDb, DB_Empty);
53011 pDb->pSchema->enc = ENC(db);
53013 size = meta[2];
53014 if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
53015 pDb->pSchema->cache_size = size;
53016 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
53019 ** file_format==1 Version 3.0.0.
53020 ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
53021 ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
53022 ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
53024 pDb->pSchema->file_format = meta[1];
53025 if( pDb->pSchema->file_format==0 ){
53026 pDb->pSchema->file_format = 1;
53028 if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
53029 sqlite3BtreeCloseCursor(curMain);
53030 sqlite3SetString(pzErrMsg, "unsupported file format", (char*)0);
53031 return SQLITE_ERROR;
53035 /* Read the schema information out of the schema tables
53037 assert( db->init.busy );
53038 if( rc==SQLITE_EMPTY ){
53039 /* For an empty database, there is nothing to read */
53040 rc = SQLITE_OK;
53041 }else{
53042 char *zSql;
53043 zSql = sqlite3MPrintf(
53044 "SELECT name, rootpage, sql FROM '%q'.%s",
53045 db->aDb[iDb].zName, zMasterName);
53046 sqlite3SafetyOff(db);
53047 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
53048 if( rc==SQLITE_ABORT ) rc = initData.rc;
53049 sqlite3SafetyOn(db);
53050 sqliteFree(zSql);
53051 #ifndef SQLITE_OMIT_ANALYZE
53052 if( rc==SQLITE_OK ){
53053 sqlite3AnalysisLoad(db, iDb);
53055 #endif
53056 sqlite3BtreeCloseCursor(curMain);
53058 if( sqlite3MallocFailed() ){
53059 /* sqlite3SetString(pzErrMsg, "out of memory", (char*)0); */
53060 rc = SQLITE_NOMEM;
53061 sqlite3ResetInternalSchema(db, 0);
53063 if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
53064 /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
53065 ** the schema loaded, even if errors occured. In this situation the
53066 ** current sqlite3_prepare() operation will fail, but the following one
53067 ** will attempt to compile the supplied statement against whatever subset
53068 ** of the schema was loaded before the error occured. The primary
53069 ** purpose of this is to allow access to the sqlite_master table
53070 ** even when it's contents have been corrupted.
53072 DbSetProperty(db, iDb, DB_SchemaLoaded);
53073 rc = SQLITE_OK;
53075 return rc;
53079 ** Initialize all database files - the main database file, the file
53080 ** used to store temporary tables, and any additional database files
53081 ** created using ATTACH statements. Return a success code. If an
53082 ** error occurs, write an error message into *pzErrMsg.
53084 ** After a database is initialized, the DB_SchemaLoaded bit is set
53085 ** bit is set in the flags field of the Db structure. If the database
53086 ** file was of zero-length, then the DB_Empty flag is also set.
53088 static int sqlite3Init(sqlite3 *db, char **pzErrMsg){
53089 int i, rc;
53090 int called_initone = 0;
53092 if( db->init.busy ) return SQLITE_OK;
53093 rc = SQLITE_OK;
53094 db->init.busy = 1;
53095 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
53096 if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
53097 rc = sqlite3InitOne(db, i, pzErrMsg);
53098 if( rc ){
53099 sqlite3ResetInternalSchema(db, i);
53101 called_initone = 1;
53104 /* Once all the other databases have been initialised, load the schema
53105 ** for the TEMP database. This is loaded last, as the TEMP database
53106 ** schema may contain references to objects in other databases.
53108 #ifndef SQLITE_OMIT_TEMPDB
53109 if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
53110 rc = sqlite3InitOne(db, 1, pzErrMsg);
53111 if( rc ){
53112 sqlite3ResetInternalSchema(db, 1);
53114 called_initone = 1;
53116 #endif
53118 db->init.busy = 0;
53119 if( rc==SQLITE_OK && called_initone ){
53120 sqlite3CommitInternalChanges(db);
53123 return rc;
53127 ** This routine is a no-op if the database schema is already initialised.
53128 ** Otherwise, the schema is loaded. An error code is returned.
53130 static int sqlite3ReadSchema(Parse *pParse){
53131 int rc = SQLITE_OK;
53132 sqlite3 *db = pParse->db;
53133 if( !db->init.busy ){
53134 rc = sqlite3Init(db, &pParse->zErrMsg);
53136 if( rc!=SQLITE_OK ){
53137 pParse->rc = rc;
53138 pParse->nErr++;
53140 return rc;
53145 ** Check schema cookies in all databases. If any cookie is out
53146 ** of date, return 0. If all schema cookies are current, return 1.
53148 static int schemaIsValid(sqlite3 *db){
53149 int iDb;
53150 int rc;
53151 BtCursor *curTemp;
53152 int cookie;
53153 int allOk = 1;
53155 for(iDb=0; allOk && iDb<db->nDb; iDb++){
53156 Btree *pBt;
53157 pBt = db->aDb[iDb].pBt;
53158 if( pBt==0 ) continue;
53159 rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, 0, &curTemp);
53160 if( rc==SQLITE_OK ){
53161 rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
53162 if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
53163 allOk = 0;
53165 sqlite3BtreeCloseCursor(curTemp);
53168 return allOk;
53172 ** Convert a schema pointer into the iDb index that indicates
53173 ** which database file in db->aDb[] the schema refers to.
53175 ** If the same database is attached more than once, the first
53176 ** attached database is returned.
53178 static int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
53179 int i = -1000000;
53181 /* If pSchema is NULL, then return -1000000. This happens when code in
53182 ** expr.c is trying to resolve a reference to a transient table (i.e. one
53183 ** created by a sub-select). In this case the return value of this
53184 ** function should never be used.
53186 ** We return -1000000 instead of the more usual -1 simply because using
53187 ** -1000000 as incorrectly using -1000000 index into db->aDb[] is much
53188 ** more likely to cause a segfault than -1 (of course there are assert()
53189 ** statements too, but it never hurts to play the odds).
53191 if( pSchema ){
53192 for(i=0; i<db->nDb; i++){
53193 if( db->aDb[i].pSchema==pSchema ){
53194 break;
53197 assert( i>=0 &&i>=0 && i<db->nDb );
53199 return i;
53203 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
53205 static int sqlite3Prepare(
53206 sqlite3 *db, /* Database handle. */
53207 const char *zSql, /* UTF-8 encoded SQL statement. */
53208 int nBytes, /* Length of zSql in bytes. */
53209 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
53210 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
53211 const char **pzTail /* OUT: End of parsed string */
53213 Parse sParse;
53214 char *zErrMsg = 0;
53215 int rc = SQLITE_OK;
53216 int i;
53218 /* Assert that malloc() has not failed */
53219 assert( !sqlite3MallocFailed() );
53221 assert( ppStmt );
53222 *ppStmt = 0;
53223 if( sqlite3SafetyOn(db) ){
53224 return SQLITE_MISUSE;
53227 /* If any attached database schemas are locked, do not proceed with
53228 ** compilation. Instead return SQLITE_LOCKED immediately.
53230 for(i=0; i<db->nDb; i++) {
53231 Btree *pBt = db->aDb[i].pBt;
53232 if( pBt && sqlite3BtreeSchemaLocked(pBt) ){
53233 const char *zDb = db->aDb[i].zName;
53234 sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb);
53235 sqlite3SafetyOff(db);
53236 return SQLITE_LOCKED;
53240 memset(&sParse, 0, sizeof(sParse));
53241 sParse.db = db;
53242 if( nBytes>=0 && zSql[nBytes]!=0 ){
53243 char *zSqlCopy;
53244 if( nBytes>SQLITE_MAX_SQL_LENGTH ){
53245 return SQLITE_TOOBIG;
53247 zSqlCopy = sqlite3StrNDup(zSql, nBytes);
53248 if( zSqlCopy ){
53249 sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
53250 sqliteFree(zSqlCopy);
53252 sParse.zTail = &zSql[nBytes];
53253 }else{
53254 sqlite3RunParser(&sParse, zSql, &zErrMsg);
53257 if( sqlite3MallocFailed() ){
53258 sParse.rc = SQLITE_NOMEM;
53260 if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
53261 if( sParse.checkSchema && !schemaIsValid(db) ){
53262 sParse.rc = SQLITE_SCHEMA;
53264 if( sParse.rc==SQLITE_SCHEMA ){
53265 sqlite3ResetInternalSchema(db, 0);
53267 if( sqlite3MallocFailed() ){
53268 sParse.rc = SQLITE_NOMEM;
53270 if( pzTail ){
53271 *pzTail = sParse.zTail;
53273 rc = sParse.rc;
53275 #ifndef SQLITE_OMIT_EXPLAIN
53276 if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
53277 if( sParse.explain==2 ){
53278 sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
53279 sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", P3_STATIC);
53280 sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", P3_STATIC);
53281 sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", P3_STATIC);
53282 }else{
53283 sqlite3VdbeSetNumCols(sParse.pVdbe, 5);
53284 sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", P3_STATIC);
53285 sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", P3_STATIC);
53286 sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", P3_STATIC);
53287 sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", P3_STATIC);
53288 sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", P3_STATIC);
53291 #endif
53293 if( sqlite3SafetyOff(db) ){
53294 rc = SQLITE_MISUSE;
53297 if( saveSqlFlag ){
53298 sqlite3VdbeSetSql(sParse.pVdbe, zSql, sParse.zTail - zSql);
53300 if( rc!=SQLITE_OK || sqlite3MallocFailed() ){
53301 sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
53302 assert(!(*ppStmt));
53303 }else{
53304 *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
53307 if( zErrMsg ){
53308 sqlite3Error(db, rc, "%s", zErrMsg);
53309 sqliteFree(zErrMsg);
53310 }else{
53311 sqlite3Error(db, rc, 0);
53314 rc = sqlite3ApiExit(db, rc);
53315 sqlite3ReleaseThreadData();
53316 assert( (rc&db->errMask)==rc );
53317 return rc;
53321 ** Rerun the compilation of a statement after a schema change.
53322 ** Return true if the statement was recompiled successfully.
53323 ** Return false if there is an error of some kind.
53325 static int sqlite3Reprepare(Vdbe *p){
53326 int rc;
53327 sqlite3_stmt *pNew;
53328 const char *zSql;
53329 sqlite3 *db;
53331 zSql = sqlite3VdbeGetSql(p);
53332 if( zSql==0 ){
53333 return 0;
53335 db = sqlite3VdbeDb(p);
53336 rc = sqlite3Prepare(db, zSql, -1, 0, &pNew, 0);
53337 if( rc ){
53338 assert( pNew==0 );
53339 return 0;
53340 }else{
53341 assert( pNew!=0 );
53343 sqlite3VdbeSwap((Vdbe*)pNew, p);
53344 sqlite3_transfer_bindings(pNew, (sqlite3_stmt*)p);
53345 sqlite3VdbeResetStepResult((Vdbe*)pNew);
53346 sqlite3VdbeFinalize((Vdbe*)pNew);
53347 return 1;
53352 ** Two versions of the official API. Legacy and new use. In the legacy
53353 ** version, the original SQL text is not saved in the prepared statement
53354 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
53355 ** sqlite3_step(). In the new version, the original SQL text is retained
53356 ** and the statement is automatically recompiled if an schema change
53357 ** occurs.
53359 int sqlite3_prepare(
53360 sqlite3 *db, /* Database handle. */
53361 const char *zSql, /* UTF-8 encoded SQL statement. */
53362 int nBytes, /* Length of zSql in bytes. */
53363 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
53364 const char **pzTail /* OUT: End of parsed string */
53366 return sqlite3Prepare(db,zSql,nBytes,0,ppStmt,pzTail);
53368 int sqlite3_prepare_v2(
53369 sqlite3 *db, /* Database handle. */
53370 const char *zSql, /* UTF-8 encoded SQL statement. */
53371 int nBytes, /* Length of zSql in bytes. */
53372 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
53373 const char **pzTail /* OUT: End of parsed string */
53375 return sqlite3Prepare(db,zSql,nBytes,1,ppStmt,pzTail);
53379 #ifndef SQLITE_OMIT_UTF16
53381 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
53383 static int sqlite3Prepare16(
53384 sqlite3 *db, /* Database handle. */
53385 const void *zSql, /* UTF-8 encoded SQL statement. */
53386 int nBytes, /* Length of zSql in bytes. */
53387 int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
53388 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
53389 const void **pzTail /* OUT: End of parsed string */
53391 /* This function currently works by first transforming the UTF-16
53392 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
53393 ** tricky bit is figuring out the pointer to return in *pzTail.
53395 char *zSql8;
53396 const char *zTail8 = 0;
53397 int rc = SQLITE_OK;
53399 if( sqlite3SafetyCheck(db) ){
53400 return SQLITE_MISUSE;
53402 zSql8 = sqlite3Utf16to8(zSql, nBytes);
53403 if( zSql8 ){
53404 rc = sqlite3Prepare(db, zSql8, -1, saveSqlFlag, ppStmt, &zTail8);
53407 if( zTail8 && pzTail ){
53408 /* If sqlite3_prepare returns a tail pointer, we calculate the
53409 ** equivalent pointer into the UTF-16 string by counting the unicode
53410 ** characters between zSql8 and zTail8, and then returning a pointer
53411 ** the same number of characters into the UTF-16 string.
53413 int chars_parsed = sqlite3Utf8CharLen(zSql8, zTail8-zSql8);
53414 *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
53416 sqliteFree(zSql8);
53417 return sqlite3ApiExit(db, rc);
53421 ** Two versions of the official API. Legacy and new use. In the legacy
53422 ** version, the original SQL text is not saved in the prepared statement
53423 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
53424 ** sqlite3_step(). In the new version, the original SQL text is retained
53425 ** and the statement is automatically recompiled if an schema change
53426 ** occurs.
53428 int sqlite3_prepare16(
53429 sqlite3 *db, /* Database handle. */
53430 const void *zSql, /* UTF-8 encoded SQL statement. */
53431 int nBytes, /* Length of zSql in bytes. */
53432 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
53433 const void **pzTail /* OUT: End of parsed string */
53435 return sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
53437 int sqlite3_prepare16_v2(
53438 sqlite3 *db, /* Database handle. */
53439 const void *zSql, /* UTF-8 encoded SQL statement. */
53440 int nBytes, /* Length of zSql in bytes. */
53441 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
53442 const void **pzTail /* OUT: End of parsed string */
53444 return sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
53447 #endif /* SQLITE_OMIT_UTF16 */
53449 /************** End of prepare.c *********************************************/
53450 /************** Begin file select.c ******************************************/
53452 ** 2001 September 15
53454 ** The author disclaims copyright to this source code. In place of
53455 ** a legal notice, here is a blessing:
53457 ** May you do good and not evil.
53458 ** May you find forgiveness for yourself and forgive others.
53459 ** May you share freely, never taking more than you give.
53461 *************************************************************************
53462 ** This file contains C code routines that are called by the parser
53463 ** to handle SELECT statements in SQLite.
53465 ** $Id: select.c,v 1.351 2007/06/15 15:31:50 drh Exp $
53470 ** Delete all the content of a Select structure but do not deallocate
53471 ** the select structure itself.
53473 static void clearSelect(Select *p){
53474 sqlite3ExprListDelete(p->pEList);
53475 sqlite3SrcListDelete(p->pSrc);
53476 sqlite3ExprDelete(p->pWhere);
53477 sqlite3ExprListDelete(p->pGroupBy);
53478 sqlite3ExprDelete(p->pHaving);
53479 sqlite3ExprListDelete(p->pOrderBy);
53480 sqlite3SelectDelete(p->pPrior);
53481 sqlite3ExprDelete(p->pLimit);
53482 sqlite3ExprDelete(p->pOffset);
53487 ** Allocate a new Select structure and return a pointer to that
53488 ** structure.
53490 static Select *sqlite3SelectNew(
53491 ExprList *pEList, /* which columns to include in the result */
53492 SrcList *pSrc, /* the FROM clause -- which tables to scan */
53493 Expr *pWhere, /* the WHERE clause */
53494 ExprList *pGroupBy, /* the GROUP BY clause */
53495 Expr *pHaving, /* the HAVING clause */
53496 ExprList *pOrderBy, /* the ORDER BY clause */
53497 int isDistinct, /* true if the DISTINCT keyword is present */
53498 Expr *pLimit, /* LIMIT value. NULL means not used */
53499 Expr *pOffset /* OFFSET value. NULL means no offset */
53501 Select *pNew;
53502 Select standin;
53503 pNew = sqliteMalloc( sizeof(*pNew) );
53504 assert( !pOffset || pLimit ); /* Can't have OFFSET without LIMIT. */
53505 if( pNew==0 ){
53506 pNew = &standin;
53507 memset(pNew, 0, sizeof(*pNew));
53509 if( pEList==0 ){
53510 pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
53512 pNew->pEList = pEList;
53513 pNew->pSrc = pSrc;
53514 pNew->pWhere = pWhere;
53515 pNew->pGroupBy = pGroupBy;
53516 pNew->pHaving = pHaving;
53517 pNew->pOrderBy = pOrderBy;
53518 pNew->isDistinct = isDistinct;
53519 pNew->op = TK_SELECT;
53520 assert( pOffset==0 || pLimit!=0 );
53521 pNew->pLimit = pLimit;
53522 pNew->pOffset = pOffset;
53523 pNew->iLimit = -1;
53524 pNew->iOffset = -1;
53525 pNew->addrOpenEphm[0] = -1;
53526 pNew->addrOpenEphm[1] = -1;
53527 pNew->addrOpenEphm[2] = -1;
53528 if( pNew==&standin) {
53529 clearSelect(pNew);
53530 pNew = 0;
53532 return pNew;
53536 ** Delete the given Select structure and all of its substructures.
53538 static void sqlite3SelectDelete(Select *p){
53539 if( p ){
53540 clearSelect(p);
53541 sqliteFree(p);
53546 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
53547 ** type of join. Return an integer constant that expresses that type
53548 ** in terms of the following bit values:
53550 ** JT_INNER
53551 ** JT_CROSS
53552 ** JT_OUTER
53553 ** JT_NATURAL
53554 ** JT_LEFT
53555 ** JT_RIGHT
53557 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
53559 ** If an illegal or unsupported join type is seen, then still return
53560 ** a join type, but put an error in the pParse structure.
53562 static int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
53563 int jointype = 0;
53564 Token *apAll[3];
53565 Token *p;
53566 static const struct {
53567 const char zKeyword[8];
53568 u8 nChar;
53569 u8 code;
53570 } keywords[] = {
53571 { "natural", 7, JT_NATURAL },
53572 { "left", 4, JT_LEFT|JT_OUTER },
53573 { "right", 5, JT_RIGHT|JT_OUTER },
53574 { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
53575 { "outer", 5, JT_OUTER },
53576 { "inner", 5, JT_INNER },
53577 { "cross", 5, JT_INNER|JT_CROSS },
53579 int i, j;
53580 apAll[0] = pA;
53581 apAll[1] = pB;
53582 apAll[2] = pC;
53583 for(i=0; i<3 && apAll[i]; i++){
53584 p = apAll[i];
53585 for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
53586 if( p->n==keywords[j].nChar
53587 && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
53588 jointype |= keywords[j].code;
53589 break;
53592 if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
53593 jointype |= JT_ERROR;
53594 break;
53598 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
53599 (jointype & JT_ERROR)!=0
53601 const char *zSp1 = " ";
53602 const char *zSp2 = " ";
53603 if( pB==0 ){ zSp1++; }
53604 if( pC==0 ){ zSp2++; }
53605 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
53606 "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
53607 jointype = JT_INNER;
53608 }else if( jointype & JT_RIGHT ){
53609 sqlite3ErrorMsg(pParse,
53610 "RIGHT and FULL OUTER JOINs are not currently supported");
53611 jointype = JT_INNER;
53613 return jointype;
53617 ** Return the index of a column in a table. Return -1 if the column
53618 ** is not contained in the table.
53620 static int columnIndex(Table *pTab, const char *zCol){
53621 int i;
53622 for(i=0; i<pTab->nCol; i++){
53623 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
53625 return -1;
53629 ** Set the value of a token to a '\000'-terminated string.
53631 static void setToken(Token *p, const char *z){
53632 p->z = (u8*)z;
53633 p->n = z ? strlen(z) : 0;
53634 p->dyn = 0;
53638 ** Create an expression node for an identifier with the name of zName
53640 static Expr *sqlite3CreateIdExpr(const char *zName){
53641 Token dummy;
53642 setToken(&dummy, zName);
53643 return sqlite3Expr(TK_ID, 0, 0, &dummy);
53648 ** Add a term to the WHERE expression in *ppExpr that requires the
53649 ** zCol column to be equal in the two tables pTab1 and pTab2.
53651 static void addWhereTerm(
53652 const char *zCol, /* Name of the column */
53653 const Table *pTab1, /* First table */
53654 const char *zAlias1, /* Alias for first table. May be NULL */
53655 const Table *pTab2, /* Second table */
53656 const char *zAlias2, /* Alias for second table. May be NULL */
53657 int iRightJoinTable, /* VDBE cursor for the right table */
53658 Expr **ppExpr /* Add the equality term to this expression */
53660 Expr *pE1a, *pE1b, *pE1c;
53661 Expr *pE2a, *pE2b, *pE2c;
53662 Expr *pE;
53664 pE1a = sqlite3CreateIdExpr(zCol);
53665 pE2a = sqlite3CreateIdExpr(zCol);
53666 if( zAlias1==0 ){
53667 zAlias1 = pTab1->zName;
53669 pE1b = sqlite3CreateIdExpr(zAlias1);
53670 if( zAlias2==0 ){
53671 zAlias2 = pTab2->zName;
53673 pE2b = sqlite3CreateIdExpr(zAlias2);
53674 pE1c = sqlite3ExprOrFree(TK_DOT, pE1b, pE1a, 0);
53675 pE2c = sqlite3ExprOrFree(TK_DOT, pE2b, pE2a, 0);
53676 pE = sqlite3ExprOrFree(TK_EQ, pE1c, pE2c, 0);
53677 if( pE ){
53678 ExprSetProperty(pE, EP_FromJoin);
53679 pE->iRightJoinTable = iRightJoinTable;
53681 pE = sqlite3ExprAnd(*ppExpr, pE);
53682 if( pE ){
53683 *ppExpr = pE;
53688 ** Set the EP_FromJoin property on all terms of the given expression.
53689 ** And set the Expr.iRightJoinTable to iTable for every term in the
53690 ** expression.
53692 ** The EP_FromJoin property is used on terms of an expression to tell
53693 ** the LEFT OUTER JOIN processing logic that this term is part of the
53694 ** join restriction specified in the ON or USING clause and not a part
53695 ** of the more general WHERE clause. These terms are moved over to the
53696 ** WHERE clause during join processing but we need to remember that they
53697 ** originated in the ON or USING clause.
53699 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
53700 ** expression depends on table iRightJoinTable even if that table is not
53701 ** explicitly mentioned in the expression. That information is needed
53702 ** for cases like this:
53704 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
53706 ** The where clause needs to defer the handling of the t1.x=5
53707 ** term until after the t2 loop of the join. In that way, a
53708 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
53709 ** defer the handling of t1.x=5, it will be processed immediately
53710 ** after the t1 loop and rows with t1.x!=5 will never appear in
53711 ** the output, which is incorrect.
53713 static void setJoinExpr(Expr *p, int iTable){
53714 while( p ){
53715 ExprSetProperty(p, EP_FromJoin);
53716 p->iRightJoinTable = iTable;
53717 setJoinExpr(p->pLeft, iTable);
53718 p = p->pRight;
53723 ** This routine processes the join information for a SELECT statement.
53724 ** ON and USING clauses are converted into extra terms of the WHERE clause.
53725 ** NATURAL joins also create extra WHERE clause terms.
53727 ** The terms of a FROM clause are contained in the Select.pSrc structure.
53728 ** The left most table is the first entry in Select.pSrc. The right-most
53729 ** table is the last entry. The join operator is held in the entry to
53730 ** the left. Thus entry 0 contains the join operator for the join between
53731 ** entries 0 and 1. Any ON or USING clauses associated with the join are
53732 ** also attached to the left entry.
53734 ** This routine returns the number of errors encountered.
53736 static int sqliteProcessJoin(Parse *pParse, Select *p){
53737 SrcList *pSrc; /* All tables in the FROM clause */
53738 int i, j; /* Loop counters */
53739 struct SrcList_item *pLeft; /* Left table being joined */
53740 struct SrcList_item *pRight; /* Right table being joined */
53742 pSrc = p->pSrc;
53743 pLeft = &pSrc->a[0];
53744 pRight = &pLeft[1];
53745 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
53746 Table *pLeftTab = pLeft->pTab;
53747 Table *pRightTab = pRight->pTab;
53749 if( pLeftTab==0 || pRightTab==0 ) continue;
53751 /* When the NATURAL keyword is present, add WHERE clause terms for
53752 ** every column that the two tables have in common.
53754 if( pRight->jointype & JT_NATURAL ){
53755 if( pRight->pOn || pRight->pUsing ){
53756 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
53757 "an ON or USING clause", 0);
53758 return 1;
53760 for(j=0; j<pLeftTab->nCol; j++){
53761 char *zName = pLeftTab->aCol[j].zName;
53762 if( columnIndex(pRightTab, zName)>=0 ){
53763 addWhereTerm(zName, pLeftTab, pLeft->zAlias,
53764 pRightTab, pRight->zAlias,
53765 pRight->iCursor, &p->pWhere);
53771 /* Disallow both ON and USING clauses in the same join
53773 if( pRight->pOn && pRight->pUsing ){
53774 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
53775 "clauses in the same join");
53776 return 1;
53779 /* Add the ON clause to the end of the WHERE clause, connected by
53780 ** an AND operator.
53782 if( pRight->pOn ){
53783 setJoinExpr(pRight->pOn, pRight->iCursor);
53784 p->pWhere = sqlite3ExprAnd(p->pWhere, pRight->pOn);
53785 pRight->pOn = 0;
53788 /* Create extra terms on the WHERE clause for each column named
53789 ** in the USING clause. Example: If the two tables to be joined are
53790 ** A and B and the USING clause names X, Y, and Z, then add this
53791 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
53792 ** Report an error if any column mentioned in the USING clause is
53793 ** not contained in both tables to be joined.
53795 if( pRight->pUsing ){
53796 IdList *pList = pRight->pUsing;
53797 for(j=0; j<pList->nId; j++){
53798 char *zName = pList->a[j].zName;
53799 if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
53800 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
53801 "not present in both tables", zName);
53802 return 1;
53804 addWhereTerm(zName, pLeftTab, pLeft->zAlias,
53805 pRightTab, pRight->zAlias,
53806 pRight->iCursor, &p->pWhere);
53810 return 0;
53814 ** Insert code into "v" that will push the record on the top of the
53815 ** stack into the sorter.
53817 static void pushOntoSorter(
53818 Parse *pParse, /* Parser context */
53819 ExprList *pOrderBy, /* The ORDER BY clause */
53820 Select *pSelect /* The whole SELECT statement */
53822 Vdbe *v = pParse->pVdbe;
53823 sqlite3ExprCodeExprList(pParse, pOrderBy);
53824 sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0);
53825 sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0);
53826 sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0);
53827 sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0);
53828 if( pSelect->iLimit>=0 ){
53829 int addr1, addr2;
53830 addr1 = sqlite3VdbeAddOp(v, OP_IfMemZero, pSelect->iLimit+1, 0);
53831 sqlite3VdbeAddOp(v, OP_MemIncr, -1, pSelect->iLimit+1);
53832 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
53833 sqlite3VdbeJumpHere(v, addr1);
53834 sqlite3VdbeAddOp(v, OP_Last, pOrderBy->iECursor, 0);
53835 sqlite3VdbeAddOp(v, OP_Delete, pOrderBy->iECursor, 0);
53836 sqlite3VdbeJumpHere(v, addr2);
53837 pSelect->iLimit = -1;
53842 ** Add code to implement the OFFSET
53844 static void codeOffset(
53845 Vdbe *v, /* Generate code into this VM */
53846 Select *p, /* The SELECT statement being coded */
53847 int iContinue, /* Jump here to skip the current record */
53848 int nPop /* Number of times to pop stack when jumping */
53850 if( p->iOffset>=0 && iContinue!=0 ){
53851 int addr;
53852 sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iOffset);
53853 addr = sqlite3VdbeAddOp(v, OP_IfMemNeg, p->iOffset, 0);
53854 if( nPop>0 ){
53855 sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
53857 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
53858 VdbeComment((v, "# skip OFFSET records"));
53859 sqlite3VdbeJumpHere(v, addr);
53864 ** Add code that will check to make sure the top N elements of the
53865 ** stack are distinct. iTab is a sorting index that holds previously
53866 ** seen combinations of the N values. A new entry is made in iTab
53867 ** if the current N values are new.
53869 ** A jump to addrRepeat is made and the N+1 values are popped from the
53870 ** stack if the top N elements are not distinct.
53872 static void codeDistinct(
53873 Vdbe *v, /* Generate code into this VM */
53874 int iTab, /* A sorting index used to test for distinctness */
53875 int addrRepeat, /* Jump to here if not distinct */
53876 int N /* The top N elements of the stack must be distinct */
53878 sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0);
53879 sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3);
53880 sqlite3VdbeAddOp(v, OP_Pop, N+1, 0);
53881 sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat);
53882 VdbeComment((v, "# skip indistinct records"));
53883 sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0);
53887 ** Generate an error message when a SELECT is used within a subexpression
53888 ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
53889 ** column. We do this in a subroutine because the error occurs in multiple
53890 ** places.
53892 static int checkForMultiColumnSelectError(Parse *pParse, int eDest, int nExpr){
53893 if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
53894 sqlite3ErrorMsg(pParse, "only a single result allowed for "
53895 "a SELECT that is part of an expression");
53896 return 1;
53897 }else{
53898 return 0;
53903 ** This routine generates the code for the inside of the inner loop
53904 ** of a SELECT.
53906 ** If srcTab and nColumn are both zero, then the pEList expressions
53907 ** are evaluated in order to get the data for this row. If nColumn>0
53908 ** then data is pulled from srcTab and pEList is used only to get the
53909 ** datatypes for each column.
53911 static int selectInnerLoop(
53912 Parse *pParse, /* The parser context */
53913 Select *p, /* The complete select statement being coded */
53914 ExprList *pEList, /* List of values being extracted */
53915 int srcTab, /* Pull data from this table */
53916 int nColumn, /* Number of columns in the source table */
53917 ExprList *pOrderBy, /* If not NULL, sort results using this key */
53918 int distinct, /* If >=0, make sure results are distinct */
53919 int eDest, /* How to dispose of the results */
53920 int iParm, /* An argument to the disposal method */
53921 int iContinue, /* Jump here to continue with next row */
53922 int iBreak, /* Jump here to break out of the inner loop */
53923 char *aff /* affinity string if eDest is SRT_Union */
53925 Vdbe *v = pParse->pVdbe;
53926 int i;
53927 int hasDistinct; /* True if the DISTINCT keyword is present */
53929 if( v==0 ) return 0;
53930 assert( pEList!=0 );
53932 /* If there was a LIMIT clause on the SELECT statement, then do the check
53933 ** to see if this row should be output.
53935 hasDistinct = distinct>=0 && pEList->nExpr>0;
53936 if( pOrderBy==0 && !hasDistinct ){
53937 codeOffset(v, p, iContinue, 0);
53940 /* Pull the requested columns.
53942 if( nColumn>0 ){
53943 for(i=0; i<nColumn; i++){
53944 sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
53946 }else{
53947 nColumn = pEList->nExpr;
53948 sqlite3ExprCodeExprList(pParse, pEList);
53951 /* If the DISTINCT keyword was present on the SELECT statement
53952 ** and this row has been seen before, then do not make this row
53953 ** part of the result.
53955 if( hasDistinct ){
53956 assert( pEList!=0 );
53957 assert( pEList->nExpr==nColumn );
53958 codeDistinct(v, distinct, iContinue, nColumn);
53959 if( pOrderBy==0 ){
53960 codeOffset(v, p, iContinue, nColumn);
53964 if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
53965 return 0;
53968 switch( eDest ){
53969 /* In this mode, write each query result to the key of the temporary
53970 ** table iParm.
53972 #ifndef SQLITE_OMIT_COMPOUND_SELECT
53973 case SRT_Union: {
53974 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
53975 if( aff ){
53976 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
53978 sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
53979 break;
53982 /* Construct a record from the query result, but instead of
53983 ** saving that record, use it as a key to delete elements from
53984 ** the temporary table iParm.
53986 case SRT_Except: {
53987 int addr;
53988 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
53989 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
53990 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
53991 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
53992 break;
53994 #endif
53996 /* Store the result as data using a unique key.
53998 case SRT_Table:
53999 case SRT_EphemTab: {
54000 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
54001 if( pOrderBy ){
54002 pushOntoSorter(pParse, pOrderBy, p);
54003 }else{
54004 sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
54005 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
54006 sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
54008 break;
54011 #ifndef SQLITE_OMIT_SUBQUERY
54012 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
54013 ** then there should be a single item on the stack. Write this
54014 ** item into the set table with bogus data.
54016 case SRT_Set: {
54017 int addr1 = sqlite3VdbeCurrentAddr(v);
54018 int addr2;
54020 assert( nColumn==1 );
54021 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
54022 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
54023 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
54024 p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr,(iParm>>16)&0xff);
54025 if( pOrderBy ){
54026 /* At first glance you would think we could optimize out the
54027 ** ORDER BY in this case since the order of entries in the set
54028 ** does not matter. But there might be a LIMIT clause, in which
54029 ** case the order does matter */
54030 pushOntoSorter(pParse, pOrderBy, p);
54031 }else{
54032 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
54033 sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
54035 sqlite3VdbeJumpHere(v, addr2);
54036 break;
54039 /* If any row exist in the result set, record that fact and abort.
54041 case SRT_Exists: {
54042 sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm);
54043 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
54044 /* The LIMIT clause will terminate the loop for us */
54045 break;
54048 /* If this is a scalar select that is part of an expression, then
54049 ** store the results in the appropriate memory cell and break out
54050 ** of the scan loop.
54052 case SRT_Mem: {
54053 assert( nColumn==1 );
54054 if( pOrderBy ){
54055 pushOntoSorter(pParse, pOrderBy, p);
54056 }else{
54057 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
54058 /* The LIMIT clause will jump out of the loop for us */
54060 break;
54062 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
54064 /* Send the data to the callback function or to a subroutine. In the
54065 ** case of a subroutine, the subroutine itself is responsible for
54066 ** popping the data from the stack.
54068 case SRT_Subroutine:
54069 case SRT_Callback: {
54070 if( pOrderBy ){
54071 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
54072 pushOntoSorter(pParse, pOrderBy, p);
54073 }else if( eDest==SRT_Subroutine ){
54074 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
54075 }else{
54076 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
54078 break;
54081 #if !defined(SQLITE_OMIT_TRIGGER)
54082 /* Discard the results. This is used for SELECT statements inside
54083 ** the body of a TRIGGER. The purpose of such selects is to call
54084 ** user-defined functions that have side effects. We do not care
54085 ** about the actual results of the select.
54087 default: {
54088 assert( eDest==SRT_Discard );
54089 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
54090 break;
54092 #endif
54095 /* Jump to the end of the loop if the LIMIT is reached.
54097 if( p->iLimit>=0 && pOrderBy==0 ){
54098 sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
54099 sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak);
54101 return 0;
54105 ** Given an expression list, generate a KeyInfo structure that records
54106 ** the collating sequence for each expression in that expression list.
54108 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
54109 ** KeyInfo structure is appropriate for initializing a virtual index to
54110 ** implement that clause. If the ExprList is the result set of a SELECT
54111 ** then the KeyInfo structure is appropriate for initializing a virtual
54112 ** index to implement a DISTINCT test.
54114 ** Space to hold the KeyInfo structure is obtain from malloc. The calling
54115 ** function is responsible for seeing that this structure is eventually
54116 ** freed. Add the KeyInfo structure to the P3 field of an opcode using
54117 ** P3_KEYINFO_HANDOFF is the usual way of dealing with this.
54119 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
54120 sqlite3 *db = pParse->db;
54121 int nExpr;
54122 KeyInfo *pInfo;
54123 struct ExprList_item *pItem;
54124 int i;
54126 nExpr = pList->nExpr;
54127 pInfo = sqliteMalloc( sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
54128 if( pInfo ){
54129 pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
54130 pInfo->nField = nExpr;
54131 pInfo->enc = ENC(db);
54132 for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
54133 CollSeq *pColl;
54134 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
54135 if( !pColl ){
54136 pColl = db->pDfltColl;
54138 pInfo->aColl[i] = pColl;
54139 pInfo->aSortOrder[i] = pItem->sortOrder;
54142 return pInfo;
54147 ** If the inner loop was generated using a non-null pOrderBy argument,
54148 ** then the results were placed in a sorter. After the loop is terminated
54149 ** we need to run the sorter and output the results. The following
54150 ** routine generates the code needed to do that.
54152 static void generateSortTail(
54153 Parse *pParse, /* Parsing context */
54154 Select *p, /* The SELECT statement */
54155 Vdbe *v, /* Generate code into this VDBE */
54156 int nColumn, /* Number of columns of data */
54157 int eDest, /* Write the sorted results here */
54158 int iParm /* Optional parameter associated with eDest */
54160 int brk = sqlite3VdbeMakeLabel(v);
54161 int cont = sqlite3VdbeMakeLabel(v);
54162 int addr;
54163 int iTab;
54164 int pseudoTab = 0;
54165 ExprList *pOrderBy = p->pOrderBy;
54167 iTab = pOrderBy->iECursor;
54168 if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
54169 pseudoTab = pParse->nTab++;
54170 sqlite3VdbeAddOp(v, OP_OpenPseudo, pseudoTab, 0);
54171 sqlite3VdbeAddOp(v, OP_SetNumColumns, pseudoTab, nColumn);
54173 addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk);
54174 codeOffset(v, p, cont, 0);
54175 if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
54176 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
54178 sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1);
54179 switch( eDest ){
54180 case SRT_Table:
54181 case SRT_EphemTab: {
54182 sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
54183 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
54184 sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
54185 break;
54187 #ifndef SQLITE_OMIT_SUBQUERY
54188 case SRT_Set: {
54189 assert( nColumn==1 );
54190 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
54191 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
54192 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
54193 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
54194 sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
54195 break;
54197 case SRT_Mem: {
54198 assert( nColumn==1 );
54199 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
54200 /* The LIMIT clause will terminate the loop for us */
54201 break;
54203 #endif
54204 case SRT_Callback:
54205 case SRT_Subroutine: {
54206 int i;
54207 sqlite3VdbeAddOp(v, OP_Insert, pseudoTab, 0);
54208 for(i=0; i<nColumn; i++){
54209 sqlite3VdbeAddOp(v, OP_Column, pseudoTab, i);
54211 if( eDest==SRT_Callback ){
54212 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
54213 }else{
54214 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
54216 break;
54218 default: {
54219 /* Do nothing */
54220 break;
54224 /* Jump to the end of the loop when the LIMIT is reached
54226 if( p->iLimit>=0 ){
54227 sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
54228 sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk);
54231 /* The bottom of the loop
54233 sqlite3VdbeResolveLabel(v, cont);
54234 sqlite3VdbeAddOp(v, OP_Next, iTab, addr);
54235 sqlite3VdbeResolveLabel(v, brk);
54236 if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
54237 sqlite3VdbeAddOp(v, OP_Close, pseudoTab, 0);
54243 ** Return a pointer to a string containing the 'declaration type' of the
54244 ** expression pExpr. The string may be treated as static by the caller.
54246 ** The declaration type is the exact datatype definition extracted from the
54247 ** original CREATE TABLE statement if the expression is a column. The
54248 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
54249 ** is considered a column can be complex in the presence of subqueries. The
54250 ** result-set expression in all of the following SELECT statements is
54251 ** considered a column by this function.
54253 ** SELECT col FROM tbl;
54254 ** SELECT (SELECT col FROM tbl;
54255 ** SELECT (SELECT col FROM tbl);
54256 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
54258 ** The declaration type for any expression other than a column is NULL.
54260 static const char *columnType(
54261 NameContext *pNC,
54262 Expr *pExpr,
54263 const char **pzOriginDb,
54264 const char **pzOriginTab,
54265 const char **pzOriginCol
54267 char const *zType = 0;
54268 char const *zOriginDb = 0;
54269 char const *zOriginTab = 0;
54270 char const *zOriginCol = 0;
54271 int j;
54272 if( pExpr==0 || pNC->pSrcList==0 ) return 0;
54274 switch( pExpr->op ){
54275 case TK_AGG_COLUMN:
54276 case TK_COLUMN: {
54277 /* The expression is a column. Locate the table the column is being
54278 ** extracted from in NameContext.pSrcList. This table may be real
54279 ** database table or a subquery.
54281 Table *pTab = 0; /* Table structure column is extracted from */
54282 Select *pS = 0; /* Select the column is extracted from */
54283 int iCol = pExpr->iColumn; /* Index of column in pTab */
54284 while( pNC && !pTab ){
54285 SrcList *pTabList = pNC->pSrcList;
54286 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
54287 if( j<pTabList->nSrc ){
54288 pTab = pTabList->a[j].pTab;
54289 pS = pTabList->a[j].pSelect;
54290 }else{
54291 pNC = pNC->pNext;
54295 if( pTab==0 ){
54296 /* FIX ME:
54297 ** This can occurs if you have something like "SELECT new.x;" inside
54298 ** a trigger. In other words, if you reference the special "new"
54299 ** table in the result set of a select. We do not have a good way
54300 ** to find the actual table type, so call it "TEXT". This is really
54301 ** something of a bug, but I do not know how to fix it.
54303 ** This code does not produce the correct answer - it just prevents
54304 ** a segfault. See ticket #1229.
54306 zType = "TEXT";
54307 break;
54310 assert( pTab );
54311 if( pS ){
54312 /* The "table" is actually a sub-select or a view in the FROM clause
54313 ** of the SELECT statement. Return the declaration type and origin
54314 ** data for the result-set column of the sub-select.
54316 if( iCol>=0 && iCol<pS->pEList->nExpr ){
54317 /* If iCol is less than zero, then the expression requests the
54318 ** rowid of the sub-select or view. This expression is legal (see
54319 ** test case misc2.2.2) - it always evaluates to NULL.
54321 NameContext sNC;
54322 Expr *p = pS->pEList->a[iCol].pExpr;
54323 sNC.pSrcList = pS->pSrc;
54324 sNC.pNext = 0;
54325 sNC.pParse = pNC->pParse;
54326 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
54328 }else if( pTab->pSchema ){
54329 /* A real table */
54330 assert( !pS );
54331 if( iCol<0 ) iCol = pTab->iPKey;
54332 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
54333 if( iCol<0 ){
54334 zType = "INTEGER";
54335 zOriginCol = "rowid";
54336 }else{
54337 zType = pTab->aCol[iCol].zType;
54338 zOriginCol = pTab->aCol[iCol].zName;
54340 zOriginTab = pTab->zName;
54341 if( pNC->pParse ){
54342 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
54343 zOriginDb = pNC->pParse->db->aDb[iDb].zName;
54346 break;
54348 #ifndef SQLITE_OMIT_SUBQUERY
54349 case TK_SELECT: {
54350 /* The expression is a sub-select. Return the declaration type and
54351 ** origin info for the single column in the result set of the SELECT
54352 ** statement.
54354 NameContext sNC;
54355 Select *pS = pExpr->pSelect;
54356 Expr *p = pS->pEList->a[0].pExpr;
54357 sNC.pSrcList = pS->pSrc;
54358 sNC.pNext = pNC;
54359 sNC.pParse = pNC->pParse;
54360 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
54361 break;
54363 #endif
54366 if( pzOriginDb ){
54367 assert( pzOriginTab && pzOriginCol );
54368 *pzOriginDb = zOriginDb;
54369 *pzOriginTab = zOriginTab;
54370 *pzOriginCol = zOriginCol;
54372 return zType;
54376 ** Generate code that will tell the VDBE the declaration types of columns
54377 ** in the result set.
54379 static void generateColumnTypes(
54380 Parse *pParse, /* Parser context */
54381 SrcList *pTabList, /* List of tables */
54382 ExprList *pEList /* Expressions defining the result set */
54384 Vdbe *v = pParse->pVdbe;
54385 int i;
54386 NameContext sNC;
54387 sNC.pSrcList = pTabList;
54388 sNC.pParse = pParse;
54389 for(i=0; i<pEList->nExpr; i++){
54390 Expr *p = pEList->a[i].pExpr;
54391 const char *zOrigDb = 0;
54392 const char *zOrigTab = 0;
54393 const char *zOrigCol = 0;
54394 const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
54396 /* The vdbe must make it's own copy of the column-type and other
54397 ** column specific strings, in case the schema is reset before this
54398 ** virtual machine is deleted.
54400 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P3_TRANSIENT);
54401 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P3_TRANSIENT);
54402 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P3_TRANSIENT);
54403 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P3_TRANSIENT);
54408 ** Generate code that will tell the VDBE the names of columns
54409 ** in the result set. This information is used to provide the
54410 ** azCol[] values in the callback.
54412 static void generateColumnNames(
54413 Parse *pParse, /* Parser context */
54414 SrcList *pTabList, /* List of tables */
54415 ExprList *pEList /* Expressions defining the result set */
54417 Vdbe *v = pParse->pVdbe;
54418 int i, j;
54419 sqlite3 *db = pParse->db;
54420 int fullNames, shortNames;
54422 #ifndef SQLITE_OMIT_EXPLAIN
54423 /* If this is an EXPLAIN, skip this step */
54424 if( pParse->explain ){
54425 return;
54427 #endif
54429 assert( v!=0 );
54430 if( pParse->colNamesSet || v==0 || sqlite3MallocFailed() ) return;
54431 pParse->colNamesSet = 1;
54432 fullNames = (db->flags & SQLITE_FullColNames)!=0;
54433 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
54434 sqlite3VdbeSetNumCols(v, pEList->nExpr);
54435 for(i=0; i<pEList->nExpr; i++){
54436 Expr *p;
54437 p = pEList->a[i].pExpr;
54438 if( p==0 ) continue;
54439 if( pEList->a[i].zName ){
54440 char *zName = pEList->a[i].zName;
54441 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
54442 continue;
54444 if( p->op==TK_COLUMN && pTabList ){
54445 Table *pTab;
54446 char *zCol;
54447 int iCol = p->iColumn;
54448 for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
54449 assert( j<pTabList->nSrc );
54450 pTab = pTabList->a[j].pTab;
54451 if( iCol<0 ) iCol = pTab->iPKey;
54452 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
54453 if( iCol<0 ){
54454 zCol = "rowid";
54455 }else{
54456 zCol = pTab->aCol[iCol].zName;
54458 if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
54459 sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
54460 }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
54461 char *zName = 0;
54462 char *zTab;
54464 zTab = pTabList->a[j].zAlias;
54465 if( fullNames || zTab==0 ) zTab = pTab->zName;
54466 sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
54467 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P3_DYNAMIC);
54468 }else{
54469 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
54471 }else if( p->span.z && p->span.z[0] ){
54472 sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
54473 /* sqlite3VdbeCompressSpace(v, addr); */
54474 }else{
54475 char zName[30];
54476 assert( p->op!=TK_COLUMN || pTabList==0 );
54477 sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1);
54478 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0);
54481 generateColumnTypes(pParse, pTabList, pEList);
54484 #ifndef SQLITE_OMIT_COMPOUND_SELECT
54486 ** Name of the connection operator, used for error messages.
54488 static const char *selectOpName(int id){
54489 char *z;
54490 switch( id ){
54491 case TK_ALL: z = "UNION ALL"; break;
54492 case TK_INTERSECT: z = "INTERSECT"; break;
54493 case TK_EXCEPT: z = "EXCEPT"; break;
54494 default: z = "UNION"; break;
54496 return z;
54498 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
54501 ** Forward declaration
54503 static int prepSelectStmt(Parse*, Select*);
54506 ** Given a SELECT statement, generate a Table structure that describes
54507 ** the result set of that SELECT.
54509 static Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
54510 Table *pTab;
54511 int i, j;
54512 ExprList *pEList;
54513 Column *aCol, *pCol;
54515 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
54516 if( prepSelectStmt(pParse, pSelect) ){
54517 return 0;
54519 if( sqlite3SelectResolve(pParse, pSelect, 0) ){
54520 return 0;
54522 pTab = sqliteMalloc( sizeof(Table) );
54523 if( pTab==0 ){
54524 return 0;
54526 pTab->nRef = 1;
54527 pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
54528 pEList = pSelect->pEList;
54529 pTab->nCol = pEList->nExpr;
54530 assert( pTab->nCol>0 );
54531 pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
54532 for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
54533 Expr *p, *pR;
54534 char *zType;
54535 char *zName;
54536 int nName;
54537 CollSeq *pColl;
54538 int cnt;
54539 NameContext sNC;
54541 /* Get an appropriate name for the column
54543 p = pEList->a[i].pExpr;
54544 assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
54545 if( (zName = pEList->a[i].zName)!=0 ){
54546 /* If the column contains an "AS <name>" phrase, use <name> as the name */
54547 zName = sqliteStrDup(zName);
54548 }else if( p->op==TK_DOT
54549 && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
54550 /* For columns of the from A.B use B as the name */
54551 zName = sqlite3MPrintf("%T", &pR->token);
54552 }else if( p->span.z && p->span.z[0] ){
54553 /* Use the original text of the column expression as its name */
54554 zName = sqlite3MPrintf("%T", &p->span);
54555 }else{
54556 /* If all else fails, make up a name */
54557 zName = sqlite3MPrintf("column%d", i+1);
54559 sqlite3Dequote(zName);
54560 if( sqlite3MallocFailed() ){
54561 sqliteFree(zName);
54562 sqlite3DeleteTable(pTab);
54563 return 0;
54566 /* Make sure the column name is unique. If the name is not unique,
54567 ** append a integer to the name so that it becomes unique.
54569 nName = strlen(zName);
54570 for(j=cnt=0; j<i; j++){
54571 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
54572 zName[nName] = 0;
54573 zName = sqlite3MPrintf("%z:%d", zName, ++cnt);
54574 j = -1;
54575 if( zName==0 ) break;
54578 pCol->zName = zName;
54580 /* Get the typename, type affinity, and collating sequence for the
54581 ** column.
54583 memset(&sNC, 0, sizeof(sNC));
54584 sNC.pSrcList = pSelect->pSrc;
54585 zType = sqliteStrDup(columnType(&sNC, p, 0, 0, 0));
54586 pCol->zType = zType;
54587 pCol->affinity = sqlite3ExprAffinity(p);
54588 pColl = sqlite3ExprCollSeq(pParse, p);
54589 if( pColl ){
54590 pCol->zColl = sqliteStrDup(pColl->zName);
54593 pTab->iPKey = -1;
54594 return pTab;
54598 ** Prepare a SELECT statement for processing by doing the following
54599 ** things:
54601 ** (1) Make sure VDBE cursor numbers have been assigned to every
54602 ** element of the FROM clause.
54604 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
54605 ** defines FROM clause. When views appear in the FROM clause,
54606 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
54607 ** that implements the view. A copy is made of the view's SELECT
54608 ** statement so that we can freely modify or delete that statement
54609 ** without worrying about messing up the presistent representation
54610 ** of the view.
54612 ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
54613 ** on joins and the ON and USING clause of joins.
54615 ** (4) Scan the list of columns in the result set (pEList) looking
54616 ** for instances of the "*" operator or the TABLE.* operator.
54617 ** If found, expand each "*" to be every column in every table
54618 ** and TABLE.* to be every column in TABLE.
54620 ** Return 0 on success. If there are problems, leave an error message
54621 ** in pParse and return non-zero.
54623 static int prepSelectStmt(Parse *pParse, Select *p){
54624 int i, j, k, rc;
54625 SrcList *pTabList;
54626 ExprList *pEList;
54627 struct SrcList_item *pFrom;
54629 if( p==0 || p->pSrc==0 || sqlite3MallocFailed() ){
54630 return 1;
54632 pTabList = p->pSrc;
54633 pEList = p->pEList;
54635 /* Make sure cursor numbers have been assigned to all entries in
54636 ** the FROM clause of the SELECT statement.
54638 sqlite3SrcListAssignCursors(pParse, p->pSrc);
54640 /* Look up every table named in the FROM clause of the select. If
54641 ** an entry of the FROM clause is a subquery instead of a table or view,
54642 ** then create a transient table structure to describe the subquery.
54644 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
54645 Table *pTab;
54646 if( pFrom->pTab!=0 ){
54647 /* This statement has already been prepared. There is no need
54648 ** to go further. */
54649 assert( i==0 );
54650 return 0;
54652 if( pFrom->zName==0 ){
54653 #ifndef SQLITE_OMIT_SUBQUERY
54654 /* A sub-query in the FROM clause of a SELECT */
54655 assert( pFrom->pSelect!=0 );
54656 if( pFrom->zAlias==0 ){
54657 pFrom->zAlias =
54658 sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
54660 assert( pFrom->pTab==0 );
54661 pFrom->pTab = pTab =
54662 sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
54663 if( pTab==0 ){
54664 return 1;
54666 /* The isEphem flag indicates that the Table structure has been
54667 ** dynamically allocated and may be freed at any time. In other words,
54668 ** pTab is not pointing to a persistent table structure that defines
54669 ** part of the schema. */
54670 pTab->isEphem = 1;
54671 #endif
54672 }else{
54673 /* An ordinary table or view name in the FROM clause */
54674 assert( pFrom->pTab==0 );
54675 pFrom->pTab = pTab =
54676 sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
54677 if( pTab==0 ){
54678 return 1;
54680 pTab->nRef++;
54681 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
54682 if( pTab->pSelect || IsVirtual(pTab) ){
54683 /* We reach here if the named table is a really a view */
54684 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
54685 return 1;
54687 /* If pFrom->pSelect!=0 it means we are dealing with a
54688 ** view within a view. The SELECT structure has already been
54689 ** copied by the outer view so we can skip the copy step here
54690 ** in the inner view.
54692 if( pFrom->pSelect==0 ){
54693 pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
54696 #endif
54700 /* Process NATURAL keywords, and ON and USING clauses of joins.
54702 if( sqliteProcessJoin(pParse, p) ) return 1;
54704 /* For every "*" that occurs in the column list, insert the names of
54705 ** all columns in all tables. And for every TABLE.* insert the names
54706 ** of all columns in TABLE. The parser inserted a special expression
54707 ** with the TK_ALL operator for each "*" that it found in the column list.
54708 ** The following code just has to locate the TK_ALL expressions and expand
54709 ** each one to the list of all columns in all tables.
54711 ** The first loop just checks to see if there are any "*" operators
54712 ** that need expanding.
54714 for(k=0; k<pEList->nExpr; k++){
54715 Expr *pE = pEList->a[k].pExpr;
54716 if( pE->op==TK_ALL ) break;
54717 if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
54718 && pE->pLeft && pE->pLeft->op==TK_ID ) break;
54720 rc = 0;
54721 if( k<pEList->nExpr ){
54723 ** If we get here it means the result set contains one or more "*"
54724 ** operators that need to be expanded. Loop through each expression
54725 ** in the result set and expand them one by one.
54727 struct ExprList_item *a = pEList->a;
54728 ExprList *pNew = 0;
54729 int flags = pParse->db->flags;
54730 int longNames = (flags & SQLITE_FullColNames)!=0 &&
54731 (flags & SQLITE_ShortColNames)==0;
54733 for(k=0; k<pEList->nExpr; k++){
54734 Expr *pE = a[k].pExpr;
54735 if( pE->op!=TK_ALL &&
54736 (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
54737 /* This particular expression does not need to be expanded.
54739 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
54740 if( pNew ){
54741 pNew->a[pNew->nExpr-1].zName = a[k].zName;
54742 }else{
54743 rc = 1;
54745 a[k].pExpr = 0;
54746 a[k].zName = 0;
54747 }else{
54748 /* This expression is a "*" or a "TABLE.*" and needs to be
54749 ** expanded. */
54750 int tableSeen = 0; /* Set to 1 when TABLE matches */
54751 char *zTName; /* text of name of TABLE */
54752 if( pE->op==TK_DOT && pE->pLeft ){
54753 zTName = sqlite3NameFromToken(&pE->pLeft->token);
54754 }else{
54755 zTName = 0;
54757 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
54758 Table *pTab = pFrom->pTab;
54759 char *zTabName = pFrom->zAlias;
54760 if( zTabName==0 || zTabName[0]==0 ){
54761 zTabName = pTab->zName;
54763 if( zTName && (zTabName==0 || zTabName[0]==0 ||
54764 sqlite3StrICmp(zTName, zTabName)!=0) ){
54765 continue;
54767 tableSeen = 1;
54768 for(j=0; j<pTab->nCol; j++){
54769 Expr *pExpr, *pRight;
54770 char *zName = pTab->aCol[j].zName;
54772 if( i>0 ){
54773 struct SrcList_item *pLeft = &pTabList->a[i-1];
54774 if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
54775 columnIndex(pLeft->pTab, zName)>=0 ){
54776 /* In a NATURAL join, omit the join columns from the
54777 ** table on the right */
54778 continue;
54780 if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
54781 /* In a join with a USING clause, omit columns in the
54782 ** using clause from the table on the right. */
54783 continue;
54786 pRight = sqlite3Expr(TK_ID, 0, 0, 0);
54787 if( pRight==0 ) break;
54788 setToken(&pRight->token, zName);
54789 if( zTabName && (longNames || pTabList->nSrc>1) ){
54790 Expr *pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
54791 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
54792 if( pExpr==0 ) break;
54793 setToken(&pLeft->token, zTabName);
54794 setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
54795 pExpr->span.dyn = 1;
54796 pExpr->token.z = 0;
54797 pExpr->token.n = 0;
54798 pExpr->token.dyn = 0;
54799 }else{
54800 pExpr = pRight;
54801 pExpr->span = pExpr->token;
54803 if( longNames ){
54804 pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span);
54805 }else{
54806 pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
54810 if( !tableSeen ){
54811 if( zTName ){
54812 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
54813 }else{
54814 sqlite3ErrorMsg(pParse, "no tables specified");
54816 rc = 1;
54818 sqliteFree(zTName);
54821 sqlite3ExprListDelete(pEList);
54822 p->pEList = pNew;
54824 if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){
54825 sqlite3ErrorMsg(pParse, "too many columns in result set");
54826 rc = SQLITE_ERROR;
54828 return rc;
54831 #ifndef SQLITE_OMIT_COMPOUND_SELECT
54833 ** This routine associates entries in an ORDER BY expression list with
54834 ** columns in a result. For each ORDER BY expression, the opcode of
54835 ** the top-level node is changed to TK_COLUMN and the iColumn value of
54836 ** the top-level node is filled in with column number and the iTable
54837 ** value of the top-level node is filled with iTable parameter.
54839 ** If there are prior SELECT clauses, they are processed first. A match
54840 ** in an earlier SELECT takes precedence over a later SELECT.
54842 ** Any entry that does not match is flagged as an error. The number
54843 ** of errors is returned.
54845 static int matchOrderbyToColumn(
54846 Parse *pParse, /* A place to leave error messages */
54847 Select *pSelect, /* Match to result columns of this SELECT */
54848 ExprList *pOrderBy, /* The ORDER BY values to match against columns */
54849 int iTable, /* Insert this value in iTable */
54850 int mustComplete /* If TRUE all ORDER BYs must match */
54852 int nErr = 0;
54853 int i, j;
54854 ExprList *pEList;
54856 if( pSelect==0 || pOrderBy==0 ) return 1;
54857 if( mustComplete ){
54858 for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
54860 if( prepSelectStmt(pParse, pSelect) ){
54861 return 1;
54863 if( pSelect->pPrior ){
54864 if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
54865 return 1;
54868 pEList = pSelect->pEList;
54869 for(i=0; i<pOrderBy->nExpr; i++){
54870 struct ExprList_item *pItem;
54871 Expr *pE = pOrderBy->a[i].pExpr;
54872 int iCol = -1;
54873 char *zLabel;
54875 if( pOrderBy->a[i].done ) continue;
54876 if( sqlite3ExprIsInteger(pE, &iCol) ){
54877 if( iCol<=0 || iCol>pEList->nExpr ){
54878 sqlite3ErrorMsg(pParse,
54879 "ORDER BY position %d should be between 1 and %d",
54880 iCol, pEList->nExpr);
54881 nErr++;
54882 break;
54884 if( !mustComplete ) continue;
54885 iCol--;
54887 if( iCol<0 && (zLabel = sqlite3NameFromToken(&pE->token))!=0 ){
54888 for(j=0, pItem=pEList->a; j<pEList->nExpr; j++, pItem++){
54889 char *zName;
54890 int isMatch;
54891 if( pItem->zName ){
54892 zName = sqlite3StrDup(pItem->zName);
54893 }else{
54894 zName = sqlite3NameFromToken(&pItem->pExpr->token);
54896 isMatch = zName && sqlite3StrICmp(zName, zLabel)==0;
54897 sqliteFree(zName);
54898 if( isMatch ){
54899 iCol = j;
54900 break;
54903 sqliteFree(zLabel);
54905 if( iCol>=0 ){
54906 pE->op = TK_COLUMN;
54907 pE->iColumn = iCol;
54908 pE->iTable = iTable;
54909 pE->iAgg = -1;
54910 pOrderBy->a[i].done = 1;
54911 }else if( mustComplete ){
54912 sqlite3ErrorMsg(pParse,
54913 "ORDER BY term number %d does not match any result column", i+1);
54914 nErr++;
54915 break;
54918 return nErr;
54920 #endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
54923 ** Get a VDBE for the given parser context. Create a new one if necessary.
54924 ** If an error occurs, return NULL and leave a message in pParse.
54926 static Vdbe *sqlite3GetVdbe(Parse *pParse){
54927 Vdbe *v = pParse->pVdbe;
54928 if( v==0 ){
54929 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
54931 return v;
54936 ** Compute the iLimit and iOffset fields of the SELECT based on the
54937 ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
54938 ** that appear in the original SQL statement after the LIMIT and OFFSET
54939 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
54940 ** are the integer memory register numbers for counters used to compute
54941 ** the limit and offset. If there is no limit and/or offset, then
54942 ** iLimit and iOffset are negative.
54944 ** This routine changes the values of iLimit and iOffset only if
54945 ** a limit or offset is defined by pLimit and pOffset. iLimit and
54946 ** iOffset should have been preset to appropriate default values
54947 ** (usually but not always -1) prior to calling this routine.
54948 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
54949 ** redefined. The UNION ALL operator uses this property to force
54950 ** the reuse of the same limit and offset registers across multiple
54951 ** SELECT statements.
54953 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
54954 Vdbe *v = 0;
54955 int iLimit = 0;
54956 int iOffset;
54957 int addr1, addr2;
54960 ** "LIMIT -1" always shows all rows. There is some
54961 ** contraversy about what the correct behavior should be.
54962 ** The current implementation interprets "LIMIT 0" to mean
54963 ** no rows.
54965 if( p->pLimit ){
54966 p->iLimit = iLimit = pParse->nMem;
54967 pParse->nMem += 2;
54968 v = sqlite3GetVdbe(pParse);
54969 if( v==0 ) return;
54970 sqlite3ExprCode(pParse, p->pLimit);
54971 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
54972 sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 1);
54973 VdbeComment((v, "# LIMIT counter"));
54974 sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak);
54975 sqlite3VdbeAddOp(v, OP_MemLoad, iLimit, 0);
54977 if( p->pOffset ){
54978 p->iOffset = iOffset = pParse->nMem++;
54979 v = sqlite3GetVdbe(pParse);
54980 if( v==0 ) return;
54981 sqlite3ExprCode(pParse, p->pOffset);
54982 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
54983 sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0);
54984 VdbeComment((v, "# OFFSET counter"));
54985 addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0);
54986 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
54987 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
54988 sqlite3VdbeJumpHere(v, addr1);
54989 if( p->pLimit ){
54990 sqlite3VdbeAddOp(v, OP_Add, 0, 0);
54993 if( p->pLimit ){
54994 addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0);
54995 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
54996 sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1);
54997 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
54998 sqlite3VdbeJumpHere(v, addr1);
54999 sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1);
55000 VdbeComment((v, "# LIMIT+OFFSET"));
55001 sqlite3VdbeJumpHere(v, addr2);
55006 ** Allocate a virtual index to use for sorting.
55008 static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
55009 if( pOrderBy ){
55010 int addr;
55011 assert( pOrderBy->iECursor==0 );
55012 pOrderBy->iECursor = pParse->nTab++;
55013 addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenEphemeral,
55014 pOrderBy->iECursor, pOrderBy->nExpr+1);
55015 assert( p->addrOpenEphm[2] == -1 );
55016 p->addrOpenEphm[2] = addr;
55020 #ifndef SQLITE_OMIT_COMPOUND_SELECT
55022 ** Return the appropriate collating sequence for the iCol-th column of
55023 ** the result set for the compound-select statement "p". Return NULL if
55024 ** the column has no default collating sequence.
55026 ** The collating sequence for the compound select is taken from the
55027 ** left-most term of the select that has a collating sequence.
55029 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
55030 CollSeq *pRet;
55031 if( p->pPrior ){
55032 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
55033 }else{
55034 pRet = 0;
55036 if( pRet==0 ){
55037 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
55039 return pRet;
55041 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
55043 #ifndef SQLITE_OMIT_COMPOUND_SELECT
55045 ** This routine is called to process a query that is really the union
55046 ** or intersection of two or more separate queries.
55048 ** "p" points to the right-most of the two queries. the query on the
55049 ** left is p->pPrior. The left query could also be a compound query
55050 ** in which case this routine will be called recursively.
55052 ** The results of the total query are to be written into a destination
55053 ** of type eDest with parameter iParm.
55055 ** Example 1: Consider a three-way compound SQL statement.
55057 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
55059 ** This statement is parsed up as follows:
55061 ** SELECT c FROM t3
55062 ** |
55063 ** `-----> SELECT b FROM t2
55064 ** |
55065 ** `------> SELECT a FROM t1
55067 ** The arrows in the diagram above represent the Select.pPrior pointer.
55068 ** So if this routine is called with p equal to the t3 query, then
55069 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
55071 ** Notice that because of the way SQLite parses compound SELECTs, the
55072 ** individual selects always group from left to right.
55074 static int multiSelect(
55075 Parse *pParse, /* Parsing context */
55076 Select *p, /* The right-most of SELECTs to be coded */
55077 int eDest, /* \___ Store query results as specified */
55078 int iParm, /* / by these two parameters. */
55079 char *aff /* If eDest is SRT_Union, the affinity string */
55081 int rc = SQLITE_OK; /* Success code from a subroutine */
55082 Select *pPrior; /* Another SELECT immediately to our left */
55083 Vdbe *v; /* Generate code to this VDBE */
55084 int nCol; /* Number of columns in the result set */
55085 ExprList *pOrderBy; /* The ORDER BY clause on p */
55086 int aSetP2[2]; /* Set P2 value of these op to number of columns */
55087 int nSetP2 = 0; /* Number of slots in aSetP2[] used */
55089 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
55090 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
55092 if( p==0 || p->pPrior==0 ){
55093 rc = 1;
55094 goto multi_select_end;
55096 pPrior = p->pPrior;
55097 assert( pPrior->pRightmost!=pPrior );
55098 assert( pPrior->pRightmost==p->pRightmost );
55099 if( pPrior->pOrderBy ){
55100 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
55101 selectOpName(p->op));
55102 rc = 1;
55103 goto multi_select_end;
55105 if( pPrior->pLimit ){
55106 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
55107 selectOpName(p->op));
55108 rc = 1;
55109 goto multi_select_end;
55112 /* Make sure we have a valid query engine. If not, create a new one.
55114 v = sqlite3GetVdbe(pParse);
55115 if( v==0 ){
55116 rc = 1;
55117 goto multi_select_end;
55120 /* Create the destination temporary table if necessary
55122 if( eDest==SRT_EphemTab ){
55123 assert( p->pEList );
55124 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
55125 aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 0);
55126 eDest = SRT_Table;
55129 /* Generate code for the left and right SELECT statements.
55131 pOrderBy = p->pOrderBy;
55132 switch( p->op ){
55133 case TK_ALL: {
55134 if( pOrderBy==0 ){
55135 int addr = 0;
55136 assert( !pPrior->pLimit );
55137 pPrior->pLimit = p->pLimit;
55138 pPrior->pOffset = p->pOffset;
55139 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
55140 p->pLimit = 0;
55141 p->pOffset = 0;
55142 if( rc ){
55143 goto multi_select_end;
55145 p->pPrior = 0;
55146 p->iLimit = pPrior->iLimit;
55147 p->iOffset = pPrior->iOffset;
55148 if( p->iLimit>=0 ){
55149 addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0);
55150 VdbeComment((v, "# Jump ahead if LIMIT reached"));
55152 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
55153 p->pPrior = pPrior;
55154 if( rc ){
55155 goto multi_select_end;
55157 if( addr ){
55158 sqlite3VdbeJumpHere(v, addr);
55160 break;
55162 /* For UNION ALL ... ORDER BY fall through to the next case */
55164 case TK_EXCEPT:
55165 case TK_UNION: {
55166 int unionTab; /* Cursor number of the temporary table holding result */
55167 int op = 0; /* One of the SRT_ operations to apply to self */
55168 int priorOp; /* The SRT_ operation to apply to prior selects */
55169 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
55170 int addr;
55172 priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
55173 if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
55174 /* We can reuse a temporary table generated by a SELECT to our
55175 ** right.
55177 unionTab = iParm;
55178 }else{
55179 /* We will need to create our own temporary table to hold the
55180 ** intermediate results.
55182 unionTab = pParse->nTab++;
55183 if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){
55184 rc = 1;
55185 goto multi_select_end;
55187 addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, unionTab, 0);
55188 if( priorOp==SRT_Table ){
55189 assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
55190 aSetP2[nSetP2++] = addr;
55191 }else{
55192 assert( p->addrOpenEphm[0] == -1 );
55193 p->addrOpenEphm[0] = addr;
55194 p->pRightmost->usesEphm = 1;
55196 createSortingIndex(pParse, p, pOrderBy);
55197 assert( p->pEList );
55200 /* Code the SELECT statements to our left
55202 assert( !pPrior->pOrderBy );
55203 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
55204 if( rc ){
55205 goto multi_select_end;
55208 /* Code the current SELECT statement
55210 switch( p->op ){
55211 case TK_EXCEPT: op = SRT_Except; break;
55212 case TK_UNION: op = SRT_Union; break;
55213 case TK_ALL: op = SRT_Table; break;
55215 p->pPrior = 0;
55216 p->pOrderBy = 0;
55217 p->disallowOrderBy = pOrderBy!=0;
55218 pLimit = p->pLimit;
55219 p->pLimit = 0;
55220 pOffset = p->pOffset;
55221 p->pOffset = 0;
55222 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
55223 /* Query flattening in sqlite3Select() might refill p->pOrderBy.
55224 ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
55225 sqlite3ExprListDelete(p->pOrderBy);
55226 p->pPrior = pPrior;
55227 p->pOrderBy = pOrderBy;
55228 sqlite3ExprDelete(p->pLimit);
55229 p->pLimit = pLimit;
55230 p->pOffset = pOffset;
55231 p->iLimit = -1;
55232 p->iOffset = -1;
55233 if( rc ){
55234 goto multi_select_end;
55238 /* Convert the data in the temporary table into whatever form
55239 ** it is that we currently need.
55241 if( eDest!=priorOp || unionTab!=iParm ){
55242 int iCont, iBreak, iStart;
55243 assert( p->pEList );
55244 if( eDest==SRT_Callback ){
55245 Select *pFirst = p;
55246 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
55247 generateColumnNames(pParse, 0, pFirst->pEList);
55249 iBreak = sqlite3VdbeMakeLabel(v);
55250 iCont = sqlite3VdbeMakeLabel(v);
55251 computeLimitRegisters(pParse, p, iBreak);
55252 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
55253 iStart = sqlite3VdbeCurrentAddr(v);
55254 rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
55255 pOrderBy, -1, eDest, iParm,
55256 iCont, iBreak, 0);
55257 if( rc ){
55258 rc = 1;
55259 goto multi_select_end;
55261 sqlite3VdbeResolveLabel(v, iCont);
55262 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
55263 sqlite3VdbeResolveLabel(v, iBreak);
55264 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
55266 break;
55268 case TK_INTERSECT: {
55269 int tab1, tab2;
55270 int iCont, iBreak, iStart;
55271 Expr *pLimit, *pOffset;
55272 int addr;
55274 /* INTERSECT is different from the others since it requires
55275 ** two temporary tables. Hence it has its own case. Begin
55276 ** by allocating the tables we will need.
55278 tab1 = pParse->nTab++;
55279 tab2 = pParse->nTab++;
55280 if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){
55281 rc = 1;
55282 goto multi_select_end;
55284 createSortingIndex(pParse, p, pOrderBy);
55286 addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab1, 0);
55287 assert( p->addrOpenEphm[0] == -1 );
55288 p->addrOpenEphm[0] = addr;
55289 p->pRightmost->usesEphm = 1;
55290 assert( p->pEList );
55292 /* Code the SELECTs to our left into temporary table "tab1".
55294 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
55295 if( rc ){
55296 goto multi_select_end;
55299 /* Code the current SELECT into temporary table "tab2"
55301 addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab2, 0);
55302 assert( p->addrOpenEphm[1] == -1 );
55303 p->addrOpenEphm[1] = addr;
55304 p->pPrior = 0;
55305 pLimit = p->pLimit;
55306 p->pLimit = 0;
55307 pOffset = p->pOffset;
55308 p->pOffset = 0;
55309 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
55310 p->pPrior = pPrior;
55311 sqlite3ExprDelete(p->pLimit);
55312 p->pLimit = pLimit;
55313 p->pOffset = pOffset;
55314 if( rc ){
55315 goto multi_select_end;
55318 /* Generate code to take the intersection of the two temporary
55319 ** tables.
55321 assert( p->pEList );
55322 if( eDest==SRT_Callback ){
55323 Select *pFirst = p;
55324 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
55325 generateColumnNames(pParse, 0, pFirst->pEList);
55327 iBreak = sqlite3VdbeMakeLabel(v);
55328 iCont = sqlite3VdbeMakeLabel(v);
55329 computeLimitRegisters(pParse, p, iBreak);
55330 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
55331 iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
55332 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
55333 rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
55334 pOrderBy, -1, eDest, iParm,
55335 iCont, iBreak, 0);
55336 if( rc ){
55337 rc = 1;
55338 goto multi_select_end;
55340 sqlite3VdbeResolveLabel(v, iCont);
55341 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
55342 sqlite3VdbeResolveLabel(v, iBreak);
55343 sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
55344 sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
55345 break;
55349 /* Make sure all SELECTs in the statement have the same number of elements
55350 ** in their result sets.
55352 assert( p->pEList && pPrior->pEList );
55353 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
55354 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
55355 " do not have the same number of result columns", selectOpName(p->op));
55356 rc = 1;
55357 goto multi_select_end;
55360 /* Set the number of columns in temporary tables
55362 nCol = p->pEList->nExpr;
55363 while( nSetP2 ){
55364 sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
55367 /* Compute collating sequences used by either the ORDER BY clause or
55368 ** by any temporary tables needed to implement the compound select.
55369 ** Attach the KeyInfo structure to all temporary tables. Invoke the
55370 ** ORDER BY processing if there is an ORDER BY clause.
55372 ** This section is run by the right-most SELECT statement only.
55373 ** SELECT statements to the left always skip this part. The right-most
55374 ** SELECT might also skip this part if it has no ORDER BY clause and
55375 ** no temp tables are required.
55377 if( pOrderBy || p->usesEphm ){
55378 int i; /* Loop counter */
55379 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
55380 Select *pLoop; /* For looping through SELECT statements */
55381 int nKeyCol; /* Number of entries in pKeyInfo->aCol[] */
55382 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
55383 CollSeq **aCopy; /* A copy of pKeyInfo->aColl[] */
55385 assert( p->pRightmost==p );
55386 nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0);
55387 pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1));
55388 if( !pKeyInfo ){
55389 rc = SQLITE_NOMEM;
55390 goto multi_select_end;
55393 pKeyInfo->enc = ENC(pParse->db);
55394 pKeyInfo->nField = nCol;
55396 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
55397 *apColl = multiSelectCollSeq(pParse, p, i);
55398 if( 0==*apColl ){
55399 *apColl = pParse->db->pDfltColl;
55403 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
55404 for(i=0; i<2; i++){
55405 int addr = pLoop->addrOpenEphm[i];
55406 if( addr<0 ){
55407 /* If [0] is unused then [1] is also unused. So we can
55408 ** always safely abort as soon as the first unused slot is found */
55409 assert( pLoop->addrOpenEphm[1]<0 );
55410 break;
55412 sqlite3VdbeChangeP2(v, addr, nCol);
55413 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
55414 pLoop->addrOpenEphm[i] = -1;
55418 if( pOrderBy ){
55419 struct ExprList_item *pOTerm = pOrderBy->a;
55420 int nOrderByExpr = pOrderBy->nExpr;
55421 int addr;
55422 u8 *pSortOrder;
55424 /* Reuse the same pKeyInfo for the ORDER BY as was used above for
55425 ** the compound select statements. Except we have to change out the
55426 ** pKeyInfo->aColl[] values. Some of the aColl[] values will be
55427 ** reused when constructing the pKeyInfo for the ORDER BY, so make
55428 ** a copy. Sufficient space to hold both the nCol entries for
55429 ** the compound select and the nOrderbyExpr entries for the ORDER BY
55430 ** was allocated above. But we need to move the compound select
55431 ** entries out of the way before constructing the ORDER BY entries.
55432 ** Move the compound select entries into aCopy[] where they can be
55433 ** accessed and reused when constructing the ORDER BY entries.
55434 ** Because nCol might be greater than or less than nOrderByExpr
55435 ** we have to use memmove() when doing the copy.
55437 aCopy = &pKeyInfo->aColl[nOrderByExpr];
55438 pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
55439 memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
55441 apColl = pKeyInfo->aColl;
55442 for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
55443 Expr *pExpr = pOTerm->pExpr;
55444 if( (pExpr->flags & EP_ExpCollate) ){
55445 assert( pExpr->pColl!=0 );
55446 *apColl = pExpr->pColl;
55447 }else{
55448 *apColl = aCopy[pExpr->iColumn];
55450 *pSortOrder = pOTerm->sortOrder;
55452 assert( p->pRightmost==p );
55453 assert( p->addrOpenEphm[2]>=0 );
55454 addr = p->addrOpenEphm[2];
55455 sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2);
55456 pKeyInfo->nField = nOrderByExpr;
55457 sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
55458 pKeyInfo = 0;
55459 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
55462 sqliteFree(pKeyInfo);
55465 multi_select_end:
55466 return rc;
55468 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
55470 #ifndef SQLITE_OMIT_VIEW
55472 ** Scan through the expression pExpr. Replace every reference to
55473 ** a column in table number iTable with a copy of the iColumn-th
55474 ** entry in pEList. (But leave references to the ROWID column
55475 ** unchanged.)
55477 ** This routine is part of the flattening procedure. A subquery
55478 ** whose result set is defined by pEList appears as entry in the
55479 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
55480 ** FORM clause entry is iTable. This routine make the necessary
55481 ** changes to pExpr so that it refers directly to the source table
55482 ** of the subquery rather the result set of the subquery.
55484 static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
55485 static void substSelect(Select *, int, ExprList *); /* Forward Decl */
55486 static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
55487 if( pExpr==0 ) return;
55488 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
55489 if( pExpr->iColumn<0 ){
55490 pExpr->op = TK_NULL;
55491 }else{
55492 Expr *pNew;
55493 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
55494 assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
55495 pNew = pEList->a[pExpr->iColumn].pExpr;
55496 assert( pNew!=0 );
55497 pExpr->op = pNew->op;
55498 assert( pExpr->pLeft==0 );
55499 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
55500 assert( pExpr->pRight==0 );
55501 pExpr->pRight = sqlite3ExprDup(pNew->pRight);
55502 assert( pExpr->pList==0 );
55503 pExpr->pList = sqlite3ExprListDup(pNew->pList);
55504 pExpr->iTable = pNew->iTable;
55505 pExpr->pTab = pNew->pTab;
55506 pExpr->iColumn = pNew->iColumn;
55507 pExpr->iAgg = pNew->iAgg;
55508 sqlite3TokenCopy(&pExpr->token, &pNew->token);
55509 sqlite3TokenCopy(&pExpr->span, &pNew->span);
55510 pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
55511 pExpr->flags = pNew->flags;
55513 }else{
55514 substExpr(pExpr->pLeft, iTable, pEList);
55515 substExpr(pExpr->pRight, iTable, pEList);
55516 substSelect(pExpr->pSelect, iTable, pEList);
55517 substExprList(pExpr->pList, iTable, pEList);
55520 static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
55521 int i;
55522 if( pList==0 ) return;
55523 for(i=0; i<pList->nExpr; i++){
55524 substExpr(pList->a[i].pExpr, iTable, pEList);
55527 static void substSelect(Select *p, int iTable, ExprList *pEList){
55528 if( !p ) return;
55529 substExprList(p->pEList, iTable, pEList);
55530 substExprList(p->pGroupBy, iTable, pEList);
55531 substExprList(p->pOrderBy, iTable, pEList);
55532 substExpr(p->pHaving, iTable, pEList);
55533 substExpr(p->pWhere, iTable, pEList);
55534 substSelect(p->pPrior, iTable, pEList);
55536 #endif /* !defined(SQLITE_OMIT_VIEW) */
55538 #ifndef SQLITE_OMIT_VIEW
55540 ** This routine attempts to flatten subqueries in order to speed
55541 ** execution. It returns 1 if it makes changes and 0 if no flattening
55542 ** occurs.
55544 ** To understand the concept of flattening, consider the following
55545 ** query:
55547 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
55549 ** The default way of implementing this query is to execute the
55550 ** subquery first and store the results in a temporary table, then
55551 ** run the outer query on that temporary table. This requires two
55552 ** passes over the data. Furthermore, because the temporary table
55553 ** has no indices, the WHERE clause on the outer query cannot be
55554 ** optimized.
55556 ** This routine attempts to rewrite queries such as the above into
55557 ** a single flat select, like this:
55559 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
55561 ** The code generated for this simpification gives the same result
55562 ** but only has to scan the data once. And because indices might
55563 ** exist on the table t1, a complete scan of the data might be
55564 ** avoided.
55566 ** Flattening is only attempted if all of the following are true:
55568 ** (1) The subquery and the outer query do not both use aggregates.
55570 ** (2) The subquery is not an aggregate or the outer query is not a join.
55572 ** (3) The subquery is not the right operand of a left outer join, or
55573 ** the subquery is not itself a join. (Ticket #306)
55575 ** (4) The subquery is not DISTINCT or the outer query is not a join.
55577 ** (5) The subquery is not DISTINCT or the outer query does not use
55578 ** aggregates.
55580 ** (6) The subquery does not use aggregates or the outer query is not
55581 ** DISTINCT.
55583 ** (7) The subquery has a FROM clause.
55585 ** (8) The subquery does not use LIMIT or the outer query is not a join.
55587 ** (9) The subquery does not use LIMIT or the outer query does not use
55588 ** aggregates.
55590 ** (10) The subquery does not use aggregates or the outer query does not
55591 ** use LIMIT.
55593 ** (11) The subquery and the outer query do not both have ORDER BY clauses.
55595 ** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
55596 ** subquery has no WHERE clause. (added by ticket #350)
55598 ** (13) The subquery and outer query do not both use LIMIT
55600 ** (14) The subquery does not use OFFSET
55602 ** (15) The outer query is not part of a compound select or the
55603 ** subquery does not have both an ORDER BY and a LIMIT clause.
55604 ** (See ticket #2339)
55606 ** In this routine, the "p" parameter is a pointer to the outer query.
55607 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
55608 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
55610 ** If flattening is not attempted, this routine is a no-op and returns 0.
55611 ** If flattening is attempted this routine returns 1.
55613 ** All of the expression analysis must occur on both the outer query and
55614 ** the subquery before this routine runs.
55616 static int flattenSubquery(
55617 Select *p, /* The parent or outer SELECT statement */
55618 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
55619 int isAgg, /* True if outer SELECT uses aggregate functions */
55620 int subqueryIsAgg /* True if the subquery uses aggregate functions */
55622 Select *pSub; /* The inner query or "subquery" */
55623 SrcList *pSrc; /* The FROM clause of the outer query */
55624 SrcList *pSubSrc; /* The FROM clause of the subquery */
55625 ExprList *pList; /* The result set of the outer query */
55626 int iParent; /* VDBE cursor number of the pSub result set temp table */
55627 int i; /* Loop counter */
55628 Expr *pWhere; /* The WHERE clause */
55629 struct SrcList_item *pSubitem; /* The subquery */
55631 /* Check to see if flattening is permitted. Return 0 if not.
55633 if( p==0 ) return 0;
55634 pSrc = p->pSrc;
55635 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
55636 pSubitem = &pSrc->a[iFrom];
55637 pSub = pSubitem->pSelect;
55638 assert( pSub!=0 );
55639 if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
55640 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
55641 pSubSrc = pSub->pSrc;
55642 assert( pSubSrc );
55643 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
55644 ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
55645 ** because they could be computed at compile-time. But when LIMIT and OFFSET
55646 ** became arbitrary expressions, we were forced to add restrictions (13)
55647 ** and (14). */
55648 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
55649 if( pSub->pOffset ) return 0; /* Restriction (14) */
55650 if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
55651 return 0; /* Restriction (15) */
55653 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
55654 if( (pSub->isDistinct || pSub->pLimit)
55655 && (pSrc->nSrc>1 || isAgg) ){ /* Restrictions (4)(5)(8)(9) */
55656 return 0;
55658 if( p->isDistinct && subqueryIsAgg ) return 0; /* Restriction (6) */
55659 if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
55660 return 0; /* Restriction (11) */
55663 /* Restriction 3: If the subquery is a join, make sure the subquery is
55664 ** not used as the right operand of an outer join. Examples of why this
55665 ** is not allowed:
55667 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
55669 ** If we flatten the above, we would get
55671 ** (t1 LEFT OUTER JOIN t2) JOIN t3
55673 ** which is not at all the same thing.
55675 if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
55676 return 0;
55679 /* Restriction 12: If the subquery is the right operand of a left outer
55680 ** join, make sure the subquery has no WHERE clause.
55681 ** An examples of why this is not allowed:
55683 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
55685 ** If we flatten the above, we would get
55687 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
55689 ** But the t2.x>0 test will always fail on a NULL row of t2, which
55690 ** effectively converts the OUTER JOIN into an INNER JOIN.
55692 if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
55693 return 0;
55696 /* If we reach this point, it means flattening is permitted for the
55697 ** iFrom-th entry of the FROM clause in the outer query.
55700 /* Move all of the FROM elements of the subquery into the
55701 ** the FROM clause of the outer query. Before doing this, remember
55702 ** the cursor number for the original outer query FROM element in
55703 ** iParent. The iParent cursor will never be used. Subsequent code
55704 ** will scan expressions looking for iParent references and replace
55705 ** those references with expressions that resolve to the subquery FROM
55706 ** elements we are now copying in.
55708 iParent = pSubitem->iCursor;
55710 int nSubSrc = pSubSrc->nSrc;
55711 int jointype = pSubitem->jointype;
55713 sqlite3DeleteTable(pSubitem->pTab);
55714 sqliteFree(pSubitem->zDatabase);
55715 sqliteFree(pSubitem->zName);
55716 sqliteFree(pSubitem->zAlias);
55717 if( nSubSrc>1 ){
55718 int extra = nSubSrc - 1;
55719 for(i=1; i<nSubSrc; i++){
55720 pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
55722 p->pSrc = pSrc;
55723 for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
55724 pSrc->a[i] = pSrc->a[i-extra];
55727 for(i=0; i<nSubSrc; i++){
55728 pSrc->a[i+iFrom] = pSubSrc->a[i];
55729 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
55731 pSrc->a[iFrom].jointype = jointype;
55734 /* Now begin substituting subquery result set expressions for
55735 ** references to the iParent in the outer query.
55737 ** Example:
55739 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
55740 ** \ \_____________ subquery __________/ /
55741 ** \_____________________ outer query ______________________________/
55743 ** We look at every expression in the outer query and every place we see
55744 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
55746 pList = p->pEList;
55747 for(i=0; i<pList->nExpr; i++){
55748 Expr *pExpr;
55749 if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
55750 pList->a[i].zName = sqliteStrNDup((char*)pExpr->span.z, pExpr->span.n);
55753 substExprList(p->pEList, iParent, pSub->pEList);
55754 if( isAgg ){
55755 substExprList(p->pGroupBy, iParent, pSub->pEList);
55756 substExpr(p->pHaving, iParent, pSub->pEList);
55758 if( pSub->pOrderBy ){
55759 assert( p->pOrderBy==0 );
55760 p->pOrderBy = pSub->pOrderBy;
55761 pSub->pOrderBy = 0;
55762 }else if( p->pOrderBy ){
55763 substExprList(p->pOrderBy, iParent, pSub->pEList);
55765 if( pSub->pWhere ){
55766 pWhere = sqlite3ExprDup(pSub->pWhere);
55767 }else{
55768 pWhere = 0;
55770 if( subqueryIsAgg ){
55771 assert( p->pHaving==0 );
55772 p->pHaving = p->pWhere;
55773 p->pWhere = pWhere;
55774 substExpr(p->pHaving, iParent, pSub->pEList);
55775 p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
55776 assert( p->pGroupBy==0 );
55777 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
55778 }else{
55779 substExpr(p->pWhere, iParent, pSub->pEList);
55780 p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
55783 /* The flattened query is distinct if either the inner or the
55784 ** outer query is distinct.
55786 p->isDistinct = p->isDistinct || pSub->isDistinct;
55789 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
55791 ** One is tempted to try to add a and b to combine the limits. But this
55792 ** does not work if either limit is negative.
55794 if( pSub->pLimit ){
55795 p->pLimit = pSub->pLimit;
55796 pSub->pLimit = 0;
55799 /* Finially, delete what is left of the subquery and return
55800 ** success.
55802 sqlite3SelectDelete(pSub);
55803 return 1;
55805 #endif /* SQLITE_OMIT_VIEW */
55808 ** Analyze the SELECT statement passed in as an argument to see if it
55809 ** is a simple min() or max() query. If it is and this query can be
55810 ** satisfied using a single seek to the beginning or end of an index,
55811 ** then generate the code for this SELECT and return 1. If this is not a
55812 ** simple min() or max() query, then return 0;
55814 ** A simply min() or max() query looks like this:
55816 ** SELECT min(a) FROM table;
55817 ** SELECT max(a) FROM table;
55819 ** The query may have only a single table in its FROM argument. There
55820 ** can be no GROUP BY or HAVING or WHERE clauses. The result set must
55821 ** be the min() or max() of a single column of the table. The column
55822 ** in the min() or max() function must be indexed.
55824 ** The parameters to this routine are the same as for sqlite3Select().
55825 ** See the header comment on that routine for additional information.
55827 static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
55828 Expr *pExpr;
55829 int iCol;
55830 Table *pTab;
55831 Index *pIdx;
55832 int base;
55833 Vdbe *v;
55834 int seekOp;
55835 ExprList *pEList, *pList, eList;
55836 struct ExprList_item eListItem;
55837 SrcList *pSrc;
55838 int brk;
55839 int iDb;
55841 /* Check to see if this query is a simple min() or max() query. Return
55842 ** zero if it is not.
55844 if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
55845 pSrc = p->pSrc;
55846 if( pSrc->nSrc!=1 ) return 0;
55847 pEList = p->pEList;
55848 if( pEList->nExpr!=1 ) return 0;
55849 pExpr = pEList->a[0].pExpr;
55850 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
55851 pList = pExpr->pList;
55852 if( pList==0 || pList->nExpr!=1 ) return 0;
55853 if( pExpr->token.n!=3 ) return 0;
55854 if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
55855 seekOp = OP_Rewind;
55856 }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
55857 seekOp = OP_Last;
55858 }else{
55859 return 0;
55861 pExpr = pList->a[0].pExpr;
55862 if( pExpr->op!=TK_COLUMN ) return 0;
55863 iCol = pExpr->iColumn;
55864 pTab = pSrc->a[0].pTab;
55866 /* This optimization cannot be used with virtual tables. */
55867 if( IsVirtual(pTab) ) return 0;
55869 /* If we get to here, it means the query is of the correct form.
55870 ** Check to make sure we have an index and make pIdx point to the
55871 ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
55872 ** key column, no index is necessary so set pIdx to NULL. If no
55873 ** usable index is found, return 0.
55875 if( iCol<0 ){
55876 pIdx = 0;
55877 }else{
55878 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
55879 if( pColl==0 ) return 0;
55880 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
55881 assert( pIdx->nColumn>=1 );
55882 if( pIdx->aiColumn[0]==iCol &&
55883 0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){
55884 break;
55887 if( pIdx==0 ) return 0;
55890 /* Identify column types if we will be using the callback. This
55891 ** step is skipped if the output is going to a table or a memory cell.
55892 ** The column names have already been generated in the calling function.
55894 v = sqlite3GetVdbe(pParse);
55895 if( v==0 ) return 0;
55897 /* If the output is destined for a temporary table, open that table.
55899 if( eDest==SRT_EphemTab ){
55900 sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 1);
55903 /* Generating code to find the min or the max. Basically all we have
55904 ** to do is find the first or the last entry in the chosen index. If
55905 ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
55906 ** or last entry in the main table.
55908 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
55909 assert( iDb>=0 || pTab->isEphem );
55910 sqlite3CodeVerifySchema(pParse, iDb);
55911 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
55912 base = pSrc->a[0].iCursor;
55913 brk = sqlite3VdbeMakeLabel(v);
55914 computeLimitRegisters(pParse, p, brk);
55915 if( pSrc->a[0].pSelect==0 ){
55916 sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead);
55918 if( pIdx==0 ){
55919 sqlite3VdbeAddOp(v, seekOp, base, 0);
55920 }else{
55921 /* Even though the cursor used to open the index here is closed
55922 ** as soon as a single value has been read from it, allocate it
55923 ** using (pParse->nTab++) to prevent the cursor id from being
55924 ** reused. This is important for statements of the form
55925 ** "INSERT INTO x SELECT max() FROM x".
55927 int iIdx;
55928 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
55929 iIdx = pParse->nTab++;
55930 assert( pIdx->pSchema==pTab->pSchema );
55931 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
55932 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
55933 (char*)pKey, P3_KEYINFO_HANDOFF);
55934 if( seekOp==OP_Rewind ){
55935 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
55936 sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
55937 seekOp = OP_MoveGt;
55939 sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
55940 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
55941 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
55942 sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
55944 eList.nExpr = 1;
55945 memset(&eListItem, 0, sizeof(eListItem));
55946 eList.a = &eListItem;
55947 eList.a[0].pExpr = pExpr;
55948 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0);
55949 sqlite3VdbeResolveLabel(v, brk);
55950 sqlite3VdbeAddOp(v, OP_Close, base, 0);
55952 return 1;
55956 ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return
55957 ** the number of errors seen.
55959 ** An ORDER BY or GROUP BY is a list of expressions. If any expression
55960 ** is an integer constant, then that expression is replaced by the
55961 ** corresponding entry in the result set.
55963 static int processOrderGroupBy(
55964 NameContext *pNC, /* Name context of the SELECT statement. */
55965 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
55966 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
55968 int i;
55969 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */
55970 Parse *pParse = pNC->pParse; /* The result set of the SELECT */
55971 assert( pEList );
55973 if( pOrderBy==0 ) return 0;
55974 if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
55975 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
55976 return 1;
55978 for(i=0; i<pOrderBy->nExpr; i++){
55979 int iCol;
55980 Expr *pE = pOrderBy->a[i].pExpr;
55981 if( sqlite3ExprIsInteger(pE, &iCol) ){
55982 if( iCol>0 && iCol<=pEList->nExpr ){
55983 CollSeq *pColl = pE->pColl;
55984 int flags = pE->flags & EP_ExpCollate;
55985 sqlite3ExprDelete(pE);
55986 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
55987 if( pColl && flags ){
55988 pE->pColl = pColl;
55989 pE->flags |= flags;
55991 }else{
55992 sqlite3ErrorMsg(pParse,
55993 "%s BY column number %d out of range - should be "
55994 "between 1 and %d", zType, iCol, pEList->nExpr);
55995 return 1;
55998 if( sqlite3ExprResolveNames(pNC, pE) ){
55999 return 1;
56002 return 0;
56006 ** This routine resolves any names used in the result set of the
56007 ** supplied SELECT statement. If the SELECT statement being resolved
56008 ** is a sub-select, then pOuterNC is a pointer to the NameContext
56009 ** of the parent SELECT.
56011 static int sqlite3SelectResolve(
56012 Parse *pParse, /* The parser context */
56013 Select *p, /* The SELECT statement being coded. */
56014 NameContext *pOuterNC /* The outer name context. May be NULL. */
56016 ExprList *pEList; /* Result set. */
56017 int i; /* For-loop variable used in multiple places */
56018 NameContext sNC; /* Local name-context */
56019 ExprList *pGroupBy; /* The group by clause */
56021 /* If this routine has run before, return immediately. */
56022 if( p->isResolved ){
56023 assert( !pOuterNC );
56024 return SQLITE_OK;
56026 p->isResolved = 1;
56028 /* If there have already been errors, do nothing. */
56029 if( pParse->nErr>0 ){
56030 return SQLITE_ERROR;
56033 /* Prepare the select statement. This call will allocate all cursors
56034 ** required to handle the tables and subqueries in the FROM clause.
56036 if( prepSelectStmt(pParse, p) ){
56037 return SQLITE_ERROR;
56040 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
56041 ** are not allowed to refer to any names, so pass an empty NameContext.
56043 memset(&sNC, 0, sizeof(sNC));
56044 sNC.pParse = pParse;
56045 if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
56046 sqlite3ExprResolveNames(&sNC, p->pOffset) ){
56047 return SQLITE_ERROR;
56050 /* Set up the local name-context to pass to ExprResolveNames() to
56051 ** resolve the expression-list.
56053 sNC.allowAgg = 1;
56054 sNC.pSrcList = p->pSrc;
56055 sNC.pNext = pOuterNC;
56057 /* Resolve names in the result set. */
56058 pEList = p->pEList;
56059 if( !pEList ) return SQLITE_ERROR;
56060 for(i=0; i<pEList->nExpr; i++){
56061 Expr *pX = pEList->a[i].pExpr;
56062 if( sqlite3ExprResolveNames(&sNC, pX) ){
56063 return SQLITE_ERROR;
56067 /* If there are no aggregate functions in the result-set, and no GROUP BY
56068 ** expression, do not allow aggregates in any of the other expressions.
56070 assert( !p->isAgg );
56071 pGroupBy = p->pGroupBy;
56072 if( pGroupBy || sNC.hasAgg ){
56073 p->isAgg = 1;
56074 }else{
56075 sNC.allowAgg = 0;
56078 /* If a HAVING clause is present, then there must be a GROUP BY clause.
56080 if( p->pHaving && !pGroupBy ){
56081 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
56082 return SQLITE_ERROR;
56085 /* Add the expression list to the name-context before parsing the
56086 ** other expressions in the SELECT statement. This is so that
56087 ** expressions in the WHERE clause (etc.) can refer to expressions by
56088 ** aliases in the result set.
56090 ** Minor point: If this is the case, then the expression will be
56091 ** re-evaluated for each reference to it.
56093 sNC.pEList = p->pEList;
56094 if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
56095 sqlite3ExprResolveNames(&sNC, p->pHaving) ){
56096 return SQLITE_ERROR;
56098 if( p->pPrior==0 ){
56099 if( processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
56100 processOrderGroupBy(&sNC, pGroupBy, "GROUP") ){
56101 return SQLITE_ERROR;
56105 if( sqlite3MallocFailed() ){
56106 return SQLITE_NOMEM;
56109 /* Make sure the GROUP BY clause does not contain aggregate functions.
56111 if( pGroupBy ){
56112 struct ExprList_item *pItem;
56114 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
56115 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
56116 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
56117 "the GROUP BY clause");
56118 return SQLITE_ERROR;
56123 /* If this is one SELECT of a compound, be sure to resolve names
56124 ** in the other SELECTs.
56126 if( p->pPrior ){
56127 return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
56128 }else{
56129 return SQLITE_OK;
56134 ** Reset the aggregate accumulator.
56136 ** The aggregate accumulator is a set of memory cells that hold
56137 ** intermediate results while calculating an aggregate. This
56138 ** routine simply stores NULLs in all of those memory cells.
56140 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
56141 Vdbe *v = pParse->pVdbe;
56142 int i;
56143 struct AggInfo_func *pFunc;
56144 if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
56145 return;
56147 for(i=0; i<pAggInfo->nColumn; i++){
56148 sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0);
56150 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
56151 sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0);
56152 if( pFunc->iDistinct>=0 ){
56153 Expr *pE = pFunc->pExpr;
56154 if( pE->pList==0 || pE->pList->nExpr!=1 ){
56155 sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
56156 "by an expression");
56157 pFunc->iDistinct = -1;
56158 }else{
56159 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
56160 sqlite3VdbeOp3(v, OP_OpenEphemeral, pFunc->iDistinct, 0,
56161 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
56168 ** Invoke the OP_AggFinalize opcode for every aggregate function
56169 ** in the AggInfo structure.
56171 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
56172 Vdbe *v = pParse->pVdbe;
56173 int i;
56174 struct AggInfo_func *pF;
56175 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
56176 ExprList *pList = pF->pExpr->pList;
56177 sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
56178 (void*)pF->pFunc, P3_FUNCDEF);
56183 ** Update the accumulator memory cells for an aggregate based on
56184 ** the current cursor position.
56186 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
56187 Vdbe *v = pParse->pVdbe;
56188 int i;
56189 struct AggInfo_func *pF;
56190 struct AggInfo_col *pC;
56192 pAggInfo->directMode = 1;
56193 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
56194 int nArg;
56195 int addrNext = 0;
56196 ExprList *pList = pF->pExpr->pList;
56197 if( pList ){
56198 nArg = pList->nExpr;
56199 sqlite3ExprCodeExprList(pParse, pList);
56200 }else{
56201 nArg = 0;
56203 if( pF->iDistinct>=0 ){
56204 addrNext = sqlite3VdbeMakeLabel(v);
56205 assert( nArg==1 );
56206 codeDistinct(v, pF->iDistinct, addrNext, 1);
56208 if( pF->pFunc->needCollSeq ){
56209 CollSeq *pColl = 0;
56210 struct ExprList_item *pItem;
56211 int j;
56212 assert( pList!=0 ); /* pList!=0 if pF->pFunc->needCollSeq is true */
56213 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
56214 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
56216 if( !pColl ){
56217 pColl = pParse->db->pDfltColl;
56219 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
56221 sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
56222 if( addrNext ){
56223 sqlite3VdbeResolveLabel(v, addrNext);
56226 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
56227 sqlite3ExprCode(pParse, pC->pExpr);
56228 sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
56230 pAggInfo->directMode = 0;
56235 ** Generate code for the given SELECT statement.
56237 ** The results are distributed in various ways depending on the
56238 ** value of eDest and iParm.
56240 ** eDest Value Result
56241 ** ------------ -------------------------------------------
56242 ** SRT_Callback Invoke the callback for each row of the result.
56244 ** SRT_Mem Store first result in memory cell iParm
56246 ** SRT_Set Store results as keys of table iParm.
56248 ** SRT_Union Store results as a key in a temporary table iParm
56250 ** SRT_Except Remove results from the temporary table iParm.
56252 ** SRT_Table Store results in temporary table iParm
56254 ** The table above is incomplete. Additional eDist value have be added
56255 ** since this comment was written. See the selectInnerLoop() function for
56256 ** a complete listing of the allowed values of eDest and their meanings.
56258 ** This routine returns the number of errors. If any errors are
56259 ** encountered, then an appropriate error message is left in
56260 ** pParse->zErrMsg.
56262 ** This routine does NOT free the Select structure passed in. The
56263 ** calling function needs to do that.
56265 ** The pParent, parentTab, and *pParentAgg fields are filled in if this
56266 ** SELECT is a subquery. This routine may try to combine this SELECT
56267 ** with its parent to form a single flat query. In so doing, it might
56268 ** change the parent query from a non-aggregate to an aggregate query.
56269 ** For that reason, the pParentAgg flag is passed as a pointer, so it
56270 ** can be changed.
56272 ** Example 1: The meaning of the pParent parameter.
56274 ** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
56275 ** \ \_______ subquery _______/ /
56276 ** \ /
56277 ** \____________________ outer query ___________________/
56279 ** This routine is called for the outer query first. For that call,
56280 ** pParent will be NULL. During the processing of the outer query, this
56281 ** routine is called recursively to handle the subquery. For the recursive
56282 ** call, pParent will point to the outer query. Because the subquery is
56283 ** the second element in a three-way join, the parentTab parameter will
56284 ** be 1 (the 2nd value of a 0-indexed array.)
56286 static int sqlite3Select(
56287 Parse *pParse, /* The parser context */
56288 Select *p, /* The SELECT statement being coded. */
56289 int eDest, /* How to dispose of the results */
56290 int iParm, /* A parameter used by the eDest disposal method */
56291 Select *pParent, /* Another SELECT for which this is a sub-query */
56292 int parentTab, /* Index in pParent->pSrc of this query */
56293 int *pParentAgg, /* True if pParent uses aggregate functions */
56294 char *aff /* If eDest is SRT_Union, the affinity string */
56296 int i, j; /* Loop counters */
56297 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
56298 Vdbe *v; /* The virtual machine under construction */
56299 int isAgg; /* True for select lists like "count(*)" */
56300 ExprList *pEList; /* List of columns to extract. */
56301 SrcList *pTabList; /* List of tables to select from */
56302 Expr *pWhere; /* The WHERE clause. May be NULL */
56303 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
56304 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
56305 Expr *pHaving; /* The HAVING clause. May be NULL */
56306 int isDistinct; /* True if the DISTINCT keyword is present */
56307 int distinct; /* Table to use for the distinct set */
56308 int rc = 1; /* Value to return from this function */
56309 int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
56310 AggInfo sAggInfo; /* Information used by aggregate queries */
56311 int iEnd; /* Address of the end of the query */
56313 if( p==0 || sqlite3MallocFailed() || pParse->nErr ){
56314 return 1;
56316 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
56317 memset(&sAggInfo, 0, sizeof(sAggInfo));
56319 #ifndef SQLITE_OMIT_COMPOUND_SELECT
56320 /* If there is are a sequence of queries, do the earlier ones first.
56322 if( p->pPrior ){
56323 if( p->pRightmost==0 ){
56324 Select *pLoop;
56325 int cnt = 0;
56326 for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
56327 pLoop->pRightmost = p;
56329 if( SQLITE_MAX_COMPOUND_SELECT>0 && cnt>SQLITE_MAX_COMPOUND_SELECT ){
56330 sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
56331 return 1;
56334 return multiSelect(pParse, p, eDest, iParm, aff);
56336 #endif
56338 pOrderBy = p->pOrderBy;
56339 if( IgnorableOrderby(eDest) ){
56340 p->pOrderBy = 0;
56342 if( sqlite3SelectResolve(pParse, p, 0) ){
56343 goto select_end;
56345 p->pOrderBy = pOrderBy;
56347 /* Make local copies of the parameters for this query.
56349 pTabList = p->pSrc;
56350 pWhere = p->pWhere;
56351 pGroupBy = p->pGroupBy;
56352 pHaving = p->pHaving;
56353 isAgg = p->isAgg;
56354 isDistinct = p->isDistinct;
56355 pEList = p->pEList;
56356 if( pEList==0 ) goto select_end;
56359 ** Do not even attempt to generate any code if we have already seen
56360 ** errors before this routine starts.
56362 if( pParse->nErr>0 ) goto select_end;
56364 /* If writing to memory or generating a set
56365 ** only a single column may be output.
56367 #ifndef SQLITE_OMIT_SUBQUERY
56368 if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
56369 goto select_end;
56371 #endif
56373 /* ORDER BY is ignored for some destinations.
56375 if( IgnorableOrderby(eDest) ){
56376 pOrderBy = 0;
56379 /* Begin generating code.
56381 v = sqlite3GetVdbe(pParse);
56382 if( v==0 ) goto select_end;
56384 /* Generate code for all sub-queries in the FROM clause
56386 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
56387 for(i=0; i<pTabList->nSrc; i++){
56388 const char *zSavedAuthContext = 0;
56389 int needRestoreContext;
56390 struct SrcList_item *pItem = &pTabList->a[i];
56392 if( pItem->pSelect==0 || pItem->isPopulated ) continue;
56393 if( pItem->zName!=0 ){
56394 zSavedAuthContext = pParse->zAuthContext;
56395 pParse->zAuthContext = pItem->zName;
56396 needRestoreContext = 1;
56397 }else{
56398 needRestoreContext = 0;
56400 #if SQLITE_MAX_EXPR_DEPTH>0
56401 /* Increment Parse.nHeight by the height of the largest expression
56402 ** tree refered to by this, the parent select. The child select
56403 ** may contain expression trees of at most
56404 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
56405 ** more conservative than necessary, but much easier than enforcing
56406 ** an exact limit.
56408 pParse->nHeight += sqlite3SelectExprHeight(p);
56409 #endif
56410 sqlite3Select(pParse, pItem->pSelect, SRT_EphemTab,
56411 pItem->iCursor, p, i, &isAgg, 0);
56412 #if SQLITE_MAX_EXPR_DEPTH>0
56413 pParse->nHeight -= sqlite3SelectExprHeight(p);
56414 #endif
56415 if( needRestoreContext ){
56416 pParse->zAuthContext = zSavedAuthContext;
56418 pTabList = p->pSrc;
56419 pWhere = p->pWhere;
56420 if( !IgnorableOrderby(eDest) ){
56421 pOrderBy = p->pOrderBy;
56423 pGroupBy = p->pGroupBy;
56424 pHaving = p->pHaving;
56425 isDistinct = p->isDistinct;
56427 #endif
56429 /* Check for the special case of a min() or max() function by itself
56430 ** in the result set.
56432 if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
56433 rc = 0;
56434 goto select_end;
56437 /* Check to see if this is a subquery that can be "flattened" into its parent.
56438 ** If flattening is a possiblity, do so and return immediately.
56440 #ifndef SQLITE_OMIT_VIEW
56441 if( pParent && pParentAgg &&
56442 flattenSubquery(pParent, parentTab, *pParentAgg, isAgg) ){
56443 if( isAgg ) *pParentAgg = 1;
56444 goto select_end;
56446 #endif
56448 /* If there is an ORDER BY clause, then this sorting
56449 ** index might end up being unused if the data can be
56450 ** extracted in pre-sorted order. If that is the case, then the
56451 ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
56452 ** we figure out that the sorting index is not needed. The addrSortIndex
56453 ** variable is used to facilitate that change.
56455 if( pOrderBy ){
56456 KeyInfo *pKeyInfo;
56457 if( pParse->nErr ){
56458 goto select_end;
56460 pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
56461 pOrderBy->iECursor = pParse->nTab++;
56462 p->addrOpenEphm[2] = addrSortIndex =
56463 sqlite3VdbeOp3(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
56464 }else{
56465 addrSortIndex = -1;
56468 /* If the output is destined for a temporary table, open that table.
56470 if( eDest==SRT_EphemTab ){
56471 sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, pEList->nExpr);
56474 /* Set the limiter.
56476 iEnd = sqlite3VdbeMakeLabel(v);
56477 computeLimitRegisters(pParse, p, iEnd);
56479 /* Open a virtual index to use for the distinct set.
56481 if( isDistinct ){
56482 KeyInfo *pKeyInfo;
56483 distinct = pParse->nTab++;
56484 pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
56485 sqlite3VdbeOp3(v, OP_OpenEphemeral, distinct, 0,
56486 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
56487 }else{
56488 distinct = -1;
56491 /* Aggregate and non-aggregate queries are handled differently */
56492 if( !isAgg && pGroupBy==0 ){
56493 /* This case is for non-aggregate queries
56494 ** Begin the database scan
56496 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
56497 if( pWInfo==0 ) goto select_end;
56499 /* If sorting index that was created by a prior OP_OpenEphemeral
56500 ** instruction ended up not being needed, then change the OP_OpenEphemeral
56501 ** into an OP_Noop.
56503 if( addrSortIndex>=0 && pOrderBy==0 ){
56504 sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
56505 p->addrOpenEphm[2] = -1;
56508 /* Use the standard inner loop
56510 if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
56511 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
56512 goto select_end;
56515 /* End the database scan loop.
56517 sqlite3WhereEnd(pWInfo);
56518 }else{
56519 /* This is the processing for aggregate queries */
56520 NameContext sNC; /* Name context for processing aggregate information */
56521 int iAMem; /* First Mem address for storing current GROUP BY */
56522 int iBMem; /* First Mem address for previous GROUP BY */
56523 int iUseFlag; /* Mem address holding flag indicating that at least
56524 ** one row of the input to the aggregator has been
56525 ** processed */
56526 int iAbortFlag; /* Mem address which causes query abort if positive */
56527 int groupBySort; /* Rows come from source in GROUP BY order */
56530 /* The following variables hold addresses or labels for parts of the
56531 ** virtual machine program we are putting together */
56532 int addrOutputRow; /* Start of subroutine that outputs a result row */
56533 int addrSetAbort; /* Set the abort flag and return */
56534 int addrInitializeLoop; /* Start of code that initializes the input loop */
56535 int addrTopOfLoop; /* Top of the input loop */
56536 int addrGroupByChange; /* Code that runs when any GROUP BY term changes */
56537 int addrProcessRow; /* Code to process a single input row */
56538 int addrEnd; /* End of all processing */
56539 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
56540 int addrReset; /* Subroutine for resetting the accumulator */
56542 addrEnd = sqlite3VdbeMakeLabel(v);
56544 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
56545 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
56546 ** SELECT statement.
56548 memset(&sNC, 0, sizeof(sNC));
56549 sNC.pParse = pParse;
56550 sNC.pSrcList = pTabList;
56551 sNC.pAggInfo = &sAggInfo;
56552 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
56553 sAggInfo.pGroupBy = pGroupBy;
56554 if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
56555 goto select_end;
56557 if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
56558 goto select_end;
56560 if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
56561 goto select_end;
56563 sAggInfo.nAccumulator = sAggInfo.nColumn;
56564 for(i=0; i<sAggInfo.nFunc; i++){
56565 if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
56566 goto select_end;
56569 if( sqlite3MallocFailed() ) goto select_end;
56571 /* Processing for aggregates with GROUP BY is very different and
56572 ** much more complex tha aggregates without a GROUP BY.
56574 if( pGroupBy ){
56575 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
56577 /* Create labels that we will be needing
56580 addrInitializeLoop = sqlite3VdbeMakeLabel(v);
56581 addrGroupByChange = sqlite3VdbeMakeLabel(v);
56582 addrProcessRow = sqlite3VdbeMakeLabel(v);
56584 /* If there is a GROUP BY clause we might need a sorting index to
56585 ** implement it. Allocate that sorting index now. If it turns out
56586 ** that we do not need it after all, the OpenEphemeral instruction
56587 ** will be converted into a Noop.
56589 sAggInfo.sortingIdx = pParse->nTab++;
56590 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
56591 addrSortingIdx =
56592 sqlite3VdbeOp3(v, OP_OpenEphemeral, sAggInfo.sortingIdx,
56593 sAggInfo.nSortingColumn,
56594 (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
56596 /* Initialize memory locations used by GROUP BY aggregate processing
56598 iUseFlag = pParse->nMem++;
56599 iAbortFlag = pParse->nMem++;
56600 iAMem = pParse->nMem;
56601 pParse->nMem += pGroupBy->nExpr;
56602 iBMem = pParse->nMem;
56603 pParse->nMem += pGroupBy->nExpr;
56604 sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag);
56605 VdbeComment((v, "# clear abort flag"));
56606 sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag);
56607 VdbeComment((v, "# indicate accumulator empty"));
56608 sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
56610 /* Generate a subroutine that outputs a single row of the result
56611 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
56612 ** is less than or equal to zero, the subroutine is a no-op. If
56613 ** the processing calls for the query to abort, this subroutine
56614 ** increments the iAbortFlag memory location before returning in
56615 ** order to signal the caller to abort.
56617 addrSetAbort = sqlite3VdbeCurrentAddr(v);
56618 sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag);
56619 VdbeComment((v, "# set abort flag"));
56620 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
56621 addrOutputRow = sqlite3VdbeCurrentAddr(v);
56622 sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
56623 VdbeComment((v, "# Groupby result generator entry point"));
56624 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
56625 finalizeAggFunctions(pParse, &sAggInfo);
56626 if( pHaving ){
56627 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
56629 rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
56630 distinct, eDest, iParm,
56631 addrOutputRow+1, addrSetAbort, aff);
56632 if( rc ){
56633 goto select_end;
56635 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
56636 VdbeComment((v, "# end groupby result generator"));
56638 /* Generate a subroutine that will reset the group-by accumulator
56640 addrReset = sqlite3VdbeCurrentAddr(v);
56641 resetAccumulator(pParse, &sAggInfo);
56642 sqlite3VdbeAddOp(v, OP_Return, 0, 0);
56644 /* Begin a loop that will extract all source rows in GROUP BY order.
56645 ** This might involve two separate loops with an OP_Sort in between, or
56646 ** it might be a single loop that uses an index to extract information
56647 ** in the right order to begin with.
56649 sqlite3VdbeResolveLabel(v, addrInitializeLoop);
56650 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
56651 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
56652 if( pWInfo==0 ) goto select_end;
56653 if( pGroupBy==0 ){
56654 /* The optimizer is able to deliver rows in group by order so
56655 ** we do not have to sort. The OP_OpenEphemeral table will be
56656 ** cancelled later because we still need to use the pKeyInfo
56658 pGroupBy = p->pGroupBy;
56659 groupBySort = 0;
56660 }else{
56661 /* Rows are coming out in undetermined order. We have to push
56662 ** each row into a sorting index, terminate the first loop,
56663 ** then loop over the sorting index in order to get the output
56664 ** in sorted order
56666 groupBySort = 1;
56667 sqlite3ExprCodeExprList(pParse, pGroupBy);
56668 sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
56669 j = pGroupBy->nExpr+1;
56670 for(i=0; i<sAggInfo.nColumn; i++){
56671 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
56672 if( pCol->iSorterColumn<j ) continue;
56673 sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable);
56674 j++;
56676 sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
56677 sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
56678 sqlite3WhereEnd(pWInfo);
56679 sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
56680 VdbeComment((v, "# GROUP BY sort"));
56681 sAggInfo.useSortingIdx = 1;
56684 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
56685 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
56686 ** Then compare the current GROUP BY terms against the GROUP BY terms
56687 ** from the previous row currently stored in a0, a1, a2...
56689 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
56690 for(j=0; j<pGroupBy->nExpr; j++){
56691 if( groupBySort ){
56692 sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
56693 }else{
56694 sAggInfo.directMode = 1;
56695 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
56697 sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
56699 for(j=pGroupBy->nExpr-1; j>=0; j--){
56700 if( j<pGroupBy->nExpr-1 ){
56701 sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
56703 sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
56704 if( j==0 ){
56705 sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow);
56706 }else{
56707 sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange);
56709 sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
56712 /* Generate code that runs whenever the GROUP BY changes.
56713 ** Change in the GROUP BY are detected by the previous code
56714 ** block. If there were no changes, this block is skipped.
56716 ** This code copies current group by terms in b0,b1,b2,...
56717 ** over to a0,a1,a2. It then calls the output subroutine
56718 ** and resets the aggregate accumulator registers in preparation
56719 ** for the next GROUP BY batch.
56721 sqlite3VdbeResolveLabel(v, addrGroupByChange);
56722 for(j=0; j<pGroupBy->nExpr; j++){
56723 sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j);
56725 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
56726 VdbeComment((v, "# output one row"));
56727 sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
56728 VdbeComment((v, "# check abort flag"));
56729 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
56730 VdbeComment((v, "# reset accumulator"));
56732 /* Update the aggregate accumulators based on the content of
56733 ** the current row
56735 sqlite3VdbeResolveLabel(v, addrProcessRow);
56736 updateAccumulator(pParse, &sAggInfo);
56737 sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag);
56738 VdbeComment((v, "# indicate data in accumulator"));
56740 /* End of the loop
56742 if( groupBySort ){
56743 sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
56744 }else{
56745 sqlite3WhereEnd(pWInfo);
56746 sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
56749 /* Output the final row of result
56751 sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
56752 VdbeComment((v, "# output final row"));
56754 } /* endif pGroupBy */
56755 else {
56756 /* This case runs if the aggregate has no GROUP BY clause. The
56757 ** processing is much simpler since there is only a single row
56758 ** of output.
56760 resetAccumulator(pParse, &sAggInfo);
56761 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
56762 if( pWInfo==0 ) goto select_end;
56763 updateAccumulator(pParse, &sAggInfo);
56764 sqlite3WhereEnd(pWInfo);
56765 finalizeAggFunctions(pParse, &sAggInfo);
56766 pOrderBy = 0;
56767 if( pHaving ){
56768 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
56770 selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
56771 eDest, iParm, addrEnd, addrEnd, aff);
56773 sqlite3VdbeResolveLabel(v, addrEnd);
56775 } /* endif aggregate query */
56777 /* If there is an ORDER BY clause, then we need to sort the results
56778 ** and send them to the callback one by one.
56780 if( pOrderBy ){
56781 generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
56784 #ifndef SQLITE_OMIT_SUBQUERY
56785 /* If this was a subquery, we have now converted the subquery into a
56786 ** temporary table. So set the SrcList_item.isPopulated flag to prevent
56787 ** this subquery from being evaluated again and to force the use of
56788 ** the temporary table.
56790 if( pParent ){
56791 assert( pParent->pSrc->nSrc>parentTab );
56792 assert( pParent->pSrc->a[parentTab].pSelect==p );
56793 pParent->pSrc->a[parentTab].isPopulated = 1;
56795 #endif
56797 /* Jump here to skip this query
56799 sqlite3VdbeResolveLabel(v, iEnd);
56801 /* The SELECT was successfully coded. Set the return code to 0
56802 ** to indicate no errors.
56804 rc = 0;
56806 /* Control jumps to here if an error is encountered above, or upon
56807 ** successful coding of the SELECT.
56809 select_end:
56811 /* Identify column names if we will be using them in a callback. This
56812 ** step is skipped if the output is going to some other destination.
56814 if( rc==SQLITE_OK && eDest==SRT_Callback ){
56815 generateColumnNames(pParse, pTabList, pEList);
56818 sqliteFree(sAggInfo.aCol);
56819 sqliteFree(sAggInfo.aFunc);
56820 return rc;
56823 #if defined(SQLITE_DEBUG)
56825 *******************************************************************************
56826 ** The following code is used for testing and debugging only. The code
56827 ** that follows does not appear in normal builds.
56829 ** These routines are used to print out the content of all or part of a
56830 ** parse structures such as Select or Expr. Such printouts are useful
56831 ** for helping to understand what is happening inside the code generator
56832 ** during the execution of complex SELECT statements.
56834 ** These routine are not called anywhere from within the normal
56835 ** code base. Then are intended to be called from within the debugger
56836 ** or from temporary "printf" statements inserted for debugging.
56838 static void sqlite3PrintExpr(Expr *p){
56839 if( p->token.z && p->token.n>0 ){
56840 sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
56841 }else{
56842 sqlite3DebugPrintf("(%d", p->op);
56844 if( p->pLeft ){
56845 sqlite3DebugPrintf(" ");
56846 sqlite3PrintExpr(p->pLeft);
56848 if( p->pRight ){
56849 sqlite3DebugPrintf(" ");
56850 sqlite3PrintExpr(p->pRight);
56852 sqlite3DebugPrintf(")");
56854 static void sqlite3PrintExprList(ExprList *pList){
56855 int i;
56856 for(i=0; i<pList->nExpr; i++){
56857 sqlite3PrintExpr(pList->a[i].pExpr);
56858 if( i<pList->nExpr-1 ){
56859 sqlite3DebugPrintf(", ");
56863 static void sqlite3PrintSelect(Select *p, int indent){
56864 sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
56865 sqlite3PrintExprList(p->pEList);
56866 sqlite3DebugPrintf("\n");
56867 if( p->pSrc ){
56868 char *zPrefix;
56869 int i;
56870 zPrefix = "FROM";
56871 for(i=0; i<p->pSrc->nSrc; i++){
56872 struct SrcList_item *pItem = &p->pSrc->a[i];
56873 sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
56874 zPrefix = "";
56875 if( pItem->pSelect ){
56876 sqlite3DebugPrintf("(\n");
56877 sqlite3PrintSelect(pItem->pSelect, indent+10);
56878 sqlite3DebugPrintf("%*s)", indent+8, "");
56879 }else if( pItem->zName ){
56880 sqlite3DebugPrintf("%s", pItem->zName);
56882 if( pItem->pTab ){
56883 sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
56885 if( pItem->zAlias ){
56886 sqlite3DebugPrintf(" AS %s", pItem->zAlias);
56888 if( i<p->pSrc->nSrc-1 ){
56889 sqlite3DebugPrintf(",");
56891 sqlite3DebugPrintf("\n");
56894 if( p->pWhere ){
56895 sqlite3DebugPrintf("%*s WHERE ", indent, "");
56896 sqlite3PrintExpr(p->pWhere);
56897 sqlite3DebugPrintf("\n");
56899 if( p->pGroupBy ){
56900 sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
56901 sqlite3PrintExprList(p->pGroupBy);
56902 sqlite3DebugPrintf("\n");
56904 if( p->pHaving ){
56905 sqlite3DebugPrintf("%*s HAVING ", indent, "");
56906 sqlite3PrintExpr(p->pHaving);
56907 sqlite3DebugPrintf("\n");
56909 if( p->pOrderBy ){
56910 sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
56911 sqlite3PrintExprList(p->pOrderBy);
56912 sqlite3DebugPrintf("\n");
56915 /* End of the structure debug printing code
56916 *****************************************************************************/
56917 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
56919 /************** End of select.c **********************************************/
56920 /************** Begin file table.c *******************************************/
56922 ** 2001 September 15
56924 ** The author disclaims copyright to this source code. In place of
56925 ** a legal notice, here is a blessing:
56927 ** May you do good and not evil.
56928 ** May you find forgiveness for yourself and forgive others.
56929 ** May you share freely, never taking more than you give.
56931 *************************************************************************
56932 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
56933 ** interface routines. These are just wrappers around the main
56934 ** interface routine of sqlite3_exec().
56936 ** These routines are in a separate files so that they will not be linked
56937 ** if they are not used.
56940 #ifndef SQLITE_OMIT_GET_TABLE
56943 ** This structure is used to pass data from sqlite3_get_table() through
56944 ** to the callback function is uses to build the result.
56946 typedef struct TabResult {
56947 char **azResult;
56948 char *zErrMsg;
56949 int nResult;
56950 int nAlloc;
56951 int nRow;
56952 int nColumn;
56953 int nData;
56954 int rc;
56955 } TabResult;
56958 ** This routine is called once for each row in the result table. Its job
56959 ** is to fill in the TabResult structure appropriately, allocating new
56960 ** memory as necessary.
56962 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
56963 TabResult *p = (TabResult*)pArg;
56964 int need;
56965 int i;
56966 char *z;
56968 /* Make sure there is enough space in p->azResult to hold everything
56969 ** we need to remember from this invocation of the callback.
56971 if( p->nRow==0 && argv!=0 ){
56972 need = nCol*2;
56973 }else{
56974 need = nCol;
56976 if( p->nData + need >= p->nAlloc ){
56977 char **azNew;
56978 p->nAlloc = p->nAlloc*2 + need + 1;
56979 azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
56980 if( azNew==0 ) goto malloc_failed;
56981 p->azResult = azNew;
56984 /* If this is the first row, then generate an extra row containing
56985 ** the names of all columns.
56987 if( p->nRow==0 ){
56988 p->nColumn = nCol;
56989 for(i=0; i<nCol; i++){
56990 if( colv[i]==0 ){
56991 z = sqlite3_mprintf("");
56992 }else{
56993 z = sqlite3_mprintf("%s", colv[i]);
56995 p->azResult[p->nData++] = z;
56997 }else if( p->nColumn!=nCol ){
56998 sqlite3SetString(&p->zErrMsg,
56999 "sqlite3_get_table() called with two or more incompatible queries",
57000 (char*)0);
57001 p->rc = SQLITE_ERROR;
57002 return 1;
57005 /* Copy over the row data
57007 if( argv!=0 ){
57008 for(i=0; i<nCol; i++){
57009 if( argv[i]==0 ){
57010 z = 0;
57011 }else{
57012 int n = strlen(argv[i])+1;
57013 z = sqlite3_malloc( n );
57014 if( z==0 ) goto malloc_failed;
57015 memcpy(z, argv[i], n);
57017 p->azResult[p->nData++] = z;
57019 p->nRow++;
57021 return 0;
57023 malloc_failed:
57024 p->rc = SQLITE_NOMEM;
57025 return 1;
57029 ** Query the database. But instead of invoking a callback for each row,
57030 ** malloc() for space to hold the result and return the entire results
57031 ** at the conclusion of the call.
57033 ** The result that is written to ***pazResult is held in memory obtained
57034 ** from malloc(). But the caller cannot free this memory directly.
57035 ** Instead, the entire table should be passed to sqlite3_free_table() when
57036 ** the calling procedure is finished using it.
57038 int sqlite3_get_table(
57039 sqlite3 *db, /* The database on which the SQL executes */
57040 const char *zSql, /* The SQL to be executed */
57041 char ***pazResult, /* Write the result table here */
57042 int *pnRow, /* Write the number of rows in the result here */
57043 int *pnColumn, /* Write the number of columns of result here */
57044 char **pzErrMsg /* Write error messages here */
57046 int rc;
57047 TabResult res;
57048 if( pazResult==0 ){ return SQLITE_ERROR; }
57049 *pazResult = 0;
57050 if( pnColumn ) *pnColumn = 0;
57051 if( pnRow ) *pnRow = 0;
57052 res.zErrMsg = 0;
57053 res.nResult = 0;
57054 res.nRow = 0;
57055 res.nColumn = 0;
57056 res.nData = 1;
57057 res.nAlloc = 20;
57058 res.rc = SQLITE_OK;
57059 res.azResult = sqlite3_malloc( sizeof(char*)*res.nAlloc );
57060 if( res.azResult==0 ) return SQLITE_NOMEM;
57061 res.azResult[0] = 0;
57062 rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
57063 if( res.azResult ){
57064 assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
57065 res.azResult[0] = (char*)res.nData;
57067 if( (rc&0xff)==SQLITE_ABORT ){
57068 sqlite3_free_table(&res.azResult[1]);
57069 if( res.zErrMsg ){
57070 if( pzErrMsg ){
57071 sqlite3_free(*pzErrMsg);
57072 *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
57074 sqliteFree(res.zErrMsg);
57076 db->errCode = res.rc;
57077 return res.rc & db->errMask;
57079 sqliteFree(res.zErrMsg);
57080 if( rc!=SQLITE_OK ){
57081 sqlite3_free_table(&res.azResult[1]);
57082 return rc & db->errMask;
57084 if( res.nAlloc>res.nData ){
57085 char **azNew;
57086 azNew = sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) );
57087 if( azNew==0 ){
57088 sqlite3_free_table(&res.azResult[1]);
57089 return SQLITE_NOMEM;
57091 res.nAlloc = res.nData+1;
57092 res.azResult = azNew;
57094 *pazResult = &res.azResult[1];
57095 if( pnColumn ) *pnColumn = res.nColumn;
57096 if( pnRow ) *pnRow = res.nRow;
57097 return rc & db->errMask;
57101 ** This routine frees the space the sqlite3_get_table() malloced.
57103 void sqlite3_free_table(
57104 char **azResult /* Result returned from from sqlite3_get_table() */
57106 if( azResult ){
57107 int i, n;
57108 azResult--;
57109 if( azResult==0 ) return;
57110 n = (int)azResult[0];
57111 for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
57112 sqlite3_free(azResult);
57116 #endif /* SQLITE_OMIT_GET_TABLE */
57118 /************** End of table.c ***********************************************/
57119 /************** Begin file trigger.c *****************************************/
57122 ** The author disclaims copyright to this source code. In place of
57123 ** a legal notice, here is a blessing:
57125 ** May you do good and not evil.
57126 ** May you find forgiveness for yourself and forgive others.
57127 ** May you share freely, never taking more than you give.
57129 *************************************************************************
57133 #ifndef SQLITE_OMIT_TRIGGER
57135 ** Delete a linked list of TriggerStep structures.
57137 static void sqlite3DeleteTriggerStep(TriggerStep *pTriggerStep){
57138 while( pTriggerStep ){
57139 TriggerStep * pTmp = pTriggerStep;
57140 pTriggerStep = pTriggerStep->pNext;
57142 if( pTmp->target.dyn ) sqliteFree((char*)pTmp->target.z);
57143 sqlite3ExprDelete(pTmp->pWhere);
57144 sqlite3ExprListDelete(pTmp->pExprList);
57145 sqlite3SelectDelete(pTmp->pSelect);
57146 sqlite3IdListDelete(pTmp->pIdList);
57148 sqliteFree(pTmp);
57153 ** This is called by the parser when it sees a CREATE TRIGGER statement
57154 ** up to the point of the BEGIN before the trigger actions. A Trigger
57155 ** structure is generated based on the information available and stored
57156 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
57157 ** sqlite3FinishTrigger() function is called to complete the trigger
57158 ** construction process.
57160 static void sqlite3BeginTrigger(
57161 Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
57162 Token *pName1, /* The name of the trigger */
57163 Token *pName2, /* The name of the trigger */
57164 int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
57165 int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
57166 IdList *pColumns, /* column list if this is an UPDATE OF trigger */
57167 SrcList *pTableName,/* The name of the table/view the trigger applies to */
57168 Expr *pWhen, /* WHEN clause */
57169 int isTemp, /* True if the TEMPORARY keyword is present */
57170 int noErr /* Suppress errors if the trigger already exists */
57172 Trigger *pTrigger = 0;
57173 Table *pTab;
57174 char *zName = 0; /* Name of the trigger */
57175 sqlite3 *db = pParse->db;
57176 int iDb; /* The database to store the trigger in */
57177 Token *pName; /* The unqualified db name */
57178 DbFixer sFix;
57179 int iTabDb;
57181 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
57182 assert( pName2!=0 );
57183 if( isTemp ){
57184 /* If TEMP was specified, then the trigger name may not be qualified. */
57185 if( pName2->n>0 ){
57186 sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
57187 goto trigger_cleanup;
57189 iDb = 1;
57190 pName = pName1;
57191 }else{
57192 /* Figure out the db that the the trigger will be created in */
57193 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
57194 if( iDb<0 ){
57195 goto trigger_cleanup;
57199 /* If the trigger name was unqualified, and the table is a temp table,
57200 ** then set iDb to 1 to create the trigger in the temporary database.
57201 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
57202 ** exist, the error is caught by the block below.
57204 if( !pTableName || sqlite3MallocFailed() ){
57205 goto trigger_cleanup;
57207 pTab = sqlite3SrcListLookup(pParse, pTableName);
57208 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
57209 iDb = 1;
57212 /* Ensure the table name matches database name and that the table exists */
57213 if( sqlite3MallocFailed() ) goto trigger_cleanup;
57214 assert( pTableName->nSrc==1 );
57215 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
57216 sqlite3FixSrcList(&sFix, pTableName) ){
57217 goto trigger_cleanup;
57219 pTab = sqlite3SrcListLookup(pParse, pTableName);
57220 if( !pTab ){
57221 /* The table does not exist. */
57222 goto trigger_cleanup;
57224 if( IsVirtual(pTab) ){
57225 sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
57226 goto trigger_cleanup;
57229 /* Check that the trigger name is not reserved and that no trigger of the
57230 ** specified name exists */
57231 zName = sqlite3NameFromToken(pName);
57232 if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
57233 goto trigger_cleanup;
57235 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash), zName,strlen(zName)) ){
57236 if( !noErr ){
57237 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
57239 goto trigger_cleanup;
57242 /* Do not create a trigger on a system table */
57243 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
57244 sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
57245 pParse->nErr++;
57246 goto trigger_cleanup;
57249 /* INSTEAD of triggers are only for views and views only support INSTEAD
57250 ** of triggers.
57252 if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
57253 sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
57254 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
57255 goto trigger_cleanup;
57257 if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
57258 sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
57259 " trigger on table: %S", pTableName, 0);
57260 goto trigger_cleanup;
57262 iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
57264 #ifndef SQLITE_OMIT_AUTHORIZATION
57266 int code = SQLITE_CREATE_TRIGGER;
57267 const char *zDb = db->aDb[iTabDb].zName;
57268 const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
57269 if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
57270 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
57271 goto trigger_cleanup;
57273 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
57274 goto trigger_cleanup;
57277 #endif
57279 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
57280 ** cannot appear on views. So we might as well translate every
57281 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
57282 ** elsewhere.
57284 if (tr_tm == TK_INSTEAD){
57285 tr_tm = TK_BEFORE;
57288 /* Build the Trigger object */
57289 pTrigger = (Trigger*)sqliteMalloc(sizeof(Trigger));
57290 if( pTrigger==0 ) goto trigger_cleanup;
57291 pTrigger->name = zName;
57292 zName = 0;
57293 pTrigger->table = sqliteStrDup(pTableName->a[0].zName);
57294 pTrigger->pSchema = db->aDb[iDb].pSchema;
57295 pTrigger->pTabSchema = pTab->pSchema;
57296 pTrigger->op = op;
57297 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
57298 pTrigger->pWhen = sqlite3ExprDup(pWhen);
57299 pTrigger->pColumns = sqlite3IdListDup(pColumns);
57300 sqlite3TokenCopy(&pTrigger->nameToken,pName);
57301 assert( pParse->pNewTrigger==0 );
57302 pParse->pNewTrigger = pTrigger;
57304 trigger_cleanup:
57305 sqliteFree(zName);
57306 sqlite3SrcListDelete(pTableName);
57307 sqlite3IdListDelete(pColumns);
57308 sqlite3ExprDelete(pWhen);
57309 if( !pParse->pNewTrigger ){
57310 sqlite3DeleteTrigger(pTrigger);
57311 }else{
57312 assert( pParse->pNewTrigger==pTrigger );
57317 ** This routine is called after all of the trigger actions have been parsed
57318 ** in order to complete the process of building the trigger.
57320 static void sqlite3FinishTrigger(
57321 Parse *pParse, /* Parser context */
57322 TriggerStep *pStepList, /* The triggered program */
57323 Token *pAll /* Token that describes the complete CREATE TRIGGER */
57325 Trigger *pTrig = 0; /* The trigger whose construction is finishing up */
57326 sqlite3 *db = pParse->db; /* The database */
57327 DbFixer sFix;
57328 int iDb; /* Database containing the trigger */
57330 pTrig = pParse->pNewTrigger;
57331 pParse->pNewTrigger = 0;
57332 if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
57333 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
57334 pTrig->step_list = pStepList;
57335 while( pStepList ){
57336 pStepList->pTrig = pTrig;
57337 pStepList = pStepList->pNext;
57339 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken)
57340 && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
57341 goto triggerfinish_cleanup;
57344 /* if we are not initializing, and this trigger is not on a TEMP table,
57345 ** build the sqlite_master entry
57347 if( !db->init.busy ){
57348 static const VdbeOpList insertTrig[] = {
57349 { OP_NewRowid, 0, 0, 0 },
57350 { OP_String8, 0, 0, "trigger" },
57351 { OP_String8, 0, 0, 0 }, /* 2: trigger name */
57352 { OP_String8, 0, 0, 0 }, /* 3: table name */
57353 { OP_Integer, 0, 0, 0 },
57354 { OP_String8, 0, 0, "CREATE TRIGGER "},
57355 { OP_String8, 0, 0, 0 }, /* 6: SQL */
57356 { OP_Concat, 0, 0, 0 },
57357 { OP_MakeRecord, 5, 0, "aaada" },
57358 { OP_Insert, 0, 0, 0 },
57360 int addr;
57361 Vdbe *v;
57363 /* Make an entry in the sqlite_master table */
57364 v = sqlite3GetVdbe(pParse);
57365 if( v==0 ) goto triggerfinish_cleanup;
57366 sqlite3BeginWriteOperation(pParse, 0, iDb);
57367 sqlite3OpenMasterTable(pParse, iDb);
57368 addr = sqlite3VdbeAddOpList(v, ArraySize(insertTrig), insertTrig);
57369 sqlite3VdbeChangeP3(v, addr+2, pTrig->name, 0);
57370 sqlite3VdbeChangeP3(v, addr+3, pTrig->table, 0);
57371 sqlite3VdbeChangeP3(v, addr+6, (char*)pAll->z, pAll->n);
57372 sqlite3ChangeCookie(db, v, iDb);
57373 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
57374 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
57375 sqlite3MPrintf("type='trigger' AND name='%q'", pTrig->name), P3_DYNAMIC);
57378 if( db->init.busy ){
57379 int n;
57380 Table *pTab;
57381 Trigger *pDel;
57382 pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash,
57383 pTrig->name, strlen(pTrig->name), pTrig);
57384 if( pDel ){
57385 assert( sqlite3MallocFailed() && pDel==pTrig );
57386 goto triggerfinish_cleanup;
57388 n = strlen(pTrig->table) + 1;
57389 pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
57390 assert( pTab!=0 );
57391 pTrig->pNext = pTab->pTrigger;
57392 pTab->pTrigger = pTrig;
57393 pTrig = 0;
57396 triggerfinish_cleanup:
57397 sqlite3DeleteTrigger(pTrig);
57398 assert( !pParse->pNewTrigger );
57399 sqlite3DeleteTriggerStep(pStepList);
57403 ** Make a copy of all components of the given trigger step. This has
57404 ** the effect of copying all Expr.token.z values into memory obtained
57405 ** from sqliteMalloc(). As initially created, the Expr.token.z values
57406 ** all point to the input string that was fed to the parser. But that
57407 ** string is ephemeral - it will go away as soon as the sqlite3_exec()
57408 ** call that started the parser exits. This routine makes a persistent
57409 ** copy of all the Expr.token.z strings so that the TriggerStep structure
57410 ** will be valid even after the sqlite3_exec() call returns.
57412 static void sqlitePersistTriggerStep(TriggerStep *p){
57413 if( p->target.z ){
57414 p->target.z = (u8*)sqliteStrNDup((char*)p->target.z, p->target.n);
57415 p->target.dyn = 1;
57417 if( p->pSelect ){
57418 Select *pNew = sqlite3SelectDup(p->pSelect);
57419 sqlite3SelectDelete(p->pSelect);
57420 p->pSelect = pNew;
57422 if( p->pWhere ){
57423 Expr *pNew = sqlite3ExprDup(p->pWhere);
57424 sqlite3ExprDelete(p->pWhere);
57425 p->pWhere = pNew;
57427 if( p->pExprList ){
57428 ExprList *pNew = sqlite3ExprListDup(p->pExprList);
57429 sqlite3ExprListDelete(p->pExprList);
57430 p->pExprList = pNew;
57432 if( p->pIdList ){
57433 IdList *pNew = sqlite3IdListDup(p->pIdList);
57434 sqlite3IdListDelete(p->pIdList);
57435 p->pIdList = pNew;
57440 ** Turn a SELECT statement (that the pSelect parameter points to) into
57441 ** a trigger step. Return a pointer to a TriggerStep structure.
57443 ** The parser calls this routine when it finds a SELECT statement in
57444 ** body of a TRIGGER.
57446 static TriggerStep *sqlite3TriggerSelectStep(Select *pSelect){
57447 TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
57448 if( pTriggerStep==0 ) {
57449 sqlite3SelectDelete(pSelect);
57450 return 0;
57453 pTriggerStep->op = TK_SELECT;
57454 pTriggerStep->pSelect = pSelect;
57455 pTriggerStep->orconf = OE_Default;
57456 sqlitePersistTriggerStep(pTriggerStep);
57458 return pTriggerStep;
57462 ** Build a trigger step out of an INSERT statement. Return a pointer
57463 ** to the new trigger step.
57465 ** The parser calls this routine when it sees an INSERT inside the
57466 ** body of a trigger.
57468 static TriggerStep *sqlite3TriggerInsertStep(
57469 Token *pTableName, /* Name of the table into which we insert */
57470 IdList *pColumn, /* List of columns in pTableName to insert into */
57471 ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
57472 Select *pSelect, /* A SELECT statement that supplies values */
57473 int orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
57475 TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
57477 assert(pEList == 0 || pSelect == 0);
57478 assert(pEList != 0 || pSelect != 0);
57480 if( pTriggerStep ){
57481 pTriggerStep->op = TK_INSERT;
57482 pTriggerStep->pSelect = pSelect;
57483 pTriggerStep->target = *pTableName;
57484 pTriggerStep->pIdList = pColumn;
57485 pTriggerStep->pExprList = pEList;
57486 pTriggerStep->orconf = orconf;
57487 sqlitePersistTriggerStep(pTriggerStep);
57488 }else{
57489 sqlite3IdListDelete(pColumn);
57490 sqlite3ExprListDelete(pEList);
57491 sqlite3SelectDup(pSelect);
57494 return pTriggerStep;
57498 ** Construct a trigger step that implements an UPDATE statement and return
57499 ** a pointer to that trigger step. The parser calls this routine when it
57500 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
57502 static TriggerStep *sqlite3TriggerUpdateStep(
57503 Token *pTableName, /* Name of the table to be updated */
57504 ExprList *pEList, /* The SET clause: list of column and new values */
57505 Expr *pWhere, /* The WHERE clause */
57506 int orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
57508 TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
57509 if( pTriggerStep==0 ){
57510 sqlite3ExprListDelete(pEList);
57511 sqlite3ExprDelete(pWhere);
57512 return 0;
57515 pTriggerStep->op = TK_UPDATE;
57516 pTriggerStep->target = *pTableName;
57517 pTriggerStep->pExprList = pEList;
57518 pTriggerStep->pWhere = pWhere;
57519 pTriggerStep->orconf = orconf;
57520 sqlitePersistTriggerStep(pTriggerStep);
57522 return pTriggerStep;
57526 ** Construct a trigger step that implements a DELETE statement and return
57527 ** a pointer to that trigger step. The parser calls this routine when it
57528 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
57530 static TriggerStep *sqlite3TriggerDeleteStep(Token *pTableName, Expr *pWhere){
57531 TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
57532 if( pTriggerStep==0 ){
57533 sqlite3ExprDelete(pWhere);
57534 return 0;
57537 pTriggerStep->op = TK_DELETE;
57538 pTriggerStep->target = *pTableName;
57539 pTriggerStep->pWhere = pWhere;
57540 pTriggerStep->orconf = OE_Default;
57541 sqlitePersistTriggerStep(pTriggerStep);
57543 return pTriggerStep;
57547 ** Recursively delete a Trigger structure
57549 static void sqlite3DeleteTrigger(Trigger *pTrigger){
57550 if( pTrigger==0 ) return;
57551 sqlite3DeleteTriggerStep(pTrigger->step_list);
57552 sqliteFree(pTrigger->name);
57553 sqliteFree(pTrigger->table);
57554 sqlite3ExprDelete(pTrigger->pWhen);
57555 sqlite3IdListDelete(pTrigger->pColumns);
57556 if( pTrigger->nameToken.dyn ) sqliteFree((char*)pTrigger->nameToken.z);
57557 sqliteFree(pTrigger);
57561 ** This function is called to drop a trigger from the database schema.
57563 ** This may be called directly from the parser and therefore identifies
57564 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
57565 ** same job as this routine except it takes a pointer to the trigger
57566 ** instead of the trigger name.
57568 static void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
57569 Trigger *pTrigger = 0;
57570 int i;
57571 const char *zDb;
57572 const char *zName;
57573 int nName;
57574 sqlite3 *db = pParse->db;
57576 if( sqlite3MallocFailed() ) goto drop_trigger_cleanup;
57577 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
57578 goto drop_trigger_cleanup;
57581 assert( pName->nSrc==1 );
57582 zDb = pName->a[0].zDatabase;
57583 zName = pName->a[0].zName;
57584 nName = strlen(zName);
57585 for(i=OMIT_TEMPDB; i<db->nDb; i++){
57586 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
57587 if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
57588 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
57589 if( pTrigger ) break;
57591 if( !pTrigger ){
57592 if( !noErr ){
57593 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
57595 goto drop_trigger_cleanup;
57597 sqlite3DropTriggerPtr(pParse, pTrigger);
57599 drop_trigger_cleanup:
57600 sqlite3SrcListDelete(pName);
57604 ** Return a pointer to the Table structure for the table that a trigger
57605 ** is set on.
57607 static Table *tableOfTrigger(Trigger *pTrigger){
57608 int n = strlen(pTrigger->table) + 1;
57609 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
57614 ** Drop a trigger given a pointer to that trigger.
57616 static void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
57617 Table *pTable;
57618 Vdbe *v;
57619 sqlite3 *db = pParse->db;
57620 int iDb;
57622 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
57623 assert( iDb>=0 && iDb<db->nDb );
57624 pTable = tableOfTrigger(pTrigger);
57625 assert( pTable );
57626 assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
57627 #ifndef SQLITE_OMIT_AUTHORIZATION
57629 int code = SQLITE_DROP_TRIGGER;
57630 const char *zDb = db->aDb[iDb].zName;
57631 const char *zTab = SCHEMA_TABLE(iDb);
57632 if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
57633 if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
57634 sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
57635 return;
57638 #endif
57640 /* Generate code to destroy the database record of the trigger.
57642 assert( pTable!=0 );
57643 if( (v = sqlite3GetVdbe(pParse))!=0 ){
57644 int base;
57645 static const VdbeOpList dropTrigger[] = {
57646 { OP_Rewind, 0, ADDR(9), 0},
57647 { OP_String8, 0, 0, 0}, /* 1 */
57648 { OP_Column, 0, 1, 0},
57649 { OP_Ne, 0, ADDR(8), 0},
57650 { OP_String8, 0, 0, "trigger"},
57651 { OP_Column, 0, 0, 0},
57652 { OP_Ne, 0, ADDR(8), 0},
57653 { OP_Delete, 0, 0, 0},
57654 { OP_Next, 0, ADDR(1), 0}, /* 8 */
57657 sqlite3BeginWriteOperation(pParse, 0, iDb);
57658 sqlite3OpenMasterTable(pParse, iDb);
57659 base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
57660 sqlite3VdbeChangeP3(v, base+1, pTrigger->name, 0);
57661 sqlite3ChangeCookie(db, v, iDb);
57662 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
57663 sqlite3VdbeOp3(v, OP_DropTrigger, iDb, 0, pTrigger->name, 0);
57668 ** Remove a trigger from the hash tables of the sqlite* pointer.
57670 static void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
57671 Trigger *pTrigger;
57672 int nName = strlen(zName);
57673 pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
57674 zName, nName, 0);
57675 if( pTrigger ){
57676 Table *pTable = tableOfTrigger(pTrigger);
57677 assert( pTable!=0 );
57678 if( pTable->pTrigger == pTrigger ){
57679 pTable->pTrigger = pTrigger->pNext;
57680 }else{
57681 Trigger *cc = pTable->pTrigger;
57682 while( cc ){
57683 if( cc->pNext == pTrigger ){
57684 cc->pNext = cc->pNext->pNext;
57685 break;
57687 cc = cc->pNext;
57689 assert(cc);
57691 sqlite3DeleteTrigger(pTrigger);
57692 db->flags |= SQLITE_InternChanges;
57697 ** pEList is the SET clause of an UPDATE statement. Each entry
57698 ** in pEList is of the format <id>=<expr>. If any of the entries
57699 ** in pEList have an <id> which matches an identifier in pIdList,
57700 ** then return TRUE. If pIdList==NULL, then it is considered a
57701 ** wildcard that matches anything. Likewise if pEList==NULL then
57702 ** it matches anything so always return true. Return false only
57703 ** if there is no match.
57705 static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
57706 int e;
57707 if( !pIdList || !pEList ) return 1;
57708 for(e=0; e<pEList->nExpr; e++){
57709 if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
57711 return 0;
57715 ** Return a bit vector to indicate what kind of triggers exist for operation
57716 ** "op" on table pTab. If pChanges is not NULL then it is a list of columns
57717 ** that are being updated. Triggers only match if the ON clause of the
57718 ** trigger definition overlaps the set of columns being updated.
57720 ** The returned bit vector is some combination of TRIGGER_BEFORE and
57721 ** TRIGGER_AFTER.
57723 static int sqlite3TriggersExist(
57724 Parse *pParse, /* Used to check for recursive triggers */
57725 Table *pTab, /* The table the contains the triggers */
57726 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
57727 ExprList *pChanges /* Columns that change in an UPDATE statement */
57729 Trigger *pTrigger;
57730 int mask = 0;
57732 pTrigger = IsVirtual(pTab) ? 0 : pTab->pTrigger;
57733 while( pTrigger ){
57734 if( pTrigger->op==op && checkColumnOverLap(pTrigger->pColumns, pChanges) ){
57735 mask |= pTrigger->tr_tm;
57737 pTrigger = pTrigger->pNext;
57739 return mask;
57743 ** Convert the pStep->target token into a SrcList and return a pointer
57744 ** to that SrcList.
57746 ** This routine adds a specific database name, if needed, to the target when
57747 ** forming the SrcList. This prevents a trigger in one database from
57748 ** referring to a target in another database. An exception is when the
57749 ** trigger is in TEMP in which case it can refer to any other database it
57750 ** wants.
57752 static SrcList *targetSrcList(
57753 Parse *pParse, /* The parsing context */
57754 TriggerStep *pStep /* The trigger containing the target token */
57756 Token sDb; /* Dummy database name token */
57757 int iDb; /* Index of the database to use */
57758 SrcList *pSrc; /* SrcList to be returned */
57760 iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
57761 if( iDb==0 || iDb>=2 ){
57762 assert( iDb<pParse->db->nDb );
57763 sDb.z = (u8*)pParse->db->aDb[iDb].zName;
57764 sDb.n = strlen((char*)sDb.z);
57765 pSrc = sqlite3SrcListAppend(0, &sDb, &pStep->target);
57766 } else {
57767 pSrc = sqlite3SrcListAppend(0, &pStep->target, 0);
57769 return pSrc;
57773 ** Generate VDBE code for zero or more statements inside the body of a
57774 ** trigger.
57776 static int codeTriggerProgram(
57777 Parse *pParse, /* The parser context */
57778 TriggerStep *pStepList, /* List of statements inside the trigger body */
57779 int orconfin /* Conflict algorithm. (OE_Abort, etc) */
57781 TriggerStep * pTriggerStep = pStepList;
57782 int orconf;
57783 Vdbe *v = pParse->pVdbe;
57785 assert( pTriggerStep!=0 );
57786 assert( v!=0 );
57787 sqlite3VdbeAddOp(v, OP_ContextPush, 0, 0);
57788 VdbeComment((v, "# begin trigger %s", pStepList->pTrig->name));
57789 while( pTriggerStep ){
57790 orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
57791 pParse->trigStack->orconf = orconf;
57792 switch( pTriggerStep->op ){
57793 case TK_SELECT: {
57794 Select *ss = sqlite3SelectDup(pTriggerStep->pSelect);
57795 if( ss ){
57796 sqlite3SelectResolve(pParse, ss, 0);
57797 sqlite3Select(pParse, ss, SRT_Discard, 0, 0, 0, 0, 0);
57798 sqlite3SelectDelete(ss);
57800 break;
57802 case TK_UPDATE: {
57803 SrcList *pSrc;
57804 pSrc = targetSrcList(pParse, pTriggerStep);
57805 sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
57806 sqlite3Update(pParse, pSrc,
57807 sqlite3ExprListDup(pTriggerStep->pExprList),
57808 sqlite3ExprDup(pTriggerStep->pWhere), orconf);
57809 sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
57810 break;
57812 case TK_INSERT: {
57813 SrcList *pSrc;
57814 pSrc = targetSrcList(pParse, pTriggerStep);
57815 sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
57816 sqlite3Insert(pParse, pSrc,
57817 sqlite3ExprListDup(pTriggerStep->pExprList),
57818 sqlite3SelectDup(pTriggerStep->pSelect),
57819 sqlite3IdListDup(pTriggerStep->pIdList), orconf);
57820 sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
57821 break;
57823 case TK_DELETE: {
57824 SrcList *pSrc;
57825 sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
57826 pSrc = targetSrcList(pParse, pTriggerStep);
57827 sqlite3DeleteFrom(pParse, pSrc, sqlite3ExprDup(pTriggerStep->pWhere));
57828 sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0);
57829 break;
57831 default:
57832 assert(0);
57834 pTriggerStep = pTriggerStep->pNext;
57836 sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
57837 VdbeComment((v, "# end trigger %s", pStepList->pTrig->name));
57839 return 0;
57843 ** This is called to code FOR EACH ROW triggers.
57845 ** When the code that this function generates is executed, the following
57846 ** must be true:
57848 ** 1. No cursors may be open in the main database. (But newIdx and oldIdx
57849 ** can be indices of cursors in temporary tables. See below.)
57851 ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
57852 ** a temporary vdbe cursor (index newIdx) must be open and pointing at
57853 ** a row containing values to be substituted for new.* expressions in the
57854 ** trigger program(s).
57856 ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
57857 ** a temporary vdbe cursor (index oldIdx) must be open and pointing at
57858 ** a row containing values to be substituted for old.* expressions in the
57859 ** trigger program(s).
57862 static int sqlite3CodeRowTrigger(
57863 Parse *pParse, /* Parse context */
57864 int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
57865 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
57866 int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
57867 Table *pTab, /* The table to code triggers from */
57868 int newIdx, /* The indice of the "new" row to access */
57869 int oldIdx, /* The indice of the "old" row to access */
57870 int orconf, /* ON CONFLICT policy */
57871 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
57873 Trigger *p;
57874 TriggerStack trigStackEntry;
57876 assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
57877 assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
57879 assert(newIdx != -1 || oldIdx != -1);
57881 for(p=pTab->pTrigger; p; p=p->pNext){
57882 int fire_this = 0;
57884 /* Determine whether we should code this trigger */
57885 if(
57886 p->op==op &&
57887 p->tr_tm==tr_tm &&
57888 (p->pSchema==p->pTabSchema || p->pSchema==pParse->db->aDb[1].pSchema) &&
57889 (op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
57891 TriggerStack *pS; /* Pointer to trigger-stack entry */
57892 for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
57893 if( !pS ){
57894 fire_this = 1;
57896 #if 0 /* Give no warning for recursive triggers. Just do not do them */
57897 else{
57898 sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
57899 p->name);
57900 return SQLITE_ERROR;
57902 #endif
57905 if( fire_this ){
57906 int endTrigger;
57907 Expr * whenExpr;
57908 AuthContext sContext;
57909 NameContext sNC;
57911 memset(&sNC, 0, sizeof(sNC));
57912 sNC.pParse = pParse;
57914 /* Push an entry on to the trigger stack */
57915 trigStackEntry.pTrigger = p;
57916 trigStackEntry.newIdx = newIdx;
57917 trigStackEntry.oldIdx = oldIdx;
57918 trigStackEntry.pTab = pTab;
57919 trigStackEntry.pNext = pParse->trigStack;
57920 trigStackEntry.ignoreJump = ignoreJump;
57921 pParse->trigStack = &trigStackEntry;
57922 sqlite3AuthContextPush(pParse, &sContext, p->name);
57924 /* code the WHEN clause */
57925 endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
57926 whenExpr = sqlite3ExprDup(p->pWhen);
57927 if( sqlite3ExprResolveNames(&sNC, whenExpr) ){
57928 pParse->trigStack = trigStackEntry.pNext;
57929 sqlite3ExprDelete(whenExpr);
57930 return 1;
57932 sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, 1);
57933 sqlite3ExprDelete(whenExpr);
57935 codeTriggerProgram(pParse, p->step_list, orconf);
57937 /* Pop the entry off the trigger stack */
57938 pParse->trigStack = trigStackEntry.pNext;
57939 sqlite3AuthContextPop(&sContext);
57941 sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
57944 return 0;
57946 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
57948 /************** End of trigger.c *********************************************/
57949 /************** Begin file update.c ******************************************/
57951 ** 2001 September 15
57953 ** The author disclaims copyright to this source code. In place of
57954 ** a legal notice, here is a blessing:
57956 ** May you do good and not evil.
57957 ** May you find forgiveness for yourself and forgive others.
57958 ** May you share freely, never taking more than you give.
57960 *************************************************************************
57961 ** This file contains C code routines that are called by the parser
57962 ** to handle UPDATE statements.
57964 ** $Id: update.c,v 1.137 2007/03/29 05:51:49 drh Exp $
57967 #ifndef SQLITE_OMIT_VIRTUALTABLE
57968 /* Forward declaration */
57969 static void updateVirtualTable(
57970 Parse *pParse, /* The parsing context */
57971 SrcList *pSrc, /* The virtual table to be modified */
57972 Table *pTab, /* The virtual table */
57973 ExprList *pChanges, /* The columns to change in the UPDATE statement */
57974 Expr *pRowidExpr, /* Expression used to recompute the rowid */
57975 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
57976 Expr *pWhere /* WHERE clause of the UPDATE statement */
57978 #endif /* SQLITE_OMIT_VIRTUALTABLE */
57981 ** The most recently coded instruction was an OP_Column to retrieve the
57982 ** i-th column of table pTab. This routine sets the P3 parameter of the
57983 ** OP_Column to the default value, if any.
57985 ** The default value of a column is specified by a DEFAULT clause in the
57986 ** column definition. This was either supplied by the user when the table
57987 ** was created, or added later to the table definition by an ALTER TABLE
57988 ** command. If the latter, then the row-records in the table btree on disk
57989 ** may not contain a value for the column and the default value, taken
57990 ** from the P3 parameter of the OP_Column instruction, is returned instead.
57991 ** If the former, then all row-records are guaranteed to include a value
57992 ** for the column and the P3 value is not required.
57994 ** Column definitions created by an ALTER TABLE command may only have
57995 ** literal default values specified: a number, null or a string. (If a more
57996 ** complicated default expression value was provided, it is evaluated
57997 ** when the ALTER TABLE is executed and one of the literal values written
57998 ** into the sqlite_master table.)
58000 ** Therefore, the P3 parameter is only required if the default value for
58001 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
58002 ** function is capable of transforming these types of expressions into
58003 ** sqlite3_value objects.
58005 static void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
58006 if( pTab && !pTab->pSelect ){
58007 sqlite3_value *pValue;
58008 u8 enc = ENC(sqlite3VdbeDb(v));
58009 Column *pCol = &pTab->aCol[i];
58010 sqlite3ValueFromExpr(pCol->pDflt, enc, pCol->affinity, &pValue);
58011 if( pValue ){
58012 sqlite3VdbeChangeP3(v, -1, (const char *)pValue, P3_MEM);
58013 }else{
58014 VdbeComment((v, "# %s.%s", pTab->zName, pCol->zName));
58020 ** Process an UPDATE statement.
58022 ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
58023 ** \_______/ \________/ \______/ \________________/
58024 * onError pTabList pChanges pWhere
58026 static void sqlite3Update(
58027 Parse *pParse, /* The parser context */
58028 SrcList *pTabList, /* The table in which we should change things */
58029 ExprList *pChanges, /* Things to be changed */
58030 Expr *pWhere, /* The WHERE clause. May be null */
58031 int onError /* How to handle constraint errors */
58033 int i, j; /* Loop counters */
58034 Table *pTab; /* The table to be updated */
58035 int addr = 0; /* VDBE instruction address of the start of the loop */
58036 WhereInfo *pWInfo; /* Information about the WHERE clause */
58037 Vdbe *v; /* The virtual database engine */
58038 Index *pIdx; /* For looping over indices */
58039 int nIdx; /* Number of indices that need updating */
58040 int nIdxTotal; /* Total number of indices */
58041 int iCur; /* VDBE Cursor number of pTab */
58042 sqlite3 *db; /* The database structure */
58043 Index **apIdx = 0; /* An array of indices that need updating too */
58044 char *aIdxUsed = 0; /* aIdxUsed[i]==1 if the i-th index is used */
58045 int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
58046 ** an expression for the i-th column of the table.
58047 ** aXRef[i]==-1 if the i-th column is not changed. */
58048 int chngRowid; /* True if the record number is being changed */
58049 Expr *pRowidExpr = 0; /* Expression defining the new record number */
58050 int openAll = 0; /* True if all indices need to be opened */
58051 AuthContext sContext; /* The authorization context */
58052 NameContext sNC; /* The name-context to resolve expressions in */
58053 int iDb; /* Database containing the table being updated */
58054 int memCnt = 0; /* Memory cell used for counting rows changed */
58056 #ifndef SQLITE_OMIT_TRIGGER
58057 int isView; /* Trying to update a view */
58058 int triggers_exist = 0; /* True if any row triggers exist */
58059 #endif
58061 int newIdx = -1; /* index of trigger "new" temp table */
58062 int oldIdx = -1; /* index of trigger "old" temp table */
58064 sContext.pParse = 0;
58065 if( pParse->nErr || sqlite3MallocFailed() ){
58066 goto update_cleanup;
58068 db = pParse->db;
58069 assert( pTabList->nSrc==1 );
58071 /* Locate the table which we want to update.
58073 pTab = sqlite3SrcListLookup(pParse, pTabList);
58074 if( pTab==0 ) goto update_cleanup;
58075 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
58077 /* Figure out if we have any triggers and if the table being
58078 ** updated is a view
58080 #ifndef SQLITE_OMIT_TRIGGER
58081 triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges);
58082 isView = pTab->pSelect!=0;
58083 #else
58084 # define triggers_exist 0
58085 # define isView 0
58086 #endif
58087 #ifdef SQLITE_OMIT_VIEW
58088 # undef isView
58089 # define isView 0
58090 #endif
58092 if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
58093 goto update_cleanup;
58095 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
58096 goto update_cleanup;
58098 aXRef = sqliteMallocRaw( sizeof(int) * pTab->nCol );
58099 if( aXRef==0 ) goto update_cleanup;
58100 for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
58102 /* If there are FOR EACH ROW triggers, allocate cursors for the
58103 ** special OLD and NEW tables
58105 if( triggers_exist ){
58106 newIdx = pParse->nTab++;
58107 oldIdx = pParse->nTab++;
58110 /* Allocate a cursors for the main database table and for all indices.
58111 ** The index cursors might not be used, but if they are used they
58112 ** need to occur right after the database cursor. So go ahead and
58113 ** allocate enough space, just in case.
58115 pTabList->a[0].iCursor = iCur = pParse->nTab++;
58116 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
58117 pParse->nTab++;
58120 /* Initialize the name-context */
58121 memset(&sNC, 0, sizeof(sNC));
58122 sNC.pParse = pParse;
58123 sNC.pSrcList = pTabList;
58125 /* Resolve the column names in all the expressions of the
58126 ** of the UPDATE statement. Also find the column index
58127 ** for each column to be updated in the pChanges array. For each
58128 ** column to be updated, make sure we have authorization to change
58129 ** that column.
58131 chngRowid = 0;
58132 for(i=0; i<pChanges->nExpr; i++){
58133 if( sqlite3ExprResolveNames(&sNC, pChanges->a[i].pExpr) ){
58134 goto update_cleanup;
58136 for(j=0; j<pTab->nCol; j++){
58137 if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
58138 if( j==pTab->iPKey ){
58139 chngRowid = 1;
58140 pRowidExpr = pChanges->a[i].pExpr;
58142 aXRef[j] = i;
58143 break;
58146 if( j>=pTab->nCol ){
58147 if( sqlite3IsRowid(pChanges->a[i].zName) ){
58148 chngRowid = 1;
58149 pRowidExpr = pChanges->a[i].pExpr;
58150 }else{
58151 sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
58152 goto update_cleanup;
58155 #ifndef SQLITE_OMIT_AUTHORIZATION
58157 int rc;
58158 rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
58159 pTab->aCol[j].zName, db->aDb[iDb].zName);
58160 if( rc==SQLITE_DENY ){
58161 goto update_cleanup;
58162 }else if( rc==SQLITE_IGNORE ){
58163 aXRef[j] = -1;
58166 #endif
58169 /* Allocate memory for the array apIdx[] and fill it with pointers to every
58170 ** index that needs to be updated. Indices only need updating if their
58171 ** key includes one of the columns named in pChanges or if the record
58172 ** number of the original table entry is changing.
58174 for(nIdx=nIdxTotal=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdxTotal++){
58175 if( chngRowid ){
58176 i = 0;
58177 }else {
58178 for(i=0; i<pIdx->nColumn; i++){
58179 if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
58182 if( i<pIdx->nColumn ) nIdx++;
58184 if( nIdxTotal>0 ){
58185 apIdx = sqliteMallocRaw( sizeof(Index*) * nIdx + nIdxTotal );
58186 if( apIdx==0 ) goto update_cleanup;
58187 aIdxUsed = (char*)&apIdx[nIdx];
58189 for(nIdx=j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
58190 if( chngRowid ){
58191 i = 0;
58192 }else{
58193 for(i=0; i<pIdx->nColumn; i++){
58194 if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
58197 if( i<pIdx->nColumn ){
58198 apIdx[nIdx++] = pIdx;
58199 aIdxUsed[j] = 1;
58200 }else{
58201 aIdxUsed[j] = 0;
58205 /* Begin generating code.
58207 v = sqlite3GetVdbe(pParse);
58208 if( v==0 ) goto update_cleanup;
58209 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
58210 sqlite3BeginWriteOperation(pParse, 1, iDb);
58212 #ifndef SQLITE_OMIT_VIRTUALTABLE
58213 /* Virtual tables must be handled separately */
58214 if( IsVirtual(pTab) ){
58215 updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
58216 pWhere);
58217 pWhere = 0;
58218 pTabList = 0;
58219 goto update_cleanup;
58221 #endif
58223 /* Resolve the column names in all the expressions in the
58224 ** WHERE clause.
58226 if( sqlite3ExprResolveNames(&sNC, pWhere) ){
58227 goto update_cleanup;
58230 /* Start the view context
58232 if( isView ){
58233 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
58236 /* If we are trying to update a view, realize that view into
58237 ** a ephemeral table.
58239 if( isView ){
58240 Select *pView;
58241 pView = sqlite3SelectDup(pTab->pSelect);
58242 sqlite3Select(pParse, pView, SRT_EphemTab, iCur, 0, 0, 0, 0);
58243 sqlite3SelectDelete(pView);
58246 /* Begin the database scan
58248 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
58249 if( pWInfo==0 ) goto update_cleanup;
58251 /* Remember the rowid of every item to be updated.
58253 sqlite3VdbeAddOp(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, 0);
58254 sqlite3VdbeAddOp(v, OP_FifoWrite, 0, 0);
58256 /* End the database scan loop.
58258 sqlite3WhereEnd(pWInfo);
58260 /* Initialize the count of updated rows
58262 if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
58263 memCnt = pParse->nMem++;
58264 sqlite3VdbeAddOp(v, OP_MemInt, 0, memCnt);
58267 if( triggers_exist ){
58268 /* Create pseudo-tables for NEW and OLD
58270 sqlite3VdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
58271 sqlite3VdbeAddOp(v, OP_SetNumColumns, oldIdx, pTab->nCol);
58272 sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
58273 sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol);
58275 /* The top of the update loop for when there are triggers.
58277 addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, 0);
58279 if( !isView ){
58280 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
58281 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
58282 /* Open a cursor and make it point to the record that is
58283 ** being updated.
58285 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
58287 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
58289 /* Generate the OLD table
58291 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
58292 sqlite3VdbeAddOp(v, OP_RowData, iCur, 0);
58293 sqlite3VdbeAddOp(v, OP_Insert, oldIdx, 0);
58295 /* Generate the NEW table
58297 if( chngRowid ){
58298 sqlite3ExprCodeAndCache(pParse, pRowidExpr);
58299 }else{
58300 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
58302 for(i=0; i<pTab->nCol; i++){
58303 if( i==pTab->iPKey ){
58304 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
58305 continue;
58307 j = aXRef[i];
58308 if( j<0 ){
58309 sqlite3VdbeAddOp(v, OP_Column, iCur, i);
58310 sqlite3ColumnDefault(v, pTab, i);
58311 }else{
58312 sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr);
58315 sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
58316 if( !isView ){
58317 sqlite3TableAffinityStr(v, pTab);
58319 if( pParse->nErr ) goto update_cleanup;
58320 sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0);
58321 if( !isView ){
58322 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
58325 /* Fire the BEFORE and INSTEAD OF triggers
58327 if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab,
58328 newIdx, oldIdx, onError, addr) ){
58329 goto update_cleanup;
58333 if( !isView && !IsVirtual(pTab) ){
58335 ** Open every index that needs updating. Note that if any
58336 ** index could potentially invoke a REPLACE conflict resolution
58337 ** action, then we need to open all indices because we might need
58338 ** to be deleting some records.
58340 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
58341 if( onError==OE_Replace ){
58342 openAll = 1;
58343 }else{
58344 openAll = 0;
58345 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
58346 if( pIdx->onError==OE_Replace ){
58347 openAll = 1;
58348 break;
58352 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
58353 if( openAll || aIdxUsed[i] ){
58354 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
58355 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
58356 sqlite3VdbeOp3(v, OP_OpenWrite, iCur+i+1, pIdx->tnum,
58357 (char*)pKey, P3_KEYINFO_HANDOFF);
58358 assert( pParse->nTab>iCur+i+1 );
58362 /* Loop over every record that needs updating. We have to load
58363 ** the old data for each record to be updated because some columns
58364 ** might not change and we will need to copy the old value.
58365 ** Also, the old data is needed to delete the old index entries.
58366 ** So make the cursor point at the old record.
58368 if( !triggers_exist ){
58369 addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, 0);
58370 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
58372 sqlite3VdbeAddOp(v, OP_NotExists, iCur, addr);
58374 /* If the record number will change, push the record number as it
58375 ** will be after the update. (The old record number is currently
58376 ** on top of the stack.)
58378 if( chngRowid ){
58379 sqlite3ExprCode(pParse, pRowidExpr);
58380 sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
58383 /* Compute new data for this record.
58385 for(i=0; i<pTab->nCol; i++){
58386 if( i==pTab->iPKey ){
58387 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
58388 continue;
58390 j = aXRef[i];
58391 if( j<0 ){
58392 sqlite3VdbeAddOp(v, OP_Column, iCur, i);
58393 sqlite3ColumnDefault(v, pTab, i);
58394 }else{
58395 sqlite3ExprCode(pParse, pChanges->a[j].pExpr);
58399 /* Do constraint checks
58401 sqlite3GenerateConstraintChecks(pParse, pTab, iCur, aIdxUsed, chngRowid, 1,
58402 onError, addr);
58404 /* Delete the old indices for the current record.
58406 sqlite3GenerateRowIndexDelete(v, pTab, iCur, aIdxUsed);
58408 /* If changing the record number, delete the old record.
58410 if( chngRowid ){
58411 sqlite3VdbeAddOp(v, OP_Delete, iCur, 0);
58414 /* Create the new index entries and the new record.
58416 sqlite3CompleteInsertion(pParse, pTab, iCur, aIdxUsed, chngRowid, 1, -1, 0);
58419 /* Increment the row counter
58421 if( db->flags & SQLITE_CountRows && !pParse->trigStack){
58422 sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt);
58425 /* If there are triggers, close all the cursors after each iteration
58426 ** through the loop. The fire the after triggers.
58428 if( triggers_exist ){
58429 if( !isView ){
58430 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
58431 if( openAll || aIdxUsed[i] )
58432 sqlite3VdbeAddOp(v, OP_Close, iCur+i+1, 0);
58434 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
58436 if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab,
58437 newIdx, oldIdx, onError, addr) ){
58438 goto update_cleanup;
58442 /* Repeat the above with the next record to be updated, until
58443 ** all record selected by the WHERE clause have been updated.
58445 sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
58446 sqlite3VdbeJumpHere(v, addr);
58448 /* Close all tables if there were no FOR EACH ROW triggers */
58449 if( !triggers_exist ){
58450 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
58451 if( openAll || aIdxUsed[i] ){
58452 sqlite3VdbeAddOp(v, OP_Close, iCur+i+1, 0);
58455 sqlite3VdbeAddOp(v, OP_Close, iCur, 0);
58456 }else{
58457 sqlite3VdbeAddOp(v, OP_Close, newIdx, 0);
58458 sqlite3VdbeAddOp(v, OP_Close, oldIdx, 0);
58462 ** Return the number of rows that were changed. If this routine is
58463 ** generating code because of a call to sqlite3NestedParse(), do not
58464 ** invoke the callback function.
58466 if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
58467 sqlite3VdbeAddOp(v, OP_MemLoad, memCnt, 0);
58468 sqlite3VdbeAddOp(v, OP_Callback, 1, 0);
58469 sqlite3VdbeSetNumCols(v, 1);
58470 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", P3_STATIC);
58473 update_cleanup:
58474 sqlite3AuthContextPop(&sContext);
58475 sqliteFree(apIdx);
58476 sqliteFree(aXRef);
58477 sqlite3SrcListDelete(pTabList);
58478 sqlite3ExprListDelete(pChanges);
58479 sqlite3ExprDelete(pWhere);
58480 return;
58483 #ifndef SQLITE_OMIT_VIRTUALTABLE
58485 ** Generate code for an UPDATE of a virtual table.
58487 ** The strategy is that we create an ephemerial table that contains
58488 ** for each row to be changed:
58490 ** (A) The original rowid of that row.
58491 ** (B) The revised rowid for the row. (note1)
58492 ** (C) The content of every column in the row.
58494 ** Then we loop over this ephemeral table and for each row in
58495 ** the ephermeral table call VUpdate.
58497 ** When finished, drop the ephemeral table.
58499 ** (note1) Actually, if we know in advance that (A) is always the same
58500 ** as (B) we only store (A), then duplicate (A) when pulling
58501 ** it out of the ephemeral table before calling VUpdate.
58503 static void updateVirtualTable(
58504 Parse *pParse, /* The parsing context */
58505 SrcList *pSrc, /* The virtual table to be modified */
58506 Table *pTab, /* The virtual table */
58507 ExprList *pChanges, /* The columns to change in the UPDATE statement */
58508 Expr *pRowid, /* Expression used to recompute the rowid */
58509 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
58510 Expr *pWhere /* WHERE clause of the UPDATE statement */
58512 Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
58513 ExprList *pEList = 0; /* The result set of the SELECT statement */
58514 Select *pSelect = 0; /* The SELECT statement */
58515 Expr *pExpr; /* Temporary expression */
58516 int ephemTab; /* Table holding the result of the SELECT */
58517 int i; /* Loop counter */
58518 int addr; /* Address of top of loop */
58520 /* Construct the SELECT statement that will find the new values for
58521 ** all updated rows.
58523 pEList = sqlite3ExprListAppend(0, sqlite3CreateIdExpr("_rowid_"), 0);
58524 if( pRowid ){
58525 pEList = sqlite3ExprListAppend(pEList, sqlite3ExprDup(pRowid), 0);
58527 assert( pTab->iPKey<0 );
58528 for(i=0; i<pTab->nCol; i++){
58529 if( aXRef[i]>=0 ){
58530 pExpr = sqlite3ExprDup(pChanges->a[aXRef[i]].pExpr);
58531 }else{
58532 pExpr = sqlite3CreateIdExpr(pTab->aCol[i].zName);
58534 pEList = sqlite3ExprListAppend(pEList, pExpr, 0);
58536 pSelect = sqlite3SelectNew(pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
58538 /* Create the ephemeral table into which the update results will
58539 ** be stored.
58541 assert( v );
58542 ephemTab = pParse->nTab++;
58543 sqlite3VdbeAddOp(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
58545 /* fill the ephemeral table
58547 sqlite3Select(pParse, pSelect, SRT_Table, ephemTab, 0, 0, 0, 0);
58550 ** Generate code to scan the ephemeral table and call VDelete and
58551 ** VInsert
58553 sqlite3VdbeAddOp(v, OP_Rewind, ephemTab, 0);
58554 addr = sqlite3VdbeCurrentAddr(v);
58555 sqlite3VdbeAddOp(v, OP_Column, ephemTab, 0);
58556 if( pRowid ){
58557 sqlite3VdbeAddOp(v, OP_Column, ephemTab, 1);
58558 }else{
58559 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
58561 for(i=0; i<pTab->nCol; i++){
58562 sqlite3VdbeAddOp(v, OP_Column, ephemTab, i+1+(pRowid!=0));
58564 pParse->pVirtualLock = pTab;
58565 sqlite3VdbeOp3(v, OP_VUpdate, 0, pTab->nCol+2,
58566 (const char*)pTab->pVtab, P3_VTAB);
58567 sqlite3VdbeAddOp(v, OP_Next, ephemTab, addr);
58568 sqlite3VdbeJumpHere(v, addr-1);
58569 sqlite3VdbeAddOp(v, OP_Close, ephemTab, 0);
58571 /* Cleanup */
58572 sqlite3SelectDelete(pSelect);
58574 #endif /* SQLITE_OMIT_VIRTUALTABLE */
58576 /************** End of update.c **********************************************/
58577 /************** Begin file vacuum.c ******************************************/
58579 ** 2003 April 6
58581 ** The author disclaims copyright to this source code. In place of
58582 ** a legal notice, here is a blessing:
58584 ** May you do good and not evil.
58585 ** May you find forgiveness for yourself and forgive others.
58586 ** May you share freely, never taking more than you give.
58588 *************************************************************************
58589 ** This file contains code used to implement the VACUUM command.
58591 ** Most of the code in this file may be omitted by defining the
58592 ** SQLITE_OMIT_VACUUM macro.
58594 ** $Id: vacuum.c,v 1.69 2007/03/27 16:19:52 danielk1977 Exp $
58597 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
58599 ** Execute zSql on database db. Return an error code.
58601 static int execSql(sqlite3 *db, const char *zSql){
58602 sqlite3_stmt *pStmt;
58603 if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
58604 return sqlite3_errcode(db);
58606 while( SQLITE_ROW==sqlite3_step(pStmt) ){}
58607 return sqlite3_finalize(pStmt);
58611 ** Execute zSql on database db. The statement returns exactly
58612 ** one column. Execute this as SQL on the same database.
58614 static int execExecSql(sqlite3 *db, const char *zSql){
58615 sqlite3_stmt *pStmt;
58616 int rc;
58618 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
58619 if( rc!=SQLITE_OK ) return rc;
58621 while( SQLITE_ROW==sqlite3_step(pStmt) ){
58622 rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
58623 if( rc!=SQLITE_OK ){
58624 sqlite3_finalize(pStmt);
58625 return rc;
58629 return sqlite3_finalize(pStmt);
58633 ** The non-standard VACUUM command is used to clean up the database,
58634 ** collapse free space, etc. It is modelled after the VACUUM command
58635 ** in PostgreSQL.
58637 ** In version 1.0.x of SQLite, the VACUUM command would call
58638 ** gdbm_reorganize() on all the database tables. But beginning
58639 ** with 2.0.0, SQLite no longer uses GDBM so this command has
58640 ** become a no-op.
58642 static void sqlite3Vacuum(Parse *pParse){
58643 Vdbe *v = sqlite3GetVdbe(pParse);
58644 if( v ){
58645 sqlite3VdbeAddOp(v, OP_Vacuum, 0, 0);
58647 return;
58651 ** This routine implements the OP_Vacuum opcode of the VDBE.
58653 static int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
58654 int rc = SQLITE_OK; /* Return code from service routines */
58655 Btree *pMain; /* The database being vacuumed */
58656 Btree *pTemp; /* The temporary database we vacuum into */
58657 char *zSql = 0; /* SQL statements */
58658 int saved_flags; /* Saved value of the db->flags */
58659 Db *pDb = 0; /* Database to detach at end of vacuum */
58661 /* Save the current value of the write-schema flag before setting it. */
58662 saved_flags = db->flags;
58663 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
58665 if( !db->autoCommit ){
58666 sqlite3SetString(pzErrMsg, "cannot VACUUM from within a transaction",
58667 (char*)0);
58668 rc = SQLITE_ERROR;
58669 goto end_of_vacuum;
58671 pMain = db->aDb[0].pBt;
58673 /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
58674 ** can be set to 'off' for this file, as it is not recovered if a crash
58675 ** occurs anyway. The integrity of the database is maintained by a
58676 ** (possibly synchronous) transaction opened on the main database before
58677 ** sqlite3BtreeCopyFile() is called.
58679 ** An optimisation would be to use a non-journaled pager.
58681 zSql = "ATTACH '' AS vacuum_db;";
58682 rc = execSql(db, zSql);
58683 if( rc!=SQLITE_OK ) goto end_of_vacuum;
58684 pDb = &db->aDb[db->nDb-1];
58685 assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
58686 pTemp = db->aDb[db->nDb-1].pBt;
58687 sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain),
58688 sqlite3BtreeGetReserve(pMain));
58689 if( sqlite3MallocFailed() ){
58690 rc = SQLITE_NOMEM;
58691 goto end_of_vacuum;
58693 assert( sqlite3BtreeGetPageSize(pTemp)==sqlite3BtreeGetPageSize(pMain) );
58694 rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
58695 if( rc!=SQLITE_OK ){
58696 goto end_of_vacuum;
58699 #ifndef SQLITE_OMIT_AUTOVACUUM
58700 sqlite3BtreeSetAutoVacuum(pTemp, sqlite3BtreeGetAutoVacuum(pMain));
58701 #endif
58703 /* Begin a transaction */
58704 rc = execSql(db, "BEGIN EXCLUSIVE;");
58705 if( rc!=SQLITE_OK ) goto end_of_vacuum;
58707 /* Query the schema of the main database. Create a mirror schema
58708 ** in the temporary database.
58710 rc = execExecSql(db,
58711 "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14,100000000) "
58712 " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
58713 " AND rootpage>0"
58715 if( rc!=SQLITE_OK ) goto end_of_vacuum;
58716 rc = execExecSql(db,
58717 "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14,100000000)"
58718 " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
58719 if( rc!=SQLITE_OK ) goto end_of_vacuum;
58720 rc = execExecSql(db,
58721 "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21,100000000) "
58722 " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
58723 if( rc!=SQLITE_OK ) goto end_of_vacuum;
58725 /* Loop through the tables in the main database. For each, do
58726 ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy
58727 ** the contents to the temporary database.
58729 rc = execExecSql(db,
58730 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
58731 "|| ' SELECT * FROM ' || quote(name) || ';'"
58732 "FROM sqlite_master "
58733 "WHERE type = 'table' AND name!='sqlite_sequence' "
58734 " AND rootpage>0"
58737 if( rc!=SQLITE_OK ) goto end_of_vacuum;
58739 /* Copy over the sequence table
58741 rc = execExecSql(db,
58742 "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
58743 "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
58745 if( rc!=SQLITE_OK ) goto end_of_vacuum;
58746 rc = execExecSql(db,
58747 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
58748 "|| ' SELECT * FROM ' || quote(name) || ';' "
58749 "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
58751 if( rc!=SQLITE_OK ) goto end_of_vacuum;
58754 /* Copy the triggers, views, and virtual tables from the main database
58755 ** over to the temporary database. None of these objects has any
58756 ** associated storage, so all we have to do is copy their entries
58757 ** from the SQLITE_MASTER table.
58759 rc = execSql(db,
58760 "INSERT INTO vacuum_db.sqlite_master "
58761 " SELECT type, name, tbl_name, rootpage, sql"
58762 " FROM sqlite_master"
58763 " WHERE type='view' OR type='trigger'"
58764 " OR (type='table' AND rootpage=0)"
58766 if( rc ) goto end_of_vacuum;
58768 /* At this point, unless the main db was completely empty, there is now a
58769 ** transaction open on the vacuum database, but not on the main database.
58770 ** Open a btree level transaction on the main database. This allows a
58771 ** call to sqlite3BtreeCopyFile(). The main database btree level
58772 ** transaction is then committed, so the SQL level never knows it was
58773 ** opened for writing. This way, the SQL transaction used to create the
58774 ** temporary database never needs to be committed.
58776 if( rc==SQLITE_OK ){
58777 u32 meta;
58778 int i;
58780 /* This array determines which meta meta values are preserved in the
58781 ** vacuum. Even entries are the meta value number and odd entries
58782 ** are an increment to apply to the meta value after the vacuum.
58783 ** The increment is used to increase the schema cookie so that other
58784 ** connections to the same database will know to reread the schema.
58786 static const unsigned char aCopy[] = {
58787 1, 1, /* Add one to the old schema cookie */
58788 3, 0, /* Preserve the default page cache size */
58789 5, 0, /* Preserve the default text encoding */
58790 6, 0, /* Preserve the user version */
58793 assert( 1==sqlite3BtreeIsInTrans(pTemp) );
58794 assert( 1==sqlite3BtreeIsInTrans(pMain) );
58796 /* Copy Btree meta values */
58797 for(i=0; i<sizeof(aCopy)/sizeof(aCopy[0]); i+=2){
58798 rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
58799 if( rc!=SQLITE_OK ) goto end_of_vacuum;
58800 rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
58801 if( rc!=SQLITE_OK ) goto end_of_vacuum;
58804 rc = sqlite3BtreeCopyFile(pMain, pTemp);
58805 if( rc!=SQLITE_OK ) goto end_of_vacuum;
58806 rc = sqlite3BtreeCommit(pTemp);
58807 if( rc!=SQLITE_OK ) goto end_of_vacuum;
58808 rc = sqlite3BtreeCommit(pMain);
58811 end_of_vacuum:
58812 /* Restore the original value of db->flags */
58813 db->flags = saved_flags;
58815 /* Currently there is an SQL level transaction open on the vacuum
58816 ** database. No locks are held on any other files (since the main file
58817 ** was committed at the btree level). So it safe to end the transaction
58818 ** by manually setting the autoCommit flag to true and detaching the
58819 ** vacuum database. The vacuum_db journal file is deleted when the pager
58820 ** is closed by the DETACH.
58822 db->autoCommit = 1;
58824 if( pDb ){
58825 sqlite3MallocDisallow();
58826 sqlite3BtreeClose(pDb->pBt);
58827 sqlite3MallocAllow();
58828 pDb->pBt = 0;
58829 pDb->pSchema = 0;
58832 sqlite3ResetInternalSchema(db, 0);
58834 return rc;
58836 #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
58838 /************** End of vacuum.c **********************************************/
58839 /************** Begin file vtab.c ********************************************/
58841 ** 2006 June 10
58843 ** The author disclaims copyright to this source code. In place of
58844 ** a legal notice, here is a blessing:
58846 ** May you do good and not evil.
58847 ** May you find forgiveness for yourself and forgive others.
58848 ** May you share freely, never taking more than you give.
58850 *************************************************************************
58851 ** This file contains code used to help implement virtual tables.
58853 ** $Id: vtab.c,v 1.46 2007/05/04 13:15:57 drh Exp $
58855 #ifndef SQLITE_OMIT_VIRTUALTABLE
58858 ** External API function used to create a new virtual-table module.
58860 int sqlite3_create_module(
58861 sqlite3 *db, /* Database in which module is registered */
58862 const char *zName, /* Name assigned to this module */
58863 const sqlite3_module *pModule, /* The definition of the module */
58864 void *pAux /* Context pointer for xCreate/xConnect */
58866 int nName = strlen(zName);
58867 Module *pMod = (Module *)sqliteMallocRaw(sizeof(Module) + nName + 1);
58868 if( pMod ){
58869 char *zCopy = (char *)(&pMod[1]);
58870 memcpy(zCopy, zName, nName+1);
58871 pMod->zName = zCopy;
58872 pMod->pModule = pModule;
58873 pMod->pAux = pAux;
58874 pMod = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
58875 sqliteFree(pMod);
58876 sqlite3ResetInternalSchema(db, 0);
58878 return sqlite3ApiExit(db, SQLITE_OK);
58882 ** Lock the virtual table so that it cannot be disconnected.
58883 ** Locks nest. Every lock should have a corresponding unlock.
58884 ** If an unlock is omitted, resources leaks will occur.
58886 ** If a disconnect is attempted while a virtual table is locked,
58887 ** the disconnect is deferred until all locks have been removed.
58889 static void sqlite3VtabLock(sqlite3_vtab *pVtab){
58890 pVtab->nRef++;
58894 ** Unlock a virtual table. When the last lock is removed,
58895 ** disconnect the virtual table.
58897 static void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
58898 pVtab->nRef--;
58899 assert(db);
58900 assert(!sqlite3SafetyCheck(db));
58901 if( pVtab->nRef==0 ){
58902 if( db->magic==SQLITE_MAGIC_BUSY ){
58903 sqlite3SafetyOff(db);
58904 pVtab->pModule->xDisconnect(pVtab);
58905 sqlite3SafetyOn(db);
58906 } else {
58907 pVtab->pModule->xDisconnect(pVtab);
58913 ** Clear any and all virtual-table information from the Table record.
58914 ** This routine is called, for example, just before deleting the Table
58915 ** record.
58917 static void sqlite3VtabClear(Table *p){
58918 sqlite3_vtab *pVtab = p->pVtab;
58919 if( pVtab ){
58920 assert( p->pMod && p->pMod->pModule );
58921 sqlite3VtabUnlock(p->pSchema->db, pVtab);
58922 p->pVtab = 0;
58924 if( p->azModuleArg ){
58925 int i;
58926 for(i=0; i<p->nModuleArg; i++){
58927 sqliteFree(p->azModuleArg[i]);
58929 sqliteFree(p->azModuleArg);
58934 ** Add a new module argument to pTable->azModuleArg[].
58935 ** The string is not copied - the pointer is stored. The
58936 ** string will be freed automatically when the table is
58937 ** deleted.
58939 static void addModuleArgument(Table *pTable, char *zArg){
58940 int i = pTable->nModuleArg++;
58941 int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
58942 char **azModuleArg;
58943 azModuleArg = sqliteRealloc(pTable->azModuleArg, nBytes);
58944 if( azModuleArg==0 ){
58945 int j;
58946 for(j=0; j<i; j++){
58947 sqliteFree(pTable->azModuleArg[j]);
58949 sqliteFree(zArg);
58950 sqliteFree(pTable->azModuleArg);
58951 pTable->nModuleArg = 0;
58952 }else{
58953 azModuleArg[i] = zArg;
58954 azModuleArg[i+1] = 0;
58956 pTable->azModuleArg = azModuleArg;
58960 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
58961 ** statement. The module name has been parsed, but the optional list
58962 ** of parameters that follow the module name are still pending.
58964 static void sqlite3VtabBeginParse(
58965 Parse *pParse, /* Parsing context */
58966 Token *pName1, /* Name of new table, or database name */
58967 Token *pName2, /* Name of new table or NULL */
58968 Token *pModuleName /* Name of the module for the virtual table */
58970 int iDb; /* The database the table is being created in */
58971 Table *pTable; /* The new virtual table */
58973 #ifndef SQLITE_OMIT_SHARED_CACHE
58974 if( sqlite3ThreadDataReadOnly()->useSharedData ){
58975 sqlite3ErrorMsg(pParse, "Cannot use virtual tables in shared-cache mode");
58976 return;
58978 #endif
58980 sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
58981 pTable = pParse->pNewTable;
58982 if( pTable==0 || pParse->nErr ) return;
58983 assert( 0==pTable->pIndex );
58985 iDb = sqlite3SchemaToIndex(pParse->db, pTable->pSchema);
58986 assert( iDb>=0 );
58988 pTable->isVirtual = 1;
58989 pTable->nModuleArg = 0;
58990 addModuleArgument(pTable, sqlite3NameFromToken(pModuleName));
58991 addModuleArgument(pTable, sqlite3StrDup(pParse->db->aDb[iDb].zName));
58992 addModuleArgument(pTable, sqlite3StrDup(pTable->zName));
58993 pParse->sNameToken.n = pModuleName->z + pModuleName->n - pName1->z;
58995 #ifndef SQLITE_OMIT_AUTHORIZATION
58996 /* Creating a virtual table invokes the authorization callback twice.
58997 ** The first invocation, to obtain permission to INSERT a row into the
58998 ** sqlite_master table, has already been made by sqlite3StartTable().
58999 ** The second call, to obtain permission to create the table, is made now.
59001 if( pTable->azModuleArg ){
59002 sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
59003 pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
59005 #endif
59009 ** This routine takes the module argument that has been accumulating
59010 ** in pParse->zArg[] and appends it to the list of arguments on the
59011 ** virtual table currently under construction in pParse->pTable.
59013 static void addArgumentToVtab(Parse *pParse){
59014 if( pParse->sArg.z && pParse->pNewTable ){
59015 const char *z = (const char*)pParse->sArg.z;
59016 int n = pParse->sArg.n;
59017 addModuleArgument(pParse->pNewTable, sqliteStrNDup(z, n));
59022 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
59023 ** has been completely parsed.
59025 static void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
59026 Table *pTab; /* The table being constructed */
59027 sqlite3 *db; /* The database connection */
59028 char *zModule; /* The module name of the table: USING modulename */
59029 Module *pMod = 0;
59031 addArgumentToVtab(pParse);
59032 pParse->sArg.z = 0;
59034 /* Lookup the module name. */
59035 pTab = pParse->pNewTable;
59036 if( pTab==0 ) return;
59037 db = pParse->db;
59038 if( pTab->nModuleArg<1 ) return;
59039 zModule = pTab->azModuleArg[0];
59040 pMod = (Module *)sqlite3HashFind(&db->aModule, zModule, strlen(zModule));
59041 pTab->pMod = pMod;
59043 /* If the CREATE VIRTUAL TABLE statement is being entered for the
59044 ** first time (in other words if the virtual table is actually being
59045 ** created now instead of just being read out of sqlite_master) then
59046 ** do additional initialization work and store the statement text
59047 ** in the sqlite_master table.
59049 if( !db->init.busy ){
59050 char *zStmt;
59051 char *zWhere;
59052 int iDb;
59053 Vdbe *v;
59055 /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
59056 if( pEnd ){
59057 pParse->sNameToken.n = pEnd->z - pParse->sNameToken.z + pEnd->n;
59059 zStmt = sqlite3MPrintf("CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
59061 /* A slot for the record has already been allocated in the
59062 ** SQLITE_MASTER table. We just need to update that slot with all
59063 ** the information we've collected.
59065 ** The top of the stack is the rootpage allocated by sqlite3StartTable().
59066 ** This value is always 0 and is ignored, a virtual table does not have a
59067 ** rootpage. The next entry on the stack is the rowid of the record
59068 ** in the sqlite_master table.
59070 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
59071 sqlite3NestedParse(pParse,
59072 "UPDATE %Q.%s "
59073 "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
59074 "WHERE rowid=#1",
59075 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
59076 pTab->zName,
59077 pTab->zName,
59078 zStmt
59080 sqliteFree(zStmt);
59081 v = sqlite3GetVdbe(pParse);
59082 sqlite3ChangeCookie(db, v, iDb);
59084 sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
59085 zWhere = sqlite3MPrintf("name='%q'", pTab->zName);
59086 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 1, zWhere, P3_DYNAMIC);
59087 sqlite3VdbeOp3(v, OP_VCreate, iDb, 0, pTab->zName, strlen(pTab->zName) + 1);
59090 /* If we are rereading the sqlite_master table create the in-memory
59091 ** record of the table. If the module has already been registered,
59092 ** also call the xConnect method here.
59094 else {
59095 Table *pOld;
59096 Schema *pSchema = pTab->pSchema;
59097 const char *zName = pTab->zName;
59098 int nName = strlen(zName) + 1;
59099 pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
59100 if( pOld ){
59101 assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
59102 return;
59104 pSchema->db = pParse->db;
59105 pParse->pNewTable = 0;
59110 ** The parser calls this routine when it sees the first token
59111 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
59113 static void sqlite3VtabArgInit(Parse *pParse){
59114 addArgumentToVtab(pParse);
59115 pParse->sArg.z = 0;
59116 pParse->sArg.n = 0;
59120 ** The parser calls this routine for each token after the first token
59121 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
59123 static void sqlite3VtabArgExtend(Parse *pParse, Token *p){
59124 Token *pArg = &pParse->sArg;
59125 if( pArg->z==0 ){
59126 pArg->z = p->z;
59127 pArg->n = p->n;
59128 }else{
59129 assert(pArg->z < p->z);
59130 pArg->n = (p->z + p->n - pArg->z);
59135 ** Invoke a virtual table constructor (either xCreate or xConnect). The
59136 ** pointer to the function to invoke is passed as the fourth parameter
59137 ** to this procedure.
59139 static int vtabCallConstructor(
59140 sqlite3 *db,
59141 Table *pTab,
59142 Module *pMod,
59143 int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
59144 char **pzErr
59146 int rc;
59147 int rc2;
59148 sqlite3_vtab *pVtab;
59149 const char *const*azArg = (const char *const*)pTab->azModuleArg;
59150 int nArg = pTab->nModuleArg;
59151 char *zErr = 0;
59152 char *zModuleName = sqlite3MPrintf("%s", pTab->zName);
59154 if( !zModuleName ){
59155 return SQLITE_NOMEM;
59158 assert( !db->pVTab );
59159 assert( xConstruct );
59161 db->pVTab = pTab;
59162 rc = sqlite3SafetyOff(db);
59163 assert( rc==SQLITE_OK );
59164 rc = xConstruct(db, pMod->pAux, nArg, azArg, &pTab->pVtab, &zErr);
59165 rc2 = sqlite3SafetyOn(db);
59166 pVtab = pTab->pVtab;
59167 if( rc==SQLITE_OK && pVtab ){
59168 pVtab->pModule = pMod->pModule;
59169 pVtab->nRef = 1;
59172 if( SQLITE_OK!=rc ){
59173 if( zErr==0 ){
59174 *pzErr = sqlite3MPrintf("vtable constructor failed: %s", zModuleName);
59175 }else {
59176 *pzErr = sqlite3MPrintf("%s", zErr);
59177 sqlite3_free(zErr);
59179 }else if( db->pVTab ){
59180 const char *zFormat = "vtable constructor did not declare schema: %s";
59181 *pzErr = sqlite3MPrintf(zFormat, pTab->zName);
59182 rc = SQLITE_ERROR;
59184 if( rc==SQLITE_OK ){
59185 rc = rc2;
59187 db->pVTab = 0;
59188 sqliteFree(zModuleName);
59189 return rc;
59193 ** This function is invoked by the parser to call the xConnect() method
59194 ** of the virtual table pTab. If an error occurs, an error code is returned
59195 ** and an error left in pParse.
59197 ** This call is a no-op if table pTab is not a virtual table.
59199 static int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
59200 Module *pMod;
59201 int rc = SQLITE_OK;
59203 if( !pTab || !pTab->isVirtual || pTab->pVtab ){
59204 return SQLITE_OK;
59207 pMod = pTab->pMod;
59208 if( !pMod ){
59209 const char *zModule = pTab->azModuleArg[0];
59210 sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
59211 rc = SQLITE_ERROR;
59212 } else {
59213 char *zErr = 0;
59214 sqlite3 *db = pParse->db;
59215 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
59216 if( rc!=SQLITE_OK ){
59217 sqlite3ErrorMsg(pParse, "%s", zErr);
59219 sqliteFree(zErr);
59222 return rc;
59226 ** Add the virtual table pVtab to the array sqlite3.aVTrans[].
59228 static int addToVTrans(sqlite3 *db, sqlite3_vtab *pVtab){
59229 const int ARRAY_INCR = 5;
59231 /* Grow the sqlite3.aVTrans array if required */
59232 if( (db->nVTrans%ARRAY_INCR)==0 ){
59233 sqlite3_vtab **aVTrans;
59234 int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
59235 aVTrans = sqliteRealloc((void *)db->aVTrans, nBytes);
59236 if( !aVTrans ){
59237 return SQLITE_NOMEM;
59239 memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
59240 db->aVTrans = aVTrans;
59243 /* Add pVtab to the end of sqlite3.aVTrans */
59244 db->aVTrans[db->nVTrans++] = pVtab;
59245 sqlite3VtabLock(pVtab);
59246 return SQLITE_OK;
59250 ** This function is invoked by the vdbe to call the xCreate method
59251 ** of the virtual table named zTab in database iDb.
59253 ** If an error occurs, *pzErr is set to point an an English language
59254 ** description of the error and an SQLITE_XXX error code is returned.
59255 ** In this case the caller must call sqliteFree() on *pzErr.
59257 static int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
59258 int rc = SQLITE_OK;
59259 Table *pTab;
59260 Module *pMod;
59261 const char *zModule;
59263 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
59264 assert(pTab && pTab->isVirtual && !pTab->pVtab);
59265 pMod = pTab->pMod;
59266 zModule = pTab->azModuleArg[0];
59268 /* If the module has been registered and includes a Create method,
59269 ** invoke it now. If the module has not been registered, return an
59270 ** error. Otherwise, do nothing.
59272 if( !pMod ){
59273 *pzErr = sqlite3MPrintf("no such module: %s", zModule);
59274 rc = SQLITE_ERROR;
59275 }else{
59276 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
59279 if( rc==SQLITE_OK && pTab->pVtab ){
59280 rc = addToVTrans(db, pTab->pVtab);
59283 return rc;
59287 ** This function is used to set the schema of a virtual table. It is only
59288 ** valid to call this function from within the xCreate() or xConnect() of a
59289 ** virtual table module.
59291 int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
59292 Parse sParse;
59294 int rc = SQLITE_OK;
59295 Table *pTab = db->pVTab;
59296 char *zErr = 0;
59298 if( !pTab ){
59299 sqlite3Error(db, SQLITE_MISUSE, 0);
59300 return SQLITE_MISUSE;
59302 assert(pTab->isVirtual && pTab->nCol==0 && pTab->aCol==0);
59304 memset(&sParse, 0, sizeof(Parse));
59305 sParse.declareVtab = 1;
59306 sParse.db = db;
59308 if(
59309 SQLITE_OK == sqlite3RunParser(&sParse, zCreateTable, &zErr) &&
59310 sParse.pNewTable &&
59311 !sParse.pNewTable->pSelect &&
59312 !sParse.pNewTable->isVirtual
59314 pTab->aCol = sParse.pNewTable->aCol;
59315 pTab->nCol = sParse.pNewTable->nCol;
59316 sParse.pNewTable->nCol = 0;
59317 sParse.pNewTable->aCol = 0;
59318 db->pVTab = 0;
59319 } else {
59320 sqlite3Error(db, SQLITE_ERROR, zErr);
59321 sqliteFree(zErr);
59322 rc = SQLITE_ERROR;
59324 sParse.declareVtab = 0;
59326 sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
59327 sqlite3DeleteTable(sParse.pNewTable);
59328 sParse.pNewTable = 0;
59330 assert( (rc&0xff)==rc );
59331 return sqlite3ApiExit(db, rc);
59335 ** This function is invoked by the vdbe to call the xDestroy method
59336 ** of the virtual table named zTab in database iDb. This occurs
59337 ** when a DROP TABLE is mentioned.
59339 ** This call is a no-op if zTab is not a virtual table.
59341 static int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab)
59343 int rc = SQLITE_OK;
59344 Table *pTab;
59346 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
59347 assert(pTab);
59348 if( pTab->pVtab ){
59349 int (*xDestroy)(sqlite3_vtab *pVTab) = pTab->pMod->pModule->xDestroy;
59350 rc = sqlite3SafetyOff(db);
59351 assert( rc==SQLITE_OK );
59352 if( xDestroy ){
59353 rc = xDestroy(pTab->pVtab);
59355 sqlite3SafetyOn(db);
59356 if( rc==SQLITE_OK ){
59357 pTab->pVtab = 0;
59361 return rc;
59365 ** This function invokes either the xRollback or xCommit method
59366 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
59367 ** called is identified by the second argument, "offset", which is
59368 ** the offset of the method to call in the sqlite3_module structure.
59370 ** The array is cleared after invoking the callbacks.
59372 static void callFinaliser(sqlite3 *db, int offset){
59373 int i;
59374 if( db->aVTrans ){
59375 for(i=0; i<db->nVTrans && db->aVTrans[i]; i++){
59376 sqlite3_vtab *pVtab = db->aVTrans[i];
59377 int (*x)(sqlite3_vtab *);
59378 x = *(int (**)(sqlite3_vtab *))((char *)pVtab->pModule + offset);
59379 if( x ) x(pVtab);
59380 sqlite3VtabUnlock(db, pVtab);
59382 sqliteFree(db->aVTrans);
59383 db->nVTrans = 0;
59384 db->aVTrans = 0;
59389 ** If argument rc2 is not SQLITE_OK, then return it and do nothing.
59390 ** Otherwise, invoke the xSync method of all virtual tables in the
59391 ** sqlite3.aVTrans array. Return the error code for the first error
59392 ** that occurs, or SQLITE_OK if all xSync operations are successful.
59394 static int sqlite3VtabSync(sqlite3 *db, int rc2){
59395 int i;
59396 int rc = SQLITE_OK;
59397 int rcsafety;
59398 sqlite3_vtab **aVTrans = db->aVTrans;
59399 if( rc2!=SQLITE_OK ) return rc2;
59401 rc = sqlite3SafetyOff(db);
59402 db->aVTrans = 0;
59403 for(i=0; rc==SQLITE_OK && i<db->nVTrans && aVTrans[i]; i++){
59404 sqlite3_vtab *pVtab = aVTrans[i];
59405 int (*x)(sqlite3_vtab *);
59406 x = pVtab->pModule->xSync;
59407 if( x ){
59408 rc = x(pVtab);
59411 db->aVTrans = aVTrans;
59412 rcsafety = sqlite3SafetyOn(db);
59414 if( rc==SQLITE_OK ){
59415 rc = rcsafety;
59417 return rc;
59421 ** Invoke the xRollback method of all virtual tables in the
59422 ** sqlite3.aVTrans array. Then clear the array itself.
59424 static int sqlite3VtabRollback(sqlite3 *db){
59425 callFinaliser(db, (int)(&((sqlite3_module *)0)->xRollback));
59426 return SQLITE_OK;
59430 ** Invoke the xCommit method of all virtual tables in the
59431 ** sqlite3.aVTrans array. Then clear the array itself.
59433 static int sqlite3VtabCommit(sqlite3 *db){
59434 callFinaliser(db, (int)(&((sqlite3_module *)0)->xCommit));
59435 return SQLITE_OK;
59439 ** If the virtual table pVtab supports the transaction interface
59440 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
59441 ** not currently open, invoke the xBegin method now.
59443 ** If the xBegin call is successful, place the sqlite3_vtab pointer
59444 ** in the sqlite3.aVTrans array.
59446 static int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
59447 int rc = SQLITE_OK;
59448 const sqlite3_module *pModule;
59450 /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
59451 ** than zero, then this function is being called from within a
59452 ** virtual module xSync() callback. It is illegal to write to
59453 ** virtual module tables in this case, so return SQLITE_LOCKED.
59455 if( 0==db->aVTrans && db->nVTrans>0 ){
59456 return SQLITE_LOCKED;
59458 if( !pVtab ){
59459 return SQLITE_OK;
59461 pModule = pVtab->pModule;
59463 if( pModule->xBegin ){
59464 int i;
59467 /* If pVtab is already in the aVTrans array, return early */
59468 for(i=0; (i<db->nVTrans) && 0!=db->aVTrans[i]; i++){
59469 if( db->aVTrans[i]==pVtab ){
59470 return SQLITE_OK;
59474 /* Invoke the xBegin method */
59475 rc = pModule->xBegin(pVtab);
59476 if( rc!=SQLITE_OK ){
59477 return rc;
59480 rc = addToVTrans(db, pVtab);
59482 return rc;
59486 ** The first parameter (pDef) is a function implementation. The
59487 ** second parameter (pExpr) is the first argument to this function.
59488 ** If pExpr is a column in a virtual table, then let the virtual
59489 ** table implementation have an opportunity to overload the function.
59491 ** This routine is used to allow virtual table implementations to
59492 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
59494 ** Return either the pDef argument (indicating no change) or a
59495 ** new FuncDef structure that is marked as ephemeral using the
59496 ** SQLITE_FUNC_EPHEM flag.
59498 static FuncDef *sqlite3VtabOverloadFunction(
59499 FuncDef *pDef, /* Function to possibly overload */
59500 int nArg, /* Number of arguments to the function */
59501 Expr *pExpr /* First argument to the function */
59503 Table *pTab;
59504 sqlite3_vtab *pVtab;
59505 sqlite3_module *pMod;
59506 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
59507 void *pArg;
59508 FuncDef *pNew;
59509 int rc;
59510 char *zLowerName;
59511 unsigned char *z;
59514 /* Check to see the left operand is a column in a virtual table */
59515 if( pExpr==0 ) return pDef;
59516 if( pExpr->op!=TK_COLUMN ) return pDef;
59517 pTab = pExpr->pTab;
59518 if( pTab==0 ) return pDef;
59519 if( !pTab->isVirtual ) return pDef;
59520 pVtab = pTab->pVtab;
59521 assert( pVtab!=0 );
59522 assert( pVtab->pModule!=0 );
59523 pMod = (sqlite3_module *)pVtab->pModule;
59524 if( pMod->xFindFunction==0 ) return pDef;
59526 /* Call the xFuncFunction method on the virtual table implementation
59527 ** to see if the implementation wants to overload this function
59529 zLowerName = sqlite3StrDup(pDef->zName);
59530 for(z=(unsigned char*)zLowerName; *z; z++){
59531 *z = sqlite3UpperToLower[*z];
59533 rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
59534 sqliteFree(zLowerName);
59535 if( rc==0 ){
59536 return pDef;
59539 /* Create a new ephemeral function definition for the overloaded
59540 ** function */
59541 pNew = sqliteMalloc( sizeof(*pNew) + strlen(pDef->zName) );
59542 if( pNew==0 ){
59543 return pDef;
59545 *pNew = *pDef;
59546 memcpy(pNew->zName, pDef->zName, strlen(pDef->zName)+1);
59547 pNew->xFunc = xFunc;
59548 pNew->pUserData = pArg;
59549 pNew->flags |= SQLITE_FUNC_EPHEM;
59550 return pNew;
59553 #endif /* SQLITE_OMIT_VIRTUALTABLE */
59555 /************** End of vtab.c ************************************************/
59556 /************** Begin file where.c *******************************************/
59558 ** 2001 September 15
59560 ** The author disclaims copyright to this source code. In place of
59561 ** a legal notice, here is a blessing:
59563 ** May you do good and not evil.
59564 ** May you find forgiveness for yourself and forgive others.
59565 ** May you share freely, never taking more than you give.
59567 *************************************************************************
59568 ** This module contains C code that generates VDBE code used to process
59569 ** the WHERE clause of SQL statements. This module is reponsible for
59570 ** generating the code that loops through a table looking for applicable
59571 ** rows. Indices are selected and used to speed the search when doing
59572 ** so is applicable. Because this module is responsible for selecting
59573 ** indices, you might also think of this module as the "query optimizer".
59575 ** $Id: where.c,v 1.253 2007/06/11 12:56:15 drh Exp $
59579 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
59581 #define BMS (sizeof(Bitmask)*8)
59584 ** Trace output macros
59586 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
59587 int sqlite3_where_trace = 0;
59588 # define WHERETRACE(X) if(sqlite3_where_trace) sqlite3DebugPrintf X
59589 #else
59590 # define WHERETRACE(X)
59591 #endif
59593 /* Forward reference
59595 typedef struct WhereClause WhereClause;
59596 typedef struct ExprMaskSet ExprMaskSet;
59599 ** The query generator uses an array of instances of this structure to
59600 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
59601 ** clause subexpression is separated from the others by an AND operator.
59603 ** All WhereTerms are collected into a single WhereClause structure.
59604 ** The following identity holds:
59606 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
59608 ** When a term is of the form:
59610 ** X <op> <expr>
59612 ** where X is a column name and <op> is one of certain operators,
59613 ** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
59614 ** cursor number and column number for X. WhereTerm.operator records
59615 ** the <op> using a bitmask encoding defined by WO_xxx below. The
59616 ** use of a bitmask encoding for the operator allows us to search
59617 ** quickly for terms that match any of several different operators.
59619 ** prereqRight and prereqAll record sets of cursor numbers,
59620 ** but they do so indirectly. A single ExprMaskSet structure translates
59621 ** cursor number into bits and the translated bit is stored in the prereq
59622 ** fields. The translation is used in order to maximize the number of
59623 ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
59624 ** spread out over the non-negative integers. For example, the cursor
59625 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The ExprMaskSet
59626 ** translates these sparse cursor numbers into consecutive integers
59627 ** beginning with 0 in order to make the best possible use of the available
59628 ** bits in the Bitmask. So, in the example above, the cursor numbers
59629 ** would be mapped into integers 0 through 7.
59631 typedef struct WhereTerm WhereTerm;
59632 struct WhereTerm {
59633 Expr *pExpr; /* Pointer to the subexpression */
59634 i16 iParent; /* Disable pWC->a[iParent] when this term disabled */
59635 i16 leftCursor; /* Cursor number of X in "X <op> <expr>" */
59636 i16 leftColumn; /* Column number of X in "X <op> <expr>" */
59637 u16 eOperator; /* A WO_xx value describing <op> */
59638 u8 flags; /* Bit flags. See below */
59639 u8 nChild; /* Number of children that must disable us */
59640 WhereClause *pWC; /* The clause this term is part of */
59641 Bitmask prereqRight; /* Bitmask of tables used by pRight */
59642 Bitmask prereqAll; /* Bitmask of tables referenced by p */
59646 ** Allowed values of WhereTerm.flags
59648 #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(pExpr) */
59649 #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
59650 #define TERM_CODED 0x04 /* This term is already coded */
59651 #define TERM_COPIED 0x08 /* Has a child */
59652 #define TERM_OR_OK 0x10 /* Used during OR-clause processing */
59655 ** An instance of the following structure holds all information about a
59656 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
59658 struct WhereClause {
59659 Parse *pParse; /* The parser context */
59660 ExprMaskSet *pMaskSet; /* Mapping of table indices to bitmasks */
59661 int nTerm; /* Number of terms */
59662 int nSlot; /* Number of entries in a[] */
59663 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
59664 WhereTerm aStatic[10]; /* Initial static space for a[] */
59668 ** An instance of the following structure keeps track of a mapping
59669 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
59671 ** The VDBE cursor numbers are small integers contained in
59672 ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
59673 ** clause, the cursor numbers might not begin with 0 and they might
59674 ** contain gaps in the numbering sequence. But we want to make maximum
59675 ** use of the bits in our bitmasks. This structure provides a mapping
59676 ** from the sparse cursor numbers into consecutive integers beginning
59677 ** with 0.
59679 ** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
59680 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
59682 ** For example, if the WHERE clause expression used these VDBE
59683 ** cursors: 4, 5, 8, 29, 57, 73. Then the ExprMaskSet structure
59684 ** would map those cursor numbers into bits 0 through 5.
59686 ** Note that the mapping is not necessarily ordered. In the example
59687 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
59688 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
59689 ** does not really matter. What is important is that sparse cursor
59690 ** numbers all get mapped into bit numbers that begin with 0 and contain
59691 ** no gaps.
59693 struct ExprMaskSet {
59694 int n; /* Number of assigned cursor values */
59695 int ix[sizeof(Bitmask)*8]; /* Cursor assigned to each bit */
59700 ** Bitmasks for the operators that indices are able to exploit. An
59701 ** OR-ed combination of these values can be used when searching for
59702 ** terms in the where clause.
59704 #define WO_IN 1
59705 #define WO_EQ 2
59706 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
59707 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
59708 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
59709 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
59710 #define WO_MATCH 64
59711 #define WO_ISNULL 128
59714 ** Value for flags returned by bestIndex().
59716 ** The least significant byte is reserved as a mask for WO_ values above.
59717 ** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
59718 ** But if the table is the right table of a left join, WhereLevel.flags
59719 ** is set to WO_IN|WO_EQ. The WhereLevel.flags field can then be used as
59720 ** the "op" parameter to findTerm when we are resolving equality constraints.
59721 ** ISNULL constraints will then not be used on the right table of a left
59722 ** join. Tickets #2177 and #2189.
59724 #define WHERE_ROWID_EQ 0x000100 /* rowid=EXPR or rowid IN (...) */
59725 #define WHERE_ROWID_RANGE 0x000200 /* rowid<EXPR and/or rowid>EXPR */
59726 #define WHERE_COLUMN_EQ 0x001000 /* x=EXPR or x IN (...) */
59727 #define WHERE_COLUMN_RANGE 0x002000 /* x<EXPR and/or x>EXPR */
59728 #define WHERE_COLUMN_IN 0x004000 /* x IN (...) */
59729 #define WHERE_TOP_LIMIT 0x010000 /* x<EXPR or x<=EXPR constraint */
59730 #define WHERE_BTM_LIMIT 0x020000 /* x>EXPR or x>=EXPR constraint */
59731 #define WHERE_IDX_ONLY 0x080000 /* Use index only - omit table */
59732 #define WHERE_ORDERBY 0x100000 /* Output will appear in correct order */
59733 #define WHERE_REVERSE 0x200000 /* Scan in reverse order */
59734 #define WHERE_UNIQUE 0x400000 /* Selects no more than one row */
59735 #define WHERE_VIRTUALTABLE 0x800000 /* Use virtual-table processing */
59738 ** Initialize a preallocated WhereClause structure.
59740 static void whereClauseInit(
59741 WhereClause *pWC, /* The WhereClause to be initialized */
59742 Parse *pParse, /* The parsing context */
59743 ExprMaskSet *pMaskSet /* Mapping from table indices to bitmasks */
59745 pWC->pParse = pParse;
59746 pWC->pMaskSet = pMaskSet;
59747 pWC->nTerm = 0;
59748 pWC->nSlot = ArraySize(pWC->aStatic);
59749 pWC->a = pWC->aStatic;
59753 ** Deallocate a WhereClause structure. The WhereClause structure
59754 ** itself is not freed. This routine is the inverse of whereClauseInit().
59756 static void whereClauseClear(WhereClause *pWC){
59757 int i;
59758 WhereTerm *a;
59759 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
59760 if( a->flags & TERM_DYNAMIC ){
59761 sqlite3ExprDelete(a->pExpr);
59764 if( pWC->a!=pWC->aStatic ){
59765 sqliteFree(pWC->a);
59770 ** Add a new entries to the WhereClause structure. Increase the allocated
59771 ** space as necessary.
59773 ** If the flags argument includes TERM_DYNAMIC, then responsibility
59774 ** for freeing the expression p is assumed by the WhereClause object.
59776 ** WARNING: This routine might reallocate the space used to store
59777 ** WhereTerms. All pointers to WhereTerms should be invalided after
59778 ** calling this routine. Such pointers may be reinitialized by referencing
59779 ** the pWC->a[] array.
59781 static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
59782 WhereTerm *pTerm;
59783 int idx;
59784 if( pWC->nTerm>=pWC->nSlot ){
59785 WhereTerm *pOld = pWC->a;
59786 pWC->a = sqliteMalloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
59787 if( pWC->a==0 ){
59788 if( flags & TERM_DYNAMIC ){
59789 sqlite3ExprDelete(p);
59791 return 0;
59793 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
59794 if( pOld!=pWC->aStatic ){
59795 sqliteFree(pOld);
59797 pWC->nSlot *= 2;
59799 pTerm = &pWC->a[idx = pWC->nTerm];
59800 pWC->nTerm++;
59801 pTerm->pExpr = p;
59802 pTerm->flags = flags;
59803 pTerm->pWC = pWC;
59804 pTerm->iParent = -1;
59805 return idx;
59809 ** This routine identifies subexpressions in the WHERE clause where
59810 ** each subexpression is separated by the AND operator or some other
59811 ** operator specified in the op parameter. The WhereClause structure
59812 ** is filled with pointers to subexpressions. For example:
59814 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
59815 ** \________/ \_______________/ \________________/
59816 ** slot[0] slot[1] slot[2]
59818 ** The original WHERE clause in pExpr is unaltered. All this routine
59819 ** does is make slot[] entries point to substructure within pExpr.
59821 ** In the previous sentence and in the diagram, "slot[]" refers to
59822 ** the WhereClause.a[] array. This array grows as needed to contain
59823 ** all terms of the WHERE clause.
59825 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
59826 if( pExpr==0 ) return;
59827 if( pExpr->op!=op ){
59828 whereClauseInsert(pWC, pExpr, 0);
59829 }else{
59830 whereSplit(pWC, pExpr->pLeft, op);
59831 whereSplit(pWC, pExpr->pRight, op);
59836 ** Initialize an expression mask set
59838 #define initMaskSet(P) memset(P, 0, sizeof(*P))
59841 ** Return the bitmask for the given cursor number. Return 0 if
59842 ** iCursor is not in the set.
59844 static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
59845 int i;
59846 for(i=0; i<pMaskSet->n; i++){
59847 if( pMaskSet->ix[i]==iCursor ){
59848 return ((Bitmask)1)<<i;
59851 return 0;
59855 ** Create a new mask for cursor iCursor.
59857 ** There is one cursor per table in the FROM clause. The number of
59858 ** tables in the FROM clause is limited by a test early in the
59859 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
59860 ** array will never overflow.
59862 static void createMask(ExprMaskSet *pMaskSet, int iCursor){
59863 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
59864 pMaskSet->ix[pMaskSet->n++] = iCursor;
59868 ** This routine walks (recursively) an expression tree and generates
59869 ** a bitmask indicating which tables are used in that expression
59870 ** tree.
59872 ** In order for this routine to work, the calling function must have
59873 ** previously invoked sqlite3ExprResolveNames() on the expression. See
59874 ** the header comment on that routine for additional information.
59875 ** The sqlite3ExprResolveNames() routines looks for column names and
59876 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
59877 ** the VDBE cursor number of the table. This routine just has to
59878 ** translate the cursor numbers into bitmask values and OR all
59879 ** the bitmasks together.
59881 static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
59882 static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
59883 static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
59884 Bitmask mask = 0;
59885 if( p==0 ) return 0;
59886 if( p->op==TK_COLUMN ){
59887 mask = getMask(pMaskSet, p->iTable);
59888 return mask;
59890 mask = exprTableUsage(pMaskSet, p->pRight);
59891 mask |= exprTableUsage(pMaskSet, p->pLeft);
59892 mask |= exprListTableUsage(pMaskSet, p->pList);
59893 mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
59894 return mask;
59896 static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
59897 int i;
59898 Bitmask mask = 0;
59899 if( pList ){
59900 for(i=0; i<pList->nExpr; i++){
59901 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
59904 return mask;
59906 static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
59907 Bitmask mask;
59908 if( pS==0 ){
59909 mask = 0;
59910 }else{
59911 mask = exprListTableUsage(pMaskSet, pS->pEList);
59912 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
59913 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
59914 mask |= exprTableUsage(pMaskSet, pS->pWhere);
59915 mask |= exprTableUsage(pMaskSet, pS->pHaving);
59917 return mask;
59921 ** Return TRUE if the given operator is one of the operators that is
59922 ** allowed for an indexable WHERE clause term. The allowed operators are
59923 ** "=", "<", ">", "<=", ">=", and "IN".
59925 static int allowedOp(int op){
59926 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
59927 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
59928 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
59929 assert( TK_GE==TK_EQ+4 );
59930 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
59934 ** Swap two objects of type T.
59936 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
59939 ** Commute a comparision operator. Expressions of the form "X op Y"
59940 ** are converted into "Y op X".
59942 static void exprCommute(Expr *pExpr){
59943 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
59944 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
59945 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
59946 if( pExpr->op>=TK_GT ){
59947 assert( TK_LT==TK_GT+2 );
59948 assert( TK_GE==TK_LE+2 );
59949 assert( TK_GT>TK_EQ );
59950 assert( TK_GT<TK_LE );
59951 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
59952 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
59957 ** Translate from TK_xx operator to WO_xx bitmask.
59959 static int operatorMask(int op){
59960 int c;
59961 assert( allowedOp(op) );
59962 if( op==TK_IN ){
59963 c = WO_IN;
59964 }else if( op==TK_ISNULL ){
59965 c = WO_ISNULL;
59966 }else{
59967 c = WO_EQ<<(op-TK_EQ);
59969 assert( op!=TK_ISNULL || c==WO_ISNULL );
59970 assert( op!=TK_IN || c==WO_IN );
59971 assert( op!=TK_EQ || c==WO_EQ );
59972 assert( op!=TK_LT || c==WO_LT );
59973 assert( op!=TK_LE || c==WO_LE );
59974 assert( op!=TK_GT || c==WO_GT );
59975 assert( op!=TK_GE || c==WO_GE );
59976 return c;
59980 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
59981 ** where X is a reference to the iColumn of table iCur and <op> is one of
59982 ** the WO_xx operator codes specified by the op parameter.
59983 ** Return a pointer to the term. Return 0 if not found.
59985 static WhereTerm *findTerm(
59986 WhereClause *pWC, /* The WHERE clause to be searched */
59987 int iCur, /* Cursor number of LHS */
59988 int iColumn, /* Column number of LHS */
59989 Bitmask notReady, /* RHS must not overlap with this mask */
59990 u16 op, /* Mask of WO_xx values describing operator */
59991 Index *pIdx /* Must be compatible with this index, if not NULL */
59993 WhereTerm *pTerm;
59994 int k;
59995 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
59996 if( pTerm->leftCursor==iCur
59997 && (pTerm->prereqRight & notReady)==0
59998 && pTerm->leftColumn==iColumn
59999 && (pTerm->eOperator & op)!=0
60001 if( iCur>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
60002 Expr *pX = pTerm->pExpr;
60003 CollSeq *pColl;
60004 char idxaff;
60005 int j;
60006 Parse *pParse = pWC->pParse;
60008 idxaff = pIdx->pTable->aCol[iColumn].affinity;
60009 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
60011 /* Figure out the collation sequence required from an index for
60012 ** it to be useful for optimising expression pX. Store this
60013 ** value in variable pColl.
60015 assert(pX->pLeft);
60016 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
60017 if( !pColl ){
60018 pColl = pParse->db->pDfltColl;
60021 for(j=0; j<pIdx->nColumn && pIdx->aiColumn[j]!=iColumn; j++){}
60022 assert( j<pIdx->nColumn );
60023 if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
60025 return pTerm;
60028 return 0;
60031 /* Forward reference */
60032 static void exprAnalyze(SrcList*, WhereClause*, int);
60035 ** Call exprAnalyze on all terms in a WHERE clause.
60039 static void exprAnalyzeAll(
60040 SrcList *pTabList, /* the FROM clause */
60041 WhereClause *pWC /* the WHERE clause to be analyzed */
60043 int i;
60044 for(i=pWC->nTerm-1; i>=0; i--){
60045 exprAnalyze(pTabList, pWC, i);
60049 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
60051 ** Check to see if the given expression is a LIKE or GLOB operator that
60052 ** can be optimized using inequality constraints. Return TRUE if it is
60053 ** so and false if not.
60055 ** In order for the operator to be optimizible, the RHS must be a string
60056 ** literal that does not begin with a wildcard.
60058 static int isLikeOrGlob(
60059 sqlite3 *db, /* The database */
60060 Expr *pExpr, /* Test this expression */
60061 int *pnPattern, /* Number of non-wildcard prefix characters */
60062 int *pisComplete /* True if the only wildcard is % in the last character */
60064 const char *z;
60065 Expr *pRight, *pLeft;
60066 ExprList *pList;
60067 int c, cnt;
60068 int noCase;
60069 char wc[3];
60070 CollSeq *pColl;
60072 if( !sqlite3IsLikeFunction(db, pExpr, &noCase, wc) ){
60073 return 0;
60075 pList = pExpr->pList;
60076 pRight = pList->a[0].pExpr;
60077 if( pRight->op!=TK_STRING ){
60078 return 0;
60080 pLeft = pList->a[1].pExpr;
60081 if( pLeft->op!=TK_COLUMN ){
60082 return 0;
60084 pColl = pLeft->pColl;
60085 if( pColl==0 ){
60086 /* TODO: Coverage testing doesn't get this case. Is it actually possible
60087 ** for an expression of type TK_COLUMN to not have an assigned collation
60088 ** sequence at this point?
60090 pColl = db->pDfltColl;
60092 if( (pColl->type!=SQLITE_COLL_BINARY || noCase) &&
60093 (pColl->type!=SQLITE_COLL_NOCASE || !noCase) ){
60094 return 0;
60096 sqlite3DequoteExpr(pRight);
60097 z = (char *)pRight->token.z;
60098 for(cnt=0; (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2]; cnt++){}
60099 if( cnt==0 || 255==(u8)z[cnt] ){
60100 return 0;
60102 *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
60103 *pnPattern = cnt;
60104 return 1;
60106 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
60109 #ifndef SQLITE_OMIT_VIRTUALTABLE
60111 ** Check to see if the given expression is of the form
60113 ** column MATCH expr
60115 ** If it is then return TRUE. If not, return FALSE.
60117 static int isMatchOfColumn(
60118 Expr *pExpr /* Test this expression */
60120 ExprList *pList;
60122 if( pExpr->op!=TK_FUNCTION ){
60123 return 0;
60125 if( pExpr->token.n!=5 ||
60126 sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
60127 return 0;
60129 pList = pExpr->pList;
60130 if( pList->nExpr!=2 ){
60131 return 0;
60133 if( pList->a[1].pExpr->op != TK_COLUMN ){
60134 return 0;
60136 return 1;
60138 #endif /* SQLITE_OMIT_VIRTUALTABLE */
60141 ** If the pBase expression originated in the ON or USING clause of
60142 ** a join, then transfer the appropriate markings over to derived.
60144 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
60145 pDerived->flags |= pBase->flags & EP_FromJoin;
60146 pDerived->iRightJoinTable = pBase->iRightJoinTable;
60149 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
60151 ** Return TRUE if the given term of an OR clause can be converted
60152 ** into an IN clause. The iCursor and iColumn define the left-hand
60153 ** side of the IN clause.
60155 ** The context is that we have multiple OR-connected equality terms
60156 ** like this:
60158 ** a=<expr1> OR a=<expr2> OR b=<expr3> OR ...
60160 ** The pOrTerm input to this routine corresponds to a single term of
60161 ** this OR clause. In order for the term to be a condidate for
60162 ** conversion to an IN operator, the following must be true:
60164 ** * The left-hand side of the term must be the column which
60165 ** is identified by iCursor and iColumn.
60167 ** * If the right-hand side is also a column, then the affinities
60168 ** of both right and left sides must be such that no type
60169 ** conversions are required on the right. (Ticket #2249)
60171 ** If both of these conditions are true, then return true. Otherwise
60172 ** return false.
60174 static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){
60175 int affLeft, affRight;
60176 assert( pOrTerm->eOperator==WO_EQ );
60177 if( pOrTerm->leftCursor!=iCursor ){
60178 return 0;
60180 if( pOrTerm->leftColumn!=iColumn ){
60181 return 0;
60183 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
60184 if( affRight==0 ){
60185 return 1;
60187 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
60188 if( affRight!=affLeft ){
60189 return 0;
60191 return 1;
60195 ** Return true if the given term of an OR clause can be ignored during
60196 ** a check to make sure all OR terms are candidates for optimization.
60197 ** In other words, return true if a call to the orTermIsOptCandidate()
60198 ** above returned false but it is not necessary to disqualify the
60199 ** optimization.
60201 ** Suppose the original OR phrase was this:
60203 ** a=4 OR a=11 OR a=b
60205 ** During analysis, the third term gets flipped around and duplicate
60206 ** so that we are left with this:
60208 ** a=4 OR a=11 OR a=b OR b=a
60210 ** Since the last two terms are duplicates, only one of them
60211 ** has to qualify in order for the whole phrase to qualify. When
60212 ** this routine is called, we know that pOrTerm did not qualify.
60213 ** This routine merely checks to see if pOrTerm has a duplicate that
60214 ** might qualify. If there is a duplicate that has not yet been
60215 ** disqualified, then return true. If there are no duplicates, or
60216 ** the duplicate has also been disqualifed, return false.
60218 static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){
60219 if( pOrTerm->flags & TERM_COPIED ){
60220 /* This is the original term. The duplicate is to the left had
60221 ** has not yet been analyzed and thus has not yet been disqualified. */
60222 return 1;
60224 if( (pOrTerm->flags & TERM_VIRTUAL)!=0
60225 && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){
60226 /* This is a duplicate term. The original qualified so this one
60227 ** does not have to. */
60228 return 1;
60230 /* This is either a singleton term or else it is a duplicate for
60231 ** which the original did not qualify. Either way we are done for. */
60232 return 0;
60234 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
60237 ** The input to this routine is an WhereTerm structure with only the
60238 ** "pExpr" field filled in. The job of this routine is to analyze the
60239 ** subexpression and populate all the other fields of the WhereTerm
60240 ** structure.
60242 ** If the expression is of the form "<expr> <op> X" it gets commuted
60243 ** to the standard form of "X <op> <expr>". If the expression is of
60244 ** the form "X <op> Y" where both X and Y are columns, then the original
60245 ** expression is unchanged and a new virtual expression of the form
60246 ** "Y <op> X" is added to the WHERE clause and analyzed separately.
60248 static void exprAnalyze(
60249 SrcList *pSrc, /* the FROM clause */
60250 WhereClause *pWC, /* the WHERE clause */
60251 int idxTerm /* Index of the term to be analyzed */
60253 WhereTerm *pTerm = &pWC->a[idxTerm];
60254 ExprMaskSet *pMaskSet = pWC->pMaskSet;
60255 Expr *pExpr = pTerm->pExpr;
60256 Bitmask prereqLeft;
60257 Bitmask prereqAll;
60258 int nPattern;
60259 int isComplete;
60260 int op;
60262 if( sqlite3MallocFailed() ) return;
60263 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
60264 op = pExpr->op;
60265 if( op==TK_IN ){
60266 assert( pExpr->pRight==0 );
60267 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
60268 | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
60269 }else if( op==TK_ISNULL ){
60270 pTerm->prereqRight = 0;
60271 }else{
60272 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
60274 prereqAll = exprTableUsage(pMaskSet, pExpr);
60275 if( ExprHasProperty(pExpr, EP_FromJoin) ){
60276 prereqAll |= getMask(pMaskSet, pExpr->iRightJoinTable);
60278 pTerm->prereqAll = prereqAll;
60279 pTerm->leftCursor = -1;
60280 pTerm->iParent = -1;
60281 pTerm->eOperator = 0;
60282 if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
60283 Expr *pLeft = pExpr->pLeft;
60284 Expr *pRight = pExpr->pRight;
60285 if( pLeft->op==TK_COLUMN ){
60286 pTerm->leftCursor = pLeft->iTable;
60287 pTerm->leftColumn = pLeft->iColumn;
60288 pTerm->eOperator = operatorMask(op);
60290 if( pRight && pRight->op==TK_COLUMN ){
60291 WhereTerm *pNew;
60292 Expr *pDup;
60293 if( pTerm->leftCursor>=0 ){
60294 int idxNew;
60295 pDup = sqlite3ExprDup(pExpr);
60296 if( sqlite3MallocFailed() ){
60297 sqlite3ExprDelete(pDup);
60298 return;
60300 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
60301 if( idxNew==0 ) return;
60302 pNew = &pWC->a[idxNew];
60303 pNew->iParent = idxTerm;
60304 pTerm = &pWC->a[idxTerm];
60305 pTerm->nChild = 1;
60306 pTerm->flags |= TERM_COPIED;
60307 }else{
60308 pDup = pExpr;
60309 pNew = pTerm;
60311 exprCommute(pDup);
60312 pLeft = pDup->pLeft;
60313 pNew->leftCursor = pLeft->iTable;
60314 pNew->leftColumn = pLeft->iColumn;
60315 pNew->prereqRight = prereqLeft;
60316 pNew->prereqAll = prereqAll;
60317 pNew->eOperator = operatorMask(pDup->op);
60321 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
60322 /* If a term is the BETWEEN operator, create two new virtual terms
60323 ** that define the range that the BETWEEN implements.
60325 else if( pExpr->op==TK_BETWEEN ){
60326 ExprList *pList = pExpr->pList;
60327 int i;
60328 static const u8 ops[] = {TK_GE, TK_LE};
60329 assert( pList!=0 );
60330 assert( pList->nExpr==2 );
60331 for(i=0; i<2; i++){
60332 Expr *pNewExpr;
60333 int idxNew;
60334 pNewExpr = sqlite3Expr(ops[i], sqlite3ExprDup(pExpr->pLeft),
60335 sqlite3ExprDup(pList->a[i].pExpr), 0);
60336 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
60337 exprAnalyze(pSrc, pWC, idxNew);
60338 pTerm = &pWC->a[idxTerm];
60339 pWC->a[idxNew].iParent = idxTerm;
60341 pTerm->nChild = 2;
60343 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
60345 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
60346 /* Attempt to convert OR-connected terms into an IN operator so that
60347 ** they can make use of indices. Example:
60349 ** x = expr1 OR expr2 = x OR x = expr3
60351 ** is converted into
60353 ** x IN (expr1,expr2,expr3)
60355 ** This optimization must be omitted if OMIT_SUBQUERY is defined because
60356 ** the compiler for the the IN operator is part of sub-queries.
60358 else if( pExpr->op==TK_OR ){
60359 int ok;
60360 int i, j;
60361 int iColumn, iCursor;
60362 WhereClause sOr;
60363 WhereTerm *pOrTerm;
60365 assert( (pTerm->flags & TERM_DYNAMIC)==0 );
60366 whereClauseInit(&sOr, pWC->pParse, pMaskSet);
60367 whereSplit(&sOr, pExpr, TK_OR);
60368 exprAnalyzeAll(pSrc, &sOr);
60369 assert( sOr.nTerm>=2 );
60370 j = 0;
60372 assert( j<sOr.nTerm );
60373 iColumn = sOr.a[j].leftColumn;
60374 iCursor = sOr.a[j].leftCursor;
60375 ok = iCursor>=0;
60376 for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
60377 if( pOrTerm->eOperator!=WO_EQ ){
60378 goto or_not_possible;
60380 if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){
60381 pOrTerm->flags |= TERM_OR_OK;
60382 }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){
60383 pOrTerm->flags &= ~TERM_OR_OK;
60384 }else{
60385 ok = 0;
60388 }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 );
60389 if( ok ){
60390 ExprList *pList = 0;
60391 Expr *pNew, *pDup;
60392 Expr *pLeft = 0;
60393 for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
60394 if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
60395 pDup = sqlite3ExprDup(pOrTerm->pExpr->pRight);
60396 pList = sqlite3ExprListAppend(pList, pDup, 0);
60397 pLeft = pOrTerm->pExpr->pLeft;
60399 assert( pLeft!=0 );
60400 pDup = sqlite3ExprDup(pLeft);
60401 pNew = sqlite3Expr(TK_IN, pDup, 0, 0);
60402 if( pNew ){
60403 int idxNew;
60404 transferJoinMarkings(pNew, pExpr);
60405 pNew->pList = pList;
60406 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
60407 exprAnalyze(pSrc, pWC, idxNew);
60408 pTerm = &pWC->a[idxTerm];
60409 pWC->a[idxNew].iParent = idxTerm;
60410 pTerm->nChild = 1;
60411 }else{
60412 sqlite3ExprListDelete(pList);
60415 or_not_possible:
60416 whereClauseClear(&sOr);
60418 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
60420 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
60421 /* Add constraints to reduce the search space on a LIKE or GLOB
60422 ** operator.
60424 if( isLikeOrGlob(pWC->pParse->db, pExpr, &nPattern, &isComplete) ){
60425 Expr *pLeft, *pRight;
60426 Expr *pStr1, *pStr2;
60427 Expr *pNewExpr1, *pNewExpr2;
60428 int idxNew1, idxNew2;
60430 pLeft = pExpr->pList->a[1].pExpr;
60431 pRight = pExpr->pList->a[0].pExpr;
60432 pStr1 = sqlite3Expr(TK_STRING, 0, 0, 0);
60433 if( pStr1 ){
60434 sqlite3TokenCopy(&pStr1->token, &pRight->token);
60435 pStr1->token.n = nPattern;
60436 pStr1->flags = EP_Dequoted;
60438 pStr2 = sqlite3ExprDup(pStr1);
60439 if( pStr2 ){
60440 assert( pStr2->token.dyn );
60441 ++*(u8*)&pStr2->token.z[nPattern-1];
60443 pNewExpr1 = sqlite3Expr(TK_GE, sqlite3ExprDup(pLeft), pStr1, 0);
60444 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
60445 exprAnalyze(pSrc, pWC, idxNew1);
60446 pNewExpr2 = sqlite3Expr(TK_LT, sqlite3ExprDup(pLeft), pStr2, 0);
60447 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
60448 exprAnalyze(pSrc, pWC, idxNew2);
60449 pTerm = &pWC->a[idxTerm];
60450 if( isComplete ){
60451 pWC->a[idxNew1].iParent = idxTerm;
60452 pWC->a[idxNew2].iParent = idxTerm;
60453 pTerm->nChild = 2;
60456 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
60458 #ifndef SQLITE_OMIT_VIRTUALTABLE
60459 /* Add a WO_MATCH auxiliary term to the constraint set if the
60460 ** current expression is of the form: column MATCH expr.
60461 ** This information is used by the xBestIndex methods of
60462 ** virtual tables. The native query optimizer does not attempt
60463 ** to do anything with MATCH functions.
60465 if( isMatchOfColumn(pExpr) ){
60466 int idxNew;
60467 Expr *pRight, *pLeft;
60468 WhereTerm *pNewTerm;
60469 Bitmask prereqColumn, prereqExpr;
60471 pRight = pExpr->pList->a[0].pExpr;
60472 pLeft = pExpr->pList->a[1].pExpr;
60473 prereqExpr = exprTableUsage(pMaskSet, pRight);
60474 prereqColumn = exprTableUsage(pMaskSet, pLeft);
60475 if( (prereqExpr & prereqColumn)==0 ){
60476 Expr *pNewExpr;
60477 pNewExpr = sqlite3Expr(TK_MATCH, 0, sqlite3ExprDup(pRight), 0);
60478 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
60479 pNewTerm = &pWC->a[idxNew];
60480 pNewTerm->prereqRight = prereqExpr;
60481 pNewTerm->leftCursor = pLeft->iTable;
60482 pNewTerm->leftColumn = pLeft->iColumn;
60483 pNewTerm->eOperator = WO_MATCH;
60484 pNewTerm->iParent = idxTerm;
60485 pTerm = &pWC->a[idxTerm];
60486 pTerm->nChild = 1;
60487 pTerm->flags |= TERM_COPIED;
60488 pNewTerm->prereqAll = pTerm->prereqAll;
60491 #endif /* SQLITE_OMIT_VIRTUALTABLE */
60495 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
60496 ** a reference to any table other than the iBase table.
60498 static int referencesOtherTables(
60499 ExprList *pList, /* Search expressions in ths list */
60500 ExprMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
60501 int iFirst, /* Be searching with the iFirst-th expression */
60502 int iBase /* Ignore references to this table */
60504 Bitmask allowed = ~getMask(pMaskSet, iBase);
60505 while( iFirst<pList->nExpr ){
60506 if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
60507 return 1;
60510 return 0;
60515 ** This routine decides if pIdx can be used to satisfy the ORDER BY
60516 ** clause. If it can, it returns 1. If pIdx cannot satisfy the
60517 ** ORDER BY clause, this routine returns 0.
60519 ** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
60520 ** left-most table in the FROM clause of that same SELECT statement and
60521 ** the table has a cursor number of "base". pIdx is an index on pTab.
60523 ** nEqCol is the number of columns of pIdx that are used as equality
60524 ** constraints. Any of these columns may be missing from the ORDER BY
60525 ** clause and the match can still be a success.
60527 ** All terms of the ORDER BY that match against the index must be either
60528 ** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
60529 ** index do not need to satisfy this constraint.) The *pbRev value is
60530 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
60531 ** the ORDER BY clause is all ASC.
60533 static int isSortingIndex(
60534 Parse *pParse, /* Parsing context */
60535 ExprMaskSet *pMaskSet, /* Mapping from table indices to bitmaps */
60536 Index *pIdx, /* The index we are testing */
60537 int base, /* Cursor number for the table to be sorted */
60538 ExprList *pOrderBy, /* The ORDER BY clause */
60539 int nEqCol, /* Number of index columns with == constraints */
60540 int *pbRev /* Set to 1 if ORDER BY is DESC */
60542 int i, j; /* Loop counters */
60543 int sortOrder = 0; /* XOR of index and ORDER BY sort direction */
60544 int nTerm; /* Number of ORDER BY terms */
60545 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
60546 sqlite3 *db = pParse->db;
60548 assert( pOrderBy!=0 );
60549 nTerm = pOrderBy->nExpr;
60550 assert( nTerm>0 );
60552 /* Match terms of the ORDER BY clause against columns of
60553 ** the index.
60555 ** Note that indices have pIdx->nColumn regular columns plus
60556 ** one additional column containing the rowid. The rowid column
60557 ** of the index is also allowed to match against the ORDER BY
60558 ** clause.
60560 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
60561 Expr *pExpr; /* The expression of the ORDER BY pTerm */
60562 CollSeq *pColl; /* The collating sequence of pExpr */
60563 int termSortOrder; /* Sort order for this term */
60564 int iColumn; /* The i-th column of the index. -1 for rowid */
60565 int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
60566 const char *zColl; /* Name of the collating sequence for i-th index term */
60568 pExpr = pTerm->pExpr;
60569 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
60570 /* Can not use an index sort on anything that is not a column in the
60571 ** left-most table of the FROM clause */
60572 break;
60574 pColl = sqlite3ExprCollSeq(pParse, pExpr);
60575 if( !pColl ){
60576 pColl = db->pDfltColl;
60578 if( i<pIdx->nColumn ){
60579 iColumn = pIdx->aiColumn[i];
60580 if( iColumn==pIdx->pTable->iPKey ){
60581 iColumn = -1;
60583 iSortOrder = pIdx->aSortOrder[i];
60584 zColl = pIdx->azColl[i];
60585 }else{
60586 iColumn = -1;
60587 iSortOrder = 0;
60588 zColl = pColl->zName;
60590 if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
60591 /* Term j of the ORDER BY clause does not match column i of the index */
60592 if( i<nEqCol ){
60593 /* If an index column that is constrained by == fails to match an
60594 ** ORDER BY term, that is OK. Just ignore that column of the index
60596 continue;
60597 }else{
60598 /* If an index column fails to match and is not constrained by ==
60599 ** then the index cannot satisfy the ORDER BY constraint.
60601 return 0;
60604 assert( pIdx->aSortOrder!=0 );
60605 assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
60606 assert( iSortOrder==0 || iSortOrder==1 );
60607 termSortOrder = iSortOrder ^ pTerm->sortOrder;
60608 if( i>nEqCol ){
60609 if( termSortOrder!=sortOrder ){
60610 /* Indices can only be used if all ORDER BY terms past the
60611 ** equality constraints are all either DESC or ASC. */
60612 return 0;
60614 }else{
60615 sortOrder = termSortOrder;
60617 j++;
60618 pTerm++;
60619 if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
60620 /* If the indexed column is the primary key and everything matches
60621 ** so far and none of the ORDER BY terms to the right reference other
60622 ** tables in the join, then we are assured that the index can be used
60623 ** to sort because the primary key is unique and so none of the other
60624 ** columns will make any difference
60626 j = nTerm;
60630 *pbRev = sortOrder!=0;
60631 if( j>=nTerm ){
60632 /* All terms of the ORDER BY clause are covered by this index so
60633 ** this index can be used for sorting. */
60634 return 1;
60636 if( pIdx->onError!=OE_None && i==pIdx->nColumn
60637 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
60638 /* All terms of this index match some prefix of the ORDER BY clause
60639 ** and the index is UNIQUE and no terms on the tail of the ORDER BY
60640 ** clause reference other tables in a join. If this is all true then
60641 ** the order by clause is superfluous. */
60642 return 1;
60644 return 0;
60648 ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
60649 ** by sorting in order of ROWID. Return true if so and set *pbRev to be
60650 ** true for reverse ROWID and false for forward ROWID order.
60652 static int sortableByRowid(
60653 int base, /* Cursor number for table to be sorted */
60654 ExprList *pOrderBy, /* The ORDER BY clause */
60655 ExprMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
60656 int *pbRev /* Set to 1 if ORDER BY is DESC */
60658 Expr *p;
60660 assert( pOrderBy!=0 );
60661 assert( pOrderBy->nExpr>0 );
60662 p = pOrderBy->a[0].pExpr;
60663 if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
60664 && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
60665 *pbRev = pOrderBy->a[0].sortOrder;
60666 return 1;
60668 return 0;
60672 ** Prepare a crude estimate of the logarithm of the input value.
60673 ** The results need not be exact. This is only used for estimating
60674 ** the total cost of performing operatings with O(logN) or O(NlogN)
60675 ** complexity. Because N is just a guess, it is no great tragedy if
60676 ** logN is a little off.
60678 static double estLog(double N){
60679 double logN = 1;
60680 double x = 10;
60681 while( N>x ){
60682 logN += 1;
60683 x *= 10;
60685 return logN;
60689 ** Two routines for printing the content of an sqlite3_index_info
60690 ** structure. Used for testing and debugging only. If neither
60691 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
60692 ** are no-ops.
60694 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
60695 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
60696 int i;
60697 if( !sqlite3_where_trace ) return;
60698 for(i=0; i<p->nConstraint; i++){
60699 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
60701 p->aConstraint[i].iColumn,
60702 p->aConstraint[i].iTermOffset,
60703 p->aConstraint[i].op,
60704 p->aConstraint[i].usable);
60706 for(i=0; i<p->nOrderBy; i++){
60707 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
60709 p->aOrderBy[i].iColumn,
60710 p->aOrderBy[i].desc);
60713 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
60714 int i;
60715 if( !sqlite3_where_trace ) return;
60716 for(i=0; i<p->nConstraint; i++){
60717 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
60719 p->aConstraintUsage[i].argvIndex,
60720 p->aConstraintUsage[i].omit);
60722 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
60723 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
60724 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
60725 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
60727 #else
60728 #define TRACE_IDX_INPUTS(A)
60729 #define TRACE_IDX_OUTPUTS(A)
60730 #endif
60732 #ifndef SQLITE_OMIT_VIRTUALTABLE
60734 ** Compute the best index for a virtual table.
60736 ** The best index is computed by the xBestIndex method of the virtual
60737 ** table module. This routine is really just a wrapper that sets up
60738 ** the sqlite3_index_info structure that is used to communicate with
60739 ** xBestIndex.
60741 ** In a join, this routine might be called multiple times for the
60742 ** same virtual table. The sqlite3_index_info structure is created
60743 ** and initialized on the first invocation and reused on all subsequent
60744 ** invocations. The sqlite3_index_info structure is also used when
60745 ** code is generated to access the virtual table. The whereInfoDelete()
60746 ** routine takes care of freeing the sqlite3_index_info structure after
60747 ** everybody has finished with it.
60749 static double bestVirtualIndex(
60750 Parse *pParse, /* The parsing context */
60751 WhereClause *pWC, /* The WHERE clause */
60752 struct SrcList_item *pSrc, /* The FROM clause term to search */
60753 Bitmask notReady, /* Mask of cursors that are not available */
60754 ExprList *pOrderBy, /* The order by clause */
60755 int orderByUsable, /* True if we can potential sort */
60756 sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
60758 Table *pTab = pSrc->pTab;
60759 sqlite3_index_info *pIdxInfo;
60760 struct sqlite3_index_constraint *pIdxCons;
60761 struct sqlite3_index_orderby *pIdxOrderBy;
60762 struct sqlite3_index_constraint_usage *pUsage;
60763 WhereTerm *pTerm;
60764 int i, j;
60765 int nOrderBy;
60766 int rc;
60768 /* If the sqlite3_index_info structure has not been previously
60769 ** allocated and initialized for this virtual table, then allocate
60770 ** and initialize it now
60772 pIdxInfo = *ppIdxInfo;
60773 if( pIdxInfo==0 ){
60774 WhereTerm *pTerm;
60775 int nTerm;
60776 WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
60778 /* Count the number of possible WHERE clause constraints referring
60779 ** to this virtual table */
60780 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
60781 if( pTerm->leftCursor != pSrc->iCursor ) continue;
60782 if( pTerm->eOperator==WO_IN ) continue;
60783 nTerm++;
60786 /* If the ORDER BY clause contains only columns in the current
60787 ** virtual table then allocate space for the aOrderBy part of
60788 ** the sqlite3_index_info structure.
60790 nOrderBy = 0;
60791 if( pOrderBy ){
60792 for(i=0; i<pOrderBy->nExpr; i++){
60793 Expr *pExpr = pOrderBy->a[i].pExpr;
60794 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
60796 if( i==pOrderBy->nExpr ){
60797 nOrderBy = pOrderBy->nExpr;
60801 /* Allocate the sqlite3_index_info structure
60803 pIdxInfo = sqliteMalloc( sizeof(*pIdxInfo)
60804 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
60805 + sizeof(*pIdxOrderBy)*nOrderBy );
60806 if( pIdxInfo==0 ){
60807 sqlite3ErrorMsg(pParse, "out of memory");
60808 return 0.0;
60810 *ppIdxInfo = pIdxInfo;
60812 /* Initialize the structure. The sqlite3_index_info structure contains
60813 ** many fields that are declared "const" to prevent xBestIndex from
60814 ** changing them. We have to do some funky casting in order to
60815 ** initialize those fields.
60817 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
60818 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
60819 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
60820 *(int*)&pIdxInfo->nConstraint = nTerm;
60821 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
60822 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
60823 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
60824 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
60825 pUsage;
60827 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
60828 if( pTerm->leftCursor != pSrc->iCursor ) continue;
60829 if( pTerm->eOperator==WO_IN ) continue;
60830 pIdxCons[j].iColumn = pTerm->leftColumn;
60831 pIdxCons[j].iTermOffset = i;
60832 pIdxCons[j].op = pTerm->eOperator;
60833 /* The direct assignment in the previous line is possible only because
60834 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
60835 ** following asserts verify this fact. */
60836 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
60837 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
60838 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
60839 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
60840 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
60841 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
60842 assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
60843 j++;
60845 for(i=0; i<nOrderBy; i++){
60846 Expr *pExpr = pOrderBy->a[i].pExpr;
60847 pIdxOrderBy[i].iColumn = pExpr->iColumn;
60848 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
60852 /* At this point, the sqlite3_index_info structure that pIdxInfo points
60853 ** to will have been initialized, either during the current invocation or
60854 ** during some prior invocation. Now we just have to customize the
60855 ** details of pIdxInfo for the current invocation and pass it to
60856 ** xBestIndex.
60859 /* The module name must be defined. Also, by this point there must
60860 ** be a pointer to an sqlite3_vtab structure. Otherwise
60861 ** sqlite3ViewGetColumnNames() would have picked up the error.
60863 assert( pTab->azModuleArg && pTab->azModuleArg[0] );
60864 assert( pTab->pVtab );
60865 #if 0
60866 if( pTab->pVtab==0 ){
60867 sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
60868 pTab->azModuleArg[0], pTab->zName);
60869 return 0.0;
60871 #endif
60873 /* Set the aConstraint[].usable fields and initialize all
60874 ** output variables to zero.
60876 ** aConstraint[].usable is true for constraints where the right-hand
60877 ** side contains only references to tables to the left of the current
60878 ** table. In other words, if the constraint is of the form:
60880 ** column = expr
60882 ** and we are evaluating a join, then the constraint on column is
60883 ** only valid if all tables referenced in expr occur to the left
60884 ** of the table containing column.
60886 ** The aConstraints[] array contains entries for all constraints
60887 ** on the current table. That way we only have to compute it once
60888 ** even though we might try to pick the best index multiple times.
60889 ** For each attempt at picking an index, the order of tables in the
60890 ** join might be different so we have to recompute the usable flag
60891 ** each time.
60893 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
60894 pUsage = pIdxInfo->aConstraintUsage;
60895 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
60896 j = pIdxCons->iTermOffset;
60897 pTerm = &pWC->a[j];
60898 pIdxCons->usable = (pTerm->prereqRight & notReady)==0;
60900 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
60901 if( pIdxInfo->needToFreeIdxStr ){
60902 sqlite3_free(pIdxInfo->idxStr);
60904 pIdxInfo->idxStr = 0;
60905 pIdxInfo->idxNum = 0;
60906 pIdxInfo->needToFreeIdxStr = 0;
60907 pIdxInfo->orderByConsumed = 0;
60908 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
60909 nOrderBy = pIdxInfo->nOrderBy;
60910 if( pIdxInfo->nOrderBy && !orderByUsable ){
60911 *(int*)&pIdxInfo->nOrderBy = 0;
60914 sqlite3SafetyOff(pParse->db);
60915 WHERETRACE(("xBestIndex for %s\n", pTab->zName));
60916 TRACE_IDX_INPUTS(pIdxInfo);
60917 rc = pTab->pVtab->pModule->xBestIndex(pTab->pVtab, pIdxInfo);
60918 TRACE_IDX_OUTPUTS(pIdxInfo);
60919 if( rc!=SQLITE_OK ){
60920 if( rc==SQLITE_NOMEM ){
60921 sqlite3FailedMalloc();
60922 }else {
60923 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
60925 sqlite3SafetyOn(pParse->db);
60926 }else{
60927 rc = sqlite3SafetyOn(pParse->db);
60929 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
60931 return pIdxInfo->estimatedCost;
60933 #endif /* SQLITE_OMIT_VIRTUALTABLE */
60936 ** Find the best index for accessing a particular table. Return a pointer
60937 ** to the index, flags that describe how the index should be used, the
60938 ** number of equality constraints, and the "cost" for this index.
60940 ** The lowest cost index wins. The cost is an estimate of the amount of
60941 ** CPU and disk I/O need to process the request using the selected index.
60942 ** Factors that influence cost include:
60944 ** * The estimated number of rows that will be retrieved. (The
60945 ** fewer the better.)
60947 ** * Whether or not sorting must occur.
60949 ** * Whether or not there must be separate lookups in the
60950 ** index and in the main table.
60953 static double bestIndex(
60954 Parse *pParse, /* The parsing context */
60955 WhereClause *pWC, /* The WHERE clause */
60956 struct SrcList_item *pSrc, /* The FROM clause term to search */
60957 Bitmask notReady, /* Mask of cursors that are not available */
60958 ExprList *pOrderBy, /* The order by clause */
60959 Index **ppIndex, /* Make *ppIndex point to the best index */
60960 int *pFlags, /* Put flags describing this choice in *pFlags */
60961 int *pnEq /* Put the number of == or IN constraints here */
60963 WhereTerm *pTerm;
60964 Index *bestIdx = 0; /* Index that gives the lowest cost */
60965 double lowestCost; /* The cost of using bestIdx */
60966 int bestFlags = 0; /* Flags associated with bestIdx */
60967 int bestNEq = 0; /* Best value for nEq */
60968 int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
60969 Index *pProbe; /* An index we are evaluating */
60970 int rev; /* True to scan in reverse order */
60971 int flags; /* Flags associated with pProbe */
60972 int nEq; /* Number of == or IN constraints */
60973 int eqTermMask; /* Mask of valid equality operators */
60974 double cost; /* Cost of using pProbe */
60976 WHERETRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady));
60977 lowestCost = SQLITE_BIG_DBL;
60978 pProbe = pSrc->pTab->pIndex;
60980 /* If the table has no indices and there are no terms in the where
60981 ** clause that refer to the ROWID, then we will never be able to do
60982 ** anything other than a full table scan on this table. We might as
60983 ** well put it first in the join order. That way, perhaps it can be
60984 ** referenced by other tables in the join.
60986 if( pProbe==0 &&
60987 findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
60988 (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
60989 *pFlags = 0;
60990 *ppIndex = 0;
60991 *pnEq = 0;
60992 return 0.0;
60995 /* Check for a rowid=EXPR or rowid IN (...) constraints
60997 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
60998 if( pTerm ){
60999 Expr *pExpr;
61000 *ppIndex = 0;
61001 bestFlags = WHERE_ROWID_EQ;
61002 if( pTerm->eOperator & WO_EQ ){
61003 /* Rowid== is always the best pick. Look no further. Because only
61004 ** a single row is generated, output is always in sorted order */
61005 *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
61006 *pnEq = 1;
61007 WHERETRACE(("... best is rowid\n"));
61008 return 0.0;
61009 }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
61010 /* Rowid IN (LIST): cost is NlogN where N is the number of list
61011 ** elements. */
61012 lowestCost = pExpr->pList->nExpr;
61013 lowestCost *= estLog(lowestCost);
61014 }else{
61015 /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
61016 ** in the result of the inner select. We have no way to estimate
61017 ** that value so make a wild guess. */
61018 lowestCost = 200;
61020 WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost));
61023 /* Estimate the cost of a table scan. If we do not know how many
61024 ** entries are in the table, use 1 million as a guess.
61026 cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
61027 WHERETRACE(("... table scan base cost: %.9g\n", cost));
61028 flags = WHERE_ROWID_RANGE;
61030 /* Check for constraints on a range of rowids in a table scan.
61032 pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
61033 if( pTerm ){
61034 if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
61035 flags |= WHERE_TOP_LIMIT;
61036 cost /= 3; /* Guess that rowid<EXPR eliminates two-thirds or rows */
61038 if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
61039 flags |= WHERE_BTM_LIMIT;
61040 cost /= 3; /* Guess that rowid>EXPR eliminates two-thirds of rows */
61042 WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
61043 }else{
61044 flags = 0;
61047 /* If the table scan does not satisfy the ORDER BY clause, increase
61048 ** the cost by NlogN to cover the expense of sorting. */
61049 if( pOrderBy ){
61050 if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
61051 flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
61052 if( rev ){
61053 flags |= WHERE_REVERSE;
61055 }else{
61056 cost += cost*estLog(cost);
61057 WHERETRACE(("... sorting increases cost to %.9g\n", cost));
61060 if( cost<lowestCost ){
61061 lowestCost = cost;
61062 bestFlags = flags;
61065 /* If the pSrc table is the right table of a LEFT JOIN then we may not
61066 ** use an index to satisfy IS NULL constraints on that table. This is
61067 ** because columns might end up being NULL if the table does not match -
61068 ** a circumstance which the index cannot help us discover. Ticket #2177.
61070 if( (pSrc->jointype & JT_LEFT)!=0 ){
61071 eqTermMask = WO_EQ|WO_IN;
61072 }else{
61073 eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
61076 /* Look at each index.
61078 for(; pProbe; pProbe=pProbe->pNext){
61079 int i; /* Loop counter */
61080 double inMultiplier = 1;
61082 WHERETRACE(("... index %s:\n", pProbe->zName));
61084 /* Count the number of columns in the index that are satisfied
61085 ** by x=EXPR constraints or x IN (...) constraints.
61087 flags = 0;
61088 for(i=0; i<pProbe->nColumn; i++){
61089 int j = pProbe->aiColumn[i];
61090 pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
61091 if( pTerm==0 ) break;
61092 flags |= WHERE_COLUMN_EQ;
61093 if( pTerm->eOperator & WO_IN ){
61094 Expr *pExpr = pTerm->pExpr;
61095 flags |= WHERE_COLUMN_IN;
61096 if( pExpr->pSelect!=0 ){
61097 inMultiplier *= 25;
61098 }else if( pExpr->pList!=0 ){
61099 inMultiplier *= pExpr->pList->nExpr + 1;
61103 cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
61104 nEq = i;
61105 if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
61106 && nEq==pProbe->nColumn ){
61107 flags |= WHERE_UNIQUE;
61109 WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n", nEq, inMultiplier, cost));
61111 /* Look for range constraints
61113 if( nEq<pProbe->nColumn ){
61114 int j = pProbe->aiColumn[nEq];
61115 pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
61116 if( pTerm ){
61117 flags |= WHERE_COLUMN_RANGE;
61118 if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
61119 flags |= WHERE_TOP_LIMIT;
61120 cost /= 3;
61122 if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
61123 flags |= WHERE_BTM_LIMIT;
61124 cost /= 3;
61126 WHERETRACE(("...... range reduces cost to %.9g\n", cost));
61130 /* Add the additional cost of sorting if that is a factor.
61132 if( pOrderBy ){
61133 if( (flags & WHERE_COLUMN_IN)==0 &&
61134 isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
61135 if( flags==0 ){
61136 flags = WHERE_COLUMN_RANGE;
61138 flags |= WHERE_ORDERBY;
61139 if( rev ){
61140 flags |= WHERE_REVERSE;
61142 }else{
61143 cost += cost*estLog(cost);
61144 WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
61148 /* Check to see if we can get away with using just the index without
61149 ** ever reading the table. If that is the case, then halve the
61150 ** cost of this index.
61152 if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
61153 Bitmask m = pSrc->colUsed;
61154 int j;
61155 for(j=0; j<pProbe->nColumn; j++){
61156 int x = pProbe->aiColumn[j];
61157 if( x<BMS-1 ){
61158 m &= ~(((Bitmask)1)<<x);
61161 if( m==0 ){
61162 flags |= WHERE_IDX_ONLY;
61163 cost /= 2;
61164 WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
61168 /* If this index has achieved the lowest cost so far, then use it.
61170 if( cost < lowestCost ){
61171 bestIdx = pProbe;
61172 lowestCost = cost;
61173 assert( flags!=0 );
61174 bestFlags = flags;
61175 bestNEq = nEq;
61179 /* Report the best result
61181 *ppIndex = bestIdx;
61182 WHERETRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
61183 bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
61184 *pFlags = bestFlags | eqTermMask;
61185 *pnEq = bestNEq;
61186 return lowestCost;
61191 ** Disable a term in the WHERE clause. Except, do not disable the term
61192 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
61193 ** or USING clause of that join.
61195 ** Consider the term t2.z='ok' in the following queries:
61197 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
61198 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
61199 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
61201 ** The t2.z='ok' is disabled in the in (2) because it originates
61202 ** in the ON clause. The term is disabled in (3) because it is not part
61203 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
61205 ** Disabling a term causes that term to not be tested in the inner loop
61206 ** of the join. Disabling is an optimization. When terms are satisfied
61207 ** by indices, we disable them to prevent redundant tests in the inner
61208 ** loop. We would get the correct results if nothing were ever disabled,
61209 ** but joins might run a little slower. The trick is to disable as much
61210 ** as we can without disabling too much. If we disabled in (1), we'd get
61211 ** the wrong answer. See ticket #813.
61213 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
61214 if( pTerm
61215 && (pTerm->flags & TERM_CODED)==0
61216 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
61218 pTerm->flags |= TERM_CODED;
61219 if( pTerm->iParent>=0 ){
61220 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
61221 if( (--pOther->nChild)==0 ){
61222 disableTerm(pLevel, pOther);
61229 ** Generate code that builds a probe for an index.
61231 ** There should be nColumn values on the stack. The index
61232 ** to be probed is pIdx. Pop the values from the stack and
61233 ** replace them all with a single record that is the index
61234 ** problem.
61236 static void buildIndexProbe(
61237 Vdbe *v, /* Generate code into this VM */
61238 int nColumn, /* The number of columns to check for NULL */
61239 Index *pIdx /* Index that we will be searching */
61241 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
61242 sqlite3IndexAffinityStr(v, pIdx);
61247 ** Generate code for a single equality term of the WHERE clause. An equality
61248 ** term can be either X=expr or X IN (...). pTerm is the term to be
61249 ** coded.
61251 ** The current value for the constraint is left on the top of the stack.
61253 ** For a constraint of the form X=expr, the expression is evaluated and its
61254 ** result is left on the stack. For constraints of the form X IN (...)
61255 ** this routine sets up a loop that will iterate over all values of X.
61257 static void codeEqualityTerm(
61258 Parse *pParse, /* The parsing context */
61259 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
61260 WhereLevel *pLevel /* When level of the FROM clause we are working on */
61262 Expr *pX = pTerm->pExpr;
61263 Vdbe *v = pParse->pVdbe;
61264 if( pX->op==TK_EQ ){
61265 sqlite3ExprCode(pParse, pX->pRight);
61266 }else if( pX->op==TK_ISNULL ){
61267 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
61268 #ifndef SQLITE_OMIT_SUBQUERY
61269 }else{
61270 int iTab;
61271 struct InLoop *pIn;
61273 assert( pX->op==TK_IN );
61274 sqlite3CodeSubselect(pParse, pX);
61275 iTab = pX->iTable;
61276 sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
61277 VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
61278 if( pLevel->nIn==0 ){
61279 pLevel->nxt = sqlite3VdbeMakeLabel(v);
61281 pLevel->nIn++;
61282 pLevel->aInLoop = sqliteReallocOrFree(pLevel->aInLoop,
61283 sizeof(pLevel->aInLoop[0])*pLevel->nIn);
61284 pIn = pLevel->aInLoop;
61285 if( pIn ){
61286 pIn += pLevel->nIn - 1;
61287 pIn->iCur = iTab;
61288 pIn->topAddr = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
61289 sqlite3VdbeAddOp(v, OP_IsNull, -1, 0);
61290 }else{
61291 pLevel->nIn = 0;
61293 #endif
61295 disableTerm(pLevel, pTerm);
61299 ** Generate code that will evaluate all == and IN constraints for an
61300 ** index. The values for all constraints are left on the stack.
61302 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
61303 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
61304 ** The index has as many as three equality constraints, but in this
61305 ** example, the third "c" value is an inequality. So only two
61306 ** constraints are coded. This routine will generate code to evaluate
61307 ** a==5 and b IN (1,2,3). The current values for a and b will be left
61308 ** on the stack - a is the deepest and b the shallowest.
61310 ** In the example above nEq==2. But this subroutine works for any value
61311 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
61312 ** The only thing it does is allocate the pLevel->iMem memory cell.
61314 ** This routine always allocates at least one memory cell and puts
61315 ** the address of that memory cell in pLevel->iMem. The code that
61316 ** calls this routine will use pLevel->iMem to store the termination
61317 ** key value of the loop. If one or more IN operators appear, then
61318 ** this routine allocates an additional nEq memory cells for internal
61319 ** use.
61321 static void codeAllEqualityTerms(
61322 Parse *pParse, /* Parsing context */
61323 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
61324 WhereClause *pWC, /* The WHERE clause */
61325 Bitmask notReady /* Which parts of FROM have not yet been coded */
61327 int nEq = pLevel->nEq; /* The number of == or IN constraints to code */
61328 int termsInMem = 0; /* If true, store value in mem[] cells */
61329 Vdbe *v = pParse->pVdbe; /* The virtual machine under construction */
61330 Index *pIdx = pLevel->pIdx; /* The index being used for this loop */
61331 int iCur = pLevel->iTabCur; /* The cursor of the table */
61332 WhereTerm *pTerm; /* A single constraint term */
61333 int j; /* Loop counter */
61335 /* Figure out how many memory cells we will need then allocate them.
61336 ** We always need at least one used to store the loop terminator
61337 ** value. If there are IN operators we'll need one for each == or
61338 ** IN constraint.
61340 pLevel->iMem = pParse->nMem++;
61341 if( pLevel->flags & WHERE_COLUMN_IN ){
61342 pParse->nMem += pLevel->nEq;
61343 termsInMem = 1;
61346 /* Evaluate the equality constraints
61348 assert( pIdx->nColumn>=nEq );
61349 for(j=0; j<nEq; j++){
61350 int k = pIdx->aiColumn[j];
61351 pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx);
61352 if( pTerm==0 ) break;
61353 assert( (pTerm->flags & TERM_CODED)==0 );
61354 codeEqualityTerm(pParse, pTerm, pLevel);
61355 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
61356 sqlite3VdbeAddOp(v, OP_IsNull, termsInMem ? -1 : -(j+1), pLevel->brk);
61358 if( termsInMem ){
61359 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem+j+1, 1);
61363 /* Make sure all the constraint values are on the top of the stack
61365 if( termsInMem ){
61366 for(j=0; j<nEq; j++){
61367 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem+j+1, 0);
61372 #if defined(SQLITE_TEST)
61374 ** The following variable holds a text description of query plan generated
61375 ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
61376 ** overwrites the previous. This information is used for testing and
61377 ** analysis only.
61379 char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
61380 static int nQPlan = 0; /* Next free slow in _query_plan[] */
61382 #endif /* SQLITE_TEST */
61386 ** Free a WhereInfo structure
61388 static void whereInfoFree(WhereInfo *pWInfo){
61389 if( pWInfo ){
61390 int i;
61391 for(i=0; i<pWInfo->nLevel; i++){
61392 sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
61393 if( pInfo ){
61394 if( pInfo->needToFreeIdxStr ){
61395 /* Coverage: Don't think this can be reached. By the time this
61396 ** function is called, the index-strings have been passed
61397 ** to the vdbe layer for deletion.
61399 sqlite3_free(pInfo->idxStr);
61401 sqliteFree(pInfo);
61404 sqliteFree(pWInfo);
61410 ** Generate the beginning of the loop used for WHERE clause processing.
61411 ** The return value is a pointer to an opaque structure that contains
61412 ** information needed to terminate the loop. Later, the calling routine
61413 ** should invoke sqlite3WhereEnd() with the return value of this function
61414 ** in order to complete the WHERE clause processing.
61416 ** If an error occurs, this routine returns NULL.
61418 ** The basic idea is to do a nested loop, one loop for each table in
61419 ** the FROM clause of a select. (INSERT and UPDATE statements are the
61420 ** same as a SELECT with only a single table in the FROM clause.) For
61421 ** example, if the SQL is this:
61423 ** SELECT * FROM t1, t2, t3 WHERE ...;
61425 ** Then the code generated is conceptually like the following:
61427 ** foreach row1 in t1 do \ Code generated
61428 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
61429 ** foreach row3 in t3 do /
61430 ** ...
61431 ** end \ Code generated
61432 ** end |-- by sqlite3WhereEnd()
61433 ** end /
61435 ** Note that the loops might not be nested in the order in which they
61436 ** appear in the FROM clause if a different order is better able to make
61437 ** use of indices. Note also that when the IN operator appears in
61438 ** the WHERE clause, it might result in additional nested loops for
61439 ** scanning through all values on the right-hand side of the IN.
61441 ** There are Btree cursors associated with each table. t1 uses cursor
61442 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
61443 ** And so forth. This routine generates code to open those VDBE cursors
61444 ** and sqlite3WhereEnd() generates the code to close them.
61446 ** The code that sqlite3WhereBegin() generates leaves the cursors named
61447 ** in pTabList pointing at their appropriate entries. The [...] code
61448 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
61449 ** data from the various tables of the loop.
61451 ** If the WHERE clause is empty, the foreach loops must each scan their
61452 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
61453 ** the tables have indices and there are terms in the WHERE clause that
61454 ** refer to those indices, a complete table scan can be avoided and the
61455 ** code will run much faster. Most of the work of this routine is checking
61456 ** to see if there are indices that can be used to speed up the loop.
61458 ** Terms of the WHERE clause are also used to limit which rows actually
61459 ** make it to the "..." in the middle of the loop. After each "foreach",
61460 ** terms of the WHERE clause that use only terms in that loop and outer
61461 ** loops are evaluated and if false a jump is made around all subsequent
61462 ** inner loops (or around the "..." if the test occurs within the inner-
61463 ** most loop)
61465 ** OUTER JOINS
61467 ** An outer join of tables t1 and t2 is conceptally coded as follows:
61469 ** foreach row1 in t1 do
61470 ** flag = 0
61471 ** foreach row2 in t2 do
61472 ** start:
61473 ** ...
61474 ** flag = 1
61475 ** end
61476 ** if flag==0 then
61477 ** move the row2 cursor to a null row
61478 ** goto start
61479 ** fi
61480 ** end
61482 ** ORDER BY CLAUSE PROCESSING
61484 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
61485 ** if there is one. If there is no ORDER BY clause or if this routine
61486 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
61488 ** If an index can be used so that the natural output order of the table
61489 ** scan is correct for the ORDER BY clause, then that index is used and
61490 ** *ppOrderBy is set to NULL. This is an optimization that prevents an
61491 ** unnecessary sort of the result set if an index appropriate for the
61492 ** ORDER BY clause already exists.
61494 ** If the where clause loops cannot be arranged to provide the correct
61495 ** output order, then the *ppOrderBy is unchanged.
61497 static WhereInfo *sqlite3WhereBegin(
61498 Parse *pParse, /* The parser context */
61499 SrcList *pTabList, /* A list of all tables to be scanned */
61500 Expr *pWhere, /* The WHERE clause */
61501 ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
61503 int i; /* Loop counter */
61504 WhereInfo *pWInfo; /* Will become the return value of this function */
61505 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
61506 int brk, cont = 0; /* Addresses used during code generation */
61507 Bitmask notReady; /* Cursors that are not yet positioned */
61508 WhereTerm *pTerm; /* A single term in the WHERE clause */
61509 ExprMaskSet maskSet; /* The expression mask set */
61510 WhereClause wc; /* The WHERE clause is divided into these terms */
61511 struct SrcList_item *pTabItem; /* A single entry from pTabList */
61512 WhereLevel *pLevel; /* A single level in the pWInfo list */
61513 int iFrom; /* First unused FROM clause element */
61514 int andFlags; /* AND-ed combination of all wc.a[].flags */
61516 /* The number of tables in the FROM clause is limited by the number of
61517 ** bits in a Bitmask
61519 if( pTabList->nSrc>BMS ){
61520 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
61521 return 0;
61524 /* Split the WHERE clause into separate subexpressions where each
61525 ** subexpression is separated by an AND operator.
61527 initMaskSet(&maskSet);
61528 whereClauseInit(&wc, pParse, &maskSet);
61529 whereSplit(&wc, pWhere, TK_AND);
61531 /* Allocate and initialize the WhereInfo structure that will become the
61532 ** return value.
61534 pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
61535 if( sqlite3MallocFailed() ){
61536 goto whereBeginNoMem;
61538 pWInfo->nLevel = pTabList->nSrc;
61539 pWInfo->pParse = pParse;
61540 pWInfo->pTabList = pTabList;
61541 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
61543 /* Special case: a WHERE clause that is constant. Evaluate the
61544 ** expression and either jump over all of the code or fall thru.
61546 if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
61547 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
61548 pWhere = 0;
61551 /* Analyze all of the subexpressions. Note that exprAnalyze() might
61552 ** add new virtual terms onto the end of the WHERE clause. We do not
61553 ** want to analyze these virtual terms, so start analyzing at the end
61554 ** and work forward so that the added virtual terms are never processed.
61556 for(i=0; i<pTabList->nSrc; i++){
61557 createMask(&maskSet, pTabList->a[i].iCursor);
61559 exprAnalyzeAll(pTabList, &wc);
61560 if( sqlite3MallocFailed() ){
61561 goto whereBeginNoMem;
61564 /* Chose the best index to use for each table in the FROM clause.
61566 ** This loop fills in the following fields:
61568 ** pWInfo->a[].pIdx The index to use for this level of the loop.
61569 ** pWInfo->a[].flags WHERE_xxx flags associated with pIdx
61570 ** pWInfo->a[].nEq The number of == and IN constraints
61571 ** pWInfo->a[].iFrom When term of the FROM clause is being coded
61572 ** pWInfo->a[].iTabCur The VDBE cursor for the database table
61573 ** pWInfo->a[].iIdxCur The VDBE cursor for the index
61575 ** This loop also figures out the nesting order of tables in the FROM
61576 ** clause.
61578 notReady = ~(Bitmask)0;
61579 pTabItem = pTabList->a;
61580 pLevel = pWInfo->a;
61581 andFlags = ~0;
61582 WHERETRACE(("*** Optimizer Start ***\n"));
61583 for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
61584 Index *pIdx; /* Index for FROM table at pTabItem */
61585 int flags; /* Flags asssociated with pIdx */
61586 int nEq; /* Number of == or IN constraints */
61587 double cost; /* The cost for pIdx */
61588 int j; /* For looping over FROM tables */
61589 Index *pBest = 0; /* The best index seen so far */
61590 int bestFlags = 0; /* Flags associated with pBest */
61591 int bestNEq = 0; /* nEq associated with pBest */
61592 double lowestCost; /* Cost of the pBest */
61593 int bestJ = 0; /* The value of j */
61594 Bitmask m; /* Bitmask value for j or bestJ */
61595 int once = 0; /* True when first table is seen */
61596 sqlite3_index_info *pIndex; /* Current virtual index */
61598 lowestCost = SQLITE_BIG_DBL;
61599 for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
61600 int doNotReorder; /* True if this table should not be reordered */
61602 doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
61603 if( once && doNotReorder ) break;
61604 m = getMask(&maskSet, pTabItem->iCursor);
61605 if( (m & notReady)==0 ){
61606 if( j==iFrom ) iFrom++;
61607 continue;
61609 assert( pTabItem->pTab );
61610 #ifndef SQLITE_OMIT_VIRTUALTABLE
61611 if( IsVirtual(pTabItem->pTab) ){
61612 sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
61613 cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady,
61614 ppOrderBy ? *ppOrderBy : 0, i==0,
61615 ppIdxInfo);
61616 flags = WHERE_VIRTUALTABLE;
61617 pIndex = *ppIdxInfo;
61618 if( pIndex && pIndex->orderByConsumed ){
61619 flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
61621 pIdx = 0;
61622 nEq = 0;
61623 if( (SQLITE_BIG_DBL/2.0)<cost ){
61624 /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
61625 ** inital value of lowestCost in this loop. If it is, then
61626 ** the (cost<lowestCost) test below will never be true and
61627 ** pLevel->pBestIdx never set.
61629 cost = (SQLITE_BIG_DBL/2.0);
61631 }else
61632 #endif
61634 cost = bestIndex(pParse, &wc, pTabItem, notReady,
61635 (i==0 && ppOrderBy) ? *ppOrderBy : 0,
61636 &pIdx, &flags, &nEq);
61637 pIndex = 0;
61639 if( cost<lowestCost ){
61640 once = 1;
61641 lowestCost = cost;
61642 pBest = pIdx;
61643 bestFlags = flags;
61644 bestNEq = nEq;
61645 bestJ = j;
61646 pLevel->pBestIdx = pIndex;
61648 if( doNotReorder ) break;
61650 WHERETRACE(("*** Optimizer choose table %d for loop %d\n", bestJ,
61651 pLevel-pWInfo->a));
61652 if( (bestFlags & WHERE_ORDERBY)!=0 ){
61653 *ppOrderBy = 0;
61655 andFlags &= bestFlags;
61656 pLevel->flags = bestFlags;
61657 pLevel->pIdx = pBest;
61658 pLevel->nEq = bestNEq;
61659 pLevel->aInLoop = 0;
61660 pLevel->nIn = 0;
61661 if( pBest ){
61662 pLevel->iIdxCur = pParse->nTab++;
61663 }else{
61664 pLevel->iIdxCur = -1;
61666 notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
61667 pLevel->iFrom = bestJ;
61669 WHERETRACE(("*** Optimizer Finished ***\n"));
61671 /* If the total query only selects a single row, then the ORDER BY
61672 ** clause is irrelevant.
61674 if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
61675 *ppOrderBy = 0;
61678 /* Open all tables in the pTabList and any indices selected for
61679 ** searching those tables.
61681 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
61682 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
61683 Table *pTab; /* Table to open */
61684 Index *pIx; /* Index used to access pTab (if any) */
61685 int iDb; /* Index of database containing table/index */
61686 int iIdxCur = pLevel->iIdxCur;
61688 #ifndef SQLITE_OMIT_EXPLAIN
61689 if( pParse->explain==2 ){
61690 char *zMsg;
61691 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
61692 zMsg = sqlite3MPrintf("TABLE %s", pItem->zName);
61693 if( pItem->zAlias ){
61694 zMsg = sqlite3MPrintf("%z AS %s", zMsg, pItem->zAlias);
61696 if( (pIx = pLevel->pIdx)!=0 ){
61697 zMsg = sqlite3MPrintf("%z WITH INDEX %s", zMsg, pIx->zName);
61698 }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
61699 zMsg = sqlite3MPrintf("%z USING PRIMARY KEY", zMsg);
61701 #ifndef SQLITE_OMIT_VIRTUALTABLE
61702 else if( pLevel->pBestIdx ){
61703 sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
61704 zMsg = sqlite3MPrintf("%z VIRTUAL TABLE INDEX %d:%s", zMsg,
61705 pBestIdx->idxNum, pBestIdx->idxStr);
61707 #endif
61708 if( pLevel->flags & WHERE_ORDERBY ){
61709 zMsg = sqlite3MPrintf("%z ORDER BY", zMsg);
61711 sqlite3VdbeOp3(v, OP_Explain, i, pLevel->iFrom, zMsg, P3_DYNAMIC);
61713 #endif /* SQLITE_OMIT_EXPLAIN */
61714 pTabItem = &pTabList->a[pLevel->iFrom];
61715 pTab = pTabItem->pTab;
61716 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
61717 if( pTab->isEphem || pTab->pSelect ) continue;
61718 #ifndef SQLITE_OMIT_VIRTUALTABLE
61719 if( pLevel->pBestIdx ){
61720 int iCur = pTabItem->iCursor;
61721 sqlite3VdbeOp3(v, OP_VOpen, iCur, 0, (const char*)pTab->pVtab, P3_VTAB);
61722 }else
61723 #endif
61724 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
61725 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, OP_OpenRead);
61726 if( pTab->nCol<(sizeof(Bitmask)*8) ){
61727 Bitmask b = pTabItem->colUsed;
61728 int n = 0;
61729 for(; b; b=b>>1, n++){}
61730 sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-1, n);
61731 assert( n<=pTab->nCol );
61733 }else{
61734 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
61736 pLevel->iTabCur = pTabItem->iCursor;
61737 if( (pIx = pLevel->pIdx)!=0 ){
61738 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
61739 assert( pIx->pSchema==pTab->pSchema );
61740 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
61741 VdbeComment((v, "# %s", pIx->zName));
61742 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
61743 (char*)pKey, P3_KEYINFO_HANDOFF);
61745 if( (pLevel->flags & (WHERE_IDX_ONLY|WHERE_COLUMN_RANGE))!=0 ){
61746 /* Only call OP_SetNumColumns on the index if we might later use
61747 ** OP_Column on the index. */
61748 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
61750 sqlite3CodeVerifySchema(pParse, iDb);
61752 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
61754 /* Generate the code to do the search. Each iteration of the for
61755 ** loop below generates code for a single nested loop of the VM
61756 ** program.
61758 notReady = ~(Bitmask)0;
61759 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
61760 int j;
61761 int iCur = pTabItem->iCursor; /* The VDBE cursor for the table */
61762 Index *pIdx; /* The index we will be using */
61763 int nxt; /* Where to jump to continue with the next IN case */
61764 int iIdxCur; /* The VDBE cursor for the index */
61765 int omitTable; /* True if we use the index only */
61766 int bRev; /* True if we need to scan in reverse order */
61768 pTabItem = &pTabList->a[pLevel->iFrom];
61769 iCur = pTabItem->iCursor;
61770 pIdx = pLevel->pIdx;
61771 iIdxCur = pLevel->iIdxCur;
61772 bRev = (pLevel->flags & WHERE_REVERSE)!=0;
61773 omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
61775 /* Create labels for the "break" and "continue" instructions
61776 ** for the current loop. Jump to brk to break out of a loop.
61777 ** Jump to cont to go immediately to the next iteration of the
61778 ** loop.
61780 ** When there is an IN operator, we also have a "nxt" label that
61781 ** means to continue with the next IN value combination. When
61782 ** there are no IN operators in the constraints, the "nxt" label
61783 ** is the same as "brk".
61785 brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v);
61786 cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
61788 /* If this is the right table of a LEFT OUTER JOIN, allocate and
61789 ** initialize a memory cell that records if this table matches any
61790 ** row of the left table of the join.
61792 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
61793 if( !pParse->nMem ) pParse->nMem++;
61794 pLevel->iLeftJoin = pParse->nMem++;
61795 sqlite3VdbeAddOp(v, OP_MemInt, 0, pLevel->iLeftJoin);
61796 VdbeComment((v, "# init LEFT JOIN no-match flag"));
61799 #ifndef SQLITE_OMIT_VIRTUALTABLE
61800 if( pLevel->pBestIdx ){
61801 /* Case 0: The table is a virtual-table. Use the VFilter and VNext
61802 ** to access the data.
61804 int j;
61805 sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
61806 int nConstraint = pBestIdx->nConstraint;
61807 struct sqlite3_index_constraint_usage *aUsage =
61808 pBestIdx->aConstraintUsage;
61809 const struct sqlite3_index_constraint *aConstraint =
61810 pBestIdx->aConstraint;
61812 for(j=1; j<=nConstraint; j++){
61813 int k;
61814 for(k=0; k<nConstraint; k++){
61815 if( aUsage[k].argvIndex==j ){
61816 int iTerm = aConstraint[k].iTermOffset;
61817 sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight);
61818 break;
61821 if( k==nConstraint ) break;
61823 sqlite3VdbeAddOp(v, OP_Integer, j-1, 0);
61824 sqlite3VdbeAddOp(v, OP_Integer, pBestIdx->idxNum, 0);
61825 sqlite3VdbeOp3(v, OP_VFilter, iCur, brk, pBestIdx->idxStr,
61826 pBestIdx->needToFreeIdxStr ? P3_MPRINTF : P3_STATIC);
61827 pBestIdx->needToFreeIdxStr = 0;
61828 for(j=0; j<pBestIdx->nConstraint; j++){
61829 if( aUsage[j].omit ){
61830 int iTerm = aConstraint[j].iTermOffset;
61831 disableTerm(pLevel, &wc.a[iTerm]);
61834 pLevel->op = OP_VNext;
61835 pLevel->p1 = iCur;
61836 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
61837 }else
61838 #endif /* SQLITE_OMIT_VIRTUALTABLE */
61840 if( pLevel->flags & WHERE_ROWID_EQ ){
61841 /* Case 1: We can directly reference a single row using an
61842 ** equality comparison against the ROWID field. Or
61843 ** we reference multiple rows using a "rowid IN (...)"
61844 ** construct.
61846 pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
61847 assert( pTerm!=0 );
61848 assert( pTerm->pExpr!=0 );
61849 assert( pTerm->leftCursor==iCur );
61850 assert( omitTable==0 );
61851 codeEqualityTerm(pParse, pTerm, pLevel);
61852 nxt = pLevel->nxt;
61853 sqlite3VdbeAddOp(v, OP_MustBeInt, 1, nxt);
61854 sqlite3VdbeAddOp(v, OP_NotExists, iCur, nxt);
61855 VdbeComment((v, "pk"));
61856 pLevel->op = OP_Noop;
61857 }else if( pLevel->flags & WHERE_ROWID_RANGE ){
61858 /* Case 2: We have an inequality comparison against the ROWID field.
61860 int testOp = OP_Noop;
61861 int start;
61862 WhereTerm *pStart, *pEnd;
61864 assert( omitTable==0 );
61865 pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
61866 pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
61867 if( bRev ){
61868 pTerm = pStart;
61869 pStart = pEnd;
61870 pEnd = pTerm;
61872 if( pStart ){
61873 Expr *pX;
61874 pX = pStart->pExpr;
61875 assert( pX!=0 );
61876 assert( pStart->leftCursor==iCur );
61877 sqlite3ExprCode(pParse, pX->pRight);
61878 sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
61879 sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
61880 VdbeComment((v, "pk"));
61881 disableTerm(pLevel, pStart);
61882 }else{
61883 sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
61885 if( pEnd ){
61886 Expr *pX;
61887 pX = pEnd->pExpr;
61888 assert( pX!=0 );
61889 assert( pEnd->leftCursor==iCur );
61890 sqlite3ExprCode(pParse, pX->pRight);
61891 pLevel->iMem = pParse->nMem++;
61892 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
61893 if( pX->op==TK_LT || pX->op==TK_GT ){
61894 testOp = bRev ? OP_Le : OP_Ge;
61895 }else{
61896 testOp = bRev ? OP_Lt : OP_Gt;
61898 disableTerm(pLevel, pEnd);
61900 start = sqlite3VdbeCurrentAddr(v);
61901 pLevel->op = bRev ? OP_Prev : OP_Next;
61902 pLevel->p1 = iCur;
61903 pLevel->p2 = start;
61904 if( testOp!=OP_Noop ){
61905 sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
61906 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
61907 sqlite3VdbeAddOp(v, testOp, SQLITE_AFF_NUMERIC|0x100, brk);
61909 }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
61910 /* Case 3: The WHERE clause term that refers to the right-most
61911 ** column of the index is an inequality. For example, if
61912 ** the index is on (x,y,z) and the WHERE clause is of the
61913 ** form "x=5 AND y<10" then this case is used. Only the
61914 ** right-most column can be an inequality - the rest must
61915 ** use the "==" and "IN" operators.
61917 ** This case is also used when there are no WHERE clause
61918 ** constraints but an index is selected anyway, in order
61919 ** to force the output order to conform to an ORDER BY.
61921 int start;
61922 int nEq = pLevel->nEq;
61923 int topEq=0; /* True if top limit uses ==. False is strictly < */
61924 int btmEq=0; /* True if btm limit uses ==. False if strictly > */
61925 int topOp, btmOp; /* Operators for the top and bottom search bounds */
61926 int testOp;
61927 int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
61928 int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
61930 /* Generate code to evaluate all constraint terms using == or IN
61931 ** and level the values of those terms on the stack.
61933 codeAllEqualityTerms(pParse, pLevel, &wc, notReady);
61935 /* Duplicate the equality term values because they will all be
61936 ** used twice: once to make the termination key and once to make the
61937 ** start key.
61939 for(j=0; j<nEq; j++){
61940 sqlite3VdbeAddOp(v, OP_Dup, nEq-1, 0);
61943 /* Figure out what comparison operators to use for top and bottom
61944 ** search bounds. For an ascending index, the bottom bound is a > or >=
61945 ** operator and the top bound is a < or <= operator. For a descending
61946 ** index the operators are reversed.
61948 if( pIdx->aSortOrder[nEq]==SQLITE_SO_ASC ){
61949 topOp = WO_LT|WO_LE;
61950 btmOp = WO_GT|WO_GE;
61951 }else{
61952 topOp = WO_GT|WO_GE;
61953 btmOp = WO_LT|WO_LE;
61954 SWAP(int, topLimit, btmLimit);
61957 /* Generate the termination key. This is the key value that
61958 ** will end the search. There is no termination key if there
61959 ** are no equality terms and no "X<..." term.
61961 ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
61962 ** key computed here really ends up being the start key.
61964 nxt = pLevel->nxt;
61965 if( topLimit ){
61966 Expr *pX;
61967 int k = pIdx->aiColumn[j];
61968 pTerm = findTerm(&wc, iCur, k, notReady, topOp, pIdx);
61969 assert( pTerm!=0 );
61970 pX = pTerm->pExpr;
61971 assert( (pTerm->flags & TERM_CODED)==0 );
61972 sqlite3ExprCode(pParse, pX->pRight);
61973 sqlite3VdbeAddOp(v, OP_IsNull, -(nEq*2+1), nxt);
61974 topEq = pTerm->eOperator & (WO_LE|WO_GE);
61975 disableTerm(pLevel, pTerm);
61976 testOp = OP_IdxGE;
61977 }else{
61978 testOp = nEq>0 ? OP_IdxGE : OP_Noop;
61979 topEq = 1;
61981 if( testOp!=OP_Noop ){
61982 int nCol = nEq + topLimit;
61983 pLevel->iMem = pParse->nMem++;
61984 buildIndexProbe(v, nCol, pIdx);
61985 if( bRev ){
61986 int op = topEq ? OP_MoveLe : OP_MoveLt;
61987 sqlite3VdbeAddOp(v, op, iIdxCur, nxt);
61988 }else{
61989 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
61991 }else if( bRev ){
61992 sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
61995 /* Generate the start key. This is the key that defines the lower
61996 ** bound on the search. There is no start key if there are no
61997 ** equality terms and if there is no "X>..." term. In
61998 ** that case, generate a "Rewind" instruction in place of the
61999 ** start key search.
62001 ** 2002-Dec-04: In the case of a reverse-order search, the so-called
62002 ** "start" key really ends up being used as the termination key.
62004 if( btmLimit ){
62005 Expr *pX;
62006 int k = pIdx->aiColumn[j];
62007 pTerm = findTerm(&wc, iCur, k, notReady, btmOp, pIdx);
62008 assert( pTerm!=0 );
62009 pX = pTerm->pExpr;
62010 assert( (pTerm->flags & TERM_CODED)==0 );
62011 sqlite3ExprCode(pParse, pX->pRight);
62012 sqlite3VdbeAddOp(v, OP_IsNull, -(nEq+1), nxt);
62013 btmEq = pTerm->eOperator & (WO_LE|WO_GE);
62014 disableTerm(pLevel, pTerm);
62015 }else{
62016 btmEq = 1;
62018 if( nEq>0 || btmLimit ){
62019 int nCol = nEq + btmLimit;
62020 buildIndexProbe(v, nCol, pIdx);
62021 if( bRev ){
62022 pLevel->iMem = pParse->nMem++;
62023 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
62024 testOp = OP_IdxLT;
62025 }else{
62026 int op = btmEq ? OP_MoveGe : OP_MoveGt;
62027 sqlite3VdbeAddOp(v, op, iIdxCur, nxt);
62029 }else if( bRev ){
62030 testOp = OP_Noop;
62031 }else{
62032 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
62035 /* Generate the the top of the loop. If there is a termination
62036 ** key we have to test for that key and abort at the top of the
62037 ** loop.
62039 start = sqlite3VdbeCurrentAddr(v);
62040 if( testOp!=OP_Noop ){
62041 sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
62042 sqlite3VdbeAddOp(v, testOp, iIdxCur, nxt);
62043 if( (topEq && !bRev) || (!btmEq && bRev) ){
62044 sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
62047 if( topLimit | btmLimit ){
62048 sqlite3VdbeAddOp(v, OP_Column, iIdxCur, nEq);
62049 sqlite3VdbeAddOp(v, OP_IsNull, 1, cont);
62051 if( !omitTable ){
62052 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
62053 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
62056 /* Record the instruction used to terminate the loop.
62058 pLevel->op = bRev ? OP_Prev : OP_Next;
62059 pLevel->p1 = iIdxCur;
62060 pLevel->p2 = start;
62061 }else if( pLevel->flags & WHERE_COLUMN_EQ ){
62062 /* Case 4: There is an index and all terms of the WHERE clause that
62063 ** refer to the index using the "==" or "IN" operators.
62065 int start;
62066 int nEq = pLevel->nEq;
62068 /* Generate code to evaluate all constraint terms using == or IN
62069 ** and leave the values of those terms on the stack.
62071 codeAllEqualityTerms(pParse, pLevel, &wc, notReady);
62072 nxt = pLevel->nxt;
62074 /* Generate a single key that will be used to both start and terminate
62075 ** the search
62077 buildIndexProbe(v, nEq, pIdx);
62078 sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
62080 /* Generate code (1) to move to the first matching element of the table.
62081 ** Then generate code (2) that jumps to "nxt" after the cursor is past
62082 ** the last matching element of the table. The code (1) is executed
62083 ** once to initialize the search, the code (2) is executed before each
62084 ** iteration of the scan to see if the scan has finished. */
62085 if( bRev ){
62086 /* Scan in reverse order */
62087 sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, nxt);
62088 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
62089 sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, nxt);
62090 pLevel->op = OP_Prev;
62091 }else{
62092 /* Scan in the forward order */
62093 sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, nxt);
62094 start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
62095 sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, nxt, "+", P3_STATIC);
62096 pLevel->op = OP_Next;
62098 if( !omitTable ){
62099 sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
62100 sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
62102 pLevel->p1 = iIdxCur;
62103 pLevel->p2 = start;
62104 }else{
62105 /* Case 5: There is no usable index. We must do a complete
62106 ** scan of the entire table.
62108 assert( omitTable==0 );
62109 assert( bRev==0 );
62110 pLevel->op = OP_Next;
62111 pLevel->p1 = iCur;
62112 pLevel->p2 = 1 + sqlite3VdbeAddOp(v, OP_Rewind, iCur, brk);
62114 notReady &= ~getMask(&maskSet, iCur);
62116 /* Insert code to test every subexpression that can be completely
62117 ** computed using the current set of tables.
62119 for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
62120 Expr *pE;
62121 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
62122 if( (pTerm->prereqAll & notReady)!=0 ) continue;
62123 pE = pTerm->pExpr;
62124 assert( pE!=0 );
62125 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
62126 continue;
62128 sqlite3ExprIfFalse(pParse, pE, cont, 1);
62129 pTerm->flags |= TERM_CODED;
62132 /* For a LEFT OUTER JOIN, generate code that will record the fact that
62133 ** at least one row of the right table has matched the left table.
62135 if( pLevel->iLeftJoin ){
62136 pLevel->top = sqlite3VdbeCurrentAddr(v);
62137 sqlite3VdbeAddOp(v, OP_MemInt, 1, pLevel->iLeftJoin);
62138 VdbeComment((v, "# record LEFT JOIN hit"));
62139 for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
62140 if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
62141 if( (pTerm->prereqAll & notReady)!=0 ) continue;
62142 assert( pTerm->pExpr );
62143 sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1);
62144 pTerm->flags |= TERM_CODED;
62149 #ifdef SQLITE_TEST /* For testing and debugging use only */
62150 /* Record in the query plan information about the current table
62151 ** and the index used to access it (if any). If the table itself
62152 ** is not used, its name is just '{}'. If no index is used
62153 ** the index is listed as "{}". If the primary key is used the
62154 ** index name is '*'.
62156 for(i=0; i<pTabList->nSrc; i++){
62157 char *z;
62158 int n;
62159 pLevel = &pWInfo->a[i];
62160 pTabItem = &pTabList->a[pLevel->iFrom];
62161 z = pTabItem->zAlias;
62162 if( z==0 ) z = pTabItem->pTab->zName;
62163 n = strlen(z);
62164 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
62165 if( pLevel->flags & WHERE_IDX_ONLY ){
62166 memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
62167 nQPlan += 2;
62168 }else{
62169 memcpy(&sqlite3_query_plan[nQPlan], z, n);
62170 nQPlan += n;
62172 sqlite3_query_plan[nQPlan++] = ' ';
62174 if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
62175 memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
62176 nQPlan += 2;
62177 }else if( pLevel->pIdx==0 ){
62178 memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
62179 nQPlan += 3;
62180 }else{
62181 n = strlen(pLevel->pIdx->zName);
62182 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
62183 memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n);
62184 nQPlan += n;
62185 sqlite3_query_plan[nQPlan++] = ' ';
62189 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
62190 sqlite3_query_plan[--nQPlan] = 0;
62192 sqlite3_query_plan[nQPlan] = 0;
62193 nQPlan = 0;
62194 #endif /* SQLITE_TEST // Testing and debugging use only */
62196 /* Record the continuation address in the WhereInfo structure. Then
62197 ** clean up and return.
62199 pWInfo->iContinue = cont;
62200 whereClauseClear(&wc);
62201 return pWInfo;
62203 /* Jump here if malloc fails */
62204 whereBeginNoMem:
62205 whereClauseClear(&wc);
62206 whereInfoFree(pWInfo);
62207 return 0;
62211 ** Generate the end of the WHERE loop. See comments on
62212 ** sqlite3WhereBegin() for additional information.
62214 static void sqlite3WhereEnd(WhereInfo *pWInfo){
62215 Vdbe *v = pWInfo->pParse->pVdbe;
62216 int i;
62217 WhereLevel *pLevel;
62218 SrcList *pTabList = pWInfo->pTabList;
62220 /* Generate loop termination code.
62222 for(i=pTabList->nSrc-1; i>=0; i--){
62223 pLevel = &pWInfo->a[i];
62224 sqlite3VdbeResolveLabel(v, pLevel->cont);
62225 if( pLevel->op!=OP_Noop ){
62226 sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
62228 if( pLevel->nIn ){
62229 struct InLoop *pIn;
62230 int j;
62231 sqlite3VdbeResolveLabel(v, pLevel->nxt);
62232 for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){
62233 sqlite3VdbeJumpHere(v, pIn->topAddr+1);
62234 sqlite3VdbeAddOp(v, OP_Next, pIn->iCur, pIn->topAddr);
62235 sqlite3VdbeJumpHere(v, pIn->topAddr-1);
62237 sqliteFree(pLevel->aInLoop);
62239 sqlite3VdbeResolveLabel(v, pLevel->brk);
62240 if( pLevel->iLeftJoin ){
62241 int addr;
62242 addr = sqlite3VdbeAddOp(v, OP_IfMemPos, pLevel->iLeftJoin, 0);
62243 sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
62244 if( pLevel->iIdxCur>=0 ){
62245 sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
62247 sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
62248 sqlite3VdbeJumpHere(v, addr);
62252 /* The "break" point is here, just past the end of the outer loop.
62253 ** Set it.
62255 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
62257 /* Close all of the cursors that were opened by sqlite3WhereBegin.
62259 for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
62260 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
62261 Table *pTab = pTabItem->pTab;
62262 assert( pTab!=0 );
62263 if( pTab->isEphem || pTab->pSelect ) continue;
62264 if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
62265 sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
62267 if( pLevel->pIdx!=0 ){
62268 sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
62271 /* Make cursor substitutions for cases where we want to use
62272 ** just the index and never reference the table.
62274 ** Calls to the code generator in between sqlite3WhereBegin and
62275 ** sqlite3WhereEnd will have created code that references the table
62276 ** directly. This loop scans all that code looking for opcodes
62277 ** that reference the table and converts them into opcodes that
62278 ** reference the index.
62280 if( pLevel->flags & WHERE_IDX_ONLY ){
62281 int k, j, last;
62282 VdbeOp *pOp;
62283 Index *pIdx = pLevel->pIdx;
62285 assert( pIdx!=0 );
62286 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
62287 last = sqlite3VdbeCurrentAddr(v);
62288 for(k=pWInfo->iTop; k<last; k++, pOp++){
62289 if( pOp->p1!=pLevel->iTabCur ) continue;
62290 if( pOp->opcode==OP_Column ){
62291 pOp->p1 = pLevel->iIdxCur;
62292 for(j=0; j<pIdx->nColumn; j++){
62293 if( pOp->p2==pIdx->aiColumn[j] ){
62294 pOp->p2 = j;
62295 break;
62298 }else if( pOp->opcode==OP_Rowid ){
62299 pOp->p1 = pLevel->iIdxCur;
62300 pOp->opcode = OP_IdxRowid;
62301 }else if( pOp->opcode==OP_NullRow ){
62302 pOp->opcode = OP_Noop;
62308 /* Final cleanup
62310 whereInfoFree(pWInfo);
62311 return;
62314 /************** End of where.c ***********************************************/
62315 /************** Begin file parse.c *******************************************/
62316 /* Driver template for the LEMON parser generator.
62317 ** The author disclaims copyright to this source code.
62319 /* First off, code is include which follows the "include" declaration
62320 ** in the input file. */
62324 ** An instance of this structure holds information about the
62325 ** LIMIT clause of a SELECT statement.
62327 struct LimitVal {
62328 Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
62329 Expr *pOffset; /* The OFFSET expression. NULL if there is none */
62333 ** An instance of this structure is used to store the LIKE,
62334 ** GLOB, NOT LIKE, and NOT GLOB operators.
62336 struct LikeOp {
62337 Token eOperator; /* "like" or "glob" or "regexp" */
62338 int not; /* True if the NOT keyword is present */
62342 ** An instance of the following structure describes the event of a
62343 ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
62344 ** TK_DELETE, or TK_INSTEAD. If the event is of the form
62346 ** UPDATE ON (a,b,c)
62348 ** Then the "b" IdList records the list "a,b,c".
62350 struct TrigEvent { int a; IdList * b; };
62353 ** An instance of this structure holds the ATTACH key and the key type.
62355 struct AttachKey { int type; Token key; };
62357 /* Next is all token values, in a form suitable for use by makeheaders.
62358 ** This section will be null unless lemon is run with the -m switch.
62361 ** These constants (all generated automatically by the parser generator)
62362 ** specify the various kinds of tokens (terminals) that the parser
62363 ** understands.
62365 ** Each symbol here is a terminal symbol in the grammar.
62367 /* Make sure the INTERFACE macro is defined.
62369 #ifndef INTERFACE
62370 # define INTERFACE 1
62371 #endif
62372 /* The next thing included is series of defines which control
62373 ** various aspects of the generated parser.
62374 ** YYCODETYPE is the data type used for storing terminal
62375 ** and nonterminal numbers. "unsigned char" is
62376 ** used if there are fewer than 250 terminals
62377 ** and nonterminals. "int" is used otherwise.
62378 ** YYNOCODE is a number of type YYCODETYPE which corresponds
62379 ** to no legal terminal or nonterminal number. This
62380 ** number is used to fill in empty slots of the hash
62381 ** table.
62382 ** YYFALLBACK If defined, this indicates that one or more tokens
62383 ** have fall-back values which should be used if the
62384 ** original value of the token will not parse.
62385 ** YYACTIONTYPE is the data type used for storing terminal
62386 ** and nonterminal numbers. "unsigned char" is
62387 ** used if there are fewer than 250 rules and
62388 ** states combined. "int" is used otherwise.
62389 ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
62390 ** directly to the parser from the tokenizer.
62391 ** YYMINORTYPE is the data type used for all minor tokens.
62392 ** This is typically a union of many types, one of
62393 ** which is sqlite3ParserTOKENTYPE. The entry in the union
62394 ** for base tokens is called "yy0".
62395 ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
62396 ** zero the stack is dynamically sized using realloc()
62397 ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
62398 ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
62399 ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
62400 ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
62401 ** YYNSTATE the combined number of states.
62402 ** YYNRULE the number of rules in the grammar
62403 ** YYERRORSYMBOL is the code number of the error symbol. If not
62404 ** defined, then do no error processing.
62406 #define YYCODETYPE unsigned char
62407 #define YYNOCODE 248
62408 #define YYACTIONTYPE unsigned short int
62409 #define YYWILDCARD 59
62410 #define sqlite3ParserTOKENTYPE Token
62411 typedef union {
62412 sqlite3ParserTOKENTYPE yy0;
62413 int yy46;
62414 struct LikeOp yy72;
62415 Expr* yy172;
62416 ExprList* yy174;
62417 Select* yy219;
62418 struct LimitVal yy234;
62419 TriggerStep* yy243;
62420 struct TrigEvent yy370;
62421 SrcList* yy373;
62422 Expr * yy386;
62423 struct {int value; int mask;} yy405;
62424 Token yy410;
62425 IdList* yy432;
62426 int yy495;
62427 } YYMINORTYPE;
62428 #ifndef YYSTACKDEPTH
62429 #define YYSTACKDEPTH 100
62430 #endif
62431 #define sqlite3ParserARG_SDECL Parse *pParse;
62432 #define sqlite3ParserARG_PDECL ,Parse *pParse
62433 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
62434 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
62435 #define YYNSTATE 586
62436 #define YYNRULE 311
62437 #define YYERRORSYMBOL 138
62438 #define YYERRSYMDT yy495
62439 #define YYFALLBACK 1
62440 #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
62441 #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
62442 #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
62444 /* Next are that tables used to determine what action to take based on the
62445 ** current state and lookahead token. These tables are used to implement
62446 ** functions that take a state number and lookahead value and return an
62447 ** action integer.
62449 ** Suppose the action integer is N. Then the action is determined as
62450 ** follows
62452 ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
62453 ** token onto the stack and goto state N.
62455 ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
62457 ** N == YYNSTATE+YYNRULE A syntax error has occurred.
62459 ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
62461 ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
62462 ** slots in the yy_action[] table.
62464 ** The action table is constructed as a single large table named yy_action[].
62465 ** Given state S and lookahead X, the action is computed as
62467 ** yy_action[ yy_shift_ofst[S] + X ]
62469 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
62470 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
62471 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
62472 ** and that yy_default[S] should be used instead.
62474 ** The formula above is for computing the action when the lookahead is
62475 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
62476 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
62477 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
62478 ** YY_SHIFT_USE_DFLT.
62480 ** The following are the tables generated in this section:
62482 ** yy_action[] A single table containing all actions.
62483 ** yy_lookahead[] A table containing the lookahead for each entry in
62484 ** yy_action. Used to detect hash collisions.
62485 ** yy_shift_ofst[] For each state, the offset into yy_action for
62486 ** shifting terminals.
62487 ** yy_reduce_ofst[] For each state, the offset into yy_action for
62488 ** shifting non-terminals after a reduce.
62489 ** yy_default[] Default action for each state.
62491 static const YYACTIONTYPE yy_action[] = {
62492 /* 0 */ 289, 898, 121, 585, 405, 169, 2, 435, 61, 61,
62493 /* 10 */ 61, 61, 517, 63, 63, 63, 63, 64, 64, 65,
62494 /* 20 */ 65, 65, 66, 230, 387, 384, 420, 426, 68, 63,
62495 /* 30 */ 63, 63, 63, 64, 64, 65, 65, 65, 66, 230,
62496 /* 40 */ 443, 208, 392, 447, 60, 59, 294, 430, 431, 427,
62497 /* 50 */ 427, 62, 62, 61, 61, 61, 61, 205, 63, 63,
62498 /* 60 */ 63, 63, 64, 64, 65, 65, 65, 66, 230, 289,
62499 /* 70 */ 368, 316, 435, 487, 205, 80, 67, 415, 69, 151,
62500 /* 80 */ 63, 63, 63, 63, 64, 64, 65, 65, 65, 66,
62501 /* 90 */ 230, 515, 162, 410, 35, 420, 426, 443, 571, 58,
62502 /* 100 */ 64, 64, 65, 65, 65, 66, 230, 393, 394, 417,
62503 /* 110 */ 417, 417, 289, 60, 59, 294, 430, 431, 427, 427,
62504 /* 120 */ 62, 62, 61, 61, 61, 61, 302, 63, 63, 63,
62505 /* 130 */ 63, 64, 64, 65, 65, 65, 66, 230, 420, 426,
62506 /* 140 */ 92, 65, 65, 65, 66, 230, 392, 456, 472, 67,
62507 /* 150 */ 56, 69, 151, 169, 406, 435, 60, 59, 294, 430,
62508 /* 160 */ 431, 427, 427, 62, 62, 61, 61, 61, 61, 247,
62509 /* 170 */ 63, 63, 63, 63, 64, 64, 65, 65, 65, 66,
62510 /* 180 */ 230, 289, 569, 522, 292, 620, 111, 478, 515, 447,
62511 /* 190 */ 230, 316, 403, 21, 67, 460, 69, 151, 66, 230,
62512 /* 200 */ 568, 443, 208, 67, 224, 69, 151, 420, 426, 146,
62513 /* 210 */ 147, 393, 394, 410, 41, 386, 148, 531, 2, 487,
62514 /* 220 */ 435, 566, 232, 415, 289, 60, 59, 294, 430, 431,
62515 /* 230 */ 427, 427, 62, 62, 61, 61, 61, 61, 316, 63,
62516 /* 240 */ 63, 63, 63, 64, 64, 65, 65, 65, 66, 230,
62517 /* 250 */ 420, 426, 486, 330, 211, 417, 417, 417, 359, 270,
62518 /* 260 */ 410, 41, 378, 207, 362, 542, 245, 289, 60, 59,
62519 /* 270 */ 294, 430, 431, 427, 427, 62, 62, 61, 61, 61,
62520 /* 280 */ 61, 392, 63, 63, 63, 63, 64, 64, 65, 65,
62521 /* 290 */ 65, 66, 230, 420, 426, 260, 299, 273, 522, 271,
62522 /* 300 */ 522, 210, 370, 319, 223, 433, 433, 532, 21, 576,
62523 /* 310 */ 21, 60, 59, 294, 430, 431, 427, 427, 62, 62,
62524 /* 320 */ 61, 61, 61, 61, 191, 63, 63, 63, 63, 64,
62525 /* 330 */ 64, 65, 65, 65, 66, 230, 261, 316, 239, 76,
62526 /* 340 */ 289, 544, 299, 149, 482, 150, 393, 394, 178, 240,
62527 /* 350 */ 569, 341, 344, 345, 404, 520, 445, 322, 165, 410,
62528 /* 360 */ 28, 540, 346, 517, 248, 539, 420, 426, 568, 567,
62529 /* 370 */ 161, 115, 238, 339, 243, 340, 173, 358, 272, 411,
62530 /* 380 */ 821, 488, 79, 249, 60, 59, 294, 430, 431, 427,
62531 /* 390 */ 427, 62, 62, 61, 61, 61, 61, 530, 63, 63,
62532 /* 400 */ 63, 63, 64, 64, 65, 65, 65, 66, 230, 289,
62533 /* 410 */ 248, 178, 465, 485, 341, 344, 345, 115, 238, 339,
62534 /* 420 */ 243, 340, 173, 82, 316, 346, 316, 491, 492, 249,
62535 /* 430 */ 565, 207, 152, 523, 489, 420, 426, 178, 529, 503,
62536 /* 440 */ 341, 344, 345, 407, 472, 528, 410, 35, 410, 35,
62537 /* 450 */ 171, 346, 198, 60, 59, 294, 430, 431, 427, 427,
62538 /* 460 */ 62, 62, 61, 61, 61, 61, 411, 63, 63, 63,
62539 /* 470 */ 63, 64, 64, 65, 65, 65, 66, 230, 289, 548,
62540 /* 480 */ 579, 288, 502, 234, 411, 316, 411, 316, 296, 283,
62541 /* 490 */ 298, 316, 445, 521, 165, 476, 172, 157, 421, 422,
62542 /* 500 */ 457, 335, 457, 144, 420, 426, 366, 410, 35, 410,
62543 /* 510 */ 36, 435, 1, 410, 49, 327, 392, 547, 193, 424,
62544 /* 520 */ 425, 156, 60, 59, 294, 430, 431, 427, 427, 62,
62545 /* 530 */ 62, 61, 61, 61, 61, 333, 63, 63, 63, 63,
62546 /* 540 */ 64, 64, 65, 65, 65, 66, 230, 289, 423, 332,
62547 /* 550 */ 452, 252, 411, 295, 438, 439, 297, 316, 349, 307,
62548 /* 560 */ 231, 457, 453, 321, 438, 439, 392, 369, 266, 265,
62549 /* 570 */ 189, 217, 392, 420, 426, 454, 435, 493, 205, 410,
62550 /* 580 */ 49, 393, 394, 583, 889, 174, 889, 494, 545, 492,
62551 /* 590 */ 392, 60, 59, 294, 430, 431, 427, 427, 62, 62,
62552 /* 600 */ 61, 61, 61, 61, 411, 63, 63, 63, 63, 64,
62553 /* 610 */ 64, 65, 65, 65, 66, 230, 289, 207, 586, 387,
62554 /* 620 */ 384, 91, 10, 580, 336, 308, 392, 207, 367, 480,
62555 /* 630 */ 316, 393, 394, 583, 888, 219, 888, 393, 394, 476,
62556 /* 640 */ 291, 233, 420, 426, 481, 249, 410, 3, 434, 260,
62557 /* 650 */ 317, 363, 410, 29, 448, 393, 394, 468, 260, 289,
62558 /* 660 */ 60, 59, 294, 430, 431, 427, 427, 62, 62, 61,
62559 /* 670 */ 61, 61, 61, 580, 63, 63, 63, 63, 64, 64,
62560 /* 680 */ 65, 65, 65, 66, 230, 420, 426, 391, 312, 388,
62561 /* 690 */ 555, 393, 394, 75, 204, 77, 395, 396, 397, 557,
62562 /* 700 */ 357, 197, 289, 60, 59, 294, 430, 431, 427, 427,
62563 /* 710 */ 62, 62, 61, 61, 61, 61, 316, 63, 63, 63,
62564 /* 720 */ 63, 64, 64, 65, 65, 65, 66, 230, 420, 426,
62565 /* 730 */ 319, 116, 433, 433, 319, 411, 433, 433, 410, 24,
62566 /* 740 */ 319, 515, 433, 433, 515, 289, 60, 70, 294, 430,
62567 /* 750 */ 431, 427, 427, 62, 62, 61, 61, 61, 61, 375,
62568 /* 760 */ 63, 63, 63, 63, 64, 64, 65, 65, 65, 66,
62569 /* 770 */ 230, 420, 426, 538, 356, 538, 216, 260, 472, 303,
62570 /* 780 */ 175, 176, 177, 254, 476, 515, 260, 383, 289, 5,
62571 /* 790 */ 59, 294, 430, 431, 427, 427, 62, 62, 61, 61,
62572 /* 800 */ 61, 61, 316, 63, 63, 63, 63, 64, 64, 65,
62573 /* 810 */ 65, 65, 66, 230, 420, 426, 392, 236, 380, 247,
62574 /* 820 */ 304, 258, 247, 256, 410, 33, 260, 558, 125, 467,
62575 /* 830 */ 515, 416, 168, 157, 294, 430, 431, 427, 427, 62,
62576 /* 840 */ 62, 61, 61, 61, 61, 306, 63, 63, 63, 63,
62577 /* 850 */ 64, 64, 65, 65, 65, 66, 230, 72, 323, 452,
62578 /* 860 */ 4, 153, 22, 247, 293, 305, 435, 559, 316, 382,
62579 /* 870 */ 316, 453, 320, 72, 323, 316, 4, 366, 316, 180,
62580 /* 880 */ 293, 393, 394, 20, 454, 141, 326, 316, 320, 325,
62581 /* 890 */ 410, 53, 410, 52, 316, 411, 155, 410, 96, 447,
62582 /* 900 */ 410, 94, 316, 500, 316, 325, 328, 469, 247, 410,
62583 /* 910 */ 99, 444, 260, 411, 318, 447, 410, 100, 316, 74,
62584 /* 920 */ 73, 467, 183, 260, 410, 110, 410, 112, 72, 314,
62585 /* 930 */ 315, 435, 337, 415, 458, 74, 73, 479, 316, 377,
62586 /* 940 */ 410, 17, 218, 19, 72, 314, 315, 72, 323, 415,
62587 /* 950 */ 4, 205, 316, 274, 293, 316, 411, 466, 205, 409,
62588 /* 960 */ 410, 97, 320, 408, 374, 417, 417, 417, 418, 419,
62589 /* 970 */ 12, 376, 316, 206, 410, 34, 174, 410, 95, 325,
62590 /* 980 */ 55, 417, 417, 417, 418, 419, 12, 310, 120, 447,
62591 /* 990 */ 428, 159, 9, 260, 410, 25, 220, 221, 222, 102,
62592 /* 1000 */ 441, 441, 316, 471, 409, 316, 475, 316, 408, 74,
62593 /* 1010 */ 73, 436, 202, 23, 278, 455, 244, 13, 72, 314,
62594 /* 1020 */ 315, 279, 316, 415, 410, 54, 316, 410, 113, 410,
62595 /* 1030 */ 114, 291, 581, 200, 276, 547, 462, 497, 498, 199,
62596 /* 1040 */ 316, 504, 201, 463, 410, 26, 316, 524, 410, 37,
62597 /* 1050 */ 316, 474, 316, 170, 253, 417, 417, 417, 418, 419,
62598 /* 1060 */ 12, 505, 410, 38, 510, 483, 316, 13, 410, 27,
62599 /* 1070 */ 508, 582, 410, 39, 410, 40, 316, 255, 507, 506,
62600 /* 1080 */ 512, 316, 125, 316, 511, 373, 275, 265, 410, 42,
62601 /* 1090 */ 509, 290, 316, 251, 316, 125, 205, 257, 410, 43,
62602 /* 1100 */ 316, 259, 316, 410, 44, 410, 30, 348, 316, 125,
62603 /* 1110 */ 316, 353, 186, 316, 410, 31, 410, 45, 316, 543,
62604 /* 1120 */ 379, 125, 410, 46, 410, 47, 316, 551, 264, 170,
62605 /* 1130 */ 410, 48, 410, 32, 401, 410, 11, 552, 440, 89,
62606 /* 1140 */ 410, 50, 301, 562, 578, 89, 287, 361, 410, 51,
62607 /* 1150 */ 364, 365, 267, 268, 269, 554, 143, 564, 277, 324,
62608 /* 1160 */ 280, 281, 575, 225, 442, 461, 464, 503, 241, 513,
62609 /* 1170 */ 516, 550, 343, 160, 561, 390, 8, 313, 398, 399,
62610 /* 1180 */ 400, 412, 82, 226, 331, 329, 81, 406, 57, 78,
62611 /* 1190 */ 209, 167, 83, 459, 122, 414, 227, 334, 228, 338,
62612 /* 1200 */ 300, 500, 103, 496, 246, 519, 514, 490, 495, 242,
62613 /* 1210 */ 214, 518, 499, 229, 501, 413, 350, 533, 284, 525,
62614 /* 1220 */ 526, 527, 235, 181, 473, 237, 285, 477, 182, 354,
62615 /* 1230 */ 352, 184, 86, 185, 118, 535, 187, 546, 360, 190,
62616 /* 1240 */ 129, 553, 139, 371, 372, 130, 215, 309, 560, 131,
62617 /* 1250 */ 132, 133, 572, 577, 135, 573, 98, 574, 389, 262,
62618 /* 1260 */ 402, 621, 536, 213, 101, 622, 432, 163, 164, 429,
62619 /* 1270 */ 138, 71, 449, 437, 446, 140, 470, 154, 6, 450,
62620 /* 1280 */ 7, 158, 166, 451, 14, 123, 13, 124, 484, 212,
62621 /* 1290 */ 84, 342, 104, 105, 90, 250, 85, 117, 106, 347,
62622 /* 1300 */ 179, 240, 351, 142, 534, 126, 18, 170, 93, 263,
62623 /* 1310 */ 188, 107, 355, 286, 109, 127, 549, 541, 128, 119,
62624 /* 1320 */ 537, 192, 15, 194, 195, 136, 196, 134, 556, 563,
62625 /* 1330 */ 311, 137, 16, 108, 570, 203, 145, 385, 381, 282,
62626 /* 1340 */ 584, 899, 899, 899, 899, 899, 87, 899, 88,
62628 static const YYCODETYPE yy_lookahead[] = {
62629 /* 0 */ 16, 139, 140, 141, 168, 21, 144, 23, 69, 70,
62630 /* 10 */ 71, 72, 176, 74, 75, 76, 77, 78, 79, 80,
62631 /* 20 */ 81, 82, 83, 84, 1, 2, 42, 43, 73, 74,
62632 /* 30 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
62633 /* 40 */ 78, 79, 23, 58, 60, 61, 62, 63, 64, 65,
62634 /* 50 */ 66, 67, 68, 69, 70, 71, 72, 110, 74, 75,
62635 /* 60 */ 76, 77, 78, 79, 80, 81, 82, 83, 84, 16,
62636 /* 70 */ 123, 147, 88, 88, 110, 22, 216, 92, 218, 219,
62637 /* 80 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
62638 /* 90 */ 84, 147, 19, 169, 170, 42, 43, 78, 238, 46,
62639 /* 100 */ 78, 79, 80, 81, 82, 83, 84, 88, 89, 124,
62640 /* 110 */ 125, 126, 16, 60, 61, 62, 63, 64, 65, 66,
62641 /* 120 */ 67, 68, 69, 70, 71, 72, 182, 74, 75, 76,
62642 /* 130 */ 77, 78, 79, 80, 81, 82, 83, 84, 42, 43,
62643 /* 140 */ 44, 80, 81, 82, 83, 84, 23, 223, 161, 216,
62644 /* 150 */ 19, 218, 219, 21, 23, 23, 60, 61, 62, 63,
62645 /* 160 */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 225,
62646 /* 170 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
62647 /* 180 */ 84, 16, 147, 147, 150, 112, 21, 200, 147, 58,
62648 /* 190 */ 84, 147, 156, 157, 216, 217, 218, 219, 83, 84,
62649 /* 200 */ 165, 78, 79, 216, 190, 218, 219, 42, 43, 78,
62650 /* 210 */ 79, 88, 89, 169, 170, 141, 180, 181, 144, 88,
62651 /* 220 */ 88, 98, 147, 92, 16, 60, 61, 62, 63, 64,
62652 /* 230 */ 65, 66, 67, 68, 69, 70, 71, 72, 147, 74,
62653 /* 240 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
62654 /* 250 */ 42, 43, 169, 209, 210, 124, 125, 126, 224, 14,
62655 /* 260 */ 169, 170, 227, 228, 230, 18, 225, 16, 60, 61,
62656 /* 270 */ 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
62657 /* 280 */ 72, 23, 74, 75, 76, 77, 78, 79, 80, 81,
62658 /* 290 */ 82, 83, 84, 42, 43, 147, 16, 52, 147, 54,
62659 /* 300 */ 147, 210, 55, 106, 153, 108, 109, 156, 157, 156,
62660 /* 310 */ 157, 60, 61, 62, 63, 64, 65, 66, 67, 68,
62661 /* 320 */ 69, 70, 71, 72, 22, 74, 75, 76, 77, 78,
62662 /* 330 */ 79, 80, 81, 82, 83, 84, 188, 147, 92, 131,
62663 /* 340 */ 16, 94, 16, 22, 20, 155, 88, 89, 90, 103,
62664 /* 350 */ 147, 93, 94, 95, 167, 168, 161, 162, 163, 169,
62665 /* 360 */ 170, 25, 104, 176, 84, 29, 42, 43, 165, 166,
62666 /* 370 */ 90, 91, 92, 93, 94, 95, 96, 41, 133, 189,
62667 /* 380 */ 133, 169, 131, 103, 60, 61, 62, 63, 64, 65,
62668 /* 390 */ 66, 67, 68, 69, 70, 71, 72, 181, 74, 75,
62669 /* 400 */ 76, 77, 78, 79, 80, 81, 82, 83, 84, 16,
62670 /* 410 */ 84, 90, 22, 20, 93, 94, 95, 91, 92, 93,
62671 /* 420 */ 94, 95, 96, 121, 147, 104, 147, 185, 186, 103,
62672 /* 430 */ 227, 228, 155, 181, 160, 42, 43, 90, 176, 177,
62673 /* 440 */ 93, 94, 95, 169, 161, 183, 169, 170, 169, 170,
62674 /* 450 */ 155, 104, 155, 60, 61, 62, 63, 64, 65, 66,
62675 /* 460 */ 67, 68, 69, 70, 71, 72, 189, 74, 75, 76,
62676 /* 470 */ 77, 78, 79, 80, 81, 82, 83, 84, 16, 11,
62677 /* 480 */ 244, 245, 20, 200, 189, 147, 189, 147, 211, 158,
62678 /* 490 */ 211, 147, 161, 162, 163, 147, 201, 202, 42, 43,
62679 /* 500 */ 223, 206, 223, 113, 42, 43, 147, 169, 170, 169,
62680 /* 510 */ 170, 23, 19, 169, 170, 186, 23, 49, 155, 63,
62681 /* 520 */ 64, 147, 60, 61, 62, 63, 64, 65, 66, 67,
62682 /* 530 */ 68, 69, 70, 71, 72, 147, 74, 75, 76, 77,
62683 /* 540 */ 78, 79, 80, 81, 82, 83, 84, 16, 92, 211,
62684 /* 550 */ 12, 20, 189, 164, 165, 166, 208, 147, 16, 215,
62685 /* 560 */ 220, 223, 24, 164, 165, 166, 23, 99, 100, 101,
62686 /* 570 */ 155, 212, 23, 42, 43, 37, 88, 39, 110, 169,
62687 /* 580 */ 170, 88, 89, 19, 20, 43, 22, 49, 185, 186,
62688 /* 590 */ 23, 60, 61, 62, 63, 64, 65, 66, 67, 68,
62689 /* 600 */ 69, 70, 71, 72, 189, 74, 75, 76, 77, 78,
62690 /* 610 */ 79, 80, 81, 82, 83, 84, 16, 228, 0, 1,
62691 /* 620 */ 2, 21, 19, 59, 147, 215, 23, 228, 213, 80,
62692 /* 630 */ 147, 88, 89, 19, 20, 145, 22, 88, 89, 147,
62693 /* 640 */ 98, 147, 42, 43, 20, 103, 169, 170, 20, 147,
62694 /* 650 */ 147, 236, 169, 170, 20, 88, 89, 114, 147, 16,
62695 /* 660 */ 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
62696 /* 670 */ 70, 71, 72, 59, 74, 75, 76, 77, 78, 79,
62697 /* 680 */ 80, 81, 82, 83, 84, 42, 43, 147, 142, 143,
62698 /* 690 */ 188, 88, 89, 130, 148, 132, 7, 8, 9, 188,
62699 /* 700 */ 208, 155, 16, 60, 61, 62, 63, 64, 65, 66,
62700 /* 710 */ 67, 68, 69, 70, 71, 72, 147, 74, 75, 76,
62701 /* 720 */ 77, 78, 79, 80, 81, 82, 83, 84, 42, 43,
62702 /* 730 */ 106, 147, 108, 109, 106, 189, 108, 109, 169, 170,
62703 /* 740 */ 106, 147, 108, 109, 147, 16, 60, 61, 62, 63,
62704 /* 750 */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 213,
62705 /* 760 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
62706 /* 770 */ 84, 42, 43, 99, 100, 101, 182, 147, 161, 182,
62707 /* 780 */ 99, 100, 101, 14, 147, 147, 147, 241, 16, 191,
62708 /* 790 */ 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
62709 /* 800 */ 71, 72, 147, 74, 75, 76, 77, 78, 79, 80,
62710 /* 810 */ 81, 82, 83, 84, 42, 43, 23, 200, 188, 225,
62711 /* 820 */ 182, 52, 225, 54, 169, 170, 147, 188, 22, 22,
62712 /* 830 */ 147, 147, 201, 202, 62, 63, 64, 65, 66, 67,
62713 /* 840 */ 68, 69, 70, 71, 72, 208, 74, 75, 76, 77,
62714 /* 850 */ 78, 79, 80, 81, 82, 83, 84, 16, 17, 12,
62715 /* 860 */ 19, 155, 19, 225, 23, 182, 23, 188, 147, 239,
62716 /* 870 */ 147, 24, 31, 16, 17, 147, 19, 147, 147, 155,
62717 /* 880 */ 23, 88, 89, 19, 37, 21, 39, 147, 31, 48,
62718 /* 890 */ 169, 170, 169, 170, 147, 189, 89, 169, 170, 58,
62719 /* 900 */ 169, 170, 147, 97, 147, 48, 147, 114, 225, 169,
62720 /* 910 */ 170, 161, 147, 189, 16, 58, 169, 170, 147, 78,
62721 /* 920 */ 79, 114, 155, 147, 169, 170, 169, 170, 87, 88,
62722 /* 930 */ 89, 88, 80, 92, 147, 78, 79, 80, 147, 91,
62723 /* 940 */ 169, 170, 212, 19, 87, 88, 89, 16, 17, 92,
62724 /* 950 */ 19, 110, 147, 188, 23, 147, 189, 203, 110, 107,
62725 /* 960 */ 169, 170, 31, 111, 188, 124, 125, 126, 127, 128,
62726 /* 970 */ 129, 123, 147, 192, 169, 170, 43, 169, 170, 48,
62727 /* 980 */ 199, 124, 125, 126, 127, 128, 129, 242, 243, 58,
62728 /* 990 */ 92, 5, 68, 147, 169, 170, 10, 11, 12, 13,
62729 /* 1000 */ 124, 125, 147, 147, 107, 147, 147, 147, 111, 78,
62730 /* 1010 */ 79, 20, 26, 22, 28, 20, 147, 22, 87, 88,
62731 /* 1020 */ 89, 35, 147, 92, 169, 170, 147, 169, 170, 169,
62732 /* 1030 */ 170, 98, 20, 47, 188, 49, 27, 7, 8, 53,
62733 /* 1040 */ 147, 147, 56, 34, 169, 170, 147, 147, 169, 170,
62734 /* 1050 */ 147, 20, 147, 22, 147, 124, 125, 126, 127, 128,
62735 /* 1060 */ 129, 178, 169, 170, 178, 20, 147, 22, 169, 170,
62736 /* 1070 */ 30, 59, 169, 170, 169, 170, 147, 147, 91, 92,
62737 /* 1080 */ 20, 147, 22, 147, 178, 99, 100, 101, 169, 170,
62738 /* 1090 */ 50, 105, 147, 20, 147, 22, 110, 147, 169, 170,
62739 /* 1100 */ 147, 147, 147, 169, 170, 169, 170, 20, 147, 22,
62740 /* 1110 */ 147, 233, 232, 147, 169, 170, 169, 170, 147, 20,
62741 /* 1120 */ 134, 22, 169, 170, 169, 170, 147, 20, 147, 22,
62742 /* 1130 */ 169, 170, 169, 170, 149, 169, 170, 20, 229, 22,
62743 /* 1140 */ 169, 170, 102, 20, 20, 22, 22, 147, 169, 170,
62744 /* 1150 */ 147, 147, 147, 147, 147, 147, 191, 147, 147, 222,
62745 /* 1160 */ 147, 147, 147, 193, 229, 172, 172, 177, 172, 172,
62746 /* 1170 */ 172, 194, 173, 6, 194, 146, 22, 154, 146, 146,
62747 /* 1180 */ 146, 189, 121, 194, 118, 116, 119, 23, 120, 130,
62748 /* 1190 */ 221, 112, 98, 152, 152, 160, 195, 115, 196, 98,
62749 /* 1200 */ 40, 97, 19, 179, 84, 179, 160, 171, 171, 171,
62750 /* 1210 */ 226, 160, 173, 197, 171, 198, 15, 152, 174, 171,
62751 /* 1220 */ 171, 171, 204, 151, 205, 204, 174, 205, 151, 38,
62752 /* 1230 */ 152, 151, 130, 152, 60, 152, 151, 184, 152, 184,
62753 /* 1240 */ 19, 194, 214, 152, 15, 187, 226, 152, 194, 187,
62754 /* 1250 */ 187, 187, 33, 137, 184, 152, 159, 152, 1, 234,
62755 /* 1260 */ 20, 112, 235, 175, 175, 112, 107, 112, 112, 92,
62756 /* 1270 */ 214, 19, 11, 20, 20, 19, 114, 19, 117, 20,
62757 /* 1280 */ 117, 112, 22, 20, 22, 19, 22, 20, 20, 44,
62758 /* 1290 */ 19, 44, 19, 19, 237, 20, 19, 32, 19, 44,
62759 /* 1300 */ 96, 103, 16, 21, 17, 98, 231, 22, 237, 133,
62760 /* 1310 */ 98, 19, 36, 5, 240, 45, 1, 45, 102, 243,
62761 /* 1320 */ 51, 122, 19, 113, 14, 102, 115, 113, 17, 123,
62762 /* 1330 */ 246, 122, 19, 14, 20, 135, 19, 3, 57, 136,
62763 /* 1340 */ 4, 247, 247, 247, 247, 247, 68, 247, 68,
62765 #define YY_SHIFT_USE_DFLT (-62)
62766 #define YY_SHIFT_MAX 385
62767 static const short yy_shift_ofst[] = {
62768 /* 0 */ 23, 841, 986, -16, 841, 931, 931, 931, 258, 123,
62769 /* 10 */ -36, 96, 931, 931, 931, 931, 931, -45, 468, 19,
62770 /* 20 */ 567, 488, -38, -38, 53, 165, 208, 251, 324, 393,
62771 /* 30 */ 462, 531, 600, 643, 686, 643, 643, 643, 643, 643,
62772 /* 40 */ 643, 643, 643, 643, 643, 643, 643, 643, 643, 643,
62773 /* 50 */ 643, 643, 729, 772, 772, 857, 931, 931, 931, 931,
62774 /* 60 */ 931, 931, 931, 931, 931, 931, 931, 931, 931, 931,
62775 /* 70 */ 931, 931, 931, 931, 931, 931, 931, 931, 931, 931,
62776 /* 80 */ 931, 931, 931, 931, 931, 931, 931, 931, 931, 931,
62777 /* 90 */ 931, 931, 931, 931, -61, -61, 6, 6, 280, 22,
62778 /* 100 */ 61, 542, 247, 567, 567, 567, 567, 567, 567, 567,
62779 /* 110 */ 115, 488, 106, -62, -62, 131, 326, 538, 538, 564,
62780 /* 120 */ 614, 618, 132, 567, 132, 567, 567, 567, 567, 567,
62781 /* 130 */ 567, 567, 567, 567, 567, 567, 567, 567, 848, -53,
62782 /* 140 */ -36, -36, -36, -62, -62, -62, -15, -15, 321, 347,
62783 /* 150 */ 624, 493, 628, 634, 847, 543, 793, 603, 549, 689,
62784 /* 160 */ 567, 567, 852, 567, 567, 843, 567, 567, 807, 567,
62785 /* 170 */ 567, 197, 807, 567, 567, 1040, 1040, 1040, 567, 567,
62786 /* 180 */ 197, 567, 567, 197, 567, 336, 674, 567, 567, 197,
62787 /* 190 */ 567, 567, 567, 197, 567, 567, 567, 197, 197, 567,
62788 /* 200 */ 567, 567, 567, 567, 864, 897, 390, 876, 876, 563,
62789 /* 210 */ 1009, 1009, 1009, 933, 1009, 1009, 806, 302, 302, 1167,
62790 /* 220 */ 1167, 1167, 1167, 1154, -36, 1061, 1066, 1067, 1069, 1068,
62791 /* 230 */ 1164, 1059, 1079, 1079, 1094, 1082, 1094, 1082, 1101, 1101,
62792 /* 240 */ 1160, 1101, 1104, 1101, 1183, 1120, 1164, 1120, 1164, 1160,
62793 /* 250 */ 1101, 1101, 1101, 1183, 1201, 1079, 1201, 1079, 1201, 1079,
62794 /* 260 */ 1079, 1191, 1102, 1201, 1079, 1174, 1174, 1221, 1061, 1079,
62795 /* 270 */ 1229, 1229, 1229, 1229, 1061, 1174, 1221, 1079, 1219, 1219,
62796 /* 280 */ 1079, 1079, 1116, -62, -62, -62, -62, -62, -62, 456,
62797 /* 290 */ 245, 681, 769, 73, 898, 991, 995, 1031, 1045, 246,
62798 /* 300 */ 1030, 987, 1060, 1073, 1087, 1099, 1107, 1117, 1123, 924,
62799 /* 310 */ 1124, 1012, 1257, 1240, 1149, 1153, 1155, 1156, 1177, 1159,
62800 /* 320 */ 1252, 1253, 1254, 1256, 1261, 1258, 1259, 1260, 1263, 1161,
62801 /* 330 */ 1262, 1163, 1264, 1162, 1266, 1267, 1169, 1268, 1265, 1245,
62802 /* 340 */ 1271, 1247, 1273, 1275, 1274, 1277, 1255, 1279, 1204, 1198,
62803 /* 350 */ 1286, 1287, 1282, 1207, 1276, 1269, 1270, 1285, 1272, 1176,
62804 /* 360 */ 1212, 1292, 1308, 1315, 1216, 1278, 1280, 1199, 1303, 1210,
62805 /* 370 */ 1310, 1211, 1311, 1214, 1223, 1209, 1313, 1206, 1314, 1319,
62806 /* 380 */ 1281, 1200, 1203, 1317, 1334, 1336,
62808 #define YY_REDUCE_USE_DFLT (-165)
62809 #define YY_REDUCE_MAX 288
62810 static const short yy_reduce_ofst[] = {
62811 /* 0 */ -138, 277, 546, -13, 190, 279, 44, 338, 36, 203,
62812 /* 10 */ 295, -140, 340, -76, 91, 344, 410, -22, 415, 35,
62813 /* 20 */ 151, 331, 389, 399, -67, -67, -67, -67, -67, -67,
62814 /* 30 */ -67, -67, -67, -67, -67, -67, -67, -67, -67, -67,
62815 /* 40 */ -67, -67, -67, -67, -67, -67, -67, -67, -67, -67,
62816 /* 50 */ -67, -67, -67, -67, -67, 477, 483, 569, 655, 721,
62817 /* 60 */ 723, 728, 731, 740, 747, 755, 757, 771, 791, 805,
62818 /* 70 */ 808, 825, 855, 858, 860, 875, 879, 893, 899, 903,
62819 /* 80 */ 905, 919, 929, 934, 936, 945, 947, 953, 955, 961,
62820 /* 90 */ 963, 966, 971, 979, -67, -67, -67, -67, 187, -67,
62821 /* 100 */ -67, 262, 34, -56, 594, 597, 638, 683, 630, 153,
62822 /* 110 */ -67, 195, -67, -67, -67, 274, -164, 242, 403, 236,
62823 /* 120 */ 236, 74, 283, 348, 617, 41, 148, 492, 359, 637,
62824 /* 130 */ 502, 511, 639, 679, 765, 776, 730, 846, 297, 363,
62825 /* 140 */ 706, 724, 767, 781, 631, 745, 83, 212, 216, 252,
62826 /* 150 */ 14, 75, 14, 14, 329, 374, 388, 494, 503, 490,
62827 /* 160 */ 540, 584, 598, 503, 684, 750, 759, 787, 754, 856,
62828 /* 170 */ 859, 14, 754, 869, 894, 883, 886, 906, 900, 907,
62829 /* 180 */ 14, 930, 950, 14, 954, 880, 878, 981, 1000, 14,
62830 /* 190 */ 1003, 1004, 1005, 14, 1006, 1007, 1008, 14, 14, 1010,
62831 /* 200 */ 1011, 1013, 1014, 1015, 985, 965, 970, 909, 935, 937,
62832 /* 210 */ 993, 994, 996, 990, 997, 998, 999, 977, 980, 1029,
62833 /* 220 */ 1032, 1033, 1034, 1023, 992, 989, 1001, 1002, 1016, 1017,
62834 /* 230 */ 1035, 969, 1041, 1042, 1018, 1019, 1021, 1022, 1036, 1037,
62835 /* 240 */ 1024, 1038, 1039, 1043, 1044, 984, 1046, 1020, 1051, 1026,
62836 /* 250 */ 1048, 1049, 1050, 1052, 1072, 1065, 1077, 1078, 1080, 1081,
62837 /* 260 */ 1083, 1025, 1027, 1085, 1086, 1053, 1055, 1028, 1047, 1091,
62838 /* 270 */ 1058, 1062, 1063, 1064, 1054, 1070, 1056, 1095, 1057, 1071,
62839 /* 280 */ 1103, 1105, 1074, 1097, 1088, 1089, 1075, 1076, 1084,
62841 static const YYACTIONTYPE yy_default[] = {
62842 /* 0 */ 592, 818, 897, 707, 897, 818, 897, 818, 897, 843,
62843 /* 10 */ 711, 872, 814, 818, 897, 897, 897, 789, 897, 843,
62844 /* 20 */ 897, 623, 843, 843, 740, 897, 897, 897, 897, 897,
62845 /* 30 */ 897, 897, 897, 741, 897, 817, 813, 809, 811, 810,
62846 /* 40 */ 742, 731, 738, 745, 723, 856, 747, 748, 754, 755,
62847 /* 50 */ 873, 871, 777, 776, 795, 897, 897, 897, 897, 897,
62848 /* 60 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
62849 /* 70 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
62850 /* 80 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
62851 /* 90 */ 897, 897, 897, 897, 779, 800, 778, 788, 616, 780,
62852 /* 100 */ 781, 676, 611, 897, 897, 897, 897, 897, 897, 897,
62853 /* 110 */ 782, 897, 783, 796, 797, 897, 897, 897, 897, 897,
62854 /* 120 */ 897, 592, 707, 897, 707, 897, 897, 897, 897, 897,
62855 /* 130 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
62856 /* 140 */ 897, 897, 897, 701, 711, 890, 897, 897, 667, 897,
62857 /* 150 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 599,
62858 /* 160 */ 597, 897, 699, 897, 897, 625, 897, 897, 709, 897,
62859 /* 170 */ 897, 714, 715, 897, 897, 897, 897, 897, 897, 897,
62860 /* 180 */ 613, 897, 897, 688, 897, 849, 897, 897, 897, 863,
62861 /* 190 */ 897, 897, 897, 861, 897, 897, 897, 690, 750, 830,
62862 /* 200 */ 897, 876, 878, 897, 897, 699, 708, 897, 897, 812,
62863 /* 210 */ 734, 734, 734, 646, 734, 734, 649, 744, 744, 596,
62864 /* 220 */ 596, 596, 596, 666, 897, 744, 735, 737, 727, 739,
62865 /* 230 */ 897, 897, 716, 716, 724, 726, 724, 726, 678, 678,
62866 /* 240 */ 663, 678, 649, 678, 822, 827, 897, 827, 897, 663,
62867 /* 250 */ 678, 678, 678, 822, 608, 716, 608, 716, 608, 716,
62868 /* 260 */ 716, 853, 855, 608, 716, 680, 680, 756, 744, 716,
62869 /* 270 */ 687, 687, 687, 687, 744, 680, 756, 716, 875, 875,
62870 /* 280 */ 716, 716, 883, 633, 651, 651, 858, 890, 895, 897,
62871 /* 290 */ 897, 897, 897, 763, 897, 897, 897, 897, 897, 897,
62872 /* 300 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 836,
62873 /* 310 */ 897, 897, 897, 897, 768, 764, 897, 765, 897, 693,
62874 /* 320 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
62875 /* 330 */ 728, 897, 736, 897, 897, 897, 897, 897, 897, 897,
62876 /* 340 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
62877 /* 350 */ 897, 897, 897, 897, 897, 897, 851, 852, 897, 897,
62878 /* 360 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
62879 /* 370 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
62880 /* 380 */ 882, 897, 897, 885, 593, 897, 587, 590, 589, 591,
62881 /* 390 */ 595, 598, 620, 621, 622, 600, 601, 602, 603, 604,
62882 /* 400 */ 605, 606, 612, 614, 632, 634, 618, 636, 697, 698,
62883 /* 410 */ 760, 691, 692, 696, 771, 762, 766, 767, 769, 770,
62884 /* 420 */ 784, 785, 787, 793, 799, 802, 786, 791, 792, 794,
62885 /* 430 */ 798, 801, 694, 695, 805, 619, 626, 627, 630, 631,
62886 /* 440 */ 839, 841, 840, 842, 629, 628, 772, 775, 807, 808,
62887 /* 450 */ 864, 865, 866, 867, 868, 803, 815, 816, 717, 806,
62888 /* 460 */ 790, 729, 732, 733, 730, 700, 710, 719, 720, 721,
62889 /* 470 */ 722, 705, 706, 712, 725, 758, 759, 713, 702, 703,
62890 /* 480 */ 704, 804, 761, 773, 774, 637, 638, 768, 639, 640,
62891 /* 490 */ 641, 679, 682, 683, 684, 642, 661, 664, 665, 643,
62892 /* 500 */ 650, 644, 645, 652, 653, 654, 657, 658, 659, 660,
62893 /* 510 */ 655, 656, 823, 824, 828, 826, 825, 647, 648, 662,
62894 /* 520 */ 635, 624, 617, 668, 671, 672, 673, 674, 675, 677,
62895 /* 530 */ 669, 670, 615, 607, 609, 718, 845, 854, 850, 846,
62896 /* 540 */ 847, 848, 610, 819, 820, 681, 752, 753, 844, 857,
62897 /* 550 */ 859, 757, 860, 862, 887, 685, 686, 689, 829, 869,
62898 /* 560 */ 743, 746, 749, 751, 831, 832, 833, 834, 837, 838,
62899 /* 570 */ 835, 870, 874, 877, 879, 880, 881, 884, 886, 891,
62900 /* 580 */ 892, 893, 896, 894, 594, 588,
62902 #define YY_SZ_ACTTAB (int)(sizeof(yy_action)/sizeof(yy_action[0]))
62904 /* The next table maps tokens into fallback tokens. If a construct
62905 ** like the following:
62907 ** %fallback ID X Y Z.
62909 ** appears in the grammer, then ID becomes a fallback token for X, Y,
62910 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
62911 ** but it does not parse, the type of the token is changed to ID and
62912 ** the parse is retried before an error is thrown.
62914 #ifdef YYFALLBACK
62915 static const YYCODETYPE yyFallback[] = {
62916 0, /* $ => nothing */
62917 0, /* SEMI => nothing */
62918 23, /* EXPLAIN => ID */
62919 23, /* QUERY => ID */
62920 23, /* PLAN => ID */
62921 23, /* BEGIN => ID */
62922 0, /* TRANSACTION => nothing */
62923 23, /* DEFERRED => ID */
62924 23, /* IMMEDIATE => ID */
62925 23, /* EXCLUSIVE => ID */
62926 0, /* COMMIT => nothing */
62927 23, /* END => ID */
62928 0, /* ROLLBACK => nothing */
62929 0, /* CREATE => nothing */
62930 0, /* TABLE => nothing */
62931 23, /* IF => ID */
62932 0, /* NOT => nothing */
62933 0, /* EXISTS => nothing */
62934 23, /* TEMP => ID */
62935 0, /* LP => nothing */
62936 0, /* RP => nothing */
62937 0, /* AS => nothing */
62938 0, /* COMMA => nothing */
62939 0, /* ID => nothing */
62940 23, /* ABORT => ID */
62941 23, /* AFTER => ID */
62942 23, /* ANALYZE => ID */
62943 23, /* ASC => ID */
62944 23, /* ATTACH => ID */
62945 23, /* BEFORE => ID */
62946 23, /* CASCADE => ID */
62947 23, /* CAST => ID */
62948 23, /* CONFLICT => ID */
62949 23, /* DATABASE => ID */
62950 23, /* DESC => ID */
62951 23, /* DETACH => ID */
62952 23, /* EACH => ID */
62953 23, /* FAIL => ID */
62954 23, /* FOR => ID */
62955 23, /* IGNORE => ID */
62956 23, /* INITIALLY => ID */
62957 23, /* INSTEAD => ID */
62958 23, /* LIKE_KW => ID */
62959 23, /* MATCH => ID */
62960 23, /* KEY => ID */
62961 23, /* OF => ID */
62962 23, /* OFFSET => ID */
62963 23, /* PRAGMA => ID */
62964 23, /* RAISE => ID */
62965 23, /* REPLACE => ID */
62966 23, /* RESTRICT => ID */
62967 23, /* ROW => ID */
62968 23, /* TRIGGER => ID */
62969 23, /* VACUUM => ID */
62970 23, /* VIEW => ID */
62971 23, /* VIRTUAL => ID */
62972 23, /* REINDEX => ID */
62973 23, /* RENAME => ID */
62974 23, /* CTIME_KW => ID */
62975 0, /* ANY => nothing */
62976 0, /* OR => nothing */
62977 0, /* AND => nothing */
62978 0, /* IS => nothing */
62979 0, /* BETWEEN => nothing */
62980 0, /* IN => nothing */
62981 0, /* ISNULL => nothing */
62982 0, /* NOTNULL => nothing */
62983 0, /* NE => nothing */
62984 0, /* EQ => nothing */
62985 0, /* GT => nothing */
62986 0, /* LE => nothing */
62987 0, /* LT => nothing */
62988 0, /* GE => nothing */
62989 0, /* ESCAPE => nothing */
62990 0, /* BITAND => nothing */
62991 0, /* BITOR => nothing */
62992 0, /* LSHIFT => nothing */
62993 0, /* RSHIFT => nothing */
62994 0, /* PLUS => nothing */
62995 0, /* MINUS => nothing */
62996 0, /* STAR => nothing */
62997 0, /* SLASH => nothing */
62998 0, /* REM => nothing */
62999 0, /* CONCAT => nothing */
63000 0, /* COLLATE => nothing */
63001 0, /* UMINUS => nothing */
63002 0, /* UPLUS => nothing */
63003 0, /* BITNOT => nothing */
63004 0, /* STRING => nothing */
63005 0, /* JOIN_KW => nothing */
63006 0, /* CONSTRAINT => nothing */
63007 0, /* DEFAULT => nothing */
63008 0, /* NULL => nothing */
63009 0, /* PRIMARY => nothing */
63010 0, /* UNIQUE => nothing */
63011 0, /* CHECK => nothing */
63012 0, /* REFERENCES => nothing */
63013 0, /* AUTOINCR => nothing */
63014 0, /* ON => nothing */
63015 0, /* DELETE => nothing */
63016 0, /* UPDATE => nothing */
63017 0, /* INSERT => nothing */
63018 0, /* SET => nothing */
63019 0, /* DEFERRABLE => nothing */
63020 0, /* FOREIGN => nothing */
63021 0, /* DROP => nothing */
63022 0, /* UNION => nothing */
63023 0, /* ALL => nothing */
63024 0, /* EXCEPT => nothing */
63025 0, /* INTERSECT => nothing */
63026 0, /* SELECT => nothing */
63027 0, /* DISTINCT => nothing */
63028 0, /* DOT => nothing */
63029 0, /* FROM => nothing */
63030 0, /* JOIN => nothing */
63031 0, /* USING => nothing */
63032 0, /* ORDER => nothing */
63033 0, /* BY => nothing */
63034 0, /* GROUP => nothing */
63035 0, /* HAVING => nothing */
63036 0, /* LIMIT => nothing */
63037 0, /* WHERE => nothing */
63038 0, /* INTO => nothing */
63039 0, /* VALUES => nothing */
63040 0, /* INTEGER => nothing */
63041 0, /* FLOAT => nothing */
63042 0, /* BLOB => nothing */
63043 0, /* REGISTER => nothing */
63044 0, /* VARIABLE => nothing */
63045 0, /* CASE => nothing */
63046 0, /* WHEN => nothing */
63047 0, /* THEN => nothing */
63048 0, /* ELSE => nothing */
63049 0, /* INDEX => nothing */
63050 0, /* ALTER => nothing */
63051 0, /* TO => nothing */
63052 0, /* ADD => nothing */
63053 0, /* COLUMNKW => nothing */
63055 #endif /* YYFALLBACK */
63057 /* The following structure represents a single element of the
63058 ** parser's stack. Information stored includes:
63060 ** + The state number for the parser at this level of the stack.
63062 ** + The value of the token stored at this level of the stack.
63063 ** (In other words, the "major" token.)
63065 ** + The semantic value stored at this level of the stack. This is
63066 ** the information used by the action routines in the grammar.
63067 ** It is sometimes called the "minor" token.
63069 struct yyStackEntry {
63070 int stateno; /* The state-number */
63071 int major; /* The major token value. This is the code
63072 ** number for the token at this stack level */
63073 YYMINORTYPE minor; /* The user-supplied minor token value. This
63074 ** is the value of the token */
63076 typedef struct yyStackEntry yyStackEntry;
63078 /* The state of the parser is completely contained in an instance of
63079 ** the following structure */
63080 struct yyParser {
63081 int yyidx; /* Index of top element in stack */
63082 int yyerrcnt; /* Shifts left before out of the error */
63083 sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
63084 #if YYSTACKDEPTH<=0
63085 int yystksz; /* Current side of the stack */
63086 yyStackEntry *yystack; /* The parser's stack */
63087 #else
63088 yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
63089 #endif
63091 typedef struct yyParser yyParser;
63093 #ifndef NDEBUG
63094 static FILE *yyTraceFILE = 0;
63095 static char *yyTracePrompt = 0;
63096 #endif /* NDEBUG */
63098 #ifndef NDEBUG
63100 ** Turn parser tracing on by giving a stream to which to write the trace
63101 ** and a prompt to preface each trace message. Tracing is turned off
63102 ** by making either argument NULL
63104 ** Inputs:
63105 ** <ul>
63106 ** <li> A FILE* to which trace output should be written.
63107 ** If NULL, then tracing is turned off.
63108 ** <li> A prefix string written at the beginning of every
63109 ** line of trace output. If NULL, then tracing is
63110 ** turned off.
63111 ** </ul>
63113 ** Outputs:
63114 ** None.
63116 static void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
63117 yyTraceFILE = TraceFILE;
63118 yyTracePrompt = zTracePrompt;
63119 if( yyTraceFILE==0 ) yyTracePrompt = 0;
63120 else if( yyTracePrompt==0 ) yyTraceFILE = 0;
63122 #endif /* NDEBUG */
63124 #ifndef NDEBUG
63125 /* For tracing shifts, the names of all terminals and nonterminals
63126 ** are required. The following table supplies these names */
63127 static const char *const yyTokenName[] = {
63128 "$", "SEMI", "EXPLAIN", "QUERY",
63129 "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
63130 "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
63131 "ROLLBACK", "CREATE", "TABLE", "IF",
63132 "NOT", "EXISTS", "TEMP", "LP",
63133 "RP", "AS", "COMMA", "ID",
63134 "ABORT", "AFTER", "ANALYZE", "ASC",
63135 "ATTACH", "BEFORE", "CASCADE", "CAST",
63136 "CONFLICT", "DATABASE", "DESC", "DETACH",
63137 "EACH", "FAIL", "FOR", "IGNORE",
63138 "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
63139 "KEY", "OF", "OFFSET", "PRAGMA",
63140 "RAISE", "REPLACE", "RESTRICT", "ROW",
63141 "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
63142 "REINDEX", "RENAME", "CTIME_KW", "ANY",
63143 "OR", "AND", "IS", "BETWEEN",
63144 "IN", "ISNULL", "NOTNULL", "NE",
63145 "EQ", "GT", "LE", "LT",
63146 "GE", "ESCAPE", "BITAND", "BITOR",
63147 "LSHIFT", "RSHIFT", "PLUS", "MINUS",
63148 "STAR", "SLASH", "REM", "CONCAT",
63149 "COLLATE", "UMINUS", "UPLUS", "BITNOT",
63150 "STRING", "JOIN_KW", "CONSTRAINT", "DEFAULT",
63151 "NULL", "PRIMARY", "UNIQUE", "CHECK",
63152 "REFERENCES", "AUTOINCR", "ON", "DELETE",
63153 "UPDATE", "INSERT", "SET", "DEFERRABLE",
63154 "FOREIGN", "DROP", "UNION", "ALL",
63155 "EXCEPT", "INTERSECT", "SELECT", "DISTINCT",
63156 "DOT", "FROM", "JOIN", "USING",
63157 "ORDER", "BY", "GROUP", "HAVING",
63158 "LIMIT", "WHERE", "INTO", "VALUES",
63159 "INTEGER", "FLOAT", "BLOB", "REGISTER",
63160 "VARIABLE", "CASE", "WHEN", "THEN",
63161 "ELSE", "INDEX", "ALTER", "TO",
63162 "ADD", "COLUMNKW", "error", "input",
63163 "cmdlist", "ecmd", "cmdx", "cmd",
63164 "explain", "transtype", "trans_opt", "nm",
63165 "create_table", "create_table_args", "temp", "ifnotexists",
63166 "dbnm", "columnlist", "conslist_opt", "select",
63167 "column", "columnid", "type", "carglist",
63168 "id", "ids", "typetoken", "typename",
63169 "signed", "plus_num", "minus_num", "carg",
63170 "ccons", "term", "expr", "onconf",
63171 "sortorder", "autoinc", "idxlist_opt", "refargs",
63172 "defer_subclause", "refarg", "refact", "init_deferred_pred_opt",
63173 "conslist", "tcons", "idxlist", "defer_subclause_opt",
63174 "orconf", "resolvetype", "raisetype", "ifexists",
63175 "fullname", "oneselect", "multiselect_op", "distinct",
63176 "selcollist", "from", "where_opt", "groupby_opt",
63177 "having_opt", "orderby_opt", "limit_opt", "sclp",
63178 "as", "seltablist", "stl_prefix", "joinop",
63179 "on_opt", "using_opt", "seltablist_paren", "joinop2",
63180 "inscollist", "sortlist", "sortitem", "exprlist",
63181 "setlist", "insert_cmd", "inscollist_opt", "itemlist",
63182 "likeop", "escape", "between_op", "in_op",
63183 "case_operand", "case_exprlist", "case_else", "expritem",
63184 "uniqueflag", "idxitem", "collate", "nmnum",
63185 "plus_opt", "number", "trigger_decl", "trigger_cmd_list",
63186 "trigger_time", "trigger_event", "foreach_clause", "when_clause",
63187 "trigger_cmd", "database_kw_opt", "key_opt", "add_column_fullname",
63188 "kwcolumn_opt", "create_vtab", "vtabarglist", "vtabarg",
63189 "vtabargtoken", "lp", "anylist",
63191 #endif /* NDEBUG */
63193 #ifndef NDEBUG
63194 /* For tracing reduce actions, the names of all rules are required.
63196 static const char *const yyRuleName[] = {
63197 /* 0 */ "input ::= cmdlist",
63198 /* 1 */ "cmdlist ::= cmdlist ecmd",
63199 /* 2 */ "cmdlist ::= ecmd",
63200 /* 3 */ "cmdx ::= cmd",
63201 /* 4 */ "ecmd ::= SEMI",
63202 /* 5 */ "ecmd ::= explain cmdx SEMI",
63203 /* 6 */ "explain ::=",
63204 /* 7 */ "explain ::= EXPLAIN",
63205 /* 8 */ "explain ::= EXPLAIN QUERY PLAN",
63206 /* 9 */ "cmd ::= BEGIN transtype trans_opt",
63207 /* 10 */ "trans_opt ::=",
63208 /* 11 */ "trans_opt ::= TRANSACTION",
63209 /* 12 */ "trans_opt ::= TRANSACTION nm",
63210 /* 13 */ "transtype ::=",
63211 /* 14 */ "transtype ::= DEFERRED",
63212 /* 15 */ "transtype ::= IMMEDIATE",
63213 /* 16 */ "transtype ::= EXCLUSIVE",
63214 /* 17 */ "cmd ::= COMMIT trans_opt",
63215 /* 18 */ "cmd ::= END trans_opt",
63216 /* 19 */ "cmd ::= ROLLBACK trans_opt",
63217 /* 20 */ "cmd ::= create_table create_table_args",
63218 /* 21 */ "create_table ::= CREATE temp TABLE ifnotexists nm dbnm",
63219 /* 22 */ "ifnotexists ::=",
63220 /* 23 */ "ifnotexists ::= IF NOT EXISTS",
63221 /* 24 */ "temp ::= TEMP",
63222 /* 25 */ "temp ::=",
63223 /* 26 */ "create_table_args ::= LP columnlist conslist_opt RP",
63224 /* 27 */ "create_table_args ::= AS select",
63225 /* 28 */ "columnlist ::= columnlist COMMA column",
63226 /* 29 */ "columnlist ::= column",
63227 /* 30 */ "column ::= columnid type carglist",
63228 /* 31 */ "columnid ::= nm",
63229 /* 32 */ "id ::= ID",
63230 /* 33 */ "ids ::= ID|STRING",
63231 /* 34 */ "nm ::= ID",
63232 /* 35 */ "nm ::= STRING",
63233 /* 36 */ "nm ::= JOIN_KW",
63234 /* 37 */ "type ::=",
63235 /* 38 */ "type ::= typetoken",
63236 /* 39 */ "typetoken ::= typename",
63237 /* 40 */ "typetoken ::= typename LP signed RP",
63238 /* 41 */ "typetoken ::= typename LP signed COMMA signed RP",
63239 /* 42 */ "typename ::= ids",
63240 /* 43 */ "typename ::= typename ids",
63241 /* 44 */ "signed ::= plus_num",
63242 /* 45 */ "signed ::= minus_num",
63243 /* 46 */ "carglist ::= carglist carg",
63244 /* 47 */ "carglist ::=",
63245 /* 48 */ "carg ::= CONSTRAINT nm ccons",
63246 /* 49 */ "carg ::= ccons",
63247 /* 50 */ "ccons ::= DEFAULT term",
63248 /* 51 */ "ccons ::= DEFAULT LP expr RP",
63249 /* 52 */ "ccons ::= DEFAULT PLUS term",
63250 /* 53 */ "ccons ::= DEFAULT MINUS term",
63251 /* 54 */ "ccons ::= DEFAULT id",
63252 /* 55 */ "ccons ::= NULL onconf",
63253 /* 56 */ "ccons ::= NOT NULL onconf",
63254 /* 57 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
63255 /* 58 */ "ccons ::= UNIQUE onconf",
63256 /* 59 */ "ccons ::= CHECK LP expr RP",
63257 /* 60 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
63258 /* 61 */ "ccons ::= defer_subclause",
63259 /* 62 */ "ccons ::= COLLATE id",
63260 /* 63 */ "autoinc ::=",
63261 /* 64 */ "autoinc ::= AUTOINCR",
63262 /* 65 */ "refargs ::=",
63263 /* 66 */ "refargs ::= refargs refarg",
63264 /* 67 */ "refarg ::= MATCH nm",
63265 /* 68 */ "refarg ::= ON DELETE refact",
63266 /* 69 */ "refarg ::= ON UPDATE refact",
63267 /* 70 */ "refarg ::= ON INSERT refact",
63268 /* 71 */ "refact ::= SET NULL",
63269 /* 72 */ "refact ::= SET DEFAULT",
63270 /* 73 */ "refact ::= CASCADE",
63271 /* 74 */ "refact ::= RESTRICT",
63272 /* 75 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
63273 /* 76 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
63274 /* 77 */ "init_deferred_pred_opt ::=",
63275 /* 78 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
63276 /* 79 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
63277 /* 80 */ "conslist_opt ::=",
63278 /* 81 */ "conslist_opt ::= COMMA conslist",
63279 /* 82 */ "conslist ::= conslist COMMA tcons",
63280 /* 83 */ "conslist ::= conslist tcons",
63281 /* 84 */ "conslist ::= tcons",
63282 /* 85 */ "tcons ::= CONSTRAINT nm",
63283 /* 86 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
63284 /* 87 */ "tcons ::= UNIQUE LP idxlist RP onconf",
63285 /* 88 */ "tcons ::= CHECK LP expr RP onconf",
63286 /* 89 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
63287 /* 90 */ "defer_subclause_opt ::=",
63288 /* 91 */ "defer_subclause_opt ::= defer_subclause",
63289 /* 92 */ "onconf ::=",
63290 /* 93 */ "onconf ::= ON CONFLICT resolvetype",
63291 /* 94 */ "orconf ::=",
63292 /* 95 */ "orconf ::= OR resolvetype",
63293 /* 96 */ "resolvetype ::= raisetype",
63294 /* 97 */ "resolvetype ::= IGNORE",
63295 /* 98 */ "resolvetype ::= REPLACE",
63296 /* 99 */ "cmd ::= DROP TABLE ifexists fullname",
63297 /* 100 */ "ifexists ::= IF EXISTS",
63298 /* 101 */ "ifexists ::=",
63299 /* 102 */ "cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select",
63300 /* 103 */ "cmd ::= DROP VIEW ifexists fullname",
63301 /* 104 */ "cmd ::= select",
63302 /* 105 */ "select ::= oneselect",
63303 /* 106 */ "select ::= select multiselect_op oneselect",
63304 /* 107 */ "multiselect_op ::= UNION",
63305 /* 108 */ "multiselect_op ::= UNION ALL",
63306 /* 109 */ "multiselect_op ::= EXCEPT|INTERSECT",
63307 /* 110 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
63308 /* 111 */ "distinct ::= DISTINCT",
63309 /* 112 */ "distinct ::= ALL",
63310 /* 113 */ "distinct ::=",
63311 /* 114 */ "sclp ::= selcollist COMMA",
63312 /* 115 */ "sclp ::=",
63313 /* 116 */ "selcollist ::= sclp expr as",
63314 /* 117 */ "selcollist ::= sclp STAR",
63315 /* 118 */ "selcollist ::= sclp nm DOT STAR",
63316 /* 119 */ "as ::= AS nm",
63317 /* 120 */ "as ::= ids",
63318 /* 121 */ "as ::=",
63319 /* 122 */ "from ::=",
63320 /* 123 */ "from ::= FROM seltablist",
63321 /* 124 */ "stl_prefix ::= seltablist joinop",
63322 /* 125 */ "stl_prefix ::=",
63323 /* 126 */ "seltablist ::= stl_prefix nm dbnm as on_opt using_opt",
63324 /* 127 */ "seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt",
63325 /* 128 */ "seltablist_paren ::= select",
63326 /* 129 */ "seltablist_paren ::= seltablist",
63327 /* 130 */ "dbnm ::=",
63328 /* 131 */ "dbnm ::= DOT nm",
63329 /* 132 */ "fullname ::= nm dbnm",
63330 /* 133 */ "joinop ::= COMMA|JOIN",
63331 /* 134 */ "joinop ::= JOIN_KW JOIN",
63332 /* 135 */ "joinop ::= JOIN_KW nm JOIN",
63333 /* 136 */ "joinop ::= JOIN_KW nm nm JOIN",
63334 /* 137 */ "on_opt ::= ON expr",
63335 /* 138 */ "on_opt ::=",
63336 /* 139 */ "using_opt ::= USING LP inscollist RP",
63337 /* 140 */ "using_opt ::=",
63338 /* 141 */ "orderby_opt ::=",
63339 /* 142 */ "orderby_opt ::= ORDER BY sortlist",
63340 /* 143 */ "sortlist ::= sortlist COMMA sortitem sortorder",
63341 /* 144 */ "sortlist ::= sortitem sortorder",
63342 /* 145 */ "sortitem ::= expr",
63343 /* 146 */ "sortorder ::= ASC",
63344 /* 147 */ "sortorder ::= DESC",
63345 /* 148 */ "sortorder ::=",
63346 /* 149 */ "groupby_opt ::=",
63347 /* 150 */ "groupby_opt ::= GROUP BY exprlist",
63348 /* 151 */ "having_opt ::=",
63349 /* 152 */ "having_opt ::= HAVING expr",
63350 /* 153 */ "limit_opt ::=",
63351 /* 154 */ "limit_opt ::= LIMIT expr",
63352 /* 155 */ "limit_opt ::= LIMIT expr OFFSET expr",
63353 /* 156 */ "limit_opt ::= LIMIT expr COMMA expr",
63354 /* 157 */ "cmd ::= DELETE FROM fullname where_opt",
63355 /* 158 */ "where_opt ::=",
63356 /* 159 */ "where_opt ::= WHERE expr",
63357 /* 160 */ "cmd ::= UPDATE orconf fullname SET setlist where_opt",
63358 /* 161 */ "setlist ::= setlist COMMA nm EQ expr",
63359 /* 162 */ "setlist ::= nm EQ expr",
63360 /* 163 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
63361 /* 164 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
63362 /* 165 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
63363 /* 166 */ "insert_cmd ::= INSERT orconf",
63364 /* 167 */ "insert_cmd ::= REPLACE",
63365 /* 168 */ "itemlist ::= itemlist COMMA expr",
63366 /* 169 */ "itemlist ::= expr",
63367 /* 170 */ "inscollist_opt ::=",
63368 /* 171 */ "inscollist_opt ::= LP inscollist RP",
63369 /* 172 */ "inscollist ::= inscollist COMMA nm",
63370 /* 173 */ "inscollist ::= nm",
63371 /* 174 */ "expr ::= term",
63372 /* 175 */ "expr ::= LP expr RP",
63373 /* 176 */ "term ::= NULL",
63374 /* 177 */ "expr ::= ID",
63375 /* 178 */ "expr ::= JOIN_KW",
63376 /* 179 */ "expr ::= nm DOT nm",
63377 /* 180 */ "expr ::= nm DOT nm DOT nm",
63378 /* 181 */ "term ::= INTEGER|FLOAT|BLOB",
63379 /* 182 */ "term ::= STRING",
63380 /* 183 */ "expr ::= REGISTER",
63381 /* 184 */ "expr ::= VARIABLE",
63382 /* 185 */ "expr ::= expr COLLATE id",
63383 /* 186 */ "expr ::= CAST LP expr AS typetoken RP",
63384 /* 187 */ "expr ::= ID LP distinct exprlist RP",
63385 /* 188 */ "expr ::= ID LP STAR RP",
63386 /* 189 */ "term ::= CTIME_KW",
63387 /* 190 */ "expr ::= expr AND expr",
63388 /* 191 */ "expr ::= expr OR expr",
63389 /* 192 */ "expr ::= expr LT|GT|GE|LE expr",
63390 /* 193 */ "expr ::= expr EQ|NE expr",
63391 /* 194 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
63392 /* 195 */ "expr ::= expr PLUS|MINUS expr",
63393 /* 196 */ "expr ::= expr STAR|SLASH|REM expr",
63394 /* 197 */ "expr ::= expr CONCAT expr",
63395 /* 198 */ "likeop ::= LIKE_KW",
63396 /* 199 */ "likeop ::= NOT LIKE_KW",
63397 /* 200 */ "likeop ::= MATCH",
63398 /* 201 */ "likeop ::= NOT MATCH",
63399 /* 202 */ "escape ::= ESCAPE expr",
63400 /* 203 */ "escape ::=",
63401 /* 204 */ "expr ::= expr likeop expr escape",
63402 /* 205 */ "expr ::= expr ISNULL|NOTNULL",
63403 /* 206 */ "expr ::= expr IS NULL",
63404 /* 207 */ "expr ::= expr NOT NULL",
63405 /* 208 */ "expr ::= expr IS NOT NULL",
63406 /* 209 */ "expr ::= NOT|BITNOT expr",
63407 /* 210 */ "expr ::= MINUS expr",
63408 /* 211 */ "expr ::= PLUS expr",
63409 /* 212 */ "between_op ::= BETWEEN",
63410 /* 213 */ "between_op ::= NOT BETWEEN",
63411 /* 214 */ "expr ::= expr between_op expr AND expr",
63412 /* 215 */ "in_op ::= IN",
63413 /* 216 */ "in_op ::= NOT IN",
63414 /* 217 */ "expr ::= expr in_op LP exprlist RP",
63415 /* 218 */ "expr ::= LP select RP",
63416 /* 219 */ "expr ::= expr in_op LP select RP",
63417 /* 220 */ "expr ::= expr in_op nm dbnm",
63418 /* 221 */ "expr ::= EXISTS LP select RP",
63419 /* 222 */ "expr ::= CASE case_operand case_exprlist case_else END",
63420 /* 223 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
63421 /* 224 */ "case_exprlist ::= WHEN expr THEN expr",
63422 /* 225 */ "case_else ::= ELSE expr",
63423 /* 226 */ "case_else ::=",
63424 /* 227 */ "case_operand ::= expr",
63425 /* 228 */ "case_operand ::=",
63426 /* 229 */ "exprlist ::= exprlist COMMA expritem",
63427 /* 230 */ "exprlist ::= expritem",
63428 /* 231 */ "expritem ::= expr",
63429 /* 232 */ "expritem ::=",
63430 /* 233 */ "cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
63431 /* 234 */ "uniqueflag ::= UNIQUE",
63432 /* 235 */ "uniqueflag ::=",
63433 /* 236 */ "idxlist_opt ::=",
63434 /* 237 */ "idxlist_opt ::= LP idxlist RP",
63435 /* 238 */ "idxlist ::= idxlist COMMA idxitem collate sortorder",
63436 /* 239 */ "idxlist ::= idxitem collate sortorder",
63437 /* 240 */ "idxitem ::= nm",
63438 /* 241 */ "collate ::=",
63439 /* 242 */ "collate ::= COLLATE id",
63440 /* 243 */ "cmd ::= DROP INDEX ifexists fullname",
63441 /* 244 */ "cmd ::= VACUUM",
63442 /* 245 */ "cmd ::= VACUUM nm",
63443 /* 246 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
63444 /* 247 */ "cmd ::= PRAGMA nm dbnm EQ ON",
63445 /* 248 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
63446 /* 249 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
63447 /* 250 */ "cmd ::= PRAGMA nm dbnm",
63448 /* 251 */ "nmnum ::= plus_num",
63449 /* 252 */ "nmnum ::= nm",
63450 /* 253 */ "plus_num ::= plus_opt number",
63451 /* 254 */ "minus_num ::= MINUS number",
63452 /* 255 */ "number ::= INTEGER|FLOAT",
63453 /* 256 */ "plus_opt ::= PLUS",
63454 /* 257 */ "plus_opt ::=",
63455 /* 258 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END",
63456 /* 259 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
63457 /* 260 */ "trigger_time ::= BEFORE",
63458 /* 261 */ "trigger_time ::= AFTER",
63459 /* 262 */ "trigger_time ::= INSTEAD OF",
63460 /* 263 */ "trigger_time ::=",
63461 /* 264 */ "trigger_event ::= DELETE|INSERT",
63462 /* 265 */ "trigger_event ::= UPDATE",
63463 /* 266 */ "trigger_event ::= UPDATE OF inscollist",
63464 /* 267 */ "foreach_clause ::=",
63465 /* 268 */ "foreach_clause ::= FOR EACH ROW",
63466 /* 269 */ "when_clause ::=",
63467 /* 270 */ "when_clause ::= WHEN expr",
63468 /* 271 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
63469 /* 272 */ "trigger_cmd_list ::=",
63470 /* 273 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
63471 /* 274 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
63472 /* 275 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select",
63473 /* 276 */ "trigger_cmd ::= DELETE FROM nm where_opt",
63474 /* 277 */ "trigger_cmd ::= select",
63475 /* 278 */ "expr ::= RAISE LP IGNORE RP",
63476 /* 279 */ "expr ::= RAISE LP raisetype COMMA nm RP",
63477 /* 280 */ "raisetype ::= ROLLBACK",
63478 /* 281 */ "raisetype ::= ABORT",
63479 /* 282 */ "raisetype ::= FAIL",
63480 /* 283 */ "cmd ::= DROP TRIGGER ifexists fullname",
63481 /* 284 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
63482 /* 285 */ "cmd ::= DETACH database_kw_opt expr",
63483 /* 286 */ "key_opt ::=",
63484 /* 287 */ "key_opt ::= KEY expr",
63485 /* 288 */ "database_kw_opt ::= DATABASE",
63486 /* 289 */ "database_kw_opt ::=",
63487 /* 290 */ "cmd ::= REINDEX",
63488 /* 291 */ "cmd ::= REINDEX nm dbnm",
63489 /* 292 */ "cmd ::= ANALYZE",
63490 /* 293 */ "cmd ::= ANALYZE nm dbnm",
63491 /* 294 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
63492 /* 295 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
63493 /* 296 */ "add_column_fullname ::= fullname",
63494 /* 297 */ "kwcolumn_opt ::=",
63495 /* 298 */ "kwcolumn_opt ::= COLUMNKW",
63496 /* 299 */ "cmd ::= create_vtab",
63497 /* 300 */ "cmd ::= create_vtab LP vtabarglist RP",
63498 /* 301 */ "create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm",
63499 /* 302 */ "vtabarglist ::= vtabarg",
63500 /* 303 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
63501 /* 304 */ "vtabarg ::=",
63502 /* 305 */ "vtabarg ::= vtabarg vtabargtoken",
63503 /* 306 */ "vtabargtoken ::= ANY",
63504 /* 307 */ "vtabargtoken ::= lp anylist RP",
63505 /* 308 */ "lp ::= LP",
63506 /* 309 */ "anylist ::=",
63507 /* 310 */ "anylist ::= anylist ANY",
63509 #endif /* NDEBUG */
63512 #if YYSTACKDEPTH<=0
63514 ** Try to increase the size of the parser stack.
63516 static void yyGrowStack(yyParser *p){
63517 int newSize;
63518 yyStackEntry *pNew;
63520 newSize = p->yystksz*2 + 100;
63521 pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
63522 if( pNew ){
63523 p->yystack = pNew;
63524 p->yystksz = newSize;
63525 #ifndef NDEBUG
63526 if( yyTraceFILE ){
63527 fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
63528 yyTracePrompt, p->yystksz);
63530 #endif
63533 #endif
63536 ** This function allocates a new parser.
63537 ** The only argument is a pointer to a function which works like
63538 ** malloc.
63540 ** Inputs:
63541 ** A pointer to the function used to allocate memory.
63543 ** Outputs:
63544 ** A pointer to a parser. This pointer is used in subsequent calls
63545 ** to sqlite3Parser and sqlite3ParserFree.
63547 static void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
63548 yyParser *pParser;
63549 pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
63550 if( pParser ){
63551 pParser->yyidx = -1;
63552 #if YYSTACKDEPTH<=0
63553 yyGrowStack(pParser);
63554 #endif
63556 return pParser;
63559 /* The following function deletes the value associated with a
63560 ** symbol. The symbol can be either a terminal or nonterminal.
63561 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
63562 ** the value.
63564 static void yy_destructor(YYCODETYPE yymajor, YYMINORTYPE *yypminor){
63565 switch( yymajor ){
63566 /* Here is inserted the actions which take place when a
63567 ** terminal or non-terminal is destroyed. This can happen
63568 ** when the symbol is popped from the stack during a
63569 ** reduce or during error processing or when a parser is
63570 ** being destroyed before it is finished parsing.
63572 ** Note: during a reduce, the only symbols destroyed are those
63573 ** which appear on the RHS of the rule, but which are not used
63574 ** inside the C code.
63576 case 155:
63577 case 189:
63578 case 206:
63579 {sqlite3SelectDelete((yypminor->yy219));}
63580 break;
63581 case 169:
63582 case 170:
63583 case 194:
63584 case 196:
63585 case 204:
63586 case 210:
63587 case 217:
63588 case 220:
63589 case 222:
63590 case 223:
63591 case 235:
63592 {sqlite3ExprDelete((yypminor->yy172));}
63593 break;
63594 case 174:
63595 case 182:
63596 case 192:
63597 case 195:
63598 case 197:
63599 case 199:
63600 case 209:
63601 case 211:
63602 case 212:
63603 case 215:
63604 case 221:
63605 {sqlite3ExprListDelete((yypminor->yy174));}
63606 break;
63607 case 188:
63608 case 193:
63609 case 201:
63610 case 202:
63611 {sqlite3SrcListDelete((yypminor->yy373));}
63612 break;
63613 case 205:
63614 case 208:
63615 case 214:
63616 {sqlite3IdListDelete((yypminor->yy432));}
63617 break;
63618 case 231:
63619 case 236:
63620 {sqlite3DeleteTriggerStep((yypminor->yy243));}
63621 break;
63622 case 233:
63623 {sqlite3IdListDelete((yypminor->yy370).b);}
63624 break;
63625 case 238:
63626 {sqlite3ExprDelete((yypminor->yy386));}
63627 break;
63628 default: break; /* If no destructor action specified: do nothing */
63633 ** Pop the parser's stack once.
63635 ** If there is a destructor routine associated with the token which
63636 ** is popped from the stack, then call it.
63638 ** Return the major token number for the symbol popped.
63640 static int yy_pop_parser_stack(yyParser *pParser){
63641 YYCODETYPE yymajor;
63642 yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
63644 if( pParser->yyidx<0 ) return 0;
63645 #ifndef NDEBUG
63646 if( yyTraceFILE && pParser->yyidx>=0 ){
63647 fprintf(yyTraceFILE,"%sPopping %s\n",
63648 yyTracePrompt,
63649 yyTokenName[yytos->major]);
63651 #endif
63652 yymajor = yytos->major;
63653 yy_destructor( yymajor, &yytos->minor);
63654 pParser->yyidx--;
63655 return yymajor;
63659 ** Deallocate and destroy a parser. Destructors are all called for
63660 ** all stack elements before shutting the parser down.
63662 ** Inputs:
63663 ** <ul>
63664 ** <li> A pointer to the parser. This should be a pointer
63665 ** obtained from sqlite3ParserAlloc.
63666 ** <li> A pointer to a function used to reclaim memory obtained
63667 ** from malloc.
63668 ** </ul>
63670 static void sqlite3ParserFree(
63671 void *p, /* The parser to be deleted */
63672 void (*freeProc)(void*) /* Function used to reclaim memory */
63674 yyParser *pParser = (yyParser*)p;
63675 if( pParser==0 ) return;
63676 while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
63677 #if YYSTACKDEPTH<=0
63678 free(pParser->yystack);
63679 #endif
63680 (*freeProc)((void*)pParser);
63684 ** Find the appropriate action for a parser given the terminal
63685 ** look-ahead token iLookAhead.
63687 ** If the look-ahead token is YYNOCODE, then check to see if the action is
63688 ** independent of the look-ahead. If it is, return the action, otherwise
63689 ** return YY_NO_ACTION.
63691 static int yy_find_shift_action(
63692 yyParser *pParser, /* The parser */
63693 YYCODETYPE iLookAhead /* The look-ahead token */
63695 int i;
63696 int stateno = pParser->yystack[pParser->yyidx].stateno;
63698 if( stateno>YY_SHIFT_MAX || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
63699 return yy_default[stateno];
63701 if( iLookAhead==YYNOCODE ){
63702 return YY_NO_ACTION;
63704 i += iLookAhead;
63705 if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
63706 if( iLookAhead>0 ){
63707 #ifdef YYFALLBACK
63708 int iFallback; /* Fallback token */
63709 if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
63710 && (iFallback = yyFallback[iLookAhead])!=0 ){
63711 #ifndef NDEBUG
63712 if( yyTraceFILE ){
63713 fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
63714 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
63716 #endif
63717 return yy_find_shift_action(pParser, iFallback);
63719 #endif
63720 #ifdef YYWILDCARD
63722 int j = i - iLookAhead + YYWILDCARD;
63723 if( j>=0 && j<YY_SZ_ACTTAB && yy_lookahead[j]==YYWILDCARD ){
63724 #ifndef NDEBUG
63725 if( yyTraceFILE ){
63726 fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
63727 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
63729 #endif /* NDEBUG */
63730 return yy_action[j];
63733 #endif /* YYWILDCARD */
63735 return yy_default[stateno];
63736 }else{
63737 return yy_action[i];
63742 ** Find the appropriate action for a parser given the non-terminal
63743 ** look-ahead token iLookAhead.
63745 ** If the look-ahead token is YYNOCODE, then check to see if the action is
63746 ** independent of the look-ahead. If it is, return the action, otherwise
63747 ** return YY_NO_ACTION.
63749 static int yy_find_reduce_action(
63750 int stateno, /* Current state number */
63751 YYCODETYPE iLookAhead /* The look-ahead token */
63753 int i;
63754 /* int stateno = pParser->yystack[pParser->yyidx].stateno; */
63756 if( stateno>YY_REDUCE_MAX ||
63757 (i = yy_reduce_ofst[stateno])==YY_REDUCE_USE_DFLT ){
63758 return yy_default[stateno];
63760 if( iLookAhead==YYNOCODE ){
63761 return YY_NO_ACTION;
63763 i += iLookAhead;
63764 if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
63765 return yy_default[stateno];
63766 }else{
63767 return yy_action[i];
63772 ** The following routine is called if the stack overflows.
63774 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
63775 sqlite3ParserARG_FETCH;
63776 yypParser->yyidx--;
63777 #ifndef NDEBUG
63778 if( yyTraceFILE ){
63779 fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
63781 #endif
63782 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
63783 /* Here code is inserted which will execute if the parser
63784 ** stack every overflows */
63786 sqlite3ErrorMsg(pParse, "parser stack overflow");
63787 pParse->parseError = 1;
63788 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
63792 ** Perform a shift action.
63794 static void yy_shift(
63795 yyParser *yypParser, /* The parser to be shifted */
63796 int yyNewState, /* The new state to shift in */
63797 int yyMajor, /* The major token to shift in */
63798 YYMINORTYPE *yypMinor /* Pointer ot the minor token to shift in */
63800 yyStackEntry *yytos;
63801 yypParser->yyidx++;
63802 #if YYSTACKDEPTH>0
63803 if( yypParser->yyidx>=YYSTACKDEPTH ){
63804 yyStackOverflow(yypParser, yypMinor);
63805 return;
63807 #else
63808 if( yypParser->yyidx>=yypParser->yystksz ){
63809 yyGrowStack(yypParser);
63810 if( yypParser->yyidx>=yypParser->yystksz ){
63811 yyStackOverflow(yypParser, yypMinor);
63812 return;
63815 #endif
63816 yytos = &yypParser->yystack[yypParser->yyidx];
63817 yytos->stateno = yyNewState;
63818 yytos->major = yyMajor;
63819 yytos->minor = *yypMinor;
63820 #ifndef NDEBUG
63821 if( yyTraceFILE && yypParser->yyidx>0 ){
63822 int i;
63823 fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
63824 fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
63825 for(i=1; i<=yypParser->yyidx; i++)
63826 fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
63827 fprintf(yyTraceFILE,"\n");
63829 #endif
63832 /* The following table contains information about every rule that
63833 ** is used during the reduce.
63835 static const struct {
63836 YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
63837 unsigned char nrhs; /* Number of right-hand side symbols in the rule */
63838 } yyRuleInfo[] = {
63839 { 139, 1 },
63840 { 140, 2 },
63841 { 140, 1 },
63842 { 142, 1 },
63843 { 141, 1 },
63844 { 141, 3 },
63845 { 144, 0 },
63846 { 144, 1 },
63847 { 144, 3 },
63848 { 143, 3 },
63849 { 146, 0 },
63850 { 146, 1 },
63851 { 146, 2 },
63852 { 145, 0 },
63853 { 145, 1 },
63854 { 145, 1 },
63855 { 145, 1 },
63856 { 143, 2 },
63857 { 143, 2 },
63858 { 143, 2 },
63859 { 143, 2 },
63860 { 148, 6 },
63861 { 151, 0 },
63862 { 151, 3 },
63863 { 150, 1 },
63864 { 150, 0 },
63865 { 149, 4 },
63866 { 149, 2 },
63867 { 153, 3 },
63868 { 153, 1 },
63869 { 156, 3 },
63870 { 157, 1 },
63871 { 160, 1 },
63872 { 161, 1 },
63873 { 147, 1 },
63874 { 147, 1 },
63875 { 147, 1 },
63876 { 158, 0 },
63877 { 158, 1 },
63878 { 162, 1 },
63879 { 162, 4 },
63880 { 162, 6 },
63881 { 163, 1 },
63882 { 163, 2 },
63883 { 164, 1 },
63884 { 164, 1 },
63885 { 159, 2 },
63886 { 159, 0 },
63887 { 167, 3 },
63888 { 167, 1 },
63889 { 168, 2 },
63890 { 168, 4 },
63891 { 168, 3 },
63892 { 168, 3 },
63893 { 168, 2 },
63894 { 168, 2 },
63895 { 168, 3 },
63896 { 168, 5 },
63897 { 168, 2 },
63898 { 168, 4 },
63899 { 168, 4 },
63900 { 168, 1 },
63901 { 168, 2 },
63902 { 173, 0 },
63903 { 173, 1 },
63904 { 175, 0 },
63905 { 175, 2 },
63906 { 177, 2 },
63907 { 177, 3 },
63908 { 177, 3 },
63909 { 177, 3 },
63910 { 178, 2 },
63911 { 178, 2 },
63912 { 178, 1 },
63913 { 178, 1 },
63914 { 176, 3 },
63915 { 176, 2 },
63916 { 179, 0 },
63917 { 179, 2 },
63918 { 179, 2 },
63919 { 154, 0 },
63920 { 154, 2 },
63921 { 180, 3 },
63922 { 180, 2 },
63923 { 180, 1 },
63924 { 181, 2 },
63925 { 181, 7 },
63926 { 181, 5 },
63927 { 181, 5 },
63928 { 181, 10 },
63929 { 183, 0 },
63930 { 183, 1 },
63931 { 171, 0 },
63932 { 171, 3 },
63933 { 184, 0 },
63934 { 184, 2 },
63935 { 185, 1 },
63936 { 185, 1 },
63937 { 185, 1 },
63938 { 143, 4 },
63939 { 187, 2 },
63940 { 187, 0 },
63941 { 143, 8 },
63942 { 143, 4 },
63943 { 143, 1 },
63944 { 155, 1 },
63945 { 155, 3 },
63946 { 190, 1 },
63947 { 190, 2 },
63948 { 190, 1 },
63949 { 189, 9 },
63950 { 191, 1 },
63951 { 191, 1 },
63952 { 191, 0 },
63953 { 199, 2 },
63954 { 199, 0 },
63955 { 192, 3 },
63956 { 192, 2 },
63957 { 192, 4 },
63958 { 200, 2 },
63959 { 200, 1 },
63960 { 200, 0 },
63961 { 193, 0 },
63962 { 193, 2 },
63963 { 202, 2 },
63964 { 202, 0 },
63965 { 201, 6 },
63966 { 201, 7 },
63967 { 206, 1 },
63968 { 206, 1 },
63969 { 152, 0 },
63970 { 152, 2 },
63971 { 188, 2 },
63972 { 203, 1 },
63973 { 203, 2 },
63974 { 203, 3 },
63975 { 203, 4 },
63976 { 204, 2 },
63977 { 204, 0 },
63978 { 205, 4 },
63979 { 205, 0 },
63980 { 197, 0 },
63981 { 197, 3 },
63982 { 209, 4 },
63983 { 209, 2 },
63984 { 210, 1 },
63985 { 172, 1 },
63986 { 172, 1 },
63987 { 172, 0 },
63988 { 195, 0 },
63989 { 195, 3 },
63990 { 196, 0 },
63991 { 196, 2 },
63992 { 198, 0 },
63993 { 198, 2 },
63994 { 198, 4 },
63995 { 198, 4 },
63996 { 143, 4 },
63997 { 194, 0 },
63998 { 194, 2 },
63999 { 143, 6 },
64000 { 212, 5 },
64001 { 212, 3 },
64002 { 143, 8 },
64003 { 143, 5 },
64004 { 143, 6 },
64005 { 213, 2 },
64006 { 213, 1 },
64007 { 215, 3 },
64008 { 215, 1 },
64009 { 214, 0 },
64010 { 214, 3 },
64011 { 208, 3 },
64012 { 208, 1 },
64013 { 170, 1 },
64014 { 170, 3 },
64015 { 169, 1 },
64016 { 170, 1 },
64017 { 170, 1 },
64018 { 170, 3 },
64019 { 170, 5 },
64020 { 169, 1 },
64021 { 169, 1 },
64022 { 170, 1 },
64023 { 170, 1 },
64024 { 170, 3 },
64025 { 170, 6 },
64026 { 170, 5 },
64027 { 170, 4 },
64028 { 169, 1 },
64029 { 170, 3 },
64030 { 170, 3 },
64031 { 170, 3 },
64032 { 170, 3 },
64033 { 170, 3 },
64034 { 170, 3 },
64035 { 170, 3 },
64036 { 170, 3 },
64037 { 216, 1 },
64038 { 216, 2 },
64039 { 216, 1 },
64040 { 216, 2 },
64041 { 217, 2 },
64042 { 217, 0 },
64043 { 170, 4 },
64044 { 170, 2 },
64045 { 170, 3 },
64046 { 170, 3 },
64047 { 170, 4 },
64048 { 170, 2 },
64049 { 170, 2 },
64050 { 170, 2 },
64051 { 218, 1 },
64052 { 218, 2 },
64053 { 170, 5 },
64054 { 219, 1 },
64055 { 219, 2 },
64056 { 170, 5 },
64057 { 170, 3 },
64058 { 170, 5 },
64059 { 170, 4 },
64060 { 170, 4 },
64061 { 170, 5 },
64062 { 221, 5 },
64063 { 221, 4 },
64064 { 222, 2 },
64065 { 222, 0 },
64066 { 220, 1 },
64067 { 220, 0 },
64068 { 211, 3 },
64069 { 211, 1 },
64070 { 223, 1 },
64071 { 223, 0 },
64072 { 143, 11 },
64073 { 224, 1 },
64074 { 224, 0 },
64075 { 174, 0 },
64076 { 174, 3 },
64077 { 182, 5 },
64078 { 182, 3 },
64079 { 225, 1 },
64080 { 226, 0 },
64081 { 226, 2 },
64082 { 143, 4 },
64083 { 143, 1 },
64084 { 143, 2 },
64085 { 143, 5 },
64086 { 143, 5 },
64087 { 143, 5 },
64088 { 143, 6 },
64089 { 143, 3 },
64090 { 227, 1 },
64091 { 227, 1 },
64092 { 165, 2 },
64093 { 166, 2 },
64094 { 229, 1 },
64095 { 228, 1 },
64096 { 228, 0 },
64097 { 143, 5 },
64098 { 230, 11 },
64099 { 232, 1 },
64100 { 232, 1 },
64101 { 232, 2 },
64102 { 232, 0 },
64103 { 233, 1 },
64104 { 233, 1 },
64105 { 233, 3 },
64106 { 234, 0 },
64107 { 234, 3 },
64108 { 235, 0 },
64109 { 235, 2 },
64110 { 231, 3 },
64111 { 231, 0 },
64112 { 236, 6 },
64113 { 236, 8 },
64114 { 236, 5 },
64115 { 236, 4 },
64116 { 236, 1 },
64117 { 170, 4 },
64118 { 170, 6 },
64119 { 186, 1 },
64120 { 186, 1 },
64121 { 186, 1 },
64122 { 143, 4 },
64123 { 143, 6 },
64124 { 143, 3 },
64125 { 238, 0 },
64126 { 238, 2 },
64127 { 237, 1 },
64128 { 237, 0 },
64129 { 143, 1 },
64130 { 143, 3 },
64131 { 143, 1 },
64132 { 143, 3 },
64133 { 143, 6 },
64134 { 143, 6 },
64135 { 239, 1 },
64136 { 240, 0 },
64137 { 240, 1 },
64138 { 143, 1 },
64139 { 143, 4 },
64140 { 241, 7 },
64141 { 242, 1 },
64142 { 242, 3 },
64143 { 243, 0 },
64144 { 243, 2 },
64145 { 244, 1 },
64146 { 244, 3 },
64147 { 245, 1 },
64148 { 246, 0 },
64149 { 246, 2 },
64152 static void yy_accept(yyParser*); /* Forward Declaration */
64155 ** Perform a reduce action and the shift that must immediately
64156 ** follow the reduce.
64158 static void yy_reduce(
64159 yyParser *yypParser, /* The parser */
64160 int yyruleno /* Number of the rule by which to reduce */
64162 int yygoto; /* The next state */
64163 int yyact; /* The next action */
64164 YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
64165 yyStackEntry *yymsp; /* The top of the parser's stack */
64166 int yysize; /* Amount to pop the stack */
64167 sqlite3ParserARG_FETCH;
64168 yymsp = &yypParser->yystack[yypParser->yyidx];
64169 #ifndef NDEBUG
64170 if( yyTraceFILE && yyruleno>=0
64171 && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
64172 fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
64173 yyRuleName[yyruleno]);
64175 #endif /* NDEBUG */
64177 /* Silence complaints from purify about yygotominor being uninitialized
64178 ** in some cases when it is copied into the stack after the following
64179 ** switch. yygotominor is uninitialized when a rule reduces that does
64180 ** not set the value of its left-hand side nonterminal. Leaving the
64181 ** value of the nonterminal uninitialized is utterly harmless as long
64182 ** as the value is never used. So really the only thing this code
64183 ** accomplishes is to quieten purify.
64185 ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
64186 ** without this code, their parser segfaults. I'm not sure what there
64187 ** parser is doing to make this happen. This is the second bug report
64188 ** from wireshark this week. Clearly they are stressing Lemon in ways
64189 ** that it has not been previously stressed... (SQLite ticket #2172)
64191 memset(&yygotominor, 0, sizeof(yygotominor));
64194 switch( yyruleno ){
64195 /* Beginning here are the reduction cases. A typical example
64196 ** follows:
64197 ** case 0:
64198 ** #line <lineno> <grammarfile>
64199 ** { ... } // User supplied code
64200 ** #line <lineno> <thisfile>
64201 ** break;
64203 case 0:
64204 case 1:
64205 case 2:
64206 case 4:
64207 case 5:
64208 case 10:
64209 case 11:
64210 case 12:
64211 case 20:
64212 case 28:
64213 case 29:
64214 case 37:
64215 case 44:
64216 case 45:
64217 case 46:
64218 case 47:
64219 case 48:
64220 case 49:
64221 case 55:
64222 case 82:
64223 case 83:
64224 case 84:
64225 case 85:
64226 case 256:
64227 case 257:
64228 case 267:
64229 case 268:
64230 case 288:
64231 case 289:
64232 case 297:
64233 case 298:
64234 case 302:
64235 case 303:
64236 case 305:
64237 case 309:
64240 break;
64241 case 3:
64242 { sqlite3FinishCoding(pParse); }
64243 break;
64244 case 6:
64245 { sqlite3BeginParse(pParse, 0); }
64246 break;
64247 case 7:
64248 { sqlite3BeginParse(pParse, 1); }
64249 break;
64250 case 8:
64251 { sqlite3BeginParse(pParse, 2); }
64252 break;
64253 case 9:
64254 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy46);}
64255 break;
64256 case 13:
64257 {yygotominor.yy46 = TK_DEFERRED;}
64258 break;
64259 case 14:
64260 case 15:
64261 case 16:
64262 case 107:
64263 case 109:
64264 {yygotominor.yy46 = yymsp[0].major;}
64265 break;
64266 case 17:
64267 case 18:
64268 {sqlite3CommitTransaction(pParse);}
64269 break;
64270 case 19:
64271 {sqlite3RollbackTransaction(pParse);}
64272 break;
64273 case 21:
64275 sqlite3StartTable(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410,yymsp[-4].minor.yy46,0,0,yymsp[-2].minor.yy46);
64277 break;
64278 case 22:
64279 case 25:
64280 case 63:
64281 case 77:
64282 case 79:
64283 case 90:
64284 case 101:
64285 case 112:
64286 case 113:
64287 case 212:
64288 case 215:
64289 {yygotominor.yy46 = 0;}
64290 break;
64291 case 23:
64292 case 24:
64293 case 64:
64294 case 78:
64295 case 100:
64296 case 111:
64297 case 213:
64298 case 216:
64299 {yygotominor.yy46 = 1;}
64300 break;
64301 case 26:
64303 sqlite3EndTable(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy0,0);
64305 break;
64306 case 27:
64308 sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy219);
64309 sqlite3SelectDelete(yymsp[0].minor.yy219);
64311 break;
64312 case 30:
64314 yygotominor.yy410.z = yymsp[-2].minor.yy410.z;
64315 yygotominor.yy410.n = (pParse->sLastToken.z-yymsp[-2].minor.yy410.z) + pParse->sLastToken.n;
64317 break;
64318 case 31:
64320 sqlite3AddColumn(pParse,&yymsp[0].minor.yy410);
64321 yygotominor.yy410 = yymsp[0].minor.yy410;
64323 break;
64324 case 32:
64325 case 33:
64326 case 34:
64327 case 35:
64328 case 36:
64329 case 255:
64330 {yygotominor.yy410 = yymsp[0].minor.yy0;}
64331 break;
64332 case 38:
64333 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy410);}
64334 break;
64335 case 39:
64336 case 42:
64337 case 119:
64338 case 120:
64339 case 131:
64340 case 240:
64341 case 242:
64342 case 251:
64343 case 252:
64344 case 253:
64345 case 254:
64346 {yygotominor.yy410 = yymsp[0].minor.yy410;}
64347 break;
64348 case 40:
64350 yygotominor.yy410.z = yymsp[-3].minor.yy410.z;
64351 yygotominor.yy410.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy410.z;
64353 break;
64354 case 41:
64356 yygotominor.yy410.z = yymsp[-5].minor.yy410.z;
64357 yygotominor.yy410.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy410.z;
64359 break;
64360 case 43:
64361 {yygotominor.yy410.z=yymsp[-1].minor.yy410.z; yygotominor.yy410.n=yymsp[0].minor.yy410.n+(yymsp[0].minor.yy410.z-yymsp[-1].minor.yy410.z);}
64362 break;
64363 case 50:
64364 case 52:
64365 {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy172);}
64366 break;
64367 case 51:
64368 {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy172);}
64369 break;
64370 case 53:
64372 Expr *p = sqlite3Expr(TK_UMINUS, yymsp[0].minor.yy172, 0, 0);
64373 sqlite3AddDefaultValue(pParse,p);
64375 break;
64376 case 54:
64378 Expr *p = sqlite3Expr(TK_STRING, 0, 0, &yymsp[0].minor.yy410);
64379 sqlite3AddDefaultValue(pParse,p);
64381 break;
64382 case 56:
64383 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy46);}
64384 break;
64385 case 57:
64386 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy46,yymsp[0].minor.yy46,yymsp[-2].minor.yy46);}
64387 break;
64388 case 58:
64389 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy46,0,0,0,0);}
64390 break;
64391 case 59:
64392 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy172);}
64393 break;
64394 case 60:
64395 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy410,yymsp[-1].minor.yy174,yymsp[0].minor.yy46);}
64396 break;
64397 case 61:
64398 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy46);}
64399 break;
64400 case 62:
64401 {sqlite3AddCollateType(pParse, (char*)yymsp[0].minor.yy410.z, yymsp[0].minor.yy410.n);}
64402 break;
64403 case 65:
64404 { yygotominor.yy46 = OE_Restrict * 0x010101; }
64405 break;
64406 case 66:
64407 { yygotominor.yy46 = (yymsp[-1].minor.yy46 & yymsp[0].minor.yy405.mask) | yymsp[0].minor.yy405.value; }
64408 break;
64409 case 67:
64410 { yygotominor.yy405.value = 0; yygotominor.yy405.mask = 0x000000; }
64411 break;
64412 case 68:
64413 { yygotominor.yy405.value = yymsp[0].minor.yy46; yygotominor.yy405.mask = 0x0000ff; }
64414 break;
64415 case 69:
64416 { yygotominor.yy405.value = yymsp[0].minor.yy46<<8; yygotominor.yy405.mask = 0x00ff00; }
64417 break;
64418 case 70:
64419 { yygotominor.yy405.value = yymsp[0].minor.yy46<<16; yygotominor.yy405.mask = 0xff0000; }
64420 break;
64421 case 71:
64422 { yygotominor.yy46 = OE_SetNull; }
64423 break;
64424 case 72:
64425 { yygotominor.yy46 = OE_SetDflt; }
64426 break;
64427 case 73:
64428 { yygotominor.yy46 = OE_Cascade; }
64429 break;
64430 case 74:
64431 { yygotominor.yy46 = OE_Restrict; }
64432 break;
64433 case 75:
64434 case 76:
64435 case 91:
64436 case 93:
64437 case 95:
64438 case 96:
64439 case 166:
64440 {yygotominor.yy46 = yymsp[0].minor.yy46;}
64441 break;
64442 case 80:
64443 {yygotominor.yy410.n = 0; yygotominor.yy410.z = 0;}
64444 break;
64445 case 81:
64446 {yygotominor.yy410 = yymsp[-1].minor.yy0;}
64447 break;
64448 case 86:
64449 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy174,yymsp[0].minor.yy46,yymsp[-2].minor.yy46,0);}
64450 break;
64451 case 87:
64452 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy174,yymsp[0].minor.yy46,0,0,0,0);}
64453 break;
64454 case 88:
64455 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy172);}
64456 break;
64457 case 89:
64459 sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy174, &yymsp[-3].minor.yy410, yymsp[-2].minor.yy174, yymsp[-1].minor.yy46);
64460 sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy46);
64462 break;
64463 case 92:
64464 case 94:
64465 {yygotominor.yy46 = OE_Default;}
64466 break;
64467 case 97:
64468 {yygotominor.yy46 = OE_Ignore;}
64469 break;
64470 case 98:
64471 case 167:
64472 {yygotominor.yy46 = OE_Replace;}
64473 break;
64474 case 99:
64476 sqlite3DropTable(pParse, yymsp[0].minor.yy373, 0, yymsp[-1].minor.yy46);
64478 break;
64479 case 102:
64481 sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy410, &yymsp[-2].minor.yy410, yymsp[0].minor.yy219, yymsp[-6].minor.yy46, yymsp[-4].minor.yy46);
64483 break;
64484 case 103:
64486 sqlite3DropTable(pParse, yymsp[0].minor.yy373, 1, yymsp[-1].minor.yy46);
64488 break;
64489 case 104:
64491 sqlite3Select(pParse, yymsp[0].minor.yy219, SRT_Callback, 0, 0, 0, 0, 0);
64492 sqlite3SelectDelete(yymsp[0].minor.yy219);
64494 break;
64495 case 105:
64496 case 128:
64497 {yygotominor.yy219 = yymsp[0].minor.yy219;}
64498 break;
64499 case 106:
64501 if( yymsp[0].minor.yy219 ){
64502 yymsp[0].minor.yy219->op = yymsp[-1].minor.yy46;
64503 yymsp[0].minor.yy219->pPrior = yymsp[-2].minor.yy219;
64504 }else{
64505 sqlite3SelectDelete(yymsp[-2].minor.yy219);
64507 yygotominor.yy219 = yymsp[0].minor.yy219;
64509 break;
64510 case 108:
64511 {yygotominor.yy46 = TK_ALL;}
64512 break;
64513 case 110:
64515 yygotominor.yy219 = sqlite3SelectNew(yymsp[-6].minor.yy174,yymsp[-5].minor.yy373,yymsp[-4].minor.yy172,yymsp[-3].minor.yy174,yymsp[-2].minor.yy172,yymsp[-1].minor.yy174,yymsp[-7].minor.yy46,yymsp[0].minor.yy234.pLimit,yymsp[0].minor.yy234.pOffset);
64517 break;
64518 case 114:
64519 case 237:
64520 {yygotominor.yy174 = yymsp[-1].minor.yy174;}
64521 break;
64522 case 115:
64523 case 141:
64524 case 149:
64525 case 236:
64526 {yygotominor.yy174 = 0;}
64527 break;
64528 case 116:
64530 yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-2].minor.yy174,yymsp[-1].minor.yy172,yymsp[0].minor.yy410.n?&yymsp[0].minor.yy410:0);
64532 break;
64533 case 117:
64535 yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-1].minor.yy174, sqlite3Expr(TK_ALL, 0, 0, 0), 0);
64537 break;
64538 case 118:
64540 Expr *pRight = sqlite3Expr(TK_ALL, 0, 0, 0);
64541 Expr *pLeft = sqlite3Expr(TK_ID, 0, 0, &yymsp[-2].minor.yy410);
64542 yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-3].minor.yy174, sqlite3Expr(TK_DOT, pLeft, pRight, 0), 0);
64544 break;
64545 case 121:
64546 {yygotominor.yy410.n = 0;}
64547 break;
64548 case 122:
64549 {yygotominor.yy373 = sqliteMalloc(sizeof(*yygotominor.yy373));}
64550 break;
64551 case 123:
64553 yygotominor.yy373 = yymsp[0].minor.yy373;
64554 sqlite3SrcListShiftJoinType(yygotominor.yy373);
64556 break;
64557 case 124:
64559 yygotominor.yy373 = yymsp[-1].minor.yy373;
64560 if( yygotominor.yy373 && yygotominor.yy373->nSrc>0 ) yygotominor.yy373->a[yygotominor.yy373->nSrc-1].jointype = yymsp[0].minor.yy46;
64562 break;
64563 case 125:
64564 {yygotominor.yy373 = 0;}
64565 break;
64566 case 126:
64568 yygotominor.yy373 = sqlite3SrcListAppendFromTerm(yymsp[-5].minor.yy373,&yymsp[-4].minor.yy410,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,0,yymsp[-1].minor.yy172,yymsp[0].minor.yy432);
64570 break;
64571 case 127:
64573 yygotominor.yy373 = sqlite3SrcListAppendFromTerm(yymsp[-6].minor.yy373,0,0,&yymsp[-2].minor.yy410,yymsp[-4].minor.yy219,yymsp[-1].minor.yy172,yymsp[0].minor.yy432);
64575 break;
64576 case 129:
64578 sqlite3SrcListShiftJoinType(yymsp[0].minor.yy373);
64579 yygotominor.yy219 = sqlite3SelectNew(0,yymsp[0].minor.yy373,0,0,0,0,0,0,0);
64581 break;
64582 case 130:
64583 {yygotominor.yy410.z=0; yygotominor.yy410.n=0;}
64584 break;
64585 case 132:
64586 {yygotominor.yy373 = sqlite3SrcListAppend(0,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410);}
64587 break;
64588 case 133:
64589 { yygotominor.yy46 = JT_INNER; }
64590 break;
64591 case 134:
64592 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
64593 break;
64594 case 135:
64595 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy410,0); }
64596 break;
64597 case 136:
64598 { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy410,&yymsp[-1].minor.yy410); }
64599 break;
64600 case 137:
64601 case 145:
64602 case 152:
64603 case 159:
64604 case 174:
64605 case 202:
64606 case 225:
64607 case 227:
64608 case 231:
64609 {yygotominor.yy172 = yymsp[0].minor.yy172;}
64610 break;
64611 case 138:
64612 case 151:
64613 case 158:
64614 case 203:
64615 case 226:
64616 case 228:
64617 case 232:
64618 {yygotominor.yy172 = 0;}
64619 break;
64620 case 139:
64621 case 171:
64622 {yygotominor.yy432 = yymsp[-1].minor.yy432;}
64623 break;
64624 case 140:
64625 case 170:
64626 {yygotominor.yy432 = 0;}
64627 break;
64628 case 142:
64629 case 150:
64630 {yygotominor.yy174 = yymsp[0].minor.yy174;}
64631 break;
64632 case 143:
64634 yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-3].minor.yy174,yymsp[-1].minor.yy172,0);
64635 if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
64637 break;
64638 case 144:
64640 yygotominor.yy174 = sqlite3ExprListAppend(0,yymsp[-1].minor.yy172,0);
64641 if( yygotominor.yy174 && yygotominor.yy174->a ) yygotominor.yy174->a[0].sortOrder = yymsp[0].minor.yy46;
64643 break;
64644 case 146:
64645 case 148:
64646 {yygotominor.yy46 = SQLITE_SO_ASC;}
64647 break;
64648 case 147:
64649 {yygotominor.yy46 = SQLITE_SO_DESC;}
64650 break;
64651 case 153:
64652 {yygotominor.yy234.pLimit = 0; yygotominor.yy234.pOffset = 0;}
64653 break;
64654 case 154:
64655 {yygotominor.yy234.pLimit = yymsp[0].minor.yy172; yygotominor.yy234.pOffset = 0;}
64656 break;
64657 case 155:
64658 {yygotominor.yy234.pLimit = yymsp[-2].minor.yy172; yygotominor.yy234.pOffset = yymsp[0].minor.yy172;}
64659 break;
64660 case 156:
64661 {yygotominor.yy234.pOffset = yymsp[-2].minor.yy172; yygotominor.yy234.pLimit = yymsp[0].minor.yy172;}
64662 break;
64663 case 157:
64664 {sqlite3DeleteFrom(pParse,yymsp[-1].minor.yy373,yymsp[0].minor.yy172);}
64665 break;
64666 case 160:
64668 sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy174,SQLITE_MAX_COLUMN,"set list");
64669 sqlite3Update(pParse,yymsp[-3].minor.yy373,yymsp[-1].minor.yy174,yymsp[0].minor.yy172,yymsp[-4].minor.yy46);
64671 break;
64672 case 161:
64673 {yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-4].minor.yy174,yymsp[0].minor.yy172,&yymsp[-2].minor.yy410);}
64674 break;
64675 case 162:
64676 {yygotominor.yy174 = sqlite3ExprListAppend(0,yymsp[0].minor.yy172,&yymsp[-2].minor.yy410);}
64677 break;
64678 case 163:
64679 {sqlite3Insert(pParse, yymsp[-5].minor.yy373, yymsp[-1].minor.yy174, 0, yymsp[-4].minor.yy432, yymsp[-7].minor.yy46);}
64680 break;
64681 case 164:
64682 {sqlite3Insert(pParse, yymsp[-2].minor.yy373, 0, yymsp[0].minor.yy219, yymsp[-1].minor.yy432, yymsp[-4].minor.yy46);}
64683 break;
64684 case 165:
64685 {sqlite3Insert(pParse, yymsp[-3].minor.yy373, 0, 0, yymsp[-2].minor.yy432, yymsp[-5].minor.yy46);}
64686 break;
64687 case 168:
64688 case 229:
64689 {yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-2].minor.yy174,yymsp[0].minor.yy172,0);}
64690 break;
64691 case 169:
64692 case 230:
64693 {yygotominor.yy174 = sqlite3ExprListAppend(0,yymsp[0].minor.yy172,0);}
64694 break;
64695 case 172:
64696 {yygotominor.yy432 = sqlite3IdListAppend(yymsp[-2].minor.yy432,&yymsp[0].minor.yy410);}
64697 break;
64698 case 173:
64699 {yygotominor.yy432 = sqlite3IdListAppend(0,&yymsp[0].minor.yy410);}
64700 break;
64701 case 175:
64702 {yygotominor.yy172 = yymsp[-1].minor.yy172; sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
64703 break;
64704 case 176:
64705 case 181:
64706 case 182:
64707 {yygotominor.yy172 = sqlite3Expr(yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);}
64708 break;
64709 case 177:
64710 case 178:
64711 {yygotominor.yy172 = sqlite3Expr(TK_ID, 0, 0, &yymsp[0].minor.yy0);}
64712 break;
64713 case 179:
64715 Expr *temp1 = sqlite3Expr(TK_ID, 0, 0, &yymsp[-2].minor.yy410);
64716 Expr *temp2 = sqlite3Expr(TK_ID, 0, 0, &yymsp[0].minor.yy410);
64717 yygotominor.yy172 = sqlite3Expr(TK_DOT, temp1, temp2, 0);
64719 break;
64720 case 180:
64722 Expr *temp1 = sqlite3Expr(TK_ID, 0, 0, &yymsp[-4].minor.yy410);
64723 Expr *temp2 = sqlite3Expr(TK_ID, 0, 0, &yymsp[-2].minor.yy410);
64724 Expr *temp3 = sqlite3Expr(TK_ID, 0, 0, &yymsp[0].minor.yy410);
64725 Expr *temp4 = sqlite3Expr(TK_DOT, temp2, temp3, 0);
64726 yygotominor.yy172 = sqlite3Expr(TK_DOT, temp1, temp4, 0);
64728 break;
64729 case 183:
64730 {yygotominor.yy172 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);}
64731 break;
64732 case 184:
64734 Token *pToken = &yymsp[0].minor.yy0;
64735 Expr *pExpr = yygotominor.yy172 = sqlite3Expr(TK_VARIABLE, 0, 0, pToken);
64736 sqlite3ExprAssignVarNumber(pParse, pExpr);
64738 break;
64739 case 185:
64741 yygotominor.yy172 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy172, &yymsp[0].minor.yy410);
64743 break;
64744 case 186:
64746 yygotominor.yy172 = sqlite3Expr(TK_CAST, yymsp[-3].minor.yy172, 0, &yymsp[-1].minor.yy410);
64747 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
64749 break;
64750 case 187:
64752 if( yymsp[-1].minor.yy174 && yymsp[-1].minor.yy174->nExpr>SQLITE_MAX_FUNCTION_ARG ){
64753 sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
64755 yygotominor.yy172 = sqlite3ExprFunction(yymsp[-1].minor.yy174, &yymsp[-4].minor.yy0);
64756 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
64757 if( yymsp[-2].minor.yy46 && yygotominor.yy172 ){
64758 yygotominor.yy172->flags |= EP_Distinct;
64761 break;
64762 case 188:
64764 yygotominor.yy172 = sqlite3ExprFunction(0, &yymsp[-3].minor.yy0);
64765 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
64767 break;
64768 case 189:
64770 /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
64771 ** treated as functions that return constants */
64772 yygotominor.yy172 = sqlite3ExprFunction(0,&yymsp[0].minor.yy0);
64773 if( yygotominor.yy172 ){
64774 yygotominor.yy172->op = TK_CONST_FUNC;
64775 yygotominor.yy172->span = yymsp[0].minor.yy0;
64778 break;
64779 case 190:
64780 case 191:
64781 case 192:
64782 case 193:
64783 case 194:
64784 case 195:
64785 case 196:
64786 case 197:
64787 {yygotominor.yy172 = sqlite3Expr(yymsp[-1].major, yymsp[-2].minor.yy172, yymsp[0].minor.yy172, 0);}
64788 break;
64789 case 198:
64790 case 200:
64791 {yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 0;}
64792 break;
64793 case 199:
64794 case 201:
64795 {yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 1;}
64796 break;
64797 case 204:
64799 ExprList *pList;
64800 pList = sqlite3ExprListAppend(0, yymsp[-1].minor.yy172, 0);
64801 pList = sqlite3ExprListAppend(pList, yymsp[-3].minor.yy172, 0);
64802 if( yymsp[0].minor.yy172 ){
64803 pList = sqlite3ExprListAppend(pList, yymsp[0].minor.yy172, 0);
64805 yygotominor.yy172 = sqlite3ExprFunction(pList, &yymsp[-2].minor.yy72.eOperator);
64806 if( yymsp[-2].minor.yy72.not ) yygotominor.yy172 = sqlite3Expr(TK_NOT, yygotominor.yy172, 0, 0);
64807 sqlite3ExprSpan(yygotominor.yy172, &yymsp[-3].minor.yy172->span, &yymsp[-1].minor.yy172->span);
64808 if( yygotominor.yy172 ) yygotominor.yy172->flags |= EP_InfixFunc;
64810 break;
64811 case 205:
64813 yygotominor.yy172 = sqlite3Expr(yymsp[0].major, yymsp[-1].minor.yy172, 0, 0);
64814 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy172->span,&yymsp[0].minor.yy0);
64816 break;
64817 case 206:
64819 yygotominor.yy172 = sqlite3Expr(TK_ISNULL, yymsp[-2].minor.yy172, 0, 0);
64820 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy172->span,&yymsp[0].minor.yy0);
64822 break;
64823 case 207:
64825 yygotominor.yy172 = sqlite3Expr(TK_NOTNULL, yymsp[-2].minor.yy172, 0, 0);
64826 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy172->span,&yymsp[0].minor.yy0);
64828 break;
64829 case 208:
64831 yygotominor.yy172 = sqlite3Expr(TK_NOTNULL, yymsp[-3].minor.yy172, 0, 0);
64832 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,&yymsp[0].minor.yy0);
64834 break;
64835 case 209:
64837 yygotominor.yy172 = sqlite3Expr(yymsp[-1].major, yymsp[0].minor.yy172, 0, 0);
64838 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
64840 break;
64841 case 210:
64843 yygotominor.yy172 = sqlite3Expr(TK_UMINUS, yymsp[0].minor.yy172, 0, 0);
64844 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
64846 break;
64847 case 211:
64849 yygotominor.yy172 = sqlite3Expr(TK_UPLUS, yymsp[0].minor.yy172, 0, 0);
64850 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span);
64852 break;
64853 case 214:
64855 ExprList *pList = sqlite3ExprListAppend(0, yymsp[-2].minor.yy172, 0);
64856 pList = sqlite3ExprListAppend(pList, yymsp[0].minor.yy172, 0);
64857 yygotominor.yy172 = sqlite3Expr(TK_BETWEEN, yymsp[-4].minor.yy172, 0, 0);
64858 if( yygotominor.yy172 ){
64859 yygotominor.yy172->pList = pList;
64860 }else{
64861 sqlite3ExprListDelete(pList);
64863 if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3Expr(TK_NOT, yygotominor.yy172, 0, 0);
64864 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy172->span);
64866 break;
64867 case 217:
64869 yygotominor.yy172 = sqlite3Expr(TK_IN, yymsp[-4].minor.yy172, 0, 0);
64870 if( yygotominor.yy172 ){
64871 yygotominor.yy172->pList = yymsp[-1].minor.yy174;
64872 sqlite3ExprSetHeight(yygotominor.yy172);
64873 }else{
64874 sqlite3ExprListDelete(yymsp[-1].minor.yy174);
64876 if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3Expr(TK_NOT, yygotominor.yy172, 0, 0);
64877 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0);
64879 break;
64880 case 218:
64882 yygotominor.yy172 = sqlite3Expr(TK_SELECT, 0, 0, 0);
64883 if( yygotominor.yy172 ){
64884 yygotominor.yy172->pSelect = yymsp[-1].minor.yy219;
64885 sqlite3ExprSetHeight(yygotominor.yy172);
64886 }else{
64887 sqlite3SelectDelete(yymsp[-1].minor.yy219);
64889 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
64891 break;
64892 case 219:
64894 yygotominor.yy172 = sqlite3Expr(TK_IN, yymsp[-4].minor.yy172, 0, 0);
64895 if( yygotominor.yy172 ){
64896 yygotominor.yy172->pSelect = yymsp[-1].minor.yy219;
64897 sqlite3ExprSetHeight(yygotominor.yy172);
64898 }else{
64899 sqlite3SelectDelete(yymsp[-1].minor.yy219);
64901 if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3Expr(TK_NOT, yygotominor.yy172, 0, 0);
64902 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0);
64904 break;
64905 case 220:
64907 SrcList *pSrc = sqlite3SrcListAppend(0,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410);
64908 yygotominor.yy172 = sqlite3Expr(TK_IN, yymsp[-3].minor.yy172, 0, 0);
64909 if( yygotominor.yy172 ){
64910 yygotominor.yy172->pSelect = sqlite3SelectNew(0,pSrc,0,0,0,0,0,0,0);
64911 sqlite3ExprSetHeight(yygotominor.yy172);
64912 }else{
64913 sqlite3SrcListDelete(pSrc);
64915 if( yymsp[-2].minor.yy46 ) yygotominor.yy172 = sqlite3Expr(TK_NOT, yygotominor.yy172, 0, 0);
64916 sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,yymsp[0].minor.yy410.z?&yymsp[0].minor.yy410:&yymsp[-1].minor.yy410);
64918 break;
64919 case 221:
64921 Expr *p = yygotominor.yy172 = sqlite3Expr(TK_EXISTS, 0, 0, 0);
64922 if( p ){
64923 p->pSelect = yymsp[-1].minor.yy219;
64924 sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
64925 sqlite3ExprSetHeight(yygotominor.yy172);
64926 }else{
64927 sqlite3SelectDelete(yymsp[-1].minor.yy219);
64930 break;
64931 case 222:
64933 yygotominor.yy172 = sqlite3Expr(TK_CASE, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, 0);
64934 if( yygotominor.yy172 ){
64935 yygotominor.yy172->pList = yymsp[-2].minor.yy174;
64936 sqlite3ExprSetHeight(yygotominor.yy172);
64937 }else{
64938 sqlite3ExprListDelete(yymsp[-2].minor.yy174);
64940 sqlite3ExprSpan(yygotominor.yy172, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
64942 break;
64943 case 223:
64945 yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-4].minor.yy174, yymsp[-2].minor.yy172, 0);
64946 yygotominor.yy174 = sqlite3ExprListAppend(yygotominor.yy174, yymsp[0].minor.yy172, 0);
64948 break;
64949 case 224:
64951 yygotominor.yy174 = sqlite3ExprListAppend(0, yymsp[-2].minor.yy172, 0);
64952 yygotominor.yy174 = sqlite3ExprListAppend(yygotominor.yy174, yymsp[0].minor.yy172, 0);
64954 break;
64955 case 233:
64957 sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy410, &yymsp[-5].minor.yy410, sqlite3SrcListAppend(0,&yymsp[-3].minor.yy410,0), yymsp[-1].minor.yy174, yymsp[-9].minor.yy46,
64958 &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy46);
64960 break;
64961 case 234:
64962 case 281:
64963 {yygotominor.yy46 = OE_Abort;}
64964 break;
64965 case 235:
64966 {yygotominor.yy46 = OE_None;}
64967 break;
64968 case 238:
64970 Expr *p = 0;
64971 if( yymsp[-1].minor.yy410.n>0 ){
64972 p = sqlite3Expr(TK_COLUMN, 0, 0, 0);
64973 if( p ) p->pColl = sqlite3LocateCollSeq(pParse, (char*)yymsp[-1].minor.yy410.z, yymsp[-1].minor.yy410.n);
64975 yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-4].minor.yy174, p, &yymsp[-2].minor.yy410);
64976 sqlite3ExprListCheckLength(pParse, yygotominor.yy174, SQLITE_MAX_COLUMN, "index");
64977 if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
64979 break;
64980 case 239:
64982 Expr *p = 0;
64983 if( yymsp[-1].minor.yy410.n>0 ){
64984 p = sqlite3Expr(TK_COLUMN, 0, 0, 0);
64985 if( p ) p->pColl = sqlite3LocateCollSeq(pParse, (char*)yymsp[-1].minor.yy410.z, yymsp[-1].minor.yy410.n);
64987 yygotominor.yy174 = sqlite3ExprListAppend(0, p, &yymsp[-2].minor.yy410);
64988 sqlite3ExprListCheckLength(pParse, yygotominor.yy174, SQLITE_MAX_COLUMN, "index");
64989 if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
64991 break;
64992 case 241:
64993 {yygotominor.yy410.z = 0; yygotominor.yy410.n = 0;}
64994 break;
64995 case 243:
64996 {sqlite3DropIndex(pParse, yymsp[0].minor.yy373, yymsp[-1].minor.yy46);}
64997 break;
64998 case 244:
64999 case 245:
65000 {sqlite3Vacuum(pParse);}
65001 break;
65002 case 246:
65003 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy410,0);}
65004 break;
65005 case 247:
65006 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy0,0);}
65007 break;
65008 case 248:
65010 sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy410,1);
65012 break;
65013 case 249:
65014 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy410,&yymsp[-3].minor.yy410,&yymsp[-1].minor.yy410,0);}
65015 break;
65016 case 250:
65017 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410,0,0);}
65018 break;
65019 case 258:
65021 Token all;
65022 all.z = yymsp[-3].minor.yy410.z;
65023 all.n = (yymsp[0].minor.yy0.z - yymsp[-3].minor.yy410.z) + yymsp[0].minor.yy0.n;
65024 sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy243, &all);
65026 break;
65027 case 259:
65029 sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy410, &yymsp[-6].minor.yy410, yymsp[-5].minor.yy46, yymsp[-4].minor.yy370.a, yymsp[-4].minor.yy370.b, yymsp[-2].minor.yy373, yymsp[0].minor.yy172, yymsp[-10].minor.yy46, yymsp[-8].minor.yy46);
65030 yygotominor.yy410 = (yymsp[-6].minor.yy410.n==0?yymsp[-7].minor.yy410:yymsp[-6].minor.yy410);
65032 break;
65033 case 260:
65034 case 263:
65035 { yygotominor.yy46 = TK_BEFORE; }
65036 break;
65037 case 261:
65038 { yygotominor.yy46 = TK_AFTER; }
65039 break;
65040 case 262:
65041 { yygotominor.yy46 = TK_INSTEAD;}
65042 break;
65043 case 264:
65044 case 265:
65045 {yygotominor.yy370.a = yymsp[0].major; yygotominor.yy370.b = 0;}
65046 break;
65047 case 266:
65048 {yygotominor.yy370.a = TK_UPDATE; yygotominor.yy370.b = yymsp[0].minor.yy432;}
65049 break;
65050 case 269:
65051 { yygotominor.yy172 = 0; }
65052 break;
65053 case 270:
65054 { yygotominor.yy172 = yymsp[0].minor.yy172; }
65055 break;
65056 case 271:
65058 if( yymsp[-2].minor.yy243 ){
65059 yymsp[-2].minor.yy243->pLast->pNext = yymsp[-1].minor.yy243;
65060 }else{
65061 yymsp[-2].minor.yy243 = yymsp[-1].minor.yy243;
65063 yymsp[-2].minor.yy243->pLast = yymsp[-1].minor.yy243;
65064 yygotominor.yy243 = yymsp[-2].minor.yy243;
65066 break;
65067 case 272:
65068 { yygotominor.yy243 = 0; }
65069 break;
65070 case 273:
65071 { yygotominor.yy243 = sqlite3TriggerUpdateStep(&yymsp[-3].minor.yy410, yymsp[-1].minor.yy174, yymsp[0].minor.yy172, yymsp[-4].minor.yy46); }
65072 break;
65073 case 274:
65074 {yygotominor.yy243 = sqlite3TriggerInsertStep(&yymsp[-5].minor.yy410, yymsp[-4].minor.yy432, yymsp[-1].minor.yy174, 0, yymsp[-7].minor.yy46);}
65075 break;
65076 case 275:
65077 {yygotominor.yy243 = sqlite3TriggerInsertStep(&yymsp[-2].minor.yy410, yymsp[-1].minor.yy432, 0, yymsp[0].minor.yy219, yymsp[-4].minor.yy46);}
65078 break;
65079 case 276:
65080 {yygotominor.yy243 = sqlite3TriggerDeleteStep(&yymsp[-1].minor.yy410, yymsp[0].minor.yy172);}
65081 break;
65082 case 277:
65083 {yygotominor.yy243 = sqlite3TriggerSelectStep(yymsp[0].minor.yy219); }
65084 break;
65085 case 278:
65087 yygotominor.yy172 = sqlite3Expr(TK_RAISE, 0, 0, 0);
65088 if( yygotominor.yy172 ){
65089 yygotominor.yy172->iColumn = OE_Ignore;
65090 sqlite3ExprSpan(yygotominor.yy172, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
65093 break;
65094 case 279:
65096 yygotominor.yy172 = sqlite3Expr(TK_RAISE, 0, 0, &yymsp[-1].minor.yy410);
65097 if( yygotominor.yy172 ) {
65098 yygotominor.yy172->iColumn = yymsp[-3].minor.yy46;
65099 sqlite3ExprSpan(yygotominor.yy172, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
65102 break;
65103 case 280:
65104 {yygotominor.yy46 = OE_Rollback;}
65105 break;
65106 case 282:
65107 {yygotominor.yy46 = OE_Fail;}
65108 break;
65109 case 283:
65111 sqlite3DropTrigger(pParse,yymsp[0].minor.yy373,yymsp[-1].minor.yy46);
65113 break;
65114 case 284:
65116 sqlite3Attach(pParse, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, yymsp[0].minor.yy386);
65118 break;
65119 case 285:
65121 sqlite3Detach(pParse, yymsp[0].minor.yy172);
65123 break;
65124 case 286:
65125 { yygotominor.yy386 = 0; }
65126 break;
65127 case 287:
65128 { yygotominor.yy386 = yymsp[0].minor.yy172; }
65129 break;
65130 case 290:
65131 {sqlite3Reindex(pParse, 0, 0);}
65132 break;
65133 case 291:
65134 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy410, &yymsp[0].minor.yy410);}
65135 break;
65136 case 292:
65137 {sqlite3Analyze(pParse, 0, 0);}
65138 break;
65139 case 293:
65140 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy410, &yymsp[0].minor.yy410);}
65141 break;
65142 case 294:
65144 sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy373,&yymsp[0].minor.yy410);
65146 break;
65147 case 295:
65149 sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy410);
65151 break;
65152 case 296:
65154 sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy373);
65156 break;
65157 case 299:
65158 {sqlite3VtabFinishParse(pParse,0);}
65159 break;
65160 case 300:
65161 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
65162 break;
65163 case 301:
65165 sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy410, &yymsp[-2].minor.yy410, &yymsp[0].minor.yy410);
65167 break;
65168 case 304:
65169 {sqlite3VtabArgInit(pParse);}
65170 break;
65171 case 306:
65172 case 307:
65173 case 308:
65174 case 310:
65175 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
65176 break;
65178 yygoto = yyRuleInfo[yyruleno].lhs;
65179 yysize = yyRuleInfo[yyruleno].nrhs;
65180 yypParser->yyidx -= yysize;
65181 yyact = yy_find_reduce_action(yymsp[-yysize].stateno,yygoto);
65182 if( yyact < YYNSTATE ){
65183 #ifdef NDEBUG
65184 /* If we are not debugging and the reduce action popped at least
65185 ** one element off the stack, then we can push the new element back
65186 ** onto the stack here, and skip the stack overflow test in yy_shift().
65187 ** That gives a significant speed improvement. */
65188 if( yysize ){
65189 yypParser->yyidx++;
65190 yymsp -= yysize-1;
65191 yymsp->stateno = yyact;
65192 yymsp->major = yygoto;
65193 yymsp->minor = yygotominor;
65194 }else
65195 #endif
65197 yy_shift(yypParser,yyact,yygoto,&yygotominor);
65199 }else if( yyact == YYNSTATE + YYNRULE + 1 ){
65200 yy_accept(yypParser);
65205 ** The following code executes when the parse fails
65207 static void yy_parse_failed(
65208 yyParser *yypParser /* The parser */
65210 sqlite3ParserARG_FETCH;
65211 #ifndef NDEBUG
65212 if( yyTraceFILE ){
65213 fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
65215 #endif
65216 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
65217 /* Here code is inserted which will be executed whenever the
65218 ** parser fails */
65219 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
65223 ** The following code executes when a syntax error first occurs.
65225 static void yy_syntax_error(
65226 yyParser *yypParser, /* The parser */
65227 int yymajor, /* The major type of the error token */
65228 YYMINORTYPE yyminor /* The minor type of the error token */
65230 sqlite3ParserARG_FETCH;
65231 #define TOKEN (yyminor.yy0)
65233 if( !pParse->parseError ){
65234 if( TOKEN.z[0] ){
65235 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
65236 }else{
65237 sqlite3ErrorMsg(pParse, "incomplete SQL statement");
65239 pParse->parseError = 1;
65241 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
65245 ** The following is executed when the parser accepts
65247 static void yy_accept(
65248 yyParser *yypParser /* The parser */
65250 sqlite3ParserARG_FETCH;
65251 #ifndef NDEBUG
65252 if( yyTraceFILE ){
65253 fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
65255 #endif
65256 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
65257 /* Here code is inserted which will be executed whenever the
65258 ** parser accepts */
65259 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
65262 /* The main parser program.
65263 ** The first argument is a pointer to a structure obtained from
65264 ** "sqlite3ParserAlloc" which describes the current state of the parser.
65265 ** The second argument is the major token number. The third is
65266 ** the minor token. The fourth optional argument is whatever the
65267 ** user wants (and specified in the grammar) and is available for
65268 ** use by the action routines.
65270 ** Inputs:
65271 ** <ul>
65272 ** <li> A pointer to the parser (an opaque structure.)
65273 ** <li> The major token number.
65274 ** <li> The minor token number.
65275 ** <li> An option argument of a grammar-specified type.
65276 ** </ul>
65278 ** Outputs:
65279 ** None.
65281 static void sqlite3Parser(
65282 void *yyp, /* The parser */
65283 int yymajor, /* The major token code number */
65284 sqlite3ParserTOKENTYPE yyminor /* The value for the token */
65285 sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
65287 YYMINORTYPE yyminorunion;
65288 int yyact; /* The parser action. */
65289 int yyendofinput; /* True if we are at the end of input */
65290 int yyerrorhit = 0; /* True if yymajor has invoked an error */
65291 yyParser *yypParser; /* The parser */
65293 /* (re)initialize the parser, if necessary */
65294 yypParser = (yyParser*)yyp;
65295 if( yypParser->yyidx<0 ){
65296 #if YYSTACKDEPTH<=0
65297 if( yypParser->yystksz <=0 ){
65298 memset(&yyminorunion, 0, sizeof(yyminorunion));
65299 yyStackOverflow(yypParser, &yyminorunion);
65300 return;
65302 #endif
65303 yypParser->yyidx = 0;
65304 yypParser->yyerrcnt = -1;
65305 yypParser->yystack[0].stateno = 0;
65306 yypParser->yystack[0].major = 0;
65308 yyminorunion.yy0 = yyminor;
65309 yyendofinput = (yymajor==0);
65310 sqlite3ParserARG_STORE;
65312 #ifndef NDEBUG
65313 if( yyTraceFILE ){
65314 fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
65316 #endif
65319 yyact = yy_find_shift_action(yypParser,yymajor);
65320 if( yyact<YYNSTATE ){
65321 yy_shift(yypParser,yyact,yymajor,&yyminorunion);
65322 yypParser->yyerrcnt--;
65323 if( yyendofinput && yypParser->yyidx>=0 ){
65324 yymajor = 0;
65325 }else{
65326 yymajor = YYNOCODE;
65328 }else if( yyact < YYNSTATE + YYNRULE ){
65329 yy_reduce(yypParser,yyact-YYNSTATE);
65330 }else if( yyact == YY_ERROR_ACTION ){
65331 int yymx;
65332 #ifndef NDEBUG
65333 if( yyTraceFILE ){
65334 fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
65336 #endif
65337 #ifdef YYERRORSYMBOL
65338 /* A syntax error has occurred.
65339 ** The response to an error depends upon whether or not the
65340 ** grammar defines an error token "ERROR".
65342 ** This is what we do if the grammar does define ERROR:
65344 ** * Call the %syntax_error function.
65346 ** * Begin popping the stack until we enter a state where
65347 ** it is legal to shift the error symbol, then shift
65348 ** the error symbol.
65350 ** * Set the error count to three.
65352 ** * Begin accepting and shifting new tokens. No new error
65353 ** processing will occur until three tokens have been
65354 ** shifted successfully.
65357 if( yypParser->yyerrcnt<0 ){
65358 yy_syntax_error(yypParser,yymajor,yyminorunion);
65360 yymx = yypParser->yystack[yypParser->yyidx].major;
65361 if( yymx==YYERRORSYMBOL || yyerrorhit ){
65362 #ifndef NDEBUG
65363 if( yyTraceFILE ){
65364 fprintf(yyTraceFILE,"%sDiscard input token %s\n",
65365 yyTracePrompt,yyTokenName[yymajor]);
65367 #endif
65368 yy_destructor(yymajor,&yyminorunion);
65369 yymajor = YYNOCODE;
65370 }else{
65371 while(
65372 yypParser->yyidx >= 0 &&
65373 yymx != YYERRORSYMBOL &&
65374 (yyact = yy_find_reduce_action(
65375 yypParser->yystack[yypParser->yyidx].stateno,
65376 YYERRORSYMBOL)) >= YYNSTATE
65378 yy_pop_parser_stack(yypParser);
65380 if( yypParser->yyidx < 0 || yymajor==0 ){
65381 yy_destructor(yymajor,&yyminorunion);
65382 yy_parse_failed(yypParser);
65383 yymajor = YYNOCODE;
65384 }else if( yymx!=YYERRORSYMBOL ){
65385 YYMINORTYPE u2;
65386 u2.YYERRSYMDT = 0;
65387 yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
65390 yypParser->yyerrcnt = 3;
65391 yyerrorhit = 1;
65392 #else /* YYERRORSYMBOL is not defined */
65393 /* This is what we do if the grammar does not define ERROR:
65395 ** * Report an error message, and throw away the input token.
65397 ** * If the input token is $, then fail the parse.
65399 ** As before, subsequent error messages are suppressed until
65400 ** three input tokens have been successfully shifted.
65402 if( yypParser->yyerrcnt<=0 ){
65403 yy_syntax_error(yypParser,yymajor,yyminorunion);
65405 yypParser->yyerrcnt = 3;
65406 yy_destructor(yymajor,&yyminorunion);
65407 if( yyendofinput ){
65408 yy_parse_failed(yypParser);
65410 yymajor = YYNOCODE;
65411 #endif
65412 }else{
65413 yy_accept(yypParser);
65414 yymajor = YYNOCODE;
65416 }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
65417 return;
65420 /************** End of parse.c ***********************************************/
65421 /************** Begin file tokenize.c ****************************************/
65423 ** 2001 September 15
65425 ** The author disclaims copyright to this source code. In place of
65426 ** a legal notice, here is a blessing:
65428 ** May you do good and not evil.
65429 ** May you find forgiveness for yourself and forgive others.
65430 ** May you share freely, never taking more than you give.
65432 *************************************************************************
65433 ** An tokenizer for SQL
65435 ** This file contains C code that splits an SQL input string up into
65436 ** individual tokens and sends those tokens one-by-one over to the
65437 ** parser for analysis.
65439 ** $Id: tokenize.c,v 1.129 2007/05/15 14:34:32 drh Exp $
65443 ** The charMap() macro maps alphabetic characters into their
65444 ** lower-case ASCII equivalent. On ASCII machines, this is just
65445 ** an upper-to-lower case map. On EBCDIC machines we also need
65446 ** to adjust the encoding. Only alphabetic characters and underscores
65447 ** need to be translated.
65449 #ifdef SQLITE_ASCII
65450 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
65451 #endif
65452 #ifdef SQLITE_EBCDIC
65453 # define charMap(X) ebcdicToAscii[(unsigned char)X]
65454 const unsigned char ebcdicToAscii[] = {
65455 /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
65456 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
65457 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
65458 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
65459 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
65460 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
65461 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
65462 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
65463 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
65464 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
65465 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
65466 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
65467 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
65468 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
65469 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
65470 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
65471 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
65473 #endif
65476 ** The sqlite3KeywordCode function looks up an identifier to determine if
65477 ** it is a keyword. If it is a keyword, the token code of that keyword is
65478 ** returned. If the input is not a keyword, TK_ID is returned.
65480 ** The implementation of this routine was generated by a program,
65481 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
65482 ** The output of the mkkeywordhash.c program is written into a file
65483 ** named keywordhash.h and then included into this source file by
65484 ** the #include below.
65486 /************** Include keywordhash.h in the middle of tokenize.c ************/
65487 /************** Begin file keywordhash.h *************************************/
65488 /***** This file contains automatically generated code ******
65490 ** The code in this file has been automatically generated by
65492 ** $Header: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.30 2007/05/04 18:30:41 drh Exp $
65494 ** The code in this file implements a function that determines whether
65495 ** or not a given identifier is really an SQL keyword. The same thing
65496 ** might be implemented more directly using a hand-written hash table.
65497 ** But by using this automatically generated code, the size of the code
65498 ** is substantially reduced. This is important for embedded applications
65499 ** on platforms with limited memory.
65501 /* Hash score: 165 */
65502 static int keywordCode(const char *z, int n){
65503 /* zText[] encodes 775 bytes of keywords in 526 bytes */
65504 static const char zText[526] =
65505 "BEFOREIGNOREGEXPLAINSTEADDESCAPEACHECKEYCONSTRAINTERSECTABLEFT"
65506 "HENDATABASELECTRANSACTIONATURALTERAISELSEXCEPTRIGGEREFERENCES"
65507 "UNIQUERYATTACHAVINGROUPDATEMPORARYBEGINNEREINDEXCLUSIVEXISTSBETWEEN"
65508 "OTNULLIKECASCADEFERRABLECASECOLLATECREATECURRENT_DATEDELETEDETACH"
65509 "IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN"
65510 "WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICT"
65511 "CROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOB"
65512 "YIFINTOFFSETISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUM"
65513 "VIEWINITIALLY";
65514 static const unsigned char aHash[127] = {
65515 63, 92, 109, 61, 0, 38, 0, 0, 69, 0, 64, 0, 0,
65516 102, 4, 65, 7, 0, 108, 72, 103, 99, 0, 22, 0, 0,
65517 113, 0, 111, 106, 0, 18, 80, 0, 1, 0, 0, 56, 57,
65518 0, 55, 11, 0, 33, 77, 89, 0, 110, 88, 0, 0, 45,
65519 0, 90, 54, 0, 20, 0, 114, 34, 19, 0, 10, 97, 28,
65520 83, 0, 0, 116, 93, 47, 115, 41, 12, 44, 0, 78, 0,
65521 87, 29, 0, 86, 0, 0, 0, 82, 79, 84, 75, 96, 6,
65522 14, 95, 0, 68, 0, 21, 76, 98, 27, 0, 112, 67, 104,
65523 49, 40, 71, 0, 0, 81, 100, 0, 107, 0, 15, 0, 0,
65524 24, 0, 73, 42, 50, 0, 16, 48, 0, 37,
65526 static const unsigned char aNext[116] = {
65527 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0,
65528 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0,
65529 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0,
65530 17, 0, 0, 0, 36, 39, 0, 0, 25, 0, 0, 31, 0,
65531 0, 0, 43, 52, 0, 0, 0, 53, 0, 0, 0, 0, 0,
65532 0, 0, 0, 0, 51, 0, 0, 0, 0, 26, 0, 8, 46,
65533 2, 0, 0, 0, 0, 0, 0, 0, 3, 58, 66, 0, 13,
65534 0, 91, 85, 0, 94, 0, 74, 0, 0, 62, 0, 35, 101,
65535 0, 0, 105, 23, 30, 60, 70, 0, 0, 59, 0, 0,
65537 static const unsigned char aLen[116] = {
65538 6, 7, 3, 6, 6, 7, 7, 3, 4, 6, 4, 5, 3,
65539 10, 9, 5, 4, 4, 3, 8, 2, 6, 11, 2, 7, 5,
65540 5, 4, 6, 7, 10, 6, 5, 6, 6, 5, 6, 4, 9,
65541 2, 5, 5, 7, 5, 9, 6, 7, 7, 3, 4, 4, 7,
65542 3, 10, 4, 7, 6, 12, 6, 6, 9, 4, 6, 5, 4,
65543 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
65544 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
65545 2, 4, 4, 4, 4, 4, 2, 2, 4, 6, 2, 3, 6,
65546 5, 8, 5, 5, 8, 3, 5, 5, 6, 4, 9, 3,
65548 static const unsigned short int aOffset[116] = {
65549 0, 2, 2, 6, 10, 13, 18, 23, 25, 26, 31, 33, 37,
65550 40, 47, 55, 58, 61, 63, 65, 70, 71, 76, 85, 86, 91,
65551 95, 99, 102, 107, 113, 123, 126, 131, 136, 141, 144, 148, 148,
65552 152, 157, 160, 164, 166, 169, 177, 183, 189, 189, 192, 195, 199,
65553 200, 204, 214, 218, 225, 231, 243, 249, 255, 264, 266, 272, 277,
65554 279, 286, 291, 296, 302, 308, 313, 317, 320, 326, 330, 337, 339,
65555 346, 348, 350, 359, 363, 369, 375, 383, 388, 388, 404, 411, 418,
65556 419, 426, 430, 434, 438, 442, 445, 447, 449, 452, 452, 455, 458,
65557 464, 468, 476, 480, 485, 493, 496, 501, 506, 512, 516, 521,
65559 static const unsigned char aCode[116] = {
65560 TK_BEFORE, TK_FOREIGN, TK_FOR, TK_IGNORE, TK_LIKE_KW,
65561 TK_EXPLAIN, TK_INSTEAD, TK_ADD, TK_DESC, TK_ESCAPE,
65562 TK_EACH, TK_CHECK, TK_KEY, TK_CONSTRAINT, TK_INTERSECT,
65563 TK_TABLE, TK_JOIN_KW, TK_THEN, TK_END, TK_DATABASE,
65564 TK_AS, TK_SELECT, TK_TRANSACTION,TK_ON, TK_JOIN_KW,
65565 TK_ALTER, TK_RAISE, TK_ELSE, TK_EXCEPT, TK_TRIGGER,
65566 TK_REFERENCES, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
65567 TK_GROUP, TK_UPDATE, TK_TEMP, TK_TEMP, TK_OR,
65568 TK_BEGIN, TK_JOIN_KW, TK_REINDEX, TK_INDEX, TK_EXCLUSIVE,
65569 TK_EXISTS, TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NULL,
65570 TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DEFERRABLE, TK_CASE,
65571 TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DELETE, TK_DETACH,
65572 TK_IMMEDIATE, TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN,
65573 TK_ANALYZE, TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL,
65574 TK_LIMIT, TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER,
65575 TK_REPLACE, TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO,
65576 TK_IN, TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT,
65577 TK_JOIN_KW, TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED,
65578 TK_DISTINCT, TK_IS, TK_DROP, TK_FAIL, TK_FROM,
65579 TK_JOIN_KW, TK_LIKE_KW, TK_BY, TK_IF, TK_INTO,
65580 TK_OFFSET, TK_OF, TK_SET, TK_ISNULL, TK_ORDER,
65581 TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
65582 TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
65583 TK_ALL,
65585 int h, i;
65586 if( n<2 ) return TK_ID;
65587 h = ((charMap(z[0])*4) ^
65588 (charMap(z[n-1])*3) ^
65589 n) % 127;
65590 for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
65591 if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
65592 return aCode[i];
65595 return TK_ID;
65597 static int sqlite3KeywordCode(const unsigned char *z, int n){
65598 return keywordCode((char*)z, n);
65601 /************** End of keywordhash.h *****************************************/
65602 /************** Continuing where we left off in tokenize.c *******************/
65606 ** If X is a character that can be used in an identifier then
65607 ** IdChar(X) will be true. Otherwise it is false.
65609 ** For ASCII, any character with the high-order bit set is
65610 ** allowed in an identifier. For 7-bit characters,
65611 ** sqlite3IsIdChar[X] must be 1.
65613 ** For EBCDIC, the rules are more complex but have the same
65614 ** end result.
65616 ** Ticket #1066. the SQL standard does not allow '$' in the
65617 ** middle of identfiers. But many SQL implementations do.
65618 ** SQLite will allow '$' in identifiers for compatibility.
65619 ** But the feature is undocumented.
65621 #ifdef SQLITE_ASCII
65622 const char sqlite3IsIdChar[] = {
65623 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
65624 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
65625 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
65626 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
65627 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
65628 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
65629 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
65631 #define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsIdChar[c-0x20]))
65632 #endif
65633 #ifdef SQLITE_EBCDIC
65634 const char sqlite3IsIdChar[] = {
65635 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
65636 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
65637 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
65638 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
65639 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
65640 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
65641 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
65642 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
65643 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
65644 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
65645 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
65646 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
65647 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
65649 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsIdChar[c-0x40]))
65650 #endif
65654 ** Return the length of the token that begins at z[0].
65655 ** Store the token type in *tokenType before returning.
65657 static int getToken(const unsigned char *z, int *tokenType){
65658 int i, c;
65659 switch( *z ){
65660 case ' ': case '\t': case '\n': case '\f': case '\r': {
65661 for(i=1; isspace(z[i]); i++){}
65662 *tokenType = TK_SPACE;
65663 return i;
65665 case '-': {
65666 if( z[1]=='-' ){
65667 for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
65668 *tokenType = TK_COMMENT;
65669 return i;
65671 *tokenType = TK_MINUS;
65672 return 1;
65674 case '(': {
65675 *tokenType = TK_LP;
65676 return 1;
65678 case ')': {
65679 *tokenType = TK_RP;
65680 return 1;
65682 case ';': {
65683 *tokenType = TK_SEMI;
65684 return 1;
65686 case '+': {
65687 *tokenType = TK_PLUS;
65688 return 1;
65690 case '*': {
65691 *tokenType = TK_STAR;
65692 return 1;
65694 case '/': {
65695 if( z[1]!='*' || z[2]==0 ){
65696 *tokenType = TK_SLASH;
65697 return 1;
65699 for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
65700 if( c ) i++;
65701 *tokenType = TK_COMMENT;
65702 return i;
65704 case '%': {
65705 *tokenType = TK_REM;
65706 return 1;
65708 case '=': {
65709 *tokenType = TK_EQ;
65710 return 1 + (z[1]=='=');
65712 case '<': {
65713 if( (c=z[1])=='=' ){
65714 *tokenType = TK_LE;
65715 return 2;
65716 }else if( c=='>' ){
65717 *tokenType = TK_NE;
65718 return 2;
65719 }else if( c=='<' ){
65720 *tokenType = TK_LSHIFT;
65721 return 2;
65722 }else{
65723 *tokenType = TK_LT;
65724 return 1;
65727 case '>': {
65728 if( (c=z[1])=='=' ){
65729 *tokenType = TK_GE;
65730 return 2;
65731 }else if( c=='>' ){
65732 *tokenType = TK_RSHIFT;
65733 return 2;
65734 }else{
65735 *tokenType = TK_GT;
65736 return 1;
65739 case '!': {
65740 if( z[1]!='=' ){
65741 *tokenType = TK_ILLEGAL;
65742 return 2;
65743 }else{
65744 *tokenType = TK_NE;
65745 return 2;
65748 case '|': {
65749 if( z[1]!='|' ){
65750 *tokenType = TK_BITOR;
65751 return 1;
65752 }else{
65753 *tokenType = TK_CONCAT;
65754 return 2;
65757 case ',': {
65758 *tokenType = TK_COMMA;
65759 return 1;
65761 case '&': {
65762 *tokenType = TK_BITAND;
65763 return 1;
65765 case '~': {
65766 *tokenType = TK_BITNOT;
65767 return 1;
65769 case '`':
65770 case '\'':
65771 case '"': {
65772 int delim = z[0];
65773 for(i=1; (c=z[i])!=0; i++){
65774 if( c==delim ){
65775 if( z[i+1]==delim ){
65776 i++;
65777 }else{
65778 break;
65782 if( c ){
65783 *tokenType = TK_STRING;
65784 return i+1;
65785 }else{
65786 *tokenType = TK_ILLEGAL;
65787 return i;
65790 case '.': {
65791 #ifndef SQLITE_OMIT_FLOATING_POINT
65792 if( !isdigit(z[1]) )
65793 #endif
65795 *tokenType = TK_DOT;
65796 return 1;
65798 /* If the next character is a digit, this is a floating point
65799 ** number that begins with ".". Fall thru into the next case */
65801 case '0': case '1': case '2': case '3': case '4':
65802 case '5': case '6': case '7': case '8': case '9': {
65803 *tokenType = TK_INTEGER;
65804 for(i=0; isdigit(z[i]); i++){}
65805 #ifndef SQLITE_OMIT_FLOATING_POINT
65806 if( z[i]=='.' ){
65807 i++;
65808 while( isdigit(z[i]) ){ i++; }
65809 *tokenType = TK_FLOAT;
65811 if( (z[i]=='e' || z[i]=='E') &&
65812 ( isdigit(z[i+1])
65813 || ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
65816 i += 2;
65817 while( isdigit(z[i]) ){ i++; }
65818 *tokenType = TK_FLOAT;
65820 #endif
65821 while( IdChar(z[i]) ){
65822 *tokenType = TK_ILLEGAL;
65823 i++;
65825 return i;
65827 case '[': {
65828 for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
65829 *tokenType = TK_ID;
65830 return i;
65832 case '?': {
65833 *tokenType = TK_VARIABLE;
65834 for(i=1; isdigit(z[i]); i++){}
65835 return i;
65837 case '#': {
65838 for(i=1; isdigit(z[i]); i++){}
65839 if( i>1 ){
65840 /* Parameters of the form #NNN (where NNN is a number) are used
65841 ** internally by sqlite3NestedParse. */
65842 *tokenType = TK_REGISTER;
65843 return i;
65845 /* Fall through into the next case if the '#' is not followed by
65846 ** a digit. Try to match #AAAA where AAAA is a parameter name. */
65848 #ifndef SQLITE_OMIT_TCL_VARIABLE
65849 case '$':
65850 #endif
65851 case '@': /* For compatibility with MS SQL Server */
65852 case ':': {
65853 int n = 0;
65854 *tokenType = TK_VARIABLE;
65855 for(i=1; (c=z[i])!=0; i++){
65856 if( IdChar(c) ){
65857 n++;
65858 #ifndef SQLITE_OMIT_TCL_VARIABLE
65859 }else if( c=='(' && n>0 ){
65861 i++;
65862 }while( (c=z[i])!=0 && !isspace(c) && c!=')' );
65863 if( c==')' ){
65864 i++;
65865 }else{
65866 *tokenType = TK_ILLEGAL;
65868 break;
65869 }else if( c==':' && z[i+1]==':' ){
65870 i++;
65871 #endif
65872 }else{
65873 break;
65876 if( n==0 ) *tokenType = TK_ILLEGAL;
65877 return i;
65879 #ifndef SQLITE_OMIT_BLOB_LITERAL
65880 case 'x': case 'X': {
65881 if( (c=z[1])=='\'' || c=='"' ){
65882 int delim = c;
65883 *tokenType = TK_BLOB;
65884 for(i=2; (c=z[i])!=0; i++){
65885 if( c==delim ){
65886 if( i%2 ) *tokenType = TK_ILLEGAL;
65887 break;
65889 if( !isxdigit(c) ){
65890 *tokenType = TK_ILLEGAL;
65891 return i;
65894 if( c ) i++;
65895 return i;
65897 /* Otherwise fall through to the next case */
65899 #endif
65900 default: {
65901 if( !IdChar(*z) ){
65902 break;
65904 for(i=1; IdChar(z[i]); i++){}
65905 *tokenType = keywordCode((char*)z, i);
65906 return i;
65909 *tokenType = TK_ILLEGAL;
65910 return 1;
65912 static int sqlite3GetToken(const unsigned char *z, int *tokenType){
65913 return getToken(z, tokenType);
65917 ** Run the parser on the given SQL string. The parser structure is
65918 ** passed in. An SQLITE_ status code is returned. If an error occurs
65919 ** and pzErrMsg!=NULL then an error message might be written into
65920 ** memory obtained from malloc() and *pzErrMsg made to point to that
65921 ** error message. Or maybe not.
65923 static int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
65924 int nErr = 0;
65925 int i;
65926 void *pEngine;
65927 int tokenType;
65928 int lastTokenParsed = -1;
65929 sqlite3 *db = pParse->db;
65930 extern void *sqlite3ParserAlloc(void*(*)(size_t));
65931 extern void sqlite3ParserFree(void*, void(*)(void*));
65932 extern void sqlite3Parser(void*, int, Token, Parse*);
65934 if( db->activeVdbeCnt==0 ){
65935 db->u1.isInterrupted = 0;
65937 pParse->rc = SQLITE_OK;
65938 i = 0;
65939 pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3MallocX);
65940 if( pEngine==0 ){
65941 return SQLITE_NOMEM;
65943 assert( pParse->sLastToken.dyn==0 );
65944 assert( pParse->pNewTable==0 );
65945 assert( pParse->pNewTrigger==0 );
65946 assert( pParse->nVar==0 );
65947 assert( pParse->nVarExpr==0 );
65948 assert( pParse->nVarExprAlloc==0 );
65949 assert( pParse->apVarExpr==0 );
65950 pParse->zTail = pParse->zSql = zSql;
65951 while( !sqlite3MallocFailed() && zSql[i]!=0 ){
65952 assert( i>=0 );
65953 pParse->sLastToken.z = (u8*)&zSql[i];
65954 assert( pParse->sLastToken.dyn==0 );
65955 pParse->sLastToken.n = getToken((unsigned char*)&zSql[i],&tokenType);
65956 i += pParse->sLastToken.n;
65957 if( i>SQLITE_MAX_SQL_LENGTH ){
65958 pParse->rc = SQLITE_TOOBIG;
65959 break;
65961 switch( tokenType ){
65962 case TK_SPACE:
65963 case TK_COMMENT: {
65964 if( db->u1.isInterrupted ){
65965 pParse->rc = SQLITE_INTERRUPT;
65966 sqlite3SetString(pzErrMsg, "interrupt", (char*)0);
65967 goto abort_parse;
65969 break;
65971 case TK_ILLEGAL: {
65972 if( pzErrMsg ){
65973 sqliteFree(*pzErrMsg);
65974 *pzErrMsg = sqlite3MPrintf("unrecognized token: \"%T\"",
65975 &pParse->sLastToken);
65977 nErr++;
65978 goto abort_parse;
65980 case TK_SEMI: {
65981 pParse->zTail = &zSql[i];
65982 /* Fall thru into the default case */
65984 default: {
65985 sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
65986 lastTokenParsed = tokenType;
65987 if( pParse->rc!=SQLITE_OK ){
65988 goto abort_parse;
65990 break;
65994 abort_parse:
65995 if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
65996 if( lastTokenParsed!=TK_SEMI ){
65997 sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
65998 pParse->zTail = &zSql[i];
66000 sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
66002 sqlite3ParserFree(pEngine, sqlite3FreeX);
66003 if( sqlite3MallocFailed() ){
66004 pParse->rc = SQLITE_NOMEM;
66006 if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
66007 sqlite3SetString(&pParse->zErrMsg, sqlite3ErrStr(pParse->rc), (char*)0);
66009 if( pParse->zErrMsg ){
66010 if( pzErrMsg && *pzErrMsg==0 ){
66011 *pzErrMsg = pParse->zErrMsg;
66012 }else{
66013 sqliteFree(pParse->zErrMsg);
66015 pParse->zErrMsg = 0;
66016 if( !nErr ) nErr++;
66018 if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
66019 sqlite3VdbeDelete(pParse->pVdbe);
66020 pParse->pVdbe = 0;
66022 #ifndef SQLITE_OMIT_SHARED_CACHE
66023 if( pParse->nested==0 ){
66024 sqliteFree(pParse->aTableLock);
66025 pParse->aTableLock = 0;
66026 pParse->nTableLock = 0;
66028 #endif
66030 if( !IN_DECLARE_VTAB ){
66031 /* If the pParse->declareVtab flag is set, do not delete any table
66032 ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
66033 ** will take responsibility for freeing the Table structure.
66035 sqlite3DeleteTable(pParse->pNewTable);
66038 sqlite3DeleteTrigger(pParse->pNewTrigger);
66039 sqliteFree(pParse->apVarExpr);
66040 if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
66041 pParse->rc = SQLITE_ERROR;
66043 return nErr;
66046 /************** End of tokenize.c ********************************************/
66047 /************** Begin file main.c ********************************************/
66049 ** 2001 September 15
66051 ** The author disclaims copyright to this source code. In place of
66052 ** a legal notice, here is a blessing:
66054 ** May you do good and not evil.
66055 ** May you find forgiveness for yourself and forgive others.
66056 ** May you share freely, never taking more than you give.
66058 *************************************************************************
66059 ** Main file for the SQLite library. The routines in this file
66060 ** implement the programmer interface to the library. Routines in
66061 ** other files are for internal use by SQLite and should not be
66062 ** accessed by users of the library.
66064 ** $Id: main.c,v 1.376 2007/05/08 20:37:39 drh Exp $
66068 ** The version of the library
66070 const char sqlite3_version[] = SQLITE_VERSION;
66071 const char *sqlite3_libversion(void){ return sqlite3_version; }
66072 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
66075 ** If the following function pointer is not NULL and if
66076 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
66077 ** I/O active are written using this function. These messages
66078 ** are intended for debugging activity only.
66080 void (*sqlite3_io_trace)(const char*, ...) = 0;
66083 ** If the following global variable points to a string which is the
66084 ** name of a directory, then that directory will be used to store
66085 ** temporary files.
66087 ** See also the "PRAGMA temp_store_directory" SQL command.
66089 char *sqlite3_temp_directory = 0;
66093 ** This is the default collating function named "BINARY" which is always
66094 ** available.
66096 static int binCollFunc(
66097 void *NotUsed,
66098 int nKey1, const void *pKey1,
66099 int nKey2, const void *pKey2
66101 int rc, n;
66102 n = nKey1<nKey2 ? nKey1 : nKey2;
66103 rc = memcmp(pKey1, pKey2, n);
66104 if( rc==0 ){
66105 rc = nKey1 - nKey2;
66107 return rc;
66111 ** Another built-in collating sequence: NOCASE.
66113 ** This collating sequence is intended to be used for "case independant
66114 ** comparison". SQLite's knowledge of upper and lower case equivalents
66115 ** extends only to the 26 characters used in the English language.
66117 ** At the moment there is only a UTF-8 implementation.
66119 static int nocaseCollatingFunc(
66120 void *NotUsed,
66121 int nKey1, const void *pKey1,
66122 int nKey2, const void *pKey2
66124 int r = sqlite3StrNICmp(
66125 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
66126 if( 0==r ){
66127 r = nKey1-nKey2;
66129 return r;
66133 ** Return the ROWID of the most recent insert
66135 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
66136 return db->lastRowid;
66140 ** Return the number of changes in the most recent call to sqlite3_exec().
66142 int sqlite3_changes(sqlite3 *db){
66143 return db->nChange;
66147 ** Return the number of changes since the database handle was opened.
66149 int sqlite3_total_changes(sqlite3 *db){
66150 return db->nTotalChange;
66154 ** Close an existing SQLite database
66156 int sqlite3_close(sqlite3 *db){
66157 HashElem *i;
66158 int j;
66160 if( !db ){
66161 return SQLITE_OK;
66163 if( sqlite3SafetyCheck(db) ){
66164 return SQLITE_MISUSE;
66167 #ifdef SQLITE_SSE
66169 extern void sqlite3SseCleanup(sqlite3*);
66170 sqlite3SseCleanup(db);
66172 #endif
66174 sqlite3ResetInternalSchema(db, 0);
66176 /* If a transaction is open, the ResetInternalSchema() call above
66177 ** will not have called the xDisconnect() method on any virtual
66178 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
66179 ** call will do so. We need to do this before the check for active
66180 ** SQL statements below, as the v-table implementation may be storing
66181 ** some prepared statements internally.
66183 sqlite3VtabRollback(db);
66185 /* If there are any outstanding VMs, return SQLITE_BUSY. */
66186 if( db->pVdbe ){
66187 sqlite3Error(db, SQLITE_BUSY,
66188 "Unable to close due to unfinalised statements");
66189 return SQLITE_BUSY;
66191 assert( !sqlite3SafetyCheck(db) );
66193 /* FIX ME: db->magic may be set to SQLITE_MAGIC_CLOSED if the database
66194 ** cannot be opened for some reason. So this routine needs to run in
66195 ** that case. But maybe there should be an extra magic value for the
66196 ** "failed to open" state.
66198 ** TODO: Coverage tests do not test the case where this condition is
66199 ** true. It's hard to see how to cause it without messing with threads.
66201 if( db->magic!=SQLITE_MAGIC_CLOSED && sqlite3SafetyOn(db) ){
66202 /* printf("DID NOT CLOSE\n"); fflush(stdout); */
66203 return SQLITE_ERROR;
66206 for(j=0; j<db->nDb; j++){
66207 struct Db *pDb = &db->aDb[j];
66208 if( pDb->pBt ){
66209 sqlite3BtreeClose(pDb->pBt);
66210 pDb->pBt = 0;
66211 if( j!=1 ){
66212 pDb->pSchema = 0;
66216 sqlite3ResetInternalSchema(db, 0);
66217 assert( db->nDb<=2 );
66218 assert( db->aDb==db->aDbStatic );
66219 for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
66220 FuncDef *pFunc, *pNext;
66221 for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
66222 pNext = pFunc->pNext;
66223 sqliteFree(pFunc);
66227 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
66228 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
66229 /* Invoke any destructors registered for collation sequence user data. */
66230 for(j=0; j<3; j++){
66231 if( pColl[j].xDel ){
66232 pColl[j].xDel(pColl[j].pUser);
66235 sqliteFree(pColl);
66237 sqlite3HashClear(&db->aCollSeq);
66238 #ifndef SQLITE_OMIT_VIRTUALTABLE
66239 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
66240 Module *pMod = (Module *)sqliteHashData(i);
66241 sqliteFree(pMod);
66243 sqlite3HashClear(&db->aModule);
66244 #endif
66246 sqlite3HashClear(&db->aFunc);
66247 sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
66248 if( db->pErr ){
66249 sqlite3ValueFree(db->pErr);
66251 sqlite3CloseExtensions(db);
66253 db->magic = SQLITE_MAGIC_ERROR;
66255 /* The temp-database schema is allocated differently from the other schema
66256 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
66257 ** So it needs to be freed here. Todo: Why not roll the temp schema into
66258 ** the same sqliteMalloc() as the one that allocates the database
66259 ** structure?
66261 sqliteFree(db->aDb[1].pSchema);
66262 sqliteFree(db);
66263 sqlite3ReleaseThreadData();
66264 return SQLITE_OK;
66268 ** Rollback all database files.
66270 static void sqlite3RollbackAll(sqlite3 *db){
66271 int i;
66272 int inTrans = 0;
66273 for(i=0; i<db->nDb; i++){
66274 if( db->aDb[i].pBt ){
66275 if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
66276 inTrans = 1;
66278 sqlite3BtreeRollback(db->aDb[i].pBt);
66279 db->aDb[i].inTrans = 0;
66282 sqlite3VtabRollback(db);
66283 if( db->flags&SQLITE_InternChanges ){
66284 sqlite3ResetInternalSchema(db, 0);
66287 /* If one has been configured, invoke the rollback-hook callback */
66288 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
66289 db->xRollbackCallback(db->pRollbackArg);
66294 ** Return a static string that describes the kind of error specified in the
66295 ** argument.
66297 static const char *sqlite3ErrStr(int rc){
66298 const char *z;
66299 switch( rc & 0xff ){
66300 case SQLITE_ROW:
66301 case SQLITE_DONE:
66302 case SQLITE_OK: z = "not an error"; break;
66303 case SQLITE_ERROR: z = "SQL logic error or missing database"; break;
66304 case SQLITE_PERM: z = "access permission denied"; break;
66305 case SQLITE_ABORT: z = "callback requested query abort"; break;
66306 case SQLITE_BUSY: z = "database is locked"; break;
66307 case SQLITE_LOCKED: z = "database table is locked"; break;
66308 case SQLITE_NOMEM: z = "out of memory"; break;
66309 case SQLITE_READONLY: z = "attempt to write a readonly database"; break;
66310 case SQLITE_INTERRUPT: z = "interrupted"; break;
66311 case SQLITE_IOERR: z = "disk I/O error"; break;
66312 case SQLITE_CORRUPT: z = "database disk image is malformed"; break;
66313 case SQLITE_FULL: z = "database or disk is full"; break;
66314 case SQLITE_CANTOPEN: z = "unable to open database file"; break;
66315 case SQLITE_EMPTY: z = "table contains no data"; break;
66316 case SQLITE_SCHEMA: z = "database schema has changed"; break;
66317 case SQLITE_TOOBIG: z = "String or BLOB exceeded size limit"; break;
66318 case SQLITE_CONSTRAINT: z = "constraint failed"; break;
66319 case SQLITE_MISMATCH: z = "datatype mismatch"; break;
66320 case SQLITE_MISUSE: z = "library routine called out of sequence";break;
66321 case SQLITE_NOLFS: z = "kernel lacks large file support"; break;
66322 case SQLITE_AUTH: z = "authorization denied"; break;
66323 case SQLITE_FORMAT: z = "auxiliary database format error"; break;
66324 case SQLITE_RANGE: z = "bind or column index out of range"; break;
66325 case SQLITE_NOTADB: z = "file is encrypted or is not a database";break;
66326 default: z = "unknown error"; break;
66328 return z;
66332 ** This routine implements a busy callback that sleeps and tries
66333 ** again until a timeout value is reached. The timeout value is
66334 ** an integer number of milliseconds passed in as the first
66335 ** argument.
66337 static int sqliteDefaultBusyCallback(
66338 void *ptr, /* Database connection */
66339 int count /* Number of times table has been busy */
66341 #if OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
66342 static const u8 delays[] =
66343 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
66344 static const u8 totals[] =
66345 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
66346 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
66347 int timeout = ((sqlite3 *)ptr)->busyTimeout;
66348 int delay, prior;
66350 assert( count>=0 );
66351 if( count < NDELAY ){
66352 delay = delays[count];
66353 prior = totals[count];
66354 }else{
66355 delay = delays[NDELAY-1];
66356 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
66358 if( prior + delay > timeout ){
66359 delay = timeout - prior;
66360 if( delay<=0 ) return 0;
66362 sqlite3OsSleep(delay);
66363 return 1;
66364 #else
66365 int timeout = ((sqlite3 *)ptr)->busyTimeout;
66366 if( (count+1)*1000 > timeout ){
66367 return 0;
66369 sqlite3OsSleep(1000);
66370 return 1;
66371 #endif
66375 ** Invoke the given busy handler.
66377 ** This routine is called when an operation failed with a lock.
66378 ** If this routine returns non-zero, the lock is retried. If it
66379 ** returns 0, the operation aborts with an SQLITE_BUSY error.
66381 static int sqlite3InvokeBusyHandler(BusyHandler *p){
66382 int rc;
66383 if( p==0 || p->xFunc==0 || p->nBusy<0 ) return 0;
66384 rc = p->xFunc(p->pArg, p->nBusy);
66385 if( rc==0 ){
66386 p->nBusy = -1;
66387 }else{
66388 p->nBusy++;
66390 return rc;
66394 ** This routine sets the busy callback for an Sqlite database to the
66395 ** given callback function with the given argument.
66397 int sqlite3_busy_handler(
66398 sqlite3 *db,
66399 int (*xBusy)(void*,int),
66400 void *pArg
66402 if( sqlite3SafetyCheck(db) ){
66403 return SQLITE_MISUSE;
66405 db->busyHandler.xFunc = xBusy;
66406 db->busyHandler.pArg = pArg;
66407 db->busyHandler.nBusy = 0;
66408 return SQLITE_OK;
66411 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
66413 ** This routine sets the progress callback for an Sqlite database to the
66414 ** given callback function with the given argument. The progress callback will
66415 ** be invoked every nOps opcodes.
66417 void sqlite3_progress_handler(
66418 sqlite3 *db,
66419 int nOps,
66420 int (*xProgress)(void*),
66421 void *pArg
66423 if( !sqlite3SafetyCheck(db) ){
66424 if( nOps>0 ){
66425 db->xProgress = xProgress;
66426 db->nProgressOps = nOps;
66427 db->pProgressArg = pArg;
66428 }else{
66429 db->xProgress = 0;
66430 db->nProgressOps = 0;
66431 db->pProgressArg = 0;
66435 #endif
66439 ** This routine installs a default busy handler that waits for the
66440 ** specified number of milliseconds before returning 0.
66442 int sqlite3_busy_timeout(sqlite3 *db, int ms){
66443 if( sqlite3SafetyCheck(db) ){
66444 return SQLITE_MISUSE;
66446 if( ms>0 ){
66447 db->busyTimeout = ms;
66448 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
66449 }else{
66450 sqlite3_busy_handler(db, 0, 0);
66452 return SQLITE_OK;
66456 ** Cause any pending operation to stop at its earliest opportunity.
66458 void sqlite3_interrupt(sqlite3 *db){
66459 if( db && (db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_BUSY) ){
66460 db->u1.isInterrupted = 1;
66465 ** Memory allocation routines that use SQLites internal memory
66466 ** memory allocator. Depending on how SQLite is compiled, the
66467 ** internal memory allocator might be just an alias for the
66468 ** system default malloc/realloc/free. Or the built-in allocator
66469 ** might do extra stuff like put sentinals around buffers to
66470 ** check for overruns or look for memory leaks.
66472 ** Use sqlite3_free() to free memory returned by sqlite3_mprintf().
66474 void sqlite3_free(void *p){ if( p ) sqlite3OsFree(p); }
66475 void *sqlite3_malloc(int nByte){ return nByte>0 ? sqlite3OsMalloc(nByte) : 0; }
66476 void *sqlite3_realloc(void *pOld, int nByte){
66477 if( pOld ){
66478 if( nByte>0 ){
66479 return sqlite3OsRealloc(pOld, nByte);
66480 }else{
66481 sqlite3OsFree(pOld);
66482 return 0;
66484 }else{
66485 return sqlite3_malloc(nByte);
66490 ** This function is exactly the same as sqlite3_create_function(), except
66491 ** that it is designed to be called by internal code. The difference is
66492 ** that if a malloc() fails in sqlite3_create_function(), an error code
66493 ** is returned and the mallocFailed flag cleared.
66495 static int sqlite3CreateFunc(
66496 sqlite3 *db,
66497 const char *zFunctionName,
66498 int nArg,
66499 int enc,
66500 void *pUserData,
66501 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
66502 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
66503 void (*xFinal)(sqlite3_context*)
66505 FuncDef *p;
66506 int nName;
66508 if( sqlite3SafetyCheck(db) ){
66509 return SQLITE_MISUSE;
66511 if( zFunctionName==0 ||
66512 (xFunc && (xFinal || xStep)) ||
66513 (!xFunc && (xFinal && !xStep)) ||
66514 (!xFunc && (!xFinal && xStep)) ||
66515 (nArg<-1 || nArg>127) ||
66516 (255<(nName = strlen(zFunctionName))) ){
66517 sqlite3Error(db, SQLITE_ERROR, "bad parameters");
66518 return SQLITE_ERROR;
66521 #ifndef SQLITE_OMIT_UTF16
66522 /* If SQLITE_UTF16 is specified as the encoding type, transform this
66523 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
66524 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
66526 ** If SQLITE_ANY is specified, add three versions of the function
66527 ** to the hash table.
66529 if( enc==SQLITE_UTF16 ){
66530 enc = SQLITE_UTF16NATIVE;
66531 }else if( enc==SQLITE_ANY ){
66532 int rc;
66533 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
66534 pUserData, xFunc, xStep, xFinal);
66535 if( rc!=SQLITE_OK ) return rc;
66536 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
66537 pUserData, xFunc, xStep, xFinal);
66538 if( rc!=SQLITE_OK ) return rc;
66539 enc = SQLITE_UTF16BE;
66541 #else
66542 enc = SQLITE_UTF8;
66543 #endif
66545 /* Check if an existing function is being overridden or deleted. If so,
66546 ** and there are active VMs, then return SQLITE_BUSY. If a function
66547 ** is being overridden/deleted but there are no active VMs, allow the
66548 ** operation to continue but invalidate all precompiled statements.
66550 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
66551 if( p && p->iPrefEnc==enc && p->nArg==nArg ){
66552 if( db->activeVdbeCnt ){
66553 sqlite3Error(db, SQLITE_BUSY,
66554 "Unable to delete/modify user-function due to active statements");
66555 assert( !sqlite3MallocFailed() );
66556 return SQLITE_BUSY;
66557 }else{
66558 sqlite3ExpirePreparedStatements(db);
66562 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
66563 if( p ){
66564 p->flags = 0;
66565 p->xFunc = xFunc;
66566 p->xStep = xStep;
66567 p->xFinalize = xFinal;
66568 p->pUserData = pUserData;
66569 p->nArg = nArg;
66571 return SQLITE_OK;
66575 ** Create new user functions.
66577 int sqlite3_create_function(
66578 sqlite3 *db,
66579 const char *zFunctionName,
66580 int nArg,
66581 int enc,
66582 void *p,
66583 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
66584 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
66585 void (*xFinal)(sqlite3_context*)
66587 int rc;
66588 assert( !sqlite3MallocFailed() );
66589 rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
66591 return sqlite3ApiExit(db, rc);
66594 #ifndef SQLITE_OMIT_UTF16
66595 int sqlite3_create_function16(
66596 sqlite3 *db,
66597 const void *zFunctionName,
66598 int nArg,
66599 int eTextRep,
66600 void *p,
66601 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
66602 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
66603 void (*xFinal)(sqlite3_context*)
66605 int rc;
66606 char *zFunc8;
66607 assert( !sqlite3MallocFailed() );
66609 zFunc8 = sqlite3Utf16to8(zFunctionName, -1);
66610 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
66611 sqliteFree(zFunc8);
66613 return sqlite3ApiExit(db, rc);
66615 #endif
66619 ** Declare that a function has been overloaded by a virtual table.
66621 ** If the function already exists as a regular global function, then
66622 ** this routine is a no-op. If the function does not exist, then create
66623 ** a new one that always throws a run-time error.
66625 ** When virtual tables intend to provide an overloaded function, they
66626 ** should call this routine to make sure the global function exists.
66627 ** A global function must exist in order for name resolution to work
66628 ** properly.
66630 int sqlite3_overload_function(
66631 sqlite3 *db,
66632 const char *zName,
66633 int nArg
66635 int nName = strlen(zName);
66636 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
66637 sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
66638 0, sqlite3InvalidFunction, 0, 0);
66640 return sqlite3ApiExit(db, SQLITE_OK);
66643 #ifndef SQLITE_OMIT_TRACE
66645 ** Register a trace function. The pArg from the previously registered trace
66646 ** is returned.
66648 ** A NULL trace function means that no tracing is executes. A non-NULL
66649 ** trace is a pointer to a function that is invoked at the start of each
66650 ** SQL statement.
66652 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
66653 void *pOld = db->pTraceArg;
66654 db->xTrace = xTrace;
66655 db->pTraceArg = pArg;
66656 return pOld;
66659 ** Register a profile function. The pArg from the previously registered
66660 ** profile function is returned.
66662 ** A NULL profile function means that no profiling is executes. A non-NULL
66663 ** profile is a pointer to a function that is invoked at the conclusion of
66664 ** each SQL statement that is run.
66666 void *sqlite3_profile(
66667 sqlite3 *db,
66668 void (*xProfile)(void*,const char*,sqlite_uint64),
66669 void *pArg
66671 void *pOld = db->pProfileArg;
66672 db->xProfile = xProfile;
66673 db->pProfileArg = pArg;
66674 return pOld;
66676 #endif /* SQLITE_OMIT_TRACE */
66678 /*** EXPERIMENTAL ***
66680 ** Register a function to be invoked when a transaction comments.
66681 ** If the invoked function returns non-zero, then the commit becomes a
66682 ** rollback.
66684 void *sqlite3_commit_hook(
66685 sqlite3 *db, /* Attach the hook to this database */
66686 int (*xCallback)(void*), /* Function to invoke on each commit */
66687 void *pArg /* Argument to the function */
66689 void *pOld = db->pCommitArg;
66690 db->xCommitCallback = xCallback;
66691 db->pCommitArg = pArg;
66692 return pOld;
66696 ** Register a callback to be invoked each time a row is updated,
66697 ** inserted or deleted using this database connection.
66699 void *sqlite3_update_hook(
66700 sqlite3 *db, /* Attach the hook to this database */
66701 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
66702 void *pArg /* Argument to the function */
66704 void *pRet = db->pUpdateArg;
66705 db->xUpdateCallback = xCallback;
66706 db->pUpdateArg = pArg;
66707 return pRet;
66711 ** Register a callback to be invoked each time a transaction is rolled
66712 ** back by this database connection.
66714 void *sqlite3_rollback_hook(
66715 sqlite3 *db, /* Attach the hook to this database */
66716 void (*xCallback)(void*), /* Callback function */
66717 void *pArg /* Argument to the function */
66719 void *pRet = db->pRollbackArg;
66720 db->xRollbackCallback = xCallback;
66721 db->pRollbackArg = pArg;
66722 return pRet;
66726 ** This routine is called to create a connection to a database BTree
66727 ** driver. If zFilename is the name of a file, then that file is
66728 ** opened and used. If zFilename is the magic name ":memory:" then
66729 ** the database is stored in memory (and is thus forgotten as soon as
66730 ** the connection is closed.) If zFilename is NULL then the database
66731 ** is a "virtual" database for transient use only and is deleted as
66732 ** soon as the connection is closed.
66734 ** A virtual database can be either a disk file (that is automatically
66735 ** deleted when the file is closed) or it an be held entirely in memory,
66736 ** depending on the values of the TEMP_STORE compile-time macro and the
66737 ** db->temp_store variable, according to the following chart:
66739 ** TEMP_STORE db->temp_store Location of temporary database
66740 ** ---------- -------------- ------------------------------
66741 ** 0 any file
66742 ** 1 1 file
66743 ** 1 2 memory
66744 ** 1 0 file
66745 ** 2 1 file
66746 ** 2 2 memory
66747 ** 2 0 memory
66748 ** 3 any memory
66750 static int sqlite3BtreeFactory(
66751 const sqlite3 *db, /* Main database when opening aux otherwise 0 */
66752 const char *zFilename, /* Name of the file containing the BTree database */
66753 int omitJournal, /* if TRUE then do not journal this file */
66754 int nCache, /* How many pages in the page cache */
66755 Btree **ppBtree /* Pointer to new Btree object written here */
66757 int btree_flags = 0;
66758 int rc;
66760 assert( ppBtree != 0);
66761 if( omitJournal ){
66762 btree_flags |= BTREE_OMIT_JOURNAL;
66764 if( db->flags & SQLITE_NoReadlock ){
66765 btree_flags |= BTREE_NO_READLOCK;
66767 if( zFilename==0 ){
66768 #if TEMP_STORE==0
66769 /* Do nothing */
66770 #endif
66771 #ifndef SQLITE_OMIT_MEMORYDB
66772 #if TEMP_STORE==1
66773 if( db->temp_store==2 ) zFilename = ":memory:";
66774 #endif
66775 #if TEMP_STORE==2
66776 if( db->temp_store!=1 ) zFilename = ":memory:";
66777 #endif
66778 #if TEMP_STORE==3
66779 zFilename = ":memory:";
66780 #endif
66781 #endif /* SQLITE_OMIT_MEMORYDB */
66784 rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btree_flags);
66785 if( rc==SQLITE_OK ){
66786 sqlite3BtreeSetBusyHandler(*ppBtree, (void*)&db->busyHandler);
66787 sqlite3BtreeSetCacheSize(*ppBtree, nCache);
66789 return rc;
66793 ** Return UTF-8 encoded English language explanation of the most recent
66794 ** error.
66796 const char *sqlite3_errmsg(sqlite3 *db){
66797 const char *z;
66798 assert( !sqlite3MallocFailed() );
66799 if( !db ){
66800 return sqlite3ErrStr(SQLITE_NOMEM);
66802 if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
66803 return sqlite3ErrStr(SQLITE_MISUSE);
66805 z = (char*)sqlite3_value_text(db->pErr);
66806 if( z==0 ){
66807 z = sqlite3ErrStr(db->errCode);
66809 return z;
66812 #ifndef SQLITE_OMIT_UTF16
66814 ** Return UTF-16 encoded English language explanation of the most recent
66815 ** error.
66817 const void *sqlite3_errmsg16(sqlite3 *db){
66818 /* Because all the characters in the string are in the unicode
66819 ** range 0x00-0xFF, if we pad the big-endian string with a
66820 ** zero byte, we can obtain the little-endian string with
66821 ** &big_endian[1].
66823 static const char outOfMemBe[] = {
66824 0, 'o', 0, 'u', 0, 't', 0, ' ',
66825 0, 'o', 0, 'f', 0, ' ',
66826 0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
66828 static const char misuseBe [] = {
66829 0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ',
66830 0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ',
66831 0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ',
66832 0, 'o', 0, 'u', 0, 't', 0, ' ',
66833 0, 'o', 0, 'f', 0, ' ',
66834 0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
66837 const void *z;
66838 assert( !sqlite3MallocFailed() );
66839 if( !db ){
66840 return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
66842 if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
66843 return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
66845 z = sqlite3_value_text16(db->pErr);
66846 if( z==0 ){
66847 sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
66848 SQLITE_UTF8, SQLITE_STATIC);
66849 z = sqlite3_value_text16(db->pErr);
66851 sqlite3ApiExit(0, 0);
66852 return z;
66854 #endif /* SQLITE_OMIT_UTF16 */
66857 ** Return the most recent error code generated by an SQLite routine. If NULL is
66858 ** passed to this function, we assume a malloc() failed during sqlite3_open().
66860 int sqlite3_errcode(sqlite3 *db){
66861 if( !db || sqlite3MallocFailed() ){
66862 return SQLITE_NOMEM;
66864 if( sqlite3SafetyCheck(db) ){
66865 return SQLITE_MISUSE;
66867 return db->errCode & db->errMask;
66871 ** Create a new collating function for database "db". The name is zName
66872 ** and the encoding is enc.
66874 static int createCollation(
66875 sqlite3* db,
66876 const char *zName,
66877 int enc,
66878 void* pCtx,
66879 int(*xCompare)(void*,int,const void*,int,const void*),
66880 void(*xDel)(void*)
66882 CollSeq *pColl;
66883 int enc2;
66885 if( sqlite3SafetyCheck(db) ){
66886 return SQLITE_MISUSE;
66889 /* If SQLITE_UTF16 is specified as the encoding type, transform this
66890 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
66891 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
66893 enc2 = enc & ~SQLITE_UTF16_ALIGNED;
66894 if( enc2==SQLITE_UTF16 ){
66895 enc2 = SQLITE_UTF16NATIVE;
66898 if( (enc2&~3)!=0 ){
66899 sqlite3Error(db, SQLITE_ERROR, "unknown encoding");
66900 return SQLITE_ERROR;
66903 /* Check if this call is removing or replacing an existing collation
66904 ** sequence. If so, and there are active VMs, return busy. If there
66905 ** are no active VMs, invalidate any pre-compiled statements.
66907 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 0);
66908 if( pColl && pColl->xCmp ){
66909 if( db->activeVdbeCnt ){
66910 sqlite3Error(db, SQLITE_BUSY,
66911 "Unable to delete/modify collation sequence due to active statements");
66912 return SQLITE_BUSY;
66914 sqlite3ExpirePreparedStatements(db);
66916 /* If collation sequence pColl was created directly by a call to
66917 ** sqlite3_create_collation, and not generated by synthCollSeq(),
66918 ** then any copies made by synthCollSeq() need to be invalidated.
66919 ** Also, collation destructor - CollSeq.xDel() - function may need
66920 ** to be called.
66922 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
66923 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, strlen(zName));
66924 int j;
66925 for(j=0; j<3; j++){
66926 CollSeq *p = &aColl[j];
66927 if( p->enc==pColl->enc ){
66928 if( p->xDel ){
66929 p->xDel(p->pUser);
66931 p->xCmp = 0;
66937 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 1);
66938 if( pColl ){
66939 pColl->xCmp = xCompare;
66940 pColl->pUser = pCtx;
66941 pColl->xDel = xDel;
66942 pColl->enc = enc2 | (enc & SQLITE_UTF16_ALIGNED);
66944 sqlite3Error(db, SQLITE_OK, 0);
66945 return SQLITE_OK;
66950 ** This routine does the work of opening a database on behalf of
66951 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
66952 ** is UTF-8 encoded.
66954 static int openDatabase(
66955 const char *zFilename, /* Database filename UTF-8 encoded */
66956 sqlite3 **ppDb /* OUT: Returned database handle */
66958 sqlite3 *db;
66959 int rc;
66960 CollSeq *pColl;
66962 assert( !sqlite3MallocFailed() );
66964 /* Allocate the sqlite data structure */
66965 db = sqliteMalloc( sizeof(sqlite3) );
66966 if( db==0 ) goto opendb_out;
66967 db->errMask = 0xff;
66968 db->priorNewRowid = 0;
66969 db->magic = SQLITE_MAGIC_BUSY;
66970 db->nDb = 2;
66971 db->aDb = db->aDbStatic;
66972 db->autoCommit = 1;
66973 db->flags |= SQLITE_ShortColNames
66974 #if SQLITE_DEFAULT_FILE_FORMAT<4
66975 | SQLITE_LegacyFileFmt
66976 #endif
66977 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
66978 | SQLITE_LoadExtension
66979 #endif
66981 sqlite3HashInit(&db->aFunc, SQLITE_HASH_STRING, 0);
66982 sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0);
66983 #ifndef SQLITE_OMIT_VIRTUALTABLE
66984 sqlite3HashInit(&db->aModule, SQLITE_HASH_STRING, 0);
66985 #endif
66987 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
66988 ** and UTF-16, so add a version for each to avoid any unnecessary
66989 ** conversions. The only error that can occur here is a malloc() failure.
66991 if( createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0) ||
66992 createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0) ||
66993 createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0) ||
66994 (db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0))==0
66996 assert( sqlite3MallocFailed() );
66997 db->magic = SQLITE_MAGIC_CLOSED;
66998 goto opendb_out;
67001 /* Also add a UTF-8 case-insensitive collation sequence. */
67002 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
67004 /* Set flags on the built-in collating sequences */
67005 db->pDfltColl->type = SQLITE_COLL_BINARY;
67006 pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
67007 if( pColl ){
67008 pColl->type = SQLITE_COLL_NOCASE;
67011 /* Open the backend database driver */
67012 rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
67013 &db->aDb[0].pBt);
67014 if( rc!=SQLITE_OK ){
67015 sqlite3Error(db, rc, 0);
67016 db->magic = SQLITE_MAGIC_CLOSED;
67017 goto opendb_out;
67019 db->aDb[0].pSchema = sqlite3SchemaGet(db->aDb[0].pBt);
67020 db->aDb[1].pSchema = sqlite3SchemaGet(0);
67023 /* The default safety_level for the main database is 'full'; for the temp
67024 ** database it is 'NONE'. This matches the pager layer defaults.
67026 db->aDb[0].zName = "main";
67027 db->aDb[0].safety_level = 3;
67028 #ifndef SQLITE_OMIT_TEMPDB
67029 db->aDb[1].zName = "temp";
67030 db->aDb[1].safety_level = 1;
67031 #endif
67033 /* Register all built-in functions, but do not attempt to read the
67034 ** database schema yet. This is delayed until the first time the database
67035 ** is accessed.
67037 if( !sqlite3MallocFailed() ){
67038 sqlite3Error(db, SQLITE_OK, 0);
67039 sqlite3RegisterBuiltinFunctions(db);
67041 db->magic = SQLITE_MAGIC_OPEN;
67043 /* Load automatic extensions - extensions that have been registered
67044 ** using the sqlite3_automatic_extension() API.
67046 (void)sqlite3AutoLoadExtensions(db);
67048 #ifdef SQLITE_ENABLE_FTS1
67050 extern int sqlite3Fts1Init(sqlite3*);
67051 sqlite3Fts1Init(db);
67053 #endif
67055 #ifdef SQLITE_ENABLE_FTS2
67057 extern int sqlite3Fts2Init(sqlite3*);
67058 sqlite3Fts2Init(db);
67060 #endif
67062 #ifdef SQLITE_ENABLE_ICU
67063 if( !sqlite3MallocFailed() ){
67064 extern int sqlite3IcuInit(sqlite3*);
67065 sqlite3IcuInit(db);
67067 #endif
67069 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
67070 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
67071 ** mode. Doing nothing at all also makes NORMAL the default.
67073 #ifdef SQLITE_DEFAULT_LOCKING_MODE
67074 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
67075 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
67076 SQLITE_DEFAULT_LOCKING_MODE);
67077 #endif
67079 opendb_out:
67080 if( SQLITE_NOMEM==(rc = sqlite3_errcode(db)) ){
67081 sqlite3_close(db);
67082 db = 0;
67084 *ppDb = db;
67085 return sqlite3ApiExit(0, rc);
67089 ** Open a new database handle.
67091 int sqlite3_open(
67092 const char *zFilename,
67093 sqlite3 **ppDb
67095 return openDatabase(zFilename, ppDb);
67098 #ifndef SQLITE_OMIT_UTF16
67100 ** Open a new database handle.
67102 int sqlite3_open16(
67103 const void *zFilename,
67104 sqlite3 **ppDb
67106 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
67107 int rc = SQLITE_OK;
67108 sqlite3_value *pVal;
67110 assert( zFilename );
67111 assert( ppDb );
67112 *ppDb = 0;
67113 pVal = sqlite3ValueNew();
67114 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
67115 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
67116 if( zFilename8 ){
67117 rc = openDatabase(zFilename8, ppDb);
67118 if( rc==SQLITE_OK && *ppDb ){
67119 rc = sqlite3_exec(*ppDb, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);
67120 if( rc!=SQLITE_OK ){
67121 sqlite3_close(*ppDb);
67122 *ppDb = 0;
67126 sqlite3ValueFree(pVal);
67128 return sqlite3ApiExit(0, rc);
67130 #endif /* SQLITE_OMIT_UTF16 */
67133 ** The following routine destroys a virtual machine that is created by
67134 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
67135 ** success/failure code that describes the result of executing the virtual
67136 ** machine.
67138 ** This routine sets the error code and string returned by
67139 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
67141 int sqlite3_finalize(sqlite3_stmt *pStmt){
67142 int rc;
67143 if( pStmt==0 ){
67144 rc = SQLITE_OK;
67145 }else{
67146 rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
67148 return rc;
67152 ** Terminate the current execution of an SQL statement and reset it
67153 ** back to its starting state so that it can be reused. A success code from
67154 ** the prior execution is returned.
67156 ** This routine sets the error code and string returned by
67157 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
67159 int sqlite3_reset(sqlite3_stmt *pStmt){
67160 int rc;
67161 if( pStmt==0 ){
67162 rc = SQLITE_OK;
67163 }else{
67164 rc = sqlite3VdbeReset((Vdbe*)pStmt);
67165 sqlite3VdbeMakeReady((Vdbe*)pStmt, -1, 0, 0, 0);
67166 assert( (rc & (sqlite3_db_handle(pStmt)->errMask))==rc );
67168 return rc;
67172 ** Register a new collation sequence with the database handle db.
67174 int sqlite3_create_collation(
67175 sqlite3* db,
67176 const char *zName,
67177 int enc,
67178 void* pCtx,
67179 int(*xCompare)(void*,int,const void*,int,const void*)
67181 int rc;
67182 assert( !sqlite3MallocFailed() );
67183 rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
67184 return sqlite3ApiExit(db, rc);
67188 ** Register a new collation sequence with the database handle db.
67190 int sqlite3_create_collation_v2(
67191 sqlite3* db,
67192 const char *zName,
67193 int enc,
67194 void* pCtx,
67195 int(*xCompare)(void*,int,const void*,int,const void*),
67196 void(*xDel)(void*)
67198 int rc;
67199 assert( !sqlite3MallocFailed() );
67200 rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
67201 return sqlite3ApiExit(db, rc);
67204 #ifndef SQLITE_OMIT_UTF16
67206 ** Register a new collation sequence with the database handle db.
67208 int sqlite3_create_collation16(
67209 sqlite3* db,
67210 const char *zName,
67211 int enc,
67212 void* pCtx,
67213 int(*xCompare)(void*,int,const void*,int,const void*)
67215 int rc = SQLITE_OK;
67216 char *zName8;
67217 assert( !sqlite3MallocFailed() );
67218 zName8 = sqlite3Utf16to8(zName, -1);
67219 if( zName8 ){
67220 rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
67221 sqliteFree(zName8);
67223 return sqlite3ApiExit(db, rc);
67225 #endif /* SQLITE_OMIT_UTF16 */
67228 ** Register a collation sequence factory callback with the database handle
67229 ** db. Replace any previously installed collation sequence factory.
67231 int sqlite3_collation_needed(
67232 sqlite3 *db,
67233 void *pCollNeededArg,
67234 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
67236 if( sqlite3SafetyCheck(db) ){
67237 return SQLITE_MISUSE;
67239 db->xCollNeeded = xCollNeeded;
67240 db->xCollNeeded16 = 0;
67241 db->pCollNeededArg = pCollNeededArg;
67242 return SQLITE_OK;
67245 #ifndef SQLITE_OMIT_UTF16
67247 ** Register a collation sequence factory callback with the database handle
67248 ** db. Replace any previously installed collation sequence factory.
67250 int sqlite3_collation_needed16(
67251 sqlite3 *db,
67252 void *pCollNeededArg,
67253 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
67255 if( sqlite3SafetyCheck(db) ){
67256 return SQLITE_MISUSE;
67258 db->xCollNeeded = 0;
67259 db->xCollNeeded16 = xCollNeeded16;
67260 db->pCollNeededArg = pCollNeededArg;
67261 return SQLITE_OK;
67263 #endif /* SQLITE_OMIT_UTF16 */
67265 #ifndef SQLITE_OMIT_GLOBALRECOVER
67267 ** This function is now an anachronism. It used to be used to recover from a
67268 ** malloc() failure, but SQLite now does this automatically.
67270 int sqlite3_global_recover(){
67271 return SQLITE_OK;
67273 #endif
67276 ** Test to see whether or not the database connection is in autocommit
67277 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
67278 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
67279 ** by the next COMMIT or ROLLBACK.
67281 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
67283 int sqlite3_get_autocommit(sqlite3 *db){
67284 return db->autoCommit;
67287 #ifdef SQLITE_DEBUG
67289 ** The following routine is subtituted for constant SQLITE_CORRUPT in
67290 ** debugging builds. This provides a way to set a breakpoint for when
67291 ** corruption is first detected.
67293 static int sqlite3Corrupt(void){
67294 return SQLITE_CORRUPT;
67296 #endif
67299 #ifndef SQLITE_OMIT_SHARED_CACHE
67301 ** Enable or disable the shared pager and schema features for the
67302 ** current thread.
67304 ** This routine should only be called when there are no open
67305 ** database connections.
67307 int sqlite3_enable_shared_cache(int enable){
67308 ThreadData *pTd = sqlite3ThreadData();
67309 if( pTd ){
67310 /* It is only legal to call sqlite3_enable_shared_cache() when there
67311 ** are no currently open b-trees that were opened by the calling thread.
67312 ** This condition is only easy to detect if the shared-cache were
67313 ** previously enabled (and is being disabled).
67315 if( pTd->pBtree && !enable ){
67316 assert( pTd->useSharedData );
67317 return SQLITE_MISUSE;
67320 pTd->useSharedData = enable;
67321 sqlite3ReleaseThreadData();
67323 return sqlite3ApiExit(0, SQLITE_OK);
67325 #endif
67328 ** This is a convenience routine that makes sure that all thread-specific
67329 ** data for this thread has been deallocated.
67331 void sqlite3_thread_cleanup(void){
67332 ThreadData *pTd = sqlite3OsThreadSpecificData(0);
67333 if( pTd ){
67334 memset(pTd, 0, sizeof(*pTd));
67335 sqlite3OsThreadSpecificData(-1);
67340 ** Return meta information about a specific column of a database table.
67341 ** See comment in sqlite3.h (sqlite.h.in) for details.
67343 #ifdef SQLITE_ENABLE_COLUMN_METADATA
67344 int sqlite3_table_column_metadata(
67345 sqlite3 *db, /* Connection handle */
67346 const char *zDbName, /* Database name or NULL */
67347 const char *zTableName, /* Table name */
67348 const char *zColumnName, /* Column name */
67349 char const **pzDataType, /* OUTPUT: Declared data type */
67350 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
67351 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
67352 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
67353 int *pAutoinc /* OUTPUT: True if colums is auto-increment */
67355 int rc;
67356 char *zErrMsg = 0;
67357 Table *pTab = 0;
67358 Column *pCol = 0;
67359 int iCol;
67361 char const *zDataType = 0;
67362 char const *zCollSeq = 0;
67363 int notnull = 0;
67364 int primarykey = 0;
67365 int autoinc = 0;
67367 /* Ensure the database schema has been loaded */
67368 if( sqlite3SafetyOn(db) ){
67369 return SQLITE_MISUSE;
67371 rc = sqlite3Init(db, &zErrMsg);
67372 if( SQLITE_OK!=rc ){
67373 goto error_out;
67376 /* Locate the table in question */
67377 pTab = sqlite3FindTable(db, zTableName, zDbName);
67378 if( !pTab || pTab->pSelect ){
67379 pTab = 0;
67380 goto error_out;
67383 /* Find the column for which info is requested */
67384 if( sqlite3IsRowid(zColumnName) ){
67385 iCol = pTab->iPKey;
67386 if( iCol>=0 ){
67387 pCol = &pTab->aCol[iCol];
67389 }else{
67390 for(iCol=0; iCol<pTab->nCol; iCol++){
67391 pCol = &pTab->aCol[iCol];
67392 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
67393 break;
67396 if( iCol==pTab->nCol ){
67397 pTab = 0;
67398 goto error_out;
67402 /* The following block stores the meta information that will be returned
67403 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
67404 ** and autoinc. At this point there are two possibilities:
67406 ** 1. The specified column name was rowid", "oid" or "_rowid_"
67407 ** and there is no explicitly declared IPK column.
67409 ** 2. The table is not a view and the column name identified an
67410 ** explicitly declared column. Copy meta information from *pCol.
67412 if( pCol ){
67413 zDataType = pCol->zType;
67414 zCollSeq = pCol->zColl;
67415 notnull = (pCol->notNull?1:0);
67416 primarykey = (pCol->isPrimKey?1:0);
67417 autoinc = ((pTab->iPKey==iCol && pTab->autoInc)?1:0);
67418 }else{
67419 zDataType = "INTEGER";
67420 primarykey = 1;
67422 if( !zCollSeq ){
67423 zCollSeq = "BINARY";
67426 error_out:
67427 if( sqlite3SafetyOff(db) ){
67428 rc = SQLITE_MISUSE;
67431 /* Whether the function call succeeded or failed, set the output parameters
67432 ** to whatever their local counterparts contain. If an error did occur,
67433 ** this has the effect of zeroing all output parameters.
67435 if( pzDataType ) *pzDataType = zDataType;
67436 if( pzCollSeq ) *pzCollSeq = zCollSeq;
67437 if( pNotNull ) *pNotNull = notnull;
67438 if( pPrimaryKey ) *pPrimaryKey = primarykey;
67439 if( pAutoinc ) *pAutoinc = autoinc;
67441 if( SQLITE_OK==rc && !pTab ){
67442 sqlite3SetString(&zErrMsg, "no such table column: ", zTableName, ".",
67443 zColumnName, 0);
67444 rc = SQLITE_ERROR;
67446 sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
67447 sqliteFree(zErrMsg);
67448 return sqlite3ApiExit(db, rc);
67450 #endif
67453 ** Set all the parameters in the compiled SQL statement to NULL.
67455 int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
67456 int i;
67457 int rc = SQLITE_OK;
67458 for(i=1; rc==SQLITE_OK && i<=sqlite3_bind_parameter_count(pStmt); i++){
67459 rc = sqlite3_bind_null(pStmt, i);
67461 return rc;
67465 ** Sleep for a little while. Return the amount of time slept.
67467 int sqlite3_sleep(int ms){
67468 return sqlite3OsSleep(ms);
67472 ** Enable or disable the extended result codes.
67474 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
67475 db->errMask = onoff ? 0xffffffff : 0xff;
67476 return SQLITE_OK;
67479 /************** End of main.c ************************************************/