main.c 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486
  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.409 2007/12/07 18:55:28 drh Exp $
  18. */
  19. #include "sqliteInt.h"
  20. #include <ctype.h>
  21. /*
  22. ** The version of the library
  23. */
  24. const char sqlite3_version[] = SQLITE_VERSION;
  25. const char *sqlite3_libversion(void){ return sqlite3_version; }
  26. int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  27. int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  28. /*
  29. ** If the following function pointer is not NULL and if
  30. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  31. ** I/O active are written using this function. These messages
  32. ** are intended for debugging activity only.
  33. */
  34. void (*sqlite3_io_trace)(const char*, ...) = 0;
  35. /*
  36. ** If the following global variable points to a string which is the
  37. ** name of a directory, then that directory will be used to store
  38. ** temporary files.
  39. **
  40. ** See also the "PRAGMA temp_store_directory" SQL command.
  41. */
  42. char *sqlite3_temp_directory = 0;
  43. /*
  44. ** This is the default collating function named "BINARY" which is always
  45. ** available.
  46. */
  47. static int binCollFunc(
  48. void *NotUsed,
  49. int nKey1, const void *pKey1,
  50. int nKey2, const void *pKey2
  51. ){
  52. int rc, n;
  53. n = nKey1<nKey2 ? nKey1 : nKey2;
  54. rc = memcmp(pKey1, pKey2, n);
  55. if( rc==0 ){
  56. rc = nKey1 - nKey2;
  57. }
  58. return rc;
  59. }
  60. /*
  61. ** Another built-in collating sequence: NOCASE.
  62. **
  63. ** This collating sequence is intended to be used for "case independant
  64. ** comparison". SQLite's knowledge of upper and lower case equivalents
  65. ** extends only to the 26 characters used in the English language.
  66. **
  67. ** At the moment there is only a UTF-8 implementation.
  68. */
  69. static int nocaseCollatingFunc(
  70. void *NotUsed,
  71. int nKey1, const void *pKey1,
  72. int nKey2, const void *pKey2
  73. ){
  74. int r = sqlite3StrNICmp(
  75. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  76. if( 0==r ){
  77. r = nKey1-nKey2;
  78. }
  79. return r;
  80. }
  81. /*
  82. ** Return the ROWID of the most recent insert
  83. */
  84. sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  85. return db->lastRowid;
  86. }
  87. /*
  88. ** Return the number of changes in the most recent call to sqlite3_exec().
  89. */
  90. int sqlite3_changes(sqlite3 *db){
  91. return db->nChange;
  92. }
  93. /*
  94. ** Return the number of changes since the database handle was opened.
  95. */
  96. int sqlite3_total_changes(sqlite3 *db){
  97. return db->nTotalChange;
  98. }
  99. /*
  100. ** Close an existing SQLite database
  101. */
  102. int sqlite3_close(sqlite3 *db){
  103. HashElem *i;
  104. int j;
  105. if( !db ){
  106. return SQLITE_OK;
  107. }
  108. if( sqlite3SafetyCheck(db) ){
  109. return SQLITE_MISUSE;
  110. }
  111. sqlite3_mutex_enter(db->mutex);
  112. #ifdef SQLITE_SSE
  113. {
  114. extern void sqlite3SseCleanup(sqlite3*);
  115. sqlite3SseCleanup(db);
  116. }
  117. #endif
  118. sqlite3ResetInternalSchema(db, 0);
  119. /* If a transaction is open, the ResetInternalSchema() call above
  120. ** will not have called the xDisconnect() method on any virtual
  121. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  122. ** call will do so. We need to do this before the check for active
  123. ** SQL statements below, as the v-table implementation may be storing
  124. ** some prepared statements internally.
  125. */
  126. sqlite3VtabRollback(db);
  127. /* If there are any outstanding VMs, return SQLITE_BUSY. */
  128. if( db->pVdbe ){
  129. sqlite3Error(db, SQLITE_BUSY,
  130. "Unable to close due to unfinalised statements");
  131. sqlite3_mutex_leave(db->mutex);
  132. return SQLITE_BUSY;
  133. }
  134. assert( !sqlite3SafetyCheck(db) );
  135. /* FIX ME: db->magic may be set to SQLITE_MAGIC_CLOSED if the database
  136. ** cannot be opened for some reason. So this routine needs to run in
  137. ** that case. But maybe there should be an extra magic value for the
  138. ** "failed to open" state.
  139. **
  140. ** TODO: Coverage tests do not test the case where this condition is
  141. ** true. It's hard to see how to cause it without messing with threads.
  142. */
  143. if( db->magic!=SQLITE_MAGIC_CLOSED && sqlite3SafetyOn(db) ){
  144. /* printf("DID NOT CLOSE\n"); fflush(stdout); */
  145. sqlite3_mutex_leave(db->mutex);
  146. return SQLITE_ERROR;
  147. }
  148. for(j=0; j<db->nDb; j++){
  149. struct Db *pDb = &db->aDb[j];
  150. if( pDb->pBt ){
  151. sqlite3BtreeClose(pDb->pBt);
  152. pDb->pBt = 0;
  153. if( j!=1 ){
  154. pDb->pSchema = 0;
  155. }
  156. }
  157. }
  158. sqlite3ResetInternalSchema(db, 0);
  159. assert( db->nDb<=2 );
  160. assert( db->aDb==db->aDbStatic );
  161. for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
  162. FuncDef *pFunc, *pNext;
  163. for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
  164. pNext = pFunc->pNext;
  165. sqlite3_free(pFunc);
  166. }
  167. }
  168. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  169. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  170. /* Invoke any destructors registered for collation sequence user data. */
  171. for(j=0; j<3; j++){
  172. if( pColl[j].xDel ){
  173. pColl[j].xDel(pColl[j].pUser);
  174. }
  175. }
  176. sqlite3_free(pColl);
  177. }
  178. sqlite3HashClear(&db->aCollSeq);
  179. #ifndef SQLITE_OMIT_VIRTUALTABLE
  180. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  181. Module *pMod = (Module *)sqliteHashData(i);
  182. if( pMod->xDestroy ){
  183. pMod->xDestroy(pMod->pAux);
  184. }
  185. sqlite3_free(pMod);
  186. }
  187. sqlite3HashClear(&db->aModule);
  188. #endif
  189. sqlite3HashClear(&db->aFunc);
  190. sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
  191. if( db->pErr ){
  192. sqlite3ValueFree(db->pErr);
  193. }
  194. sqlite3CloseExtensions(db);
  195. db->magic = SQLITE_MAGIC_ERROR;
  196. /* The temp-database schema is allocated differently from the other schema
  197. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  198. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  199. ** the same sqliteMalloc() as the one that allocates the database
  200. ** structure?
  201. */
  202. sqlite3_free(db->aDb[1].pSchema);
  203. sqlite3_mutex_leave(db->mutex);
  204. sqlite3_mutex_free(db->mutex);
  205. sqlite3_free(db);
  206. return SQLITE_OK;
  207. }
  208. /*
  209. ** Rollback all database files.
  210. */
  211. void sqlite3RollbackAll(sqlite3 *db){
  212. int i;
  213. int inTrans = 0;
  214. assert( sqlite3_mutex_held(db->mutex) );
  215. sqlite3MallocEnterBenignBlock(1); /* Enter benign region */
  216. for(i=0; i<db->nDb; i++){
  217. if( db->aDb[i].pBt ){
  218. if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
  219. inTrans = 1;
  220. }
  221. sqlite3BtreeRollback(db->aDb[i].pBt);
  222. db->aDb[i].inTrans = 0;
  223. }
  224. }
  225. sqlite3VtabRollback(db);
  226. sqlite3MallocLeaveBenignBlock(); /* Leave benign region */
  227. if( db->flags&SQLITE_InternChanges ){
  228. sqlite3ExpirePreparedStatements(db);
  229. sqlite3ResetInternalSchema(db, 0);
  230. }
  231. /* If one has been configured, invoke the rollback-hook callback */
  232. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  233. db->xRollbackCallback(db->pRollbackArg);
  234. }
  235. }
  236. /*
  237. ** Return a static string that describes the kind of error specified in the
  238. ** argument.
  239. */
  240. const char *sqlite3ErrStr(int rc){
  241. const char *z;
  242. switch( rc & 0xff ){
  243. case SQLITE_ROW:
  244. case SQLITE_DONE:
  245. case SQLITE_OK: z = "not an error"; break;
  246. case SQLITE_ERROR: z = "SQL logic error or missing database"; break;
  247. case SQLITE_PERM: z = "access permission denied"; break;
  248. case SQLITE_ABORT: z = "callback requested query abort"; break;
  249. case SQLITE_BUSY: z = "database is locked"; break;
  250. case SQLITE_LOCKED: z = "database table is locked"; break;
  251. case SQLITE_NOMEM: z = "out of memory"; break;
  252. case SQLITE_READONLY: z = "attempt to write a readonly database"; break;
  253. case SQLITE_INTERRUPT: z = "interrupted"; break;
  254. case SQLITE_IOERR: z = "disk I/O error"; break;
  255. case SQLITE_CORRUPT: z = "database disk image is malformed"; break;
  256. case SQLITE_FULL: z = "database or disk is full"; break;
  257. case SQLITE_CANTOPEN: z = "unable to open database file"; break;
  258. case SQLITE_EMPTY: z = "table contains no data"; break;
  259. case SQLITE_SCHEMA: z = "database schema has changed"; break;
  260. case SQLITE_TOOBIG: z = "String or BLOB exceeded size limit"; break;
  261. case SQLITE_CONSTRAINT: z = "constraint failed"; break;
  262. case SQLITE_MISMATCH: z = "datatype mismatch"; break;
  263. case SQLITE_MISUSE: z = "library routine called out of sequence";break;
  264. case SQLITE_NOLFS: z = "kernel lacks large file support"; break;
  265. case SQLITE_AUTH: z = "authorization denied"; break;
  266. case SQLITE_FORMAT: z = "auxiliary database format error"; break;
  267. case SQLITE_RANGE: z = "bind or column index out of range"; break;
  268. case SQLITE_NOTADB: z = "file is encrypted or is not a database";break;
  269. default: z = "unknown error"; break;
  270. }
  271. return z;
  272. }
  273. /*
  274. ** This routine implements a busy callback that sleeps and tries
  275. ** again until a timeout value is reached. The timeout value is
  276. ** an integer number of milliseconds passed in as the first
  277. ** argument.
  278. */
  279. static int sqliteDefaultBusyCallback(
  280. void *ptr, /* Database connection */
  281. int count /* Number of times table has been busy */
  282. ){
  283. #if OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  284. static const u8 delays[] =
  285. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  286. static const u8 totals[] =
  287. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  288. # define NDELAY (sizeof(delays)/sizeof(delays[0]))
  289. sqlite3 *db = (sqlite3 *)ptr;
  290. int timeout = db->busyTimeout;
  291. int delay, prior;
  292. assert( count>=0 );
  293. if( count < NDELAY ){
  294. delay = delays[count];
  295. prior = totals[count];
  296. }else{
  297. delay = delays[NDELAY-1];
  298. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  299. }
  300. if( prior + delay > timeout ){
  301. delay = timeout - prior;
  302. if( delay<=0 ) return 0;
  303. }
  304. sqlite3OsSleep(db->pVfs, delay*1000);
  305. return 1;
  306. #else
  307. sqlite3 *db = (sqlite3 *)ptr;
  308. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  309. if( (count+1)*1000 > timeout ){
  310. return 0;
  311. }
  312. sqlite3OsSleep(db->pVfs, 1000000);
  313. return 1;
  314. #endif
  315. }
  316. /*
  317. ** Invoke the given busy handler.
  318. **
  319. ** This routine is called when an operation failed with a lock.
  320. ** If this routine returns non-zero, the lock is retried. If it
  321. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  322. */
  323. int sqlite3InvokeBusyHandler(BusyHandler *p){
  324. int rc;
  325. if( p==0 || p->xFunc==0 || p->nBusy<0 ) return 0;
  326. rc = p->xFunc(p->pArg, p->nBusy);
  327. if( rc==0 ){
  328. p->nBusy = -1;
  329. }else{
  330. p->nBusy++;
  331. }
  332. return rc;
  333. }
  334. /*
  335. ** This routine sets the busy callback for an Sqlite database to the
  336. ** given callback function with the given argument.
  337. */
  338. int sqlite3_busy_handler(
  339. sqlite3 *db,
  340. int (*xBusy)(void*,int),
  341. void *pArg
  342. ){
  343. if( sqlite3SafetyCheck(db) ){
  344. return SQLITE_MISUSE;
  345. }
  346. sqlite3_mutex_enter(db->mutex);
  347. db->busyHandler.xFunc = xBusy;
  348. db->busyHandler.pArg = pArg;
  349. db->busyHandler.nBusy = 0;
  350. sqlite3_mutex_leave(db->mutex);
  351. return SQLITE_OK;
  352. }
  353. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  354. /*
  355. ** This routine sets the progress callback for an Sqlite database to the
  356. ** given callback function with the given argument. The progress callback will
  357. ** be invoked every nOps opcodes.
  358. */
  359. void sqlite3_progress_handler(
  360. sqlite3 *db,
  361. int nOps,
  362. int (*xProgress)(void*),
  363. void *pArg
  364. ){
  365. if( !sqlite3SafetyCheck(db) ){
  366. sqlite3_mutex_enter(db->mutex);
  367. if( nOps>0 ){
  368. db->xProgress = xProgress;
  369. db->nProgressOps = nOps;
  370. db->pProgressArg = pArg;
  371. }else{
  372. db->xProgress = 0;
  373. db->nProgressOps = 0;
  374. db->pProgressArg = 0;
  375. }
  376. sqlite3_mutex_leave(db->mutex);
  377. }
  378. }
  379. #endif
  380. /*
  381. ** This routine installs a default busy handler that waits for the
  382. ** specified number of milliseconds before returning 0.
  383. */
  384. int sqlite3_busy_timeout(sqlite3 *db, int ms){
  385. if( sqlite3SafetyCheck(db) ){
  386. return SQLITE_MISUSE;
  387. }
  388. if( ms>0 ){
  389. db->busyTimeout = ms;
  390. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  391. }else{
  392. sqlite3_busy_handler(db, 0, 0);
  393. }
  394. return SQLITE_OK;
  395. }
  396. /*
  397. ** Cause any pending operation to stop at its earliest opportunity.
  398. */
  399. void sqlite3_interrupt(sqlite3 *db){
  400. if( db && (db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_BUSY) ){
  401. db->u1.isInterrupted = 1;
  402. }
  403. }
  404. /*
  405. ** This function is exactly the same as sqlite3_create_function(), except
  406. ** that it is designed to be called by internal code. The difference is
  407. ** that if a malloc() fails in sqlite3_create_function(), an error code
  408. ** is returned and the mallocFailed flag cleared.
  409. */
  410. int sqlite3CreateFunc(
  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. assert( sqlite3_mutex_held(db->mutex) );
  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. sqlite3Error(db, SQLITE_ERROR, "bad parameters");
  433. return SQLITE_ERROR;
  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 = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
  448. pUserData, xFunc, xStep, xFinal);
  449. if( rc==SQLITE_OK ){
  450. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
  451. pUserData, xFunc, xStep, xFinal);
  452. }
  453. if( rc!=SQLITE_OK ){
  454. return rc;
  455. }
  456. enc = SQLITE_UTF16BE;
  457. }
  458. #else
  459. enc = SQLITE_UTF8;
  460. #endif
  461. /* Check if an existing function is being overridden or deleted. If so,
  462. ** and there are active VMs, then return SQLITE_BUSY. If a function
  463. ** is being overridden/deleted but there are no active VMs, allow the
  464. ** operation to continue but invalidate all precompiled statements.
  465. */
  466. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
  467. if( p && p->iPrefEnc==enc && p->nArg==nArg ){
  468. if( db->activeVdbeCnt ){
  469. sqlite3Error(db, SQLITE_BUSY,
  470. "Unable to delete/modify user-function due to active statements");
  471. assert( !db->mallocFailed );
  472. return SQLITE_BUSY;
  473. }else{
  474. sqlite3ExpirePreparedStatements(db);
  475. }
  476. }
  477. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
  478. assert(p || db->mallocFailed);
  479. if( !p ){
  480. return SQLITE_NOMEM;
  481. }
  482. p->flags = 0;
  483. p->xFunc = xFunc;
  484. p->xStep = xStep;
  485. p->xFinalize = xFinal;
  486. p->pUserData = pUserData;
  487. p->nArg = nArg;
  488. return SQLITE_OK;
  489. }
  490. /*
  491. ** Create new user functions.
  492. */
  493. int sqlite3_create_function(
  494. sqlite3 *db,
  495. const char *zFunctionName,
  496. int nArg,
  497. int enc,
  498. void *p,
  499. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  500. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  501. void (*xFinal)(sqlite3_context*)
  502. ){
  503. int rc;
  504. sqlite3_mutex_enter(db->mutex);
  505. assert( !db->mallocFailed );
  506. rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
  507. rc = sqlite3ApiExit(db, rc);
  508. sqlite3_mutex_leave(db->mutex);
  509. return rc;
  510. }
  511. #ifndef SQLITE_OMIT_UTF16
  512. int sqlite3_create_function16(
  513. sqlite3 *db,
  514. const void *zFunctionName,
  515. int nArg,
  516. int eTextRep,
  517. void *p,
  518. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  519. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  520. void (*xFinal)(sqlite3_context*)
  521. ){
  522. int rc;
  523. char *zFunc8;
  524. sqlite3_mutex_enter(db->mutex);
  525. assert( !db->mallocFailed );
  526. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
  527. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
  528. sqlite3_free(zFunc8);
  529. rc = sqlite3ApiExit(db, rc);
  530. sqlite3_mutex_leave(db->mutex);
  531. return rc;
  532. }
  533. #endif
  534. /*
  535. ** Declare that a function has been overloaded by a virtual table.
  536. **
  537. ** If the function already exists as a regular global function, then
  538. ** this routine is a no-op. If the function does not exist, then create
  539. ** a new one that always throws a run-time error.
  540. **
  541. ** When virtual tables intend to provide an overloaded function, they
  542. ** should call this routine to make sure the global function exists.
  543. ** A global function must exist in order for name resolution to work
  544. ** properly.
  545. */
  546. int sqlite3_overload_function(
  547. sqlite3 *db,
  548. const char *zName,
  549. int nArg
  550. ){
  551. int nName = strlen(zName);
  552. int rc;
  553. sqlite3_mutex_enter(db->mutex);
  554. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  555. sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  556. 0, sqlite3InvalidFunction, 0, 0);
  557. }
  558. rc = sqlite3ApiExit(db, SQLITE_OK);
  559. sqlite3_mutex_leave(db->mutex);
  560. return rc;
  561. }
  562. #ifndef SQLITE_OMIT_TRACE
  563. /*
  564. ** Register a trace function. The pArg from the previously registered trace
  565. ** is returned.
  566. **
  567. ** A NULL trace function means that no tracing is executes. A non-NULL
  568. ** trace is a pointer to a function that is invoked at the start of each
  569. ** SQL statement.
  570. */
  571. void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  572. void *pOld;
  573. sqlite3_mutex_enter(db->mutex);
  574. pOld = db->pTraceArg;
  575. db->xTrace = xTrace;
  576. db->pTraceArg = pArg;
  577. sqlite3_mutex_leave(db->mutex);
  578. return pOld;
  579. }
  580. /*
  581. ** Register a profile function. The pArg from the previously registered
  582. ** profile function is returned.
  583. **
  584. ** A NULL profile function means that no profiling is executes. A non-NULL
  585. ** profile is a pointer to a function that is invoked at the conclusion of
  586. ** each SQL statement that is run.
  587. */
  588. void *sqlite3_profile(
  589. sqlite3 *db,
  590. void (*xProfile)(void*,const char*,sqlite_uint64),
  591. void *pArg
  592. ){
  593. void *pOld;
  594. sqlite3_mutex_enter(db->mutex);
  595. pOld = db->pProfileArg;
  596. db->xProfile = xProfile;
  597. db->pProfileArg = pArg;
  598. sqlite3_mutex_leave(db->mutex);
  599. return pOld;
  600. }
  601. #endif /* SQLITE_OMIT_TRACE */
  602. /*** EXPERIMENTAL ***
  603. **
  604. ** Register a function to be invoked when a transaction comments.
  605. ** If the invoked function returns non-zero, then the commit becomes a
  606. ** rollback.
  607. */
  608. void *sqlite3_commit_hook(
  609. sqlite3 *db, /* Attach the hook to this database */
  610. int (*xCallback)(void*), /* Function to invoke on each commit */
  611. void *pArg /* Argument to the function */
  612. ){
  613. void *pOld;
  614. sqlite3_mutex_enter(db->mutex);
  615. pOld = db->pCommitArg;
  616. db->xCommitCallback = xCallback;
  617. db->pCommitArg = pArg;
  618. sqlite3_mutex_leave(db->mutex);
  619. return pOld;
  620. }
  621. /*
  622. ** Register a callback to be invoked each time a row is updated,
  623. ** inserted or deleted using this database connection.
  624. */
  625. void *sqlite3_update_hook(
  626. sqlite3 *db, /* Attach the hook to this database */
  627. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  628. void *pArg /* Argument to the function */
  629. ){
  630. void *pRet;
  631. sqlite3_mutex_enter(db->mutex);
  632. pRet = db->pUpdateArg;
  633. db->xUpdateCallback = xCallback;
  634. db->pUpdateArg = pArg;
  635. sqlite3_mutex_leave(db->mutex);
  636. return pRet;
  637. }
  638. /*
  639. ** Register a callback to be invoked each time a transaction is rolled
  640. ** back by this database connection.
  641. */
  642. void *sqlite3_rollback_hook(
  643. sqlite3 *db, /* Attach the hook to this database */
  644. void (*xCallback)(void*), /* Callback function */
  645. void *pArg /* Argument to the function */
  646. ){
  647. void *pRet;
  648. sqlite3_mutex_enter(db->mutex);
  649. pRet = db->pRollbackArg;
  650. db->xRollbackCallback = xCallback;
  651. db->pRollbackArg = pArg;
  652. sqlite3_mutex_leave(db->mutex);
  653. return pRet;
  654. }
  655. /*
  656. ** This routine is called to create a connection to a database BTree
  657. ** driver. If zFilename is the name of a file, then that file is
  658. ** opened and used. If zFilename is the magic name ":memory:" then
  659. ** the database is stored in memory (and is thus forgotten as soon as
  660. ** the connection is closed.) If zFilename is NULL then the database
  661. ** is a "virtual" database for transient use only and is deleted as
  662. ** soon as the connection is closed.
  663. **
  664. ** A virtual database can be either a disk file (that is automatically
  665. ** deleted when the file is closed) or it an be held entirely in memory,
  666. ** depending on the values of the TEMP_STORE compile-time macro and the
  667. ** db->temp_store variable, according to the following chart:
  668. **
  669. ** TEMP_STORE db->temp_store Location of temporary database
  670. ** ---------- -------------- ------------------------------
  671. ** 0 any file
  672. ** 1 1 file
  673. ** 1 2 memory
  674. ** 1 0 file
  675. ** 2 1 file
  676. ** 2 2 memory
  677. ** 2 0 memory
  678. ** 3 any memory
  679. */
  680. int sqlite3BtreeFactory(
  681. const sqlite3 *db, /* Main database when opening aux otherwise 0 */
  682. const char *zFilename, /* Name of the file containing the BTree database */
  683. int omitJournal, /* if TRUE then do not journal this file */
  684. int nCache, /* How many pages in the page cache */
  685. int vfsFlags, /* Flags passed through to vfsOpen */
  686. Btree **ppBtree /* Pointer to new Btree object written here */
  687. ){
  688. int btFlags = 0;
  689. int rc;
  690. assert( sqlite3_mutex_held(db->mutex) );
  691. assert( ppBtree != 0);
  692. if( omitJournal ){
  693. btFlags |= BTREE_OMIT_JOURNAL;
  694. }
  695. if( db->flags & SQLITE_NoReadlock ){
  696. btFlags |= BTREE_NO_READLOCK;
  697. }
  698. if( zFilename==0 ){
  699. #if TEMP_STORE==0
  700. /* Do nothing */
  701. #endif
  702. #ifndef SQLITE_OMIT_MEMORYDB
  703. #if TEMP_STORE==1
  704. if( db->temp_store==2 ) zFilename = ":memory:";
  705. #endif
  706. #if TEMP_STORE==2
  707. if( db->temp_store!=1 ) zFilename = ":memory:";
  708. #endif
  709. #if TEMP_STORE==3
  710. zFilename = ":memory:";
  711. #endif
  712. #endif /* SQLITE_OMIT_MEMORYDB */
  713. }
  714. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
  715. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  716. }
  717. rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
  718. if( rc==SQLITE_OK ){
  719. sqlite3BtreeSetCacheSize(*ppBtree, nCache);
  720. }
  721. return rc;
  722. }
  723. /*
  724. ** Return UTF-8 encoded English language explanation of the most recent
  725. ** error.
  726. */
  727. const char *sqlite3_errmsg(sqlite3 *db){
  728. const char *z;
  729. if( !db ){
  730. return sqlite3ErrStr(SQLITE_NOMEM);
  731. }
  732. if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
  733. return sqlite3ErrStr(SQLITE_MISUSE);
  734. }
  735. sqlite3_mutex_enter(db->mutex);
  736. assert( !db->mallocFailed );
  737. z = (char*)sqlite3_value_text(db->pErr);
  738. if( z==0 ){
  739. z = sqlite3ErrStr(db->errCode);
  740. }
  741. sqlite3_mutex_leave(db->mutex);
  742. return z;
  743. }
  744. #ifndef SQLITE_OMIT_UTF16
  745. /*
  746. ** Return UTF-16 encoded English language explanation of the most recent
  747. ** error.
  748. */
  749. const void *sqlite3_errmsg16(sqlite3 *db){
  750. /* Because all the characters in the string are in the unicode
  751. ** range 0x00-0xFF, if we pad the big-endian string with a
  752. ** zero byte, we can obtain the little-endian string with
  753. ** &big_endian[1].
  754. */
  755. static const char outOfMemBe[] = {
  756. 0, 'o', 0, 'u', 0, 't', 0, ' ',
  757. 0, 'o', 0, 'f', 0, ' ',
  758. 0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
  759. };
  760. static const char misuseBe [] = {
  761. 0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ',
  762. 0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ',
  763. 0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ',
  764. 0, 'o', 0, 'u', 0, 't', 0, ' ',
  765. 0, 'o', 0, 'f', 0, ' ',
  766. 0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
  767. };
  768. const void *z;
  769. if( !db ){
  770. return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
  771. }
  772. if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
  773. return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
  774. }
  775. sqlite3_mutex_enter(db->mutex);
  776. assert( !db->mallocFailed );
  777. z = sqlite3_value_text16(db->pErr);
  778. if( z==0 ){
  779. sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
  780. SQLITE_UTF8, SQLITE_STATIC);
  781. z = sqlite3_value_text16(db->pErr);
  782. }
  783. sqlite3ApiExit(0, 0);
  784. sqlite3_mutex_leave(db->mutex);
  785. return z;
  786. }
  787. #endif /* SQLITE_OMIT_UTF16 */
  788. /*
  789. ** Return the most recent error code generated by an SQLite routine. If NULL is
  790. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  791. */
  792. int sqlite3_errcode(sqlite3 *db){
  793. if( !db || db->mallocFailed ){
  794. return SQLITE_NOMEM;
  795. }
  796. if( sqlite3SafetyCheck(db) ){
  797. return SQLITE_MISUSE;
  798. }
  799. return db->errCode & db->errMask;
  800. }
  801. /*
  802. ** Create a new collating function for database "db". The name is zName
  803. ** and the encoding is enc.
  804. */
  805. static int createCollation(
  806. sqlite3* db,
  807. const char *zName,
  808. int enc,
  809. void* pCtx,
  810. int(*xCompare)(void*,int,const void*,int,const void*),
  811. void(*xDel)(void*)
  812. ){
  813. CollSeq *pColl;
  814. int enc2;
  815. if( sqlite3SafetyCheck(db) ){
  816. return SQLITE_MISUSE;
  817. }
  818. assert( sqlite3_mutex_held(db->mutex) );
  819. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  820. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  821. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  822. */
  823. enc2 = enc & ~SQLITE_UTF16_ALIGNED;
  824. if( enc2==SQLITE_UTF16 ){
  825. enc2 = SQLITE_UTF16NATIVE;
  826. }
  827. if( (enc2&~3)!=0 ){
  828. sqlite3Error(db, SQLITE_ERROR, "unknown encoding");
  829. return SQLITE_ERROR;
  830. }
  831. /* Check if this call is removing or replacing an existing collation
  832. ** sequence. If so, and there are active VMs, return busy. If there
  833. ** are no active VMs, invalidate any pre-compiled statements.
  834. */
  835. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 0);
  836. if( pColl && pColl->xCmp ){
  837. if( db->activeVdbeCnt ){
  838. sqlite3Error(db, SQLITE_BUSY,
  839. "Unable to delete/modify collation sequence due to active statements");
  840. return SQLITE_BUSY;
  841. }
  842. sqlite3ExpirePreparedStatements(db);
  843. /* If collation sequence pColl was created directly by a call to
  844. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  845. ** then any copies made by synthCollSeq() need to be invalidated.
  846. ** Also, collation destructor - CollSeq.xDel() - function may need
  847. ** to be called.
  848. */
  849. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  850. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, strlen(zName));
  851. int j;
  852. for(j=0; j<3; j++){
  853. CollSeq *p = &aColl[j];
  854. if( p->enc==pColl->enc ){
  855. if( p->xDel ){
  856. p->xDel(p->pUser);
  857. }
  858. p->xCmp = 0;
  859. }
  860. }
  861. }
  862. }
  863. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 1);
  864. if( pColl ){
  865. pColl->xCmp = xCompare;
  866. pColl->pUser = pCtx;
  867. pColl->xDel = xDel;
  868. pColl->enc = enc2 | (enc & SQLITE_UTF16_ALIGNED);
  869. }
  870. sqlite3Error(db, SQLITE_OK, 0);
  871. return SQLITE_OK;
  872. }
  873. /*
  874. ** This routine does the work of opening a database on behalf of
  875. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  876. ** is UTF-8 encoded.
  877. */
  878. static int openDatabase(
  879. const char *zFilename, /* Database filename UTF-8 encoded */
  880. sqlite3 **ppDb, /* OUT: Returned database handle */
  881. unsigned flags, /* Operational flags */
  882. const char *zVfs /* Name of the VFS to use */
  883. ){
  884. sqlite3 *db;
  885. int rc;
  886. CollSeq *pColl;
  887. /* Allocate the sqlite data structure */
  888. db = sqlite3MallocZero( sizeof(sqlite3) );
  889. if( db==0 ) goto opendb_out;
  890. db->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  891. if( db->mutex==0 ){
  892. sqlite3_free(db);
  893. db = 0;
  894. goto opendb_out;
  895. }
  896. sqlite3_mutex_enter(db->mutex);
  897. db->errMask = 0xff;
  898. db->priorNewRowid = 0;
  899. db->nDb = 2;
  900. db->magic = SQLITE_MAGIC_BUSY;
  901. db->aDb = db->aDbStatic;
  902. db->autoCommit = 1;
  903. db->nextAutovac = -1;
  904. db->flags |= SQLITE_ShortColNames
  905. #if SQLITE_DEFAULT_FILE_FORMAT<4
  906. | SQLITE_LegacyFileFmt
  907. #endif
  908. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  909. | SQLITE_LoadExtension
  910. #endif
  911. ;
  912. sqlite3HashInit(&db->aFunc, SQLITE_HASH_STRING, 0);
  913. sqlite3HashInit(&db->aCollSeq, SQLITE_HASH_STRING, 0);
  914. #ifndef SQLITE_OMIT_VIRTUALTABLE
  915. sqlite3HashInit(&db->aModule, SQLITE_HASH_STRING, 0);
  916. #endif
  917. db->pVfs = sqlite3_vfs_find(zVfs);
  918. if( !db->pVfs ){
  919. rc = SQLITE_ERROR;
  920. db->magic = SQLITE_MAGIC_CLOSED;
  921. sqlite3Error(db, rc, "no such vfs: %s", (zVfs?zVfs:"(null)"));
  922. goto opendb_out;
  923. }
  924. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  925. ** and UTF-16, so add a version for each to avoid any unnecessary
  926. ** conversions. The only error that can occur here is a malloc() failure.
  927. */
  928. if( createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0) ||
  929. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0) ||
  930. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0) ||
  931. (db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0))==0
  932. ){
  933. assert( db->mallocFailed );
  934. db->magic = SQLITE_MAGIC_CLOSED;
  935. goto opendb_out;
  936. }
  937. /* Also add a UTF-8 case-insensitive collation sequence. */
  938. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  939. /* Set flags on the built-in collating sequences */
  940. db->pDfltColl->type = SQLITE_COLL_BINARY;
  941. pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
  942. if( pColl ){
  943. pColl->type = SQLITE_COLL_NOCASE;
  944. }
  945. /* Open the backend database driver */
  946. db->openFlags = flags;
  947. rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
  948. flags | SQLITE_OPEN_MAIN_DB,
  949. &db->aDb[0].pBt);
  950. if( rc!=SQLITE_OK ){
  951. sqlite3Error(db, rc, 0);
  952. db->magic = SQLITE_MAGIC_CLOSED;
  953. goto opendb_out;
  954. }
  955. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  956. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  957. /* The default safety_level for the main database is 'full'; for the temp
  958. ** database it is 'NONE'. This matches the pager layer defaults.
  959. */
  960. db->aDb[0].zName = "main";
  961. db->aDb[0].safety_level = 3;
  962. #ifndef SQLITE_OMIT_TEMPDB
  963. db->aDb[1].zName = "temp";
  964. db->aDb[1].safety_level = 1;
  965. #endif
  966. db->magic = SQLITE_MAGIC_OPEN;
  967. if( db->mallocFailed ){
  968. goto opendb_out;
  969. }
  970. /* Register all built-in functions, but do not attempt to read the
  971. ** database schema yet. This is delayed until the first time the database
  972. ** is accessed.
  973. */
  974. sqlite3Error(db, SQLITE_OK, 0);
  975. sqlite3RegisterBuiltinFunctions(db);
  976. /* Load automatic extensions - extensions that have been registered
  977. ** using the sqlite3_automatic_extension() API.
  978. */
  979. (void)sqlite3AutoLoadExtensions(db);
  980. if( sqlite3_errcode(db)!=SQLITE_OK ){
  981. goto opendb_out;
  982. }
  983. #ifdef SQLITE_ENABLE_FTS1
  984. if( !db->mallocFailed ){
  985. extern int sqlite3Fts1Init(sqlite3*);
  986. rc = sqlite3Fts1Init(db);
  987. }
  988. #endif
  989. #ifdef SQLITE_ENABLE_FTS2
  990. if( !db->mallocFailed && rc==SQLITE_OK ){
  991. extern int sqlite3Fts2Init(sqlite3*);
  992. rc = sqlite3Fts2Init(db);
  993. }
  994. #endif
  995. #ifdef SQLITE_ENABLE_FTS3
  996. if( !db->mallocFailed && rc==SQLITE_OK ){
  997. extern int sqlite3Fts3Init(sqlite3*);
  998. rc = sqlite3Fts3Init(db);
  999. }
  1000. #endif
  1001. #ifdef SQLITE_ENABLE_ICU
  1002. if( !db->mallocFailed && rc==SQLITE_OK ){
  1003. extern int sqlite3IcuInit(sqlite3*);
  1004. rc = sqlite3IcuInit(db);
  1005. }
  1006. #endif
  1007. sqlite3Error(db, rc, 0);
  1008. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  1009. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  1010. ** mode. Doing nothing at all also makes NORMAL the default.
  1011. */
  1012. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  1013. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  1014. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  1015. SQLITE_DEFAULT_LOCKING_MODE);
  1016. #endif
  1017. opendb_out:
  1018. if( db && db->mutex ){
  1019. sqlite3_mutex_leave(db->mutex);
  1020. }
  1021. if( SQLITE_NOMEM==(rc = sqlite3_errcode(db)) ){
  1022. sqlite3_close(db);
  1023. db = 0;
  1024. }
  1025. *ppDb = db;
  1026. return sqlite3ApiExit(0, rc);
  1027. }
  1028. /*
  1029. ** Open a new database handle.
  1030. */
  1031. int sqlite3_open(
  1032. const char *zFilename,
  1033. sqlite3 **ppDb
  1034. ){
  1035. return openDatabase(zFilename, ppDb,
  1036. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  1037. }
  1038. int sqlite3_open_v2(
  1039. const char *filename, /* Database filename (UTF-8) */
  1040. sqlite3 **ppDb, /* OUT: SQLite db handle */
  1041. int flags, /* Flags */
  1042. const char *zVfs /* Name of VFS module to use */
  1043. ){
  1044. return openDatabase(filename, ppDb, flags, zVfs);
  1045. }
  1046. #ifndef SQLITE_OMIT_UTF16
  1047. /*
  1048. ** Open a new database handle.
  1049. */
  1050. int sqlite3_open16(
  1051. const void *zFilename,
  1052. sqlite3 **ppDb
  1053. ){
  1054. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  1055. sqlite3_value *pVal;
  1056. int rc = SQLITE_NOMEM;
  1057. assert( zFilename );
  1058. assert( ppDb );
  1059. *ppDb = 0;
  1060. pVal = sqlite3ValueNew(0);
  1061. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  1062. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  1063. if( zFilename8 ){
  1064. rc = openDatabase(zFilename8, ppDb,
  1065. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  1066. if( rc==SQLITE_OK && *ppDb ){
  1067. rc = sqlite3_exec(*ppDb, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);
  1068. if( rc!=SQLITE_OK ){
  1069. sqlite3_close(*ppDb);
  1070. *ppDb = 0;
  1071. }
  1072. }
  1073. }
  1074. sqlite3ValueFree(pVal);
  1075. return sqlite3ApiExit(0, rc);
  1076. }
  1077. #endif /* SQLITE_OMIT_UTF16 */
  1078. /*
  1079. ** Register a new collation sequence with the database handle db.
  1080. */
  1081. int sqlite3_create_collation(
  1082. sqlite3* db,
  1083. const char *zName,
  1084. int enc,
  1085. void* pCtx,
  1086. int(*xCompare)(void*,int,const void*,int,const void*)
  1087. ){
  1088. int rc;
  1089. sqlite3_mutex_enter(db->mutex);
  1090. assert( !db->mallocFailed );
  1091. rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
  1092. rc = sqlite3ApiExit(db, rc);
  1093. sqlite3_mutex_leave(db->mutex);
  1094. return rc;
  1095. }
  1096. /*
  1097. ** Register a new collation sequence with the database handle db.
  1098. */
  1099. int sqlite3_create_collation_v2(
  1100. sqlite3* db,
  1101. const char *zName,
  1102. int enc,
  1103. void* pCtx,
  1104. int(*xCompare)(void*,int,const void*,int,const void*),
  1105. void(*xDel)(void*)
  1106. ){
  1107. int rc;
  1108. sqlite3_mutex_enter(db->mutex);
  1109. assert( !db->mallocFailed );
  1110. rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
  1111. rc = sqlite3ApiExit(db, rc);
  1112. sqlite3_mutex_leave(db->mutex);
  1113. return rc;
  1114. }
  1115. #ifndef SQLITE_OMIT_UTF16
  1116. /*
  1117. ** Register a new collation sequence with the database handle db.
  1118. */
  1119. int sqlite3_create_collation16(
  1120. sqlite3* db,
  1121. const char *zName,
  1122. int enc,
  1123. void* pCtx,
  1124. int(*xCompare)(void*,int,const void*,int,const void*)
  1125. ){
  1126. int rc = SQLITE_OK;
  1127. char *zName8;
  1128. sqlite3_mutex_enter(db->mutex);
  1129. assert( !db->mallocFailed );
  1130. zName8 = sqlite3Utf16to8(db, zName, -1);
  1131. if( zName8 ){
  1132. rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
  1133. sqlite3_free(zName8);
  1134. }
  1135. rc = sqlite3ApiExit(db, rc);
  1136. sqlite3_mutex_leave(db->mutex);
  1137. return rc;
  1138. }
  1139. #endif /* SQLITE_OMIT_UTF16 */
  1140. /*
  1141. ** Register a collation sequence factory callback with the database handle
  1142. ** db. Replace any previously installed collation sequence factory.
  1143. */
  1144. int sqlite3_collation_needed(
  1145. sqlite3 *db,
  1146. void *pCollNeededArg,
  1147. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  1148. ){
  1149. if( sqlite3SafetyCheck(db) ){
  1150. return SQLITE_MISUSE;
  1151. }
  1152. sqlite3_mutex_enter(db->mutex);
  1153. db->xCollNeeded = xCollNeeded;
  1154. db->xCollNeeded16 = 0;
  1155. db->pCollNeededArg = pCollNeededArg;
  1156. sqlite3_mutex_leave(db->mutex);
  1157. return SQLITE_OK;
  1158. }
  1159. #ifndef SQLITE_OMIT_UTF16
  1160. /*
  1161. ** Register a collation sequence factory callback with the database handle
  1162. ** db. Replace any previously installed collation sequence factory.
  1163. */
  1164. int sqlite3_collation_needed16(
  1165. sqlite3 *db,
  1166. void *pCollNeededArg,
  1167. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  1168. ){
  1169. if( sqlite3SafetyCheck(db) ){
  1170. return SQLITE_MISUSE;
  1171. }
  1172. sqlite3_mutex_enter(db->mutex);
  1173. db->xCollNeeded = 0;
  1174. db->xCollNeeded16 = xCollNeeded16;
  1175. db->pCollNeededArg = pCollNeededArg;
  1176. sqlite3_mutex_leave(db->mutex);
  1177. return SQLITE_OK;
  1178. }
  1179. #endif /* SQLITE_OMIT_UTF16 */
  1180. #ifndef SQLITE_OMIT_GLOBALRECOVER
  1181. /*
  1182. ** This function is now an anachronism. It used to be used to recover from a
  1183. ** malloc() failure, but SQLite now does this automatically.
  1184. */
  1185. int sqlite3_global_recover(void){
  1186. return SQLITE_OK;
  1187. }
  1188. #endif
  1189. /*
  1190. ** Test to see whether or not the database connection is in autocommit
  1191. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  1192. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  1193. ** by the next COMMIT or ROLLBACK.
  1194. **
  1195. ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  1196. */
  1197. int sqlite3_get_autocommit(sqlite3 *db){
  1198. return db->autoCommit;
  1199. }
  1200. #ifdef SQLITE_DEBUG
  1201. /*
  1202. ** The following routine is subtituted for constant SQLITE_CORRUPT in
  1203. ** debugging builds. This provides a way to set a breakpoint for when
  1204. ** corruption is first detected.
  1205. */
  1206. int sqlite3Corrupt(void){
  1207. return SQLITE_CORRUPT;
  1208. }
  1209. #endif
  1210. /*
  1211. ** This is a convenience routine that makes sure that all thread-specific
  1212. ** data for this thread has been deallocated.
  1213. **
  1214. ** SQLite no longer uses thread-specific data so this routine is now a
  1215. ** no-op. It is retained for historical compatibility.
  1216. */
  1217. void sqlite3_thread_cleanup(void){
  1218. }
  1219. /*
  1220. ** Return meta information about a specific column of a database table.
  1221. ** See comment in sqlite3.h (sqlite.h.in) for details.
  1222. */
  1223. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  1224. int sqlite3_table_column_metadata(
  1225. sqlite3 *db, /* Connection handle */
  1226. const char *zDbName, /* Database name or NULL */
  1227. const char *zTableName, /* Table name */
  1228. const char *zColumnName, /* Column name */
  1229. char const **pzDataType, /* OUTPUT: Declared data type */
  1230. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  1231. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  1232. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  1233. int *pAutoinc /* OUTPUT: True if colums is auto-increment */
  1234. ){
  1235. int rc;
  1236. char *zErrMsg = 0;
  1237. Table *pTab = 0;
  1238. Column *pCol = 0;
  1239. int iCol;
  1240. char const *zDataType = 0;
  1241. char const *zCollSeq = 0;
  1242. int notnull = 0;
  1243. int primarykey = 0;
  1244. int autoinc = 0;
  1245. /* Ensure the database schema has been loaded */
  1246. if( sqlite3SafetyOn(db) ){
  1247. return SQLITE_MISUSE;
  1248. }
  1249. sqlite3_mutex_enter(db->mutex);
  1250. rc = sqlite3Init(db, &zErrMsg);
  1251. if( SQLITE_OK!=rc ){
  1252. goto error_out;
  1253. }
  1254. /* Locate the table in question */
  1255. pTab = sqlite3FindTable(db, zTableName, zDbName);
  1256. if( !pTab || pTab->pSelect ){
  1257. pTab = 0;
  1258. goto error_out;
  1259. }
  1260. /* Find the column for which info is requested */
  1261. if( sqlite3IsRowid(zColumnName) ){
  1262. iCol = pTab->iPKey;
  1263. if( iCol>=0 ){
  1264. pCol = &pTab->aCol[iCol];
  1265. }
  1266. }else{
  1267. for(iCol=0; iCol<pTab->nCol; iCol++){
  1268. pCol = &pTab->aCol[iCol];
  1269. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  1270. break;
  1271. }
  1272. }
  1273. if( iCol==pTab->nCol ){
  1274. pTab = 0;
  1275. goto error_out;
  1276. }
  1277. }
  1278. /* The following block stores the meta information that will be returned
  1279. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  1280. ** and autoinc. At this point there are two possibilities:
  1281. **
  1282. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  1283. ** and there is no explicitly declared IPK column.
  1284. **
  1285. ** 2. The table is not a view and the column name identified an
  1286. ** explicitly declared column. Copy meta information from *pCol.
  1287. */
  1288. if( pCol ){
  1289. zDataType = pCol->zType;
  1290. zCollSeq = pCol->zColl;
  1291. notnull = (pCol->notNull?1:0);
  1292. primarykey = (pCol->isPrimKey?1:0);
  1293. autoinc = ((pTab->iPKey==iCol && pTab->autoInc)?1:0);
  1294. }else{
  1295. zDataType = "INTEGER";
  1296. primarykey = 1;
  1297. }
  1298. if( !zCollSeq ){
  1299. zCollSeq = "BINARY";
  1300. }
  1301. error_out:
  1302. if( sqlite3SafetyOff(db) ){
  1303. rc = SQLITE_MISUSE;
  1304. }
  1305. /* Whether the function call succeeded or failed, set the output parameters
  1306. ** to whatever their local counterparts contain. If an error did occur,
  1307. ** this has the effect of zeroing all output parameters.
  1308. */
  1309. if( pzDataType ) *pzDataType = zDataType;
  1310. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  1311. if( pNotNull ) *pNotNull = notnull;
  1312. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  1313. if( pAutoinc ) *pAutoinc = autoinc;
  1314. if( SQLITE_OK==rc && !pTab ){
  1315. sqlite3SetString(&zErrMsg, "no such table column: ", zTableName, ".",
  1316. zColumnName, 0);
  1317. rc = SQLITE_ERROR;
  1318. }
  1319. sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
  1320. sqlite3_free(zErrMsg);
  1321. rc = sqlite3ApiExit(db, rc);
  1322. sqlite3_mutex_leave(db->mutex);
  1323. return rc;
  1324. }
  1325. #endif
  1326. /*
  1327. ** Sleep for a little while. Return the amount of time slept.
  1328. */
  1329. int sqlite3_sleep(int ms){
  1330. sqlite3_vfs *pVfs;
  1331. int rc;
  1332. pVfs = sqlite3_vfs_find(0);
  1333. /* This function works in milliseconds, but the underlying OsSleep()
  1334. ** API uses microseconds. Hence the 1000's.
  1335. */
  1336. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  1337. return rc;
  1338. }
  1339. /*
  1340. ** Enable or disable the extended result codes.
  1341. */
  1342. int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  1343. sqlite3_mutex_enter(db->mutex);
  1344. db->errMask = onoff ? 0xffffffff : 0xff;
  1345. sqlite3_mutex_leave(db->mutex);
  1346. return SQLITE_OK;
  1347. }
  1348. /*
  1349. ** Invoke the xFileControl method on a particular database.
  1350. */
  1351. int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  1352. int rc = SQLITE_ERROR;
  1353. int iDb;
  1354. sqlite3_mutex_enter(db->mutex);
  1355. if( zDbName==0 ){
  1356. iDb = 0;
  1357. }else{
  1358. for(iDb=0; iDb<db->nDb; iDb++){
  1359. if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
  1360. }
  1361. }
  1362. if( iDb<db->nDb ){
  1363. Btree *pBtree = db->aDb[iDb].pBt;
  1364. if( pBtree ){
  1365. Pager *pPager;
  1366. sqlite3BtreeEnter(pBtree);
  1367. pPager = sqlite3BtreePager(pBtree);
  1368. if( pPager ){
  1369. sqlite3_file *fd = sqlite3PagerFile(pPager);
  1370. if( fd ){
  1371. rc = sqlite3OsFileControl(fd, op, pArg);
  1372. }
  1373. }
  1374. sqlite3BtreeLeave(pBtree);
  1375. }
  1376. }
  1377. sqlite3_mutex_leave(db->mutex);
  1378. return rc;
  1379. }