prepare.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. /*
  2. ** 2005 May 25
  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. ** This file contains the implementation of the sqlite3_prepare()
  13. ** interface, and routines that contribute to loading the database schema
  14. ** from disk.
  15. */
  16. #include "sqliteInt.h"
  17. /*
  18. ** Fill the InitData structure with an error message that indicates
  19. ** that the database is corrupt.
  20. */
  21. static void corruptSchema(
  22. InitData *pData, /* Initialization context */
  23. const char *zObj, /* Object being parsed at the point of error */
  24. const char *zExtra /* Error information */
  25. ){
  26. sqlite3 *db = pData->db;
  27. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  28. if( zObj==0 ) zObj = "?";
  29. sqlite3SetString(pData->pzErrMsg, db,
  30. "malformed database schema (%s)", zObj);
  31. if( zExtra ){
  32. *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
  33. "%s - %s", *pData->pzErrMsg, zExtra);
  34. }
  35. }
  36. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  37. }
  38. /*
  39. ** This is the callback routine for the code that initializes the
  40. ** database. See sqlite3Init() below for additional information.
  41. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  42. **
  43. ** Each callback contains the following information:
  44. **
  45. ** argv[0] = name of thing being created
  46. ** argv[1] = root page number for table or index. 0 for trigger or view.
  47. ** argv[2] = SQL text for the CREATE statement.
  48. **
  49. */
  50. int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  51. InitData *pData = (InitData*)pInit;
  52. sqlite3 *db = pData->db;
  53. int iDb = pData->iDb;
  54. assert( argc==3 );
  55. UNUSED_PARAMETER2(NotUsed, argc);
  56. assert( sqlite3_mutex_held(db->mutex) );
  57. DbClearProperty(db, iDb, DB_Empty);
  58. if( db->mallocFailed ){
  59. corruptSchema(pData, argv[0], 0);
  60. return 1;
  61. }
  62. assert( iDb>=0 && iDb<db->nDb );
  63. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  64. if( argv[1]==0 ){
  65. corruptSchema(pData, argv[0], 0);
  66. }else if( argv[2] && argv[2][0] ){
  67. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  68. ** But because db->init.busy is set to 1, no VDBE code is generated
  69. ** or executed. All the parser does is build the internal data
  70. ** structures that describe the table, index, or view.
  71. */
  72. int rc;
  73. sqlite3_stmt *pStmt;
  74. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  75. assert( db->init.busy );
  76. db->init.iDb = iDb;
  77. db->init.newTnum = sqlite3Atoi(argv[1]);
  78. db->init.orphanTrigger = 0;
  79. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  80. rc = db->errCode;
  81. assert( (rc&0xFF)==(rcp&0xFF) );
  82. db->init.iDb = 0;
  83. if( SQLITE_OK!=rc ){
  84. if( db->init.orphanTrigger ){
  85. assert( iDb==1 );
  86. }else{
  87. pData->rc = rc;
  88. if( rc==SQLITE_NOMEM ){
  89. db->mallocFailed = 1;
  90. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  91. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  92. }
  93. }
  94. }
  95. sqlite3_finalize(pStmt);
  96. }else if( argv[0]==0 ){
  97. corruptSchema(pData, 0, 0);
  98. }else{
  99. /* If the SQL column is blank it means this is an index that
  100. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  101. ** constraint for a CREATE TABLE. The index should have already
  102. ** been created when we processed the CREATE TABLE. All we have
  103. ** to do here is record the root page number for that index.
  104. */
  105. Index *pIndex;
  106. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  107. if( pIndex==0 ){
  108. /* This can occur if there exists an index on a TEMP table which
  109. ** has the same name as another index on a permanent index. Since
  110. ** the permanent table is hidden by the TEMP table, we can also
  111. ** safely ignore the index on the permanent table.
  112. */
  113. /* Do Nothing */;
  114. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  115. corruptSchema(pData, argv[0], "invalid rootpage");
  116. }
  117. }
  118. return 0;
  119. }
  120. /*
  121. ** Attempt to read the database schema and initialize internal
  122. ** data structures for a single database file. The index of the
  123. ** database file is given by iDb. iDb==0 is used for the main
  124. ** database. iDb==1 should never be used. iDb>=2 is used for
  125. ** auxiliary databases. Return one of the SQLITE_ error codes to
  126. ** indicate success or failure.
  127. */
  128. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  129. int rc;
  130. int i;
  131. #ifndef SQLITE_OMIT_DEPRECATED
  132. int size;
  133. #endif
  134. Table *pTab;
  135. Db *pDb;
  136. char const *azArg[4];
  137. int meta[5];
  138. InitData initData;
  139. char const *zMasterSchema;
  140. char const *zMasterName;
  141. int openedTransaction = 0;
  142. /*
  143. ** The master database table has a structure like this
  144. */
  145. static const char master_schema[] =
  146. "CREATE TABLE sqlite_master(\n"
  147. " type text,\n"
  148. " name text,\n"
  149. " tbl_name text,\n"
  150. " rootpage integer,\n"
  151. " sql text\n"
  152. ")"
  153. ;
  154. #ifndef SQLITE_OMIT_TEMPDB
  155. static const char temp_master_schema[] =
  156. "CREATE TEMP TABLE sqlite_temp_master(\n"
  157. " type text,\n"
  158. " name text,\n"
  159. " tbl_name text,\n"
  160. " rootpage integer,\n"
  161. " sql text\n"
  162. ")"
  163. ;
  164. #else
  165. #define temp_master_schema 0
  166. #endif
  167. assert( iDb>=0 && iDb<db->nDb );
  168. assert( db->aDb[iDb].pSchema );
  169. assert( sqlite3_mutex_held(db->mutex) );
  170. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  171. /* zMasterSchema and zInitScript are set to point at the master schema
  172. ** and initialisation script appropriate for the database being
  173. ** initialized. zMasterName is the name of the master table.
  174. */
  175. if( !OMIT_TEMPDB && iDb==1 ){
  176. zMasterSchema = temp_master_schema;
  177. }else{
  178. zMasterSchema = master_schema;
  179. }
  180. zMasterName = SCHEMA_TABLE(iDb);
  181. /* Construct the schema tables. */
  182. azArg[0] = zMasterName;
  183. azArg[1] = "1";
  184. azArg[2] = zMasterSchema;
  185. azArg[3] = 0;
  186. initData.db = db;
  187. initData.iDb = iDb;
  188. initData.rc = SQLITE_OK;
  189. initData.pzErrMsg = pzErrMsg;
  190. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  191. if( initData.rc ){
  192. rc = initData.rc;
  193. goto error_out;
  194. }
  195. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  196. if( ALWAYS(pTab) ){
  197. pTab->tabFlags |= TF_Readonly;
  198. }
  199. /* Create a cursor to hold the database open
  200. */
  201. pDb = &db->aDb[iDb];
  202. if( pDb->pBt==0 ){
  203. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  204. DbSetProperty(db, 1, DB_SchemaLoaded);
  205. }
  206. return SQLITE_OK;
  207. }
  208. /* If there is not already a read-only (or read-write) transaction opened
  209. ** on the b-tree database, open one now. If a transaction is opened, it
  210. ** will be closed before this function returns. */
  211. sqlite3BtreeEnter(pDb->pBt);
  212. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  213. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  214. if( rc!=SQLITE_OK ){
  215. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  216. goto initone_error_out;
  217. }
  218. openedTransaction = 1;
  219. }
  220. /* Get the database meta information.
  221. **
  222. ** Meta values are as follows:
  223. ** meta[0] Schema cookie. Changes with each schema change.
  224. ** meta[1] File format of schema layer.
  225. ** meta[2] Size of the page cache.
  226. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  227. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  228. ** meta[5] User version
  229. ** meta[6] Incremental vacuum mode
  230. ** meta[7] unused
  231. ** meta[8] unused
  232. ** meta[9] unused
  233. **
  234. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  235. ** the possible values of meta[4].
  236. */
  237. for(i=0; i<ArraySize(meta); i++){
  238. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  239. }
  240. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  241. /* If opening a non-empty database, check the text encoding. For the
  242. ** main database, set sqlite3.enc to the encoding of the main database.
  243. ** For an attached db, it is an error if the encoding is not the same
  244. ** as sqlite3.enc.
  245. */
  246. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  247. if( iDb==0 ){
  248. #ifndef SQLITE_OMIT_UTF16
  249. u8 encoding;
  250. /* If opening the main database, set ENC(db). */
  251. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  252. if( encoding==0 ) encoding = SQLITE_UTF8;
  253. ENC(db) = encoding;
  254. #else
  255. ENC(db) = SQLITE_UTF8;
  256. #endif
  257. }else{
  258. /* If opening an attached database, the encoding much match ENC(db) */
  259. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  260. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  261. " text encoding as main database");
  262. rc = SQLITE_ERROR;
  263. goto initone_error_out;
  264. }
  265. }
  266. }else{
  267. DbSetProperty(db, iDb, DB_Empty);
  268. }
  269. pDb->pSchema->enc = ENC(db);
  270. if( pDb->pSchema->cache_size==0 ){
  271. #ifndef SQLITE_OMIT_DEPRECATED
  272. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  273. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  274. pDb->pSchema->cache_size = size;
  275. #else
  276. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  277. #endif
  278. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  279. }
  280. /*
  281. ** file_format==1 Version 3.0.0.
  282. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  283. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  284. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  285. */
  286. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  287. if( pDb->pSchema->file_format==0 ){
  288. pDb->pSchema->file_format = 1;
  289. }
  290. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  291. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  292. rc = SQLITE_ERROR;
  293. goto initone_error_out;
  294. }
  295. /* Ticket #2804: When we open a database in the newer file format,
  296. ** clear the legacy_file_format pragma flag so that a VACUUM will
  297. ** not downgrade the database and thus invalidate any descending
  298. ** indices that the user might have created.
  299. */
  300. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  301. db->flags &= ~SQLITE_LegacyFileFmt;
  302. }
  303. /* Read the schema information out of the schema tables
  304. */
  305. assert( db->init.busy );
  306. {
  307. char *zSql;
  308. zSql = sqlite3MPrintf(db,
  309. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  310. db->aDb[iDb].zName, zMasterName);
  311. #ifndef SQLITE_OMIT_AUTHORIZATION
  312. {
  313. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  314. xAuth = db->xAuth;
  315. db->xAuth = 0;
  316. #endif
  317. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  318. #ifndef SQLITE_OMIT_AUTHORIZATION
  319. db->xAuth = xAuth;
  320. }
  321. #endif
  322. if( rc==SQLITE_OK ) rc = initData.rc;
  323. sqlite3DbFree(db, zSql);
  324. #ifndef SQLITE_OMIT_ANALYZE
  325. if( rc==SQLITE_OK ){
  326. sqlite3AnalysisLoad(db, iDb);
  327. }
  328. #endif
  329. }
  330. if( db->mallocFailed ){
  331. rc = SQLITE_NOMEM;
  332. sqlite3ResetAllSchemasOfConnection(db);
  333. }
  334. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  335. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  336. ** the schema loaded, even if errors occurred. In this situation the
  337. ** current sqlite3_prepare() operation will fail, but the following one
  338. ** will attempt to compile the supplied statement against whatever subset
  339. ** of the schema was loaded before the error occurred. The primary
  340. ** purpose of this is to allow access to the sqlite_master table
  341. ** even when its contents have been corrupted.
  342. */
  343. DbSetProperty(db, iDb, DB_SchemaLoaded);
  344. rc = SQLITE_OK;
  345. }
  346. /* Jump here for an error that occurs after successfully allocating
  347. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  348. ** before that point, jump to error_out.
  349. */
  350. initone_error_out:
  351. if( openedTransaction ){
  352. sqlite3BtreeCommit(pDb->pBt);
  353. }
  354. sqlite3BtreeLeave(pDb->pBt);
  355. error_out:
  356. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  357. db->mallocFailed = 1;
  358. }
  359. return rc;
  360. }
  361. /*
  362. ** Initialize all database files - the main database file, the file
  363. ** used to store temporary tables, and any additional database files
  364. ** created using ATTACH statements. Return a success code. If an
  365. ** error occurs, write an error message into *pzErrMsg.
  366. **
  367. ** After a database is initialized, the DB_SchemaLoaded bit is set
  368. ** bit is set in the flags field of the Db structure. If the database
  369. ** file was of zero-length, then the DB_Empty flag is also set.
  370. */
  371. int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  372. int i, rc;
  373. int commit_internal = !(db->flags&SQLITE_InternChanges);
  374. assert( sqlite3_mutex_held(db->mutex) );
  375. rc = SQLITE_OK;
  376. db->init.busy = 1;
  377. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  378. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  379. rc = sqlite3InitOne(db, i, pzErrMsg);
  380. if( rc ){
  381. sqlite3ResetOneSchema(db, i);
  382. }
  383. }
  384. /* Once all the other databases have been initialized, load the schema
  385. ** for the TEMP database. This is loaded last, as the TEMP database
  386. ** schema may contain references to objects in other databases.
  387. */
  388. #ifndef SQLITE_OMIT_TEMPDB
  389. if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
  390. && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  391. rc = sqlite3InitOne(db, 1, pzErrMsg);
  392. if( rc ){
  393. sqlite3ResetOneSchema(db, 1);
  394. }
  395. }
  396. #endif
  397. db->init.busy = 0;
  398. if( rc==SQLITE_OK && commit_internal ){
  399. sqlite3CommitInternalChanges(db);
  400. }
  401. return rc;
  402. }
  403. /*
  404. ** This routine is a no-op if the database schema is already initialized.
  405. ** Otherwise, the schema is loaded. An error code is returned.
  406. */
  407. int sqlite3ReadSchema(Parse *pParse){
  408. int rc = SQLITE_OK;
  409. sqlite3 *db = pParse->db;
  410. assert( sqlite3_mutex_held(db->mutex) );
  411. if( !db->init.busy ){
  412. rc = sqlite3Init(db, &pParse->zErrMsg);
  413. }
  414. if( rc!=SQLITE_OK ){
  415. pParse->rc = rc;
  416. pParse->nErr++;
  417. }
  418. return rc;
  419. }
  420. /*
  421. ** Check schema cookies in all databases. If any cookie is out
  422. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  423. ** make no changes to pParse->rc.
  424. */
  425. static void schemaIsValid(Parse *pParse){
  426. sqlite3 *db = pParse->db;
  427. int iDb;
  428. int rc;
  429. int cookie;
  430. assert( pParse->checkSchema );
  431. assert( sqlite3_mutex_held(db->mutex) );
  432. for(iDb=0; iDb<db->nDb; iDb++){
  433. int openedTransaction = 0; /* True if a transaction is opened */
  434. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  435. if( pBt==0 ) continue;
  436. /* If there is not already a read-only (or read-write) transaction opened
  437. ** on the b-tree database, open one now. If a transaction is opened, it
  438. ** will be closed immediately after reading the meta-value. */
  439. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  440. rc = sqlite3BtreeBeginTrans(pBt, 0);
  441. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  442. db->mallocFailed = 1;
  443. }
  444. if( rc!=SQLITE_OK ) return;
  445. openedTransaction = 1;
  446. }
  447. /* Read the schema cookie from the database. If it does not match the
  448. ** value stored as part of the in-memory schema representation,
  449. ** set Parse.rc to SQLITE_SCHEMA. */
  450. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  451. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  452. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  453. sqlite3ResetOneSchema(db, iDb);
  454. pParse->rc = SQLITE_SCHEMA;
  455. }
  456. /* Close the transaction, if one was opened. */
  457. if( openedTransaction ){
  458. sqlite3BtreeCommit(pBt);
  459. }
  460. }
  461. }
  462. /*
  463. ** Convert a schema pointer into the iDb index that indicates
  464. ** which database file in db->aDb[] the schema refers to.
  465. **
  466. ** If the same database is attached more than once, the first
  467. ** attached database is returned.
  468. */
  469. int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  470. int i = -1000000;
  471. /* If pSchema is NULL, then return -1000000. This happens when code in
  472. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  473. ** created by a sub-select). In this case the return value of this
  474. ** function should never be used.
  475. **
  476. ** We return -1000000 instead of the more usual -1 simply because using
  477. ** -1000000 as the incorrect index into db->aDb[] is much
  478. ** more likely to cause a segfault than -1 (of course there are assert()
  479. ** statements too, but it never hurts to play the odds).
  480. */
  481. assert( sqlite3_mutex_held(db->mutex) );
  482. if( pSchema ){
  483. for(i=0; ALWAYS(i<db->nDb); i++){
  484. if( db->aDb[i].pSchema==pSchema ){
  485. break;
  486. }
  487. }
  488. assert( i>=0 && i<db->nDb );
  489. }
  490. return i;
  491. }
  492. /*
  493. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  494. */
  495. static int sqlite3Prepare(
  496. sqlite3 *db, /* Database handle. */
  497. const char *zSql, /* UTF-8 encoded SQL statement. */
  498. int nBytes, /* Length of zSql in bytes. */
  499. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  500. Vdbe *pReprepare, /* VM being reprepared */
  501. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  502. const char **pzTail /* OUT: End of parsed string */
  503. ){
  504. Parse *pParse; /* Parsing context */
  505. char *zErrMsg = 0; /* Error message */
  506. int rc = SQLITE_OK; /* Result code */
  507. int i; /* Loop counter */
  508. /* Allocate the parsing context */
  509. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  510. if( pParse==0 ){
  511. rc = SQLITE_NOMEM;
  512. goto end_prepare;
  513. }
  514. pParse->pReprepare = pReprepare;
  515. assert( ppStmt && *ppStmt==0 );
  516. assert( !db->mallocFailed );
  517. assert( sqlite3_mutex_held(db->mutex) );
  518. /* Check to verify that it is possible to get a read lock on all
  519. ** database schemas. The inability to get a read lock indicates that
  520. ** some other database connection is holding a write-lock, which in
  521. ** turn means that the other connection has made uncommitted changes
  522. ** to the schema.
  523. **
  524. ** Were we to proceed and prepare the statement against the uncommitted
  525. ** schema changes and if those schema changes are subsequently rolled
  526. ** back and different changes are made in their place, then when this
  527. ** prepared statement goes to run the schema cookie would fail to detect
  528. ** the schema change. Disaster would follow.
  529. **
  530. ** This thread is currently holding mutexes on all Btrees (because
  531. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  532. ** is not possible for another thread to start a new schema change
  533. ** while this routine is running. Hence, we do not need to hold
  534. ** locks on the schema, we just need to make sure nobody else is
  535. ** holding them.
  536. **
  537. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  538. ** but it does *not* override schema lock detection, so this all still
  539. ** works even if READ_UNCOMMITTED is set.
  540. */
  541. for(i=0; i<db->nDb; i++) {
  542. Btree *pBt = db->aDb[i].pBt;
  543. if( pBt ){
  544. assert( sqlite3BtreeHoldsMutex(pBt) );
  545. rc = sqlite3BtreeSchemaLocked(pBt);
  546. if( rc ){
  547. const char *zDb = db->aDb[i].zName;
  548. sqlite3Error(db, rc, "database schema is locked: %s", zDb);
  549. testcase( db->flags & SQLITE_ReadUncommitted );
  550. goto end_prepare;
  551. }
  552. }
  553. }
  554. sqlite3VtabUnlockList(db);
  555. pParse->db = db;
  556. pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
  557. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  558. char *zSqlCopy;
  559. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  560. testcase( nBytes==mxLen );
  561. testcase( nBytes==mxLen+1 );
  562. if( nBytes>mxLen ){
  563. sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
  564. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  565. goto end_prepare;
  566. }
  567. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  568. if( zSqlCopy ){
  569. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  570. sqlite3DbFree(db, zSqlCopy);
  571. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  572. }else{
  573. pParse->zTail = &zSql[nBytes];
  574. }
  575. }else{
  576. sqlite3RunParser(pParse, zSql, &zErrMsg);
  577. }
  578. assert( 0==pParse->nQueryLoop );
  579. if( db->mallocFailed ){
  580. pParse->rc = SQLITE_NOMEM;
  581. }
  582. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  583. if( pParse->checkSchema ){
  584. schemaIsValid(pParse);
  585. }
  586. if( db->mallocFailed ){
  587. pParse->rc = SQLITE_NOMEM;
  588. }
  589. if( pzTail ){
  590. *pzTail = pParse->zTail;
  591. }
  592. rc = pParse->rc;
  593. #ifndef SQLITE_OMIT_EXPLAIN
  594. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  595. static const char * const azColName[] = {
  596. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  597. "selectid", "order", "from", "detail"
  598. };
  599. int iFirst, mx;
  600. if( pParse->explain==2 ){
  601. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  602. iFirst = 8;
  603. mx = 12;
  604. }else{
  605. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  606. iFirst = 0;
  607. mx = 8;
  608. }
  609. for(i=iFirst; i<mx; i++){
  610. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  611. azColName[i], SQLITE_STATIC);
  612. }
  613. }
  614. #endif
  615. if( db->init.busy==0 ){
  616. Vdbe *pVdbe = pParse->pVdbe;
  617. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  618. }
  619. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  620. sqlite3VdbeFinalize(pParse->pVdbe);
  621. assert(!(*ppStmt));
  622. }else{
  623. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  624. }
  625. if( zErrMsg ){
  626. sqlite3Error(db, rc, "%s", zErrMsg);
  627. sqlite3DbFree(db, zErrMsg);
  628. }else{
  629. sqlite3Error(db, rc, 0);
  630. }
  631. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  632. while( pParse->pTriggerPrg ){
  633. TriggerPrg *pT = pParse->pTriggerPrg;
  634. pParse->pTriggerPrg = pT->pNext;
  635. sqlite3DbFree(db, pT);
  636. }
  637. end_prepare:
  638. sqlite3StackFree(db, pParse);
  639. rc = sqlite3ApiExit(db, rc);
  640. assert( (rc&db->errMask)==rc );
  641. return rc;
  642. }
  643. static int sqlite3LockAndPrepare(
  644. sqlite3 *db, /* Database handle. */
  645. const char *zSql, /* UTF-8 encoded SQL statement. */
  646. int nBytes, /* Length of zSql in bytes. */
  647. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  648. Vdbe *pOld, /* VM being reprepared */
  649. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  650. const char **pzTail /* OUT: End of parsed string */
  651. ){
  652. int rc;
  653. assert( ppStmt!=0 );
  654. *ppStmt = 0;
  655. if( !sqlite3SafetyCheckOk(db) ){
  656. return SQLITE_MISUSE_BKPT;
  657. }
  658. sqlite3_mutex_enter(db->mutex);
  659. sqlite3BtreeEnterAll(db);
  660. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  661. if( rc==SQLITE_SCHEMA ){
  662. sqlite3_finalize(*ppStmt);
  663. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  664. }
  665. sqlite3BtreeLeaveAll(db);
  666. sqlite3_mutex_leave(db->mutex);
  667. assert( rc==SQLITE_OK || *ppStmt==0 );
  668. return rc;
  669. }
  670. /*
  671. ** Rerun the compilation of a statement after a schema change.
  672. **
  673. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  674. ** if the statement cannot be recompiled because another connection has
  675. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  676. ** occurs, return SQLITE_SCHEMA.
  677. */
  678. int sqlite3Reprepare(Vdbe *p){
  679. int rc;
  680. sqlite3_stmt *pNew;
  681. const char *zSql;
  682. sqlite3 *db;
  683. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  684. zSql = sqlite3_sql((sqlite3_stmt *)p);
  685. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  686. db = sqlite3VdbeDb(p);
  687. assert( sqlite3_mutex_held(db->mutex) );
  688. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  689. if( rc ){
  690. if( rc==SQLITE_NOMEM ){
  691. db->mallocFailed = 1;
  692. }
  693. assert( pNew==0 );
  694. return rc;
  695. }else{
  696. assert( pNew!=0 );
  697. }
  698. sqlite3VdbeSwap((Vdbe*)pNew, p);
  699. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  700. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  701. sqlite3VdbeFinalize((Vdbe*)pNew);
  702. return SQLITE_OK;
  703. }
  704. /*
  705. ** Two versions of the official API. Legacy and new use. In the legacy
  706. ** version, the original SQL text is not saved in the prepared statement
  707. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  708. ** sqlite3_step(). In the new version, the original SQL text is retained
  709. ** and the statement is automatically recompiled if an schema change
  710. ** occurs.
  711. */
  712. int sqlite3_prepare(
  713. sqlite3 *db, /* Database handle. */
  714. const char *zSql, /* UTF-8 encoded SQL statement. */
  715. int nBytes, /* Length of zSql in bytes. */
  716. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  717. const char **pzTail /* OUT: End of parsed string */
  718. ){
  719. int rc;
  720. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  721. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  722. return rc;
  723. }
  724. int sqlite3_prepare_v2(
  725. sqlite3 *db, /* Database handle. */
  726. const char *zSql, /* UTF-8 encoded SQL statement. */
  727. int nBytes, /* Length of zSql in bytes. */
  728. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  729. const char **pzTail /* OUT: End of parsed string */
  730. ){
  731. int rc;
  732. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  733. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  734. return rc;
  735. }
  736. #ifndef SQLITE_OMIT_UTF16
  737. /*
  738. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  739. */
  740. static int sqlite3Prepare16(
  741. sqlite3 *db, /* Database handle. */
  742. const void *zSql, /* UTF-16 encoded SQL statement. */
  743. int nBytes, /* Length of zSql in bytes. */
  744. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  745. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  746. const void **pzTail /* OUT: End of parsed string */
  747. ){
  748. /* This function currently works by first transforming the UTF-16
  749. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  750. ** tricky bit is figuring out the pointer to return in *pzTail.
  751. */
  752. char *zSql8;
  753. const char *zTail8 = 0;
  754. int rc = SQLITE_OK;
  755. assert( ppStmt );
  756. *ppStmt = 0;
  757. if( !sqlite3SafetyCheckOk(db) ){
  758. return SQLITE_MISUSE_BKPT;
  759. }
  760. if( nBytes>=0 ){
  761. int sz;
  762. const char *z = (const char*)zSql;
  763. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  764. nBytes = sz;
  765. }
  766. sqlite3_mutex_enter(db->mutex);
  767. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  768. if( zSql8 ){
  769. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  770. }
  771. if( zTail8 && pzTail ){
  772. /* If sqlite3_prepare returns a tail pointer, we calculate the
  773. ** equivalent pointer into the UTF-16 string by counting the unicode
  774. ** characters between zSql8 and zTail8, and then returning a pointer
  775. ** the same number of characters into the UTF-16 string.
  776. */
  777. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  778. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  779. }
  780. sqlite3DbFree(db, zSql8);
  781. rc = sqlite3ApiExit(db, rc);
  782. sqlite3_mutex_leave(db->mutex);
  783. return rc;
  784. }
  785. /*
  786. ** Two versions of the official API. Legacy and new use. In the legacy
  787. ** version, the original SQL text is not saved in the prepared statement
  788. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  789. ** sqlite3_step(). In the new version, the original SQL text is retained
  790. ** and the statement is automatically recompiled if an schema change
  791. ** occurs.
  792. */
  793. int sqlite3_prepare16(
  794. sqlite3 *db, /* Database handle. */
  795. const void *zSql, /* UTF-16 encoded SQL statement. */
  796. int nBytes, /* Length of zSql in bytes. */
  797. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  798. const void **pzTail /* OUT: End of parsed string */
  799. ){
  800. int rc;
  801. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  802. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  803. return rc;
  804. }
  805. int sqlite3_prepare16_v2(
  806. sqlite3 *db, /* Database handle. */
  807. const void *zSql, /* UTF-16 encoded SQL statement. */
  808. int nBytes, /* Length of zSql in bytes. */
  809. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  810. const void **pzTail /* OUT: End of parsed string */
  811. ){
  812. int rc;
  813. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  814. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  815. return rc;
  816. }
  817. #endif /* SQLITE_OMIT_UTF16 */