000001 /*
000002 ** 2001 September 15
000003 **
000004 ** The author disclaims copyright to this source code. In place of
000005 ** a legal notice, here is a blessing:
000006 **
000007 ** May you do good and not evil.
000008 ** May you find forgiveness for yourself and forgive others.
000009 ** May you share freely, never taking more than you give.
000010 **
000011 *************************************************************************
000012 ** Main file for the SQLite library. The routines in this file
000013 ** implement the programmer interface to the library. Routines in
000014 ** other files are for internal use by SQLite and should not be
000015 ** accessed by users of the library.
000016 */
000017 #include "sqliteInt.h"
000018
000019 #ifdef SQLITE_ENABLE_FTS3
000020 # include "fts3.h"
000021 #endif
000022 #ifdef SQLITE_ENABLE_RTREE
000023 # include "rtree.h"
000024 #endif
000025 #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
000026 # include "sqliteicu.h"
000027 #endif
000028
000029 /*
000030 ** This is an extension initializer that is a no-op and always
000031 ** succeeds, except that it fails if the fault-simulation is set
000032 ** to 500.
000033 */
000034 static int sqlite3TestExtInit(sqlite3 *db){
000035 (void)db;
000036 return sqlite3FaultSim(500);
000037 }
000038
000039
000040 /*
000041 ** Forward declarations of external module initializer functions
000042 ** for modules that need them.
000043 */
000044 #ifdef SQLITE_ENABLE_FTS5
000045 int sqlite3Fts5Init(sqlite3*);
000046 #endif
000047 #ifdef SQLITE_ENABLE_STMTVTAB
000048 int sqlite3StmtVtabInit(sqlite3*);
000049 #endif
000050 #ifdef SQLITE_EXTRA_AUTOEXT
000051 int SQLITE_EXTRA_AUTOEXT(sqlite3*);
000052 #endif
000053 /*
000054 ** An array of pointers to extension initializer functions for
000055 ** built-in extensions.
000056 */
000057 static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = {
000058 #ifdef SQLITE_ENABLE_FTS3
000059 sqlite3Fts3Init,
000060 #endif
000061 #ifdef SQLITE_ENABLE_FTS5
000062 sqlite3Fts5Init,
000063 #endif
000064 #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
000065 sqlite3IcuInit,
000066 #endif
000067 #ifdef SQLITE_ENABLE_RTREE
000068 sqlite3RtreeInit,
000069 #endif
000070 #ifdef SQLITE_ENABLE_DBPAGE_VTAB
000071 sqlite3DbpageRegister,
000072 #endif
000073 #ifdef SQLITE_ENABLE_DBSTAT_VTAB
000074 sqlite3DbstatRegister,
000075 #endif
000076 sqlite3TestExtInit,
000077 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)
000078 sqlite3JsonTableFunctions,
000079 #endif
000080 #ifdef SQLITE_ENABLE_STMTVTAB
000081 sqlite3StmtVtabInit,
000082 #endif
000083 #ifdef SQLITE_ENABLE_BYTECODE_VTAB
000084 sqlite3VdbeBytecodeVtabInit,
000085 #endif
000086 #ifdef SQLITE_EXTRA_AUTOEXT
000087 SQLITE_EXTRA_AUTOEXT,
000088 #endif
000089 };
000090
000091 #ifndef SQLITE_AMALGAMATION
000092 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
000093 ** contains the text of SQLITE_VERSION macro.
000094 */
000095 const char sqlite3_version[] = SQLITE_VERSION;
000096 #endif
000097
000098 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
000099 ** a pointer to the to the sqlite3_version[] string constant.
000100 */
000101 const char *sqlite3_libversion(void){ return sqlite3_version; }
000102
000103 /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
000104 ** pointer to a string constant whose value is the same as the
000105 ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
000106 ** an edited copy of the amalgamation, then the last four characters of
000107 ** the hash might be different from SQLITE_SOURCE_ID.
000108 */
000109 const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
000110
000111 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
000112 ** returns an integer equal to SQLITE_VERSION_NUMBER.
000113 */
000114 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
000115
000116 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
000117 ** zero if and only if SQLite was compiled with mutexing code omitted due to
000118 ** the SQLITE_THREADSAFE compile-time option being set to 0.
000119 */
000120 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
000121
000122 /*
000123 ** When compiling the test fixture or with debugging enabled (on Win32),
000124 ** this variable being set to non-zero will cause OSTRACE macros to emit
000125 ** extra diagnostic information.
000126 */
000127 #ifdef SQLITE_HAVE_OS_TRACE
000128 # ifndef SQLITE_DEBUG_OS_TRACE
000129 # define SQLITE_DEBUG_OS_TRACE 0
000130 # endif
000131 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
000132 #endif
000133
000134 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
000135 /*
000136 ** If the following function pointer is not NULL and if
000137 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
000138 ** I/O active are written using this function. These messages
000139 ** are intended for debugging activity only.
000140 */
000141 SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
000142 #endif
000143
000144 /*
000145 ** If the following global variable points to a string which is the
000146 ** name of a directory, then that directory will be used to store
000147 ** temporary files.
000148 **
000149 ** See also the "PRAGMA temp_store_directory" SQL command.
000150 */
000151 char *sqlite3_temp_directory = 0;
000152
000153 /*
000154 ** If the following global variable points to a string which is the
000155 ** name of a directory, then that directory will be used to store
000156 ** all database files specified with a relative pathname.
000157 **
000158 ** See also the "PRAGMA data_store_directory" SQL command.
000159 */
000160 char *sqlite3_data_directory = 0;
000161
000162 /*
000163 ** Initialize SQLite.
000164 **
000165 ** This routine must be called to initialize the memory allocation,
000166 ** VFS, and mutex subsystems prior to doing any serious work with
000167 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
000168 ** this routine will be called automatically by key routines such as
000169 ** sqlite3_open().
000170 **
000171 ** This routine is a no-op except on its very first call for the process,
000172 ** or for the first call after a call to sqlite3_shutdown.
000173 **
000174 ** The first thread to call this routine runs the initialization to
000175 ** completion. If subsequent threads call this routine before the first
000176 ** thread has finished the initialization process, then the subsequent
000177 ** threads must block until the first thread finishes with the initialization.
000178 **
000179 ** The first thread might call this routine recursively. Recursive
000180 ** calls to this routine should not block, of course. Otherwise the
000181 ** initialization process would never complete.
000182 **
000183 ** Let X be the first thread to enter this routine. Let Y be some other
000184 ** thread. Then while the initial invocation of this routine by X is
000185 ** incomplete, it is required that:
000186 **
000187 ** * Calls to this routine from Y must block until the outer-most
000188 ** call by X completes.
000189 **
000190 ** * Recursive calls to this routine from thread X return immediately
000191 ** without blocking.
000192 */
000193 int sqlite3_initialize(void){
000194 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */
000195 int rc; /* Result code */
000196 #ifdef SQLITE_EXTRA_INIT
000197 int bRunExtraInit = 0; /* Extra initialization needed */
000198 #endif
000199
000200 #ifdef SQLITE_OMIT_WSD
000201 rc = sqlite3_wsd_init(4096, 24);
000202 if( rc!=SQLITE_OK ){
000203 return rc;
000204 }
000205 #endif
000206
000207 /* If the following assert() fails on some obscure processor/compiler
000208 ** combination, the work-around is to set the correct pointer
000209 ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
000210 assert( SQLITE_PTRSIZE==sizeof(char*) );
000211
000212 /* If SQLite is already completely initialized, then this call
000213 ** to sqlite3_initialize() should be a no-op. But the initialization
000214 ** must be complete. So isInit must not be set until the very end
000215 ** of this routine.
000216 */
000217 if( sqlite3GlobalConfig.isInit ){
000218 sqlite3MemoryBarrier();
000219 return SQLITE_OK;
000220 }
000221
000222 /* Make sure the mutex subsystem is initialized. If unable to
000223 ** initialize the mutex subsystem, return early with the error.
000224 ** If the system is so sick that we are unable to allocate a mutex,
000225 ** there is not much SQLite is going to be able to do.
000226 **
000227 ** The mutex subsystem must take care of serializing its own
000228 ** initialization.
000229 */
000230 rc = sqlite3MutexInit();
000231 if( rc ) return rc;
000232
000233 /* Initialize the malloc() system and the recursive pInitMutex mutex.
000234 ** This operation is protected by the STATIC_MAIN mutex. Note that
000235 ** MutexAlloc() is called for a static mutex prior to initializing the
000236 ** malloc subsystem - this implies that the allocation of a static
000237 ** mutex must not require support from the malloc subsystem.
000238 */
000239 MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
000240 sqlite3_mutex_enter(pMainMtx);
000241 sqlite3GlobalConfig.isMutexInit = 1;
000242 if( !sqlite3GlobalConfig.isMallocInit ){
000243 rc = sqlite3MallocInit();
000244 }
000245 if( rc==SQLITE_OK ){
000246 sqlite3GlobalConfig.isMallocInit = 1;
000247 if( !sqlite3GlobalConfig.pInitMutex ){
000248 sqlite3GlobalConfig.pInitMutex =
000249 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
000250 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
000251 rc = SQLITE_NOMEM_BKPT;
000252 }
000253 }
000254 }
000255 if( rc==SQLITE_OK ){
000256 sqlite3GlobalConfig.nRefInitMutex++;
000257 }
000258 sqlite3_mutex_leave(pMainMtx);
000259
000260 /* If rc is not SQLITE_OK at this point, then either the malloc
000261 ** subsystem could not be initialized or the system failed to allocate
000262 ** the pInitMutex mutex. Return an error in either case. */
000263 if( rc!=SQLITE_OK ){
000264 return rc;
000265 }
000266
000267 /* Do the rest of the initialization under the recursive mutex so
000268 ** that we will be able to handle recursive calls into
000269 ** sqlite3_initialize(). The recursive calls normally come through
000270 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
000271 ** recursive calls might also be possible.
000272 **
000273 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
000274 ** to the xInit method, so the xInit method need not be threadsafe.
000275 **
000276 ** The following mutex is what serializes access to the appdef pcache xInit
000277 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
000278 ** call to sqlite3PcacheInitialize().
000279 */
000280 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
000281 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
000282 sqlite3GlobalConfig.inProgress = 1;
000283 #ifdef SQLITE_ENABLE_SQLLOG
000284 {
000285 extern void sqlite3_init_sqllog(void);
000286 sqlite3_init_sqllog();
000287 }
000288 #endif
000289 memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
000290 sqlite3RegisterBuiltinFunctions();
000291 if( sqlite3GlobalConfig.isPCacheInit==0 ){
000292 rc = sqlite3PcacheInitialize();
000293 }
000294 if( rc==SQLITE_OK ){
000295 sqlite3GlobalConfig.isPCacheInit = 1;
000296 rc = sqlite3OsInit();
000297 }
000298 #ifndef SQLITE_OMIT_DESERIALIZE
000299 if( rc==SQLITE_OK ){
000300 rc = sqlite3MemdbInit();
000301 }
000302 #endif
000303 if( rc==SQLITE_OK ){
000304 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
000305 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
000306 sqlite3MemoryBarrier();
000307 sqlite3GlobalConfig.isInit = 1;
000308 #ifdef SQLITE_EXTRA_INIT
000309 bRunExtraInit = 1;
000310 #endif
000311 }
000312 sqlite3GlobalConfig.inProgress = 0;
000313 }
000314 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
000315
000316 /* Go back under the static mutex and clean up the recursive
000317 ** mutex to prevent a resource leak.
000318 */
000319 sqlite3_mutex_enter(pMainMtx);
000320 sqlite3GlobalConfig.nRefInitMutex--;
000321 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
000322 assert( sqlite3GlobalConfig.nRefInitMutex==0 );
000323 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
000324 sqlite3GlobalConfig.pInitMutex = 0;
000325 }
000326 sqlite3_mutex_leave(pMainMtx);
000327
000328 /* The following is just a sanity check to make sure SQLite has
000329 ** been compiled correctly. It is important to run this code, but
000330 ** we don't want to run it too often and soak up CPU cycles for no
000331 ** reason. So we run it once during initialization.
000332 */
000333 #ifndef NDEBUG
000334 #ifndef SQLITE_OMIT_FLOATING_POINT
000335 /* This section of code's only "output" is via assert() statements. */
000336 if( rc==SQLITE_OK ){
000337 u64 x = (((u64)1)<<63)-1;
000338 double y;
000339 assert(sizeof(x)==8);
000340 assert(sizeof(x)==sizeof(y));
000341 memcpy(&y, &x, 8);
000342 assert( sqlite3IsNaN(y) );
000343 }
000344 #endif
000345 #endif
000346
000347 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
000348 ** compile-time option.
000349 */
000350 #ifdef SQLITE_EXTRA_INIT
000351 if( bRunExtraInit ){
000352 int SQLITE_EXTRA_INIT(const char*);
000353 rc = SQLITE_EXTRA_INIT(0);
000354 }
000355 #endif
000356 return rc;
000357 }
000358
000359 /*
000360 ** Undo the effects of sqlite3_initialize(). Must not be called while
000361 ** there are outstanding database connections or memory allocations or
000362 ** while any part of SQLite is otherwise in use in any thread. This
000363 ** routine is not threadsafe. But it is safe to invoke this routine
000364 ** on when SQLite is already shut down. If SQLite is already shut down
000365 ** when this routine is invoked, then this routine is a harmless no-op.
000366 */
000367 int sqlite3_shutdown(void){
000368 #ifdef SQLITE_OMIT_WSD
000369 int rc = sqlite3_wsd_init(4096, 24);
000370 if( rc!=SQLITE_OK ){
000371 return rc;
000372 }
000373 #endif
000374
000375 if( sqlite3GlobalConfig.isInit ){
000376 #ifdef SQLITE_EXTRA_SHUTDOWN
000377 void SQLITE_EXTRA_SHUTDOWN(void);
000378 SQLITE_EXTRA_SHUTDOWN();
000379 #endif
000380 sqlite3_os_end();
000381 sqlite3_reset_auto_extension();
000382 sqlite3GlobalConfig.isInit = 0;
000383 }
000384 if( sqlite3GlobalConfig.isPCacheInit ){
000385 sqlite3PcacheShutdown();
000386 sqlite3GlobalConfig.isPCacheInit = 0;
000387 }
000388 if( sqlite3GlobalConfig.isMallocInit ){
000389 sqlite3MallocEnd();
000390 sqlite3GlobalConfig.isMallocInit = 0;
000391
000392 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
000393 /* The heap subsystem has now been shutdown and these values are supposed
000394 ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
000395 ** which would rely on that heap subsystem; therefore, make sure these
000396 ** values cannot refer to heap memory that was just invalidated when the
000397 ** heap subsystem was shutdown. This is only done if the current call to
000398 ** this function resulted in the heap subsystem actually being shutdown.
000399 */
000400 sqlite3_data_directory = 0;
000401 sqlite3_temp_directory = 0;
000402 #endif
000403 }
000404 if( sqlite3GlobalConfig.isMutexInit ){
000405 sqlite3MutexEnd();
000406 sqlite3GlobalConfig.isMutexInit = 0;
000407 }
000408
000409 return SQLITE_OK;
000410 }
000411
000412 /*
000413 ** This API allows applications to modify the global configuration of
000414 ** the SQLite library at run-time.
000415 **
000416 ** This routine should only be called when there are no outstanding
000417 ** database connections or memory allocations. This routine is not
000418 ** threadsafe. Failure to heed these warnings can lead to unpredictable
000419 ** behavior.
000420 */
000421 int sqlite3_config(int op, ...){
000422 va_list ap;
000423 int rc = SQLITE_OK;
000424
000425 /* sqlite3_config() normally returns SQLITE_MISUSE if it is invoked while
000426 ** the SQLite library is in use. Except, a few selected opcodes
000427 ** are allowed.
000428 */
000429 if( sqlite3GlobalConfig.isInit ){
000430 static const u64 mAnytimeConfigOption = 0
000431 | MASKBIT64( SQLITE_CONFIG_LOG )
000432 | MASKBIT64( SQLITE_CONFIG_PCACHE_HDRSZ )
000433 ;
000434 if( op<0 || op>63 || (MASKBIT64(op) & mAnytimeConfigOption)==0 ){
000435 return SQLITE_MISUSE_BKPT;
000436 }
000437 testcase( op==SQLITE_CONFIG_LOG );
000438 testcase( op==SQLITE_CONFIG_PCACHE_HDRSZ );
000439 }
000440
000441 va_start(ap, op);
000442 switch( op ){
000443
000444 /* Mutex configuration options are only available in a threadsafe
000445 ** compile.
000446 */
000447 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
000448 case SQLITE_CONFIG_SINGLETHREAD: {
000449 /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
000450 ** Single-thread. */
000451 sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
000452 sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
000453 break;
000454 }
000455 #endif
000456 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
000457 case SQLITE_CONFIG_MULTITHREAD: {
000458 /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
000459 ** Multi-thread. */
000460 sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
000461 sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
000462 break;
000463 }
000464 #endif
000465 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
000466 case SQLITE_CONFIG_SERIALIZED: {
000467 /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
000468 ** Serialized. */
000469 sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
000470 sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
000471 break;
000472 }
000473 #endif
000474 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
000475 case SQLITE_CONFIG_MUTEX: {
000476 /* Specify an alternative mutex implementation */
000477 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
000478 break;
000479 }
000480 #endif
000481 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
000482 case SQLITE_CONFIG_GETMUTEX: {
000483 /* Retrieve the current mutex implementation */
000484 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
000485 break;
000486 }
000487 #endif
000488
000489 case SQLITE_CONFIG_MALLOC: {
000490 /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
000491 ** single argument which is a pointer to an instance of the
000492 ** sqlite3_mem_methods structure. The argument specifies alternative
000493 ** low-level memory allocation routines to be used in place of the memory
000494 ** allocation routines built into SQLite. */
000495 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
000496 break;
000497 }
000498 case SQLITE_CONFIG_GETMALLOC: {
000499 /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
000500 ** single argument which is a pointer to an instance of the
000501 ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
000502 ** filled with the currently defined memory allocation routines. */
000503 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
000504 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
000505 break;
000506 }
000507 case SQLITE_CONFIG_MEMSTATUS: {
000508 assert( !sqlite3GlobalConfig.isInit ); /* Cannot change at runtime */
000509 /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
000510 ** single argument of type int, interpreted as a boolean, which enables
000511 ** or disables the collection of memory allocation statistics. */
000512 sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
000513 break;
000514 }
000515 case SQLITE_CONFIG_SMALL_MALLOC: {
000516 sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
000517 break;
000518 }
000519 case SQLITE_CONFIG_PAGECACHE: {
000520 /* EVIDENCE-OF: R-18761-36601 There are three arguments to
000521 ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
000522 ** the size of each page cache line (sz), and the number of cache lines
000523 ** (N). */
000524 sqlite3GlobalConfig.pPage = va_arg(ap, void*);
000525 sqlite3GlobalConfig.szPage = va_arg(ap, int);
000526 sqlite3GlobalConfig.nPage = va_arg(ap, int);
000527 break;
000528 }
000529 case SQLITE_CONFIG_PCACHE_HDRSZ: {
000530 /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
000531 ** a single parameter which is a pointer to an integer and writes into
000532 ** that integer the number of extra bytes per page required for each page
000533 ** in SQLITE_CONFIG_PAGECACHE. */
000534 *va_arg(ap, int*) =
000535 sqlite3HeaderSizeBtree() +
000536 sqlite3HeaderSizePcache() +
000537 sqlite3HeaderSizePcache1();
000538 break;
000539 }
000540
000541 case SQLITE_CONFIG_PCACHE: {
000542 /* no-op */
000543 break;
000544 }
000545 case SQLITE_CONFIG_GETPCACHE: {
000546 /* now an error */
000547 rc = SQLITE_ERROR;
000548 break;
000549 }
000550
000551 case SQLITE_CONFIG_PCACHE2: {
000552 /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
000553 ** single argument which is a pointer to an sqlite3_pcache_methods2
000554 ** object. This object specifies the interface to a custom page cache
000555 ** implementation. */
000556 sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
000557 break;
000558 }
000559 case SQLITE_CONFIG_GETPCACHE2: {
000560 /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
000561 ** single argument which is a pointer to an sqlite3_pcache_methods2
000562 ** object. SQLite copies of the current page cache implementation into
000563 ** that object. */
000564 if( sqlite3GlobalConfig.pcache2.xInit==0 ){
000565 sqlite3PCacheSetDefault();
000566 }
000567 *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
000568 break;
000569 }
000570
000571 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
000572 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
000573 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
000574 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
000575 case SQLITE_CONFIG_HEAP: {
000576 /* EVIDENCE-OF: R-19854-42126 There are three arguments to
000577 ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
000578 ** number of bytes in the memory buffer, and the minimum allocation size.
000579 */
000580 sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
000581 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
000582 sqlite3GlobalConfig.mnReq = va_arg(ap, int);
000583
000584 if( sqlite3GlobalConfig.mnReq<1 ){
000585 sqlite3GlobalConfig.mnReq = 1;
000586 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
000587 /* cap min request size at 2^12 */
000588 sqlite3GlobalConfig.mnReq = (1<<12);
000589 }
000590
000591 if( sqlite3GlobalConfig.pHeap==0 ){
000592 /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
000593 ** is NULL, then SQLite reverts to using its default memory allocator
000594 ** (the system malloc() implementation), undoing any prior invocation of
000595 ** SQLITE_CONFIG_MALLOC.
000596 **
000597 ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
000598 ** revert to its default implementation when sqlite3_initialize() is run
000599 */
000600 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
000601 }else{
000602 /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
000603 ** alternative memory allocator is engaged to handle all of SQLites
000604 ** memory allocation needs. */
000605 #ifdef SQLITE_ENABLE_MEMSYS3
000606 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
000607 #endif
000608 #ifdef SQLITE_ENABLE_MEMSYS5
000609 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
000610 #endif
000611 }
000612 break;
000613 }
000614 #endif
000615
000616 case SQLITE_CONFIG_LOOKASIDE: {
000617 sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
000618 sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
000619 break;
000620 }
000621
000622 /* Record a pointer to the logger function and its first argument.
000623 ** The default is NULL. Logging is disabled if the function pointer is
000624 ** NULL.
000625 */
000626 case SQLITE_CONFIG_LOG: {
000627 /* MSVC is picky about pulling func ptrs from va lists.
000628 ** http://support.microsoft.com/kb/47961
000629 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
000630 */
000631 typedef void(*LOGFUNC_t)(void*,int,const char*);
000632 LOGFUNC_t xLog = va_arg(ap, LOGFUNC_t);
000633 void *pLogArg = va_arg(ap, void*);
000634 AtomicStore(&sqlite3GlobalConfig.xLog, xLog);
000635 AtomicStore(&sqlite3GlobalConfig.pLogArg, pLogArg);
000636 break;
000637 }
000638
000639 /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
000640 ** can be changed at start-time using the
000641 ** sqlite3_config(SQLITE_CONFIG_URI,1) or
000642 ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
000643 */
000644 case SQLITE_CONFIG_URI: {
000645 /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
000646 ** argument of type int. If non-zero, then URI handling is globally
000647 ** enabled. If the parameter is zero, then URI handling is globally
000648 ** disabled. */
000649 int bOpenUri = va_arg(ap, int);
000650 AtomicStore(&sqlite3GlobalConfig.bOpenUri, bOpenUri);
000651 break;
000652 }
000653
000654 case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
000655 /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
000656 ** option takes a single integer argument which is interpreted as a
000657 ** boolean in order to enable or disable the use of covering indices for
000658 ** full table scans in the query optimizer. */
000659 sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
000660 break;
000661 }
000662
000663 #ifdef SQLITE_ENABLE_SQLLOG
000664 case SQLITE_CONFIG_SQLLOG: {
000665 typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
000666 sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
000667 sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
000668 break;
000669 }
000670 #endif
000671
000672 case SQLITE_CONFIG_MMAP_SIZE: {
000673 /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
000674 ** integer (sqlite3_int64) values that are the default mmap size limit
000675 ** (the default setting for PRAGMA mmap_size) and the maximum allowed
000676 ** mmap size limit. */
000677 sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
000678 sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
000679 /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
000680 ** negative, then that argument is changed to its compile-time default.
000681 **
000682 ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
000683 ** silently truncated if necessary so that it does not exceed the
000684 ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
000685 ** compile-time option.
000686 */
000687 if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
000688 mxMmap = SQLITE_MAX_MMAP_SIZE;
000689 }
000690 if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
000691 if( szMmap>mxMmap) szMmap = mxMmap;
000692 sqlite3GlobalConfig.mxMmap = mxMmap;
000693 sqlite3GlobalConfig.szMmap = szMmap;
000694 break;
000695 }
000696
000697 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
000698 case SQLITE_CONFIG_WIN32_HEAPSIZE: {
000699 /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
000700 ** unsigned integer value that specifies the maximum size of the created
000701 ** heap. */
000702 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
000703 break;
000704 }
000705 #endif
000706
000707 case SQLITE_CONFIG_PMASZ: {
000708 sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
000709 break;
000710 }
000711
000712 case SQLITE_CONFIG_STMTJRNL_SPILL: {
000713 sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
000714 break;
000715 }
000716
000717 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
000718 case SQLITE_CONFIG_SORTERREF_SIZE: {
000719 int iVal = va_arg(ap, int);
000720 if( iVal<0 ){
000721 iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
000722 }
000723 sqlite3GlobalConfig.szSorterRef = (u32)iVal;
000724 break;
000725 }
000726 #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
000727
000728 #ifndef SQLITE_OMIT_DESERIALIZE
000729 case SQLITE_CONFIG_MEMDB_MAXSIZE: {
000730 sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);
000731 break;
000732 }
000733 #endif /* SQLITE_OMIT_DESERIALIZE */
000734
000735 case SQLITE_CONFIG_ROWID_IN_VIEW: {
000736 int *pVal = va_arg(ap,int*);
000737 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
000738 if( 0==*pVal ) sqlite3GlobalConfig.mNoVisibleRowid = TF_NoVisibleRowid;
000739 if( 1==*pVal ) sqlite3GlobalConfig.mNoVisibleRowid = 0;
000740 *pVal = (sqlite3GlobalConfig.mNoVisibleRowid==0);
000741 #else
000742 *pVal = 0;
000743 #endif
000744 break;
000745 }
000746
000747 default: {
000748 rc = SQLITE_ERROR;
000749 break;
000750 }
000751 }
000752 va_end(ap);
000753 return rc;
000754 }
000755
000756 /*
000757 ** Set up the lookaside buffers for a database connection.
000758 ** Return SQLITE_OK on success.
000759 ** If lookaside is already active, return SQLITE_BUSY.
000760 **
000761 ** The sz parameter is the number of bytes in each lookaside slot.
000762 ** The cnt parameter is the number of slots. If pStart is NULL the
000763 ** space for the lookaside memory is obtained from sqlite3_malloc().
000764 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
000765 ** the lookaside memory.
000766 */
000767 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
000768 #ifndef SQLITE_OMIT_LOOKASIDE
000769 void *pStart;
000770 sqlite3_int64 szAlloc;
000771 int nBig; /* Number of full-size slots */
000772 int nSm; /* Number smaller LOOKASIDE_SMALL-byte slots */
000773
000774 if( sqlite3LookasideUsed(db,0)>0 ){
000775 return SQLITE_BUSY;
000776 }
000777 /* Free any existing lookaside buffer for this handle before
000778 ** allocating a new one so we don't have to have space for
000779 ** both at the same time.
000780 */
000781 if( db->lookaside.bMalloced ){
000782 sqlite3_free(db->lookaside.pStart);
000783 }
000784 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
000785 ** than a pointer to be useful.
000786 */
000787 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
000788 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
000789 if( sz>65528 ) sz = 65528;
000790 if( cnt<0 ) cnt = 0;
000791 szAlloc = (i64)sz*(i64)cnt;
000792 if( sz==0 || cnt==0 ){
000793 sz = 0;
000794 pStart = 0;
000795 }else if( pBuf==0 ){
000796 sqlite3BeginBenignMalloc();
000797 pStart = sqlite3Malloc( szAlloc ); /* IMP: R-61949-35727 */
000798 sqlite3EndBenignMalloc();
000799 if( pStart ) szAlloc = sqlite3MallocSize(pStart);
000800 }else{
000801 pStart = pBuf;
000802 }
000803 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
000804 if( sz>=LOOKASIDE_SMALL*3 ){
000805 nBig = szAlloc/(3*LOOKASIDE_SMALL+sz);
000806 nSm = (szAlloc - (i64)sz*(i64)nBig)/LOOKASIDE_SMALL;
000807 }else if( sz>=LOOKASIDE_SMALL*2 ){
000808 nBig = szAlloc/(LOOKASIDE_SMALL+sz);
000809 nSm = (szAlloc - (i64)sz*(i64)nBig)/LOOKASIDE_SMALL;
000810 }else
000811 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
000812 if( sz>0 ){
000813 nBig = szAlloc/sz;
000814 nSm = 0;
000815 }else{
000816 nBig = nSm = 0;
000817 }
000818 db->lookaside.pStart = pStart;
000819 db->lookaside.pInit = 0;
000820 db->lookaside.pFree = 0;
000821 db->lookaside.sz = (u16)sz;
000822 db->lookaside.szTrue = (u16)sz;
000823 if( pStart ){
000824 int i;
000825 LookasideSlot *p;
000826 assert( sz > (int)sizeof(LookasideSlot*) );
000827 p = (LookasideSlot*)pStart;
000828 for(i=0; i<nBig; i++){
000829 p->pNext = db->lookaside.pInit;
000830 db->lookaside.pInit = p;
000831 p = (LookasideSlot*)&((u8*)p)[sz];
000832 }
000833 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
000834 db->lookaside.pSmallInit = 0;
000835 db->lookaside.pSmallFree = 0;
000836 db->lookaside.pMiddle = p;
000837 for(i=0; i<nSm; i++){
000838 p->pNext = db->lookaside.pSmallInit;
000839 db->lookaside.pSmallInit = p;
000840 p = (LookasideSlot*)&((u8*)p)[LOOKASIDE_SMALL];
000841 }
000842 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
000843 assert( ((uptr)p)<=szAlloc + (uptr)pStart );
000844 db->lookaside.pEnd = p;
000845 db->lookaside.bDisable = 0;
000846 db->lookaside.bMalloced = pBuf==0 ?1:0;
000847 db->lookaside.nSlot = nBig+nSm;
000848 }else{
000849 db->lookaside.pStart = 0;
000850 #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
000851 db->lookaside.pSmallInit = 0;
000852 db->lookaside.pSmallFree = 0;
000853 db->lookaside.pMiddle = 0;
000854 #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
000855 db->lookaside.pEnd = 0;
000856 db->lookaside.bDisable = 1;
000857 db->lookaside.sz = 0;
000858 db->lookaside.bMalloced = 0;
000859 db->lookaside.nSlot = 0;
000860 }
000861 db->lookaside.pTrueEnd = db->lookaside.pEnd;
000862 assert( sqlite3LookasideUsed(db,0)==0 );
000863 #endif /* SQLITE_OMIT_LOOKASIDE */
000864 return SQLITE_OK;
000865 }
000866
000867 /*
000868 ** Return the mutex associated with a database connection.
000869 */
000870 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
000871 #ifdef SQLITE_ENABLE_API_ARMOR
000872 if( !sqlite3SafetyCheckOk(db) ){
000873 (void)SQLITE_MISUSE_BKPT;
000874 return 0;
000875 }
000876 #endif
000877 return db->mutex;
000878 }
000879
000880 /*
000881 ** Free up as much memory as we can from the given database
000882 ** connection.
000883 */
000884 int sqlite3_db_release_memory(sqlite3 *db){
000885 int i;
000886
000887 #ifdef SQLITE_ENABLE_API_ARMOR
000888 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
000889 #endif
000890 sqlite3_mutex_enter(db->mutex);
000891 sqlite3BtreeEnterAll(db);
000892 for(i=0; i<db->nDb; i++){
000893 Btree *pBt = db->aDb[i].pBt;
000894 if( pBt ){
000895 Pager *pPager = sqlite3BtreePager(pBt);
000896 sqlite3PagerShrink(pPager);
000897 }
000898 }
000899 sqlite3BtreeLeaveAll(db);
000900 sqlite3_mutex_leave(db->mutex);
000901 return SQLITE_OK;
000902 }
000903
000904 /*
000905 ** Flush any dirty pages in the pager-cache for any attached database
000906 ** to disk.
000907 */
000908 int sqlite3_db_cacheflush(sqlite3 *db){
000909 int i;
000910 int rc = SQLITE_OK;
000911 int bSeenBusy = 0;
000912
000913 #ifdef SQLITE_ENABLE_API_ARMOR
000914 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
000915 #endif
000916 sqlite3_mutex_enter(db->mutex);
000917 sqlite3BtreeEnterAll(db);
000918 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
000919 Btree *pBt = db->aDb[i].pBt;
000920 if( pBt && sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
000921 Pager *pPager = sqlite3BtreePager(pBt);
000922 rc = sqlite3PagerFlush(pPager);
000923 if( rc==SQLITE_BUSY ){
000924 bSeenBusy = 1;
000925 rc = SQLITE_OK;
000926 }
000927 }
000928 }
000929 sqlite3BtreeLeaveAll(db);
000930 sqlite3_mutex_leave(db->mutex);
000931 return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
000932 }
000933
000934 /*
000935 ** Configuration settings for an individual database connection
000936 */
000937 int sqlite3_db_config(sqlite3 *db, int op, ...){
000938 va_list ap;
000939 int rc;
000940
000941 #ifdef SQLITE_ENABLE_API_ARMOR
000942 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
000943 #endif
000944 sqlite3_mutex_enter(db->mutex);
000945 va_start(ap, op);
000946 switch( op ){
000947 case SQLITE_DBCONFIG_MAINDBNAME: {
000948 /* IMP: R-06824-28531 */
000949 /* IMP: R-36257-52125 */
000950 db->aDb[0].zDbSName = va_arg(ap,char*);
000951 rc = SQLITE_OK;
000952 break;
000953 }
000954 case SQLITE_DBCONFIG_LOOKASIDE: {
000955 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
000956 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
000957 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
000958 rc = setupLookaside(db, pBuf, sz, cnt);
000959 break;
000960 }
000961 default: {
000962 static const struct {
000963 int op; /* The opcode */
000964 u64 mask; /* Mask of the bit in sqlite3.flags to set/clear */
000965 } aFlagOp[] = {
000966 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
000967 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
000968 { SQLITE_DBCONFIG_ENABLE_VIEW, SQLITE_EnableView },
000969 { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
000970 { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
000971 { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
000972 { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG },
000973 { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP },
000974 { SQLITE_DBCONFIG_RESET_DATABASE, SQLITE_ResetDatabase },
000975 { SQLITE_DBCONFIG_DEFENSIVE, SQLITE_Defensive },
000976 { SQLITE_DBCONFIG_WRITABLE_SCHEMA, SQLITE_WriteSchema|
000977 SQLITE_NoSchemaError },
000978 { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, SQLITE_LegacyAlter },
000979 { SQLITE_DBCONFIG_DQS_DDL, SQLITE_DqsDDL },
000980 { SQLITE_DBCONFIG_DQS_DML, SQLITE_DqsDML },
000981 { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT, SQLITE_LegacyFileFmt },
000982 { SQLITE_DBCONFIG_TRUSTED_SCHEMA, SQLITE_TrustedSchema },
000983 { SQLITE_DBCONFIG_STMT_SCANSTATUS, SQLITE_StmtScanStatus },
000984 { SQLITE_DBCONFIG_REVERSE_SCANORDER, SQLITE_ReverseOrder },
000985 { SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE, SQLITE_AttachCreate },
000986 { SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE, SQLITE_AttachWrite },
000987 { SQLITE_DBCONFIG_ENABLE_COMMENTS, SQLITE_Comments },
000988 };
000989 unsigned int i;
000990 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
000991 for(i=0; i<ArraySize(aFlagOp); i++){
000992 if( aFlagOp[i].op==op ){
000993 int onoff = va_arg(ap, int);
000994 int *pRes = va_arg(ap, int*);
000995 u64 oldFlags = db->flags;
000996 if( onoff>0 ){
000997 db->flags |= aFlagOp[i].mask;
000998 }else if( onoff==0 ){
000999 db->flags &= ~(u64)aFlagOp[i].mask;
001000 }
001001 if( oldFlags!=db->flags ){
001002 sqlite3ExpirePreparedStatements(db, 0);
001003 }
001004 if( pRes ){
001005 *pRes = (db->flags & aFlagOp[i].mask)!=0;
001006 }
001007 rc = SQLITE_OK;
001008 break;
001009 }
001010 }
001011 break;
001012 }
001013 }
001014 va_end(ap);
001015 sqlite3_mutex_leave(db->mutex);
001016 return rc;
001017 }
001018
001019 /*
001020 ** This is the default collating function named "BINARY" which is always
001021 ** available.
001022 */
001023 static int binCollFunc(
001024 void *NotUsed,
001025 int nKey1, const void *pKey1,
001026 int nKey2, const void *pKey2
001027 ){
001028 int rc, n;
001029 UNUSED_PARAMETER(NotUsed);
001030 n = nKey1<nKey2 ? nKey1 : nKey2;
001031 /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
001032 ** strings byte by byte using the memcmp() function from the standard C
001033 ** library. */
001034 assert( pKey1 && pKey2 );
001035 rc = memcmp(pKey1, pKey2, n);
001036 if( rc==0 ){
001037 rc = nKey1 - nKey2;
001038 }
001039 return rc;
001040 }
001041
001042 /*
001043 ** This is the collating function named "RTRIM" which is always
001044 ** available. Ignore trailing spaces.
001045 */
001046 static int rtrimCollFunc(
001047 void *pUser,
001048 int nKey1, const void *pKey1,
001049 int nKey2, const void *pKey2
001050 ){
001051 const u8 *pK1 = (const u8*)pKey1;
001052 const u8 *pK2 = (const u8*)pKey2;
001053 while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--;
001054 while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--;
001055 return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2);
001056 }
001057
001058 /*
001059 ** Return true if CollSeq is the default built-in BINARY.
001060 */
001061 int sqlite3IsBinary(const CollSeq *p){
001062 assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 );
001063 return p==0 || p->xCmp==binCollFunc;
001064 }
001065
001066 /*
001067 ** Another built-in collating sequence: NOCASE.
001068 **
001069 ** This collating sequence is intended to be used for "case independent
001070 ** comparison". SQLite's knowledge of upper and lower case equivalents
001071 ** extends only to the 26 characters used in the English language.
001072 **
001073 ** At the moment there is only a UTF-8 implementation.
001074 */
001075 static int nocaseCollatingFunc(
001076 void *NotUsed,
001077 int nKey1, const void *pKey1,
001078 int nKey2, const void *pKey2
001079 ){
001080 int r = sqlite3StrNICmp(
001081 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
001082 UNUSED_PARAMETER(NotUsed);
001083 if( 0==r ){
001084 r = nKey1-nKey2;
001085 }
001086 return r;
001087 }
001088
001089 /*
001090 ** Return the ROWID of the most recent insert
001091 */
001092 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
001093 #ifdef SQLITE_ENABLE_API_ARMOR
001094 if( !sqlite3SafetyCheckOk(db) ){
001095 (void)SQLITE_MISUSE_BKPT;
001096 return 0;
001097 }
001098 #endif
001099 return db->lastRowid;
001100 }
001101
001102 /*
001103 ** Set the value returned by the sqlite3_last_insert_rowid() API function.
001104 */
001105 void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
001106 #ifdef SQLITE_ENABLE_API_ARMOR
001107 if( !sqlite3SafetyCheckOk(db) ){
001108 (void)SQLITE_MISUSE_BKPT;
001109 return;
001110 }
001111 #endif
001112 sqlite3_mutex_enter(db->mutex);
001113 db->lastRowid = iRowid;
001114 sqlite3_mutex_leave(db->mutex);
001115 }
001116
001117 /*
001118 ** Return the number of changes in the most recent call to sqlite3_exec().
001119 */
001120 sqlite3_int64 sqlite3_changes64(sqlite3 *db){
001121 #ifdef SQLITE_ENABLE_API_ARMOR
001122 if( !sqlite3SafetyCheckOk(db) ){
001123 (void)SQLITE_MISUSE_BKPT;
001124 return 0;
001125 }
001126 #endif
001127 return db->nChange;
001128 }
001129 int sqlite3_changes(sqlite3 *db){
001130 return (int)sqlite3_changes64(db);
001131 }
001132
001133 /*
001134 ** Return the number of changes since the database handle was opened.
001135 */
001136 sqlite3_int64 sqlite3_total_changes64(sqlite3 *db){
001137 #ifdef SQLITE_ENABLE_API_ARMOR
001138 if( !sqlite3SafetyCheckOk(db) ){
001139 (void)SQLITE_MISUSE_BKPT;
001140 return 0;
001141 }
001142 #endif
001143 return db->nTotalChange;
001144 }
001145 int sqlite3_total_changes(sqlite3 *db){
001146 return (int)sqlite3_total_changes64(db);
001147 }
001148
001149 /*
001150 ** Close all open savepoints. This function only manipulates fields of the
001151 ** database handle object, it does not close any savepoints that may be open
001152 ** at the b-tree/pager level.
001153 */
001154 void sqlite3CloseSavepoints(sqlite3 *db){
001155 while( db->pSavepoint ){
001156 Savepoint *pTmp = db->pSavepoint;
001157 db->pSavepoint = pTmp->pNext;
001158 sqlite3DbFree(db, pTmp);
001159 }
001160 db->nSavepoint = 0;
001161 db->nStatement = 0;
001162 db->isTransactionSavepoint = 0;
001163 }
001164
001165 /*
001166 ** Invoke the destructor function associated with FuncDef p, if any. Except,
001167 ** if this is not the last copy of the function, do not invoke it. Multiple
001168 ** copies of a single function are created when create_function() is called
001169 ** with SQLITE_ANY as the encoding.
001170 */
001171 static void functionDestroy(sqlite3 *db, FuncDef *p){
001172 FuncDestructor *pDestructor;
001173 assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
001174 pDestructor = p->u.pDestructor;
001175 if( pDestructor ){
001176 pDestructor->nRef--;
001177 if( pDestructor->nRef==0 ){
001178 pDestructor->xDestroy(pDestructor->pUserData);
001179 sqlite3DbFree(db, pDestructor);
001180 }
001181 }
001182 }
001183
001184 /*
001185 ** Disconnect all sqlite3_vtab objects that belong to database connection
001186 ** db. This is called when db is being closed.
001187 */
001188 static void disconnectAllVtab(sqlite3 *db){
001189 #ifndef SQLITE_OMIT_VIRTUALTABLE
001190 int i;
001191 HashElem *p;
001192 sqlite3BtreeEnterAll(db);
001193 for(i=0; i<db->nDb; i++){
001194 Schema *pSchema = db->aDb[i].pSchema;
001195 if( pSchema ){
001196 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
001197 Table *pTab = (Table *)sqliteHashData(p);
001198 if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
001199 }
001200 }
001201 }
001202 for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
001203 Module *pMod = (Module *)sqliteHashData(p);
001204 if( pMod->pEpoTab ){
001205 sqlite3VtabDisconnect(db, pMod->pEpoTab);
001206 }
001207 }
001208 sqlite3VtabUnlockList(db);
001209 sqlite3BtreeLeaveAll(db);
001210 #else
001211 UNUSED_PARAMETER(db);
001212 #endif
001213 }
001214
001215 /*
001216 ** Return TRUE if database connection db has unfinalized prepared
001217 ** statements or unfinished sqlite3_backup objects.
001218 */
001219 static int connectionIsBusy(sqlite3 *db){
001220 int j;
001221 assert( sqlite3_mutex_held(db->mutex) );
001222 if( db->pVdbe ) return 1;
001223 for(j=0; j<db->nDb; j++){
001224 Btree *pBt = db->aDb[j].pBt;
001225 if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
001226 }
001227 return 0;
001228 }
001229
001230 /*
001231 ** Close an existing SQLite database
001232 */
001233 static int sqlite3Close(sqlite3 *db, int forceZombie){
001234 if( !db ){
001235 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
001236 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
001237 return SQLITE_OK;
001238 }
001239 if( !sqlite3SafetyCheckSickOrOk(db) ){
001240 return SQLITE_MISUSE_BKPT;
001241 }
001242 sqlite3_mutex_enter(db->mutex);
001243 if( db->mTrace & SQLITE_TRACE_CLOSE ){
001244 db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
001245 }
001246
001247 /* Force xDisconnect calls on all virtual tables */
001248 disconnectAllVtab(db);
001249
001250 /* If a transaction is open, the disconnectAllVtab() call above
001251 ** will not have called the xDisconnect() method on any virtual
001252 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
001253 ** call will do so. We need to do this before the check for active
001254 ** SQL statements below, as the v-table implementation may be storing
001255 ** some prepared statements internally.
001256 */
001257 sqlite3VtabRollback(db);
001258
001259 /* Legacy behavior (sqlite3_close() behavior) is to return
001260 ** SQLITE_BUSY if the connection can not be closed immediately.
001261 */
001262 if( !forceZombie && connectionIsBusy(db) ){
001263 sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
001264 "statements or unfinished backups");
001265 sqlite3_mutex_leave(db->mutex);
001266 return SQLITE_BUSY;
001267 }
001268
001269 #ifdef SQLITE_ENABLE_SQLLOG
001270 if( sqlite3GlobalConfig.xSqllog ){
001271 /* Closing the handle. Fourth parameter is passed the value 2. */
001272 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
001273 }
001274 #endif
001275
001276 while( db->pDbData ){
001277 DbClientData *p = db->pDbData;
001278 db->pDbData = p->pNext;
001279 assert( p->pData!=0 );
001280 if( p->xDestructor ) p->xDestructor(p->pData);
001281 sqlite3_free(p);
001282 }
001283
001284 /* Convert the connection into a zombie and then close it.
001285 */
001286 db->eOpenState = SQLITE_STATE_ZOMBIE;
001287 sqlite3LeaveMutexAndCloseZombie(db);
001288 return SQLITE_OK;
001289 }
001290
001291 /*
001292 ** Return the transaction state for a single databse, or the maximum
001293 ** transaction state over all attached databases if zSchema is null.
001294 */
001295 int sqlite3_txn_state(sqlite3 *db, const char *zSchema){
001296 int iDb, nDb;
001297 int iTxn = -1;
001298 #ifdef SQLITE_ENABLE_API_ARMOR
001299 if( !sqlite3SafetyCheckOk(db) ){
001300 (void)SQLITE_MISUSE_BKPT;
001301 return -1;
001302 }
001303 #endif
001304 sqlite3_mutex_enter(db->mutex);
001305 if( zSchema ){
001306 nDb = iDb = sqlite3FindDbName(db, zSchema);
001307 if( iDb<0 ) nDb--;
001308 }else{
001309 iDb = 0;
001310 nDb = db->nDb-1;
001311 }
001312 for(; iDb<=nDb; iDb++){
001313 Btree *pBt = db->aDb[iDb].pBt;
001314 int x = pBt!=0 ? sqlite3BtreeTxnState(pBt) : SQLITE_TXN_NONE;
001315 if( x>iTxn ) iTxn = x;
001316 }
001317 sqlite3_mutex_leave(db->mutex);
001318 return iTxn;
001319 }
001320
001321 /*
001322 ** Two variations on the public interface for closing a database
001323 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
001324 ** leaves the connection open if there are unfinalized prepared
001325 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
001326 ** version forces the connection to become a zombie if there are
001327 ** unclosed resources, and arranges for deallocation when the last
001328 ** prepare statement or sqlite3_backup closes.
001329 */
001330 int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
001331 int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
001332
001333
001334 /*
001335 ** Close the mutex on database connection db.
001336 **
001337 ** Furthermore, if database connection db is a zombie (meaning that there
001338 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
001339 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
001340 ** finished, then free all resources.
001341 */
001342 void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
001343 HashElem *i; /* Hash table iterator */
001344 int j;
001345
001346 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
001347 ** or if the connection has not yet been closed by sqlite3_close_v2(),
001348 ** then just leave the mutex and return.
001349 */
001350 if( db->eOpenState!=SQLITE_STATE_ZOMBIE || connectionIsBusy(db) ){
001351 sqlite3_mutex_leave(db->mutex);
001352 return;
001353 }
001354
001355 /* If we reach this point, it means that the database connection has
001356 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
001357 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
001358 ** go ahead and free all resources.
001359 */
001360
001361 /* If a transaction is open, roll it back. This also ensures that if
001362 ** any database schemas have been modified by an uncommitted transaction
001363 ** they are reset. And that the required b-tree mutex is held to make
001364 ** the pager rollback and schema reset an atomic operation. */
001365 sqlite3RollbackAll(db, SQLITE_OK);
001366
001367 /* Free any outstanding Savepoint structures. */
001368 sqlite3CloseSavepoints(db);
001369
001370 /* Close all database connections */
001371 for(j=0; j<db->nDb; j++){
001372 struct Db *pDb = &db->aDb[j];
001373 if( pDb->pBt ){
001374 sqlite3BtreeClose(pDb->pBt);
001375 pDb->pBt = 0;
001376 if( j!=1 ){
001377 pDb->pSchema = 0;
001378 }
001379 }
001380 }
001381 /* Clear the TEMP schema separately and last */
001382 if( db->aDb[1].pSchema ){
001383 sqlite3SchemaClear(db->aDb[1].pSchema);
001384 }
001385 sqlite3VtabUnlockList(db);
001386
001387 /* Free up the array of auxiliary databases */
001388 sqlite3CollapseDatabaseArray(db);
001389 assert( db->nDb<=2 );
001390 assert( db->aDb==db->aDbStatic );
001391
001392 /* Tell the code in notify.c that the connection no longer holds any
001393 ** locks and does not require any further unlock-notify callbacks.
001394 */
001395 sqlite3ConnectionClosed(db);
001396
001397 for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
001398 FuncDef *pNext, *p;
001399 p = sqliteHashData(i);
001400 do{
001401 functionDestroy(db, p);
001402 pNext = p->pNext;
001403 sqlite3DbFree(db, p);
001404 p = pNext;
001405 }while( p );
001406 }
001407 sqlite3HashClear(&db->aFunc);
001408 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
001409 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
001410 /* Invoke any destructors registered for collation sequence user data. */
001411 for(j=0; j<3; j++){
001412 if( pColl[j].xDel ){
001413 pColl[j].xDel(pColl[j].pUser);
001414 }
001415 }
001416 sqlite3DbFree(db, pColl);
001417 }
001418 sqlite3HashClear(&db->aCollSeq);
001419 #ifndef SQLITE_OMIT_VIRTUALTABLE
001420 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
001421 Module *pMod = (Module *)sqliteHashData(i);
001422 sqlite3VtabEponymousTableClear(db, pMod);
001423 sqlite3VtabModuleUnref(db, pMod);
001424 }
001425 sqlite3HashClear(&db->aModule);
001426 #endif
001427
001428 sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
001429 sqlite3ValueFree(db->pErr);
001430 sqlite3CloseExtensions(db);
001431
001432 db->eOpenState = SQLITE_STATE_ERROR;
001433
001434 /* The temp-database schema is allocated differently from the other schema
001435 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
001436 ** So it needs to be freed here. Todo: Why not roll the temp schema into
001437 ** the same sqliteMalloc() as the one that allocates the database
001438 ** structure?
001439 */
001440 sqlite3DbFree(db, db->aDb[1].pSchema);
001441 if( db->xAutovacDestr ){
001442 db->xAutovacDestr(db->pAutovacPagesArg);
001443 }
001444 sqlite3_mutex_leave(db->mutex);
001445 db->eOpenState = SQLITE_STATE_CLOSED;
001446 sqlite3_mutex_free(db->mutex);
001447 assert( sqlite3LookasideUsed(db,0)==0 );
001448 if( db->lookaside.bMalloced ){
001449 sqlite3_free(db->lookaside.pStart);
001450 }
001451 sqlite3_free(db);
001452 }
001453
001454 /*
001455 ** Rollback all database files. If tripCode is not SQLITE_OK, then
001456 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
001457 ** breaker") and made to return tripCode if there are any further
001458 ** attempts to use that cursor. Read cursors remain open and valid
001459 ** but are "saved" in case the table pages are moved around.
001460 */
001461 void sqlite3RollbackAll(sqlite3 *db, int tripCode){
001462 int i;
001463 int inTrans = 0;
001464 int schemaChange;
001465 assert( sqlite3_mutex_held(db->mutex) );
001466 sqlite3BeginBenignMalloc();
001467
001468 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
001469 ** This is important in case the transaction being rolled back has
001470 ** modified the database schema. If the b-tree mutexes are not taken
001471 ** here, then another shared-cache connection might sneak in between
001472 ** the database rollback and schema reset, which can cause false
001473 ** corruption reports in some cases. */
001474 sqlite3BtreeEnterAll(db);
001475 schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
001476
001477 for(i=0; i<db->nDb; i++){
001478 Btree *p = db->aDb[i].pBt;
001479 if( p ){
001480 if( sqlite3BtreeTxnState(p)==SQLITE_TXN_WRITE ){
001481 inTrans = 1;
001482 }
001483 sqlite3BtreeRollback(p, tripCode, !schemaChange);
001484 }
001485 }
001486 sqlite3VtabRollback(db);
001487 sqlite3EndBenignMalloc();
001488
001489 if( schemaChange ){
001490 sqlite3ExpirePreparedStatements(db, 0);
001491 sqlite3ResetAllSchemasOfConnection(db);
001492 }
001493 sqlite3BtreeLeaveAll(db);
001494
001495 /* Any deferred constraint violations have now been resolved. */
001496 db->nDeferredCons = 0;
001497 db->nDeferredImmCons = 0;
001498 db->flags &= ~(u64)(SQLITE_DeferFKs|SQLITE_CorruptRdOnly);
001499
001500 /* If one has been configured, invoke the rollback-hook callback */
001501 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
001502 db->xRollbackCallback(db->pRollbackArg);
001503 }
001504 }
001505
001506 /*
001507 ** Return a static string containing the name corresponding to the error code
001508 ** specified in the argument.
001509 */
001510 #if defined(SQLITE_NEED_ERR_NAME)
001511 const char *sqlite3ErrName(int rc){
001512 const char *zName = 0;
001513 int i, origRc = rc;
001514 for(i=0; i<2 && zName==0; i++, rc &= 0xff){
001515 switch( rc ){
001516 case SQLITE_OK: zName = "SQLITE_OK"; break;
001517 case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
001518 case SQLITE_ERROR_SNAPSHOT: zName = "SQLITE_ERROR_SNAPSHOT"; break;
001519 case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
001520 case SQLITE_PERM: zName = "SQLITE_PERM"; break;
001521 case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
001522 case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
001523 case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
001524 case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
001525 case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
001526 case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
001527 case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
001528 case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
001529 case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
001530 case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
001531 case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break;
001532 case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
001533 case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
001534 case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
001535 case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
001536 case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
001537 case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
001538 case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
001539 case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
001540 case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
001541 case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
001542 case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
001543 case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
001544 case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
001545 case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
001546 case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
001547 case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
001548 case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
001549 case SQLITE_IOERR_CHECKRESERVEDLOCK:
001550 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
001551 case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
001552 case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
001553 case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
001554 case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
001555 case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
001556 case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
001557 case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
001558 case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
001559 case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
001560 case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
001561 case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
001562 case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
001563 case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
001564 case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
001565 case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
001566 case SQLITE_FULL: zName = "SQLITE_FULL"; break;
001567 case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
001568 case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
001569 case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
001570 case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
001571 case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
001572 case SQLITE_CANTOPEN_SYMLINK: zName = "SQLITE_CANTOPEN_SYMLINK"; break;
001573 case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
001574 case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
001575 case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
001576 case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
001577 case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
001578 case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
001579 case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
001580 case SQLITE_CONSTRAINT_FOREIGNKEY:
001581 zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
001582 case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
001583 case SQLITE_CONSTRAINT_PRIMARYKEY:
001584 zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
001585 case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
001586 case SQLITE_CONSTRAINT_COMMITHOOK:
001587 zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
001588 case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
001589 case SQLITE_CONSTRAINT_FUNCTION:
001590 zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
001591 case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
001592 case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
001593 case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
001594 case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
001595 case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
001596 case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
001597 case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
001598 case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
001599 case SQLITE_ROW: zName = "SQLITE_ROW"; break;
001600 case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
001601 case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
001602 case SQLITE_NOTICE_RECOVER_ROLLBACK:
001603 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
001604 case SQLITE_NOTICE_RBU: zName = "SQLITE_NOTICE_RBU"; break;
001605 case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
001606 case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
001607 case SQLITE_DONE: zName = "SQLITE_DONE"; break;
001608 }
001609 }
001610 if( zName==0 ){
001611 static char zBuf[50];
001612 sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
001613 zName = zBuf;
001614 }
001615 return zName;
001616 }
001617 #endif
001618
001619 /*
001620 ** Return a static string that describes the kind of error specified in the
001621 ** argument.
001622 */
001623 const char *sqlite3ErrStr(int rc){
001624 static const char* const aMsg[] = {
001625 /* SQLITE_OK */ "not an error",
001626 /* SQLITE_ERROR */ "SQL logic error",
001627 /* SQLITE_INTERNAL */ 0,
001628 /* SQLITE_PERM */ "access permission denied",
001629 /* SQLITE_ABORT */ "query aborted",
001630 /* SQLITE_BUSY */ "database is locked",
001631 /* SQLITE_LOCKED */ "database table is locked",
001632 /* SQLITE_NOMEM */ "out of memory",
001633 /* SQLITE_READONLY */ "attempt to write a readonly database",
001634 /* SQLITE_INTERRUPT */ "interrupted",
001635 /* SQLITE_IOERR */ "disk I/O error",
001636 /* SQLITE_CORRUPT */ "database disk image is malformed",
001637 /* SQLITE_NOTFOUND */ "unknown operation",
001638 /* SQLITE_FULL */ "database or disk is full",
001639 /* SQLITE_CANTOPEN */ "unable to open database file",
001640 /* SQLITE_PROTOCOL */ "locking protocol",
001641 /* SQLITE_EMPTY */ 0,
001642 /* SQLITE_SCHEMA */ "database schema has changed",
001643 /* SQLITE_TOOBIG */ "string or blob too big",
001644 /* SQLITE_CONSTRAINT */ "constraint failed",
001645 /* SQLITE_MISMATCH */ "datatype mismatch",
001646 /* SQLITE_MISUSE */ "bad parameter or other API misuse",
001647 #ifdef SQLITE_DISABLE_LFS
001648 /* SQLITE_NOLFS */ "large file support is disabled",
001649 #else
001650 /* SQLITE_NOLFS */ 0,
001651 #endif
001652 /* SQLITE_AUTH */ "authorization denied",
001653 /* SQLITE_FORMAT */ 0,
001654 /* SQLITE_RANGE */ "column index out of range",
001655 /* SQLITE_NOTADB */ "file is not a database",
001656 /* SQLITE_NOTICE */ "notification message",
001657 /* SQLITE_WARNING */ "warning message",
001658 };
001659 const char *zErr = "unknown error";
001660 switch( rc ){
001661 case SQLITE_ABORT_ROLLBACK: {
001662 zErr = "abort due to ROLLBACK";
001663 break;
001664 }
001665 case SQLITE_ROW: {
001666 zErr = "another row available";
001667 break;
001668 }
001669 case SQLITE_DONE: {
001670 zErr = "no more rows available";
001671 break;
001672 }
001673 default: {
001674 rc &= 0xff;
001675 if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
001676 zErr = aMsg[rc];
001677 }
001678 break;
001679 }
001680 }
001681 return zErr;
001682 }
001683
001684 /*
001685 ** This routine implements a busy callback that sleeps and tries
001686 ** again until a timeout value is reached. The timeout value is
001687 ** an integer number of milliseconds passed in as the first
001688 ** argument.
001689 **
001690 ** Return non-zero to retry the lock. Return zero to stop trying
001691 ** and cause SQLite to return SQLITE_BUSY.
001692 */
001693 static int sqliteDefaultBusyCallback(
001694 void *ptr, /* Database connection */
001695 int count /* Number of times table has been busy */
001696 ){
001697 #if SQLITE_OS_WIN || !defined(HAVE_NANOSLEEP) || HAVE_NANOSLEEP
001698 /* This case is for systems that have support for sleeping for fractions of
001699 ** a second. Examples: All windows systems, unix systems with nanosleep() */
001700 static const u8 delays[] =
001701 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
001702 static const u8 totals[] =
001703 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
001704 # define NDELAY ArraySize(delays)
001705 sqlite3 *db = (sqlite3 *)ptr;
001706 int tmout = db->busyTimeout;
001707 int delay, prior;
001708
001709 assert( count>=0 );
001710 if( count < NDELAY ){
001711 delay = delays[count];
001712 prior = totals[count];
001713 }else{
001714 delay = delays[NDELAY-1];
001715 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
001716 }
001717 if( prior + delay > tmout ){
001718 delay = tmout - prior;
001719 if( delay<=0 ) return 0;
001720 }
001721 sqlite3OsSleep(db->pVfs, delay*1000);
001722 return 1;
001723 #else
001724 /* This case for unix systems that lack usleep() support. Sleeping
001725 ** must be done in increments of whole seconds */
001726 sqlite3 *db = (sqlite3 *)ptr;
001727 int tmout = ((sqlite3 *)ptr)->busyTimeout;
001728 if( (count+1)*1000 > tmout ){
001729 return 0;
001730 }
001731 sqlite3OsSleep(db->pVfs, 1000000);
001732 return 1;
001733 #endif
001734 }
001735
001736 /*
001737 ** Invoke the given busy handler.
001738 **
001739 ** This routine is called when an operation failed to acquire a
001740 ** lock on VFS file pFile.
001741 **
001742 ** If this routine returns non-zero, the lock is retried. If it
001743 ** returns 0, the operation aborts with an SQLITE_BUSY error.
001744 */
001745 int sqlite3InvokeBusyHandler(BusyHandler *p){
001746 int rc;
001747 if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
001748 rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
001749 if( rc==0 ){
001750 p->nBusy = -1;
001751 }else{
001752 p->nBusy++;
001753 }
001754 return rc;
001755 }
001756
001757 /*
001758 ** This routine sets the busy callback for an Sqlite database to the
001759 ** given callback function with the given argument.
001760 */
001761 int sqlite3_busy_handler(
001762 sqlite3 *db,
001763 int (*xBusy)(void*,int),
001764 void *pArg
001765 ){
001766 #ifdef SQLITE_ENABLE_API_ARMOR
001767 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
001768 #endif
001769 sqlite3_mutex_enter(db->mutex);
001770 db->busyHandler.xBusyHandler = xBusy;
001771 db->busyHandler.pBusyArg = pArg;
001772 db->busyHandler.nBusy = 0;
001773 db->busyTimeout = 0;
001774 sqlite3_mutex_leave(db->mutex);
001775 return SQLITE_OK;
001776 }
001777
001778 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
001779 /*
001780 ** This routine sets the progress callback for an Sqlite database to the
001781 ** given callback function with the given argument. The progress callback will
001782 ** be invoked every nOps opcodes.
001783 */
001784 void sqlite3_progress_handler(
001785 sqlite3 *db,
001786 int nOps,
001787 int (*xProgress)(void*),
001788 void *pArg
001789 ){
001790 #ifdef SQLITE_ENABLE_API_ARMOR
001791 if( !sqlite3SafetyCheckOk(db) ){
001792 (void)SQLITE_MISUSE_BKPT;
001793 return;
001794 }
001795 #endif
001796 sqlite3_mutex_enter(db->mutex);
001797 if( nOps>0 ){
001798 db->xProgress = xProgress;
001799 db->nProgressOps = (unsigned)nOps;
001800 db->pProgressArg = pArg;
001801 }else{
001802 db->xProgress = 0;
001803 db->nProgressOps = 0;
001804 db->pProgressArg = 0;
001805 }
001806 sqlite3_mutex_leave(db->mutex);
001807 }
001808 #endif
001809
001810
001811 /*
001812 ** This routine installs a default busy handler that waits for the
001813 ** specified number of milliseconds before returning 0.
001814 */
001815 int sqlite3_busy_timeout(sqlite3 *db, int ms){
001816 #ifdef SQLITE_ENABLE_API_ARMOR
001817 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
001818 #endif
001819 if( ms>0 ){
001820 sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
001821 (void*)db);
001822 db->busyTimeout = ms;
001823 }else{
001824 sqlite3_busy_handler(db, 0, 0);
001825 }
001826 return SQLITE_OK;
001827 }
001828
001829 /*
001830 ** Cause any pending operation to stop at its earliest opportunity.
001831 */
001832 void sqlite3_interrupt(sqlite3 *db){
001833 #ifdef SQLITE_ENABLE_API_ARMOR
001834 if( !sqlite3SafetyCheckOk(db)
001835 && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE)
001836 ){
001837 (void)SQLITE_MISUSE_BKPT;
001838 return;
001839 }
001840 #endif
001841 AtomicStore(&db->u1.isInterrupted, 1);
001842 }
001843
001844 /*
001845 ** Return true or false depending on whether or not an interrupt is
001846 ** pending on connection db.
001847 */
001848 int sqlite3_is_interrupted(sqlite3 *db){
001849 #ifdef SQLITE_ENABLE_API_ARMOR
001850 if( !sqlite3SafetyCheckOk(db)
001851 && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE)
001852 ){
001853 (void)SQLITE_MISUSE_BKPT;
001854 return 0;
001855 }
001856 #endif
001857 return AtomicLoad(&db->u1.isInterrupted)!=0;
001858 }
001859
001860 /*
001861 ** This function is exactly the same as sqlite3_create_function(), except
001862 ** that it is designed to be called by internal code. The difference is
001863 ** that if a malloc() fails in sqlite3_create_function(), an error code
001864 ** is returned and the mallocFailed flag cleared.
001865 */
001866 int sqlite3CreateFunc(
001867 sqlite3 *db,
001868 const char *zFunctionName,
001869 int nArg,
001870 int enc,
001871 void *pUserData,
001872 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
001873 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
001874 void (*xFinal)(sqlite3_context*),
001875 void (*xValue)(sqlite3_context*),
001876 void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
001877 FuncDestructor *pDestructor
001878 ){
001879 FuncDef *p;
001880 int extraFlags;
001881
001882 assert( sqlite3_mutex_held(db->mutex) );
001883 assert( xValue==0 || xSFunc==0 );
001884 if( zFunctionName==0 /* Must have a valid name */
001885 || (xSFunc!=0 && xFinal!=0) /* Not both xSFunc and xFinal */
001886 || ((xFinal==0)!=(xStep==0)) /* Both or neither of xFinal and xStep */
001887 || ((xValue==0)!=(xInverse==0)) /* Both or neither of xValue, xInverse */
001888 || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
001889 || (255<sqlite3Strlen30(zFunctionName))
001890 ){
001891 return SQLITE_MISUSE_BKPT;
001892 }
001893
001894 assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
001895 assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY );
001896 extraFlags = enc & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|
001897 SQLITE_SUBTYPE|SQLITE_INNOCUOUS|
001898 SQLITE_RESULT_SUBTYPE|SQLITE_SELFORDER1);
001899 enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
001900
001901 /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE. But
001902 ** the meaning is inverted. So flip the bit. */
001903 assert( SQLITE_FUNC_UNSAFE==SQLITE_INNOCUOUS );
001904 extraFlags ^= SQLITE_FUNC_UNSAFE; /* tag-20230109-1 */
001905
001906
001907 #ifndef SQLITE_OMIT_UTF16
001908 /* If SQLITE_UTF16 is specified as the encoding type, transform this
001909 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
001910 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
001911 **
001912 ** If SQLITE_ANY is specified, add three versions of the function
001913 ** to the hash table.
001914 */
001915 switch( enc ){
001916 case SQLITE_UTF16:
001917 enc = SQLITE_UTF16NATIVE;
001918 break;
001919 case SQLITE_ANY: {
001920 int rc;
001921 rc = sqlite3CreateFunc(db, zFunctionName, nArg,
001922 (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE, /* tag-20230109-1 */
001923 pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
001924 if( rc==SQLITE_OK ){
001925 rc = sqlite3CreateFunc(db, zFunctionName, nArg,
001926 (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE, /* tag-20230109-1*/
001927 pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
001928 }
001929 if( rc!=SQLITE_OK ){
001930 return rc;
001931 }
001932 enc = SQLITE_UTF16BE;
001933 break;
001934 }
001935 case SQLITE_UTF8:
001936 case SQLITE_UTF16LE:
001937 case SQLITE_UTF16BE:
001938 break;
001939 default:
001940 enc = SQLITE_UTF8;
001941 break;
001942 }
001943 #else
001944 enc = SQLITE_UTF8;
001945 #endif
001946
001947 /* Check if an existing function is being overridden or deleted. If so,
001948 ** and there are active VMs, then return SQLITE_BUSY. If a function
001949 ** is being overridden/deleted but there are no active VMs, allow the
001950 ** operation to continue but invalidate all precompiled statements.
001951 */
001952 p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
001953 if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
001954 if( db->nVdbeActive ){
001955 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
001956 "unable to delete/modify user-function due to active statements");
001957 assert( !db->mallocFailed );
001958 return SQLITE_BUSY;
001959 }else{
001960 sqlite3ExpirePreparedStatements(db, 0);
001961 }
001962 }else if( xSFunc==0 && xFinal==0 ){
001963 /* Trying to delete a function that does not exist. This is a no-op.
001964 ** https://sqlite.org/forum/forumpost/726219164b */
001965 return SQLITE_OK;
001966 }
001967
001968 p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
001969 assert(p || db->mallocFailed);
001970 if( !p ){
001971 return SQLITE_NOMEM_BKPT;
001972 }
001973
001974 /* If an older version of the function with a configured destructor is
001975 ** being replaced invoke the destructor function here. */
001976 functionDestroy(db, p);
001977
001978 if( pDestructor ){
001979 pDestructor->nRef++;
001980 }
001981 p->u.pDestructor = pDestructor;
001982 p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
001983 testcase( p->funcFlags & SQLITE_DETERMINISTIC );
001984 testcase( p->funcFlags & SQLITE_DIRECTONLY );
001985 p->xSFunc = xSFunc ? xSFunc : xStep;
001986 p->xFinalize = xFinal;
001987 p->xValue = xValue;
001988 p->xInverse = xInverse;
001989 p->pUserData = pUserData;
001990 p->nArg = (u16)nArg;
001991 return SQLITE_OK;
001992 }
001993
001994 /*
001995 ** Worker function used by utf-8 APIs that create new functions:
001996 **
001997 ** sqlite3_create_function()
001998 ** sqlite3_create_function_v2()
001999 ** sqlite3_create_window_function()
002000 */
002001 static int createFunctionApi(
002002 sqlite3 *db,
002003 const char *zFunc,
002004 int nArg,
002005 int enc,
002006 void *p,
002007 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
002008 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
002009 void (*xFinal)(sqlite3_context*),
002010 void (*xValue)(sqlite3_context*),
002011 void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
002012 void(*xDestroy)(void*)
002013 ){
002014 int rc = SQLITE_ERROR;
002015 FuncDestructor *pArg = 0;
002016
002017 #ifdef SQLITE_ENABLE_API_ARMOR
002018 if( !sqlite3SafetyCheckOk(db) ){
002019 return SQLITE_MISUSE_BKPT;
002020 }
002021 #endif
002022 sqlite3_mutex_enter(db->mutex);
002023 if( xDestroy ){
002024 pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
002025 if( !pArg ){
002026 sqlite3OomFault(db);
002027 xDestroy(p);
002028 goto out;
002029 }
002030 pArg->nRef = 0;
002031 pArg->xDestroy = xDestroy;
002032 pArg->pUserData = p;
002033 }
002034 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p,
002035 xSFunc, xStep, xFinal, xValue, xInverse, pArg
002036 );
002037 if( pArg && pArg->nRef==0 ){
002038 assert( rc!=SQLITE_OK || (xStep==0 && xFinal==0) );
002039 xDestroy(p);
002040 sqlite3_free(pArg);
002041 }
002042
002043 out:
002044 rc = sqlite3ApiExit(db, rc);
002045 sqlite3_mutex_leave(db->mutex);
002046 return rc;
002047 }
002048
002049 /*
002050 ** Create new user functions.
002051 */
002052 int sqlite3_create_function(
002053 sqlite3 *db,
002054 const char *zFunc,
002055 int nArg,
002056 int enc,
002057 void *p,
002058 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
002059 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
002060 void (*xFinal)(sqlite3_context*)
002061 ){
002062 return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
002063 xFinal, 0, 0, 0);
002064 }
002065 int sqlite3_create_function_v2(
002066 sqlite3 *db,
002067 const char *zFunc,
002068 int nArg,
002069 int enc,
002070 void *p,
002071 void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
002072 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
002073 void (*xFinal)(sqlite3_context*),
002074 void (*xDestroy)(void *)
002075 ){
002076 return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
002077 xFinal, 0, 0, xDestroy);
002078 }
002079 int sqlite3_create_window_function(
002080 sqlite3 *db,
002081 const char *zFunc,
002082 int nArg,
002083 int enc,
002084 void *p,
002085 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
002086 void (*xFinal)(sqlite3_context*),
002087 void (*xValue)(sqlite3_context*),
002088 void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
002089 void (*xDestroy)(void *)
002090 ){
002091 return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
002092 xFinal, xValue, xInverse, xDestroy);
002093 }
002094
002095 #ifndef SQLITE_OMIT_UTF16
002096 int sqlite3_create_function16(
002097 sqlite3 *db,
002098 const void *zFunctionName,
002099 int nArg,
002100 int eTextRep,
002101 void *p,
002102 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
002103 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
002104 void (*xFinal)(sqlite3_context*)
002105 ){
002106 int rc;
002107 char *zFunc8;
002108
002109 #ifdef SQLITE_ENABLE_API_ARMOR
002110 if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
002111 #endif
002112 sqlite3_mutex_enter(db->mutex);
002113 assert( !db->mallocFailed );
002114 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
002115 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
002116 sqlite3DbFree(db, zFunc8);
002117 rc = sqlite3ApiExit(db, rc);
002118 sqlite3_mutex_leave(db->mutex);
002119 return rc;
002120 }
002121 #endif
002122
002123
002124 /*
002125 ** The following is the implementation of an SQL function that always
002126 ** fails with an error message stating that the function is used in the
002127 ** wrong context. The sqlite3_overload_function() API might construct
002128 ** SQL function that use this routine so that the functions will exist
002129 ** for name resolution but are actually overloaded by the xFindFunction
002130 ** method of virtual tables.
002131 */
002132 static void sqlite3InvalidFunction(
002133 sqlite3_context *context, /* The function calling context */
002134 int NotUsed, /* Number of arguments to the function */
002135 sqlite3_value **NotUsed2 /* Value of each argument */
002136 ){
002137 const char *zName = (const char*)sqlite3_user_data(context);
002138 char *zErr;
002139 UNUSED_PARAMETER2(NotUsed, NotUsed2);
002140 zErr = sqlite3_mprintf(
002141 "unable to use function %s in the requested context", zName);
002142 sqlite3_result_error(context, zErr, -1);
002143 sqlite3_free(zErr);
002144 }
002145
002146 /*
002147 ** Declare that a function has been overloaded by a virtual table.
002148 **
002149 ** If the function already exists as a regular global function, then
002150 ** this routine is a no-op. If the function does not exist, then create
002151 ** a new one that always throws a run-time error.
002152 **
002153 ** When virtual tables intend to provide an overloaded function, they
002154 ** should call this routine to make sure the global function exists.
002155 ** A global function must exist in order for name resolution to work
002156 ** properly.
002157 */
002158 int sqlite3_overload_function(
002159 sqlite3 *db,
002160 const char *zName,
002161 int nArg
002162 ){
002163 int rc;
002164 char *zCopy;
002165
002166 #ifdef SQLITE_ENABLE_API_ARMOR
002167 if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
002168 return SQLITE_MISUSE_BKPT;
002169 }
002170 #endif
002171 sqlite3_mutex_enter(db->mutex);
002172 rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
002173 sqlite3_mutex_leave(db->mutex);
002174 if( rc ) return SQLITE_OK;
002175 zCopy = sqlite3_mprintf("%s", zName);
002176 if( zCopy==0 ) return SQLITE_NOMEM;
002177 return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
002178 zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
002179 }
002180
002181 #ifndef SQLITE_OMIT_TRACE
002182 /*
002183 ** Register a trace function. The pArg from the previously registered trace
002184 ** is returned.
002185 **
002186 ** A NULL trace function means that no tracing is executes. A non-NULL
002187 ** trace is a pointer to a function that is invoked at the start of each
002188 ** SQL statement.
002189 */
002190 #ifndef SQLITE_OMIT_DEPRECATED
002191 void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
002192 void *pOld;
002193
002194 #ifdef SQLITE_ENABLE_API_ARMOR
002195 if( !sqlite3SafetyCheckOk(db) ){
002196 (void)SQLITE_MISUSE_BKPT;
002197 return 0;
002198 }
002199 #endif
002200 sqlite3_mutex_enter(db->mutex);
002201 pOld = db->pTraceArg;
002202 db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
002203 db->trace.xLegacy = xTrace;
002204 db->pTraceArg = pArg;
002205 sqlite3_mutex_leave(db->mutex);
002206 return pOld;
002207 }
002208 #endif /* SQLITE_OMIT_DEPRECATED */
002209
002210 /* Register a trace callback using the version-2 interface.
002211 */
002212 int sqlite3_trace_v2(
002213 sqlite3 *db, /* Trace this connection */
002214 unsigned mTrace, /* Mask of events to be traced */
002215 int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
002216 void *pArg /* Context */
002217 ){
002218 #ifdef SQLITE_ENABLE_API_ARMOR
002219 if( !sqlite3SafetyCheckOk(db) ){
002220 return SQLITE_MISUSE_BKPT;
002221 }
002222 #endif
002223 sqlite3_mutex_enter(db->mutex);
002224 if( mTrace==0 ) xTrace = 0;
002225 if( xTrace==0 ) mTrace = 0;
002226 db->mTrace = mTrace;
002227 db->trace.xV2 = xTrace;
002228 db->pTraceArg = pArg;
002229 sqlite3_mutex_leave(db->mutex);
002230 return SQLITE_OK;
002231 }
002232
002233 #ifndef SQLITE_OMIT_DEPRECATED
002234 /*
002235 ** Register a profile function. The pArg from the previously registered
002236 ** profile function is returned.
002237 **
002238 ** A NULL profile function means that no profiling is executes. A non-NULL
002239 ** profile is a pointer to a function that is invoked at the conclusion of
002240 ** each SQL statement that is run.
002241 */
002242 void *sqlite3_profile(
002243 sqlite3 *db,
002244 void (*xProfile)(void*,const char*,sqlite_uint64),
002245 void *pArg
002246 ){
002247 void *pOld;
002248
002249 #ifdef SQLITE_ENABLE_API_ARMOR
002250 if( !sqlite3SafetyCheckOk(db) ){
002251 (void)SQLITE_MISUSE_BKPT;
002252 return 0;
002253 }
002254 #endif
002255 sqlite3_mutex_enter(db->mutex);
002256 pOld = db->pProfileArg;
002257 db->xProfile = xProfile;
002258 db->pProfileArg = pArg;
002259 db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;
002260 if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;
002261 sqlite3_mutex_leave(db->mutex);
002262 return pOld;
002263 }
002264 #endif /* SQLITE_OMIT_DEPRECATED */
002265 #endif /* SQLITE_OMIT_TRACE */
002266
002267 /*
002268 ** Register a function to be invoked when a transaction commits.
002269 ** If the invoked function returns non-zero, then the commit becomes a
002270 ** rollback.
002271 */
002272 void *sqlite3_commit_hook(
002273 sqlite3 *db, /* Attach the hook to this database */
002274 int (*xCallback)(void*), /* Function to invoke on each commit */
002275 void *pArg /* Argument to the function */
002276 ){
002277 void *pOld;
002278
002279 #ifdef SQLITE_ENABLE_API_ARMOR
002280 if( !sqlite3SafetyCheckOk(db) ){
002281 (void)SQLITE_MISUSE_BKPT;
002282 return 0;
002283 }
002284 #endif
002285 sqlite3_mutex_enter(db->mutex);
002286 pOld = db->pCommitArg;
002287 db->xCommitCallback = xCallback;
002288 db->pCommitArg = pArg;
002289 sqlite3_mutex_leave(db->mutex);
002290 return pOld;
002291 }
002292
002293 /*
002294 ** Register a callback to be invoked each time a row is updated,
002295 ** inserted or deleted using this database connection.
002296 */
002297 void *sqlite3_update_hook(
002298 sqlite3 *db, /* Attach the hook to this database */
002299 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
002300 void *pArg /* Argument to the function */
002301 ){
002302 void *pRet;
002303
002304 #ifdef SQLITE_ENABLE_API_ARMOR
002305 if( !sqlite3SafetyCheckOk(db) ){
002306 (void)SQLITE_MISUSE_BKPT;
002307 return 0;
002308 }
002309 #endif
002310 sqlite3_mutex_enter(db->mutex);
002311 pRet = db->pUpdateArg;
002312 db->xUpdateCallback = xCallback;
002313 db->pUpdateArg = pArg;
002314 sqlite3_mutex_leave(db->mutex);
002315 return pRet;
002316 }
002317
002318 /*
002319 ** Register a callback to be invoked each time a transaction is rolled
002320 ** back by this database connection.
002321 */
002322 void *sqlite3_rollback_hook(
002323 sqlite3 *db, /* Attach the hook to this database */
002324 void (*xCallback)(void*), /* Callback function */
002325 void *pArg /* Argument to the function */
002326 ){
002327 void *pRet;
002328
002329 #ifdef SQLITE_ENABLE_API_ARMOR
002330 if( !sqlite3SafetyCheckOk(db) ){
002331 (void)SQLITE_MISUSE_BKPT;
002332 return 0;
002333 }
002334 #endif
002335 sqlite3_mutex_enter(db->mutex);
002336 pRet = db->pRollbackArg;
002337 db->xRollbackCallback = xCallback;
002338 db->pRollbackArg = pArg;
002339 sqlite3_mutex_leave(db->mutex);
002340 return pRet;
002341 }
002342
002343 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
002344 /*
002345 ** Register a callback to be invoked each time a row is updated,
002346 ** inserted or deleted using this database connection.
002347 */
002348 void *sqlite3_preupdate_hook(
002349 sqlite3 *db, /* Attach the hook to this database */
002350 void(*xCallback)( /* Callback function */
002351 void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
002352 void *pArg /* First callback argument */
002353 ){
002354 void *pRet;
002355
002356 #ifdef SQLITE_ENABLE_API_ARMOR
002357 if( db==0 ){
002358 return 0;
002359 }
002360 #endif
002361 sqlite3_mutex_enter(db->mutex);
002362 pRet = db->pPreUpdateArg;
002363 db->xPreUpdateCallback = xCallback;
002364 db->pPreUpdateArg = pArg;
002365 sqlite3_mutex_leave(db->mutex);
002366 return pRet;
002367 }
002368 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
002369
002370 /*
002371 ** Register a function to be invoked prior to each autovacuum that
002372 ** determines the number of pages to vacuum.
002373 */
002374 int sqlite3_autovacuum_pages(
002375 sqlite3 *db, /* Attach the hook to this database */
002376 unsigned int (*xCallback)(void*,const char*,u32,u32,u32),
002377 void *pArg, /* Argument to the function */
002378 void (*xDestructor)(void*) /* Destructor for pArg */
002379 ){
002380 #ifdef SQLITE_ENABLE_API_ARMOR
002381 if( !sqlite3SafetyCheckOk(db) ){
002382 if( xDestructor ) xDestructor(pArg);
002383 return SQLITE_MISUSE_BKPT;
002384 }
002385 #endif
002386 sqlite3_mutex_enter(db->mutex);
002387 if( db->xAutovacDestr ){
002388 db->xAutovacDestr(db->pAutovacPagesArg);
002389 }
002390 db->xAutovacPages = xCallback;
002391 db->pAutovacPagesArg = pArg;
002392 db->xAutovacDestr = xDestructor;
002393 sqlite3_mutex_leave(db->mutex);
002394 return SQLITE_OK;
002395 }
002396
002397
002398 #ifndef SQLITE_OMIT_WAL
002399 /*
002400 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
002401 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
002402 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
002403 ** wal_autocheckpoint()).
002404 */
002405 int sqlite3WalDefaultHook(
002406 void *pClientData, /* Argument */
002407 sqlite3 *db, /* Connection */
002408 const char *zDb, /* Database */
002409 int nFrame /* Size of WAL */
002410 ){
002411 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
002412 sqlite3BeginBenignMalloc();
002413 sqlite3_wal_checkpoint(db, zDb);
002414 sqlite3EndBenignMalloc();
002415 }
002416 return SQLITE_OK;
002417 }
002418 #endif /* SQLITE_OMIT_WAL */
002419
002420 /*
002421 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
002422 ** a database after committing a transaction if there are nFrame or
002423 ** more frames in the log file. Passing zero or a negative value as the
002424 ** nFrame parameter disables automatic checkpoints entirely.
002425 **
002426 ** The callback registered by this function replaces any existing callback
002427 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
002428 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
002429 ** configured by this function.
002430 */
002431 int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
002432 #ifdef SQLITE_OMIT_WAL
002433 UNUSED_PARAMETER(db);
002434 UNUSED_PARAMETER(nFrame);
002435 #else
002436 #ifdef SQLITE_ENABLE_API_ARMOR
002437 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
002438 #endif
002439 if( nFrame>0 ){
002440 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
002441 }else{
002442 sqlite3_wal_hook(db, 0, 0);
002443 }
002444 #endif
002445 return SQLITE_OK;
002446 }
002447
002448 /*
002449 ** Register a callback to be invoked each time a transaction is written
002450 ** into the write-ahead-log by this database connection.
002451 */
002452 void *sqlite3_wal_hook(
002453 sqlite3 *db, /* Attach the hook to this db handle */
002454 int(*xCallback)(void *, sqlite3*, const char*, int),
002455 void *pArg /* First argument passed to xCallback() */
002456 ){
002457 #ifndef SQLITE_OMIT_WAL
002458 void *pRet;
002459 #ifdef SQLITE_ENABLE_API_ARMOR
002460 if( !sqlite3SafetyCheckOk(db) ){
002461 (void)SQLITE_MISUSE_BKPT;
002462 return 0;
002463 }
002464 #endif
002465 sqlite3_mutex_enter(db->mutex);
002466 pRet = db->pWalArg;
002467 db->xWalCallback = xCallback;
002468 db->pWalArg = pArg;
002469 sqlite3_mutex_leave(db->mutex);
002470 return pRet;
002471 #else
002472 return 0;
002473 #endif
002474 }
002475
002476 /*
002477 ** Checkpoint database zDb.
002478 */
002479 int sqlite3_wal_checkpoint_v2(
002480 sqlite3 *db, /* Database handle */
002481 const char *zDb, /* Name of attached database (or NULL) */
002482 int eMode, /* SQLITE_CHECKPOINT_* value */
002483 int *pnLog, /* OUT: Size of WAL log in frames */
002484 int *pnCkpt /* OUT: Total number of frames checkpointed */
002485 ){
002486 #ifdef SQLITE_OMIT_WAL
002487 return SQLITE_OK;
002488 #else
002489 int rc; /* Return code */
002490 int iDb; /* Schema to checkpoint */
002491
002492 #ifdef SQLITE_ENABLE_API_ARMOR
002493 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
002494 #endif
002495
002496 /* Initialize the output variables to -1 in case an error occurs. */
002497 if( pnLog ) *pnLog = -1;
002498 if( pnCkpt ) *pnCkpt = -1;
002499
002500 assert( SQLITE_CHECKPOINT_PASSIVE==0 );
002501 assert( SQLITE_CHECKPOINT_FULL==1 );
002502 assert( SQLITE_CHECKPOINT_RESTART==2 );
002503 assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
002504 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
002505 /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
002506 ** mode: */
002507 return SQLITE_MISUSE_BKPT;
002508 }
002509
002510 sqlite3_mutex_enter(db->mutex);
002511 if( zDb && zDb[0] ){
002512 iDb = sqlite3FindDbName(db, zDb);
002513 }else{
002514 iDb = SQLITE_MAX_DB; /* This means process all schemas */
002515 }
002516 if( iDb<0 ){
002517 rc = SQLITE_ERROR;
002518 sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
002519 }else{
002520 db->busyHandler.nBusy = 0;
002521 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
002522 sqlite3Error(db, rc);
002523 }
002524 rc = sqlite3ApiExit(db, rc);
002525
002526 /* If there are no active statements, clear the interrupt flag at this
002527 ** point. */
002528 if( db->nVdbeActive==0 ){
002529 AtomicStore(&db->u1.isInterrupted, 0);
002530 }
002531
002532 sqlite3_mutex_leave(db->mutex);
002533 return rc;
002534 #endif
002535 }
002536
002537
002538 /*
002539 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
002540 ** to contains a zero-length string, all attached databases are
002541 ** checkpointed.
002542 */
002543 int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
002544 /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
002545 ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
002546 return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
002547 }
002548
002549 #ifndef SQLITE_OMIT_WAL
002550 /*
002551 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
002552 ** not currently open in WAL mode.
002553 **
002554 ** If a transaction is open on the database being checkpointed, this
002555 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
002556 ** an error occurs while running the checkpoint, an SQLite error code is
002557 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
002558 **
002559 ** The mutex on database handle db should be held by the caller. The mutex
002560 ** associated with the specific b-tree being checkpointed is taken by
002561 ** this function while the checkpoint is running.
002562 **
002563 ** If iDb is passed SQLITE_MAX_DB then all attached databases are
002564 ** checkpointed. If an error is encountered it is returned immediately -
002565 ** no attempt is made to checkpoint any remaining databases.
002566 **
002567 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
002568 ** or TRUNCATE.
002569 */
002570 int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
002571 int rc = SQLITE_OK; /* Return code */
002572 int i; /* Used to iterate through attached dbs */
002573 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
002574
002575 assert( sqlite3_mutex_held(db->mutex) );
002576 assert( !pnLog || *pnLog==-1 );
002577 assert( !pnCkpt || *pnCkpt==-1 );
002578 testcase( iDb==SQLITE_MAX_ATTACHED ); /* See forum post a006d86f72 */
002579 testcase( iDb==SQLITE_MAX_DB );
002580
002581 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
002582 if( i==iDb || iDb==SQLITE_MAX_DB ){
002583 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
002584 pnLog = 0;
002585 pnCkpt = 0;
002586 if( rc==SQLITE_BUSY ){
002587 bBusy = 1;
002588 rc = SQLITE_OK;
002589 }
002590 }
002591 }
002592
002593 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
002594 }
002595 #endif /* SQLITE_OMIT_WAL */
002596
002597 /*
002598 ** This function returns true if main-memory should be used instead of
002599 ** a temporary file for transient pager files and statement journals.
002600 ** The value returned depends on the value of db->temp_store (runtime
002601 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
002602 ** following table describes the relationship between these two values
002603 ** and this functions return value.
002604 **
002605 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
002606 ** ----------------- -------------- ------------------------------
002607 ** 0 any file (return 0)
002608 ** 1 1 file (return 0)
002609 ** 1 2 memory (return 1)
002610 ** 1 0 file (return 0)
002611 ** 2 1 file (return 0)
002612 ** 2 2 memory (return 1)
002613 ** 2 0 memory (return 1)
002614 ** 3 any memory (return 1)
002615 */
002616 int sqlite3TempInMemory(const sqlite3 *db){
002617 #if SQLITE_TEMP_STORE==1
002618 return ( db->temp_store==2 );
002619 #endif
002620 #if SQLITE_TEMP_STORE==2
002621 return ( db->temp_store!=1 );
002622 #endif
002623 #if SQLITE_TEMP_STORE==3
002624 UNUSED_PARAMETER(db);
002625 return 1;
002626 #endif
002627 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
002628 UNUSED_PARAMETER(db);
002629 return 0;
002630 #endif
002631 }
002632
002633 /*
002634 ** Return UTF-8 encoded English language explanation of the most recent
002635 ** error.
002636 */
002637 const char *sqlite3_errmsg(sqlite3 *db){
002638 const char *z;
002639 if( !db ){
002640 return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
002641 }
002642 if( !sqlite3SafetyCheckSickOrOk(db) ){
002643 return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
002644 }
002645 sqlite3_mutex_enter(db->mutex);
002646 if( db->mallocFailed ){
002647 z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
002648 }else{
002649 testcase( db->pErr==0 );
002650 z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;
002651 assert( !db->mallocFailed );
002652 if( z==0 ){
002653 z = sqlite3ErrStr(db->errCode);
002654 }
002655 }
002656 sqlite3_mutex_leave(db->mutex);
002657 return z;
002658 }
002659
002660 /*
002661 ** Return the byte offset of the most recent error
002662 */
002663 int sqlite3_error_offset(sqlite3 *db){
002664 int iOffset = -1;
002665 if( db && sqlite3SafetyCheckSickOrOk(db) && db->errCode ){
002666 sqlite3_mutex_enter(db->mutex);
002667 iOffset = db->errByteOffset;
002668 sqlite3_mutex_leave(db->mutex);
002669 }
002670 return iOffset;
002671 }
002672
002673 #ifndef SQLITE_OMIT_UTF16
002674 /*
002675 ** Return UTF-16 encoded English language explanation of the most recent
002676 ** error.
002677 */
002678 const void *sqlite3_errmsg16(sqlite3 *db){
002679 static const u16 outOfMem[] = {
002680 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
002681 };
002682 static const u16 misuse[] = {
002683 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
002684 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
002685 'm', 'i', 's', 'u', 's', 'e', 0
002686 };
002687
002688 const void *z;
002689 if( !db ){
002690 return (void *)outOfMem;
002691 }
002692 if( !sqlite3SafetyCheckSickOrOk(db) ){
002693 return (void *)misuse;
002694 }
002695 sqlite3_mutex_enter(db->mutex);
002696 if( db->mallocFailed ){
002697 z = (void *)outOfMem;
002698 }else{
002699 z = sqlite3_value_text16(db->pErr);
002700 if( z==0 ){
002701 sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
002702 z = sqlite3_value_text16(db->pErr);
002703 }
002704 /* A malloc() may have failed within the call to sqlite3_value_text16()
002705 ** above. If this is the case, then the db->mallocFailed flag needs to
002706 ** be cleared before returning. Do this directly, instead of via
002707 ** sqlite3ApiExit(), to avoid setting the database handle error message.
002708 */
002709 sqlite3OomClear(db);
002710 }
002711 sqlite3_mutex_leave(db->mutex);
002712 return z;
002713 }
002714 #endif /* SQLITE_OMIT_UTF16 */
002715
002716 /*
002717 ** Return the most recent error code generated by an SQLite routine. If NULL is
002718 ** passed to this function, we assume a malloc() failed during sqlite3_open().
002719 */
002720 int sqlite3_errcode(sqlite3 *db){
002721 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
002722 return SQLITE_MISUSE_BKPT;
002723 }
002724 if( !db || db->mallocFailed ){
002725 return SQLITE_NOMEM_BKPT;
002726 }
002727 return db->errCode & db->errMask;
002728 }
002729 int sqlite3_extended_errcode(sqlite3 *db){
002730 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
002731 return SQLITE_MISUSE_BKPT;
002732 }
002733 if( !db || db->mallocFailed ){
002734 return SQLITE_NOMEM_BKPT;
002735 }
002736 return db->errCode;
002737 }
002738 int sqlite3_system_errno(sqlite3 *db){
002739 return db ? db->iSysErrno : 0;
002740 }
002741
002742 /*
002743 ** Return a string that describes the kind of error specified in the
002744 ** argument. For now, this simply calls the internal sqlite3ErrStr()
002745 ** function.
002746 */
002747 const char *sqlite3_errstr(int rc){
002748 return sqlite3ErrStr(rc);
002749 }
002750
002751 /*
002752 ** Create a new collating function for database "db". The name is zName
002753 ** and the encoding is enc.
002754 */
002755 static int createCollation(
002756 sqlite3* db,
002757 const char *zName,
002758 u8 enc,
002759 void* pCtx,
002760 int(*xCompare)(void*,int,const void*,int,const void*),
002761 void(*xDel)(void*)
002762 ){
002763 CollSeq *pColl;
002764 int enc2;
002765
002766 assert( sqlite3_mutex_held(db->mutex) );
002767
002768 /* If SQLITE_UTF16 is specified as the encoding type, transform this
002769 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
002770 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
002771 */
002772 enc2 = enc;
002773 testcase( enc2==SQLITE_UTF16 );
002774 testcase( enc2==SQLITE_UTF16_ALIGNED );
002775 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
002776 enc2 = SQLITE_UTF16NATIVE;
002777 }
002778 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
002779 return SQLITE_MISUSE_BKPT;
002780 }
002781
002782 /* Check if this call is removing or replacing an existing collation
002783 ** sequence. If so, and there are active VMs, return busy. If there
002784 ** are no active VMs, invalidate any pre-compiled statements.
002785 */
002786 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
002787 if( pColl && pColl->xCmp ){
002788 if( db->nVdbeActive ){
002789 sqlite3ErrorWithMsg(db, SQLITE_BUSY,
002790 "unable to delete/modify collation sequence due to active statements");
002791 return SQLITE_BUSY;
002792 }
002793 sqlite3ExpirePreparedStatements(db, 0);
002794
002795 /* If collation sequence pColl was created directly by a call to
002796 ** sqlite3_create_collation, and not generated by synthCollSeq(),
002797 ** then any copies made by synthCollSeq() need to be invalidated.
002798 ** Also, collation destructor - CollSeq.xDel() - function may need
002799 ** to be called.
002800 */
002801 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
002802 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
002803 int j;
002804 for(j=0; j<3; j++){
002805 CollSeq *p = &aColl[j];
002806 if( p->enc==pColl->enc ){
002807 if( p->xDel ){
002808 p->xDel(p->pUser);
002809 }
002810 p->xCmp = 0;
002811 }
002812 }
002813 }
002814 }
002815
002816 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
002817 if( pColl==0 ) return SQLITE_NOMEM_BKPT;
002818 pColl->xCmp = xCompare;
002819 pColl->pUser = pCtx;
002820 pColl->xDel = xDel;
002821 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
002822 sqlite3Error(db, SQLITE_OK);
002823 return SQLITE_OK;
002824 }
002825
002826
002827 /*
002828 ** This array defines hard upper bounds on limit values. The
002829 ** initializer must be kept in sync with the SQLITE_LIMIT_*
002830 ** #defines in sqlite3.h.
002831 */
002832 static const int aHardLimit[] = {
002833 SQLITE_MAX_LENGTH,
002834 SQLITE_MAX_SQL_LENGTH,
002835 SQLITE_MAX_COLUMN,
002836 SQLITE_MAX_EXPR_DEPTH,
002837 SQLITE_MAX_COMPOUND_SELECT,
002838 SQLITE_MAX_VDBE_OP,
002839 SQLITE_MAX_FUNCTION_ARG,
002840 SQLITE_MAX_ATTACHED,
002841 SQLITE_MAX_LIKE_PATTERN_LENGTH,
002842 SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
002843 SQLITE_MAX_TRIGGER_DEPTH,
002844 SQLITE_MAX_WORKER_THREADS,
002845 };
002846
002847 /*
002848 ** Make sure the hard limits are set to reasonable values
002849 */
002850 #if SQLITE_MAX_LENGTH<100
002851 # error SQLITE_MAX_LENGTH must be at least 100
002852 #endif
002853 #if SQLITE_MAX_SQL_LENGTH<100
002854 # error SQLITE_MAX_SQL_LENGTH must be at least 100
002855 #endif
002856 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
002857 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
002858 #endif
002859 #if SQLITE_MAX_COMPOUND_SELECT<2
002860 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
002861 #endif
002862 #if SQLITE_MAX_VDBE_OP<40
002863 # error SQLITE_MAX_VDBE_OP must be at least 40
002864 #endif
002865 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>32767
002866 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 32767
002867 #endif
002868 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
002869 # error SQLITE_MAX_ATTACHED must be between 0 and 125
002870 #endif
002871 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
002872 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
002873 #endif
002874 #if SQLITE_MAX_COLUMN>32767
002875 # error SQLITE_MAX_COLUMN must not exceed 32767
002876 #endif
002877 #if SQLITE_MAX_TRIGGER_DEPTH<1
002878 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
002879 #endif
002880 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
002881 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
002882 #endif
002883
002884
002885 /*
002886 ** Change the value of a limit. Report the old value.
002887 ** If an invalid limit index is supplied, report -1.
002888 ** Make no changes but still report the old value if the
002889 ** new limit is negative.
002890 **
002891 ** A new lower limit does not shrink existing constructs.
002892 ** It merely prevents new constructs that exceed the limit
002893 ** from forming.
002894 */
002895 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
002896 int oldLimit;
002897
002898 #ifdef SQLITE_ENABLE_API_ARMOR
002899 if( !sqlite3SafetyCheckOk(db) ){
002900 (void)SQLITE_MISUSE_BKPT;
002901 return -1;
002902 }
002903 #endif
002904
002905 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
002906 ** there is a hard upper bound set at compile-time by a C preprocessor
002907 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
002908 ** "_MAX_".)
002909 */
002910 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
002911 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
002912 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
002913 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
002914 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
002915 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
002916 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
002917 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
002918 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
002919 SQLITE_MAX_LIKE_PATTERN_LENGTH );
002920 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
002921 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
002922 assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
002923 assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
002924
002925
002926 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
002927 return -1;
002928 }
002929 oldLimit = db->aLimit[limitId];
002930 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
002931 if( newLimit>aHardLimit[limitId] ){
002932 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
002933 }else if( newLimit<SQLITE_MIN_LENGTH && limitId==SQLITE_LIMIT_LENGTH ){
002934 newLimit = SQLITE_MIN_LENGTH;
002935 }
002936 db->aLimit[limitId] = newLimit;
002937 }
002938 return oldLimit; /* IMP: R-53341-35419 */
002939 }
002940
002941 /*
002942 ** This function is used to parse both URIs and non-URI filenames passed by the
002943 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
002944 ** URIs specified as part of ATTACH statements.
002945 **
002946 ** The first argument to this function is the name of the VFS to use (or
002947 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
002948 ** query parameter. The second argument contains the URI (or non-URI filename)
002949 ** itself. When this function is called the *pFlags variable should contain
002950 ** the default flags to open the database handle with. The value stored in
002951 ** *pFlags may be updated before returning if the URI filename contains
002952 ** "cache=xxx" or "mode=xxx" query parameters.
002953 **
002954 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
002955 ** the VFS that should be used to open the database file. *pzFile is set to
002956 ** point to a buffer containing the name of the file to open. The value
002957 ** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter()
002958 ** and is in the same format as names created using sqlite3_create_filename().
002959 ** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on
002960 ** the value returned in *pzFile to avoid a memory leak.
002961 **
002962 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
002963 ** may be set to point to a buffer containing an English language error
002964 ** message. It is the responsibility of the caller to eventually release
002965 ** this buffer by calling sqlite3_free().
002966 */
002967 int sqlite3ParseUri(
002968 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
002969 const char *zUri, /* Nul-terminated URI to parse */
002970 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
002971 sqlite3_vfs **ppVfs, /* OUT: VFS to use */
002972 char **pzFile, /* OUT: Filename component of URI */
002973 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
002974 ){
002975 int rc = SQLITE_OK;
002976 unsigned int flags = *pFlags;
002977 const char *zVfs = zDefaultVfs;
002978 char *zFile;
002979 char c;
002980 int nUri = sqlite3Strlen30(zUri);
002981
002982 assert( *pzErrMsg==0 );
002983
002984 if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
002985 || AtomicLoad(&sqlite3GlobalConfig.bOpenUri)) /* IMP: R-51689-46548 */
002986 && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
002987 ){
002988 char *zOpt;
002989 int eState; /* Parser state when parsing URI */
002990 int iIn; /* Input character index */
002991 int iOut = 0; /* Output character index */
002992 u64 nByte = nUri+8; /* Bytes of space to allocate */
002993
002994 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
002995 ** method that there may be extra parameters following the file-name. */
002996 flags |= SQLITE_OPEN_URI;
002997
002998 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
002999 zFile = sqlite3_malloc64(nByte);
003000 if( !zFile ) return SQLITE_NOMEM_BKPT;
003001
003002 memset(zFile, 0, 4); /* 4-byte of 0x00 is the start of DB name marker */
003003 zFile += 4;
003004
003005 iIn = 5;
003006 #ifdef SQLITE_ALLOW_URI_AUTHORITY
003007 if( strncmp(zUri+5, "///", 3)==0 ){
003008 iIn = 7;
003009 /* The following condition causes URIs with five leading / characters
003010 ** like file://///host/path to be converted into UNCs like //host/path.
003011 ** The correct URI for that UNC has only two or four leading / characters
003012 ** file://host/path or file:////host/path. But 5 leading slashes is a
003013 ** common error, we are told, so we handle it as a special case. */
003014 if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
003015 }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
003016 iIn = 16;
003017 }
003018 #else
003019 /* Discard the scheme and authority segments of the URI. */
003020 if( zUri[5]=='/' && zUri[6]=='/' ){
003021 iIn = 7;
003022 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
003023 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
003024 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
003025 iIn-7, &zUri[7]);
003026 rc = SQLITE_ERROR;
003027 goto parse_uri_out;
003028 }
003029 }
003030 #endif
003031
003032 /* Copy the filename and any query parameters into the zFile buffer.
003033 ** Decode %HH escape codes along the way.
003034 **
003035 ** Within this loop, variable eState may be set to 0, 1 or 2, depending
003036 ** on the parsing context. As follows:
003037 **
003038 ** 0: Parsing file-name.
003039 ** 1: Parsing name section of a name=value query parameter.
003040 ** 2: Parsing value section of a name=value query parameter.
003041 */
003042 eState = 0;
003043 while( (c = zUri[iIn])!=0 && c!='#' ){
003044 iIn++;
003045 if( c=='%'
003046 && sqlite3Isxdigit(zUri[iIn])
003047 && sqlite3Isxdigit(zUri[iIn+1])
003048 ){
003049 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
003050 octet += sqlite3HexToInt(zUri[iIn++]);
003051
003052 assert( octet>=0 && octet<256 );
003053 if( octet==0 ){
003054 #ifndef SQLITE_ENABLE_URI_00_ERROR
003055 /* This branch is taken when "%00" appears within the URI. In this
003056 ** case we ignore all text in the remainder of the path, name or
003057 ** value currently being parsed. So ignore the current character
003058 ** and skip to the next "?", "=" or "&", as appropriate. */
003059 while( (c = zUri[iIn])!=0 && c!='#'
003060 && (eState!=0 || c!='?')
003061 && (eState!=1 || (c!='=' && c!='&'))
003062 && (eState!=2 || c!='&')
003063 ){
003064 iIn++;
003065 }
003066 continue;
003067 #else
003068 /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
003069 *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
003070 rc = SQLITE_ERROR;
003071 goto parse_uri_out;
003072 #endif
003073 }
003074 c = octet;
003075 }else if( eState==1 && (c=='&' || c=='=') ){
003076 if( zFile[iOut-1]==0 ){
003077 /* An empty option name. Ignore this option altogether. */
003078 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
003079 continue;
003080 }
003081 if( c=='&' ){
003082 zFile[iOut++] = '\0';
003083 }else{
003084 eState = 2;
003085 }
003086 c = 0;
003087 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
003088 c = 0;
003089 eState = 1;
003090 }
003091 zFile[iOut++] = c;
003092 }
003093 if( eState==1 ) zFile[iOut++] = '\0';
003094 memset(zFile+iOut, 0, 4); /* end-of-options + empty journal filenames */
003095
003096 /* Check if there were any options specified that should be interpreted
003097 ** here. Options that are interpreted here include "vfs" and those that
003098 ** correspond to flags that may be passed to the sqlite3_open_v2()
003099 ** method. */
003100 zOpt = &zFile[sqlite3Strlen30(zFile)+1];
003101 while( zOpt[0] ){
003102 int nOpt = sqlite3Strlen30(zOpt);
003103 char *zVal = &zOpt[nOpt+1];
003104 int nVal = sqlite3Strlen30(zVal);
003105
003106 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
003107 zVfs = zVal;
003108 }else{
003109 struct OpenMode {
003110 const char *z;
003111 int mode;
003112 } *aMode = 0;
003113 char *zModeType = 0;
003114 int mask = 0;
003115 int limit = 0;
003116
003117 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
003118 static struct OpenMode aCacheMode[] = {
003119 { "shared", SQLITE_OPEN_SHAREDCACHE },
003120 { "private", SQLITE_OPEN_PRIVATECACHE },
003121 { 0, 0 }
003122 };
003123
003124 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
003125 aMode = aCacheMode;
003126 limit = mask;
003127 zModeType = "cache";
003128 }
003129 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
003130 static struct OpenMode aOpenMode[] = {
003131 { "ro", SQLITE_OPEN_READONLY },
003132 { "rw", SQLITE_OPEN_READWRITE },
003133 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
003134 { "memory", SQLITE_OPEN_MEMORY },
003135 { 0, 0 }
003136 };
003137
003138 mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
003139 | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
003140 aMode = aOpenMode;
003141 limit = mask & flags;
003142 zModeType = "access";
003143 }
003144
003145 if( aMode ){
003146 int i;
003147 int mode = 0;
003148 for(i=0; aMode[i].z; i++){
003149 const char *z = aMode[i].z;
003150 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
003151 mode = aMode[i].mode;
003152 break;
003153 }
003154 }
003155 if( mode==0 ){
003156 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
003157 rc = SQLITE_ERROR;
003158 goto parse_uri_out;
003159 }
003160 if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
003161 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
003162 zModeType, zVal);
003163 rc = SQLITE_PERM;
003164 goto parse_uri_out;
003165 }
003166 flags = (flags & ~mask) | mode;
003167 }
003168 }
003169
003170 zOpt = &zVal[nVal+1];
003171 }
003172
003173 }else{
003174 zFile = sqlite3_malloc64(nUri+8);
003175 if( !zFile ) return SQLITE_NOMEM_BKPT;
003176 memset(zFile, 0, 4);
003177 zFile += 4;
003178 if( nUri ){
003179 memcpy(zFile, zUri, nUri);
003180 }
003181 memset(zFile+nUri, 0, 4);
003182 flags &= ~SQLITE_OPEN_URI;
003183 }
003184
003185 *ppVfs = sqlite3_vfs_find(zVfs);
003186 if( *ppVfs==0 ){
003187 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
003188 rc = SQLITE_ERROR;
003189 }
003190 parse_uri_out:
003191 if( rc!=SQLITE_OK ){
003192 sqlite3_free_filename(zFile);
003193 zFile = 0;
003194 }
003195 *pFlags = flags;
003196 *pzFile = zFile;
003197 return rc;
003198 }
003199
003200 /*
003201 ** This routine does the core work of extracting URI parameters from a
003202 ** database filename for the sqlite3_uri_parameter() interface.
003203 */
003204 static const char *uriParameter(const char *zFilename, const char *zParam){
003205 zFilename += sqlite3Strlen30(zFilename) + 1;
003206 while( ALWAYS(zFilename!=0) && zFilename[0] ){
003207 int x = strcmp(zFilename, zParam);
003208 zFilename += sqlite3Strlen30(zFilename) + 1;
003209 if( x==0 ) return zFilename;
003210 zFilename += sqlite3Strlen30(zFilename) + 1;
003211 }
003212 return 0;
003213 }
003214
003215
003216
003217 /*
003218 ** This routine does the work of opening a database on behalf of
003219 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
003220 ** is UTF-8 encoded.
003221 */
003222 static int openDatabase(
003223 const char *zFilename, /* Database filename UTF-8 encoded */
003224 sqlite3 **ppDb, /* OUT: Returned database handle */
003225 unsigned int flags, /* Operational flags */
003226 const char *zVfs /* Name of the VFS to use */
003227 ){
003228 sqlite3 *db; /* Store allocated handle here */
003229 int rc; /* Return code */
003230 int isThreadsafe; /* True for threadsafe connections */
003231 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
003232 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
003233 int i; /* Loop counter */
003234
003235 #ifdef SQLITE_ENABLE_API_ARMOR
003236 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
003237 #endif
003238 *ppDb = 0;
003239 #ifndef SQLITE_OMIT_AUTOINIT
003240 rc = sqlite3_initialize();
003241 if( rc ) return rc;
003242 #endif
003243
003244 if( sqlite3GlobalConfig.bCoreMutex==0 ){
003245 isThreadsafe = 0;
003246 }else if( flags & SQLITE_OPEN_NOMUTEX ){
003247 isThreadsafe = 0;
003248 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
003249 isThreadsafe = 1;
003250 }else{
003251 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
003252 }
003253
003254 if( flags & SQLITE_OPEN_PRIVATECACHE ){
003255 flags &= ~SQLITE_OPEN_SHAREDCACHE;
003256 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
003257 flags |= SQLITE_OPEN_SHAREDCACHE;
003258 }
003259
003260 /* Remove harmful bits from the flags parameter
003261 **
003262 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
003263 ** dealt with in the previous code block. Besides these, the only
003264 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
003265 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
003266 ** SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_EXRESCODE, and some reserved
003267 ** bits. Silently mask off all other flags.
003268 */
003269 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
003270 SQLITE_OPEN_EXCLUSIVE |
003271 SQLITE_OPEN_MAIN_DB |
003272 SQLITE_OPEN_TEMP_DB |
003273 SQLITE_OPEN_TRANSIENT_DB |
003274 SQLITE_OPEN_MAIN_JOURNAL |
003275 SQLITE_OPEN_TEMP_JOURNAL |
003276 SQLITE_OPEN_SUBJOURNAL |
003277 SQLITE_OPEN_SUPER_JOURNAL |
003278 SQLITE_OPEN_NOMUTEX |
003279 SQLITE_OPEN_FULLMUTEX |
003280 SQLITE_OPEN_WAL
003281 );
003282
003283 /* Allocate the sqlite data structure */
003284 db = sqlite3MallocZero( sizeof(sqlite3) );
003285 if( db==0 ) goto opendb_out;
003286 if( isThreadsafe
003287 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
003288 || sqlite3GlobalConfig.bCoreMutex
003289 #endif
003290 ){
003291 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
003292 if( db->mutex==0 ){
003293 sqlite3_free(db);
003294 db = 0;
003295 goto opendb_out;
003296 }
003297 if( isThreadsafe==0 ){
003298 sqlite3MutexWarnOnContention(db->mutex);
003299 }
003300 }
003301 sqlite3_mutex_enter(db->mutex);
003302 db->errMask = (flags & SQLITE_OPEN_EXRESCODE)!=0 ? 0xffffffff : 0xff;
003303 db->nDb = 2;
003304 db->eOpenState = SQLITE_STATE_BUSY;
003305 db->aDb = db->aDbStatic;
003306 db->lookaside.bDisable = 1;
003307 db->lookaside.sz = 0;
003308
003309 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
003310 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
003311 db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
003312 db->autoCommit = 1;
003313 db->nextAutovac = -1;
003314 db->szMmap = sqlite3GlobalConfig.szMmap;
003315 db->nextPagesize = 0;
003316 db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
003317 #ifdef SQLITE_ENABLE_SORTER_MMAP
003318 /* Beginning with version 3.37.0, using the VFS xFetch() API to memory-map
003319 ** the temporary files used to do external sorts (see code in vdbesort.c)
003320 ** is disabled. It can still be used either by defining
003321 ** SQLITE_ENABLE_SORTER_MMAP at compile time or by using the
003322 ** SQLITE_TESTCTRL_SORTER_MMAP test-control at runtime. */
003323 db->nMaxSorterMmap = 0x7FFFFFFF;
003324 #endif
003325 db->flags |= SQLITE_ShortColNames
003326 | SQLITE_EnableTrigger
003327 | SQLITE_EnableView
003328 | SQLITE_CacheSpill
003329 | SQLITE_AttachCreate
003330 | SQLITE_AttachWrite
003331 | SQLITE_Comments
003332 #if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
003333 | SQLITE_TrustedSchema
003334 #endif
003335 /* The SQLITE_DQS compile-time option determines the default settings
003336 ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
003337 **
003338 ** SQLITE_DQS SQLITE_DBCONFIG_DQS_DDL SQLITE_DBCONFIG_DQS_DML
003339 ** ---------- ----------------------- -----------------------
003340 ** undefined on on
003341 ** 3 on on
003342 ** 2 on off
003343 ** 1 off on
003344 ** 0 off off
003345 **
003346 ** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
003347 ** and so that is the default. But developers are encouraged to use
003348 ** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
003349 */
003350 #if !defined(SQLITE_DQS)
003351 # define SQLITE_DQS 3
003352 #endif
003353 #if (SQLITE_DQS&1)==1
003354 | SQLITE_DqsDML
003355 #endif
003356 #if (SQLITE_DQS&2)==2
003357 | SQLITE_DqsDDL
003358 #endif
003359
003360 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
003361 | SQLITE_AutoIndex
003362 #endif
003363 #if SQLITE_DEFAULT_CKPTFULLFSYNC
003364 | SQLITE_CkptFullFSync
003365 #endif
003366 #if SQLITE_DEFAULT_FILE_FORMAT<4
003367 | SQLITE_LegacyFileFmt
003368 #endif
003369 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
003370 | SQLITE_LoadExtension
003371 #endif
003372 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
003373 | SQLITE_RecTriggers
003374 #endif
003375 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
003376 | SQLITE_ForeignKeys
003377 #endif
003378 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
003379 | SQLITE_ReverseOrder
003380 #endif
003381 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
003382 | SQLITE_CellSizeCk
003383 #endif
003384 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
003385 | SQLITE_Fts3Tokenizer
003386 #endif
003387 #if defined(SQLITE_ENABLE_QPSG)
003388 | SQLITE_EnableQPSG
003389 #endif
003390 #if defined(SQLITE_DEFAULT_DEFENSIVE)
003391 | SQLITE_Defensive
003392 #endif
003393 #if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
003394 | SQLITE_LegacyAlter
003395 #endif
003396 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
003397 | SQLITE_StmtScanStatus
003398 #endif
003399 ;
003400 sqlite3HashInit(&db->aCollSeq);
003401 #ifndef SQLITE_OMIT_VIRTUALTABLE
003402 sqlite3HashInit(&db->aModule);
003403 #endif
003404
003405 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
003406 ** and UTF-16, so add a version for each to avoid any unnecessary
003407 ** conversions. The only error that can occur here is a malloc() failure.
003408 **
003409 ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
003410 ** functions:
003411 */
003412 createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
003413 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
003414 createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
003415 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
003416 createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0);
003417 if( db->mallocFailed ){
003418 goto opendb_out;
003419 }
003420
003421 #if SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)
003422 /* Process magic filenames ":localStorage:" and ":sessionStorage:" */
003423 if( zFilename && zFilename[0]==':' ){
003424 if( strcmp(zFilename, ":localStorage:")==0 ){
003425 zFilename = "file:local?vfs=kvvfs";
003426 flags |= SQLITE_OPEN_URI;
003427 }else if( strcmp(zFilename, ":sessionStorage:")==0 ){
003428 zFilename = "file:session?vfs=kvvfs";
003429 flags |= SQLITE_OPEN_URI;
003430 }
003431 }
003432 #endif /* SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL) */
003433
003434 /* Parse the filename/URI argument
003435 **
003436 ** Only allow sensible combinations of bits in the flags argument.
003437 ** Throw an error if any non-sense combination is used. If we
003438 ** do not block illegal combinations here, it could trigger
003439 ** assert() statements in deeper layers. Sensible combinations
003440 ** are:
003441 **
003442 ** 1: SQLITE_OPEN_READONLY
003443 ** 2: SQLITE_OPEN_READWRITE
003444 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
003445 */
003446 db->openFlags = flags;
003447 assert( SQLITE_OPEN_READONLY == 0x01 );
003448 assert( SQLITE_OPEN_READWRITE == 0x02 );
003449 assert( SQLITE_OPEN_CREATE == 0x04 );
003450 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
003451 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
003452 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
003453 if( ((1<<(flags&7)) & 0x46)==0 ){
003454 rc = SQLITE_MISUSE_BKPT; /* IMP: R-18321-05872 */
003455 }else{
003456 if( zFilename==0 ) zFilename = ":memory:";
003457 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
003458 }
003459 if( rc!=SQLITE_OK ){
003460 if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
003461 sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
003462 sqlite3_free(zErrMsg);
003463 goto opendb_out;
003464 }
003465 assert( db->pVfs!=0 );
003466 #if SQLITE_OS_KV || defined(SQLITE_OS_KV_OPTIONAL)
003467 if( sqlite3_stricmp(db->pVfs->zName, "kvvfs")==0 ){
003468 db->temp_store = 2;
003469 }
003470 #endif
003471
003472 /* Open the backend database driver */
003473 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
003474 flags | SQLITE_OPEN_MAIN_DB);
003475 if( rc!=SQLITE_OK ){
003476 if( rc==SQLITE_IOERR_NOMEM ){
003477 rc = SQLITE_NOMEM_BKPT;
003478 }
003479 sqlite3Error(db, rc);
003480 goto opendb_out;
003481 }
003482 sqlite3BtreeEnter(db->aDb[0].pBt);
003483 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
003484 if( !db->mallocFailed ){
003485 sqlite3SetTextEncoding(db, SCHEMA_ENC(db));
003486 }
003487 sqlite3BtreeLeave(db->aDb[0].pBt);
003488 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
003489
003490 /* The default safety_level for the main database is FULL; for the temp
003491 ** database it is OFF. This matches the pager layer defaults.
003492 */
003493 db->aDb[0].zDbSName = "main";
003494 db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
003495 db->aDb[1].zDbSName = "temp";
003496 db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
003497
003498 db->eOpenState = SQLITE_STATE_OPEN;
003499 if( db->mallocFailed ){
003500 goto opendb_out;
003501 }
003502
003503 /* Register all built-in functions, but do not attempt to read the
003504 ** database schema yet. This is delayed until the first time the database
003505 ** is accessed.
003506 */
003507 sqlite3Error(db, SQLITE_OK);
003508 sqlite3RegisterPerConnectionBuiltinFunctions(db);
003509 rc = sqlite3_errcode(db);
003510
003511
003512 /* Load compiled-in extensions */
003513 for(i=0; rc==SQLITE_OK && i<ArraySize(sqlite3BuiltinExtensions); i++){
003514 rc = sqlite3BuiltinExtensions[i](db);
003515 }
003516
003517 /* Load automatic extensions - extensions that have been registered
003518 ** using the sqlite3_automatic_extension() API.
003519 */
003520 if( rc==SQLITE_OK ){
003521 sqlite3AutoLoadExtensions(db);
003522 rc = sqlite3_errcode(db);
003523 if( rc!=SQLITE_OK ){
003524 goto opendb_out;
003525 }
003526 }
003527
003528 #ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
003529 /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
003530 ** option gives access to internal functions by default.
003531 ** Testing use only!!! */
003532 db->mDbFlags |= DBFLAG_InternalFunc;
003533 #endif
003534
003535 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
003536 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
003537 ** mode. Doing nothing at all also makes NORMAL the default.
003538 */
003539 #ifdef SQLITE_DEFAULT_LOCKING_MODE
003540 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
003541 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
003542 SQLITE_DEFAULT_LOCKING_MODE);
003543 #endif
003544
003545 if( rc ) sqlite3Error(db, rc);
003546
003547 /* Enable the lookaside-malloc subsystem */
003548 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
003549 sqlite3GlobalConfig.nLookaside);
003550
003551 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
003552
003553 opendb_out:
003554 if( db ){
003555 assert( db->mutex!=0 || isThreadsafe==0
003556 || sqlite3GlobalConfig.bFullMutex==0 );
003557 sqlite3_mutex_leave(db->mutex);
003558 }
003559 rc = sqlite3_errcode(db);
003560 assert( db!=0 || (rc&0xff)==SQLITE_NOMEM );
003561 if( (rc&0xff)==SQLITE_NOMEM ){
003562 sqlite3_close(db);
003563 db = 0;
003564 }else if( rc!=SQLITE_OK ){
003565 db->eOpenState = SQLITE_STATE_SICK;
003566 }
003567 *ppDb = db;
003568 #ifdef SQLITE_ENABLE_SQLLOG
003569 if( sqlite3GlobalConfig.xSqllog ){
003570 /* Opening a db handle. Fourth parameter is passed 0. */
003571 void *pArg = sqlite3GlobalConfig.pSqllogArg;
003572 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
003573 }
003574 #endif
003575 sqlite3_free_filename(zOpen);
003576 return rc;
003577 }
003578
003579
003580 /*
003581 ** Open a new database handle.
003582 */
003583 int sqlite3_open(
003584 const char *zFilename,
003585 sqlite3 **ppDb
003586 ){
003587 return openDatabase(zFilename, ppDb,
003588 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
003589 }
003590 int sqlite3_open_v2(
003591 const char *filename, /* Database filename (UTF-8) */
003592 sqlite3 **ppDb, /* OUT: SQLite db handle */
003593 int flags, /* Flags */
003594 const char *zVfs /* Name of VFS module to use */
003595 ){
003596 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
003597 }
003598
003599 #ifndef SQLITE_OMIT_UTF16
003600 /*
003601 ** Open a new database handle.
003602 */
003603 int sqlite3_open16(
003604 const void *zFilename,
003605 sqlite3 **ppDb
003606 ){
003607 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
003608 sqlite3_value *pVal;
003609 int rc;
003610
003611 #ifdef SQLITE_ENABLE_API_ARMOR
003612 if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
003613 #endif
003614 *ppDb = 0;
003615 #ifndef SQLITE_OMIT_AUTOINIT
003616 rc = sqlite3_initialize();
003617 if( rc ) return rc;
003618 #endif
003619 if( zFilename==0 ) zFilename = "\000\000";
003620 pVal = sqlite3ValueNew(0);
003621 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
003622 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
003623 if( zFilename8 ){
003624 rc = openDatabase(zFilename8, ppDb,
003625 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
003626 assert( *ppDb || rc==SQLITE_NOMEM );
003627 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
003628 SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
003629 }
003630 }else{
003631 rc = SQLITE_NOMEM_BKPT;
003632 }
003633 sqlite3ValueFree(pVal);
003634
003635 return rc & 0xff;
003636 }
003637 #endif /* SQLITE_OMIT_UTF16 */
003638
003639 /*
003640 ** Register a new collation sequence with the database handle db.
003641 */
003642 int sqlite3_create_collation(
003643 sqlite3* db,
003644 const char *zName,
003645 int enc,
003646 void* pCtx,
003647 int(*xCompare)(void*,int,const void*,int,const void*)
003648 ){
003649 return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
003650 }
003651
003652 /*
003653 ** Register a new collation sequence with the database handle db.
003654 */
003655 int sqlite3_create_collation_v2(
003656 sqlite3* db,
003657 const char *zName,
003658 int enc,
003659 void* pCtx,
003660 int(*xCompare)(void*,int,const void*,int,const void*),
003661 void(*xDel)(void*)
003662 ){
003663 int rc;
003664
003665 #ifdef SQLITE_ENABLE_API_ARMOR
003666 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
003667 #endif
003668 sqlite3_mutex_enter(db->mutex);
003669 assert( !db->mallocFailed );
003670 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
003671 rc = sqlite3ApiExit(db, rc);
003672 sqlite3_mutex_leave(db->mutex);
003673 return rc;
003674 }
003675
003676 #ifndef SQLITE_OMIT_UTF16
003677 /*
003678 ** Register a new collation sequence with the database handle db.
003679 */
003680 int sqlite3_create_collation16(
003681 sqlite3* db,
003682 const void *zName,
003683 int enc,
003684 void* pCtx,
003685 int(*xCompare)(void*,int,const void*,int,const void*)
003686 ){
003687 int rc = SQLITE_OK;
003688 char *zName8;
003689
003690 #ifdef SQLITE_ENABLE_API_ARMOR
003691 if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
003692 #endif
003693 sqlite3_mutex_enter(db->mutex);
003694 assert( !db->mallocFailed );
003695 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
003696 if( zName8 ){
003697 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
003698 sqlite3DbFree(db, zName8);
003699 }
003700 rc = sqlite3ApiExit(db, rc);
003701 sqlite3_mutex_leave(db->mutex);
003702 return rc;
003703 }
003704 #endif /* SQLITE_OMIT_UTF16 */
003705
003706 /*
003707 ** Register a collation sequence factory callback with the database handle
003708 ** db. Replace any previously installed collation sequence factory.
003709 */
003710 int sqlite3_collation_needed(
003711 sqlite3 *db,
003712 void *pCollNeededArg,
003713 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
003714 ){
003715 #ifdef SQLITE_ENABLE_API_ARMOR
003716 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
003717 #endif
003718 sqlite3_mutex_enter(db->mutex);
003719 db->xCollNeeded = xCollNeeded;
003720 db->xCollNeeded16 = 0;
003721 db->pCollNeededArg = pCollNeededArg;
003722 sqlite3_mutex_leave(db->mutex);
003723 return SQLITE_OK;
003724 }
003725
003726 #ifndef SQLITE_OMIT_UTF16
003727 /*
003728 ** Register a collation sequence factory callback with the database handle
003729 ** db. Replace any previously installed collation sequence factory.
003730 */
003731 int sqlite3_collation_needed16(
003732 sqlite3 *db,
003733 void *pCollNeededArg,
003734 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
003735 ){
003736 #ifdef SQLITE_ENABLE_API_ARMOR
003737 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
003738 #endif
003739 sqlite3_mutex_enter(db->mutex);
003740 db->xCollNeeded = 0;
003741 db->xCollNeeded16 = xCollNeeded16;
003742 db->pCollNeededArg = pCollNeededArg;
003743 sqlite3_mutex_leave(db->mutex);
003744 return SQLITE_OK;
003745 }
003746 #endif /* SQLITE_OMIT_UTF16 */
003747
003748 /*
003749 ** Find existing client data.
003750 */
003751 void *sqlite3_get_clientdata(sqlite3 *db, const char *zName){
003752 DbClientData *p;
003753 sqlite3_mutex_enter(db->mutex);
003754 for(p=db->pDbData; p; p=p->pNext){
003755 if( strcmp(p->zName, zName)==0 ){
003756 void *pResult = p->pData;
003757 sqlite3_mutex_leave(db->mutex);
003758 return pResult;
003759 }
003760 }
003761 sqlite3_mutex_leave(db->mutex);
003762 return 0;
003763 }
003764
003765 /*
003766 ** Add new client data to a database connection.
003767 */
003768 int sqlite3_set_clientdata(
003769 sqlite3 *db, /* Attach client data to this connection */
003770 const char *zName, /* Name of the client data */
003771 void *pData, /* The client data itself */
003772 void (*xDestructor)(void*) /* Destructor */
003773 ){
003774 DbClientData *p, **pp;
003775 sqlite3_mutex_enter(db->mutex);
003776 pp = &db->pDbData;
003777 for(p=db->pDbData; p && strcmp(p->zName,zName); p=p->pNext){
003778 pp = &p->pNext;
003779 }
003780 if( p ){
003781 assert( p->pData!=0 );
003782 if( p->xDestructor ) p->xDestructor(p->pData);
003783 if( pData==0 ){
003784 *pp = p->pNext;
003785 sqlite3_free(p);
003786 sqlite3_mutex_leave(db->mutex);
003787 return SQLITE_OK;
003788 }
003789 }else if( pData==0 ){
003790 sqlite3_mutex_leave(db->mutex);
003791 return SQLITE_OK;
003792 }else{
003793 size_t n = strlen(zName);
003794 p = sqlite3_malloc64( sizeof(DbClientData)+n+1 );
003795 if( p==0 ){
003796 if( xDestructor ) xDestructor(pData);
003797 sqlite3_mutex_leave(db->mutex);
003798 return SQLITE_NOMEM;
003799 }
003800 memcpy(p->zName, zName, n+1);
003801 p->pNext = db->pDbData;
003802 db->pDbData = p;
003803 }
003804 p->pData = pData;
003805 p->xDestructor = xDestructor;
003806 sqlite3_mutex_leave(db->mutex);
003807 return SQLITE_OK;
003808 }
003809
003810
003811 #ifndef SQLITE_OMIT_DEPRECATED
003812 /*
003813 ** This function is now an anachronism. It used to be used to recover from a
003814 ** malloc() failure, but SQLite now does this automatically.
003815 */
003816 int sqlite3_global_recover(void){
003817 return SQLITE_OK;
003818 }
003819 #endif
003820
003821 /*
003822 ** Test to see whether or not the database connection is in autocommit
003823 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
003824 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
003825 ** by the next COMMIT or ROLLBACK.
003826 */
003827 int sqlite3_get_autocommit(sqlite3 *db){
003828 #ifdef SQLITE_ENABLE_API_ARMOR
003829 if( !sqlite3SafetyCheckOk(db) ){
003830 (void)SQLITE_MISUSE_BKPT;
003831 return 0;
003832 }
003833 #endif
003834 return db->autoCommit;
003835 }
003836
003837 /*
003838 ** The following routines are substitutes for constants SQLITE_CORRUPT,
003839 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
003840 ** constants. They serve two purposes:
003841 **
003842 ** 1. Serve as a convenient place to set a breakpoint in a debugger
003843 ** to detect when version error conditions occurs.
003844 **
003845 ** 2. Invoke sqlite3_log() to provide the source code location where
003846 ** a low-level error is first detected.
003847 */
003848 int sqlite3ReportError(int iErr, int lineno, const char *zType){
003849 sqlite3_log(iErr, "%s at line %d of [%.10s]",
003850 zType, lineno, 20+sqlite3_sourceid());
003851 return iErr;
003852 }
003853 int sqlite3CorruptError(int lineno){
003854 testcase( sqlite3GlobalConfig.xLog!=0 );
003855 return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
003856 }
003857 int sqlite3MisuseError(int lineno){
003858 testcase( sqlite3GlobalConfig.xLog!=0 );
003859 return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
003860 }
003861 int sqlite3CantopenError(int lineno){
003862 testcase( sqlite3GlobalConfig.xLog!=0 );
003863 return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
003864 }
003865 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
003866 int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
003867 char zMsg[100];
003868 sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
003869 testcase( sqlite3GlobalConfig.xLog!=0 );
003870 return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
003871 }
003872 #endif
003873 #ifdef SQLITE_DEBUG
003874 int sqlite3NomemError(int lineno){
003875 testcase( sqlite3GlobalConfig.xLog!=0 );
003876 return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
003877 }
003878 int sqlite3IoerrnomemError(int lineno){
003879 testcase( sqlite3GlobalConfig.xLog!=0 );
003880 return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
003881 }
003882 #endif
003883
003884 #ifndef SQLITE_OMIT_DEPRECATED
003885 /*
003886 ** This is a convenience routine that makes sure that all thread-specific
003887 ** data for this thread has been deallocated.
003888 **
003889 ** SQLite no longer uses thread-specific data so this routine is now a
003890 ** no-op. It is retained for historical compatibility.
003891 */
003892 void sqlite3_thread_cleanup(void){
003893 }
003894 #endif
003895
003896 /*
003897 ** Return meta information about a specific column of a database table.
003898 ** See comment in sqlite3.h (sqlite.h.in) for details.
003899 */
003900 int sqlite3_table_column_metadata(
003901 sqlite3 *db, /* Connection handle */
003902 const char *zDbName, /* Database name or NULL */
003903 const char *zTableName, /* Table name */
003904 const char *zColumnName, /* Column name */
003905 char const **pzDataType, /* OUTPUT: Declared data type */
003906 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
003907 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
003908 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
003909 int *pAutoinc /* OUTPUT: True if column is auto-increment */
003910 ){
003911 int rc;
003912 char *zErrMsg = 0;
003913 Table *pTab = 0;
003914 Column *pCol = 0;
003915 int iCol = 0;
003916 char const *zDataType = 0;
003917 char const *zCollSeq = 0;
003918 int notnull = 0;
003919 int primarykey = 0;
003920 int autoinc = 0;
003921
003922
003923 #ifdef SQLITE_ENABLE_API_ARMOR
003924 if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
003925 return SQLITE_MISUSE_BKPT;
003926 }
003927 #endif
003928
003929 /* Ensure the database schema has been loaded */
003930 sqlite3_mutex_enter(db->mutex);
003931 sqlite3BtreeEnterAll(db);
003932 rc = sqlite3Init(db, &zErrMsg);
003933 if( SQLITE_OK!=rc ){
003934 goto error_out;
003935 }
003936
003937 /* Locate the table in question */
003938 pTab = sqlite3FindTable(db, zTableName, zDbName);
003939 if( !pTab || IsView(pTab) ){
003940 pTab = 0;
003941 goto error_out;
003942 }
003943
003944 /* Find the column for which info is requested */
003945 if( zColumnName==0 ){
003946 /* Query for existence of table only */
003947 }else{
003948 for(iCol=0; iCol<pTab->nCol; iCol++){
003949 pCol = &pTab->aCol[iCol];
003950 if( 0==sqlite3StrICmp(pCol->zCnName, zColumnName) ){
003951 break;
003952 }
003953 }
003954 if( iCol==pTab->nCol ){
003955 if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
003956 iCol = pTab->iPKey;
003957 pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
003958 }else{
003959 pTab = 0;
003960 goto error_out;
003961 }
003962 }
003963 }
003964
003965 /* The following block stores the meta information that will be returned
003966 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
003967 ** and autoinc. At this point there are two possibilities:
003968 **
003969 ** 1. The specified column name was rowid", "oid" or "_rowid_"
003970 ** and there is no explicitly declared IPK column.
003971 **
003972 ** 2. The table is not a view and the column name identified an
003973 ** explicitly declared column. Copy meta information from *pCol.
003974 */
003975 if( pCol ){
003976 zDataType = sqlite3ColumnType(pCol,0);
003977 zCollSeq = sqlite3ColumnColl(pCol);
003978 notnull = pCol->notNull!=0;
003979 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
003980 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
003981 }else{
003982 zDataType = "INTEGER";
003983 primarykey = 1;
003984 }
003985 if( !zCollSeq ){
003986 zCollSeq = sqlite3StrBINARY;
003987 }
003988
003989 error_out:
003990 sqlite3BtreeLeaveAll(db);
003991
003992 /* Whether the function call succeeded or failed, set the output parameters
003993 ** to whatever their local counterparts contain. If an error did occur,
003994 ** this has the effect of zeroing all output parameters.
003995 */
003996 if( pzDataType ) *pzDataType = zDataType;
003997 if( pzCollSeq ) *pzCollSeq = zCollSeq;
003998 if( pNotNull ) *pNotNull = notnull;
003999 if( pPrimaryKey ) *pPrimaryKey = primarykey;
004000 if( pAutoinc ) *pAutoinc = autoinc;
004001
004002 if( SQLITE_OK==rc && !pTab ){
004003 sqlite3DbFree(db, zErrMsg);
004004 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
004005 zColumnName);
004006 rc = SQLITE_ERROR;
004007 }
004008 sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
004009 sqlite3DbFree(db, zErrMsg);
004010 rc = sqlite3ApiExit(db, rc);
004011 sqlite3_mutex_leave(db->mutex);
004012 return rc;
004013 }
004014
004015 /*
004016 ** Sleep for a little while. Return the amount of time slept.
004017 */
004018 int sqlite3_sleep(int ms){
004019 sqlite3_vfs *pVfs;
004020 int rc;
004021 pVfs = sqlite3_vfs_find(0);
004022 if( pVfs==0 ) return 0;
004023
004024 /* This function works in milliseconds, but the underlying OsSleep()
004025 ** API uses microseconds. Hence the 1000's.
004026 */
004027 rc = (sqlite3OsSleep(pVfs, ms<0 ? 0 : 1000*ms)/1000);
004028 return rc;
004029 }
004030
004031 /*
004032 ** Enable or disable the extended result codes.
004033 */
004034 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
004035 #ifdef SQLITE_ENABLE_API_ARMOR
004036 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
004037 #endif
004038 sqlite3_mutex_enter(db->mutex);
004039 db->errMask = onoff ? 0xffffffff : 0xff;
004040 sqlite3_mutex_leave(db->mutex);
004041 return SQLITE_OK;
004042 }
004043
004044 /*
004045 ** Invoke the xFileControl method on a particular database.
004046 */
004047 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
004048 int rc = SQLITE_ERROR;
004049 Btree *pBtree;
004050
004051 #ifdef SQLITE_ENABLE_API_ARMOR
004052 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
004053 #endif
004054 sqlite3_mutex_enter(db->mutex);
004055 pBtree = sqlite3DbNameToBtree(db, zDbName);
004056 if( pBtree ){
004057 Pager *pPager;
004058 sqlite3_file *fd;
004059 sqlite3BtreeEnter(pBtree);
004060 pPager = sqlite3BtreePager(pBtree);
004061 assert( pPager!=0 );
004062 fd = sqlite3PagerFile(pPager);
004063 assert( fd!=0 );
004064 if( op==SQLITE_FCNTL_FILE_POINTER ){
004065 *(sqlite3_file**)pArg = fd;
004066 rc = SQLITE_OK;
004067 }else if( op==SQLITE_FCNTL_VFS_POINTER ){
004068 *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
004069 rc = SQLITE_OK;
004070 }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
004071 *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
004072 rc = SQLITE_OK;
004073 }else if( op==SQLITE_FCNTL_DATA_VERSION ){
004074 *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
004075 rc = SQLITE_OK;
004076 }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){
004077 int iNew = *(int*)pArg;
004078 *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree);
004079 if( iNew>=0 && iNew<=255 ){
004080 sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0);
004081 }
004082 rc = SQLITE_OK;
004083 }else if( op==SQLITE_FCNTL_RESET_CACHE ){
004084 sqlite3BtreeClearCache(pBtree);
004085 rc = SQLITE_OK;
004086 }else{
004087 int nSave = db->busyHandler.nBusy;
004088 rc = sqlite3OsFileControl(fd, op, pArg);
004089 db->busyHandler.nBusy = nSave;
004090 }
004091 sqlite3BtreeLeave(pBtree);
004092 }
004093 sqlite3_mutex_leave(db->mutex);
004094 return rc;
004095 }
004096
004097 /*
004098 ** Interface to the testing logic.
004099 */
004100 int sqlite3_test_control(int op, ...){
004101 int rc = 0;
004102 #ifdef SQLITE_UNTESTABLE
004103 UNUSED_PARAMETER(op);
004104 #else
004105 va_list ap;
004106 va_start(ap, op);
004107 switch( op ){
004108
004109 /*
004110 ** Save the current state of the PRNG.
004111 */
004112 case SQLITE_TESTCTRL_PRNG_SAVE: {
004113 sqlite3PrngSaveState();
004114 break;
004115 }
004116
004117 /*
004118 ** Restore the state of the PRNG to the last state saved using
004119 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
004120 ** this verb acts like PRNG_RESET.
004121 */
004122 case SQLITE_TESTCTRL_PRNG_RESTORE: {
004123 sqlite3PrngRestoreState();
004124 break;
004125 }
004126
004127 /* sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);
004128 **
004129 ** Control the seed for the pseudo-random number generator (PRNG) that
004130 ** is built into SQLite. Cases:
004131 **
004132 ** x!=0 && db!=0 Seed the PRNG to the current value of the
004133 ** schema cookie in the main database for db, or
004134 ** x if the schema cookie is zero. This case
004135 ** is convenient to use with database fuzzers
004136 ** as it allows the fuzzer some control over the
004137 ** the PRNG seed.
004138 **
004139 ** x!=0 && db==0 Seed the PRNG to the value of x.
004140 **
004141 ** x==0 && db==0 Revert to default behavior of using the
004142 ** xRandomness method on the primary VFS.
004143 **
004144 ** This test-control also resets the PRNG so that the new seed will
004145 ** be used for the next call to sqlite3_randomness().
004146 */
004147 #ifndef SQLITE_OMIT_WSD
004148 case SQLITE_TESTCTRL_PRNG_SEED: {
004149 int x = va_arg(ap, int);
004150 int y;
004151 sqlite3 *db = va_arg(ap, sqlite3*);
004152 assert( db==0 || db->aDb[0].pSchema!=0 );
004153 if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; }
004154 sqlite3Config.iPrngSeed = x;
004155 sqlite3_randomness(0,0);
004156 break;
004157 }
004158 #endif
004159
004160 /* sqlite3_test_control(SQLITE_TESTCTRL_FK_NO_ACTION, sqlite3 *db, int b);
004161 **
004162 ** If b is true, then activate the SQLITE_FkNoAction setting. If b is
004163 ** false then clearn that setting. If the SQLITE_FkNoAction setting is
004164 ** abled, all foreign key ON DELETE and ON UPDATE actions behave as if
004165 ** they were NO ACTION, regardless of how they are defined.
004166 **
004167 ** NB: One must usually run "PRAGMA writable_schema=RESET" after
004168 ** using this test-control, before it will take full effect. failing
004169 ** to reset the schema can result in some unexpected behavior.
004170 */
004171 case SQLITE_TESTCTRL_FK_NO_ACTION: {
004172 sqlite3 *db = va_arg(ap, sqlite3*);
004173 int b = va_arg(ap, int);
004174 if( b ){
004175 db->flags |= SQLITE_FkNoAction;
004176 }else{
004177 db->flags &= ~SQLITE_FkNoAction;
004178 }
004179 break;
004180 }
004181
004182 /*
004183 ** sqlite3_test_control(BITVEC_TEST, size, program)
004184 **
004185 ** Run a test against a Bitvec object of size. The program argument
004186 ** is an array of integers that defines the test. Return -1 on a
004187 ** memory allocation error, 0 on success, or non-zero for an error.
004188 ** See the sqlite3BitvecBuiltinTest() for additional information.
004189 */
004190 case SQLITE_TESTCTRL_BITVEC_TEST: {
004191 int sz = va_arg(ap, int);
004192 int *aProg = va_arg(ap, int*);
004193 rc = sqlite3BitvecBuiltinTest(sz, aProg);
004194 break;
004195 }
004196
004197 /*
004198 ** sqlite3_test_control(FAULT_INSTALL, xCallback)
004199 **
004200 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
004201 ** if xCallback is not NULL.
004202 **
004203 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
004204 ** is called immediately after installing the new callback and the return
004205 ** value from sqlite3FaultSim(0) becomes the return from
004206 ** sqlite3_test_control().
004207 */
004208 case SQLITE_TESTCTRL_FAULT_INSTALL: {
004209 /* A bug in MSVC prevents it from understanding pointers to functions
004210 ** types in the second argument to va_arg(). Work around the problem
004211 ** using a typedef.
004212 ** http://support.microsoft.com/kb/47961 <-- dead hyperlink
004213 ** Search at http://web.archive.org/ to find the 2015-03-16 archive
004214 ** of the link above to see the original text.
004215 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
004216 */
004217 typedef int(*sqlite3FaultFuncType)(int);
004218 sqlite3GlobalConfig.xTestCallback = va_arg(ap, sqlite3FaultFuncType);
004219 rc = sqlite3FaultSim(0);
004220 break;
004221 }
004222
004223 /*
004224 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
004225 **
004226 ** Register hooks to call to indicate which malloc() failures
004227 ** are benign.
004228 */
004229 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
004230 typedef void (*void_function)(void);
004231 void_function xBenignBegin;
004232 void_function xBenignEnd;
004233 xBenignBegin = va_arg(ap, void_function);
004234 xBenignEnd = va_arg(ap, void_function);
004235 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
004236 break;
004237 }
004238
004239 /*
004240 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
004241 **
004242 ** Set the PENDING byte to the value in the argument, if X>0.
004243 ** Make no changes if X==0. Return the value of the pending byte
004244 ** as it existing before this routine was called.
004245 **
004246 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
004247 ** an incompatible database file format. Changing the PENDING byte
004248 ** while any database connection is open results in undefined and
004249 ** deleterious behavior.
004250 */
004251 case SQLITE_TESTCTRL_PENDING_BYTE: {
004252 rc = PENDING_BYTE;
004253 #ifndef SQLITE_OMIT_WSD
004254 {
004255 unsigned int newVal = va_arg(ap, unsigned int);
004256 if( newVal ) sqlite3PendingByte = newVal;
004257 }
004258 #endif
004259 break;
004260 }
004261
004262 /*
004263 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
004264 **
004265 ** This action provides a run-time test to see whether or not
004266 ** assert() was enabled at compile-time. If X is true and assert()
004267 ** is enabled, then the return value is true. If X is true and
004268 ** assert() is disabled, then the return value is zero. If X is
004269 ** false and assert() is enabled, then the assertion fires and the
004270 ** process aborts. If X is false and assert() is disabled, then the
004271 ** return value is zero.
004272 */
004273 case SQLITE_TESTCTRL_ASSERT: {
004274 volatile int x = 0;
004275 assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
004276 rc = x;
004277 #if defined(SQLITE_DEBUG)
004278 /* Invoke these debugging routines so that the compiler does not
004279 ** issue "defined but not used" warnings. */
004280 if( x==9999 ){
004281 sqlite3ShowExpr(0);
004282 sqlite3ShowExprList(0);
004283 sqlite3ShowIdList(0);
004284 sqlite3ShowSrcList(0);
004285 sqlite3ShowWith(0);
004286 sqlite3ShowUpsert(0);
004287 #ifndef SQLITE_OMIT_TRIGGER
004288 sqlite3ShowTriggerStep(0);
004289 sqlite3ShowTriggerStepList(0);
004290 sqlite3ShowTrigger(0);
004291 sqlite3ShowTriggerList(0);
004292 #endif
004293 #ifndef SQLITE_OMIT_WINDOWFUNC
004294 sqlite3ShowWindow(0);
004295 sqlite3ShowWinFunc(0);
004296 #endif
004297 sqlite3ShowSelect(0);
004298 }
004299 #endif
004300 break;
004301 }
004302
004303
004304 /*
004305 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
004306 **
004307 ** This action provides a run-time test to see how the ALWAYS and
004308 ** NEVER macros were defined at compile-time.
004309 **
004310 ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
004311 **
004312 ** The recommended test is X==2. If the return value is 2, that means
004313 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
004314 ** default setting. If the return value is 1, then ALWAYS() is either
004315 ** hard-coded to true or else it asserts if its argument is false.
004316 ** The first behavior (hard-coded to true) is the case if
004317 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
004318 ** behavior (assert if the argument to ALWAYS() is false) is the case if
004319 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
004320 **
004321 ** The run-time test procedure might look something like this:
004322 **
004323 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
004324 ** // ALWAYS() and NEVER() are no-op pass-through macros
004325 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
004326 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
004327 ** }else{
004328 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
004329 ** }
004330 */
004331 case SQLITE_TESTCTRL_ALWAYS: {
004332 int x = va_arg(ap,int);
004333 rc = x ? ALWAYS(x) : 0;
004334 break;
004335 }
004336
004337 /*
004338 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
004339 **
004340 ** The integer returned reveals the byte-order of the computer on which
004341 ** SQLite is running:
004342 **
004343 ** 1 big-endian, determined at run-time
004344 ** 10 little-endian, determined at run-time
004345 ** 432101 big-endian, determined at compile-time
004346 ** 123410 little-endian, determined at compile-time
004347 */
004348 case SQLITE_TESTCTRL_BYTEORDER: {
004349 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
004350 break;
004351 }
004352
004353 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
004354 **
004355 ** Enable or disable various optimizations for testing purposes. The
004356 ** argument N is a bitmask of optimizations to be disabled. For normal
004357 ** operation N should be 0. The idea is that a test program (like the
004358 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
004359 ** with various optimizations disabled to verify that the same answer
004360 ** is obtained in every case.
004361 */
004362 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
004363 sqlite3 *db = va_arg(ap, sqlite3*);
004364 db->dbOptFlags = va_arg(ap, u32);
004365 break;
004366 }
004367
004368 /* sqlite3_test_control(SQLITE_TESTCTRL_GETOPT, sqlite3 *db, int *N)
004369 **
004370 ** Write the current optimization settings into *N. A zero bit means that
004371 ** the optimization is on, and a 1 bit means that the optimization is off.
004372 */
004373 case SQLITE_TESTCTRL_GETOPT: {
004374 sqlite3 *db = va_arg(ap, sqlite3*);
004375 int *pN = va_arg(ap, int*);
004376 *pN = db->dbOptFlags;
004377 break;
004378 }
004379
004380 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, onoff, xAlt);
004381 **
004382 ** If parameter onoff is 1, subsequent calls to localtime() fail.
004383 ** If 2, then invoke xAlt() instead of localtime(). If 0, normal
004384 ** processing.
004385 **
004386 ** xAlt arguments are void pointers, but they really want to be:
004387 **
004388 ** int xAlt(const time_t*, struct tm*);
004389 **
004390 ** xAlt should write results in to struct tm object of its 2nd argument
004391 ** and return zero on success, or return non-zero on failure.
004392 */
004393 case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
004394 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
004395 if( sqlite3GlobalConfig.bLocaltimeFault==2 ){
004396 typedef int(*sqlite3LocaltimeType)(const void*,void*);
004397 sqlite3GlobalConfig.xAltLocaltime = va_arg(ap, sqlite3LocaltimeType);
004398 }else{
004399 sqlite3GlobalConfig.xAltLocaltime = 0;
004400 }
004401 break;
004402 }
004403
004404 /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
004405 **
004406 ** Toggle the ability to use internal functions on or off for
004407 ** the database connection given in the argument.
004408 */
004409 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
004410 sqlite3 *db = va_arg(ap, sqlite3*);
004411 db->mDbFlags ^= DBFLAG_InternalFunc;
004412 break;
004413 }
004414
004415 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
004416 **
004417 ** Set or clear a flag that indicates that the database file is always well-
004418 ** formed and never corrupt. This flag is clear by default, indicating that
004419 ** database files might have arbitrary corruption. Setting the flag during
004420 ** testing causes certain assert() statements in the code to be activated
004421 ** that demonstrate invariants on well-formed database files.
004422 */
004423 case SQLITE_TESTCTRL_NEVER_CORRUPT: {
004424 sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
004425 break;
004426 }
004427
004428 /* sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
004429 **
004430 ** Set or clear a flag that causes SQLite to verify that type, name,
004431 ** and tbl_name fields of the sqlite_schema table. This is normally
004432 ** on, but it is sometimes useful to turn it off for testing.
004433 **
004434 ** 2020-07-22: Disabling EXTRA_SCHEMA_CHECKS also disables the
004435 ** verification of rootpage numbers when parsing the schema. This
004436 ** is useful to make it easier to reach strange internal error states
004437 ** during testing. The EXTRA_SCHEMA_CHECKS setting is always enabled
004438 ** in production.
004439 */
004440 case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: {
004441 sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int);
004442 break;
004443 }
004444
004445 /* Set the threshold at which OP_Once counters reset back to zero.
004446 ** By default this is 0x7ffffffe (over 2 billion), but that value is
004447 ** too big to test in a reasonable amount of time, so this control is
004448 ** provided to set a small and easily reachable reset value.
004449 */
004450 case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
004451 sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
004452 break;
004453 }
004454
004455 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
004456 **
004457 ** Set the VDBE coverage callback function to xCallback with context
004458 ** pointer ptr.
004459 */
004460 case SQLITE_TESTCTRL_VDBE_COVERAGE: {
004461 #ifdef SQLITE_VDBE_COVERAGE
004462 typedef void (*branch_callback)(void*,unsigned int,
004463 unsigned char,unsigned char);
004464 sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
004465 sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
004466 #endif
004467 break;
004468 }
004469
004470 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
004471 case SQLITE_TESTCTRL_SORTER_MMAP: {
004472 sqlite3 *db = va_arg(ap, sqlite3*);
004473 db->nMaxSorterMmap = va_arg(ap, int);
004474 break;
004475 }
004476
004477 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
004478 **
004479 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
004480 ** not.
004481 */
004482 case SQLITE_TESTCTRL_ISINIT: {
004483 if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
004484 break;
004485 }
004486
004487 /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
004488 **
004489 ** This test control is used to create imposter tables. "db" is a pointer
004490 ** to the database connection. dbName is the database name (ex: "main" or
004491 ** "temp") which will receive the imposter. "onOff" turns imposter mode on
004492 ** or off. "tnum" is the root page of the b-tree to which the imposter
004493 ** table should connect.
004494 **
004495 ** Enable imposter mode only when the schema has already been parsed. Then
004496 ** run a single CREATE TABLE statement to construct the imposter table in
004497 ** the parsed schema. Then turn imposter mode back off again.
004498 **
004499 ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
004500 ** the schema to be reparsed the next time it is needed. This has the
004501 ** effect of erasing all imposter tables.
004502 */
004503 case SQLITE_TESTCTRL_IMPOSTER: {
004504 sqlite3 *db = va_arg(ap, sqlite3*);
004505 int iDb;
004506 sqlite3_mutex_enter(db->mutex);
004507 iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
004508 if( iDb>=0 ){
004509 db->init.iDb = iDb;
004510 db->init.busy = db->init.imposterTable = va_arg(ap,int);
004511 db->init.newTnum = va_arg(ap,int);
004512 if( db->init.busy==0 && db->init.newTnum>0 ){
004513 sqlite3ResetAllSchemasOfConnection(db);
004514 }
004515 }
004516 sqlite3_mutex_leave(db->mutex);
004517 break;
004518 }
004519
004520 #if defined(YYCOVERAGE)
004521 /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
004522 **
004523 ** This test control (only available when SQLite is compiled with
004524 ** -DYYCOVERAGE) writes a report onto "out" that shows all
004525 ** state/lookahead combinations in the parser state machine
004526 ** which are never exercised. If any state is missed, make the
004527 ** return code SQLITE_ERROR.
004528 */
004529 case SQLITE_TESTCTRL_PARSER_COVERAGE: {
004530 FILE *out = va_arg(ap, FILE*);
004531 if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
004532 break;
004533 }
004534 #endif /* defined(YYCOVERAGE) */
004535
004536 /* sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
004537 **
004538 ** This test-control causes the most recent sqlite3_result_int64() value
004539 ** to be interpreted as a MEM_IntReal instead of as an MEM_Int. Normally,
004540 ** MEM_IntReal values only arise during an INSERT operation of integer
004541 ** values into a REAL column, so they can be challenging to test. This
004542 ** test-control enables us to write an intreal() SQL function that can
004543 ** inject an intreal() value at arbitrary places in an SQL statement,
004544 ** for testing purposes.
004545 */
004546 case SQLITE_TESTCTRL_RESULT_INTREAL: {
004547 sqlite3_context *pCtx = va_arg(ap, sqlite3_context*);
004548 sqlite3ResultIntReal(pCtx);
004549 break;
004550 }
004551
004552 /* sqlite3_test_control(SQLITE_TESTCTRL_SEEK_COUNT,
004553 ** sqlite3 *db, // Database connection
004554 ** u64 *pnSeek // Write seek count here
004555 ** );
004556 **
004557 ** This test-control queries the seek-counter on the "main" database
004558 ** file. The seek-counter is written into *pnSeek and is then reset.
004559 ** The seek-count is only available if compiled with SQLITE_DEBUG.
004560 */
004561 case SQLITE_TESTCTRL_SEEK_COUNT: {
004562 sqlite3 *db = va_arg(ap, sqlite3*);
004563 u64 *pn = va_arg(ap, sqlite3_uint64*);
004564 *pn = sqlite3BtreeSeekCount(db->aDb->pBt);
004565 (void)db; /* Silence harmless unused variable warning */
004566 break;
004567 }
004568
004569 /* sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, op, ptr)
004570 **
004571 ** "ptr" is a pointer to a u32.
004572 **
004573 ** op==0 Store the current sqlite3TreeTrace in *ptr
004574 ** op==1 Set sqlite3TreeTrace to the value *ptr
004575 ** op==2 Store the current sqlite3WhereTrace in *ptr
004576 ** op==3 Set sqlite3WhereTrace to the value *ptr
004577 */
004578 case SQLITE_TESTCTRL_TRACEFLAGS: {
004579 int opTrace = va_arg(ap, int);
004580 u32 *ptr = va_arg(ap, u32*);
004581 switch( opTrace ){
004582 case 0: *ptr = sqlite3TreeTrace; break;
004583 case 1: sqlite3TreeTrace = *ptr; break;
004584 case 2: *ptr = sqlite3WhereTrace; break;
004585 case 3: sqlite3WhereTrace = *ptr; break;
004586 }
004587 break;
004588 }
004589
004590 /* sqlite3_test_control(SQLITE_TESTCTRL_LOGEST,
004591 ** double fIn, // Input value
004592 ** int *pLogEst, // sqlite3LogEstFromDouble(fIn)
004593 ** u64 *pInt, // sqlite3LogEstToInt(*pLogEst)
004594 ** int *pLogEst2 // sqlite3LogEst(*pInt)
004595 ** );
004596 **
004597 ** Test access for the LogEst conversion routines.
004598 */
004599 case SQLITE_TESTCTRL_LOGEST: {
004600 double rIn = va_arg(ap, double);
004601 LogEst rLogEst = sqlite3LogEstFromDouble(rIn);
004602 int *pI1 = va_arg(ap,int*);
004603 u64 *pU64 = va_arg(ap,u64*);
004604 int *pI2 = va_arg(ap,int*);
004605 *pI1 = rLogEst;
004606 *pU64 = sqlite3LogEstToInt(rLogEst);
004607 *pI2 = sqlite3LogEst(*pU64);
004608 break;
004609 }
004610
004611 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
004612 /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue)
004613 **
004614 ** If "id" is an integer between 1 and SQLITE_NTUNE then set the value
004615 ** of the id-th tuning parameter to *piValue. If "id" is between -1
004616 ** and -SQLITE_NTUNE, then write the current value of the (-id)-th
004617 ** tuning parameter into *piValue.
004618 **
004619 ** Tuning parameters are for use during transient development builds,
004620 ** to help find the best values for constants in the query planner.
004621 ** Access tuning parameters using the Tuning(ID) macro. Set the
004622 ** parameters in the CLI using ".testctrl tune ID VALUE".
004623 **
004624 ** Transient use only. Tuning parameters should not be used in
004625 ** checked-in code.
004626 */
004627 case SQLITE_TESTCTRL_TUNE: {
004628 int id = va_arg(ap, int);
004629 int *piValue = va_arg(ap, int*);
004630 if( id>0 && id<=SQLITE_NTUNE ){
004631 Tuning(id) = *piValue;
004632 }else if( id<0 && id>=-SQLITE_NTUNE ){
004633 *piValue = Tuning(-id);
004634 }else{
004635 rc = SQLITE_NOTFOUND;
004636 }
004637 break;
004638 }
004639 #endif
004640
004641 /* sqlite3_test_control(SQLITE_TESTCTRL_JSON_SELFCHECK, &onOff);
004642 **
004643 ** Activate or deactivate validation of JSONB that is generated from
004644 ** text. Off by default, as the validation is slow. Validation is
004645 ** only available if compiled using SQLITE_DEBUG.
004646 **
004647 ** If onOff is initially 1, then turn it on. If onOff is initially
004648 ** off, turn it off. If onOff is initially -1, then change onOff
004649 ** to be the current setting.
004650 */
004651 case SQLITE_TESTCTRL_JSON_SELFCHECK: {
004652 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD)
004653 int *pOnOff = va_arg(ap, int*);
004654 if( *pOnOff<0 ){
004655 *pOnOff = sqlite3Config.bJsonSelfcheck;
004656 }else{
004657 sqlite3Config.bJsonSelfcheck = (u8)((*pOnOff)&0xff);
004658 }
004659 #endif
004660 break;
004661 }
004662 }
004663 va_end(ap);
004664 #endif /* SQLITE_UNTESTABLE */
004665 return rc;
004666 }
004667
004668 /*
004669 ** The Pager stores the Database filename, Journal filename, and WAL filename
004670 ** consecutively in memory, in that order. The database filename is prefixed
004671 ** by four zero bytes. Locate the start of the database filename by searching
004672 ** backwards for the first byte following four consecutive zero bytes.
004673 **
004674 ** This only works if the filename passed in was obtained from the Pager.
004675 */
004676 static const char *databaseName(const char *zName){
004677 while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
004678 zName--;
004679 }
004680 return zName;
004681 }
004682
004683 /*
004684 ** Append text z[] to the end of p[]. Return a pointer to the first
004685 ** character after then zero terminator on the new text in p[].
004686 */
004687 static char *appendText(char *p, const char *z){
004688 size_t n = strlen(z);
004689 memcpy(p, z, n+1);
004690 return p+n+1;
004691 }
004692
004693 /*
004694 ** Allocate memory to hold names for a database, journal file, WAL file,
004695 ** and query parameters. The pointer returned is valid for use by
004696 ** sqlite3_filename_database() and sqlite3_uri_parameter() and related
004697 ** functions.
004698 **
004699 ** Memory layout must be compatible with that generated by the pager
004700 ** and expected by sqlite3_uri_parameter() and databaseName().
004701 */
004702 const char *sqlite3_create_filename(
004703 const char *zDatabase,
004704 const char *zJournal,
004705 const char *zWal,
004706 int nParam,
004707 const char **azParam
004708 ){
004709 sqlite3_int64 nByte;
004710 int i;
004711 char *pResult, *p;
004712 nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10;
004713 for(i=0; i<nParam*2; i++){
004714 nByte += strlen(azParam[i])+1;
004715 }
004716 pResult = p = sqlite3_malloc64( nByte );
004717 if( p==0 ) return 0;
004718 memset(p, 0, 4);
004719 p += 4;
004720 p = appendText(p, zDatabase);
004721 for(i=0; i<nParam*2; i++){
004722 p = appendText(p, azParam[i]);
004723 }
004724 *(p++) = 0;
004725 p = appendText(p, zJournal);
004726 p = appendText(p, zWal);
004727 *(p++) = 0;
004728 *(p++) = 0;
004729 assert( (sqlite3_int64)(p - pResult)==nByte );
004730 return pResult + 4;
004731 }
004732
004733 /*
004734 ** Free memory obtained from sqlite3_create_filename(). It is a severe
004735 ** error to call this routine with any parameter other than a pointer
004736 ** previously obtained from sqlite3_create_filename() or a NULL pointer.
004737 */
004738 void sqlite3_free_filename(const char *p){
004739 if( p==0 ) return;
004740 p = databaseName(p);
004741 sqlite3_free((char*)p - 4);
004742 }
004743
004744
004745 /*
004746 ** This is a utility routine, useful to VFS implementations, that checks
004747 ** to see if a database file was a URI that contained a specific query
004748 ** parameter, and if so obtains the value of the query parameter.
004749 **
004750 ** The zFilename argument is the filename pointer passed into the xOpen()
004751 ** method of a VFS implementation. The zParam argument is the name of the
004752 ** query parameter we seek. This routine returns the value of the zParam
004753 ** parameter if it exists. If the parameter does not exist, this routine
004754 ** returns a NULL pointer.
004755 */
004756 const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
004757 if( zFilename==0 || zParam==0 ) return 0;
004758 zFilename = databaseName(zFilename);
004759 return uriParameter(zFilename, zParam);
004760 }
004761
004762 /*
004763 ** Return a pointer to the name of Nth query parameter of the filename.
004764 */
004765 const char *sqlite3_uri_key(const char *zFilename, int N){
004766 if( zFilename==0 || N<0 ) return 0;
004767 zFilename = databaseName(zFilename);
004768 zFilename += sqlite3Strlen30(zFilename) + 1;
004769 while( ALWAYS(zFilename) && zFilename[0] && (N--)>0 ){
004770 zFilename += sqlite3Strlen30(zFilename) + 1;
004771 zFilename += sqlite3Strlen30(zFilename) + 1;
004772 }
004773 return zFilename[0] ? zFilename : 0;
004774 }
004775
004776 /*
004777 ** Return a boolean value for a query parameter.
004778 */
004779 int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
004780 const char *z = sqlite3_uri_parameter(zFilename, zParam);
004781 bDflt = bDflt!=0;
004782 return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
004783 }
004784
004785 /*
004786 ** Return a 64-bit integer value for a query parameter.
004787 */
004788 sqlite3_int64 sqlite3_uri_int64(
004789 const char *zFilename, /* Filename as passed to xOpen */
004790 const char *zParam, /* URI parameter sought */
004791 sqlite3_int64 bDflt /* return if parameter is missing */
004792 ){
004793 const char *z = sqlite3_uri_parameter(zFilename, zParam);
004794 sqlite3_int64 v;
004795 if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
004796 bDflt = v;
004797 }
004798 return bDflt;
004799 }
004800
004801 /*
004802 ** Translate a filename that was handed to a VFS routine into the corresponding
004803 ** database, journal, or WAL file.
004804 **
004805 ** It is an error to pass this routine a filename string that was not
004806 ** passed into the VFS from the SQLite core. Doing so is similar to
004807 ** passing free() a pointer that was not obtained from malloc() - it is
004808 ** an error that we cannot easily detect but that will likely cause memory
004809 ** corruption.
004810 */
004811 const char *sqlite3_filename_database(const char *zFilename){
004812 if( zFilename==0 ) return 0;
004813 return databaseName(zFilename);
004814 }
004815 const char *sqlite3_filename_journal(const char *zFilename){
004816 if( zFilename==0 ) return 0;
004817 zFilename = databaseName(zFilename);
004818 zFilename += sqlite3Strlen30(zFilename) + 1;
004819 while( ALWAYS(zFilename) && zFilename[0] ){
004820 zFilename += sqlite3Strlen30(zFilename) + 1;
004821 zFilename += sqlite3Strlen30(zFilename) + 1;
004822 }
004823 return zFilename + 1;
004824 }
004825 const char *sqlite3_filename_wal(const char *zFilename){
004826 #ifdef SQLITE_OMIT_WAL
004827 return 0;
004828 #else
004829 zFilename = sqlite3_filename_journal(zFilename);
004830 if( zFilename ) zFilename += sqlite3Strlen30(zFilename) + 1;
004831 return zFilename;
004832 #endif
004833 }
004834
004835 /*
004836 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
004837 */
004838 Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
004839 int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
004840 return iDb<0 ? 0 : db->aDb[iDb].pBt;
004841 }
004842
004843 /*
004844 ** Return the name of the N-th database schema. Return NULL if N is out
004845 ** of range.
004846 */
004847 const char *sqlite3_db_name(sqlite3 *db, int N){
004848 #ifdef SQLITE_ENABLE_API_ARMOR
004849 if( !sqlite3SafetyCheckOk(db) ){
004850 (void)SQLITE_MISUSE_BKPT;
004851 return 0;
004852 }
004853 #endif
004854 if( N<0 || N>=db->nDb ){
004855 return 0;
004856 }else{
004857 return db->aDb[N].zDbSName;
004858 }
004859 }
004860
004861 /*
004862 ** Return the filename of the database associated with a database
004863 ** connection.
004864 */
004865 const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
004866 Btree *pBt;
004867 #ifdef SQLITE_ENABLE_API_ARMOR
004868 if( !sqlite3SafetyCheckOk(db) ){
004869 (void)SQLITE_MISUSE_BKPT;
004870 return 0;
004871 }
004872 #endif
004873 pBt = sqlite3DbNameToBtree(db, zDbName);
004874 return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
004875 }
004876
004877 /*
004878 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
004879 ** no such database exists.
004880 */
004881 int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
004882 Btree *pBt;
004883 #ifdef SQLITE_ENABLE_API_ARMOR
004884 if( !sqlite3SafetyCheckOk(db) ){
004885 (void)SQLITE_MISUSE_BKPT;
004886 return -1;
004887 }
004888 #endif
004889 pBt = sqlite3DbNameToBtree(db, zDbName);
004890 return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
004891 }
004892
004893 #ifdef SQLITE_ENABLE_SNAPSHOT
004894 /*
004895 ** Obtain a snapshot handle for the snapshot of database zDb currently
004896 ** being read by handle db.
004897 */
004898 int sqlite3_snapshot_get(
004899 sqlite3 *db,
004900 const char *zDb,
004901 sqlite3_snapshot **ppSnapshot
004902 ){
004903 int rc = SQLITE_ERROR;
004904 #ifndef SQLITE_OMIT_WAL
004905
004906 #ifdef SQLITE_ENABLE_API_ARMOR
004907 if( !sqlite3SafetyCheckOk(db) ){
004908 return SQLITE_MISUSE_BKPT;
004909 }
004910 #endif
004911 sqlite3_mutex_enter(db->mutex);
004912
004913 if( db->autoCommit==0 ){
004914 int iDb = sqlite3FindDbName(db, zDb);
004915 if( iDb==0 || iDb>1 ){
004916 Btree *pBt = db->aDb[iDb].pBt;
004917 if( SQLITE_TXN_WRITE!=sqlite3BtreeTxnState(pBt) ){
004918 Pager *pPager = sqlite3BtreePager(pBt);
004919 i64 dummy = 0;
004920 sqlite3PagerSnapshotOpen(pPager, (sqlite3_snapshot*)&dummy);
004921 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
004922 sqlite3PagerSnapshotOpen(pPager, 0);
004923 if( rc==SQLITE_OK ){
004924 rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
004925 }
004926 }
004927 }
004928 }
004929
004930 sqlite3_mutex_leave(db->mutex);
004931 #endif /* SQLITE_OMIT_WAL */
004932 return rc;
004933 }
004934
004935 /*
004936 ** Open a read-transaction on the snapshot identified by pSnapshot.
004937 */
004938 int sqlite3_snapshot_open(
004939 sqlite3 *db,
004940 const char *zDb,
004941 sqlite3_snapshot *pSnapshot
004942 ){
004943 int rc = SQLITE_ERROR;
004944 #ifndef SQLITE_OMIT_WAL
004945
004946 #ifdef SQLITE_ENABLE_API_ARMOR
004947 if( !sqlite3SafetyCheckOk(db) ){
004948 return SQLITE_MISUSE_BKPT;
004949 }
004950 #endif
004951 sqlite3_mutex_enter(db->mutex);
004952 if( db->autoCommit==0 ){
004953 int iDb;
004954 iDb = sqlite3FindDbName(db, zDb);
004955 if( iDb==0 || iDb>1 ){
004956 Btree *pBt = db->aDb[iDb].pBt;
004957 if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE ){
004958 Pager *pPager = sqlite3BtreePager(pBt);
004959 int bUnlock = 0;
004960 if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_NONE ){
004961 if( db->nVdbeActive==0 ){
004962 rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
004963 if( rc==SQLITE_OK ){
004964 bUnlock = 1;
004965 rc = sqlite3BtreeCommit(pBt);
004966 }
004967 }
004968 }else{
004969 rc = SQLITE_OK;
004970 }
004971 if( rc==SQLITE_OK ){
004972 rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
004973 }
004974 if( rc==SQLITE_OK ){
004975 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
004976 sqlite3PagerSnapshotOpen(pPager, 0);
004977 }
004978 if( bUnlock ){
004979 sqlite3PagerSnapshotUnlock(pPager);
004980 }
004981 }
004982 }
004983 }
004984
004985 sqlite3_mutex_leave(db->mutex);
004986 #endif /* SQLITE_OMIT_WAL */
004987 return rc;
004988 }
004989
004990 /*
004991 ** Recover as many snapshots as possible from the wal file associated with
004992 ** schema zDb of database db.
004993 */
004994 int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
004995 int rc = SQLITE_ERROR;
004996 #ifndef SQLITE_OMIT_WAL
004997 int iDb;
004998
004999 #ifdef SQLITE_ENABLE_API_ARMOR
005000 if( !sqlite3SafetyCheckOk(db) ){
005001 return SQLITE_MISUSE_BKPT;
005002 }
005003 #endif
005004
005005 sqlite3_mutex_enter(db->mutex);
005006 iDb = sqlite3FindDbName(db, zDb);
005007 if( iDb==0 || iDb>1 ){
005008 Btree *pBt = db->aDb[iDb].pBt;
005009 if( SQLITE_TXN_NONE==sqlite3BtreeTxnState(pBt) ){
005010 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
005011 if( rc==SQLITE_OK ){
005012 rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
005013 sqlite3BtreeCommit(pBt);
005014 }
005015 }
005016 }
005017 sqlite3_mutex_leave(db->mutex);
005018 #endif /* SQLITE_OMIT_WAL */
005019 return rc;
005020 }
005021
005022 /*
005023 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
005024 */
005025 void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
005026 sqlite3_free(pSnapshot);
005027 }
005028 #endif /* SQLITE_ENABLE_SNAPSHOT */
005029
005030 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
005031 /*
005032 ** Given the name of a compile-time option, return true if that option
005033 ** was used and false if not.
005034 **
005035 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
005036 ** is not required for a match.
005037 */
005038 int sqlite3_compileoption_used(const char *zOptName){
005039 int i, n;
005040 int nOpt;
005041 const char **azCompileOpt;
005042
005043 #ifdef SQLITE_ENABLE_API_ARMOR
005044 if( zOptName==0 ){
005045 (void)SQLITE_MISUSE_BKPT;
005046 return 0;
005047 }
005048 #endif
005049
005050 azCompileOpt = sqlite3CompileOptions(&nOpt);
005051
005052 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
005053 n = sqlite3Strlen30(zOptName);
005054
005055 /* Since nOpt is normally in single digits, a linear search is
005056 ** adequate. No need for a binary search. */
005057 for(i=0; i<nOpt; i++){
005058 if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
005059 && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
005060 ){
005061 return 1;
005062 }
005063 }
005064 return 0;
005065 }
005066
005067 /*
005068 ** Return the N-th compile-time option string. If N is out of range,
005069 ** return a NULL pointer.
005070 */
005071 const char *sqlite3_compileoption_get(int N){
005072 int nOpt;
005073 const char **azCompileOpt;
005074 azCompileOpt = sqlite3CompileOptions(&nOpt);
005075 if( N>=0 && N<nOpt ){
005076 return azCompileOpt[N];
005077 }
005078 return 0;
005079 }
005080 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */