xref: /sqlite-3.40.0/src/main.c (revision 4dcbdbff)
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 ** $Id: main.c,v 1.296 2005/07/15 13:05:21 drh Exp $
18 */
19 #include "sqliteInt.h"
20 #include "os.h"
21 #include <ctype.h>
22 
23 /*
24 ** The following constant value is used by the SQLITE_BIGENDIAN and
25 ** SQLITE_LITTLEENDIAN macros.
26 */
27 const int sqlite3one = 1;
28 
29 #ifndef SQLITE_OMIT_GLOBALRECOVER
30 /*
31 ** Linked list of all open database handles. This is used by the
32 ** sqlite3_global_recover() function. Entries are added to the list
33 ** by openDatabase() and removed by sqlite3_close().
34 */
35 static sqlite3 *pDbList = 0;
36 #endif
37 
38 #ifndef SQLITE_OMIT_UTF16
39 /*
40 ** Return the transient sqlite3_value object used for encoding conversions
41 ** during SQL compilation.
42 */
43 sqlite3_value *sqlite3GetTransientValue(sqlite3 *db){
44   if( !db->pValue ){
45     db->pValue = sqlite3ValueNew();
46   }
47   return db->pValue;
48 }
49 #endif
50 
51 /*
52 ** The version of the library
53 */
54 const char rcsid3[] = "@(#) \044Id: SQLite version " SQLITE_VERSION " $";
55 const char sqlite3_version[] = SQLITE_VERSION;
56 const char *sqlite3_libversion(void){ return sqlite3_version; }
57 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
58 
59 /*
60 ** This is the default collating function named "BINARY" which is always
61 ** available.
62 */
63 static int binCollFunc(
64   void *NotUsed,
65   int nKey1, const void *pKey1,
66   int nKey2, const void *pKey2
67 ){
68   int rc, n;
69   n = nKey1<nKey2 ? nKey1 : nKey2;
70   rc = memcmp(pKey1, pKey2, n);
71   if( rc==0 ){
72     rc = nKey1 - nKey2;
73   }
74   return rc;
75 }
76 
77 /*
78 ** Another built-in collating sequence: NOCASE.
79 **
80 ** This collating sequence is intended to be used for "case independant
81 ** comparison". SQLite's knowledge of upper and lower case equivalents
82 ** extends only to the 26 characters used in the English language.
83 **
84 ** At the moment there is only a UTF-8 implementation.
85 */
86 static int nocaseCollatingFunc(
87   void *NotUsed,
88   int nKey1, const void *pKey1,
89   int nKey2, const void *pKey2
90 ){
91   int r = sqlite3StrNICmp(
92       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
93   if( 0==r ){
94     r = nKey1-nKey2;
95   }
96   return r;
97 }
98 
99 /*
100 ** Return the ROWID of the most recent insert
101 */
102 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
103   return db->lastRowid;
104 }
105 
106 /*
107 ** Return the number of changes in the most recent call to sqlite3_exec().
108 */
109 int sqlite3_changes(sqlite3 *db){
110   return db->nChange;
111 }
112 
113 /*
114 ** Return the number of changes since the database handle was opened.
115 */
116 int sqlite3_total_changes(sqlite3 *db){
117   return db->nTotalChange;
118 }
119 
120 /*
121 ** Close an existing SQLite database
122 */
123 int sqlite3_close(sqlite3 *db){
124   HashElem *i;
125   int j;
126 
127   if( !db ){
128     return SQLITE_OK;
129   }
130   if( sqlite3SafetyCheck(db) ){
131     return SQLITE_MISUSE;
132   }
133 
134 #ifdef SQLITE_SSE
135   sqlite3_finalize(db->pFetch);
136 #endif
137 
138   /* If there are any outstanding VMs, return SQLITE_BUSY. */
139   if( db->pVdbe ){
140     sqlite3Error(db, SQLITE_BUSY,
141         "Unable to close due to unfinalised statements");
142     return SQLITE_BUSY;
143   }
144   assert( !sqlite3SafetyCheck(db) );
145 
146   /* FIX ME: db->magic may be set to SQLITE_MAGIC_CLOSED if the database
147   ** cannot be opened for some reason. So this routine needs to run in
148   ** that case. But maybe there should be an extra magic value for the
149   ** "failed to open" state.
150   */
151   if( db->magic!=SQLITE_MAGIC_CLOSED && sqlite3SafetyOn(db) ){
152     /* printf("DID NOT CLOSE\n"); fflush(stdout); */
153     return SQLITE_ERROR;
154   }
155 
156   for(j=0; j<db->nDb; j++){
157     struct Db *pDb = &db->aDb[j];
158     if( pDb->pBt ){
159       sqlite3BtreeClose(pDb->pBt);
160       pDb->pBt = 0;
161     }
162   }
163   sqlite3ResetInternalSchema(db, 0);
164   assert( db->nDb<=2 );
165   assert( db->aDb==db->aDbStatic );
166   for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
167     FuncDef *pFunc, *pNext;
168     for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
169       pNext = pFunc->pNext;
170       sqliteFree(pFunc);
171     }
172   }
173 
174   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
175     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
176     sqliteFree(pColl);
177   }
178   sqlite3HashClear(&db->aCollSeq);
179 
180   sqlite3HashClear(&db->aFunc);
181   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
182   if( db->pValue ){
183     sqlite3ValueFree(db->pValue);
184   }
185   if( db->pErr ){
186     sqlite3ValueFree(db->pErr);
187   }
188 
189 #ifndef SQLITE_OMIT_GLOBALRECOVER
190   {
191     sqlite3 *pPrev;
192     sqlite3OsEnterMutex();
193     pPrev = pDbList;
194     while( pPrev && pPrev->pNext!=db ){
195       pPrev = pPrev->pNext;
196     }
197     if( pPrev ){
198       pPrev->pNext = db->pNext;
199     }else{
200       assert( pDbList==db );
201       pDbList = db->pNext;
202     }
203     sqlite3OsLeaveMutex();
204   }
205 #endif
206 
207   db->magic = SQLITE_MAGIC_ERROR;
208   sqliteFree(db);
209   return SQLITE_OK;
210 }
211 
212 /*
213 ** Rollback all database files.
214 */
215 void sqlite3RollbackAll(sqlite3 *db){
216   int i;
217   for(i=0; i<db->nDb; i++){
218     if( db->aDb[i].pBt ){
219       sqlite3BtreeRollback(db->aDb[i].pBt);
220       db->aDb[i].inTrans = 0;
221     }
222   }
223   sqlite3ResetInternalSchema(db, 0);
224 }
225 
226 /*
227 ** Return a static string that describes the kind of error specified in the
228 ** argument.
229 */
230 const char *sqlite3ErrStr(int rc){
231   const char *z;
232   switch( rc ){
233     case SQLITE_ROW:
234     case SQLITE_DONE:
235     case SQLITE_OK:         z = "not an error";                          break;
236     case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
237     case SQLITE_INTERNAL:   z = "internal SQLite implementation flaw";   break;
238     case SQLITE_PERM:       z = "access permission denied";              break;
239     case SQLITE_ABORT:      z = "callback requested query abort";        break;
240     case SQLITE_BUSY:       z = "database is locked";                    break;
241     case SQLITE_LOCKED:     z = "database table is locked";              break;
242     case SQLITE_NOMEM:      z = "out of memory";                         break;
243     case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
244     case SQLITE_INTERRUPT:  z = "interrupted";                           break;
245     case SQLITE_IOERR:      z = "disk I/O error";                        break;
246     case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
247     case SQLITE_NOTFOUND:   z = "table or record not found";             break;
248     case SQLITE_FULL:       z = "database is full";                      break;
249     case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
250     case SQLITE_PROTOCOL:   z = "database locking protocol failure";     break;
251     case SQLITE_EMPTY:      z = "table contains no data";                break;
252     case SQLITE_SCHEMA:     z = "database schema has changed";           break;
253     case SQLITE_TOOBIG:     z = "too much data for one table row";       break;
254     case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
255     case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
256     case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
257     case SQLITE_NOLFS:      z = "kernel lacks large file support";       break;
258     case SQLITE_AUTH:       z = "authorization denied";                  break;
259     case SQLITE_FORMAT:     z = "auxiliary database format error";       break;
260     case SQLITE_RANGE:      z = "bind or column index out of range";     break;
261     case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;
262     default:                z = "unknown error";                         break;
263   }
264   return z;
265 }
266 
267 /*
268 ** This routine implements a busy callback that sleeps and tries
269 ** again until a timeout value is reached.  The timeout value is
270 ** an integer number of milliseconds passed in as the first
271 ** argument.
272 */
273 static int sqliteDefaultBusyCallback(
274  void *ptr,               /* Database connection */
275  int count                /* Number of times table has been busy */
276 ){
277 #if SQLITE_MIN_SLEEP_MS==1
278   static const u8 delays[] =
279      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
280   static const u8 totals[] =
281      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
282 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
283   int timeout = ((sqlite3 *)ptr)->busyTimeout;
284   int delay, prior;
285 
286   assert( count>=0 );
287   if( count < NDELAY ){
288     delay = delays[count];
289     prior = totals[count];
290   }else{
291     delay = delays[NDELAY-1];
292     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
293   }
294   if( prior + delay > timeout ){
295     delay = timeout - prior;
296     if( delay<=0 ) return 0;
297   }
298   sqlite3OsSleep(delay);
299   return 1;
300 #else
301   int timeout = ((sqlite3 *)ptr)->busyTimeout;
302   if( (count+1)*1000 > timeout ){
303     return 0;
304   }
305   sqlite3OsSleep(1000);
306   return 1;
307 #endif
308 }
309 
310 /*
311 ** Invoke the given busy handler.
312 **
313 ** This routine is called when an operation failed with a lock.
314 ** If this routine returns non-zero, the lock is retried.  If it
315 ** returns 0, the operation aborts with an SQLITE_BUSY error.
316 */
317 int sqlite3InvokeBusyHandler(BusyHandler *p){
318   int rc;
319   if( p==0 || p->xFunc==0 || p->nBusy<0 ) return 0;
320   rc = p->xFunc(p->pArg, p->nBusy);
321   if( rc==0 ){
322     p->nBusy = -1;
323   }else{
324     p->nBusy++;
325   }
326   return rc;
327 }
328 
329 /*
330 ** This routine sets the busy callback for an Sqlite database to the
331 ** given callback function with the given argument.
332 */
333 int sqlite3_busy_handler(
334   sqlite3 *db,
335   int (*xBusy)(void*,int),
336   void *pArg
337 ){
338   if( sqlite3SafetyCheck(db) ){
339     return SQLITE_MISUSE;
340   }
341   db->busyHandler.xFunc = xBusy;
342   db->busyHandler.pArg = pArg;
343   db->busyHandler.nBusy = 0;
344   return SQLITE_OK;
345 }
346 
347 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
348 /*
349 ** This routine sets the progress callback for an Sqlite database to the
350 ** given callback function with the given argument. The progress callback will
351 ** be invoked every nOps opcodes.
352 */
353 void sqlite3_progress_handler(
354   sqlite3 *db,
355   int nOps,
356   int (*xProgress)(void*),
357   void *pArg
358 ){
359   if( !sqlite3SafetyCheck(db) ){
360     if( nOps>0 ){
361       db->xProgress = xProgress;
362       db->nProgressOps = nOps;
363       db->pProgressArg = pArg;
364     }else{
365       db->xProgress = 0;
366       db->nProgressOps = 0;
367       db->pProgressArg = 0;
368     }
369   }
370 }
371 #endif
372 
373 
374 /*
375 ** This routine installs a default busy handler that waits for the
376 ** specified number of milliseconds before returning 0.
377 */
378 int sqlite3_busy_timeout(sqlite3 *db, int ms){
379   if( ms>0 ){
380     db->busyTimeout = ms;
381     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
382   }else{
383     sqlite3_busy_handler(db, 0, 0);
384   }
385   return SQLITE_OK;
386 }
387 
388 /*
389 ** Cause any pending operation to stop at its earliest opportunity.
390 */
391 void sqlite3_interrupt(sqlite3 *db){
392   if( !sqlite3SafetyCheck(db) ){
393     db->flags |= SQLITE_Interrupt;
394   }
395 }
396 
397 /*
398 ** Windows systems should call this routine to free memory that
399 ** is returned in the in the errmsg parameter of sqlite3_open() when
400 ** SQLite is a DLL.  For some reason, it does not work to call free()
401 ** directly.
402 **
403 ** Note that we need to call free() not sqliteFree() here.
404 */
405 void sqlite3_free(char *p){ free(p); }
406 
407 /*
408 ** Create new user functions.
409 */
410 int sqlite3_create_function(
411   sqlite3 *db,
412   const char *zFunctionName,
413   int nArg,
414   int enc,
415   void *pUserData,
416   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
417   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
418   void (*xFinal)(sqlite3_context*)
419 ){
420   FuncDef *p;
421   int nName;
422 
423   if( sqlite3SafetyCheck(db) ){
424     return SQLITE_MISUSE;
425   }
426   if( zFunctionName==0 ||
427       (xFunc && (xFinal || xStep)) ||
428       (!xFunc && (xFinal && !xStep)) ||
429       (!xFunc && (!xFinal && xStep)) ||
430       (nArg<-1 || nArg>127) ||
431       (255<(nName = strlen(zFunctionName))) ){
432     return SQLITE_ERROR;
433   }
434 
435 #ifndef SQLITE_OMIT_UTF16
436   /* If SQLITE_UTF16 is specified as the encoding type, transform this
437   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
438   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
439   **
440   ** If SQLITE_ANY is specified, add three versions of the function
441   ** to the hash table.
442   */
443   if( enc==SQLITE_UTF16 ){
444     enc = SQLITE_UTF16NATIVE;
445   }else if( enc==SQLITE_ANY ){
446     int rc;
447     rc = sqlite3_create_function(db, zFunctionName, nArg, SQLITE_UTF8,
448          pUserData, xFunc, xStep, xFinal);
449     if( rc!=SQLITE_OK ) return rc;
450     rc = sqlite3_create_function(db, zFunctionName, nArg, SQLITE_UTF16LE,
451         pUserData, xFunc, xStep, xFinal);
452     if( rc!=SQLITE_OK ) return rc;
453     enc = SQLITE_UTF16BE;
454   }
455 #else
456   enc = SQLITE_UTF8;
457 #endif
458 
459   /* Check if an existing function is being overridden or deleted. If so,
460   ** and there are active VMs, then return SQLITE_BUSY. If a function
461   ** is being overridden/deleted but there are no active VMs, allow the
462   ** operation to continue but invalidate all precompiled statements.
463   */
464   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
465   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
466     if( db->activeVdbeCnt ){
467       sqlite3Error(db, SQLITE_BUSY,
468         "Unable to delete/modify user-function due to active statements");
469       return SQLITE_BUSY;
470     }else{
471       sqlite3ExpirePreparedStatements(db);
472     }
473   }
474 
475   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
476   if( p==0 ) return SQLITE_NOMEM;
477   p->xFunc = xFunc;
478   p->xStep = xStep;
479   p->xFinalize = xFinal;
480   p->pUserData = pUserData;
481   return SQLITE_OK;
482 }
483 #ifndef SQLITE_OMIT_UTF16
484 int sqlite3_create_function16(
485   sqlite3 *db,
486   const void *zFunctionName,
487   int nArg,
488   int eTextRep,
489   void *pUserData,
490   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
491   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
492   void (*xFinal)(sqlite3_context*)
493 ){
494   int rc;
495   char const *zFunc8;
496   sqlite3_value *pTmp;
497 
498   if( sqlite3SafetyCheck(db) ){
499     return SQLITE_MISUSE;
500   }
501   pTmp = sqlite3GetTransientValue(db);
502   sqlite3ValueSetStr(pTmp, -1, zFunctionName, SQLITE_UTF16NATIVE,SQLITE_STATIC);
503   zFunc8 = sqlite3ValueText(pTmp, SQLITE_UTF8);
504 
505   if( !zFunc8 ){
506     return SQLITE_NOMEM;
507   }
508   rc = sqlite3_create_function(db, zFunc8, nArg, eTextRep,
509       pUserData, xFunc, xStep, xFinal);
510   return rc;
511 }
512 #endif
513 
514 /*
515 ** Register a trace function.  The pArg from the previously registered trace
516 ** is returned.
517 **
518 ** A NULL trace function means that no tracing is executes.  A non-NULL
519 ** trace is a pointer to a function that is invoked at the start of each
520 ** sqlite3_exec().
521 */
522 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
523   void *pOld = db->pTraceArg;
524   db->xTrace = xTrace;
525   db->pTraceArg = pArg;
526   return pOld;
527 }
528 
529 /*** EXPERIMENTAL ***
530 **
531 ** Register a function to be invoked when a transaction comments.
532 ** If either function returns non-zero, then the commit becomes a
533 ** rollback.
534 */
535 void *sqlite3_commit_hook(
536   sqlite3 *db,              /* Attach the hook to this database */
537   int (*xCallback)(void*),  /* Function to invoke on each commit */
538   void *pArg                /* Argument to the function */
539 ){
540   void *pOld = db->pCommitArg;
541   db->xCommitCallback = xCallback;
542   db->pCommitArg = pArg;
543   return pOld;
544 }
545 
546 
547 /*
548 ** This routine is called to create a connection to a database BTree
549 ** driver.  If zFilename is the name of a file, then that file is
550 ** opened and used.  If zFilename is the magic name ":memory:" then
551 ** the database is stored in memory (and is thus forgotten as soon as
552 ** the connection is closed.)  If zFilename is NULL then the database
553 ** is a "virtual" database for transient use only and is deleted as
554 ** soon as the connection is closed.
555 **
556 ** A virtual database can be either a disk file (that is automatically
557 ** deleted when the file is closed) or it an be held entirely in memory,
558 ** depending on the values of the TEMP_STORE compile-time macro and the
559 ** db->temp_store variable, according to the following chart:
560 **
561 **       TEMP_STORE     db->temp_store     Location of temporary database
562 **       ----------     --------------     ------------------------------
563 **           0               any             file
564 **           1                1              file
565 **           1                2              memory
566 **           1                0              file
567 **           2                1              file
568 **           2                2              memory
569 **           2                0              memory
570 **           3               any             memory
571 */
572 int sqlite3BtreeFactory(
573   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
574   const char *zFilename,    /* Name of the file containing the BTree database */
575   int omitJournal,          /* if TRUE then do not journal this file */
576   int nCache,               /* How many pages in the page cache */
577   Btree **ppBtree           /* Pointer to new Btree object written here */
578 ){
579   int btree_flags = 0;
580   int rc;
581 
582   assert( ppBtree != 0);
583   if( omitJournal ){
584     btree_flags |= BTREE_OMIT_JOURNAL;
585   }
586   if( db->flags & SQLITE_NoReadlock ){
587     btree_flags |= BTREE_NO_READLOCK;
588   }
589   if( zFilename==0 ){
590 #if TEMP_STORE==0
591     /* Do nothing */
592 #endif
593 #ifndef SQLITE_OMIT_MEMORYDB
594 #if TEMP_STORE==1
595     if( db->temp_store==2 ) zFilename = ":memory:";
596 #endif
597 #if TEMP_STORE==2
598     if( db->temp_store!=1 ) zFilename = ":memory:";
599 #endif
600 #if TEMP_STORE==3
601     zFilename = ":memory:";
602 #endif
603 #endif /* SQLITE_OMIT_MEMORYDB */
604   }
605 
606   rc = sqlite3BtreeOpen(zFilename, ppBtree, btree_flags);
607   if( rc==SQLITE_OK ){
608     sqlite3BtreeSetBusyHandler(*ppBtree, (void*)&db->busyHandler);
609     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
610   }
611   return rc;
612 }
613 
614 /*
615 ** Return UTF-8 encoded English language explanation of the most recent
616 ** error.
617 */
618 const char *sqlite3_errmsg(sqlite3 *db){
619   const char *z;
620   if( sqlite3_malloc_failed ){
621     return sqlite3ErrStr(SQLITE_NOMEM);
622   }
623   if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
624     return sqlite3ErrStr(SQLITE_MISUSE);
625   }
626   z = sqlite3_value_text(db->pErr);
627   if( z==0 ){
628     z = sqlite3ErrStr(db->errCode);
629   }
630   return z;
631 }
632 
633 #ifndef SQLITE_OMIT_UTF16
634 /*
635 ** Return UTF-16 encoded English language explanation of the most recent
636 ** error.
637 */
638 const void *sqlite3_errmsg16(sqlite3 *db){
639   /* Because all the characters in the string are in the unicode
640   ** range 0x00-0xFF, if we pad the big-endian string with a
641   ** zero byte, we can obtain the little-endian string with
642   ** &big_endian[1].
643   */
644   static const char outOfMemBe[] = {
645     0, 'o', 0, 'u', 0, 't', 0, ' ',
646     0, 'o', 0, 'f', 0, ' ',
647     0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
648   };
649   static const char misuseBe [] = {
650     0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ',
651     0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ',
652     0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ',
653     0, 'o', 0, 'u', 0, 't', 0, ' ',
654     0, 'o', 0, 'f', 0, ' ',
655     0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
656   };
657 
658   const void *z;
659   if( sqlite3_malloc_failed ){
660     return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
661   }
662   if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
663     return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
664   }
665   z = sqlite3_value_text16(db->pErr);
666   if( z==0 ){
667     sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
668          SQLITE_UTF8, SQLITE_STATIC);
669     z = sqlite3_value_text16(db->pErr);
670   }
671   return z;
672 }
673 #endif /* SQLITE_OMIT_UTF16 */
674 
675 /*
676 ** Return the most recent error code generated by an SQLite routine.
677 */
678 int sqlite3_errcode(sqlite3 *db){
679   if( sqlite3_malloc_failed ){
680     return SQLITE_NOMEM;
681   }
682   if( sqlite3SafetyCheck(db) ){
683     return SQLITE_MISUSE;
684   }
685   return db->errCode;
686 }
687 
688 /*
689 ** This routine does the work of opening a database on behalf of
690 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
691 ** is UTF-8 encoded.
692 */
693 static int openDatabase(
694   const char *zFilename, /* Database filename UTF-8 encoded */
695   sqlite3 **ppDb         /* OUT: Returned database handle */
696 ){
697   sqlite3 *db;
698   int rc, i;
699 
700   /* Allocate the sqlite data structure */
701   db = sqliteMalloc( sizeof(sqlite3) );
702   if( db==0 ) goto opendb_out;
703   db->priorNewRowid = 0;
704   db->magic = SQLITE_MAGIC_BUSY;
705   db->nDb = 2;
706   db->aDb = db->aDbStatic;
707   db->enc = SQLITE_UTF8;
708   db->autoCommit = 1;
709   db->flags |= SQLITE_ShortColNames;
710   sqlite3HashInit(&db->aFunc, SQLITE_HASH_STRING, 0);
711   sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0);
712   for(i=0; i<db->nDb; i++){
713     sqlite3HashInit(&db->aDb[i].tblHash, SQLITE_HASH_STRING, 0);
714     sqlite3HashInit(&db->aDb[i].idxHash, SQLITE_HASH_STRING, 0);
715     sqlite3HashInit(&db->aDb[i].trigHash, SQLITE_HASH_STRING, 0);
716     sqlite3HashInit(&db->aDb[i].aFKey, SQLITE_HASH_STRING, 1);
717   }
718 
719   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
720   ** and UTF-16, so add a version for each to avoid any unnecessary
721   ** conversions. The only error that can occur here is a malloc() failure.
722   */
723   if( sqlite3_create_collation(db, "BINARY", SQLITE_UTF8, 0,binCollFunc) ||
724       sqlite3_create_collation(db, "BINARY", SQLITE_UTF16, 0,binCollFunc) ||
725       !(db->pDfltColl = sqlite3FindCollSeq(db, db->enc, "BINARY", 6, 0)) ){
726     rc = db->errCode;
727     assert( rc!=SQLITE_OK );
728     db->magic = SQLITE_MAGIC_CLOSED;
729     goto opendb_out;
730   }
731 
732   /* Also add a UTF-8 case-insensitive collation sequence. */
733   sqlite3_create_collation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc);
734 
735   /* Open the backend database driver */
736   rc = sqlite3BtreeFactory(db, zFilename, 0, MAX_PAGES, &db->aDb[0].pBt);
737   if( rc!=SQLITE_OK ){
738     sqlite3Error(db, rc, 0);
739     db->magic = SQLITE_MAGIC_CLOSED;
740     goto opendb_out;
741   }
742 
743   /* The default safety_level for the main database is 'full'; for the temp
744   ** database it is 'NONE'. This matches the pager layer defaults.
745   */
746   db->aDb[0].zName = "main";
747   db->aDb[0].safety_level = 3;
748 #ifndef SQLITE_OMIT_TEMPDB
749   db->aDb[1].zName = "temp";
750   db->aDb[1].safety_level = 1;
751 #endif
752 
753 
754   /* Register all built-in functions, but do not attempt to read the
755   ** database schema yet. This is delayed until the first time the database
756   ** is accessed.
757   */
758   sqlite3RegisterBuiltinFunctions(db);
759   sqlite3Error(db, SQLITE_OK, 0);
760   db->magic = SQLITE_MAGIC_OPEN;
761 
762 opendb_out:
763   if( sqlite3_errcode(db)==SQLITE_OK && sqlite3_malloc_failed ){
764     sqlite3Error(db, SQLITE_NOMEM, 0);
765   }
766   *ppDb = db;
767 #ifndef SQLITE_OMIT_GLOBALRECOVER
768   if( db ){
769     sqlite3OsEnterMutex();
770     db->pNext = pDbList;
771     pDbList = db;
772     sqlite3OsLeaveMutex();
773   }
774 #endif
775   return sqlite3_errcode(db);
776 }
777 
778 /*
779 ** Open a new database handle.
780 */
781 int sqlite3_open(
782   const char *zFilename,
783   sqlite3 **ppDb
784 ){
785   return openDatabase(zFilename, ppDb);
786 }
787 
788 #ifndef SQLITE_OMIT_UTF16
789 /*
790 ** Open a new database handle.
791 */
792 int sqlite3_open16(
793   const void *zFilename,
794   sqlite3 **ppDb
795 ){
796   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
797   int rc = SQLITE_NOMEM;
798   sqlite3_value *pVal;
799 
800   assert( ppDb );
801   *ppDb = 0;
802   pVal = sqlite3ValueNew();
803   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
804   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
805   if( zFilename8 ){
806     rc = openDatabase(zFilename8, ppDb);
807     if( rc==SQLITE_OK && *ppDb ){
808       sqlite3_exec(*ppDb, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);
809     }
810   }
811   if( pVal ){
812     sqlite3ValueFree(pVal);
813   }
814 
815   return rc;
816 }
817 #endif /* SQLITE_OMIT_UTF16 */
818 
819 /*
820 ** The following routine destroys a virtual machine that is created by
821 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
822 ** success/failure code that describes the result of executing the virtual
823 ** machine.
824 **
825 ** This routine sets the error code and string returned by
826 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
827 */
828 int sqlite3_finalize(sqlite3_stmt *pStmt){
829   int rc;
830   if( pStmt==0 ){
831     rc = SQLITE_OK;
832   }else{
833     rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
834   }
835   return rc;
836 }
837 
838 /*
839 ** Terminate the current execution of an SQL statement and reset it
840 ** back to its starting state so that it can be reused. A success code from
841 ** the prior execution is returned.
842 **
843 ** This routine sets the error code and string returned by
844 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
845 */
846 int sqlite3_reset(sqlite3_stmt *pStmt){
847   int rc;
848   if( pStmt==0 ){
849     rc = SQLITE_OK;
850   }else{
851     rc = sqlite3VdbeReset((Vdbe*)pStmt);
852     sqlite3VdbeMakeReady((Vdbe*)pStmt, -1, 0, 0, 0, 0);
853   }
854   return rc;
855 }
856 
857 /*
858 ** Register a new collation sequence with the database handle db.
859 */
860 int sqlite3_create_collation(
861   sqlite3* db,
862   const char *zName,
863   int enc,
864   void* pCtx,
865   int(*xCompare)(void*,int,const void*,int,const void*)
866 ){
867   CollSeq *pColl;
868   int rc = SQLITE_OK;
869 
870   if( sqlite3SafetyCheck(db) ){
871     return SQLITE_MISUSE;
872   }
873 
874   /* If SQLITE_UTF16 is specified as the encoding type, transform this
875   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
876   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
877   */
878   if( enc==SQLITE_UTF16 ){
879     enc = SQLITE_UTF16NATIVE;
880   }
881 
882   if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16LE && enc!=SQLITE_UTF16BE ){
883     sqlite3Error(db, SQLITE_ERROR,
884         "Param 3 to sqlite3_create_collation() must be one of "
885         "SQLITE_UTF8, SQLITE_UTF16, SQLITE_UTF16LE or SQLITE_UTF16BE"
886     );
887     return SQLITE_ERROR;
888   }
889 
890   /* Check if this call is removing or replacing an existing collation
891   ** sequence. If so, and there are active VMs, return busy. If there
892   ** are no active VMs, invalidate any pre-compiled statements.
893   */
894   pColl = sqlite3FindCollSeq(db, (u8)enc, zName, strlen(zName), 0);
895   if( pColl && pColl->xCmp ){
896     if( db->activeVdbeCnt ){
897       sqlite3Error(db, SQLITE_BUSY,
898         "Unable to delete/modify collation sequence due to active statements");
899       return SQLITE_BUSY;
900     }
901     sqlite3ExpirePreparedStatements(db);
902   }
903 
904   pColl = sqlite3FindCollSeq(db, (u8)enc, zName, strlen(zName), 1);
905   if( 0==pColl ){
906    rc = SQLITE_NOMEM;
907   }else{
908     pColl->xCmp = xCompare;
909     pColl->pUser = pCtx;
910     pColl->enc = enc;
911   }
912   sqlite3Error(db, rc, 0);
913   return rc;
914 }
915 
916 #ifndef SQLITE_OMIT_UTF16
917 /*
918 ** Register a new collation sequence with the database handle db.
919 */
920 int sqlite3_create_collation16(
921   sqlite3* db,
922   const char *zName,
923   int enc,
924   void* pCtx,
925   int(*xCompare)(void*,int,const void*,int,const void*)
926 ){
927   char const *zName8;
928   sqlite3_value *pTmp;
929   if( sqlite3SafetyCheck(db) ){
930     return SQLITE_MISUSE;
931   }
932   pTmp = sqlite3GetTransientValue(db);
933   sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF16NATIVE, SQLITE_STATIC);
934   zName8 = sqlite3ValueText(pTmp, SQLITE_UTF8);
935   return sqlite3_create_collation(db, zName8, enc, pCtx, xCompare);
936 }
937 #endif /* SQLITE_OMIT_UTF16 */
938 
939 /*
940 ** Register a collation sequence factory callback with the database handle
941 ** db. Replace any previously installed collation sequence factory.
942 */
943 int sqlite3_collation_needed(
944   sqlite3 *db,
945   void *pCollNeededArg,
946   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
947 ){
948   if( sqlite3SafetyCheck(db) ){
949     return SQLITE_MISUSE;
950   }
951   db->xCollNeeded = xCollNeeded;
952   db->xCollNeeded16 = 0;
953   db->pCollNeededArg = pCollNeededArg;
954   return SQLITE_OK;
955 }
956 
957 #ifndef SQLITE_OMIT_UTF16
958 /*
959 ** Register a collation sequence factory callback with the database handle
960 ** db. Replace any previously installed collation sequence factory.
961 */
962 int sqlite3_collation_needed16(
963   sqlite3 *db,
964   void *pCollNeededArg,
965   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
966 ){
967   if( sqlite3SafetyCheck(db) ){
968     return SQLITE_MISUSE;
969   }
970   db->xCollNeeded = 0;
971   db->xCollNeeded16 = xCollNeeded16;
972   db->pCollNeededArg = pCollNeededArg;
973   return SQLITE_OK;
974 }
975 #endif /* SQLITE_OMIT_UTF16 */
976 
977 #ifndef SQLITE_OMIT_GLOBALRECOVER
978 /*
979 ** This function is called to recover from a malloc failure that occured
980 ** within SQLite.
981 **
982 ** This function is *not* threadsafe. Calling this from within a threaded
983 ** application when threads other than the caller have used SQLite is
984 ** dangerous and will almost certainly result in malfunctions.
985 */
986 int sqlite3_global_recover(){
987   int rc = SQLITE_OK;
988 
989   if( sqlite3_malloc_failed ){
990     sqlite3 *db;
991     int i;
992     sqlite3_malloc_failed = 0;
993     for(db=pDbList; db; db=db->pNext ){
994       sqlite3ExpirePreparedStatements(db);
995       for(i=0; i<db->nDb; i++){
996         Btree *pBt = db->aDb[i].pBt;
997         if( pBt && (rc=sqlite3BtreeReset(pBt)) ){
998           goto recover_out;
999         }
1000       }
1001       db->autoCommit = 1;
1002     }
1003   }
1004 
1005 recover_out:
1006   if( rc!=SQLITE_OK ){
1007     sqlite3_malloc_failed = 1;
1008   }
1009   return rc;
1010 }
1011 #endif
1012 
1013 /*
1014 ** Test to see whether or not the database connection is in autocommit
1015 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
1016 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
1017 ** by the next COMMIT or ROLLBACK.
1018 **
1019 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
1020 */
1021 int sqlite3_get_autocommit(sqlite3 *db){
1022   return db->autoCommit;
1023 }
1024