forgotten commit. disabled until egl is adapted.
[AROS-Contrib.git] / sqlite3 / main.c
blob7df0d48a0eb3d3a55d605234e00b0faee38013f3
1 /* vi:set ts=4 sts=4 sw=4: */
2 /*
3 * 2005 July 7, Markku Sukanen
4 * - modifying for AROS
6 ** 2001 September 15
7 **
8 ** The author disclaims copyright to this source code. In place of
9 ** a legal notice, here is a blessing:
11 ** May you do good and not evil.
12 ** May you find forgiveness for yourself and forgive others.
13 ** May you share freely, never taking more than you give.
15 *************************************************************************
17 /**
18 * @file main.c
20 * Main file for the SQLite library. The routines in this file implement the
21 * programmer interface to the library. Routines in other files are for
22 * internal use by SQLite and should not be accessed by users of the library.
24 * */
25 /* $Id$ */
26 #include "sqliteInt.h"
27 #include "os.h"
28 #include <ctype.h>
31 * The following constant value is used by the SQLITE_BIGENDIAN and
32 * SQLITE_LITTLEENDIAN macros.
33 * */
34 const int sqlite3one = 1;
36 #ifndef SQLITE_OMIT_GLOBALRECOVER
38 * Linked list of all open database handles. This is used by the
39 * sqlite3_global_recover() function. Entries are added to the list by
40 * openDatabase() and removed by sqlite3_close().
41 * */
42 static sqlite3 *pDbList = 0;
43 #endif
46 #ifndef SQLITE_OMIT_UTF16
48 * Return the transient sqlite3_value object used for encoding conversions
49 * during SQL compilation.
50 * */
51 sqlite3_value *sqlite3GetTransientValue(sqlite3 *db)
53 if( !db->pValue )
54 db->pValue = sqlite3ValueNew();
55 return db->pValue;
57 #endif
61 * The version of the library.
62 * */
63 const char rcsid3[] = "@(#) \044Id: SQLite version " SQLITE_VERSION " $";
64 const char sqlite3_version[] = SQLITE_VERSION;
65 const char *sqlite3_libversion(void){ return sqlite3_version; }
66 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
70 * This is the default collating function named "BINARY" which is always
71 * available.
72 * */
73 static int binCollFunc(
74 void *NotUsed,
75 int nKey1, const void *pKey1,
76 int nKey2, const void *pKey2
79 int rc, n;
80 n = nKey1<nKey2 ? nKey1 : nKey2;
81 rc = memcmp(pKey1, pKey2, n);
82 if( rc==0 )
83 rc = nKey1 - nKey2;
84 return rc;
89 * Another built-in collating sequence: NOCASE.
91 * This collating sequence is intended to be used for "case independant
92 * comparison". SQLite's knowledge of upper and lower case equivalents extends
93 * only to the 26 characters used in the English language.
95 * At the moment there is only a UTF-8 implementation.
96 * */
97 static int nocaseCollatingFunc(
98 void *NotUsed,
99 int nKey1, const void *pKey1,
100 int nKey2, const void *pKey2
103 int r = sqlite3StrNICmp(
104 (const char *)pKey1, (const char *)pKey2,
105 (nKey1<nKey2)?nKey1:nKey2);
106 if( 0==r )
107 r = nKey1-nKey2;
108 return r;
113 * Return the ROWID of the most recent insert.
114 * */
115 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db)
117 return db->lastRowid;
122 * Return the number of changes in the most recent call to sqlite3_exec().
123 * */
124 int sqlite3_changes(sqlite3 *db)
126 return db->nChange;
131 * Return the number of changes since the database handle was opened.
132 * */
133 int sqlite3_total_changes(sqlite3 *db)
135 return db->nTotalChange;
140 * Close an existing SQLite database.
141 * */
142 int sqlite3_close(sqlite3 *db)
144 HashElem *i;
145 int j;
147 if( !db )
148 return SQLITE_OK;
150 if( sqlite3SafetyCheck(db) )
151 return SQLITE_MISUSE;
153 #ifdef SQLITE_SSE
154 sqlite3_finalize(db->pFetch);
155 #endif
157 /* If there are any outstanding VMs, return SQLITE_BUSY. */
158 if( db->pVdbe )
160 sqlite3Error(db, SQLITE_BUSY,
161 "Unable to close due to unfinalised statements");
162 return SQLITE_BUSY;
164 assert( !sqlite3SafetyCheck(db) );
167 * FIX ME: db->magic may be set to SQLITE_MAGIC_CLOSED if the database
168 * cannot be opened for some reason. So this routine needs to run in that
169 * case. But maybe there should be an extra magic value for the "failed to
170 * open" state.
171 * */
172 if( db->magic!=SQLITE_MAGIC_CLOSED && sqlite3SafetyOn(db) )
174 /* printf("DID NOT CLOSE\n"); fflush(stdout); */
175 return SQLITE_ERROR;
178 for(j=0; j<db->nDb; j++)
180 struct Db *pDb = &db->aDb[j];
181 if( pDb->pBt )
183 sqlite3BtreeClose(pDb->pBt);
184 pDb->pBt = NULL;
187 sqlite3ResetInternalSchema(db, 0);
188 assert( db->nDb<=2 );
189 assert( db->aDb==db->aDbStatic );
190 for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i))
192 FuncDef *pFunc, *pNext;
193 for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext)
195 pNext = pFunc->pNext;
196 sqliteFree(pFunc);
200 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i))
202 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
203 sqliteFree(pColl);
205 sqlite3HashClear(&db->aCollSeq);
207 sqlite3HashClear(&db->aFunc);
208 sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
209 if( db->pValue )
210 sqlite3ValueFree(db->pValue);
211 if( db->pErr )
212 sqlite3ValueFree(db->pErr);
213 #ifndef SQLITE_OMIT_GLOBALRECOVER
215 sqlite3 *pPrev;
216 sqlite3OsEnterMutex();
217 pPrev = pDbList;
218 while( pPrev && pPrev->pNext!=db )
219 pPrev = pPrev->pNext;
220 if( pPrev )
221 pPrev->pNext = db->pNext;
222 else
224 assert( pDbList==db );
225 pDbList = db->pNext;
227 sqlite3OsLeaveMutex();
229 #endif
231 db->magic = SQLITE_MAGIC_ERROR;
232 sqliteFree(db);
233 return SQLITE_OK;
238 * Rollback all database files.
239 * */
240 void sqlite3RollbackAll(sqlite3 *db)
242 int i;
243 for(i=0; i<db->nDb; i++)
245 if( db->aDb[i].pBt )
247 sqlite3BtreeRollback(db->aDb[i].pBt);
248 db->aDb[i].inTrans = 0;
251 sqlite3ResetInternalSchema(db, 0);
256 * Return a static string that describes the kind of error specified in the
257 * argument.
258 * */
259 CONST_STRPTR sqlite3ErrStr(int rc)
261 CONST_STRPTR z;
262 switch( rc )
264 case SQLITE_ROW:
265 case SQLITE_DONE:
266 case SQLITE_OK: z = "not an error"; break;
267 case SQLITE_ERROR: z = "SQL logic error or missing database"; break;
268 case SQLITE_INTERNAL:z = "internal SQLite implementation flaw"; break;
269 case SQLITE_PERM: z = "access permission denied"; break;
270 case SQLITE_ABORT: z = "callback requested query abort"; break;
271 case SQLITE_BUSY: z = "database is locked"; break;
272 case SQLITE_LOCKED: z = "database table is locked"; break;
273 case SQLITE_NOMEM: z = "out of memory"; break;
274 case SQLITE_READONLY:z = "attempt to write a readonly database";break;
275 case SQLITE_INTERRUPT: z = "interrupted"; break;
276 case SQLITE_IOERR: z = "disk I/O error"; break;
277 case SQLITE_CORRUPT:z = "database disk image is malformed"; break;
278 case SQLITE_NOTFOUND:z = "table or record not found"; break;
279 case SQLITE_FULL: z = "database is full"; break;
280 case SQLITE_CANTOPEN:z = "unable to open database file"; break;
281 case SQLITE_PROTOCOL:z = "database locking protocol failure"; break;
282 case SQLITE_EMPTY: z = "table contains no data"; break;
283 case SQLITE_SCHEMA: z = "database schema has changed"; break;
284 case SQLITE_TOOBIG: z = "too much data for one table row"; break;
285 case SQLITE_CONSTRAINT:z = "constraint failed"; break;
286 case SQLITE_MISMATCH:z = "datatype mismatch"; break;
287 case SQLITE_MISUSE: z = "library routine called out of sequence";break;
288 case SQLITE_NOLFS: z = "kernel lacks large file support"; break;
289 case SQLITE_AUTH: z = "authorization denied"; break;
290 case SQLITE_FORMAT: z = "auxiliary database format error"; break;
291 case SQLITE_RANGE: z = "bind or column index out of range"; break;
292 case SQLITE_NOTADB: z = "file is encrypted or is not a database";break;
293 default: z = "unknown error"; break;
295 return z;
300 * This routine implements a busy callback that sleeps and tries again until
301 * a timeout value is reached. The timeout value is an integer number of
302 * milliseconds passed in as the first argument.
303 * */
304 static int sqliteDefaultBusyCallback(
305 void *ptr, /* Database connection */
306 int count /* Number of times table has been busy */
309 #if SQLITE_MIN_SLEEP_MS==1
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 int timeout = ((sqlite3 *)ptr)->busyTimeout;
316 int delay, prior;
318 assert( count>=0 );
319 if( count < NDELAY )
321 delay = delays[count];
322 prior = totals[count];
324 else
326 delay = delays[NDELAY-1];
327 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
329 if( prior + delay > timeout )
331 delay = timeout - prior;
332 if( delay<=0 ) return 0;
334 sqlite3OsSleep(delay);
335 return 1;
336 #else
337 int timeout = ((sqlite3 *)ptr)->busyTimeout;
338 if( (count+1)*1000 > timeout )
339 return 0;
340 sqlite3OsSleep(1000);
341 return 1;
342 #endif
347 * This routine sets the busy callback for an Sqlite database to the given
348 * callback function with the given argument.
349 * */
350 int sqlite3_busy_handler(
351 sqlite3 *db,
352 int (*xBusy)(void*,int),
353 void *pArg
356 if( sqlite3SafetyCheck(db) )
357 return SQLITE_MISUSE;
358 db->busyHandler.xFunc = xBusy;
359 db->busyHandler.pArg = pArg;
360 return SQLITE_OK;
364 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
366 * This routine sets the progress callback for an Sqlite database to the given
367 * callback function with the given argument. The progress callback will be
368 * invoked every nOps opcodes.
369 * */
370 void sqlite3_progress_handler(
371 sqlite3 *db,
372 int nOps,
373 int (*xProgress)(void*),
374 void *pArg
377 if( !sqlite3SafetyCheck(db) )
379 if( nOps>0 )
381 db->xProgress = xProgress;
382 db->nProgressOps = nOps;
383 db->pProgressArg = pArg;
385 else
387 db->xProgress = NULL;
388 db->nProgressOps = 0;
389 db->pProgressArg = NULL;
393 #endif
397 * This routine installs a default busy handler that waits for the specified
398 * number of milliseconds before returning 0.
399 * */
400 int sqlite3_busy_timeout(sqlite3 *db, int ms)
402 if( ms>0 )
404 db->busyTimeout = ms;
405 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
407 else sqlite3_busy_handler(db, 0, 0);
408 return SQLITE_OK;
413 * Cause any pending operation to stop at its earliest opportunity.
414 * */
415 void sqlite3_interrupt(sqlite3 *db)
417 if( !sqlite3SafetyCheck(db) )
418 db->flags |= SQLITE_Interrupt;
423 * Windows systems should call this routine to free memory that is returned in
424 * the in the errmsg parameter of sqlite3_open() when SQLite is a DLL. For some
425 * reason, it does not work to call free() directly.
427 * Note that we need to call free() not sqliteFree() here.
428 * */
429 void sqlite3_free(char *p){ free(p); }
433 * Create new user functions.
434 * */
435 int sqlite3_create_function(
436 sqlite3 *db,
437 const char *zFunctionName,
438 int nArg,
439 int enc,
440 void *pUserData,
441 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
442 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
443 void (*xFinal)(sqlite3_context*)
446 FuncDef *p;
447 int nName;
449 if( sqlite3SafetyCheck(db) )
450 return SQLITE_MISUSE;
452 if( zFunctionName==0
453 || (xFunc && (xFinal || xStep))
454 || (!xFunc && (xFinal && !xStep))
455 || (!xFunc && (!xFinal && xStep))
456 || (nArg<-1 || nArg>127)
457 || (255<(nName = strlen(zFunctionName))) )
458 return SQLITE_ERROR;
460 #ifndef SQLITE_OMIT_UTF16
462 * If SQLITE_UTF16 is specified as the encoding type, transform this to one
463 * of SQLITE_UTF16LE or SQLITE_UTF16BE using the SQLITE_UTF16NATIVE macro.
464 * SQLITE_UTF16 is not used internally.
466 * If SQLITE_ANY is specified, add three versions of the function to the
467 * hash table.
468 * */
469 if( enc==SQLITE_UTF16 )
470 enc = SQLITE_UTF16NATIVE;
471 else if( enc==SQLITE_ANY )
473 int rc;
474 rc = sqlite3_create_function(db, zFunctionName, nArg, SQLITE_UTF8,
475 pUserData, xFunc, xStep, xFinal);
476 if( rc!=SQLITE_OK ) return rc;
477 rc = sqlite3_create_function(db, zFunctionName, nArg, SQLITE_UTF16LE,
478 pUserData, xFunc, xStep, xFinal);
479 if( rc!=SQLITE_OK ) return rc;
480 enc = SQLITE_UTF16BE;
482 #else
483 enc = SQLITE_UTF8;
484 #endif
486 * Check if an existing function is being overridden or deleted. If so, and
487 * there are active VMs, then return SQLITE_BUSY. If a function is being
488 * overridden/deleted but there are no active VMs, allow the operation to
489 * continue but invalidate all precompiled statements.
490 * */
491 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
492 if( p && p->iPrefEnc==enc && p->nArg==nArg )
494 if( db->activeVdbeCnt )
496 sqlite3Error(db, SQLITE_BUSY,
497 "Unable to delete/modify user-function due to "
498 "active statements");
499 return SQLITE_BUSY;
501 else sqlite3ExpirePreparedStatements(db);
504 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
505 if( p==0 ) return SQLITE_NOMEM;
506 p->xFunc = xFunc;
507 p->xStep = xStep;
508 p->xFinalize = xFinal;
509 p->pUserData = pUserData;
510 return SQLITE_OK;
514 #ifndef SQLITE_OMIT_UTF16
515 int sqlite3_create_function16(
516 sqlite3 *db,
517 const void *zFunctionName,
518 int nArg,
519 int eTextRep,
520 void *pUserData,
521 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
522 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
523 void (*xFinal)(sqlite3_context*)
526 int rc;
527 char const *zFunc8;
528 sqlite3_value *pTmp;
530 if( sqlite3SafetyCheck(db) )
531 return SQLITE_MISUSE;
533 pTmp = sqlite3GetTransientValue(db);
534 sqlite3ValueSetStr(pTmp, -1, zFunctionName, SQLITE_UTF16NATIVE,
535 SQLITE_STATIC);
536 zFunc8 = sqlite3ValueText(pTmp, SQLITE_UTF8);
538 if( !zFunc8 )
539 return SQLITE_NOMEM;
541 rc = sqlite3_create_function(db, zFunc8, nArg, eTextRep,
542 pUserData, xFunc, xStep, xFinal);
543 return rc;
545 #endif
549 * Register a trace function. The pArg from the previously registered trace is
550 * returned.
552 * A NULL trace function means that no tracing is executes. A non-NULL trace is
553 * a pointer to a function that is invoked at the start of each sqlite3_exec().
554 * */
555 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg)
557 void *pOld = db->pTraceArg;
558 db->xTrace = xTrace;
559 db->pTraceArg = pArg;
560 return pOld;
564 /*** EXPERIMENTAL ***
566 * Register a function to be invoked when a transaction comments. If either
567 * function returns non-zero, then the commit becomes a rollback.
568 * */
569 void *sqlite3_commit_hook(
570 sqlite3 *db, /* Attach the hook to this database */
571 int (*xCallback)(void*), /* Function to invoke on each commit */
572 void *pArg /* Argument to the function */
575 void *pOld = db->pCommitArg;
576 db->xCommitCallback = xCallback;
577 db->pCommitArg = pArg;
578 return pOld;
583 * This routine is called to create a connection to a database BTree driver.
584 * If zFilename is the name of a file, then that file is opened and used. If
585 * zFilename is the magic name ":memory:" then the database is stored in memory
586 * (and is thus forgotten as soon as the connection is closed.) If zFilename is
587 * NULL then the database is for temporary use only and is deleted as soon as
588 * the connection is closed.
590 * A temporary database can be either a disk file (that is automatically
591 * deleted when the file is closed) or a set of red-black trees held in memory,
592 * depending on the values of the TEMP_STORE compile-time macro and the
593 * db->temp_store variable, according to the following chart:
595 * TEMP_STORE db->temp_store Location of temporary database
596 * ---------- -------------- ------------------------------
597 * 0 any file
598 * 1 1 file
599 * 1 2 memory
600 * 1 0 file
601 * 2 1 file
602 * 2 2 memory
603 * 2 0 memory
604 * 3 any memory
605 * */
606 int sqlite3BtreeFactory(
607 const sqlite3 *db, /* Main database when opening aux otherwise 0 */
608 const char *zFilename, /* Name of the file containing the BTree db */
609 int omitJournal, /* if TRUE then do not journal this file */
610 int nCache, /* How many pages in the page cache */
611 Btree **ppBtree /* Pointer to new Btree object written here */
614 int btree_flags = 0;
615 int rc;
617 assert( ppBtree != 0);
618 if( omitJournal )
619 btree_flags |= BTREE_OMIT_JOURNAL;
620 if( db->flags & SQLITE_NoReadlock )
621 btree_flags |= BTREE_NO_READLOCK;
622 if( !zFilename )
624 #if TEMP_STORE==0
625 /* Do nothing */
626 #endif
627 #ifndef SQLITE_OMIT_MEMORYDB
628 #if TEMP_STORE==1
629 if( db->temp_store==2 ) zFilename = ":memory:";
630 #endif
631 #if TEMP_STORE==2
632 if( db->temp_store!=1 ) zFilename = ":memory:";
633 #endif
634 #if TEMP_STORE==3
635 zFilename = ":memory:";
636 #endif
637 #endif /* SQLITE_OMIT_MEMORYDB */
640 rc = sqlite3BtreeOpen(zFilename, ppBtree, btree_flags);
641 if( rc==SQLITE_OK )
643 sqlite3BtreeSetBusyHandler(*ppBtree, (void*)&db->busyHandler);
644 sqlite3BtreeSetCacheSize(*ppBtree, nCache);
646 return rc;
651 * Return UTF-8 encoded English language explanation of the most recent error.
652 * */
653 const char *sqlite3_errmsg(sqlite3 *db)
655 const char *z;
656 if( sqlite3_malloc_failed )
657 return sqlite3ErrStr(SQLITE_NOMEM);
658 if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE )
659 return sqlite3ErrStr(SQLITE_MISUSE);
660 if( !( z = sqlite3_value_text(db->pErr) ))
661 z = sqlite3ErrStr(db->errCode);
662 return z;
666 #ifndef SQLITE_OMIT_UTF16
668 * Return UTF-16 encoded English language explanation of the most recent error.
669 * */
670 const void *sqlite3_errmsg16(sqlite3 *db)
673 * Because all the characters in the string are in the unicode range 0x00-
674 * 0xFF, if we pad the big-endian string with a zero byte, we can obtain
675 * the little-endian string with &big_endian[1].
676 * */
677 static const char outOfMemBe[] = {
678 0, 'o', 0, 'u', 0, 't', 0, ' ',
679 0, 'o', 0, 'f', 0, ' ',
680 0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
682 static const char misuseBe [] = {
683 0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ',
684 0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ',
685 0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ',
686 0, 'o', 0, 'u', 0, 't', 0, ' ',
687 0, 'o', 0, 'f', 0, ' ',
688 0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
690 const void *z;
692 if( sqlite3_malloc_failed )
693 return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
694 if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE )
695 return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
696 if( !( z = sqlite3_value_text16(db->pErr) ))
698 sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
699 SQLITE_UTF8, SQLITE_STATIC);
700 z = sqlite3_value_text16(db->pErr);
702 return z;
704 #endif /* SQLITE_OMIT_UTF16 */
708 * Return the most recent error code generated by an SQLite routine.
709 * */
710 int sqlite3_errcode(sqlite3 *db)
712 if( sqlite3_malloc_failed )
713 return SQLITE_NOMEM;
714 if( sqlite3SafetyCheck(db) )
715 return SQLITE_MISUSE;
716 return db->errCode;
721 * This routine does the work of opening a database on behalf of sqlite3_open()
722 * and sqlite3_open16(). The database filename "zFilename" is UTF-8 encoded.
723 * */
724 static int openDatabase(
725 const char *zFilename, /* Database filename UTF-8 encoded */
726 sqlite3 **ppDb /* OUT: Returned database handle */
729 sqlite3 *db;
730 int rc, i;
732 /* Allocate the sqlite data structure */
733 db = sqliteMalloc( sizeof(sqlite3) );
734 if( db==0 ) goto opendb_out;
735 db->priorNewRowid = 0;
736 db->magic = SQLITE_MAGIC_BUSY;
737 db->nDb = 2;
738 db->aDb = db->aDbStatic;
739 db->enc = SQLITE_UTF8;
740 db->autoCommit = TRUE;
741 db->flags |= SQLITE_ShortColNames;
742 sqlite3HashInit(&db->aFunc, SQLITE_HASH_STRING, 0);
743 sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0);
744 for(i=0; i<db->nDb; i++)
746 sqlite3HashInit(&db->aDb[i].tblHash, SQLITE_HASH_STRING, 0);
747 sqlite3HashInit(&db->aDb[i].idxHash, SQLITE_HASH_STRING, 0);
748 sqlite3HashInit(&db->aDb[i].trigHash, SQLITE_HASH_STRING, 0);
749 sqlite3HashInit(&db->aDb[i].aFKey, SQLITE_HASH_STRING, 1);
753 * Add the default collation sequence BINARY. BINARY works for both UTF-8
754 * and UTF-16, so add a version for each to avoid any unnecessary
755 * conversions. The only error that can occur here is a malloc() failure.
756 * */
757 if( sqlite3_create_collation(db, "BINARY", SQLITE_UTF8, 0,binCollFunc)
758 || sqlite3_create_collation(db, "BINARY", SQLITE_UTF16,
759 0,binCollFunc)
760 || !(db->pDfltColl = sqlite3FindCollSeq(db, db->enc, "BINARY",
761 6, 0)) )
763 rc = db->errCode;
764 assert( rc!=SQLITE_OK );
765 db->magic = SQLITE_MAGIC_CLOSED;
766 goto opendb_out;
769 /* Also add a UTF-8 case-insensitive collation sequence. */
770 sqlite3_create_collation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc);
772 /* Open the backend database driver */
773 rc = sqlite3BtreeFactory(db, zFilename, 0, MAX_PAGES, &db->aDb[0].pBt);
774 if( rc!=SQLITE_OK )
776 sqlite3Error(db, rc, 0);
777 db->magic = SQLITE_MAGIC_CLOSED;
778 goto opendb_out;
782 * The default safety_level for the main database is 'full'; for the temp
783 * database it is 'NONE'. This matches the pager layer defaults.
784 * */
785 db->aDb[0].zName = "main";
786 db->aDb[0].safety_level = 3;
787 #ifndef SQLITE_OMIT_TEMPDB
788 db->aDb[1].zName = "temp";
789 db->aDb[1].safety_level = 1;
790 #endif
793 * Register all built-in functions, but do not attempt to read the database
794 * schema yet. This is delayed until the first time the database is
795 * accessed.
796 * */
797 sqlite3RegisterBuiltinFunctions(db);
798 sqlite3Error(db, SQLITE_OK, 0);
799 db->magic = SQLITE_MAGIC_OPEN;
801 opendb_out:
802 if( sqlite3_errcode(db)==SQLITE_OK && sqlite3_malloc_failed )
803 sqlite3Error(db, SQLITE_NOMEM, 0);
804 *ppDb = db;
805 #ifndef SQLITE_OMIT_GLOBALRECOVER
806 if( db )
808 sqlite3OsEnterMutex();
809 db->pNext = pDbList;
810 pDbList = db;
811 sqlite3OsLeaveMutex();
813 #endif
814 return sqlite3_errcode(db);
819 * Open a new database handle.
820 * */
821 int sqlite3_open( const char *zFilename, sqlite3 **ppDb )
823 return openDatabase(zFilename, ppDb);
827 #ifndef SQLITE_OMIT_UTF16
829 * Open a new database handle.
830 * */
831 int sqlite3_open16( const void *zFilename, sqlite3 **ppDb )
833 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
834 int rc = SQLITE_NOMEM;
835 sqlite3_value *pVal;
837 assert( ppDb );
838 *ppDb = 0;
839 pVal = sqlite3ValueNew();
840 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
841 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
842 if( zFilename8 )
844 rc = openDatabase(zFilename8, ppDb);
845 if( rc==SQLITE_OK && *ppDb )
846 sqlite3_exec(*ppDb, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);
848 if( pVal )
849 sqlite3ValueFree(pVal);
851 return rc;
853 #endif /* SQLITE_OMIT_UTF16 */
857 ** The following routine destroys a virtual machine that is created by
858 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
859 ** success/failure code that describes the result of executing the virtual
860 ** machine.
862 ** This routine sets the error code and string returned by
863 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
865 int sqlite3_finalize(sqlite3_stmt *pStmt){
866 int rc;
867 if( pStmt==0 ){
868 rc = SQLITE_OK;
869 }else{
870 rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
872 return rc;
876 ** Terminate the current execution of an SQL statement and reset it
877 ** back to its starting state so that it can be reused. A success code from
878 ** the prior execution is returned.
880 ** This routine sets the error code and string returned by
881 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
883 int sqlite3_reset(sqlite3_stmt *pStmt){
884 int rc;
885 if( pStmt==0 ){
886 rc = SQLITE_OK;
887 }else{
888 rc = sqlite3VdbeReset((Vdbe*)pStmt);
889 sqlite3VdbeMakeReady((Vdbe*)pStmt, -1, 0, 0, 0, 0);
891 return rc;
895 ** Register a new collation sequence with the database handle db.
897 int sqlite3_create_collation(
898 sqlite3* db,
899 const char *zName,
900 int enc,
901 void* pCtx,
902 int(*xCompare)(void*,int,const void*,int,const void*)
904 CollSeq *pColl;
905 int rc = SQLITE_OK;
907 if( sqlite3SafetyCheck(db) ){
908 return SQLITE_MISUSE;
911 /* If SQLITE_UTF16 is specified as the encoding type, transform this
912 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
913 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
915 if( enc==SQLITE_UTF16 ){
916 enc = SQLITE_UTF16NATIVE;
919 if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16LE && enc!=SQLITE_UTF16BE ){
920 sqlite3Error(db, SQLITE_ERROR,
921 "Param 3 to sqlite3_create_collation() must be one of "
922 "SQLITE_UTF8, SQLITE_UTF16, SQLITE_UTF16LE or SQLITE_UTF16BE"
924 return SQLITE_ERROR;
927 /* Check if this call is removing or replacing an existing collation
928 ** sequence. If so, and there are active VMs, return busy. If there
929 ** are no active VMs, invalidate any pre-compiled statements.
931 pColl = sqlite3FindCollSeq(db, (u8)enc, zName, strlen(zName), 0);
932 if( pColl && pColl->xCmp ){
933 if( db->activeVdbeCnt ){
934 sqlite3Error(db, SQLITE_BUSY,
935 "Unable to delete/modify collation sequence due to active statements");
936 return SQLITE_BUSY;
938 sqlite3ExpirePreparedStatements(db);
941 pColl = sqlite3FindCollSeq(db, (u8)enc, zName, strlen(zName), 1);
942 if( 0==pColl ){
943 rc = SQLITE_NOMEM;
944 }else{
945 pColl->xCmp = xCompare;
946 pColl->pUser = pCtx;
947 pColl->enc = enc;
949 sqlite3Error(db, rc, 0);
950 return rc;
953 #ifndef SQLITE_OMIT_UTF16
955 ** Register a new collation sequence with the database handle db.
957 int sqlite3_create_collation16(
958 sqlite3* db,
959 const char *zName,
960 int enc,
961 void* pCtx,
962 int(*xCompare)(void*,int,const void*,int,const void*)
964 char const *zName8;
965 sqlite3_value *pTmp;
966 if( sqlite3SafetyCheck(db) ){
967 return SQLITE_MISUSE;
969 pTmp = sqlite3GetTransientValue(db);
970 sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF16NATIVE, SQLITE_STATIC);
971 zName8 = sqlite3ValueText(pTmp, SQLITE_UTF8);
972 return sqlite3_create_collation(db, zName8, enc, pCtx, xCompare);
974 #endif /* SQLITE_OMIT_UTF16 */
977 ** Register a collation sequence factory callback with the database handle
978 ** db. Replace any previously installed collation sequence factory.
980 int sqlite3_collation_needed(
981 sqlite3 *db,
982 void *pCollNeededArg,
983 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
985 if( sqlite3SafetyCheck(db) ){
986 return SQLITE_MISUSE;
988 db->xCollNeeded = xCollNeeded;
989 db->xCollNeeded16 = 0;
990 db->pCollNeededArg = pCollNeededArg;
991 return SQLITE_OK;
994 #ifndef SQLITE_OMIT_UTF16
996 ** Register a collation sequence factory callback with the database handle
997 ** db. Replace any previously installed collation sequence factory.
999 int sqlite3_collation_needed16(
1000 sqlite3 *db,
1001 void *pCollNeededArg,
1002 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
1004 if( sqlite3SafetyCheck(db) ){
1005 return SQLITE_MISUSE;
1007 db->xCollNeeded = 0;
1008 db->xCollNeeded16 = xCollNeeded16;
1009 db->pCollNeededArg = pCollNeededArg;
1010 return SQLITE_OK;
1012 #endif /* SQLITE_OMIT_UTF16 */
1014 #ifndef SQLITE_OMIT_GLOBALRECOVER
1016 ** This function is called to recover from a malloc failure that occured
1017 ** within SQLite.
1019 ** This function is *not* threadsafe. Calling this from within a threaded
1020 ** application when threads other than the caller have used SQLite is
1021 ** dangerous and will almost certainly result in malfunctions.
1023 int sqlite3_global_recover(){
1024 int rc = SQLITE_OK;
1026 if( sqlite3_malloc_failed ){
1027 sqlite3 *db;
1028 int i;
1029 sqlite3_malloc_failed = 0;
1030 for(db=pDbList; db; db=db->pNext ){
1031 sqlite3ExpirePreparedStatements(db);
1032 for(i=0; i<db->nDb; i++){
1033 Btree *pBt = db->aDb[i].pBt;
1034 if( pBt && (rc=sqlite3BtreeReset(pBt)) ){
1035 goto recover_out;
1038 db->autoCommit = 1;
1042 recover_out:
1043 if( rc!=SQLITE_OK ){
1044 sqlite3_malloc_failed = 1;
1046 return rc;
1048 #endif
1051 ** Test to see whether or not the database connection is in autocommit
1052 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
1053 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
1054 ** by the next COMMIT or ROLLBACK.
1056 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
1058 int sqlite3_get_autocommit(sqlite3 *db){
1059 return db->autoCommit;