4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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.
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.
19 #include "sqliteInt.h"
23 ** The version of the library
25 const char sqlite3_version[] = SQLITE_VERSION;
26 const char *sqlite3_libversion(void){ return sqlite3_version; }
27 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
28 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
31 ** If the following function pointer is not NULL and if
32 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
33 ** I/O active are written using this function. These messages
34 ** are intended for debugging activity only.
36 void (*sqlite3_io_trace)(const char*, ...) = 0;
39 ** If the following global variable points to a string which is the
40 ** name of a directory, then that directory will be used to store
43 ** See also the "PRAGMA temp_store_directory" SQL command.
45 char *sqlite3_temp_directory = 0;
49 ** This is the default collating function named "BINARY" which is always
52 static int binCollFunc(
54 int nKey1, const void *pKey1,
55 int nKey2, const void *pKey2
58 n = nKey1<nKey2 ? nKey1 : nKey2;
59 rc = memcmp(pKey1, pKey2, n);
67 ** Another built-in collating sequence: NOCASE.
69 ** This collating sequence is intended to be used for "case independant
70 ** comparison". SQLite's knowledge of upper and lower case equivalents
71 ** extends only to the 26 characters used in the English language.
73 ** At the moment there is only a UTF-8 implementation.
75 static int nocaseCollatingFunc(
77 int nKey1, const void *pKey1,
78 int nKey2, const void *pKey2
80 int r = sqlite3StrNICmp(
81 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
89 ** Return the ROWID of the most recent insert
91 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
96 ** Return the number of changes in the most recent call to sqlite3_exec().
98 int sqlite3_changes(sqlite3 *db){
103 ** Return the number of changes since the database handle was opened.
105 int sqlite3_total_changes(sqlite3 *db){
106 return db->nTotalChange;
110 ** Close an existing SQLite database
112 int sqlite3_close(sqlite3 *db){
119 if( sqlite3SafetyCheck(db) ){
120 return SQLITE_MISUSE;
122 sqlite3_mutex_enter(db->mutex);
126 extern void sqlite3SseCleanup(sqlite3*);
127 sqlite3SseCleanup(db);
131 sqlite3ResetInternalSchema(db, 0);
133 /* If a transaction is open, the ResetInternalSchema() call above
134 ** will not have called the xDisconnect() method on any virtual
135 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
136 ** call will do so. We need to do this before the check for active
137 ** SQL statements below, as the v-table implementation may be storing
138 ** some prepared statements internally.
140 sqlite3VtabRollback(db);
142 /* If there are any outstanding VMs, return SQLITE_BUSY. */
144 sqlite3Error(db, SQLITE_BUSY,
145 "Unable to close due to unfinalised statements");
146 sqlite3_mutex_leave(db->mutex);
149 assert( !sqlite3SafetyCheck(db) );
151 /* FIX ME: db->magic may be set to SQLITE_MAGIC_CLOSED if the database
152 ** cannot be opened for some reason. So this routine needs to run in
153 ** that case. But maybe there should be an extra magic value for the
154 ** "failed to open" state.
156 ** TODO: Coverage tests do not test the case where this condition is
157 ** true. It's hard to see how to cause it without messing with threads.
159 if( db->magic!=SQLITE_MAGIC_CLOSED && sqlite3SafetyOn(db) ){
160 /* printf("DID NOT CLOSE\n"); fflush(stdout); */
161 sqlite3_mutex_leave(db->mutex);
165 for(j=0; j<db->nDb; j++){
166 struct Db *pDb = &db->aDb[j];
168 sqlite3BtreeClose(pDb->pBt);
175 sqlite3ResetInternalSchema(db, 0);
176 assert( db->nDb<=2 );
177 assert( db->aDb==db->aDbStatic );
178 for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
179 FuncDef *pFunc, *pNext;
180 for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
181 pNext = pFunc->pNext;
186 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
187 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
188 /* Invoke any destructors registered for collation sequence user data. */
191 pColl[j].xDel(pColl[j].pUser);
196 sqlite3HashClear(&db->aCollSeq);
197 #ifndef SQLITE_OMIT_VIRTUALTABLE
198 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
199 Module *pMod = (Module *)sqliteHashData(i);
200 if( pMod->xDestroy ){
201 pMod->xDestroy(pMod->pAux);
205 sqlite3HashClear(&db->aModule);
208 sqlite3HashClear(&db->aFunc);
209 sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
211 sqlite3ValueFree(db->pErr);
213 sqlite3CloseExtensions(db);
215 db->magic = SQLITE_MAGIC_ERROR;
217 /* The temp-database schema is allocated differently from the other schema
218 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
219 ** So it needs to be freed here. Todo: Why not roll the temp schema into
220 ** the same sqliteMalloc() as the one that allocates the database
223 sqlite3_free(db->aDb[1].pSchema);
224 sqlite3_mutex_leave(db->mutex);
225 sqlite3_mutex_free(db->mutex);
231 ** Rollback all database files.
233 void sqlite3RollbackAll(sqlite3 *db){
236 assert( sqlite3_mutex_held(db->mutex) );
237 sqlite3MallocEnterBenignBlock(1); /* Enter benign region */
238 for(i=0; i<db->nDb; i++){
239 if( db->aDb[i].pBt ){
240 if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
243 sqlite3BtreeRollback(db->aDb[i].pBt);
244 db->aDb[i].inTrans = 0;
247 sqlite3VtabRollback(db);
248 sqlite3MallocLeaveBenignBlock(); /* Leave benign region */
250 if( db->flags&SQLITE_InternChanges ){
251 sqlite3ExpirePreparedStatements(db);
252 sqlite3ResetInternalSchema(db, 0);
255 /* If one has been configured, invoke the rollback-hook callback */
256 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
257 db->xRollbackCallback(db->pRollbackArg);
262 ** Return a static string that describes the kind of error specified in the
265 const char *sqlite3ErrStr(int rc){
270 case SQLITE_OK: z = "not an error"; break;
271 case SQLITE_ERROR: z = "SQL logic error or missing database"; break;
272 case SQLITE_PERM: z = "access permission denied"; break;
273 case SQLITE_ABORT: z = "callback requested query abort"; break;
274 case SQLITE_BUSY: z = "database is locked"; break;
275 case SQLITE_LOCKED: z = "database table is locked"; break;
276 case SQLITE_NOMEM: z = "out of memory"; break;
277 case SQLITE_READONLY: z = "attempt to write a readonly database"; break;
278 case SQLITE_INTERRUPT: z = "interrupted"; break;
279 case SQLITE_IOERR: z = "disk I/O error"; break;
280 case SQLITE_CORRUPT: z = "database disk image is malformed"; break;
281 case SQLITE_FULL: z = "database or disk is full"; break;
282 case SQLITE_CANTOPEN: z = "unable to open database file"; break;
283 case SQLITE_EMPTY: z = "table contains no data"; break;
284 case SQLITE_SCHEMA: z = "database schema has changed"; break;
285 case SQLITE_TOOBIG: z = "String or BLOB exceeded size limit"; break;
286 case SQLITE_CONSTRAINT: z = "constraint failed"; break;
287 case SQLITE_MISMATCH: z = "datatype mismatch"; break;
288 case SQLITE_MISUSE: z = "library routine called out of sequence";break;
289 case SQLITE_NOLFS: z = "kernel lacks large file support"; break;
290 case SQLITE_AUTH: z = "authorization denied"; break;
291 case SQLITE_FORMAT: z = "auxiliary database format error"; break;
292 case SQLITE_RANGE: z = "bind or column index out of range"; break;
293 case SQLITE_NOTADB: z = "file is encrypted or is not a database";break;
294 default: z = "unknown error"; break;
300 ** This routine implements a busy callback that sleeps and tries
301 ** again until a timeout value is reached. The timeout value is
302 ** an integer number of milliseconds passed in as the first
305 static int sqliteDefaultBusyCallback(
306 void *ptr, /* Database connection */
307 int count /* Number of times table has been busy */
309 #if OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
310 static const u8 delays[] =
311 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
312 static const u8 totals[] =
313 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
314 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
315 sqlite3 *db = (sqlite3 *)ptr;
316 int timeout = db->busyTimeout;
320 if( count < NDELAY ){
321 delay = delays[count];
322 prior = totals[count];
324 delay = delays[NDELAY-1];
325 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
327 if( prior + delay > timeout ){
328 delay = timeout - prior;
329 if( delay<=0 ) return 0;
331 sqlite3OsSleep(db->pVfs, delay*1000);
334 sqlite3 *db = (sqlite3 *)ptr;
335 int timeout = ((sqlite3 *)ptr)->busyTimeout;
336 if( (count+1)*1000 > timeout ){
339 sqlite3OsSleep(db->pVfs, 1000000);
345 ** Invoke the given busy handler.
347 ** This routine is called when an operation failed with a lock.
348 ** If this routine returns non-zero, the lock is retried. If it
349 ** returns 0, the operation aborts with an SQLITE_BUSY error.
351 int sqlite3InvokeBusyHandler(BusyHandler *p){
353 if( p==0 || p->xFunc==0 || p->nBusy<0 ) return 0;
354 rc = p->xFunc(p->pArg, p->nBusy);
364 ** This routine sets the busy callback for an Sqlite database to the
365 ** given callback function with the given argument.
367 int sqlite3_busy_handler(
369 int (*xBusy)(void*,int),
372 if( sqlite3SafetyCheck(db) ){
373 return SQLITE_MISUSE;
375 sqlite3_mutex_enter(db->mutex);
376 db->busyHandler.xFunc = xBusy;
377 db->busyHandler.pArg = pArg;
378 db->busyHandler.nBusy = 0;
379 sqlite3_mutex_leave(db->mutex);
383 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
385 ** This routine sets the progress callback for an Sqlite database to the
386 ** given callback function with the given argument. The progress callback will
387 ** be invoked every nOps opcodes.
389 void sqlite3_progress_handler(
392 int (*xProgress)(void*),
395 if( !sqlite3SafetyCheck(db) ){
396 sqlite3_mutex_enter(db->mutex);
398 db->xProgress = xProgress;
399 db->nProgressOps = nOps;
400 db->pProgressArg = pArg;
403 db->nProgressOps = 0;
404 db->pProgressArg = 0;
406 sqlite3_mutex_leave(db->mutex);
413 ** This routine installs a default busy handler that waits for the
414 ** specified number of milliseconds before returning 0.
416 int sqlite3_busy_timeout(sqlite3 *db, int ms){
417 if( sqlite3SafetyCheck(db) ){
418 return SQLITE_MISUSE;
421 db->busyTimeout = ms;
422 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
424 sqlite3_busy_handler(db, 0, 0);
430 ** Cause any pending operation to stop at its earliest opportunity.
432 void sqlite3_interrupt(sqlite3 *db){
433 if( db && (db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_BUSY) ){
434 db->u1.isInterrupted = 1;
440 ** This function is exactly the same as sqlite3_create_function(), except
441 ** that it is designed to be called by internal code. The difference is
442 ** that if a malloc() fails in sqlite3_create_function(), an error code
443 ** is returned and the mallocFailed flag cleared.
445 int sqlite3CreateFunc(
447 const char *zFunctionName,
451 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
452 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
453 void (*xFinal)(sqlite3_context*)
458 assert( sqlite3_mutex_held(db->mutex) );
459 if( sqlite3SafetyCheck(db) ){
460 return SQLITE_MISUSE;
462 if( zFunctionName==0 ||
463 (xFunc && (xFinal || xStep)) ||
464 (!xFunc && (xFinal && !xStep)) ||
465 (!xFunc && (!xFinal && xStep)) ||
466 (nArg<-1 || nArg>127) ||
467 (255<(nName = strlen(zFunctionName))) ){
468 sqlite3Error(db, SQLITE_ERROR, "bad parameters");
472 #ifndef SQLITE_OMIT_UTF16
473 /* If SQLITE_UTF16 is specified as the encoding type, transform this
474 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
475 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
477 ** If SQLITE_ANY is specified, add three versions of the function
478 ** to the hash table.
480 if( enc==SQLITE_UTF16 ){
481 enc = SQLITE_UTF16NATIVE;
482 }else if( enc==SQLITE_ANY ){
484 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
485 pUserData, xFunc, xStep, xFinal);
487 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
488 pUserData, xFunc, xStep, xFinal);
493 enc = SQLITE_UTF16BE;
499 /* Check if an existing function is being overridden or deleted. If so,
500 ** and there are active VMs, then return SQLITE_BUSY. If a function
501 ** is being overridden/deleted but there are no active VMs, allow the
502 ** operation to continue but invalidate all precompiled statements.
504 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
505 if( p && p->iPrefEnc==enc && p->nArg==nArg ){
506 if( db->activeVdbeCnt ){
507 sqlite3Error(db, SQLITE_BUSY,
508 "Unable to delete/modify user-function due to active statements");
509 assert( !db->mallocFailed );
512 sqlite3ExpirePreparedStatements(db);
516 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
517 assert(p || db->mallocFailed);
524 p->xFinalize = xFinal;
525 p->pUserData = pUserData;
531 ** Create new user functions.
533 int sqlite3_create_function(
535 const char *zFunctionName,
539 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
540 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
541 void (*xFinal)(sqlite3_context*)
544 sqlite3_mutex_enter(db->mutex);
545 assert( !db->mallocFailed );
546 rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
547 rc = sqlite3ApiExit(db, rc);
548 sqlite3_mutex_leave(db->mutex);
552 #ifndef SQLITE_OMIT_UTF16
553 int sqlite3_create_function16(
555 const void *zFunctionName,
559 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
560 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
561 void (*xFinal)(sqlite3_context*)
565 sqlite3_mutex_enter(db->mutex);
566 assert( !db->mallocFailed );
567 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
568 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
569 sqlite3_free(zFunc8);
570 rc = sqlite3ApiExit(db, rc);
571 sqlite3_mutex_leave(db->mutex);
578 ** Declare that a function has been overloaded by a virtual table.
580 ** If the function already exists as a regular global function, then
581 ** this routine is a no-op. If the function does not exist, then create
582 ** a new one that always throws a run-time error.
584 ** When virtual tables intend to provide an overloaded function, they
585 ** should call this routine to make sure the global function exists.
586 ** A global function must exist in order for name resolution to work
589 int sqlite3_overload_function(
594 int nName = strlen(zName);
596 sqlite3_mutex_enter(db->mutex);
597 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
598 sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
599 0, sqlite3InvalidFunction, 0, 0);
601 rc = sqlite3ApiExit(db, SQLITE_OK);
602 sqlite3_mutex_leave(db->mutex);
606 #ifndef SQLITE_OMIT_TRACE
608 ** Register a trace function. The pArg from the previously registered trace
611 ** A NULL trace function means that no tracing is executes. A non-NULL
612 ** trace is a pointer to a function that is invoked at the start of each
615 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
617 sqlite3_mutex_enter(db->mutex);
618 pOld = db->pTraceArg;
620 db->pTraceArg = pArg;
621 sqlite3_mutex_leave(db->mutex);
625 ** Register a profile function. The pArg from the previously registered
626 ** profile function is returned.
628 ** A NULL profile function means that no profiling is executes. A non-NULL
629 ** profile is a pointer to a function that is invoked at the conclusion of
630 ** each SQL statement that is run.
632 void *sqlite3_profile(
634 void (*xProfile)(void*,const char*,sqlite_uint64),
638 sqlite3_mutex_enter(db->mutex);
639 pOld = db->pProfileArg;
640 db->xProfile = xProfile;
641 db->pProfileArg = pArg;
642 sqlite3_mutex_leave(db->mutex);
645 #endif /* SQLITE_OMIT_TRACE */
647 /*** EXPERIMENTAL ***
649 ** Register a function to be invoked when a transaction comments.
650 ** If the invoked function returns non-zero, then the commit becomes a
653 void *sqlite3_commit_hook(
654 sqlite3 *db, /* Attach the hook to this database */
655 int (*xCallback)(void*), /* Function to invoke on each commit */
656 void *pArg /* Argument to the function */
659 sqlite3_mutex_enter(db->mutex);
660 pOld = db->pCommitArg;
661 db->xCommitCallback = xCallback;
662 db->pCommitArg = pArg;
663 sqlite3_mutex_leave(db->mutex);
668 ** Register a callback to be invoked each time a row is updated,
669 ** inserted or deleted using this database connection.
671 void *sqlite3_update_hook(
672 sqlite3 *db, /* Attach the hook to this database */
673 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
674 void *pArg /* Argument to the function */
677 sqlite3_mutex_enter(db->mutex);
678 pRet = db->pUpdateArg;
679 db->xUpdateCallback = xCallback;
680 db->pUpdateArg = pArg;
681 sqlite3_mutex_leave(db->mutex);
686 ** Register a callback to be invoked each time a transaction is rolled
687 ** back by this database connection.
689 void *sqlite3_rollback_hook(
690 sqlite3 *db, /* Attach the hook to this database */
691 void (*xCallback)(void*), /* Callback function */
692 void *pArg /* Argument to the function */
695 sqlite3_mutex_enter(db->mutex);
696 pRet = db->pRollbackArg;
697 db->xRollbackCallback = xCallback;
698 db->pRollbackArg = pArg;
699 sqlite3_mutex_leave(db->mutex);
704 ** This routine is called to create a connection to a database BTree
705 ** driver. If zFilename is the name of a file, then that file is
706 ** opened and used. If zFilename is the magic name ":memory:" then
707 ** the database is stored in memory (and is thus forgotten as soon as
708 ** the connection is closed.) If zFilename is NULL then the database
709 ** is a "virtual" database for transient use only and is deleted as
710 ** soon as the connection is closed.
712 ** A virtual database can be either a disk file (that is automatically
713 ** deleted when the file is closed) or it an be held entirely in memory,
714 ** depending on the values of the TEMP_STORE compile-time macro and the
715 ** db->temp_store variable, according to the following chart:
717 ** TEMP_STORE db->temp_store Location of temporary database
718 ** ---------- -------------- ------------------------------
728 int sqlite3BtreeFactory(
729 const sqlite3 *db, /* Main database when opening aux otherwise 0 */
730 const char *zFilename, /* Name of the file containing the BTree database */
731 int omitJournal, /* if TRUE then do not journal this file */
732 int nCache, /* How many pages in the page cache */
733 int vfsFlags, /* Flags passed through to vfsOpen */
734 Btree **ppBtree /* Pointer to new Btree object written here */
739 assert( sqlite3_mutex_held(db->mutex) );
740 assert( ppBtree != 0);
742 btFlags |= BTREE_OMIT_JOURNAL;
744 if( db->flags & SQLITE_NoReadlock ){
745 btFlags |= BTREE_NO_READLOCK;
751 #ifndef SQLITE_OMIT_MEMORYDB
753 if( db->temp_store==2 ) zFilename = ":memory:";
756 if( db->temp_store!=1 ) zFilename = ":memory:";
759 zFilename = ":memory:";
761 #endif /* SQLITE_OMIT_MEMORYDB */
764 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
765 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
767 rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
769 sqlite3BtreeSetBusyHandler(*ppBtree, (void*)&db->busyHandler);
770 sqlite3BtreeSetCacheSize(*ppBtree, nCache);
776 ** Return UTF-8 encoded English language explanation of the most recent
779 const char *sqlite3_errmsg(sqlite3 *db){
782 return sqlite3ErrStr(SQLITE_NOMEM);
784 if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
785 return sqlite3ErrStr(SQLITE_MISUSE);
787 sqlite3_mutex_enter(db->mutex);
788 assert( !db->mallocFailed );
789 z = (char*)sqlite3_value_text(db->pErr);
791 z = sqlite3ErrStr(db->errCode);
793 sqlite3_mutex_leave(db->mutex);
797 #ifndef SQLITE_OMIT_UTF16
799 ** Return UTF-16 encoded English language explanation of the most recent
802 const void *sqlite3_errmsg16(sqlite3 *db){
803 /* Because all the characters in the string are in the unicode
804 ** range 0x00-0xFF, if we pad the big-endian string with a
805 ** zero byte, we can obtain the little-endian string with
808 static const char outOfMemBe[] = {
809 0, 'o', 0, 'u', 0, 't', 0, ' ',
810 0, 'o', 0, 'f', 0, ' ',
811 0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
813 static const char misuseBe [] = {
814 0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ',
815 0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ',
816 0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ',
817 0, 'o', 0, 'u', 0, 't', 0, ' ',
818 0, 'o', 0, 'f', 0, ' ',
819 0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
824 return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
826 if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
827 return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
829 sqlite3_mutex_enter(db->mutex);
830 assert( !db->mallocFailed );
831 z = sqlite3_value_text16(db->pErr);
833 sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
834 SQLITE_UTF8, SQLITE_STATIC);
835 z = sqlite3_value_text16(db->pErr);
837 sqlite3ApiExit(0, 0);
838 sqlite3_mutex_leave(db->mutex);
841 #endif /* SQLITE_OMIT_UTF16 */
844 ** Return the most recent error code generated by an SQLite routine. If NULL is
845 ** passed to this function, we assume a malloc() failed during sqlite3_open().
847 int sqlite3_errcode(sqlite3 *db){
848 if( !db || db->mallocFailed ){
851 if( sqlite3SafetyCheck(db) ){
852 return SQLITE_MISUSE;
854 return db->errCode & db->errMask;
858 ** Create a new collating function for database "db". The name is zName
859 ** and the encoding is enc.
861 static int createCollation(
866 int(*xCompare)(void*,int,const void*,int,const void*),
872 if( sqlite3SafetyCheck(db) ){
873 return SQLITE_MISUSE;
875 assert( sqlite3_mutex_held(db->mutex) );
877 /* If SQLITE_UTF16 is specified as the encoding type, transform this
878 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
879 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
881 enc2 = enc & ~SQLITE_UTF16_ALIGNED;
882 if( enc2==SQLITE_UTF16 ){
883 enc2 = SQLITE_UTF16NATIVE;
887 sqlite3Error(db, SQLITE_ERROR, "unknown encoding");
891 /* Check if this call is removing or replacing an existing collation
892 ** sequence. If so, and there are active VMs, return busy. If there
893 ** are no active VMs, invalidate any pre-compiled statements.
895 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 0);
896 if( pColl && pColl->xCmp ){
897 if( db->activeVdbeCnt ){
898 sqlite3Error(db, SQLITE_BUSY,
899 "Unable to delete/modify collation sequence due to active statements");
902 sqlite3ExpirePreparedStatements(db);
904 /* If collation sequence pColl was created directly by a call to
905 ** sqlite3_create_collation, and not generated by synthCollSeq(),
906 ** then any copies made by synthCollSeq() need to be invalidated.
907 ** Also, collation destructor - CollSeq.xDel() - function may need
910 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
911 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, strlen(zName));
914 CollSeq *p = &aColl[j];
915 if( p->enc==pColl->enc ){
925 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 1);
927 pColl->xCmp = xCompare;
930 pColl->enc = enc2 | (enc & SQLITE_UTF16_ALIGNED);
932 sqlite3Error(db, SQLITE_OK, 0);
938 ** This routine does the work of opening a database on behalf of
939 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
942 static int openDatabase(
943 const char *zFilename, /* Database filename UTF-8 encoded */
944 sqlite3 **ppDb, /* OUT: Returned database handle */
945 unsigned flags, /* Operational flags */
946 const char *zVfs /* Name of the VFS to use */
952 /* Allocate the sqlite data structure */
953 db = sqlite3MallocZero( sizeof(sqlite3) );
954 if( db==0 ) goto opendb_out;
955 db->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
961 sqlite3_mutex_enter(db->mutex);
963 db->priorNewRowid = 0;
965 db->magic = SQLITE_MAGIC_BUSY;
966 db->aDb = db->aDbStatic;
968 db->flags |= SQLITE_ShortColNames
969 #if SQLITE_DEFAULT_FILE_FORMAT<4
970 | SQLITE_LegacyFileFmt
972 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
973 | SQLITE_LoadExtension
976 sqlite3HashInit(&db->aFunc, SQLITE_HASH_STRING, 0);
977 sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0);
978 #ifndef SQLITE_OMIT_VIRTUALTABLE
979 sqlite3HashInit(&db->aModule, SQLITE_HASH_STRING, 0);
982 db->pVfs = sqlite3_vfs_find(zVfs);
985 db->magic = SQLITE_MAGIC_CLOSED;
986 sqlite3Error(db, rc, "no such vfs: %s", (zVfs?zVfs:"(null)"));
990 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
991 ** and UTF-16, so add a version for each to avoid any unnecessary
992 ** conversions. The only error that can occur here is a malloc() failure.
994 if( createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0) ||
995 createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0) ||
996 createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0) ||
997 (db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0))==0
999 assert( db->mallocFailed );
1000 db->magic = SQLITE_MAGIC_CLOSED;
1004 /* Also add a UTF-8 case-insensitive collation sequence. */
1005 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
1007 /* Set flags on the built-in collating sequences */
1008 db->pDfltColl->type = SQLITE_COLL_BINARY;
1009 pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
1011 pColl->type = SQLITE_COLL_NOCASE;
1014 /* Open the backend database driver */
1015 db->openFlags = flags;
1016 rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
1017 flags | SQLITE_OPEN_MAIN_DB,
1019 if( rc!=SQLITE_OK ){
1020 sqlite3Error(db, rc, 0);
1021 db->magic = SQLITE_MAGIC_CLOSED;
1024 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
1025 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
1028 /* The default safety_level for the main database is 'full'; for the temp
1029 ** database it is 'NONE'. This matches the pager layer defaults.
1031 db->aDb[0].zName = "main";
1032 db->aDb[0].safety_level = 3;
1033 #ifndef SQLITE_OMIT_TEMPDB
1034 db->aDb[1].zName = "temp";
1035 db->aDb[1].safety_level = 1;
1038 db->magic = SQLITE_MAGIC_OPEN;
1039 if( db->mallocFailed ){
1043 /* Register all built-in functions, but do not attempt to read the
1044 ** database schema yet. This is delayed until the first time the database
1047 sqlite3Error(db, SQLITE_OK, 0);
1048 sqlite3RegisterBuiltinFunctions(db);
1050 /* Load automatic extensions - extensions that have been registered
1051 ** using the sqlite3_automatic_extension() API.
1053 (void)sqlite3AutoLoadExtensions(db);
1054 if( sqlite3_errcode(db)!=SQLITE_OK ){
1058 #ifdef SQLITE_ENABLE_FTS1
1059 if( !db->mallocFailed ){
1060 extern int sqlite3Fts1Init(sqlite3*);
1061 rc = sqlite3Fts1Init(db);
1065 #ifdef SQLITE_ENABLE_FTS2
1066 if( !db->mallocFailed && rc==SQLITE_OK ){
1067 extern int sqlite3Fts2Init(sqlite3*);
1068 rc = sqlite3Fts2Init(db);
1072 #ifdef SQLITE_ENABLE_FTS3
1073 if( !db->mallocFailed && rc==SQLITE_OK ){
1074 extern int sqlite3Fts3Init(sqlite3*);
1075 rc = sqlite3Fts3Init(db);
1079 #ifdef SQLITE_ENABLE_ICU
1080 if( !db->mallocFailed && rc==SQLITE_OK ){
1081 extern int sqlite3IcuInit(sqlite3*);
1082 rc = sqlite3IcuInit(db);
1085 sqlite3Error(db, rc, 0);
1087 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
1088 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
1089 ** mode. Doing nothing at all also makes NORMAL the default.
1091 #ifdef SQLITE_DEFAULT_LOCKING_MODE
1092 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
1093 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
1094 SQLITE_DEFAULT_LOCKING_MODE);
1098 if( db && db->mutex ){
1099 sqlite3_mutex_leave(db->mutex);
1101 if( SQLITE_NOMEM==(rc = sqlite3_errcode(db)) ){
1106 return sqlite3ApiExit(0, rc);
1110 ** Open a new database handle.
1113 const char *zFilename,
1116 return openDatabase(zFilename, ppDb,
1117 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
1119 int sqlite3_open_v2(
1120 const char *filename, /* Database filename (UTF-8) */
1121 sqlite3 **ppDb, /* OUT: SQLite db handle */
1122 int flags, /* Flags */
1123 const char *zVfs /* Name of VFS module to use */
1125 return openDatabase(filename, ppDb, flags, zVfs);
1128 #ifndef SQLITE_OMIT_UTF16
1130 ** Open a new database handle.
1133 const void *zFilename,
1136 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
1137 sqlite3_value *pVal;
1138 int rc = SQLITE_NOMEM;
1140 assert( zFilename );
1143 pVal = sqlite3ValueNew(0);
1144 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
1145 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
1147 rc = openDatabase(zFilename8, ppDb,
1148 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
1149 if( rc==SQLITE_OK && *ppDb ){
1150 rc = sqlite3_exec(*ppDb, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);
1151 if( rc!=SQLITE_OK ){
1152 sqlite3_close(*ppDb);
1157 sqlite3ValueFree(pVal);
1159 return sqlite3ApiExit(0, rc);
1161 #endif /* SQLITE_OMIT_UTF16 */
1164 ** Register a new collation sequence with the database handle db.
1166 int sqlite3_create_collation(
1171 int(*xCompare)(void*,int,const void*,int,const void*)
1174 sqlite3_mutex_enter(db->mutex);
1175 assert( !db->mallocFailed );
1176 rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
1177 rc = sqlite3ApiExit(db, rc);
1178 sqlite3_mutex_leave(db->mutex);
1183 ** Register a new collation sequence with the database handle db.
1185 int sqlite3_create_collation_v2(
1190 int(*xCompare)(void*,int,const void*,int,const void*),
1194 sqlite3_mutex_enter(db->mutex);
1195 assert( !db->mallocFailed );
1196 rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
1197 rc = sqlite3ApiExit(db, rc);
1198 sqlite3_mutex_leave(db->mutex);
1202 #ifndef SQLITE_OMIT_UTF16
1204 ** Register a new collation sequence with the database handle db.
1206 int sqlite3_create_collation16(
1211 int(*xCompare)(void*,int,const void*,int,const void*)
1215 sqlite3_mutex_enter(db->mutex);
1216 assert( !db->mallocFailed );
1217 zName8 = sqlite3Utf16to8(db, zName, -1);
1219 rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
1220 sqlite3_free(zName8);
1222 rc = sqlite3ApiExit(db, rc);
1223 sqlite3_mutex_leave(db->mutex);
1226 #endif /* SQLITE_OMIT_UTF16 */
1229 ** Register a collation sequence factory callback with the database handle
1230 ** db. Replace any previously installed collation sequence factory.
1232 int sqlite3_collation_needed(
1234 void *pCollNeededArg,
1235 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
1237 if( sqlite3SafetyCheck(db) ){
1238 return SQLITE_MISUSE;
1240 sqlite3_mutex_enter(db->mutex);
1241 db->xCollNeeded = xCollNeeded;
1242 db->xCollNeeded16 = 0;
1243 db->pCollNeededArg = pCollNeededArg;
1244 sqlite3_mutex_leave(db->mutex);
1248 #ifndef SQLITE_OMIT_UTF16
1250 ** Register a collation sequence factory callback with the database handle
1251 ** db. Replace any previously installed collation sequence factory.
1253 int sqlite3_collation_needed16(
1255 void *pCollNeededArg,
1256 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
1258 if( sqlite3SafetyCheck(db) ){
1259 return SQLITE_MISUSE;
1261 sqlite3_mutex_enter(db->mutex);
1262 db->xCollNeeded = 0;
1263 db->xCollNeeded16 = xCollNeeded16;
1264 db->pCollNeededArg = pCollNeededArg;
1265 sqlite3_mutex_leave(db->mutex);
1268 #endif /* SQLITE_OMIT_UTF16 */
1270 #ifndef SQLITE_OMIT_GLOBALRECOVER
1272 ** This function is now an anachronism. It used to be used to recover from a
1273 ** malloc() failure, but SQLite now does this automatically.
1275 int sqlite3_global_recover(){
1281 ** Test to see whether or not the database connection is in autocommit
1282 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
1283 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
1284 ** by the next COMMIT or ROLLBACK.
1286 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
1288 int sqlite3_get_autocommit(sqlite3 *db){
1289 return db->autoCommit;
1294 ** The following routine is subtituted for constant SQLITE_CORRUPT in
1295 ** debugging builds. This provides a way to set a breakpoint for when
1296 ** corruption is first detected.
1298 int sqlite3Corrupt(void){
1299 return SQLITE_CORRUPT;
1304 ** This is a convenience routine that makes sure that all thread-specific
1305 ** data for this thread has been deallocated.
1307 ** SQLite no longer uses thread-specific data so this routine is now a
1308 ** no-op. It is retained for historical compatibility.
1310 void sqlite3_thread_cleanup(void){
1314 ** Return meta information about a specific column of a database table.
1315 ** See comment in sqlite3.h (sqlite.h.in) for details.
1317 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1318 int sqlite3_table_column_metadata(
1319 sqlite3 *db, /* Connection handle */
1320 const char *zDbName, /* Database name or NULL */
1321 const char *zTableName, /* Table name */
1322 const char *zColumnName, /* Column name */
1323 char const **pzDataType, /* OUTPUT: Declared data type */
1324 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
1325 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
1326 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
1327 int *pAutoinc /* OUTPUT: True if colums is auto-increment */
1335 char const *zDataType = 0;
1336 char const *zCollSeq = 0;
1341 /* Ensure the database schema has been loaded */
1342 if( sqlite3SafetyOn(db) ){
1343 return SQLITE_MISUSE;
1345 sqlite3_mutex_enter(db->mutex);
1346 rc = sqlite3Init(db, &zErrMsg);
1347 if( SQLITE_OK!=rc ){
1351 /* Locate the table in question */
1352 pTab = sqlite3FindTable(db, zTableName, zDbName);
1353 if( !pTab || pTab->pSelect ){
1358 /* Find the column for which info is requested */
1359 if( sqlite3IsRowid(zColumnName) ){
1362 pCol = &pTab->aCol[iCol];
1365 for(iCol=0; iCol<pTab->nCol; iCol++){
1366 pCol = &pTab->aCol[iCol];
1367 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
1371 if( iCol==pTab->nCol ){
1377 /* The following block stores the meta information that will be returned
1378 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
1379 ** and autoinc. At this point there are two possibilities:
1381 ** 1. The specified column name was rowid", "oid" or "_rowid_"
1382 ** and there is no explicitly declared IPK column.
1384 ** 2. The table is not a view and the column name identified an
1385 ** explicitly declared column. Copy meta information from *pCol.
1388 zDataType = pCol->zType;
1389 zCollSeq = pCol->zColl;
1390 notnull = (pCol->notNull?1:0);
1391 primarykey = (pCol->isPrimKey?1:0);
1392 autoinc = ((pTab->iPKey==iCol && pTab->autoInc)?1:0);
1394 zDataType = "INTEGER";
1398 zCollSeq = "BINARY";
1402 if( sqlite3SafetyOff(db) ){
1406 /* Whether the function call succeeded or failed, set the output parameters
1407 ** to whatever their local counterparts contain. If an error did occur,
1408 ** this has the effect of zeroing all output parameters.
1410 if( pzDataType ) *pzDataType = zDataType;
1411 if( pzCollSeq ) *pzCollSeq = zCollSeq;
1412 if( pNotNull ) *pNotNull = notnull;
1413 if( pPrimaryKey ) *pPrimaryKey = primarykey;
1414 if( pAutoinc ) *pAutoinc = autoinc;
1416 if( SQLITE_OK==rc && !pTab ){
1417 sqlite3SetString(&zErrMsg, "no such table column: ", zTableName, ".",
1421 sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
1422 sqlite3_free(zErrMsg);
1423 rc = sqlite3ApiExit(db, rc);
1424 sqlite3_mutex_leave(db->mutex);
1430 ** Sleep for a little while. Return the amount of time slept.
1432 int sqlite3_sleep(int ms){
1435 pVfs = sqlite3_vfs_find(0);
1437 /* This function works in milliseconds, but the underlying OsSleep()
1438 ** API uses microseconds. Hence the 1000's.
1440 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
1445 ** Enable or disable the extended result codes.
1447 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
1448 sqlite3_mutex_enter(db->mutex);
1449 db->errMask = onoff ? 0xffffffff : 0xff;
1450 sqlite3_mutex_leave(db->mutex);
1455 ** Invoke the xFileControl method on a particular database.
1457 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
1458 int rc = SQLITE_ERROR;
1460 sqlite3_mutex_enter(db->mutex);
1464 for(iDb=0; iDb<db->nDb; iDb++){
1465 if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
1469 Btree *pBtree = db->aDb[iDb].pBt;
1472 sqlite3BtreeEnter(pBtree);
1473 pPager = sqlite3BtreePager(pBtree);
1475 sqlite3_file *fd = sqlite3PagerFile(pPager);
1477 rc = sqlite3OsFileControl(fd, op, pArg);
1480 sqlite3BtreeLeave(pBtree);
1483 sqlite3_mutex_leave(db->mutex);