OLD | NEW |
| (Empty) |
1 /* | |
2 ** 2001 September 15 | |
3 ** | |
4 ** The author disclaims copyright to this source code. In place of | |
5 ** a legal notice, here is a blessing: | |
6 ** | |
7 ** May you do good and not evil. | |
8 ** May you find forgiveness for yourself and forgive others. | |
9 ** May you share freely, never taking more than you give. | |
10 ** | |
11 ************************************************************************* | |
12 ** Main file for the SQLite library. The routines in this file | |
13 ** implement the programmer interface to the library. Routines in | |
14 ** other files are for internal use by SQLite and should not be | |
15 ** accessed by users of the library. | |
16 */ | |
17 #include "sqliteInt.h" | |
18 | |
19 #ifdef SQLITE_ENABLE_FTS3 | |
20 # include "fts3.h" | |
21 #endif | |
22 #ifdef SQLITE_ENABLE_RTREE | |
23 # include "rtree.h" | |
24 #endif | |
25 #ifdef SQLITE_ENABLE_ICU | |
26 # include "sqliteicu.h" | |
27 #endif | |
28 | |
29 #ifndef SQLITE_AMALGAMATION | |
30 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant | |
31 ** contains the text of SQLITE_VERSION macro. | |
32 */ | |
33 const char sqlite3_version[] = SQLITE_VERSION; | |
34 #endif | |
35 | |
36 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns | |
37 ** a pointer to the to the sqlite3_version[] string constant. | |
38 */ | |
39 const char *sqlite3_libversion(void){ return sqlite3_version; } | |
40 | |
41 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a | |
42 ** pointer to a string constant whose value is the same as the | |
43 ** SQLITE_SOURCE_ID C preprocessor macro. | |
44 */ | |
45 const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } | |
46 | |
47 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function | |
48 ** returns an integer equal to SQLITE_VERSION_NUMBER. | |
49 */ | |
50 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; } | |
51 | |
52 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns | |
53 ** zero if and only if SQLite was compiled with mutexing code omitted due to | |
54 ** the SQLITE_THREADSAFE compile-time option being set to 0. | |
55 */ | |
56 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; } | |
57 | |
58 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) | |
59 /* | |
60 ** If the following function pointer is not NULL and if | |
61 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing | |
62 ** I/O active are written using this function. These messages | |
63 ** are intended for debugging activity only. | |
64 */ | |
65 void (*sqlite3IoTrace)(const char*, ...) = 0; | |
66 #endif | |
67 | |
68 /* | |
69 ** If the following global variable points to a string which is the | |
70 ** name of a directory, then that directory will be used to store | |
71 ** temporary files. | |
72 ** | |
73 ** See also the "PRAGMA temp_store_directory" SQL command. | |
74 */ | |
75 char *sqlite3_temp_directory = 0; | |
76 | |
77 /* | |
78 ** If the following global variable points to a string which is the | |
79 ** name of a directory, then that directory will be used to store | |
80 ** all database files specified with a relative pathname. | |
81 ** | |
82 ** See also the "PRAGMA data_store_directory" SQL command. | |
83 */ | |
84 char *sqlite3_data_directory = 0; | |
85 | |
86 /* | |
87 ** Initialize SQLite. | |
88 ** | |
89 ** This routine must be called to initialize the memory allocation, | |
90 ** VFS, and mutex subsystems prior to doing any serious work with | |
91 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT | |
92 ** this routine will be called automatically by key routines such as | |
93 ** sqlite3_open(). | |
94 ** | |
95 ** This routine is a no-op except on its very first call for the process, | |
96 ** or for the first call after a call to sqlite3_shutdown. | |
97 ** | |
98 ** The first thread to call this routine runs the initialization to | |
99 ** completion. If subsequent threads call this routine before the first | |
100 ** thread has finished the initialization process, then the subsequent | |
101 ** threads must block until the first thread finishes with the initialization. | |
102 ** | |
103 ** The first thread might call this routine recursively. Recursive | |
104 ** calls to this routine should not block, of course. Otherwise the | |
105 ** initialization process would never complete. | |
106 ** | |
107 ** Let X be the first thread to enter this routine. Let Y be some other | |
108 ** thread. Then while the initial invocation of this routine by X is | |
109 ** incomplete, it is required that: | |
110 ** | |
111 ** * Calls to this routine from Y must block until the outer-most | |
112 ** call by X completes. | |
113 ** | |
114 ** * Recursive calls to this routine from thread X return immediately | |
115 ** without blocking. | |
116 */ | |
117 int sqlite3_initialize(void){ | |
118 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */ | |
119 int rc; /* Result code */ | |
120 #ifdef SQLITE_EXTRA_INIT | |
121 int bRunExtraInit = 0; /* Extra initialization needed */ | |
122 #endif | |
123 | |
124 #ifdef SQLITE_OMIT_WSD | |
125 rc = sqlite3_wsd_init(4096, 24); | |
126 if( rc!=SQLITE_OK ){ | |
127 return rc; | |
128 } | |
129 #endif | |
130 | |
131 /* If SQLite is already completely initialized, then this call | |
132 ** to sqlite3_initialize() should be a no-op. But the initialization | |
133 ** must be complete. So isInit must not be set until the very end | |
134 ** of this routine. | |
135 */ | |
136 if( sqlite3GlobalConfig.isInit ) return SQLITE_OK; | |
137 | |
138 /* Make sure the mutex subsystem is initialized. If unable to | |
139 ** initialize the mutex subsystem, return early with the error. | |
140 ** If the system is so sick that we are unable to allocate a mutex, | |
141 ** there is not much SQLite is going to be able to do. | |
142 ** | |
143 ** The mutex subsystem must take care of serializing its own | |
144 ** initialization. | |
145 */ | |
146 rc = sqlite3MutexInit(); | |
147 if( rc ) return rc; | |
148 | |
149 /* Initialize the malloc() system and the recursive pInitMutex mutex. | |
150 ** This operation is protected by the STATIC_MASTER mutex. Note that | |
151 ** MutexAlloc() is called for a static mutex prior to initializing the | |
152 ** malloc subsystem - this implies that the allocation of a static | |
153 ** mutex must not require support from the malloc subsystem. | |
154 */ | |
155 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) | |
156 sqlite3_mutex_enter(pMaster); | |
157 sqlite3GlobalConfig.isMutexInit = 1; | |
158 if( !sqlite3GlobalConfig.isMallocInit ){ | |
159 rc = sqlite3MallocInit(); | |
160 } | |
161 if( rc==SQLITE_OK ){ | |
162 sqlite3GlobalConfig.isMallocInit = 1; | |
163 if( !sqlite3GlobalConfig.pInitMutex ){ | |
164 sqlite3GlobalConfig.pInitMutex = | |
165 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); | |
166 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){ | |
167 rc = SQLITE_NOMEM; | |
168 } | |
169 } | |
170 } | |
171 if( rc==SQLITE_OK ){ | |
172 sqlite3GlobalConfig.nRefInitMutex++; | |
173 } | |
174 sqlite3_mutex_leave(pMaster); | |
175 | |
176 /* If rc is not SQLITE_OK at this point, then either the malloc | |
177 ** subsystem could not be initialized or the system failed to allocate | |
178 ** the pInitMutex mutex. Return an error in either case. */ | |
179 if( rc!=SQLITE_OK ){ | |
180 return rc; | |
181 } | |
182 | |
183 /* Do the rest of the initialization under the recursive mutex so | |
184 ** that we will be able to handle recursive calls into | |
185 ** sqlite3_initialize(). The recursive calls normally come through | |
186 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other | |
187 ** recursive calls might also be possible. | |
188 ** | |
189 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls | |
190 ** to the xInit method, so the xInit method need not be threadsafe. | |
191 ** | |
192 ** The following mutex is what serializes access to the appdef pcache xInit | |
193 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the | |
194 ** call to sqlite3PcacheInitialize(). | |
195 */ | |
196 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex); | |
197 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){ | |
198 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); | |
199 sqlite3GlobalConfig.inProgress = 1; | |
200 memset(pHash, 0, sizeof(sqlite3GlobalFunctions)); | |
201 sqlite3RegisterGlobalFunctions(); | |
202 if( sqlite3GlobalConfig.isPCacheInit==0 ){ | |
203 rc = sqlite3PcacheInitialize(); | |
204 } | |
205 if( rc==SQLITE_OK ){ | |
206 sqlite3GlobalConfig.isPCacheInit = 1; | |
207 rc = sqlite3OsInit(); | |
208 } | |
209 if( rc==SQLITE_OK ){ | |
210 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, | |
211 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage); | |
212 sqlite3GlobalConfig.isInit = 1; | |
213 #ifdef SQLITE_EXTRA_INIT | |
214 bRunExtraInit = 1; | |
215 #endif | |
216 } | |
217 sqlite3GlobalConfig.inProgress = 0; | |
218 } | |
219 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex); | |
220 | |
221 /* Go back under the static mutex and clean up the recursive | |
222 ** mutex to prevent a resource leak. | |
223 */ | |
224 sqlite3_mutex_enter(pMaster); | |
225 sqlite3GlobalConfig.nRefInitMutex--; | |
226 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){ | |
227 assert( sqlite3GlobalConfig.nRefInitMutex==0 ); | |
228 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex); | |
229 sqlite3GlobalConfig.pInitMutex = 0; | |
230 } | |
231 sqlite3_mutex_leave(pMaster); | |
232 | |
233 /* The following is just a sanity check to make sure SQLite has | |
234 ** been compiled correctly. It is important to run this code, but | |
235 ** we don't want to run it too often and soak up CPU cycles for no | |
236 ** reason. So we run it once during initialization. | |
237 */ | |
238 #ifndef NDEBUG | |
239 #ifndef SQLITE_OMIT_FLOATING_POINT | |
240 /* This section of code's only "output" is via assert() statements. */ | |
241 if ( rc==SQLITE_OK ){ | |
242 u64 x = (((u64)1)<<63)-1; | |
243 double y; | |
244 assert(sizeof(x)==8); | |
245 assert(sizeof(x)==sizeof(y)); | |
246 memcpy(&y, &x, 8); | |
247 assert( sqlite3IsNaN(y) ); | |
248 } | |
249 #endif | |
250 #endif | |
251 | |
252 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT | |
253 ** compile-time option. | |
254 */ | |
255 #ifdef SQLITE_EXTRA_INIT | |
256 if( bRunExtraInit ){ | |
257 int SQLITE_EXTRA_INIT(const char*); | |
258 rc = SQLITE_EXTRA_INIT(0); | |
259 } | |
260 #endif | |
261 | |
262 return rc; | |
263 } | |
264 | |
265 /* | |
266 ** Undo the effects of sqlite3_initialize(). Must not be called while | |
267 ** there are outstanding database connections or memory allocations or | |
268 ** while any part of SQLite is otherwise in use in any thread. This | |
269 ** routine is not threadsafe. But it is safe to invoke this routine | |
270 ** on when SQLite is already shut down. If SQLite is already shut down | |
271 ** when this routine is invoked, then this routine is a harmless no-op. | |
272 */ | |
273 int sqlite3_shutdown(void){ | |
274 if( sqlite3GlobalConfig.isInit ){ | |
275 #ifdef SQLITE_EXTRA_SHUTDOWN | |
276 void SQLITE_EXTRA_SHUTDOWN(void); | |
277 SQLITE_EXTRA_SHUTDOWN(); | |
278 #endif | |
279 sqlite3_os_end(); | |
280 sqlite3_reset_auto_extension(); | |
281 sqlite3GlobalConfig.isInit = 0; | |
282 } | |
283 if( sqlite3GlobalConfig.isPCacheInit ){ | |
284 sqlite3PcacheShutdown(); | |
285 sqlite3GlobalConfig.isPCacheInit = 0; | |
286 } | |
287 if( sqlite3GlobalConfig.isMallocInit ){ | |
288 sqlite3MallocEnd(); | |
289 sqlite3GlobalConfig.isMallocInit = 0; | |
290 | |
291 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES | |
292 /* The heap subsystem has now been shutdown and these values are supposed | |
293 ** to be NULL or point to memory that was obtained from sqlite3_malloc(), | |
294 ** which would rely on that heap subsystem; therefore, make sure these | |
295 ** values cannot refer to heap memory that was just invalidated when the | |
296 ** heap subsystem was shutdown. This is only done if the current call to | |
297 ** this function resulted in the heap subsystem actually being shutdown. | |
298 */ | |
299 sqlite3_data_directory = 0; | |
300 sqlite3_temp_directory = 0; | |
301 #endif | |
302 } | |
303 if( sqlite3GlobalConfig.isMutexInit ){ | |
304 sqlite3MutexEnd(); | |
305 sqlite3GlobalConfig.isMutexInit = 0; | |
306 } | |
307 | |
308 return SQLITE_OK; | |
309 } | |
310 | |
311 /* | |
312 ** This API allows applications to modify the global configuration of | |
313 ** the SQLite library at run-time. | |
314 ** | |
315 ** This routine should only be called when there are no outstanding | |
316 ** database connections or memory allocations. This routine is not | |
317 ** threadsafe. Failure to heed these warnings can lead to unpredictable | |
318 ** behavior. | |
319 */ | |
320 int sqlite3_config(int op, ...){ | |
321 va_list ap; | |
322 int rc = SQLITE_OK; | |
323 | |
324 /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while | |
325 ** the SQLite library is in use. */ | |
326 if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT; | |
327 | |
328 va_start(ap, op); | |
329 switch( op ){ | |
330 | |
331 /* Mutex configuration options are only available in a threadsafe | |
332 ** compile. | |
333 */ | |
334 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 | |
335 case SQLITE_CONFIG_SINGLETHREAD: { | |
336 /* Disable all mutexing */ | |
337 sqlite3GlobalConfig.bCoreMutex = 0; | |
338 sqlite3GlobalConfig.bFullMutex = 0; | |
339 break; | |
340 } | |
341 case SQLITE_CONFIG_MULTITHREAD: { | |
342 /* Disable mutexing of database connections */ | |
343 /* Enable mutexing of core data structures */ | |
344 sqlite3GlobalConfig.bCoreMutex = 1; | |
345 sqlite3GlobalConfig.bFullMutex = 0; | |
346 break; | |
347 } | |
348 case SQLITE_CONFIG_SERIALIZED: { | |
349 /* Enable all mutexing */ | |
350 sqlite3GlobalConfig.bCoreMutex = 1; | |
351 sqlite3GlobalConfig.bFullMutex = 1; | |
352 break; | |
353 } | |
354 case SQLITE_CONFIG_MUTEX: { | |
355 /* Specify an alternative mutex implementation */ | |
356 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*); | |
357 break; | |
358 } | |
359 case SQLITE_CONFIG_GETMUTEX: { | |
360 /* Retrieve the current mutex implementation */ | |
361 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex; | |
362 break; | |
363 } | |
364 #endif | |
365 | |
366 | |
367 case SQLITE_CONFIG_MALLOC: { | |
368 /* Specify an alternative malloc implementation */ | |
369 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*); | |
370 break; | |
371 } | |
372 case SQLITE_CONFIG_GETMALLOC: { | |
373 /* Retrieve the current malloc() implementation */ | |
374 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault(); | |
375 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m; | |
376 break; | |
377 } | |
378 case SQLITE_CONFIG_MEMSTATUS: { | |
379 /* Enable or disable the malloc status collection */ | |
380 sqlite3GlobalConfig.bMemstat = va_arg(ap, int); | |
381 break; | |
382 } | |
383 case SQLITE_CONFIG_SCRATCH: { | |
384 /* Designate a buffer for scratch memory space */ | |
385 sqlite3GlobalConfig.pScratch = va_arg(ap, void*); | |
386 sqlite3GlobalConfig.szScratch = va_arg(ap, int); | |
387 sqlite3GlobalConfig.nScratch = va_arg(ap, int); | |
388 break; | |
389 } | |
390 case SQLITE_CONFIG_PAGECACHE: { | |
391 /* Designate a buffer for page cache memory space */ | |
392 sqlite3GlobalConfig.pPage = va_arg(ap, void*); | |
393 sqlite3GlobalConfig.szPage = va_arg(ap, int); | |
394 sqlite3GlobalConfig.nPage = va_arg(ap, int); | |
395 break; | |
396 } | |
397 | |
398 case SQLITE_CONFIG_PCACHE: { | |
399 /* no-op */ | |
400 break; | |
401 } | |
402 case SQLITE_CONFIG_GETPCACHE: { | |
403 /* now an error */ | |
404 rc = SQLITE_ERROR; | |
405 break; | |
406 } | |
407 | |
408 case SQLITE_CONFIG_PCACHE2: { | |
409 /* Specify an alternative page cache implementation */ | |
410 sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*); | |
411 break; | |
412 } | |
413 case SQLITE_CONFIG_GETPCACHE2: { | |
414 if( sqlite3GlobalConfig.pcache2.xInit==0 ){ | |
415 sqlite3PCacheSetDefault(); | |
416 } | |
417 *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2; | |
418 break; | |
419 } | |
420 | |
421 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) | |
422 case SQLITE_CONFIG_HEAP: { | |
423 /* Designate a buffer for heap memory space */ | |
424 sqlite3GlobalConfig.pHeap = va_arg(ap, void*); | |
425 sqlite3GlobalConfig.nHeap = va_arg(ap, int); | |
426 sqlite3GlobalConfig.mnReq = va_arg(ap, int); | |
427 | |
428 if( sqlite3GlobalConfig.mnReq<1 ){ | |
429 sqlite3GlobalConfig.mnReq = 1; | |
430 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){ | |
431 /* cap min request size at 2^12 */ | |
432 sqlite3GlobalConfig.mnReq = (1<<12); | |
433 } | |
434 | |
435 if( sqlite3GlobalConfig.pHeap==0 ){ | |
436 /* If the heap pointer is NULL, then restore the malloc implementation | |
437 ** back to NULL pointers too. This will cause the malloc to go | |
438 ** back to its default implementation when sqlite3_initialize() is | |
439 ** run. | |
440 */ | |
441 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m)); | |
442 }else{ | |
443 /* The heap pointer is not NULL, then install one of the | |
444 ** mem5.c/mem3.c methods. The enclosing #if guarantees at | |
445 ** least one of these methods is currently enabled. | |
446 */ | |
447 #ifdef SQLITE_ENABLE_MEMSYS3 | |
448 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3(); | |
449 #endif | |
450 #ifdef SQLITE_ENABLE_MEMSYS5 | |
451 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5(); | |
452 #endif | |
453 } | |
454 break; | |
455 } | |
456 #endif | |
457 | |
458 case SQLITE_CONFIG_LOOKASIDE: { | |
459 sqlite3GlobalConfig.szLookaside = va_arg(ap, int); | |
460 sqlite3GlobalConfig.nLookaside = va_arg(ap, int); | |
461 break; | |
462 } | |
463 | |
464 /* Record a pointer to the logger function and its first argument. | |
465 ** The default is NULL. Logging is disabled if the function pointer is | |
466 ** NULL. | |
467 */ | |
468 case SQLITE_CONFIG_LOG: { | |
469 /* MSVC is picky about pulling func ptrs from va lists. | |
470 ** http://support.microsoft.com/kb/47961 | |
471 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*)); | |
472 */ | |
473 typedef void(*LOGFUNC_t)(void*,int,const char*); | |
474 sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t); | |
475 sqlite3GlobalConfig.pLogArg = va_arg(ap, void*); | |
476 break; | |
477 } | |
478 | |
479 /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames | |
480 ** can be changed at start-time using the | |
481 ** sqlite3_config(SQLITE_CONFIG_URI,1) or | |
482 ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls. | |
483 */ | |
484 case SQLITE_CONFIG_URI: { | |
485 sqlite3GlobalConfig.bOpenUri = va_arg(ap, int); | |
486 break; | |
487 } | |
488 | |
489 case SQLITE_CONFIG_COVERING_INDEX_SCAN: { | |
490 sqlite3GlobalConfig.bUseCis = va_arg(ap, int); | |
491 break; | |
492 } | |
493 | |
494 #ifdef SQLITE_ENABLE_SQLLOG | |
495 case SQLITE_CONFIG_SQLLOG: { | |
496 typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int); | |
497 sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t); | |
498 sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *); | |
499 break; | |
500 } | |
501 #endif | |
502 | |
503 case SQLITE_CONFIG_MMAP_SIZE: { | |
504 sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64); | |
505 sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64); | |
506 if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){ | |
507 mxMmap = SQLITE_MAX_MMAP_SIZE; | |
508 } | |
509 sqlite3GlobalConfig.mxMmap = mxMmap; | |
510 if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE; | |
511 if( szMmap>mxMmap) szMmap = mxMmap; | |
512 sqlite3GlobalConfig.szMmap = szMmap; | |
513 break; | |
514 } | |
515 | |
516 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) | |
517 case SQLITE_CONFIG_WIN32_HEAPSIZE: { | |
518 sqlite3GlobalConfig.nHeap = va_arg(ap, int); | |
519 break; | |
520 } | |
521 #endif | |
522 | |
523 default: { | |
524 rc = SQLITE_ERROR; | |
525 break; | |
526 } | |
527 } | |
528 va_end(ap); | |
529 return rc; | |
530 } | |
531 | |
532 /* | |
533 ** Set up the lookaside buffers for a database connection. | |
534 ** Return SQLITE_OK on success. | |
535 ** If lookaside is already active, return SQLITE_BUSY. | |
536 ** | |
537 ** The sz parameter is the number of bytes in each lookaside slot. | |
538 ** The cnt parameter is the number of slots. If pStart is NULL the | |
539 ** space for the lookaside memory is obtained from sqlite3_malloc(). | |
540 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for | |
541 ** the lookaside memory. | |
542 */ | |
543 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ | |
544 void *pStart; | |
545 if( db->lookaside.nOut ){ | |
546 return SQLITE_BUSY; | |
547 } | |
548 /* Free any existing lookaside buffer for this handle before | |
549 ** allocating a new one so we don't have to have space for | |
550 ** both at the same time. | |
551 */ | |
552 if( db->lookaside.bMalloced ){ | |
553 sqlite3_free(db->lookaside.pStart); | |
554 } | |
555 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger | |
556 ** than a pointer to be useful. | |
557 */ | |
558 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */ | |
559 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0; | |
560 if( cnt<0 ) cnt = 0; | |
561 if( sz==0 || cnt==0 ){ | |
562 sz = 0; | |
563 pStart = 0; | |
564 }else if( pBuf==0 ){ | |
565 sqlite3BeginBenignMalloc(); | |
566 pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */ | |
567 sqlite3EndBenignMalloc(); | |
568 if( pStart ) cnt = sqlite3MallocSize(pStart)/sz; | |
569 }else{ | |
570 pStart = pBuf; | |
571 } | |
572 db->lookaside.pStart = pStart; | |
573 db->lookaside.pFree = 0; | |
574 db->lookaside.sz = (u16)sz; | |
575 if( pStart ){ | |
576 int i; | |
577 LookasideSlot *p; | |
578 assert( sz > (int)sizeof(LookasideSlot*) ); | |
579 p = (LookasideSlot*)pStart; | |
580 for(i=cnt-1; i>=0; i--){ | |
581 p->pNext = db->lookaside.pFree; | |
582 db->lookaside.pFree = p; | |
583 p = (LookasideSlot*)&((u8*)p)[sz]; | |
584 } | |
585 db->lookaside.pEnd = p; | |
586 db->lookaside.bEnabled = 1; | |
587 db->lookaside.bMalloced = pBuf==0 ?1:0; | |
588 }else{ | |
589 db->lookaside.pStart = db; | |
590 db->lookaside.pEnd = db; | |
591 db->lookaside.bEnabled = 0; | |
592 db->lookaside.bMalloced = 0; | |
593 } | |
594 return SQLITE_OK; | |
595 } | |
596 | |
597 /* | |
598 ** Return the mutex associated with a database connection. | |
599 */ | |
600 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){ | |
601 return db->mutex; | |
602 } | |
603 | |
604 /* | |
605 ** Free up as much memory as we can from the given database | |
606 ** connection. | |
607 */ | |
608 int sqlite3_db_release_memory(sqlite3 *db){ | |
609 int i; | |
610 sqlite3_mutex_enter(db->mutex); | |
611 sqlite3BtreeEnterAll(db); | |
612 for(i=0; i<db->nDb; i++){ | |
613 Btree *pBt = db->aDb[i].pBt; | |
614 if( pBt ){ | |
615 Pager *pPager = sqlite3BtreePager(pBt); | |
616 sqlite3PagerShrink(pPager); | |
617 } | |
618 } | |
619 sqlite3BtreeLeaveAll(db); | |
620 sqlite3_mutex_leave(db->mutex); | |
621 return SQLITE_OK; | |
622 } | |
623 | |
624 /* | |
625 ** Configuration settings for an individual database connection | |
626 */ | |
627 int sqlite3_db_config(sqlite3 *db, int op, ...){ | |
628 va_list ap; | |
629 int rc; | |
630 va_start(ap, op); | |
631 switch( op ){ | |
632 case SQLITE_DBCONFIG_LOOKASIDE: { | |
633 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */ | |
634 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */ | |
635 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */ | |
636 rc = setupLookaside(db, pBuf, sz, cnt); | |
637 break; | |
638 } | |
639 default: { | |
640 static const struct { | |
641 int op; /* The opcode */ | |
642 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */ | |
643 } aFlagOp[] = { | |
644 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys }, | |
645 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger }, | |
646 }; | |
647 unsigned int i; | |
648 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */ | |
649 for(i=0; i<ArraySize(aFlagOp); i++){ | |
650 if( aFlagOp[i].op==op ){ | |
651 int onoff = va_arg(ap, int); | |
652 int *pRes = va_arg(ap, int*); | |
653 int oldFlags = db->flags; | |
654 if( onoff>0 ){ | |
655 db->flags |= aFlagOp[i].mask; | |
656 }else if( onoff==0 ){ | |
657 db->flags &= ~aFlagOp[i].mask; | |
658 } | |
659 if( oldFlags!=db->flags ){ | |
660 sqlite3ExpirePreparedStatements(db); | |
661 } | |
662 if( pRes ){ | |
663 *pRes = (db->flags & aFlagOp[i].mask)!=0; | |
664 } | |
665 rc = SQLITE_OK; | |
666 break; | |
667 } | |
668 } | |
669 break; | |
670 } | |
671 } | |
672 va_end(ap); | |
673 return rc; | |
674 } | |
675 | |
676 | |
677 /* | |
678 ** Return true if the buffer z[0..n-1] contains all spaces. | |
679 */ | |
680 static int allSpaces(const char *z, int n){ | |
681 while( n>0 && z[n-1]==' ' ){ n--; } | |
682 return n==0; | |
683 } | |
684 | |
685 /* | |
686 ** This is the default collating function named "BINARY" which is always | |
687 ** available. | |
688 ** | |
689 ** If the padFlag argument is not NULL then space padding at the end | |
690 ** of strings is ignored. This implements the RTRIM collation. | |
691 */ | |
692 static int binCollFunc( | |
693 void *padFlag, | |
694 int nKey1, const void *pKey1, | |
695 int nKey2, const void *pKey2 | |
696 ){ | |
697 int rc, n; | |
698 n = nKey1<nKey2 ? nKey1 : nKey2; | |
699 rc = memcmp(pKey1, pKey2, n); | |
700 if( rc==0 ){ | |
701 if( padFlag | |
702 && allSpaces(((char*)pKey1)+n, nKey1-n) | |
703 && allSpaces(((char*)pKey2)+n, nKey2-n) | |
704 ){ | |
705 /* Leave rc unchanged at 0 */ | |
706 }else{ | |
707 rc = nKey1 - nKey2; | |
708 } | |
709 } | |
710 return rc; | |
711 } | |
712 | |
713 /* | |
714 ** Another built-in collating sequence: NOCASE. | |
715 ** | |
716 ** This collating sequence is intended to be used for "case independent | |
717 ** comparison". SQLite's knowledge of upper and lower case equivalents | |
718 ** extends only to the 26 characters used in the English language. | |
719 ** | |
720 ** At the moment there is only a UTF-8 implementation. | |
721 */ | |
722 static int nocaseCollatingFunc( | |
723 void *NotUsed, | |
724 int nKey1, const void *pKey1, | |
725 int nKey2, const void *pKey2 | |
726 ){ | |
727 int r = sqlite3StrNICmp( | |
728 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2); | |
729 UNUSED_PARAMETER(NotUsed); | |
730 if( 0==r ){ | |
731 r = nKey1-nKey2; | |
732 } | |
733 return r; | |
734 } | |
735 | |
736 /* | |
737 ** Return the ROWID of the most recent insert | |
738 */ | |
739 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){ | |
740 return db->lastRowid; | |
741 } | |
742 | |
743 /* | |
744 ** Return the number of changes in the most recent call to sqlite3_exec(). | |
745 */ | |
746 int sqlite3_changes(sqlite3 *db){ | |
747 return db->nChange; | |
748 } | |
749 | |
750 /* | |
751 ** Return the number of changes since the database handle was opened. | |
752 */ | |
753 int sqlite3_total_changes(sqlite3 *db){ | |
754 return db->nTotalChange; | |
755 } | |
756 | |
757 /* | |
758 ** Close all open savepoints. This function only manipulates fields of the | |
759 ** database handle object, it does not close any savepoints that may be open | |
760 ** at the b-tree/pager level. | |
761 */ | |
762 void sqlite3CloseSavepoints(sqlite3 *db){ | |
763 while( db->pSavepoint ){ | |
764 Savepoint *pTmp = db->pSavepoint; | |
765 db->pSavepoint = pTmp->pNext; | |
766 sqlite3DbFree(db, pTmp); | |
767 } | |
768 db->nSavepoint = 0; | |
769 db->nStatement = 0; | |
770 db->isTransactionSavepoint = 0; | |
771 } | |
772 | |
773 /* | |
774 ** Invoke the destructor function associated with FuncDef p, if any. Except, | |
775 ** if this is not the last copy of the function, do not invoke it. Multiple | |
776 ** copies of a single function are created when create_function() is called | |
777 ** with SQLITE_ANY as the encoding. | |
778 */ | |
779 static void functionDestroy(sqlite3 *db, FuncDef *p){ | |
780 FuncDestructor *pDestructor = p->pDestructor; | |
781 if( pDestructor ){ | |
782 pDestructor->nRef--; | |
783 if( pDestructor->nRef==0 ){ | |
784 pDestructor->xDestroy(pDestructor->pUserData); | |
785 sqlite3DbFree(db, pDestructor); | |
786 } | |
787 } | |
788 } | |
789 | |
790 /* | |
791 ** Disconnect all sqlite3_vtab objects that belong to database connection | |
792 ** db. This is called when db is being closed. | |
793 */ | |
794 static void disconnectAllVtab(sqlite3 *db){ | |
795 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
796 int i; | |
797 sqlite3BtreeEnterAll(db); | |
798 for(i=0; i<db->nDb; i++){ | |
799 Schema *pSchema = db->aDb[i].pSchema; | |
800 if( db->aDb[i].pSchema ){ | |
801 HashElem *p; | |
802 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ | |
803 Table *pTab = (Table *)sqliteHashData(p); | |
804 if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab); | |
805 } | |
806 } | |
807 } | |
808 sqlite3VtabUnlockList(db); | |
809 sqlite3BtreeLeaveAll(db); | |
810 #else | |
811 UNUSED_PARAMETER(db); | |
812 #endif | |
813 } | |
814 | |
815 /* | |
816 ** Return TRUE if database connection db has unfinalized prepared | |
817 ** statements or unfinished sqlite3_backup objects. | |
818 */ | |
819 static int connectionIsBusy(sqlite3 *db){ | |
820 int j; | |
821 assert( sqlite3_mutex_held(db->mutex) ); | |
822 if( db->pVdbe ) return 1; | |
823 for(j=0; j<db->nDb; j++){ | |
824 Btree *pBt = db->aDb[j].pBt; | |
825 if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1; | |
826 } | |
827 return 0; | |
828 } | |
829 | |
830 /* | |
831 ** Close an existing SQLite database | |
832 */ | |
833 static int sqlite3Close(sqlite3 *db, int forceZombie){ | |
834 if( !db ){ | |
835 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or | |
836 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */ | |
837 return SQLITE_OK; | |
838 } | |
839 if( !sqlite3SafetyCheckSickOrOk(db) ){ | |
840 return SQLITE_MISUSE_BKPT; | |
841 } | |
842 sqlite3_mutex_enter(db->mutex); | |
843 | |
844 /* Force xDisconnect calls on all virtual tables */ | |
845 disconnectAllVtab(db); | |
846 | |
847 /* If a transaction is open, the disconnectAllVtab() call above | |
848 ** will not have called the xDisconnect() method on any virtual | |
849 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback() | |
850 ** call will do so. We need to do this before the check for active | |
851 ** SQL statements below, as the v-table implementation may be storing | |
852 ** some prepared statements internally. | |
853 */ | |
854 sqlite3VtabRollback(db); | |
855 | |
856 /* Legacy behavior (sqlite3_close() behavior) is to return | |
857 ** SQLITE_BUSY if the connection can not be closed immediately. | |
858 */ | |
859 if( !forceZombie && connectionIsBusy(db) ){ | |
860 sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized " | |
861 "statements or unfinished backups"); | |
862 sqlite3_mutex_leave(db->mutex); | |
863 return SQLITE_BUSY; | |
864 } | |
865 | |
866 #ifdef SQLITE_ENABLE_SQLLOG | |
867 if( sqlite3GlobalConfig.xSqllog ){ | |
868 /* Closing the handle. Fourth parameter is passed the value 2. */ | |
869 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2); | |
870 } | |
871 #endif | |
872 | |
873 /* Convert the connection into a zombie and then close it. | |
874 */ | |
875 db->magic = SQLITE_MAGIC_ZOMBIE; | |
876 sqlite3LeaveMutexAndCloseZombie(db); | |
877 return SQLITE_OK; | |
878 } | |
879 | |
880 /* | |
881 ** Two variations on the public interface for closing a database | |
882 ** connection. The sqlite3_close() version returns SQLITE_BUSY and | |
883 ** leaves the connection option if there are unfinalized prepared | |
884 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2() | |
885 ** version forces the connection to become a zombie if there are | |
886 ** unclosed resources, and arranges for deallocation when the last | |
887 ** prepare statement or sqlite3_backup closes. | |
888 */ | |
889 int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); } | |
890 int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); } | |
891 | |
892 | |
893 /* | |
894 ** Close the mutex on database connection db. | |
895 ** | |
896 ** Furthermore, if database connection db is a zombie (meaning that there | |
897 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and | |
898 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has | |
899 ** finished, then free all resources. | |
900 */ | |
901 void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ | |
902 HashElem *i; /* Hash table iterator */ | |
903 int j; | |
904 | |
905 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects | |
906 ** or if the connection has not yet been closed by sqlite3_close_v2(), | |
907 ** then just leave the mutex and return. | |
908 */ | |
909 if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){ | |
910 sqlite3_mutex_leave(db->mutex); | |
911 return; | |
912 } | |
913 | |
914 /* If we reach this point, it means that the database connection has | |
915 ** closed all sqlite3_stmt and sqlite3_backup objects and has been | |
916 ** passed to sqlite3_close (meaning that it is a zombie). Therefore, | |
917 ** go ahead and free all resources. | |
918 */ | |
919 | |
920 /* If a transaction is open, roll it back. This also ensures that if | |
921 ** any database schemas have been modified by an uncommitted transaction | |
922 ** they are reset. And that the required b-tree mutex is held to make | |
923 ** the pager rollback and schema reset an atomic operation. */ | |
924 sqlite3RollbackAll(db, SQLITE_OK); | |
925 | |
926 /* Free any outstanding Savepoint structures. */ | |
927 sqlite3CloseSavepoints(db); | |
928 | |
929 /* Close all database connections */ | |
930 for(j=0; j<db->nDb; j++){ | |
931 struct Db *pDb = &db->aDb[j]; | |
932 if( pDb->pBt ){ | |
933 if( pDb->pSchema ){ | |
934 /* Must clear the KeyInfo cache. See ticket [e4a18565a36884b00edf] */ | |
935 sqlite3BtreeEnter(pDb->pBt); | |
936 for(i=sqliteHashFirst(&pDb->pSchema->idxHash); i; i=sqliteHashNext(i)){ | |
937 Index *pIdx = sqliteHashData(i); | |
938 sqlite3KeyInfoUnref(pIdx->pKeyInfo); | |
939 pIdx->pKeyInfo = 0; | |
940 } | |
941 sqlite3BtreeLeave(pDb->pBt); | |
942 } | |
943 sqlite3BtreeClose(pDb->pBt); | |
944 pDb->pBt = 0; | |
945 if( j!=1 ){ | |
946 pDb->pSchema = 0; | |
947 } | |
948 } | |
949 } | |
950 /* Clear the TEMP schema separately and last */ | |
951 if( db->aDb[1].pSchema ){ | |
952 sqlite3SchemaClear(db->aDb[1].pSchema); | |
953 } | |
954 sqlite3VtabUnlockList(db); | |
955 | |
956 /* Free up the array of auxiliary databases */ | |
957 sqlite3CollapseDatabaseArray(db); | |
958 assert( db->nDb<=2 ); | |
959 assert( db->aDb==db->aDbStatic ); | |
960 | |
961 /* Tell the code in notify.c that the connection no longer holds any | |
962 ** locks and does not require any further unlock-notify callbacks. | |
963 */ | |
964 sqlite3ConnectionClosed(db); | |
965 | |
966 for(j=0; j<ArraySize(db->aFunc.a); j++){ | |
967 FuncDef *pNext, *pHash, *p; | |
968 for(p=db->aFunc.a[j]; p; p=pHash){ | |
969 pHash = p->pHash; | |
970 while( p ){ | |
971 functionDestroy(db, p); | |
972 pNext = p->pNext; | |
973 sqlite3DbFree(db, p); | |
974 p = pNext; | |
975 } | |
976 } | |
977 } | |
978 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){ | |
979 CollSeq *pColl = (CollSeq *)sqliteHashData(i); | |
980 /* Invoke any destructors registered for collation sequence user data. */ | |
981 for(j=0; j<3; j++){ | |
982 if( pColl[j].xDel ){ | |
983 pColl[j].xDel(pColl[j].pUser); | |
984 } | |
985 } | |
986 sqlite3DbFree(db, pColl); | |
987 } | |
988 sqlite3HashClear(&db->aCollSeq); | |
989 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
990 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){ | |
991 Module *pMod = (Module *)sqliteHashData(i); | |
992 if( pMod->xDestroy ){ | |
993 pMod->xDestroy(pMod->pAux); | |
994 } | |
995 sqlite3DbFree(db, pMod); | |
996 } | |
997 sqlite3HashClear(&db->aModule); | |
998 #endif | |
999 | |
1000 sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */ | |
1001 sqlite3ValueFree(db->pErr); | |
1002 sqlite3CloseExtensions(db); | |
1003 #if SQLITE_USER_AUTHENTICATION | |
1004 sqlite3_free(db->auth.zAuthUser); | |
1005 sqlite3_free(db->auth.zAuthPW); | |
1006 #endif | |
1007 | |
1008 db->magic = SQLITE_MAGIC_ERROR; | |
1009 | |
1010 /* The temp-database schema is allocated differently from the other schema | |
1011 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()). | |
1012 ** So it needs to be freed here. Todo: Why not roll the temp schema into | |
1013 ** the same sqliteMalloc() as the one that allocates the database | |
1014 ** structure? | |
1015 */ | |
1016 sqlite3DbFree(db, db->aDb[1].pSchema); | |
1017 sqlite3_mutex_leave(db->mutex); | |
1018 db->magic = SQLITE_MAGIC_CLOSED; | |
1019 sqlite3_mutex_free(db->mutex); | |
1020 assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */ | |
1021 if( db->lookaside.bMalloced ){ | |
1022 sqlite3_free(db->lookaside.pStart); | |
1023 } | |
1024 sqlite3_free(db); | |
1025 } | |
1026 | |
1027 /* | |
1028 ** Rollback all database files. If tripCode is not SQLITE_OK, then | |
1029 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit | |
1030 ** breaker") and made to return tripCode if there are any further | |
1031 ** attempts to use that cursor. Read cursors remain open and valid | |
1032 ** but are "saved" in case the table pages are moved around. | |
1033 */ | |
1034 void sqlite3RollbackAll(sqlite3 *db, int tripCode){ | |
1035 int i; | |
1036 int inTrans = 0; | |
1037 int schemaChange; | |
1038 assert( sqlite3_mutex_held(db->mutex) ); | |
1039 sqlite3BeginBenignMalloc(); | |
1040 | |
1041 /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). | |
1042 ** This is important in case the transaction being rolled back has | |
1043 ** modified the database schema. If the b-tree mutexes are not taken | |
1044 ** here, then another shared-cache connection might sneak in between | |
1045 ** the database rollback and schema reset, which can cause false | |
1046 ** corruption reports in some cases. */ | |
1047 sqlite3BtreeEnterAll(db); | |
1048 schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0; | |
1049 | |
1050 for(i=0; i<db->nDb; i++){ | |
1051 Btree *p = db->aDb[i].pBt; | |
1052 if( p ){ | |
1053 if( sqlite3BtreeIsInTrans(p) ){ | |
1054 inTrans = 1; | |
1055 } | |
1056 sqlite3BtreeRollback(p, tripCode, !schemaChange); | |
1057 } | |
1058 } | |
1059 sqlite3VtabRollback(db); | |
1060 sqlite3EndBenignMalloc(); | |
1061 | |
1062 if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){ | |
1063 sqlite3ExpirePreparedStatements(db); | |
1064 sqlite3ResetAllSchemasOfConnection(db); | |
1065 } | |
1066 sqlite3BtreeLeaveAll(db); | |
1067 | |
1068 /* Any deferred constraint violations have now been resolved. */ | |
1069 db->nDeferredCons = 0; | |
1070 db->nDeferredImmCons = 0; | |
1071 db->flags &= ~SQLITE_DeferFKs; | |
1072 | |
1073 /* If one has been configured, invoke the rollback-hook callback */ | |
1074 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){ | |
1075 db->xRollbackCallback(db->pRollbackArg); | |
1076 } | |
1077 } | |
1078 | |
1079 /* | |
1080 ** Return a static string containing the name corresponding to the error code | |
1081 ** specified in the argument. | |
1082 */ | |
1083 #if (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) || defined(SQLITE_TEST) | |
1084 const char *sqlite3ErrName(int rc){ | |
1085 const char *zName = 0; | |
1086 int i, origRc = rc; | |
1087 for(i=0; i<2 && zName==0; i++, rc &= 0xff){ | |
1088 switch( rc ){ | |
1089 case SQLITE_OK: zName = "SQLITE_OK"; break; | |
1090 case SQLITE_ERROR: zName = "SQLITE_ERROR"; break; | |
1091 case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break; | |
1092 case SQLITE_PERM: zName = "SQLITE_PERM"; break; | |
1093 case SQLITE_ABORT: zName = "SQLITE_ABORT"; break; | |
1094 case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break; | |
1095 case SQLITE_BUSY: zName = "SQLITE_BUSY"; break; | |
1096 case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break; | |
1097 case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break; | |
1098 case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break; | |
1099 case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break; | |
1100 case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break; | |
1101 case SQLITE_READONLY: zName = "SQLITE_READONLY"; break; | |
1102 case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break; | |
1103 case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break; | |
1104 case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break; | |
1105 case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break; | |
1106 case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break; | |
1107 case SQLITE_IOERR: zName = "SQLITE_IOERR"; break; | |
1108 case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break; | |
1109 case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break; | |
1110 case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break; | |
1111 case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break; | |
1112 case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break; | |
1113 case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break; | |
1114 case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break; | |
1115 case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break; | |
1116 case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break; | |
1117 case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break; | |
1118 case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break; | |
1119 case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break; | |
1120 case SQLITE_IOERR_CHECKRESERVEDLOCK: | |
1121 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break; | |
1122 case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break; | |
1123 case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break; | |
1124 case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break; | |
1125 case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break; | |
1126 case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break; | |
1127 case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break; | |
1128 case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break; | |
1129 case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break; | |
1130 case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break; | |
1131 case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break; | |
1132 case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break; | |
1133 case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break; | |
1134 case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break; | |
1135 case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break; | |
1136 case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break; | |
1137 case SQLITE_FULL: zName = "SQLITE_FULL"; break; | |
1138 case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break; | |
1139 case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break; | |
1140 case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break; | |
1141 case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break; | |
1142 case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break; | |
1143 case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break; | |
1144 case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break; | |
1145 case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break; | |
1146 case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break; | |
1147 case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break; | |
1148 case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break; | |
1149 case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break; | |
1150 case SQLITE_CONSTRAINT_FOREIGNKEY: | |
1151 zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break; | |
1152 case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break; | |
1153 case SQLITE_CONSTRAINT_PRIMARYKEY: | |
1154 zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break; | |
1155 case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break; | |
1156 case SQLITE_CONSTRAINT_COMMITHOOK: | |
1157 zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break; | |
1158 case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break; | |
1159 case SQLITE_CONSTRAINT_FUNCTION: | |
1160 zName = "SQLITE_CONSTRAINT_FUNCTION"; break; | |
1161 case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break; | |
1162 case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break; | |
1163 case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break; | |
1164 case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break; | |
1165 case SQLITE_AUTH: zName = "SQLITE_AUTH"; break; | |
1166 case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break; | |
1167 case SQLITE_RANGE: zName = "SQLITE_RANGE"; break; | |
1168 case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break; | |
1169 case SQLITE_ROW: zName = "SQLITE_ROW"; break; | |
1170 case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break; | |
1171 case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break; | |
1172 case SQLITE_NOTICE_RECOVER_ROLLBACK: | |
1173 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break; | |
1174 case SQLITE_WARNING: zName = "SQLITE_WARNING"; break; | |
1175 case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break; | |
1176 case SQLITE_DONE: zName = "SQLITE_DONE"; break; | |
1177 } | |
1178 } | |
1179 if( zName==0 ){ | |
1180 static char zBuf[50]; | |
1181 sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc); | |
1182 zName = zBuf; | |
1183 } | |
1184 return zName; | |
1185 } | |
1186 #endif | |
1187 | |
1188 /* | |
1189 ** Return a static string that describes the kind of error specified in the | |
1190 ** argument. | |
1191 */ | |
1192 const char *sqlite3ErrStr(int rc){ | |
1193 static const char* const aMsg[] = { | |
1194 /* SQLITE_OK */ "not an error", | |
1195 /* SQLITE_ERROR */ "SQL logic error or missing database", | |
1196 /* SQLITE_INTERNAL */ 0, | |
1197 /* SQLITE_PERM */ "access permission denied", | |
1198 /* SQLITE_ABORT */ "callback requested query abort", | |
1199 /* SQLITE_BUSY */ "database is locked", | |
1200 /* SQLITE_LOCKED */ "database table is locked", | |
1201 /* SQLITE_NOMEM */ "out of memory", | |
1202 /* SQLITE_READONLY */ "attempt to write a readonly database", | |
1203 /* SQLITE_INTERRUPT */ "interrupted", | |
1204 /* SQLITE_IOERR */ "disk I/O error", | |
1205 /* SQLITE_CORRUPT */ "database disk image is malformed", | |
1206 /* SQLITE_NOTFOUND */ "unknown operation", | |
1207 /* SQLITE_FULL */ "database or disk is full", | |
1208 /* SQLITE_CANTOPEN */ "unable to open database file", | |
1209 /* SQLITE_PROTOCOL */ "locking protocol", | |
1210 /* SQLITE_EMPTY */ "table contains no data", | |
1211 /* SQLITE_SCHEMA */ "database schema has changed", | |
1212 /* SQLITE_TOOBIG */ "string or blob too big", | |
1213 /* SQLITE_CONSTRAINT */ "constraint failed", | |
1214 /* SQLITE_MISMATCH */ "datatype mismatch", | |
1215 /* SQLITE_MISUSE */ "library routine called out of sequence", | |
1216 /* SQLITE_NOLFS */ "large file support is disabled", | |
1217 /* SQLITE_AUTH */ "authorization denied", | |
1218 /* SQLITE_FORMAT */ "auxiliary database format error", | |
1219 /* SQLITE_RANGE */ "bind or column index out of range", | |
1220 /* SQLITE_NOTADB */ "file is encrypted or is not a database", | |
1221 }; | |
1222 const char *zErr = "unknown error"; | |
1223 switch( rc ){ | |
1224 case SQLITE_ABORT_ROLLBACK: { | |
1225 zErr = "abort due to ROLLBACK"; | |
1226 break; | |
1227 } | |
1228 default: { | |
1229 rc &= 0xff; | |
1230 if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){ | |
1231 zErr = aMsg[rc]; | |
1232 } | |
1233 break; | |
1234 } | |
1235 } | |
1236 return zErr; | |
1237 } | |
1238 | |
1239 /* | |
1240 ** This routine implements a busy callback that sleeps and tries | |
1241 ** again until a timeout value is reached. The timeout value is | |
1242 ** an integer number of milliseconds passed in as the first | |
1243 ** argument. | |
1244 */ | |
1245 static int sqliteDefaultBusyCallback( | |
1246 void *ptr, /* Database connection */ | |
1247 int count /* Number of times table has been busy */ | |
1248 ){ | |
1249 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP) | |
1250 static const u8 delays[] = | |
1251 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 }; | |
1252 static const u8 totals[] = | |
1253 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 }; | |
1254 # define NDELAY ArraySize(delays) | |
1255 sqlite3 *db = (sqlite3 *)ptr; | |
1256 int timeout = db->busyTimeout; | |
1257 int delay, prior; | |
1258 | |
1259 assert( count>=0 ); | |
1260 if( count < NDELAY ){ | |
1261 delay = delays[count]; | |
1262 prior = totals[count]; | |
1263 }else{ | |
1264 delay = delays[NDELAY-1]; | |
1265 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1)); | |
1266 } | |
1267 if( prior + delay > timeout ){ | |
1268 delay = timeout - prior; | |
1269 if( delay<=0 ) return 0; | |
1270 } | |
1271 sqlite3OsSleep(db->pVfs, delay*1000); | |
1272 return 1; | |
1273 #else | |
1274 sqlite3 *db = (sqlite3 *)ptr; | |
1275 int timeout = ((sqlite3 *)ptr)->busyTimeout; | |
1276 if( (count+1)*1000 > timeout ){ | |
1277 return 0; | |
1278 } | |
1279 sqlite3OsSleep(db->pVfs, 1000000); | |
1280 return 1; | |
1281 #endif | |
1282 } | |
1283 | |
1284 /* | |
1285 ** Invoke the given busy handler. | |
1286 ** | |
1287 ** This routine is called when an operation failed with a lock. | |
1288 ** If this routine returns non-zero, the lock is retried. If it | |
1289 ** returns 0, the operation aborts with an SQLITE_BUSY error. | |
1290 */ | |
1291 int sqlite3InvokeBusyHandler(BusyHandler *p){ | |
1292 int rc; | |
1293 if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0; | |
1294 rc = p->xFunc(p->pArg, p->nBusy); | |
1295 if( rc==0 ){ | |
1296 p->nBusy = -1; | |
1297 }else{ | |
1298 p->nBusy++; | |
1299 } | |
1300 return rc; | |
1301 } | |
1302 | |
1303 /* | |
1304 ** This routine sets the busy callback for an Sqlite database to the | |
1305 ** given callback function with the given argument. | |
1306 */ | |
1307 int sqlite3_busy_handler( | |
1308 sqlite3 *db, | |
1309 int (*xBusy)(void*,int), | |
1310 void *pArg | |
1311 ){ | |
1312 sqlite3_mutex_enter(db->mutex); | |
1313 db->busyHandler.xFunc = xBusy; | |
1314 db->busyHandler.pArg = pArg; | |
1315 db->busyHandler.nBusy = 0; | |
1316 db->busyTimeout = 0; | |
1317 sqlite3_mutex_leave(db->mutex); | |
1318 return SQLITE_OK; | |
1319 } | |
1320 | |
1321 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK | |
1322 /* | |
1323 ** This routine sets the progress callback for an Sqlite database to the | |
1324 ** given callback function with the given argument. The progress callback will | |
1325 ** be invoked every nOps opcodes. | |
1326 */ | |
1327 void sqlite3_progress_handler( | |
1328 sqlite3 *db, | |
1329 int nOps, | |
1330 int (*xProgress)(void*), | |
1331 void *pArg | |
1332 ){ | |
1333 sqlite3_mutex_enter(db->mutex); | |
1334 if( nOps>0 ){ | |
1335 db->xProgress = xProgress; | |
1336 db->nProgressOps = (unsigned)nOps; | |
1337 db->pProgressArg = pArg; | |
1338 }else{ | |
1339 db->xProgress = 0; | |
1340 db->nProgressOps = 0; | |
1341 db->pProgressArg = 0; | |
1342 } | |
1343 sqlite3_mutex_leave(db->mutex); | |
1344 } | |
1345 #endif | |
1346 | |
1347 | |
1348 /* | |
1349 ** This routine installs a default busy handler that waits for the | |
1350 ** specified number of milliseconds before returning 0. | |
1351 */ | |
1352 int sqlite3_busy_timeout(sqlite3 *db, int ms){ | |
1353 if( ms>0 ){ | |
1354 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db); | |
1355 db->busyTimeout = ms; | |
1356 }else{ | |
1357 sqlite3_busy_handler(db, 0, 0); | |
1358 } | |
1359 return SQLITE_OK; | |
1360 } | |
1361 | |
1362 /* | |
1363 ** Cause any pending operation to stop at its earliest opportunity. | |
1364 */ | |
1365 void sqlite3_interrupt(sqlite3 *db){ | |
1366 db->u1.isInterrupted = 1; | |
1367 } | |
1368 | |
1369 | |
1370 /* | |
1371 ** This function is exactly the same as sqlite3_create_function(), except | |
1372 ** that it is designed to be called by internal code. The difference is | |
1373 ** that if a malloc() fails in sqlite3_create_function(), an error code | |
1374 ** is returned and the mallocFailed flag cleared. | |
1375 */ | |
1376 int sqlite3CreateFunc( | |
1377 sqlite3 *db, | |
1378 const char *zFunctionName, | |
1379 int nArg, | |
1380 int enc, | |
1381 void *pUserData, | |
1382 void (*xFunc)(sqlite3_context*,int,sqlite3_value **), | |
1383 void (*xStep)(sqlite3_context*,int,sqlite3_value **), | |
1384 void (*xFinal)(sqlite3_context*), | |
1385 FuncDestructor *pDestructor | |
1386 ){ | |
1387 FuncDef *p; | |
1388 int nName; | |
1389 int extraFlags; | |
1390 | |
1391 assert( sqlite3_mutex_held(db->mutex) ); | |
1392 if( zFunctionName==0 || | |
1393 (xFunc && (xFinal || xStep)) || | |
1394 (!xFunc && (xFinal && !xStep)) || | |
1395 (!xFunc && (!xFinal && xStep)) || | |
1396 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) || | |
1397 (255<(nName = sqlite3Strlen30( zFunctionName))) ){ | |
1398 return SQLITE_MISUSE_BKPT; | |
1399 } | |
1400 | |
1401 assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC ); | |
1402 extraFlags = enc & SQLITE_DETERMINISTIC; | |
1403 enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY); | |
1404 | |
1405 #ifndef SQLITE_OMIT_UTF16 | |
1406 /* If SQLITE_UTF16 is specified as the encoding type, transform this | |
1407 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the | |
1408 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. | |
1409 ** | |
1410 ** If SQLITE_ANY is specified, add three versions of the function | |
1411 ** to the hash table. | |
1412 */ | |
1413 if( enc==SQLITE_UTF16 ){ | |
1414 enc = SQLITE_UTF16NATIVE; | |
1415 }else if( enc==SQLITE_ANY ){ | |
1416 int rc; | |
1417 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags, | |
1418 pUserData, xFunc, xStep, xFinal, pDestructor); | |
1419 if( rc==SQLITE_OK ){ | |
1420 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags, | |
1421 pUserData, xFunc, xStep, xFinal, pDestructor); | |
1422 } | |
1423 if( rc!=SQLITE_OK ){ | |
1424 return rc; | |
1425 } | |
1426 enc = SQLITE_UTF16BE; | |
1427 } | |
1428 #else | |
1429 enc = SQLITE_UTF8; | |
1430 #endif | |
1431 | |
1432 /* Check if an existing function is being overridden or deleted. If so, | |
1433 ** and there are active VMs, then return SQLITE_BUSY. If a function | |
1434 ** is being overridden/deleted but there are no active VMs, allow the | |
1435 ** operation to continue but invalidate all precompiled statements. | |
1436 */ | |
1437 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0); | |
1438 if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){ | |
1439 if( db->nVdbeActive ){ | |
1440 sqlite3ErrorWithMsg(db, SQLITE_BUSY, | |
1441 "unable to delete/modify user-function due to active statements"); | |
1442 assert( !db->mallocFailed ); | |
1443 return SQLITE_BUSY; | |
1444 }else{ | |
1445 sqlite3ExpirePreparedStatements(db); | |
1446 } | |
1447 } | |
1448 | |
1449 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1); | |
1450 assert(p || db->mallocFailed); | |
1451 if( !p ){ | |
1452 return SQLITE_NOMEM; | |
1453 } | |
1454 | |
1455 /* If an older version of the function with a configured destructor is | |
1456 ** being replaced invoke the destructor function here. */ | |
1457 functionDestroy(db, p); | |
1458 | |
1459 if( pDestructor ){ | |
1460 pDestructor->nRef++; | |
1461 } | |
1462 p->pDestructor = pDestructor; | |
1463 p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags; | |
1464 testcase( p->funcFlags & SQLITE_DETERMINISTIC ); | |
1465 p->xFunc = xFunc; | |
1466 p->xStep = xStep; | |
1467 p->xFinalize = xFinal; | |
1468 p->pUserData = pUserData; | |
1469 p->nArg = (u16)nArg; | |
1470 return SQLITE_OK; | |
1471 } | |
1472 | |
1473 /* | |
1474 ** Create new user functions. | |
1475 */ | |
1476 int sqlite3_create_function( | |
1477 sqlite3 *db, | |
1478 const char *zFunc, | |
1479 int nArg, | |
1480 int enc, | |
1481 void *p, | |
1482 void (*xFunc)(sqlite3_context*,int,sqlite3_value **), | |
1483 void (*xStep)(sqlite3_context*,int,sqlite3_value **), | |
1484 void (*xFinal)(sqlite3_context*) | |
1485 ){ | |
1486 return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep, | |
1487 xFinal, 0); | |
1488 } | |
1489 | |
1490 int sqlite3_create_function_v2( | |
1491 sqlite3 *db, | |
1492 const char *zFunc, | |
1493 int nArg, | |
1494 int enc, | |
1495 void *p, | |
1496 void (*xFunc)(sqlite3_context*,int,sqlite3_value **), | |
1497 void (*xStep)(sqlite3_context*,int,sqlite3_value **), | |
1498 void (*xFinal)(sqlite3_context*), | |
1499 void (*xDestroy)(void *) | |
1500 ){ | |
1501 int rc = SQLITE_ERROR; | |
1502 FuncDestructor *pArg = 0; | |
1503 sqlite3_mutex_enter(db->mutex); | |
1504 if( xDestroy ){ | |
1505 pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor)); | |
1506 if( !pArg ){ | |
1507 xDestroy(p); | |
1508 goto out; | |
1509 } | |
1510 pArg->xDestroy = xDestroy; | |
1511 pArg->pUserData = p; | |
1512 } | |
1513 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg); | |
1514 if( pArg && pArg->nRef==0 ){ | |
1515 assert( rc!=SQLITE_OK ); | |
1516 xDestroy(p); | |
1517 sqlite3DbFree(db, pArg); | |
1518 } | |
1519 | |
1520 out: | |
1521 rc = sqlite3ApiExit(db, rc); | |
1522 sqlite3_mutex_leave(db->mutex); | |
1523 return rc; | |
1524 } | |
1525 | |
1526 #ifndef SQLITE_OMIT_UTF16 | |
1527 int sqlite3_create_function16( | |
1528 sqlite3 *db, | |
1529 const void *zFunctionName, | |
1530 int nArg, | |
1531 int eTextRep, | |
1532 void *p, | |
1533 void (*xFunc)(sqlite3_context*,int,sqlite3_value**), | |
1534 void (*xStep)(sqlite3_context*,int,sqlite3_value**), | |
1535 void (*xFinal)(sqlite3_context*) | |
1536 ){ | |
1537 int rc; | |
1538 char *zFunc8; | |
1539 sqlite3_mutex_enter(db->mutex); | |
1540 assert( !db->mallocFailed ); | |
1541 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE); | |
1542 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0); | |
1543 sqlite3DbFree(db, zFunc8); | |
1544 rc = sqlite3ApiExit(db, rc); | |
1545 sqlite3_mutex_leave(db->mutex); | |
1546 return rc; | |
1547 } | |
1548 #endif | |
1549 | |
1550 | |
1551 /* | |
1552 ** Declare that a function has been overloaded by a virtual table. | |
1553 ** | |
1554 ** If the function already exists as a regular global function, then | |
1555 ** this routine is a no-op. If the function does not exist, then create | |
1556 ** a new one that always throws a run-time error. | |
1557 ** | |
1558 ** When virtual tables intend to provide an overloaded function, they | |
1559 ** should call this routine to make sure the global function exists. | |
1560 ** A global function must exist in order for name resolution to work | |
1561 ** properly. | |
1562 */ | |
1563 int sqlite3_overload_function( | |
1564 sqlite3 *db, | |
1565 const char *zName, | |
1566 int nArg | |
1567 ){ | |
1568 int nName = sqlite3Strlen30(zName); | |
1569 int rc = SQLITE_OK; | |
1570 sqlite3_mutex_enter(db->mutex); | |
1571 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){ | |
1572 rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8, | |
1573 0, sqlite3InvalidFunction, 0, 0, 0); | |
1574 } | |
1575 rc = sqlite3ApiExit(db, rc); | |
1576 sqlite3_mutex_leave(db->mutex); | |
1577 return rc; | |
1578 } | |
1579 | |
1580 #ifndef SQLITE_OMIT_TRACE | |
1581 /* | |
1582 ** Register a trace function. The pArg from the previously registered trace | |
1583 ** is returned. | |
1584 ** | |
1585 ** A NULL trace function means that no tracing is executes. A non-NULL | |
1586 ** trace is a pointer to a function that is invoked at the start of each | |
1587 ** SQL statement. | |
1588 */ | |
1589 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){ | |
1590 void *pOld; | |
1591 sqlite3_mutex_enter(db->mutex); | |
1592 pOld = db->pTraceArg; | |
1593 db->xTrace = xTrace; | |
1594 db->pTraceArg = pArg; | |
1595 sqlite3_mutex_leave(db->mutex); | |
1596 return pOld; | |
1597 } | |
1598 /* | |
1599 ** Register a profile function. The pArg from the previously registered | |
1600 ** profile function is returned. | |
1601 ** | |
1602 ** A NULL profile function means that no profiling is executes. A non-NULL | |
1603 ** profile is a pointer to a function that is invoked at the conclusion of | |
1604 ** each SQL statement that is run. | |
1605 */ | |
1606 void *sqlite3_profile( | |
1607 sqlite3 *db, | |
1608 void (*xProfile)(void*,const char*,sqlite_uint64), | |
1609 void *pArg | |
1610 ){ | |
1611 void *pOld; | |
1612 sqlite3_mutex_enter(db->mutex); | |
1613 pOld = db->pProfileArg; | |
1614 db->xProfile = xProfile; | |
1615 db->pProfileArg = pArg; | |
1616 sqlite3_mutex_leave(db->mutex); | |
1617 return pOld; | |
1618 } | |
1619 #endif /* SQLITE_OMIT_TRACE */ | |
1620 | |
1621 /* | |
1622 ** Register a function to be invoked when a transaction commits. | |
1623 ** If the invoked function returns non-zero, then the commit becomes a | |
1624 ** rollback. | |
1625 */ | |
1626 void *sqlite3_commit_hook( | |
1627 sqlite3 *db, /* Attach the hook to this database */ | |
1628 int (*xCallback)(void*), /* Function to invoke on each commit */ | |
1629 void *pArg /* Argument to the function */ | |
1630 ){ | |
1631 void *pOld; | |
1632 sqlite3_mutex_enter(db->mutex); | |
1633 pOld = db->pCommitArg; | |
1634 db->xCommitCallback = xCallback; | |
1635 db->pCommitArg = pArg; | |
1636 sqlite3_mutex_leave(db->mutex); | |
1637 return pOld; | |
1638 } | |
1639 | |
1640 /* | |
1641 ** Register a callback to be invoked each time a row is updated, | |
1642 ** inserted or deleted using this database connection. | |
1643 */ | |
1644 void *sqlite3_update_hook( | |
1645 sqlite3 *db, /* Attach the hook to this database */ | |
1646 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64), | |
1647 void *pArg /* Argument to the function */ | |
1648 ){ | |
1649 void *pRet; | |
1650 sqlite3_mutex_enter(db->mutex); | |
1651 pRet = db->pUpdateArg; | |
1652 db->xUpdateCallback = xCallback; | |
1653 db->pUpdateArg = pArg; | |
1654 sqlite3_mutex_leave(db->mutex); | |
1655 return pRet; | |
1656 } | |
1657 | |
1658 /* | |
1659 ** Register a callback to be invoked each time a transaction is rolled | |
1660 ** back by this database connection. | |
1661 */ | |
1662 void *sqlite3_rollback_hook( | |
1663 sqlite3 *db, /* Attach the hook to this database */ | |
1664 void (*xCallback)(void*), /* Callback function */ | |
1665 void *pArg /* Argument to the function */ | |
1666 ){ | |
1667 void *pRet; | |
1668 sqlite3_mutex_enter(db->mutex); | |
1669 pRet = db->pRollbackArg; | |
1670 db->xRollbackCallback = xCallback; | |
1671 db->pRollbackArg = pArg; | |
1672 sqlite3_mutex_leave(db->mutex); | |
1673 return pRet; | |
1674 } | |
1675 | |
1676 #ifndef SQLITE_OMIT_WAL | |
1677 /* | |
1678 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint(). | |
1679 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file | |
1680 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by | |
1681 ** wal_autocheckpoint()). | |
1682 */ | |
1683 int sqlite3WalDefaultHook( | |
1684 void *pClientData, /* Argument */ | |
1685 sqlite3 *db, /* Connection */ | |
1686 const char *zDb, /* Database */ | |
1687 int nFrame /* Size of WAL */ | |
1688 ){ | |
1689 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){ | |
1690 sqlite3BeginBenignMalloc(); | |
1691 sqlite3_wal_checkpoint(db, zDb); | |
1692 sqlite3EndBenignMalloc(); | |
1693 } | |
1694 return SQLITE_OK; | |
1695 } | |
1696 #endif /* SQLITE_OMIT_WAL */ | |
1697 | |
1698 /* | |
1699 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint | |
1700 ** a database after committing a transaction if there are nFrame or | |
1701 ** more frames in the log file. Passing zero or a negative value as the | |
1702 ** nFrame parameter disables automatic checkpoints entirely. | |
1703 ** | |
1704 ** The callback registered by this function replaces any existing callback | |
1705 ** registered using sqlite3_wal_hook(). Likewise, registering a callback | |
1706 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism | |
1707 ** configured by this function. | |
1708 */ | |
1709 int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){ | |
1710 #ifdef SQLITE_OMIT_WAL | |
1711 UNUSED_PARAMETER(db); | |
1712 UNUSED_PARAMETER(nFrame); | |
1713 #else | |
1714 if( nFrame>0 ){ | |
1715 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame)); | |
1716 }else{ | |
1717 sqlite3_wal_hook(db, 0, 0); | |
1718 } | |
1719 #endif | |
1720 return SQLITE_OK; | |
1721 } | |
1722 | |
1723 /* | |
1724 ** Register a callback to be invoked each time a transaction is written | |
1725 ** into the write-ahead-log by this database connection. | |
1726 */ | |
1727 void *sqlite3_wal_hook( | |
1728 sqlite3 *db, /* Attach the hook to this db handle */ | |
1729 int(*xCallback)(void *, sqlite3*, const char*, int), | |
1730 void *pArg /* First argument passed to xCallback() */ | |
1731 ){ | |
1732 #ifndef SQLITE_OMIT_WAL | |
1733 void *pRet; | |
1734 sqlite3_mutex_enter(db->mutex); | |
1735 pRet = db->pWalArg; | |
1736 db->xWalCallback = xCallback; | |
1737 db->pWalArg = pArg; | |
1738 sqlite3_mutex_leave(db->mutex); | |
1739 return pRet; | |
1740 #else | |
1741 return 0; | |
1742 #endif | |
1743 } | |
1744 | |
1745 /* | |
1746 ** Checkpoint database zDb. | |
1747 */ | |
1748 int sqlite3_wal_checkpoint_v2( | |
1749 sqlite3 *db, /* Database handle */ | |
1750 const char *zDb, /* Name of attached database (or NULL) */ | |
1751 int eMode, /* SQLITE_CHECKPOINT_* value */ | |
1752 int *pnLog, /* OUT: Size of WAL log in frames */ | |
1753 int *pnCkpt /* OUT: Total number of frames checkpointed */ | |
1754 ){ | |
1755 #ifdef SQLITE_OMIT_WAL | |
1756 return SQLITE_OK; | |
1757 #else | |
1758 int rc; /* Return code */ | |
1759 int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */ | |
1760 | |
1761 /* Initialize the output variables to -1 in case an error occurs. */ | |
1762 if( pnLog ) *pnLog = -1; | |
1763 if( pnCkpt ) *pnCkpt = -1; | |
1764 | |
1765 assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE ); | |
1766 assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART ); | |
1767 assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART ); | |
1768 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){ | |
1769 return SQLITE_MISUSE; | |
1770 } | |
1771 | |
1772 sqlite3_mutex_enter(db->mutex); | |
1773 if( zDb && zDb[0] ){ | |
1774 iDb = sqlite3FindDbName(db, zDb); | |
1775 } | |
1776 if( iDb<0 ){ | |
1777 rc = SQLITE_ERROR; | |
1778 sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb); | |
1779 }else{ | |
1780 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt); | |
1781 sqlite3Error(db, rc); | |
1782 } | |
1783 rc = sqlite3ApiExit(db, rc); | |
1784 sqlite3_mutex_leave(db->mutex); | |
1785 return rc; | |
1786 #endif | |
1787 } | |
1788 | |
1789 | |
1790 /* | |
1791 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points | |
1792 ** to contains a zero-length string, all attached databases are | |
1793 ** checkpointed. | |
1794 */ | |
1795 int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){ | |
1796 return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0); | |
1797 } | |
1798 | |
1799 #ifndef SQLITE_OMIT_WAL | |
1800 /* | |
1801 ** Run a checkpoint on database iDb. This is a no-op if database iDb is | |
1802 ** not currently open in WAL mode. | |
1803 ** | |
1804 ** If a transaction is open on the database being checkpointed, this | |
1805 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If | |
1806 ** an error occurs while running the checkpoint, an SQLite error code is | |
1807 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK. | |
1808 ** | |
1809 ** The mutex on database handle db should be held by the caller. The mutex | |
1810 ** associated with the specific b-tree being checkpointed is taken by | |
1811 ** this function while the checkpoint is running. | |
1812 ** | |
1813 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are | |
1814 ** checkpointed. If an error is encountered it is returned immediately - | |
1815 ** no attempt is made to checkpoint any remaining databases. | |
1816 ** | |
1817 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. | |
1818 */ | |
1819 int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){ | |
1820 int rc = SQLITE_OK; /* Return code */ | |
1821 int i; /* Used to iterate through attached dbs */ | |
1822 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */ | |
1823 | |
1824 assert( sqlite3_mutex_held(db->mutex) ); | |
1825 assert( !pnLog || *pnLog==-1 ); | |
1826 assert( !pnCkpt || *pnCkpt==-1 ); | |
1827 | |
1828 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){ | |
1829 if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){ | |
1830 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt); | |
1831 pnLog = 0; | |
1832 pnCkpt = 0; | |
1833 if( rc==SQLITE_BUSY ){ | |
1834 bBusy = 1; | |
1835 rc = SQLITE_OK; | |
1836 } | |
1837 } | |
1838 } | |
1839 | |
1840 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc; | |
1841 } | |
1842 #endif /* SQLITE_OMIT_WAL */ | |
1843 | |
1844 /* | |
1845 ** This function returns true if main-memory should be used instead of | |
1846 ** a temporary file for transient pager files and statement journals. | |
1847 ** The value returned depends on the value of db->temp_store (runtime | |
1848 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The | |
1849 ** following table describes the relationship between these two values | |
1850 ** and this functions return value. | |
1851 ** | |
1852 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database | |
1853 ** ----------------- -------------- ------------------------------ | |
1854 ** 0 any file (return 0) | |
1855 ** 1 1 file (return 0) | |
1856 ** 1 2 memory (return 1) | |
1857 ** 1 0 file (return 0) | |
1858 ** 2 1 file (return 0) | |
1859 ** 2 2 memory (return 1) | |
1860 ** 2 0 memory (return 1) | |
1861 ** 3 any memory (return 1) | |
1862 */ | |
1863 int sqlite3TempInMemory(const sqlite3 *db){ | |
1864 #if SQLITE_TEMP_STORE==1 | |
1865 return ( db->temp_store==2 ); | |
1866 #endif | |
1867 #if SQLITE_TEMP_STORE==2 | |
1868 return ( db->temp_store!=1 ); | |
1869 #endif | |
1870 #if SQLITE_TEMP_STORE==3 | |
1871 return 1; | |
1872 #endif | |
1873 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3 | |
1874 return 0; | |
1875 #endif | |
1876 } | |
1877 | |
1878 /* | |
1879 ** Return UTF-8 encoded English language explanation of the most recent | |
1880 ** error. | |
1881 */ | |
1882 const char *sqlite3_errmsg(sqlite3 *db){ | |
1883 const char *z; | |
1884 if( !db ){ | |
1885 return sqlite3ErrStr(SQLITE_NOMEM); | |
1886 } | |
1887 if( !sqlite3SafetyCheckSickOrOk(db) ){ | |
1888 return sqlite3ErrStr(SQLITE_MISUSE_BKPT); | |
1889 } | |
1890 sqlite3_mutex_enter(db->mutex); | |
1891 if( db->mallocFailed ){ | |
1892 z = sqlite3ErrStr(SQLITE_NOMEM); | |
1893 }else{ | |
1894 testcase( db->pErr==0 ); | |
1895 z = (char*)sqlite3_value_text(db->pErr); | |
1896 assert( !db->mallocFailed ); | |
1897 if( z==0 ){ | |
1898 z = sqlite3ErrStr(db->errCode); | |
1899 } | |
1900 } | |
1901 sqlite3_mutex_leave(db->mutex); | |
1902 return z; | |
1903 } | |
1904 | |
1905 #ifndef SQLITE_OMIT_UTF16 | |
1906 /* | |
1907 ** Return UTF-16 encoded English language explanation of the most recent | |
1908 ** error. | |
1909 */ | |
1910 const void *sqlite3_errmsg16(sqlite3 *db){ | |
1911 static const u16 outOfMem[] = { | |
1912 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0 | |
1913 }; | |
1914 static const u16 misuse[] = { | |
1915 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', | |
1916 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', | |
1917 'c', 'a', 'l', 'l', 'e', 'd', ' ', | |
1918 'o', 'u', 't', ' ', | |
1919 'o', 'f', ' ', | |
1920 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0 | |
1921 }; | |
1922 | |
1923 const void *z; | |
1924 if( !db ){ | |
1925 return (void *)outOfMem; | |
1926 } | |
1927 if( !sqlite3SafetyCheckSickOrOk(db) ){ | |
1928 return (void *)misuse; | |
1929 } | |
1930 sqlite3_mutex_enter(db->mutex); | |
1931 if( db->mallocFailed ){ | |
1932 z = (void *)outOfMem; | |
1933 }else{ | |
1934 z = sqlite3_value_text16(db->pErr); | |
1935 if( z==0 ){ | |
1936 sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode)); | |
1937 z = sqlite3_value_text16(db->pErr); | |
1938 } | |
1939 /* A malloc() may have failed within the call to sqlite3_value_text16() | |
1940 ** above. If this is the case, then the db->mallocFailed flag needs to | |
1941 ** be cleared before returning. Do this directly, instead of via | |
1942 ** sqlite3ApiExit(), to avoid setting the database handle error message. | |
1943 */ | |
1944 db->mallocFailed = 0; | |
1945 } | |
1946 sqlite3_mutex_leave(db->mutex); | |
1947 return z; | |
1948 } | |
1949 #endif /* SQLITE_OMIT_UTF16 */ | |
1950 | |
1951 /* | |
1952 ** Return the most recent error code generated by an SQLite routine. If NULL is | |
1953 ** passed to this function, we assume a malloc() failed during sqlite3_open(). | |
1954 */ | |
1955 int sqlite3_errcode(sqlite3 *db){ | |
1956 if( db && !sqlite3SafetyCheckSickOrOk(db) ){ | |
1957 return SQLITE_MISUSE_BKPT; | |
1958 } | |
1959 if( !db || db->mallocFailed ){ | |
1960 return SQLITE_NOMEM; | |
1961 } | |
1962 return db->errCode & db->errMask; | |
1963 } | |
1964 int sqlite3_extended_errcode(sqlite3 *db){ | |
1965 if( db && !sqlite3SafetyCheckSickOrOk(db) ){ | |
1966 return SQLITE_MISUSE_BKPT; | |
1967 } | |
1968 if( !db || db->mallocFailed ){ | |
1969 return SQLITE_NOMEM; | |
1970 } | |
1971 return db->errCode; | |
1972 } | |
1973 | |
1974 /* | |
1975 ** Return a string that describes the kind of error specified in the | |
1976 ** argument. For now, this simply calls the internal sqlite3ErrStr() | |
1977 ** function. | |
1978 */ | |
1979 const char *sqlite3_errstr(int rc){ | |
1980 return sqlite3ErrStr(rc); | |
1981 } | |
1982 | |
1983 /* | |
1984 ** Invalidate all cached KeyInfo objects for database connection "db" | |
1985 */ | |
1986 static void invalidateCachedKeyInfo(sqlite3 *db){ | |
1987 Db *pDb; /* A single database */ | |
1988 int iDb; /* The database index number */ | |
1989 HashElem *k; /* For looping over tables in pDb */ | |
1990 Table *pTab; /* A table in the database */ | |
1991 Index *pIdx; /* Each index */ | |
1992 | |
1993 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ | |
1994 if( pDb->pBt==0 ) continue; | |
1995 sqlite3BtreeEnter(pDb->pBt); | |
1996 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ | |
1997 pTab = (Table*)sqliteHashData(k); | |
1998 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ | |
1999 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db==db ){ | |
2000 sqlite3KeyInfoUnref(pIdx->pKeyInfo); | |
2001 pIdx->pKeyInfo = 0; | |
2002 } | |
2003 } | |
2004 } | |
2005 sqlite3BtreeLeave(pDb->pBt); | |
2006 } | |
2007 } | |
2008 | |
2009 /* | |
2010 ** Create a new collating function for database "db". The name is zName | |
2011 ** and the encoding is enc. | |
2012 */ | |
2013 static int createCollation( | |
2014 sqlite3* db, | |
2015 const char *zName, | |
2016 u8 enc, | |
2017 void* pCtx, | |
2018 int(*xCompare)(void*,int,const void*,int,const void*), | |
2019 void(*xDel)(void*) | |
2020 ){ | |
2021 CollSeq *pColl; | |
2022 int enc2; | |
2023 | |
2024 assert( sqlite3_mutex_held(db->mutex) ); | |
2025 | |
2026 /* If SQLITE_UTF16 is specified as the encoding type, transform this | |
2027 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the | |
2028 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. | |
2029 */ | |
2030 enc2 = enc; | |
2031 testcase( enc2==SQLITE_UTF16 ); | |
2032 testcase( enc2==SQLITE_UTF16_ALIGNED ); | |
2033 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){ | |
2034 enc2 = SQLITE_UTF16NATIVE; | |
2035 } | |
2036 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){ | |
2037 return SQLITE_MISUSE_BKPT; | |
2038 } | |
2039 | |
2040 /* Check if this call is removing or replacing an existing collation | |
2041 ** sequence. If so, and there are active VMs, return busy. If there | |
2042 ** are no active VMs, invalidate any pre-compiled statements. | |
2043 */ | |
2044 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0); | |
2045 if( pColl && pColl->xCmp ){ | |
2046 if( db->nVdbeActive ){ | |
2047 sqlite3ErrorWithMsg(db, SQLITE_BUSY, | |
2048 "unable to delete/modify collation sequence due to active statements"); | |
2049 return SQLITE_BUSY; | |
2050 } | |
2051 sqlite3ExpirePreparedStatements(db); | |
2052 invalidateCachedKeyInfo(db); | |
2053 | |
2054 /* If collation sequence pColl was created directly by a call to | |
2055 ** sqlite3_create_collation, and not generated by synthCollSeq(), | |
2056 ** then any copies made by synthCollSeq() need to be invalidated. | |
2057 ** Also, collation destructor - CollSeq.xDel() - function may need | |
2058 ** to be called. | |
2059 */ | |
2060 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){ | |
2061 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName); | |
2062 int j; | |
2063 for(j=0; j<3; j++){ | |
2064 CollSeq *p = &aColl[j]; | |
2065 if( p->enc==pColl->enc ){ | |
2066 if( p->xDel ){ | |
2067 p->xDel(p->pUser); | |
2068 } | |
2069 p->xCmp = 0; | |
2070 } | |
2071 } | |
2072 } | |
2073 } | |
2074 | |
2075 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1); | |
2076 if( pColl==0 ) return SQLITE_NOMEM; | |
2077 pColl->xCmp = xCompare; | |
2078 pColl->pUser = pCtx; | |
2079 pColl->xDel = xDel; | |
2080 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED)); | |
2081 sqlite3Error(db, SQLITE_OK); | |
2082 return SQLITE_OK; | |
2083 } | |
2084 | |
2085 | |
2086 /* | |
2087 ** This array defines hard upper bounds on limit values. The | |
2088 ** initializer must be kept in sync with the SQLITE_LIMIT_* | |
2089 ** #defines in sqlite3.h. | |
2090 */ | |
2091 static const int aHardLimit[] = { | |
2092 SQLITE_MAX_LENGTH, | |
2093 SQLITE_MAX_SQL_LENGTH, | |
2094 SQLITE_MAX_COLUMN, | |
2095 SQLITE_MAX_EXPR_DEPTH, | |
2096 SQLITE_MAX_COMPOUND_SELECT, | |
2097 SQLITE_MAX_VDBE_OP, | |
2098 SQLITE_MAX_FUNCTION_ARG, | |
2099 SQLITE_MAX_ATTACHED, | |
2100 SQLITE_MAX_LIKE_PATTERN_LENGTH, | |
2101 SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */ | |
2102 SQLITE_MAX_TRIGGER_DEPTH, | |
2103 SQLITE_MAX_WORKER_THREADS, | |
2104 }; | |
2105 | |
2106 /* | |
2107 ** Make sure the hard limits are set to reasonable values | |
2108 */ | |
2109 #if SQLITE_MAX_LENGTH<100 | |
2110 # error SQLITE_MAX_LENGTH must be at least 100 | |
2111 #endif | |
2112 #if SQLITE_MAX_SQL_LENGTH<100 | |
2113 # error SQLITE_MAX_SQL_LENGTH must be at least 100 | |
2114 #endif | |
2115 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH | |
2116 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH | |
2117 #endif | |
2118 #if SQLITE_MAX_COMPOUND_SELECT<2 | |
2119 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2 | |
2120 #endif | |
2121 #if SQLITE_MAX_VDBE_OP<40 | |
2122 # error SQLITE_MAX_VDBE_OP must be at least 40 | |
2123 #endif | |
2124 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000 | |
2125 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000 | |
2126 #endif | |
2127 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125 | |
2128 # error SQLITE_MAX_ATTACHED must be between 0 and 125 | |
2129 #endif | |
2130 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 | |
2131 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 | |
2132 #endif | |
2133 #if SQLITE_MAX_COLUMN>32767 | |
2134 # error SQLITE_MAX_COLUMN must not exceed 32767 | |
2135 #endif | |
2136 #if SQLITE_MAX_TRIGGER_DEPTH<1 | |
2137 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1 | |
2138 #endif | |
2139 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50 | |
2140 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50 | |
2141 #endif | |
2142 | |
2143 | |
2144 /* | |
2145 ** Change the value of a limit. Report the old value. | |
2146 ** If an invalid limit index is supplied, report -1. | |
2147 ** Make no changes but still report the old value if the | |
2148 ** new limit is negative. | |
2149 ** | |
2150 ** A new lower limit does not shrink existing constructs. | |
2151 ** It merely prevents new constructs that exceed the limit | |
2152 ** from forming. | |
2153 */ | |
2154 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ | |
2155 int oldLimit; | |
2156 | |
2157 | |
2158 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME | |
2159 ** there is a hard upper bound set at compile-time by a C preprocessor | |
2160 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to | |
2161 ** "_MAX_".) | |
2162 */ | |
2163 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH ); | |
2164 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH ); | |
2165 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN ); | |
2166 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH ); | |
2167 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT); | |
2168 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP ); | |
2169 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG ); | |
2170 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED ); | |
2171 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]== | |
2172 SQLITE_MAX_LIKE_PATTERN_LENGTH ); | |
2173 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER); | |
2174 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH ); | |
2175 assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS ); | |
2176 assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) ); | |
2177 | |
2178 | |
2179 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){ | |
2180 return -1; | |
2181 } | |
2182 oldLimit = db->aLimit[limitId]; | |
2183 if( newLimit>=0 ){ /* IMP: R-52476-28732 */ | |
2184 if( newLimit>aHardLimit[limitId] ){ | |
2185 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */ | |
2186 } | |
2187 db->aLimit[limitId] = newLimit; | |
2188 } | |
2189 return oldLimit; /* IMP: R-53341-35419 */ | |
2190 } | |
2191 | |
2192 /* | |
2193 ** This function is used to parse both URIs and non-URI filenames passed by the | |
2194 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database | |
2195 ** URIs specified as part of ATTACH statements. | |
2196 ** | |
2197 ** The first argument to this function is the name of the VFS to use (or | |
2198 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx" | |
2199 ** query parameter. The second argument contains the URI (or non-URI filename) | |
2200 ** itself. When this function is called the *pFlags variable should contain | |
2201 ** the default flags to open the database handle with. The value stored in | |
2202 ** *pFlags may be updated before returning if the URI filename contains | |
2203 ** "cache=xxx" or "mode=xxx" query parameters. | |
2204 ** | |
2205 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to | |
2206 ** the VFS that should be used to open the database file. *pzFile is set to | |
2207 ** point to a buffer containing the name of the file to open. It is the | |
2208 ** responsibility of the caller to eventually call sqlite3_free() to release | |
2209 ** this buffer. | |
2210 ** | |
2211 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg | |
2212 ** may be set to point to a buffer containing an English language error | |
2213 ** message. It is the responsibility of the caller to eventually release | |
2214 ** this buffer by calling sqlite3_free(). | |
2215 */ | |
2216 int sqlite3ParseUri( | |
2217 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */ | |
2218 const char *zUri, /* Nul-terminated URI to parse */ | |
2219 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */ | |
2220 sqlite3_vfs **ppVfs, /* OUT: VFS to use */ | |
2221 char **pzFile, /* OUT: Filename component of URI */ | |
2222 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */ | |
2223 ){ | |
2224 int rc = SQLITE_OK; | |
2225 unsigned int flags = *pFlags; | |
2226 const char *zVfs = zDefaultVfs; | |
2227 char *zFile; | |
2228 char c; | |
2229 int nUri = sqlite3Strlen30(zUri); | |
2230 | |
2231 assert( *pzErrMsg==0 ); | |
2232 | |
2233 if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri) | |
2234 && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */ | |
2235 ){ | |
2236 char *zOpt; | |
2237 int eState; /* Parser state when parsing URI */ | |
2238 int iIn; /* Input character index */ | |
2239 int iOut = 0; /* Output character index */ | |
2240 int nByte = nUri+2; /* Bytes of space to allocate */ | |
2241 | |
2242 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen | |
2243 ** method that there may be extra parameters following the file-name. */ | |
2244 flags |= SQLITE_OPEN_URI; | |
2245 | |
2246 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&'); | |
2247 zFile = sqlite3_malloc(nByte); | |
2248 if( !zFile ) return SQLITE_NOMEM; | |
2249 | |
2250 iIn = 5; | |
2251 #ifndef SQLITE_ALLOW_URI_AUTHORITY | |
2252 /* Discard the scheme and authority segments of the URI. */ | |
2253 if( zUri[5]=='/' && zUri[6]=='/' ){ | |
2254 iIn = 7; | |
2255 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++; | |
2256 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){ | |
2257 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", | |
2258 iIn-7, &zUri[7]); | |
2259 rc = SQLITE_ERROR; | |
2260 goto parse_uri_out; | |
2261 } | |
2262 } | |
2263 #endif | |
2264 | |
2265 /* Copy the filename and any query parameters into the zFile buffer. | |
2266 ** Decode %HH escape codes along the way. | |
2267 ** | |
2268 ** Within this loop, variable eState may be set to 0, 1 or 2, depending | |
2269 ** on the parsing context. As follows: | |
2270 ** | |
2271 ** 0: Parsing file-name. | |
2272 ** 1: Parsing name section of a name=value query parameter. | |
2273 ** 2: Parsing value section of a name=value query parameter. | |
2274 */ | |
2275 eState = 0; | |
2276 while( (c = zUri[iIn])!=0 && c!='#' ){ | |
2277 iIn++; | |
2278 if( c=='%' | |
2279 && sqlite3Isxdigit(zUri[iIn]) | |
2280 && sqlite3Isxdigit(zUri[iIn+1]) | |
2281 ){ | |
2282 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4); | |
2283 octet += sqlite3HexToInt(zUri[iIn++]); | |
2284 | |
2285 assert( octet>=0 && octet<256 ); | |
2286 if( octet==0 ){ | |
2287 /* This branch is taken when "%00" appears within the URI. In this | |
2288 ** case we ignore all text in the remainder of the path, name or | |
2289 ** value currently being parsed. So ignore the current character | |
2290 ** and skip to the next "?", "=" or "&", as appropriate. */ | |
2291 while( (c = zUri[iIn])!=0 && c!='#' | |
2292 && (eState!=0 || c!='?') | |
2293 && (eState!=1 || (c!='=' && c!='&')) | |
2294 && (eState!=2 || c!='&') | |
2295 ){ | |
2296 iIn++; | |
2297 } | |
2298 continue; | |
2299 } | |
2300 c = octet; | |
2301 }else if( eState==1 && (c=='&' || c=='=') ){ | |
2302 if( zFile[iOut-1]==0 ){ | |
2303 /* An empty option name. Ignore this option altogether. */ | |
2304 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++; | |
2305 continue; | |
2306 } | |
2307 if( c=='&' ){ | |
2308 zFile[iOut++] = '\0'; | |
2309 }else{ | |
2310 eState = 2; | |
2311 } | |
2312 c = 0; | |
2313 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){ | |
2314 c = 0; | |
2315 eState = 1; | |
2316 } | |
2317 zFile[iOut++] = c; | |
2318 } | |
2319 if( eState==1 ) zFile[iOut++] = '\0'; | |
2320 zFile[iOut++] = '\0'; | |
2321 zFile[iOut++] = '\0'; | |
2322 | |
2323 /* Check if there were any options specified that should be interpreted | |
2324 ** here. Options that are interpreted here include "vfs" and those that | |
2325 ** correspond to flags that may be passed to the sqlite3_open_v2() | |
2326 ** method. */ | |
2327 zOpt = &zFile[sqlite3Strlen30(zFile)+1]; | |
2328 while( zOpt[0] ){ | |
2329 int nOpt = sqlite3Strlen30(zOpt); | |
2330 char *zVal = &zOpt[nOpt+1]; | |
2331 int nVal = sqlite3Strlen30(zVal); | |
2332 | |
2333 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){ | |
2334 zVfs = zVal; | |
2335 }else{ | |
2336 struct OpenMode { | |
2337 const char *z; | |
2338 int mode; | |
2339 } *aMode = 0; | |
2340 char *zModeType = 0; | |
2341 int mask = 0; | |
2342 int limit = 0; | |
2343 | |
2344 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){ | |
2345 static struct OpenMode aCacheMode[] = { | |
2346 { "shared", SQLITE_OPEN_SHAREDCACHE }, | |
2347 { "private", SQLITE_OPEN_PRIVATECACHE }, | |
2348 { 0, 0 } | |
2349 }; | |
2350 | |
2351 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE; | |
2352 aMode = aCacheMode; | |
2353 limit = mask; | |
2354 zModeType = "cache"; | |
2355 } | |
2356 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){ | |
2357 static struct OpenMode aOpenMode[] = { | |
2358 { "ro", SQLITE_OPEN_READONLY }, | |
2359 { "rw", SQLITE_OPEN_READWRITE }, | |
2360 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE }, | |
2361 { "memory", SQLITE_OPEN_MEMORY }, | |
2362 { 0, 0 } | |
2363 }; | |
2364 | |
2365 mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE | |
2366 | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY; | |
2367 aMode = aOpenMode; | |
2368 limit = mask & flags; | |
2369 zModeType = "access"; | |
2370 } | |
2371 | |
2372 if( aMode ){ | |
2373 int i; | |
2374 int mode = 0; | |
2375 for(i=0; aMode[i].z; i++){ | |
2376 const char *z = aMode[i].z; | |
2377 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){ | |
2378 mode = aMode[i].mode; | |
2379 break; | |
2380 } | |
2381 } | |
2382 if( mode==0 ){ | |
2383 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal); | |
2384 rc = SQLITE_ERROR; | |
2385 goto parse_uri_out; | |
2386 } | |
2387 if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){ | |
2388 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s", | |
2389 zModeType, zVal); | |
2390 rc = SQLITE_PERM; | |
2391 goto parse_uri_out; | |
2392 } | |
2393 flags = (flags & ~mask) | mode; | |
2394 } | |
2395 } | |
2396 | |
2397 zOpt = &zVal[nVal+1]; | |
2398 } | |
2399 | |
2400 }else{ | |
2401 zFile = sqlite3_malloc(nUri+2); | |
2402 if( !zFile ) return SQLITE_NOMEM; | |
2403 memcpy(zFile, zUri, nUri); | |
2404 zFile[nUri] = '\0'; | |
2405 zFile[nUri+1] = '\0'; | |
2406 flags &= ~SQLITE_OPEN_URI; | |
2407 } | |
2408 | |
2409 *ppVfs = sqlite3_vfs_find(zVfs); | |
2410 if( *ppVfs==0 ){ | |
2411 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs); | |
2412 rc = SQLITE_ERROR; | |
2413 } | |
2414 parse_uri_out: | |
2415 if( rc!=SQLITE_OK ){ | |
2416 sqlite3_free(zFile); | |
2417 zFile = 0; | |
2418 } | |
2419 *pFlags = flags; | |
2420 *pzFile = zFile; | |
2421 return rc; | |
2422 } | |
2423 | |
2424 | |
2425 /* | |
2426 ** This routine does the work of opening a database on behalf of | |
2427 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" | |
2428 ** is UTF-8 encoded. | |
2429 */ | |
2430 static int openDatabase( | |
2431 const char *zFilename, /* Database filename UTF-8 encoded */ | |
2432 sqlite3 **ppDb, /* OUT: Returned database handle */ | |
2433 unsigned int flags, /* Operational flags */ | |
2434 const char *zVfs /* Name of the VFS to use */ | |
2435 ){ | |
2436 sqlite3 *db; /* Store allocated handle here */ | |
2437 int rc; /* Return code */ | |
2438 int isThreadsafe; /* True for threadsafe connections */ | |
2439 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */ | |
2440 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */ | |
2441 | |
2442 *ppDb = 0; | |
2443 #ifndef SQLITE_OMIT_AUTOINIT | |
2444 rc = sqlite3_initialize(); | |
2445 if( rc ) return rc; | |
2446 #endif | |
2447 | |
2448 /* Only allow sensible combinations of bits in the flags argument. | |
2449 ** Throw an error if any non-sense combination is used. If we | |
2450 ** do not block illegal combinations here, it could trigger | |
2451 ** assert() statements in deeper layers. Sensible combinations | |
2452 ** are: | |
2453 ** | |
2454 ** 1: SQLITE_OPEN_READONLY | |
2455 ** 2: SQLITE_OPEN_READWRITE | |
2456 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | |
2457 */ | |
2458 assert( SQLITE_OPEN_READONLY == 0x01 ); | |
2459 assert( SQLITE_OPEN_READWRITE == 0x02 ); | |
2460 assert( SQLITE_OPEN_CREATE == 0x04 ); | |
2461 testcase( (1<<(flags&7))==0x02 ); /* READONLY */ | |
2462 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */ | |
2463 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */ | |
2464 if( ((1<<(flags&7)) & 0x46)==0 ){ | |
2465 return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */ | |
2466 } | |
2467 | |
2468 if( sqlite3GlobalConfig.bCoreMutex==0 ){ | |
2469 isThreadsafe = 0; | |
2470 }else if( flags & SQLITE_OPEN_NOMUTEX ){ | |
2471 isThreadsafe = 0; | |
2472 }else if( flags & SQLITE_OPEN_FULLMUTEX ){ | |
2473 isThreadsafe = 1; | |
2474 }else{ | |
2475 isThreadsafe = sqlite3GlobalConfig.bFullMutex; | |
2476 } | |
2477 if( flags & SQLITE_OPEN_PRIVATECACHE ){ | |
2478 flags &= ~SQLITE_OPEN_SHAREDCACHE; | |
2479 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){ | |
2480 flags |= SQLITE_OPEN_SHAREDCACHE; | |
2481 } | |
2482 | |
2483 /* Remove harmful bits from the flags parameter | |
2484 ** | |
2485 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were | |
2486 ** dealt with in the previous code block. Besides these, the only | |
2487 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY, | |
2488 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE, | |
2489 ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask | |
2490 ** off all other flags. | |
2491 */ | |
2492 flags &= ~( SQLITE_OPEN_DELETEONCLOSE | | |
2493 SQLITE_OPEN_EXCLUSIVE | | |
2494 SQLITE_OPEN_MAIN_DB | | |
2495 SQLITE_OPEN_TEMP_DB | | |
2496 SQLITE_OPEN_TRANSIENT_DB | | |
2497 SQLITE_OPEN_MAIN_JOURNAL | | |
2498 SQLITE_OPEN_TEMP_JOURNAL | | |
2499 SQLITE_OPEN_SUBJOURNAL | | |
2500 SQLITE_OPEN_MASTER_JOURNAL | | |
2501 SQLITE_OPEN_NOMUTEX | | |
2502 SQLITE_OPEN_FULLMUTEX | | |
2503 SQLITE_OPEN_WAL | |
2504 ); | |
2505 | |
2506 /* Allocate the sqlite data structure */ | |
2507 db = sqlite3MallocZero( sizeof(sqlite3) ); | |
2508 if( db==0 ) goto opendb_out; | |
2509 if( isThreadsafe ){ | |
2510 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); | |
2511 if( db->mutex==0 ){ | |
2512 sqlite3_free(db); | |
2513 db = 0; | |
2514 goto opendb_out; | |
2515 } | |
2516 } | |
2517 sqlite3_mutex_enter(db->mutex); | |
2518 db->errMask = 0xff; | |
2519 db->nDb = 2; | |
2520 db->magic = SQLITE_MAGIC_BUSY; | |
2521 db->aDb = db->aDbStatic; | |
2522 | |
2523 assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); | |
2524 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); | |
2525 db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS; | |
2526 db->autoCommit = 1; | |
2527 db->nextAutovac = -1; | |
2528 db->szMmap = sqlite3GlobalConfig.szMmap; | |
2529 db->nextPagesize = 0; | |
2530 db->nMaxSorterMmap = 0x7FFFFFFF; | |
2531 db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill | |
2532 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX | |
2533 | SQLITE_AutoIndex | |
2534 #endif | |
2535 #if SQLITE_DEFAULT_FILE_FORMAT<4 | |
2536 | SQLITE_LegacyFileFmt | |
2537 #endif | |
2538 #ifdef SQLITE_ENABLE_LOAD_EXTENSION | |
2539 | SQLITE_LoadExtension | |
2540 #endif | |
2541 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS | |
2542 | SQLITE_RecTriggers | |
2543 #endif | |
2544 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS | |
2545 | SQLITE_ForeignKeys | |
2546 #endif | |
2547 ; | |
2548 sqlite3HashInit(&db->aCollSeq); | |
2549 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
2550 sqlite3HashInit(&db->aModule); | |
2551 #endif | |
2552 | |
2553 /* Add the default collation sequence BINARY. BINARY works for both UTF-8 | |
2554 ** and UTF-16, so add a version for each to avoid any unnecessary | |
2555 ** conversions. The only error that can occur here is a malloc() failure. | |
2556 */ | |
2557 createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0); | |
2558 createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0); | |
2559 createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0); | |
2560 createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0); | |
2561 if( db->mallocFailed ){ | |
2562 goto opendb_out; | |
2563 } | |
2564 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0); | |
2565 assert( db->pDfltColl!=0 ); | |
2566 | |
2567 /* Also add a UTF-8 case-insensitive collation sequence. */ | |
2568 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0); | |
2569 | |
2570 /* Parse the filename/URI argument. */ | |
2571 db->openFlags = flags; | |
2572 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg); | |
2573 if( rc!=SQLITE_OK ){ | |
2574 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1; | |
2575 sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg); | |
2576 sqlite3_free(zErrMsg); | |
2577 goto opendb_out; | |
2578 } | |
2579 | |
2580 /* Open the backend database driver */ | |
2581 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0, | |
2582 flags | SQLITE_OPEN_MAIN_DB); | |
2583 if( rc!=SQLITE_OK ){ | |
2584 if( rc==SQLITE_IOERR_NOMEM ){ | |
2585 rc = SQLITE_NOMEM; | |
2586 } | |
2587 sqlite3Error(db, rc); | |
2588 goto opendb_out; | |
2589 } | |
2590 sqlite3BtreeEnter(db->aDb[0].pBt); | |
2591 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt); | |
2592 sqlite3BtreeLeave(db->aDb[0].pBt); | |
2593 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0); | |
2594 | |
2595 /* The default safety_level for the main database is 'full'; for the temp | |
2596 ** database it is 'NONE'. This matches the pager layer defaults. | |
2597 */ | |
2598 db->aDb[0].zName = "main"; | |
2599 db->aDb[0].safety_level = 3; | |
2600 db->aDb[1].zName = "temp"; | |
2601 db->aDb[1].safety_level = 1; | |
2602 | |
2603 db->magic = SQLITE_MAGIC_OPEN; | |
2604 if( db->mallocFailed ){ | |
2605 goto opendb_out; | |
2606 } | |
2607 | |
2608 /* Register all built-in functions, but do not attempt to read the | |
2609 ** database schema yet. This is delayed until the first time the database | |
2610 ** is accessed. | |
2611 */ | |
2612 sqlite3Error(db, SQLITE_OK); | |
2613 sqlite3RegisterBuiltinFunctions(db); | |
2614 | |
2615 /* Load automatic extensions - extensions that have been registered | |
2616 ** using the sqlite3_automatic_extension() API. | |
2617 */ | |
2618 rc = sqlite3_errcode(db); | |
2619 if( rc==SQLITE_OK ){ | |
2620 sqlite3AutoLoadExtensions(db); | |
2621 rc = sqlite3_errcode(db); | |
2622 if( rc!=SQLITE_OK ){ | |
2623 goto opendb_out; | |
2624 } | |
2625 } | |
2626 | |
2627 #ifdef SQLITE_ENABLE_FTS1 | |
2628 if( !db->mallocFailed ){ | |
2629 extern int sqlite3Fts1Init(sqlite3*); | |
2630 rc = sqlite3Fts1Init(db); | |
2631 } | |
2632 #endif | |
2633 | |
2634 #ifdef SQLITE_ENABLE_FTS2 | |
2635 if( !db->mallocFailed && rc==SQLITE_OK ){ | |
2636 extern int sqlite3Fts2Init(sqlite3*); | |
2637 rc = sqlite3Fts2Init(db); | |
2638 } | |
2639 #endif | |
2640 | |
2641 #ifdef SQLITE_ENABLE_FTS3 | |
2642 if( !db->mallocFailed && rc==SQLITE_OK ){ | |
2643 rc = sqlite3Fts3Init(db); | |
2644 } | |
2645 #endif | |
2646 | |
2647 #ifdef SQLITE_ENABLE_ICU | |
2648 if( !db->mallocFailed && rc==SQLITE_OK ){ | |
2649 rc = sqlite3IcuInit(db); | |
2650 } | |
2651 #endif | |
2652 | |
2653 #ifdef SQLITE_ENABLE_RTREE | |
2654 if( !db->mallocFailed && rc==SQLITE_OK){ | |
2655 rc = sqlite3RtreeInit(db); | |
2656 } | |
2657 #endif | |
2658 | |
2659 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking | |
2660 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking | |
2661 ** mode. Doing nothing at all also makes NORMAL the default. | |
2662 */ | |
2663 #ifdef SQLITE_DEFAULT_LOCKING_MODE | |
2664 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE; | |
2665 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt), | |
2666 SQLITE_DEFAULT_LOCKING_MODE); | |
2667 #endif | |
2668 | |
2669 if( rc ) sqlite3Error(db, rc); | |
2670 | |
2671 /* Enable the lookaside-malloc subsystem */ | |
2672 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside, | |
2673 sqlite3GlobalConfig.nLookaside); | |
2674 | |
2675 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT); | |
2676 | |
2677 opendb_out: | |
2678 sqlite3_free(zOpen); | |
2679 if( db ){ | |
2680 assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0
); | |
2681 sqlite3_mutex_leave(db->mutex); | |
2682 } | |
2683 rc = sqlite3_errcode(db); | |
2684 assert( db!=0 || rc==SQLITE_NOMEM ); | |
2685 if( rc==SQLITE_NOMEM ){ | |
2686 sqlite3_close(db); | |
2687 db = 0; | |
2688 }else if( rc!=SQLITE_OK ){ | |
2689 db->magic = SQLITE_MAGIC_SICK; | |
2690 } | |
2691 *ppDb = db; | |
2692 #ifdef SQLITE_ENABLE_SQLLOG | |
2693 if( sqlite3GlobalConfig.xSqllog ){ | |
2694 /* Opening a db handle. Fourth parameter is passed 0. */ | |
2695 void *pArg = sqlite3GlobalConfig.pSqllogArg; | |
2696 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0); | |
2697 } | |
2698 #endif | |
2699 return sqlite3ApiExit(0, rc); | |
2700 } | |
2701 | |
2702 /* | |
2703 ** Open a new database handle. | |
2704 */ | |
2705 int sqlite3_open( | |
2706 const char *zFilename, | |
2707 sqlite3 **ppDb | |
2708 ){ | |
2709 return openDatabase(zFilename, ppDb, | |
2710 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); | |
2711 } | |
2712 int sqlite3_open_v2( | |
2713 const char *filename, /* Database filename (UTF-8) */ | |
2714 sqlite3 **ppDb, /* OUT: SQLite db handle */ | |
2715 int flags, /* Flags */ | |
2716 const char *zVfs /* Name of VFS module to use */ | |
2717 ){ | |
2718 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs); | |
2719 } | |
2720 | |
2721 #ifndef SQLITE_OMIT_UTF16 | |
2722 /* | |
2723 ** Open a new database handle. | |
2724 */ | |
2725 int sqlite3_open16( | |
2726 const void *zFilename, | |
2727 sqlite3 **ppDb | |
2728 ){ | |
2729 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ | |
2730 sqlite3_value *pVal; | |
2731 int rc; | |
2732 | |
2733 assert( zFilename ); | |
2734 assert( ppDb ); | |
2735 *ppDb = 0; | |
2736 #ifndef SQLITE_OMIT_AUTOINIT | |
2737 rc = sqlite3_initialize(); | |
2738 if( rc ) return rc; | |
2739 #endif | |
2740 pVal = sqlite3ValueNew(0); | |
2741 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); | |
2742 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8); | |
2743 if( zFilename8 ){ | |
2744 rc = openDatabase(zFilename8, ppDb, | |
2745 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); | |
2746 assert( *ppDb || rc==SQLITE_NOMEM ); | |
2747 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){ | |
2748 ENC(*ppDb) = SQLITE_UTF16NATIVE; | |
2749 } | |
2750 }else{ | |
2751 rc = SQLITE_NOMEM; | |
2752 } | |
2753 sqlite3ValueFree(pVal); | |
2754 | |
2755 return sqlite3ApiExit(0, rc); | |
2756 } | |
2757 #endif /* SQLITE_OMIT_UTF16 */ | |
2758 | |
2759 /* | |
2760 ** Register a new collation sequence with the database handle db. | |
2761 */ | |
2762 int sqlite3_create_collation( | |
2763 sqlite3* db, | |
2764 const char *zName, | |
2765 int enc, | |
2766 void* pCtx, | |
2767 int(*xCompare)(void*,int,const void*,int,const void*) | |
2768 ){ | |
2769 int rc; | |
2770 sqlite3_mutex_enter(db->mutex); | |
2771 assert( !db->mallocFailed ); | |
2772 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0); | |
2773 rc = sqlite3ApiExit(db, rc); | |
2774 sqlite3_mutex_leave(db->mutex); | |
2775 return rc; | |
2776 } | |
2777 | |
2778 /* | |
2779 ** Register a new collation sequence with the database handle db. | |
2780 */ | |
2781 int sqlite3_create_collation_v2( | |
2782 sqlite3* db, | |
2783 const char *zName, | |
2784 int enc, | |
2785 void* pCtx, | |
2786 int(*xCompare)(void*,int,const void*,int,const void*), | |
2787 void(*xDel)(void*) | |
2788 ){ | |
2789 int rc; | |
2790 sqlite3_mutex_enter(db->mutex); | |
2791 assert( !db->mallocFailed ); | |
2792 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel); | |
2793 rc = sqlite3ApiExit(db, rc); | |
2794 sqlite3_mutex_leave(db->mutex); | |
2795 return rc; | |
2796 } | |
2797 | |
2798 #ifndef SQLITE_OMIT_UTF16 | |
2799 /* | |
2800 ** Register a new collation sequence with the database handle db. | |
2801 */ | |
2802 int sqlite3_create_collation16( | |
2803 sqlite3* db, | |
2804 const void *zName, | |
2805 int enc, | |
2806 void* pCtx, | |
2807 int(*xCompare)(void*,int,const void*,int,const void*) | |
2808 ){ | |
2809 int rc = SQLITE_OK; | |
2810 char *zName8; | |
2811 sqlite3_mutex_enter(db->mutex); | |
2812 assert( !db->mallocFailed ); | |
2813 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE); | |
2814 if( zName8 ){ | |
2815 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0); | |
2816 sqlite3DbFree(db, zName8); | |
2817 } | |
2818 rc = sqlite3ApiExit(db, rc); | |
2819 sqlite3_mutex_leave(db->mutex); | |
2820 return rc; | |
2821 } | |
2822 #endif /* SQLITE_OMIT_UTF16 */ | |
2823 | |
2824 /* | |
2825 ** Register a collation sequence factory callback with the database handle | |
2826 ** db. Replace any previously installed collation sequence factory. | |
2827 */ | |
2828 int sqlite3_collation_needed( | |
2829 sqlite3 *db, | |
2830 void *pCollNeededArg, | |
2831 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*) | |
2832 ){ | |
2833 sqlite3_mutex_enter(db->mutex); | |
2834 db->xCollNeeded = xCollNeeded; | |
2835 db->xCollNeeded16 = 0; | |
2836 db->pCollNeededArg = pCollNeededArg; | |
2837 sqlite3_mutex_leave(db->mutex); | |
2838 return SQLITE_OK; | |
2839 } | |
2840 | |
2841 #ifndef SQLITE_OMIT_UTF16 | |
2842 /* | |
2843 ** Register a collation sequence factory callback with the database handle | |
2844 ** db. Replace any previously installed collation sequence factory. | |
2845 */ | |
2846 int sqlite3_collation_needed16( | |
2847 sqlite3 *db, | |
2848 void *pCollNeededArg, | |
2849 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) | |
2850 ){ | |
2851 sqlite3_mutex_enter(db->mutex); | |
2852 db->xCollNeeded = 0; | |
2853 db->xCollNeeded16 = xCollNeeded16; | |
2854 db->pCollNeededArg = pCollNeededArg; | |
2855 sqlite3_mutex_leave(db->mutex); | |
2856 return SQLITE_OK; | |
2857 } | |
2858 #endif /* SQLITE_OMIT_UTF16 */ | |
2859 | |
2860 #ifndef SQLITE_OMIT_DEPRECATED | |
2861 /* | |
2862 ** This function is now an anachronism. It used to be used to recover from a | |
2863 ** malloc() failure, but SQLite now does this automatically. | |
2864 */ | |
2865 int sqlite3_global_recover(void){ | |
2866 return SQLITE_OK; | |
2867 } | |
2868 #endif | |
2869 | |
2870 /* | |
2871 ** Test to see whether or not the database connection is in autocommit | |
2872 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on | |
2873 ** by default. Autocommit is disabled by a BEGIN statement and reenabled | |
2874 ** by the next COMMIT or ROLLBACK. | |
2875 */ | |
2876 int sqlite3_get_autocommit(sqlite3 *db){ | |
2877 return db->autoCommit; | |
2878 } | |
2879 | |
2880 /* | |
2881 ** The following routines are substitutes for constants SQLITE_CORRUPT, | |
2882 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error | |
2883 ** constants. They serve two purposes: | |
2884 ** | |
2885 ** 1. Serve as a convenient place to set a breakpoint in a debugger | |
2886 ** to detect when version error conditions occurs. | |
2887 ** | |
2888 ** 2. Invoke sqlite3_log() to provide the source code location where | |
2889 ** a low-level error is first detected. | |
2890 */ | |
2891 int sqlite3CorruptError(int lineno){ | |
2892 testcase( sqlite3GlobalConfig.xLog!=0 ); | |
2893 sqlite3_log(SQLITE_CORRUPT, | |
2894 "database corruption at line %d of [%.10s]", | |
2895 lineno, 20+sqlite3_sourceid()); | |
2896 return SQLITE_CORRUPT; | |
2897 } | |
2898 int sqlite3MisuseError(int lineno){ | |
2899 testcase( sqlite3GlobalConfig.xLog!=0 ); | |
2900 sqlite3_log(SQLITE_MISUSE, | |
2901 "misuse at line %d of [%.10s]", | |
2902 lineno, 20+sqlite3_sourceid()); | |
2903 return SQLITE_MISUSE; | |
2904 } | |
2905 int sqlite3CantopenError(int lineno){ | |
2906 testcase( sqlite3GlobalConfig.xLog!=0 ); | |
2907 sqlite3_log(SQLITE_CANTOPEN, | |
2908 "cannot open file at line %d of [%.10s]", | |
2909 lineno, 20+sqlite3_sourceid()); | |
2910 return SQLITE_CANTOPEN; | |
2911 } | |
2912 | |
2913 | |
2914 #ifndef SQLITE_OMIT_DEPRECATED | |
2915 /* | |
2916 ** This is a convenience routine that makes sure that all thread-specific | |
2917 ** data for this thread has been deallocated. | |
2918 ** | |
2919 ** SQLite no longer uses thread-specific data so this routine is now a | |
2920 ** no-op. It is retained for historical compatibility. | |
2921 */ | |
2922 void sqlite3_thread_cleanup(void){ | |
2923 } | |
2924 #endif | |
2925 | |
2926 /* | |
2927 ** Return meta information about a specific column of a database table. | |
2928 ** See comment in sqlite3.h (sqlite.h.in) for details. | |
2929 */ | |
2930 #ifdef SQLITE_ENABLE_COLUMN_METADATA | |
2931 int sqlite3_table_column_metadata( | |
2932 sqlite3 *db, /* Connection handle */ | |
2933 const char *zDbName, /* Database name or NULL */ | |
2934 const char *zTableName, /* Table name */ | |
2935 const char *zColumnName, /* Column name */ | |
2936 char const **pzDataType, /* OUTPUT: Declared data type */ | |
2937 char const **pzCollSeq, /* OUTPUT: Collation sequence name */ | |
2938 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ | |
2939 int *pPrimaryKey, /* OUTPUT: True if column part of PK */ | |
2940 int *pAutoinc /* OUTPUT: True if column is auto-increment */ | |
2941 ){ | |
2942 int rc; | |
2943 char *zErrMsg = 0; | |
2944 Table *pTab = 0; | |
2945 Column *pCol = 0; | |
2946 int iCol; | |
2947 | |
2948 char const *zDataType = 0; | |
2949 char const *zCollSeq = 0; | |
2950 int notnull = 0; | |
2951 int primarykey = 0; | |
2952 int autoinc = 0; | |
2953 | |
2954 /* Ensure the database schema has been loaded */ | |
2955 sqlite3_mutex_enter(db->mutex); | |
2956 sqlite3BtreeEnterAll(db); | |
2957 rc = sqlite3Init(db, &zErrMsg); | |
2958 if( SQLITE_OK!=rc ){ | |
2959 goto error_out; | |
2960 } | |
2961 | |
2962 /* Locate the table in question */ | |
2963 pTab = sqlite3FindTable(db, zTableName, zDbName); | |
2964 if( !pTab || pTab->pSelect ){ | |
2965 pTab = 0; | |
2966 goto error_out; | |
2967 } | |
2968 | |
2969 /* Find the column for which info is requested */ | |
2970 if( sqlite3IsRowid(zColumnName) ){ | |
2971 iCol = pTab->iPKey; | |
2972 if( iCol>=0 ){ | |
2973 pCol = &pTab->aCol[iCol]; | |
2974 } | |
2975 }else{ | |
2976 for(iCol=0; iCol<pTab->nCol; iCol++){ | |
2977 pCol = &pTab->aCol[iCol]; | |
2978 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){ | |
2979 break; | |
2980 } | |
2981 } | |
2982 if( iCol==pTab->nCol ){ | |
2983 pTab = 0; | |
2984 goto error_out; | |
2985 } | |
2986 } | |
2987 | |
2988 /* The following block stores the meta information that will be returned | |
2989 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey | |
2990 ** and autoinc. At this point there are two possibilities: | |
2991 ** | |
2992 ** 1. The specified column name was rowid", "oid" or "_rowid_" | |
2993 ** and there is no explicitly declared IPK column. | |
2994 ** | |
2995 ** 2. The table is not a view and the column name identified an | |
2996 ** explicitly declared column. Copy meta information from *pCol. | |
2997 */ | |
2998 if( pCol ){ | |
2999 zDataType = pCol->zType; | |
3000 zCollSeq = pCol->zColl; | |
3001 notnull = pCol->notNull!=0; | |
3002 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0; | |
3003 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0; | |
3004 }else{ | |
3005 zDataType = "INTEGER"; | |
3006 primarykey = 1; | |
3007 } | |
3008 if( !zCollSeq ){ | |
3009 zCollSeq = "BINARY"; | |
3010 } | |
3011 | |
3012 error_out: | |
3013 sqlite3BtreeLeaveAll(db); | |
3014 | |
3015 /* Whether the function call succeeded or failed, set the output parameters | |
3016 ** to whatever their local counterparts contain. If an error did occur, | |
3017 ** this has the effect of zeroing all output parameters. | |
3018 */ | |
3019 if( pzDataType ) *pzDataType = zDataType; | |
3020 if( pzCollSeq ) *pzCollSeq = zCollSeq; | |
3021 if( pNotNull ) *pNotNull = notnull; | |
3022 if( pPrimaryKey ) *pPrimaryKey = primarykey; | |
3023 if( pAutoinc ) *pAutoinc = autoinc; | |
3024 | |
3025 if( SQLITE_OK==rc && !pTab ){ | |
3026 sqlite3DbFree(db, zErrMsg); | |
3027 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, | |
3028 zColumnName); | |
3029 rc = SQLITE_ERROR; | |
3030 } | |
3031 sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg); | |
3032 sqlite3DbFree(db, zErrMsg); | |
3033 rc = sqlite3ApiExit(db, rc); | |
3034 sqlite3_mutex_leave(db->mutex); | |
3035 return rc; | |
3036 } | |
3037 #endif | |
3038 | |
3039 /* | |
3040 ** Sleep for a little while. Return the amount of time slept. | |
3041 */ | |
3042 int sqlite3_sleep(int ms){ | |
3043 sqlite3_vfs *pVfs; | |
3044 int rc; | |
3045 pVfs = sqlite3_vfs_find(0); | |
3046 if( pVfs==0 ) return 0; | |
3047 | |
3048 /* This function works in milliseconds, but the underlying OsSleep() | |
3049 ** API uses microseconds. Hence the 1000's. | |
3050 */ | |
3051 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000); | |
3052 return rc; | |
3053 } | |
3054 | |
3055 /* | |
3056 ** Enable or disable the extended result codes. | |
3057 */ | |
3058 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){ | |
3059 sqlite3_mutex_enter(db->mutex); | |
3060 db->errMask = onoff ? 0xffffffff : 0xff; | |
3061 sqlite3_mutex_leave(db->mutex); | |
3062 return SQLITE_OK; | |
3063 } | |
3064 | |
3065 /* | |
3066 ** Invoke the xFileControl method on a particular database. | |
3067 */ | |
3068 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){ | |
3069 int rc = SQLITE_ERROR; | |
3070 Btree *pBtree; | |
3071 | |
3072 sqlite3_mutex_enter(db->mutex); | |
3073 pBtree = sqlite3DbNameToBtree(db, zDbName); | |
3074 if( pBtree ){ | |
3075 Pager *pPager; | |
3076 sqlite3_file *fd; | |
3077 sqlite3BtreeEnter(pBtree); | |
3078 pPager = sqlite3BtreePager(pBtree); | |
3079 assert( pPager!=0 ); | |
3080 fd = sqlite3PagerFile(pPager); | |
3081 assert( fd!=0 ); | |
3082 if( op==SQLITE_FCNTL_FILE_POINTER ){ | |
3083 *(sqlite3_file**)pArg = fd; | |
3084 rc = SQLITE_OK; | |
3085 }else if( fd->pMethods ){ | |
3086 rc = sqlite3OsFileControl(fd, op, pArg); | |
3087 }else{ | |
3088 rc = SQLITE_NOTFOUND; | |
3089 } | |
3090 sqlite3BtreeLeave(pBtree); | |
3091 } | |
3092 sqlite3_mutex_leave(db->mutex); | |
3093 return rc; | |
3094 } | |
3095 | |
3096 /* | |
3097 ** Interface to the testing logic. | |
3098 */ | |
3099 int sqlite3_test_control(int op, ...){ | |
3100 int rc = 0; | |
3101 #ifndef SQLITE_OMIT_BUILTIN_TEST | |
3102 va_list ap; | |
3103 va_start(ap, op); | |
3104 switch( op ){ | |
3105 | |
3106 /* | |
3107 ** Save the current state of the PRNG. | |
3108 */ | |
3109 case SQLITE_TESTCTRL_PRNG_SAVE: { | |
3110 sqlite3PrngSaveState(); | |
3111 break; | |
3112 } | |
3113 | |
3114 /* | |
3115 ** Restore the state of the PRNG to the last state saved using | |
3116 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then | |
3117 ** this verb acts like PRNG_RESET. | |
3118 */ | |
3119 case SQLITE_TESTCTRL_PRNG_RESTORE: { | |
3120 sqlite3PrngRestoreState(); | |
3121 break; | |
3122 } | |
3123 | |
3124 /* | |
3125 ** Reset the PRNG back to its uninitialized state. The next call | |
3126 ** to sqlite3_randomness() will reseed the PRNG using a single call | |
3127 ** to the xRandomness method of the default VFS. | |
3128 */ | |
3129 case SQLITE_TESTCTRL_PRNG_RESET: { | |
3130 sqlite3_randomness(0,0); | |
3131 break; | |
3132 } | |
3133 | |
3134 /* | |
3135 ** sqlite3_test_control(BITVEC_TEST, size, program) | |
3136 ** | |
3137 ** Run a test against a Bitvec object of size. The program argument | |
3138 ** is an array of integers that defines the test. Return -1 on a | |
3139 ** memory allocation error, 0 on success, or non-zero for an error. | |
3140 ** See the sqlite3BitvecBuiltinTest() for additional information. | |
3141 */ | |
3142 case SQLITE_TESTCTRL_BITVEC_TEST: { | |
3143 int sz = va_arg(ap, int); | |
3144 int *aProg = va_arg(ap, int*); | |
3145 rc = sqlite3BitvecBuiltinTest(sz, aProg); | |
3146 break; | |
3147 } | |
3148 | |
3149 /* | |
3150 ** sqlite3_test_control(FAULT_INSTALL, xCallback) | |
3151 ** | |
3152 ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called, | |
3153 ** if xCallback is not NULL. | |
3154 ** | |
3155 ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0) | |
3156 ** is called immediately after installing the new callback and the return | |
3157 ** value from sqlite3FaultSim(0) becomes the return from | |
3158 ** sqlite3_test_control(). | |
3159 */ | |
3160 case SQLITE_TESTCTRL_FAULT_INSTALL: { | |
3161 /* MSVC is picky about pulling func ptrs from va lists. | |
3162 ** http://support.microsoft.com/kb/47961 | |
3163 ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int)); | |
3164 */ | |
3165 typedef int(*TESTCALLBACKFUNC_t)(int); | |
3166 sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t); | |
3167 rc = sqlite3FaultSim(0); | |
3168 break; | |
3169 } | |
3170 | |
3171 /* | |
3172 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) | |
3173 ** | |
3174 ** Register hooks to call to indicate which malloc() failures | |
3175 ** are benign. | |
3176 */ | |
3177 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: { | |
3178 typedef void (*void_function)(void); | |
3179 void_function xBenignBegin; | |
3180 void_function xBenignEnd; | |
3181 xBenignBegin = va_arg(ap, void_function); | |
3182 xBenignEnd = va_arg(ap, void_function); | |
3183 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd); | |
3184 break; | |
3185 } | |
3186 | |
3187 /* | |
3188 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) | |
3189 ** | |
3190 ** Set the PENDING byte to the value in the argument, if X>0. | |
3191 ** Make no changes if X==0. Return the value of the pending byte | |
3192 ** as it existing before this routine was called. | |
3193 ** | |
3194 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in | |
3195 ** an incompatible database file format. Changing the PENDING byte | |
3196 ** while any database connection is open results in undefined and | |
3197 ** deleterious behavior. | |
3198 */ | |
3199 case SQLITE_TESTCTRL_PENDING_BYTE: { | |
3200 rc = PENDING_BYTE; | |
3201 #ifndef SQLITE_OMIT_WSD | |
3202 { | |
3203 unsigned int newVal = va_arg(ap, unsigned int); | |
3204 if( newVal ) sqlite3PendingByte = newVal; | |
3205 } | |
3206 #endif | |
3207 break; | |
3208 } | |
3209 | |
3210 /* | |
3211 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) | |
3212 ** | |
3213 ** This action provides a run-time test to see whether or not | |
3214 ** assert() was enabled at compile-time. If X is true and assert() | |
3215 ** is enabled, then the return value is true. If X is true and | |
3216 ** assert() is disabled, then the return value is zero. If X is | |
3217 ** false and assert() is enabled, then the assertion fires and the | |
3218 ** process aborts. If X is false and assert() is disabled, then the | |
3219 ** return value is zero. | |
3220 */ | |
3221 case SQLITE_TESTCTRL_ASSERT: { | |
3222 volatile int x = 0; | |
3223 assert( (x = va_arg(ap,int))!=0 ); | |
3224 rc = x; | |
3225 break; | |
3226 } | |
3227 | |
3228 | |
3229 /* | |
3230 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) | |
3231 ** | |
3232 ** This action provides a run-time test to see how the ALWAYS and | |
3233 ** NEVER macros were defined at compile-time. | |
3234 ** | |
3235 ** The return value is ALWAYS(X). | |
3236 ** | |
3237 ** The recommended test is X==2. If the return value is 2, that means | |
3238 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the | |
3239 ** default setting. If the return value is 1, then ALWAYS() is either | |
3240 ** hard-coded to true or else it asserts if its argument is false. | |
3241 ** The first behavior (hard-coded to true) is the case if | |
3242 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second | |
3243 ** behavior (assert if the argument to ALWAYS() is false) is the case if | |
3244 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled. | |
3245 ** | |
3246 ** The run-time test procedure might look something like this: | |
3247 ** | |
3248 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ | |
3249 ** // ALWAYS() and NEVER() are no-op pass-through macros | |
3250 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ | |
3251 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false. | |
3252 ** }else{ | |
3253 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0. | |
3254 ** } | |
3255 */ | |
3256 case SQLITE_TESTCTRL_ALWAYS: { | |
3257 int x = va_arg(ap,int); | |
3258 rc = ALWAYS(x); | |
3259 break; | |
3260 } | |
3261 | |
3262 /* | |
3263 ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER); | |
3264 ** | |
3265 ** The integer returned reveals the byte-order of the computer on which | |
3266 ** SQLite is running: | |
3267 ** | |
3268 ** 1 big-endian, determined at run-time | |
3269 ** 10 little-endian, determined at run-time | |
3270 ** 432101 big-endian, determined at compile-time | |
3271 ** 123410 little-endian, determined at compile-time | |
3272 */ | |
3273 case SQLITE_TESTCTRL_BYTEORDER: { | |
3274 rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN; | |
3275 break; | |
3276 } | |
3277 | |
3278 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N) | |
3279 ** | |
3280 ** Set the nReserve size to N for the main database on the database | |
3281 ** connection db. | |
3282 */ | |
3283 case SQLITE_TESTCTRL_RESERVE: { | |
3284 sqlite3 *db = va_arg(ap, sqlite3*); | |
3285 int x = va_arg(ap,int); | |
3286 sqlite3_mutex_enter(db->mutex); | |
3287 sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0); | |
3288 sqlite3_mutex_leave(db->mutex); | |
3289 break; | |
3290 } | |
3291 | |
3292 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N) | |
3293 ** | |
3294 ** Enable or disable various optimizations for testing purposes. The | |
3295 ** argument N is a bitmask of optimizations to be disabled. For normal | |
3296 ** operation N should be 0. The idea is that a test program (like the | |
3297 ** SQL Logic Test or SLT test module) can run the same SQL multiple times | |
3298 ** with various optimizations disabled to verify that the same answer | |
3299 ** is obtained in every case. | |
3300 */ | |
3301 case SQLITE_TESTCTRL_OPTIMIZATIONS: { | |
3302 sqlite3 *db = va_arg(ap, sqlite3*); | |
3303 db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff); | |
3304 break; | |
3305 } | |
3306 | |
3307 #ifdef SQLITE_N_KEYWORD | |
3308 /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord) | |
3309 ** | |
3310 ** If zWord is a keyword recognized by the parser, then return the | |
3311 ** number of keywords. Or if zWord is not a keyword, return 0. | |
3312 ** | |
3313 ** This test feature is only available in the amalgamation since | |
3314 ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite | |
3315 ** is built using separate source files. | |
3316 */ | |
3317 case SQLITE_TESTCTRL_ISKEYWORD: { | |
3318 const char *zWord = va_arg(ap, const char*); | |
3319 int n = sqlite3Strlen30(zWord); | |
3320 rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0; | |
3321 break; | |
3322 } | |
3323 #endif | |
3324 | |
3325 /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree); | |
3326 ** | |
3327 ** Pass pFree into sqlite3ScratchFree(). | |
3328 ** If sz>0 then allocate a scratch buffer into pNew. | |
3329 */ | |
3330 case SQLITE_TESTCTRL_SCRATCHMALLOC: { | |
3331 void *pFree, **ppNew; | |
3332 int sz; | |
3333 sz = va_arg(ap, int); | |
3334 ppNew = va_arg(ap, void**); | |
3335 pFree = va_arg(ap, void*); | |
3336 if( sz ) *ppNew = sqlite3ScratchMalloc(sz); | |
3337 sqlite3ScratchFree(pFree); | |
3338 break; | |
3339 } | |
3340 | |
3341 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff); | |
3342 ** | |
3343 ** If parameter onoff is non-zero, configure the wrappers so that all | |
3344 ** subsequent calls to localtime() and variants fail. If onoff is zero, | |
3345 ** undo this setting. | |
3346 */ | |
3347 case SQLITE_TESTCTRL_LOCALTIME_FAULT: { | |
3348 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int); | |
3349 break; | |
3350 } | |
3351 | |
3352 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int); | |
3353 ** | |
3354 ** Set or clear a flag that indicates that the database file is always well- | |
3355 ** formed and never corrupt. This flag is clear by default, indicating that | |
3356 ** database files might have arbitrary corruption. Setting the flag during | |
3357 ** testing causes certain assert() statements in the code to be activated | |
3358 ** that demonstrat invariants on well-formed database files. | |
3359 */ | |
3360 case SQLITE_TESTCTRL_NEVER_CORRUPT: { | |
3361 sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int); | |
3362 break; | |
3363 } | |
3364 | |
3365 | |
3366 /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr); | |
3367 ** | |
3368 ** Set the VDBE coverage callback function to xCallback with context | |
3369 ** pointer ptr. | |
3370 */ | |
3371 case SQLITE_TESTCTRL_VDBE_COVERAGE: { | |
3372 #ifdef SQLITE_VDBE_COVERAGE | |
3373 typedef void (*branch_callback)(void*,int,u8,u8); | |
3374 sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback); | |
3375 sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*); | |
3376 #endif | |
3377 break; | |
3378 } | |
3379 | |
3380 /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */ | |
3381 case SQLITE_TESTCTRL_SORTER_MMAP: { | |
3382 sqlite3 *db = va_arg(ap, sqlite3*); | |
3383 db->nMaxSorterMmap = va_arg(ap, int); | |
3384 break; | |
3385 } | |
3386 | |
3387 /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT); | |
3388 ** | |
3389 ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if | |
3390 ** not. | |
3391 */ | |
3392 case SQLITE_TESTCTRL_ISINIT: { | |
3393 if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR; | |
3394 break; | |
3395 } | |
3396 } | |
3397 va_end(ap); | |
3398 #endif /* SQLITE_OMIT_BUILTIN_TEST */ | |
3399 return rc; | |
3400 } | |
3401 | |
3402 /* | |
3403 ** This is a utility routine, useful to VFS implementations, that checks | |
3404 ** to see if a database file was a URI that contained a specific query | |
3405 ** parameter, and if so obtains the value of the query parameter. | |
3406 ** | |
3407 ** The zFilename argument is the filename pointer passed into the xOpen() | |
3408 ** method of a VFS implementation. The zParam argument is the name of the | |
3409 ** query parameter we seek. This routine returns the value of the zParam | |
3410 ** parameter if it exists. If the parameter does not exist, this routine | |
3411 ** returns a NULL pointer. | |
3412 */ | |
3413 const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){ | |
3414 if( zFilename==0 ) return 0; | |
3415 zFilename += sqlite3Strlen30(zFilename) + 1; | |
3416 while( zFilename[0] ){ | |
3417 int x = strcmp(zFilename, zParam); | |
3418 zFilename += sqlite3Strlen30(zFilename) + 1; | |
3419 if( x==0 ) return zFilename; | |
3420 zFilename += sqlite3Strlen30(zFilename) + 1; | |
3421 } | |
3422 return 0; | |
3423 } | |
3424 | |
3425 /* | |
3426 ** Return a boolean value for a query parameter. | |
3427 */ | |
3428 int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){ | |
3429 const char *z = sqlite3_uri_parameter(zFilename, zParam); | |
3430 bDflt = bDflt!=0; | |
3431 return z ? sqlite3GetBoolean(z, bDflt) : bDflt; | |
3432 } | |
3433 | |
3434 /* | |
3435 ** Return a 64-bit integer value for a query parameter. | |
3436 */ | |
3437 sqlite3_int64 sqlite3_uri_int64( | |
3438 const char *zFilename, /* Filename as passed to xOpen */ | |
3439 const char *zParam, /* URI parameter sought */ | |
3440 sqlite3_int64 bDflt /* return if parameter is missing */ | |
3441 ){ | |
3442 const char *z = sqlite3_uri_parameter(zFilename, zParam); | |
3443 sqlite3_int64 v; | |
3444 if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){ | |
3445 bDflt = v; | |
3446 } | |
3447 return bDflt; | |
3448 } | |
3449 | |
3450 /* | |
3451 ** Return the Btree pointer identified by zDbName. Return NULL if not found. | |
3452 */ | |
3453 Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){ | |
3454 int i; | |
3455 for(i=0; i<db->nDb; i++){ | |
3456 if( db->aDb[i].pBt | |
3457 && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0) | |
3458 ){ | |
3459 return db->aDb[i].pBt; | |
3460 } | |
3461 } | |
3462 return 0; | |
3463 } | |
3464 | |
3465 /* | |
3466 ** Return the filename of the database associated with a database | |
3467 ** connection. | |
3468 */ | |
3469 const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){ | |
3470 Btree *pBt = sqlite3DbNameToBtree(db, zDbName); | |
3471 return pBt ? sqlite3BtreeGetFilename(pBt) : 0; | |
3472 } | |
3473 | |
3474 /* | |
3475 ** Return 1 if database is read-only or 0 if read/write. Return -1 if | |
3476 ** no such database exists. | |
3477 */ | |
3478 int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){ | |
3479 Btree *pBt = sqlite3DbNameToBtree(db, zDbName); | |
3480 return pBt ? sqlite3BtreeIsReadonly(pBt) : -1; | |
3481 } | |
OLD | NEW |