xref: /sqlite-3.40.0/src/prepare.c (revision 8737d46e)
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 /*
19 ** Fill the InitData structure with an error message that indicates
20 ** that the database is corrupt.
21 */
22 static void corruptSchema(
23   InitData *pData,     /* Initialization context */
24   const char *zObj,    /* Object being parsed at the point of error */
25   const char *zExtra   /* Error information */
26 ){
27   sqlite3 *db = pData->db;
28   if( db->mallocFailed ){
29     pData->rc = SQLITE_NOMEM_BKPT;
30   }else if( pData->pzErrMsg[0]!=0 ){
31     /* A error message has already been generated.  Do not overwrite it */
32   }else if( pData->mInitFlags & INITFLAG_AlterTable ){
33     *pData->pzErrMsg = sqlite3DbStrDup(db, zExtra);
34     pData->rc = SQLITE_ERROR;
35   }else if( db->flags & SQLITE_WriteSchema ){
36     pData->rc = SQLITE_CORRUPT_BKPT;
37   }else{
38     char *z;
39     if( zObj==0 ) zObj = "?";
40     z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
41     if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
42     *pData->pzErrMsg = z;
43     pData->rc = SQLITE_CORRUPT_BKPT;
44   }
45 }
46 
47 /*
48 ** Check to see if any sibling index (another index on the same table)
49 ** of pIndex has the same root page number, and if it does, return true.
50 ** This would indicate a corrupt schema.
51 */
52 int sqlite3IndexHasDuplicateRootPage(Index *pIndex){
53   Index *p;
54   for(p=pIndex->pTable->pIndex; p; p=p->pNext){
55     if( p->tnum==pIndex->tnum && p!=pIndex ) return 1;
56   }
57   return 0;
58 }
59 
60 /* forward declaration */
61 static int sqlite3Prepare(
62   sqlite3 *db,              /* Database handle. */
63   const char *zSql,         /* UTF-8 encoded SQL statement. */
64   int nBytes,               /* Length of zSql in bytes. */
65   u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
66   Vdbe *pReprepare,         /* VM being reprepared */
67   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68   const char **pzTail       /* OUT: End of parsed string */
69 );
70 
71 
72 /*
73 ** This is the callback routine for the code that initializes the
74 ** database.  See sqlite3Init() below for additional information.
75 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
76 **
77 ** Each callback contains the following information:
78 **
79 **     argv[0] = type of object: "table", "index", "trigger", or "view".
80 **     argv[1] = name of thing being created
81 **     argv[2] = associated table if an index or trigger
82 **     argv[3] = root page number for table or index. 0 for trigger or view.
83 **     argv[4] = SQL text for the CREATE statement.
84 **
85 */
86 int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
87   InitData *pData = (InitData*)pInit;
88   sqlite3 *db = pData->db;
89   int iDb = pData->iDb;
90 
91   assert( argc==5 );
92   UNUSED_PARAMETER2(NotUsed, argc);
93   assert( sqlite3_mutex_held(db->mutex) );
94   db->mDbFlags |= DBFLAG_EncodingFixed;
95   pData->nInitRow++;
96   if( db->mallocFailed ){
97     corruptSchema(pData, argv[1], 0);
98     return 1;
99   }
100 
101   assert( iDb>=0 && iDb<db->nDb );
102   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
103   if( argv[3]==0 ){
104     corruptSchema(pData, argv[1], 0);
105   }else if( argv[4]
106          && 'c'==sqlite3UpperToLower[(unsigned char)argv[4][0]]
107          && 'r'==sqlite3UpperToLower[(unsigned char)argv[4][1]] ){
108     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
109     ** But because db->init.busy is set to 1, no VDBE code is generated
110     ** or executed.  All the parser does is build the internal data
111     ** structures that describe the table, index, or view.
112     **
113     ** No other valid SQL statement, other than the variable CREATE statements,
114     ** can begin with the letters "C" and "R".  Thus, it is not possible run
115     ** any other kind of statement while parsing the schema, even a corrupt
116     ** schema.
117     */
118     int rc;
119     u8 saved_iDb = db->init.iDb;
120     sqlite3_stmt *pStmt;
121     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
122 
123     assert( db->init.busy );
124     db->init.iDb = iDb;
125     if( sqlite3GetUInt32(argv[3], &db->init.newTnum)==0
126      || (db->init.newTnum>pData->mxPage && pData->mxPage>0)
127     ){
128       if( sqlite3Config.bExtraSchemaChecks ){
129         corruptSchema(pData, argv[1], "invalid rootpage");
130       }
131     }
132     db->init.orphanTrigger = 0;
133     db->init.azInit = argv;
134     pStmt = 0;
135     TESTONLY(rcp = ) sqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, 0);
136     rc = db->errCode;
137     assert( (rc&0xFF)==(rcp&0xFF) );
138     db->init.iDb = saved_iDb;
139     /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */
140     if( SQLITE_OK!=rc ){
141       if( db->init.orphanTrigger ){
142         assert( iDb==1 );
143       }else{
144         if( rc > pData->rc ) pData->rc = rc;
145         if( rc==SQLITE_NOMEM ){
146           sqlite3OomFault(db);
147         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
148           corruptSchema(pData, argv[1], sqlite3_errmsg(db));
149         }
150       }
151     }
152     sqlite3_finalize(pStmt);
153   }else if( argv[1]==0 || (argv[4]!=0 && argv[4][0]!=0) ){
154     corruptSchema(pData, argv[1], 0);
155   }else{
156     /* If the SQL column is blank it means this is an index that
157     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
158     ** constraint for a CREATE TABLE.  The index should have already
159     ** been created when we processed the CREATE TABLE.  All we have
160     ** to do here is record the root page number for that index.
161     */
162     Index *pIndex;
163     pIndex = sqlite3FindIndex(db, argv[1], db->aDb[iDb].zDbSName);
164     if( pIndex==0 ){
165       corruptSchema(pData, argv[1], "orphan index");
166     }else
167     if( sqlite3GetUInt32(argv[3],&pIndex->tnum)==0
168      || pIndex->tnum<2
169      || pIndex->tnum>pData->mxPage
170      || sqlite3IndexHasDuplicateRootPage(pIndex)
171     ){
172       if( sqlite3Config.bExtraSchemaChecks ){
173         corruptSchema(pData, argv[1], "invalid rootpage");
174       }
175     }
176   }
177   return 0;
178 }
179 
180 /*
181 ** Attempt to read the database schema and initialize internal
182 ** data structures for a single database file.  The index of the
183 ** database file is given by iDb.  iDb==0 is used for the main
184 ** database.  iDb==1 should never be used.  iDb>=2 is used for
185 ** auxiliary databases.  Return one of the SQLITE_ error codes to
186 ** indicate success or failure.
187 */
188 int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){
189   int rc;
190   int i;
191 #ifndef SQLITE_OMIT_DEPRECATED
192   int size;
193 #endif
194   Db *pDb;
195   char const *azArg[6];
196   int meta[5];
197   InitData initData;
198   const char *zSchemaTabName;
199   int openedTransaction = 0;
200   int mask = ((db->mDbFlags & DBFLAG_EncodingFixed) | ~DBFLAG_EncodingFixed);
201 
202   assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
203   assert( iDb>=0 && iDb<db->nDb );
204   assert( db->aDb[iDb].pSchema );
205   assert( sqlite3_mutex_held(db->mutex) );
206   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
207 
208   db->init.busy = 1;
209 
210   /* Construct the in-memory representation schema tables (sqlite_schema or
211   ** sqlite_temp_schema) by invoking the parser directly.  The appropriate
212   ** table name will be inserted automatically by the parser so we can just
213   ** use the abbreviation "x" here.  The parser will also automatically tag
214   ** the schema table as read-only. */
215   azArg[0] = "table";
216   azArg[1] = zSchemaTabName = SCHEMA_TABLE(iDb);
217   azArg[2] = azArg[1];
218   azArg[3] = "1";
219   azArg[4] = "CREATE TABLE x(type text,name text,tbl_name text,"
220                             "rootpage int,sql text)";
221   azArg[5] = 0;
222   initData.db = db;
223   initData.iDb = iDb;
224   initData.rc = SQLITE_OK;
225   initData.pzErrMsg = pzErrMsg;
226   initData.mInitFlags = mFlags;
227   initData.nInitRow = 0;
228   initData.mxPage = 0;
229   sqlite3InitCallback(&initData, 5, (char **)azArg, 0);
230   db->mDbFlags &= mask;
231   if( initData.rc ){
232     rc = initData.rc;
233     goto error_out;
234   }
235 
236   /* Create a cursor to hold the database open
237   */
238   pDb = &db->aDb[iDb];
239   if( pDb->pBt==0 ){
240     assert( iDb==1 );
241     DbSetProperty(db, 1, DB_SchemaLoaded);
242     rc = SQLITE_OK;
243     goto error_out;
244   }
245 
246   /* If there is not already a read-only (or read-write) transaction opened
247   ** on the b-tree database, open one now. If a transaction is opened, it
248   ** will be closed before this function returns.  */
249   sqlite3BtreeEnter(pDb->pBt);
250   if( sqlite3BtreeTxnState(pDb->pBt)==SQLITE_TXN_NONE ){
251     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);
252     if( rc!=SQLITE_OK ){
253       sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
254       goto initone_error_out;
255     }
256     openedTransaction = 1;
257   }
258 
259   /* Get the database meta information.
260   **
261   ** Meta values are as follows:
262   **    meta[0]   Schema cookie.  Changes with each schema change.
263   **    meta[1]   File format of schema layer.
264   **    meta[2]   Size of the page cache.
265   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
266   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
267   **    meta[5]   User version
268   **    meta[6]   Incremental vacuum mode
269   **    meta[7]   unused
270   **    meta[8]   unused
271   **    meta[9]   unused
272   **
273   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
274   ** the possible values of meta[4].
275   */
276   for(i=0; i<ArraySize(meta); i++){
277     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
278   }
279   if( (db->flags & SQLITE_ResetDatabase)!=0 ){
280     memset(meta, 0, sizeof(meta));
281   }
282   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
283 
284   /* If opening a non-empty database, check the text encoding. For the
285   ** main database, set sqlite3.enc to the encoding of the main database.
286   ** For an attached db, it is an error if the encoding is not the same
287   ** as sqlite3.enc.
288   */
289   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
290     if( iDb==0 && (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
291       u8 encoding;
292 #ifndef SQLITE_OMIT_UTF16
293       /* If opening the main database, set ENC(db). */
294       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
295       if( encoding==0 ) encoding = SQLITE_UTF8;
296 #else
297       encoding = SQLITE_UTF8;
298 #endif
299       sqlite3SetTextEncoding(db, encoding);
300     }else{
301       /* If opening an attached database, the encoding much match ENC(db) */
302       if( (meta[BTREE_TEXT_ENCODING-1] & 3)!=ENC(db) ){
303         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
304             " text encoding as main database");
305         rc = SQLITE_ERROR;
306         goto initone_error_out;
307       }
308     }
309   }
310   pDb->pSchema->enc = ENC(db);
311 
312   if( pDb->pSchema->cache_size==0 ){
313 #ifndef SQLITE_OMIT_DEPRECATED
314     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
315     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
316     pDb->pSchema->cache_size = size;
317 #else
318     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
319 #endif
320     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
321   }
322 
323   /*
324   ** file_format==1    Version 3.0.0.
325   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
326   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
327   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
328   */
329   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
330   if( pDb->pSchema->file_format==0 ){
331     pDb->pSchema->file_format = 1;
332   }
333   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
334     sqlite3SetString(pzErrMsg, db, "unsupported file format");
335     rc = SQLITE_ERROR;
336     goto initone_error_out;
337   }
338 
339   /* Ticket #2804:  When we open a database in the newer file format,
340   ** clear the legacy_file_format pragma flag so that a VACUUM will
341   ** not downgrade the database and thus invalidate any descending
342   ** indices that the user might have created.
343   */
344   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
345     db->flags &= ~(u64)SQLITE_LegacyFileFmt;
346   }
347 
348   /* Read the schema information out of the schema tables
349   */
350   assert( db->init.busy );
351   initData.mxPage = sqlite3BtreeLastPage(pDb->pBt);
352   {
353     char *zSql;
354     zSql = sqlite3MPrintf(db,
355         "SELECT*FROM\"%w\".%s ORDER BY rowid",
356         db->aDb[iDb].zDbSName, zSchemaTabName);
357 #ifndef SQLITE_OMIT_AUTHORIZATION
358     {
359       sqlite3_xauth xAuth;
360       xAuth = db->xAuth;
361       db->xAuth = 0;
362 #endif
363       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
364 #ifndef SQLITE_OMIT_AUTHORIZATION
365       db->xAuth = xAuth;
366     }
367 #endif
368     if( rc==SQLITE_OK ) rc = initData.rc;
369     sqlite3DbFree(db, zSql);
370 #ifndef SQLITE_OMIT_ANALYZE
371     if( rc==SQLITE_OK ){
372       sqlite3AnalysisLoad(db, iDb);
373     }
374 #endif
375   }
376   if( db->mallocFailed ){
377     rc = SQLITE_NOMEM_BKPT;
378     sqlite3ResetAllSchemasOfConnection(db);
379   }
380   if( rc==SQLITE_OK || (db->flags&SQLITE_NoSchemaError)){
381     /* Black magic: If the SQLITE_NoSchemaError flag is set, then consider
382     ** the schema loaded, even if errors occurred. In this situation the
383     ** current sqlite3_prepare() operation will fail, but the following one
384     ** will attempt to compile the supplied statement against whatever subset
385     ** of the schema was loaded before the error occurred. The primary
386     ** purpose of this is to allow access to the sqlite_schema table
387     ** even when its contents have been corrupted.
388     */
389     DbSetProperty(db, iDb, DB_SchemaLoaded);
390     rc = SQLITE_OK;
391   }
392 
393   /* Jump here for an error that occurs after successfully allocating
394   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
395   ** before that point, jump to error_out.
396   */
397 initone_error_out:
398   if( openedTransaction ){
399     sqlite3BtreeCommit(pDb->pBt);
400   }
401   sqlite3BtreeLeave(pDb->pBt);
402 
403 error_out:
404   if( rc ){
405     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
406       sqlite3OomFault(db);
407     }
408     sqlite3ResetOneSchema(db, iDb);
409   }
410   db->init.busy = 0;
411   return rc;
412 }
413 
414 /*
415 ** Initialize all database files - the main database file, the file
416 ** used to store temporary tables, and any additional database files
417 ** created using ATTACH statements.  Return a success code.  If an
418 ** error occurs, write an error message into *pzErrMsg.
419 **
420 ** After a database is initialized, the DB_SchemaLoaded bit is set
421 ** bit is set in the flags field of the Db structure.
422 */
423 int sqlite3Init(sqlite3 *db, char **pzErrMsg){
424   int i, rc;
425   int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
426 
427   assert( sqlite3_mutex_held(db->mutex) );
428   assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
429   assert( db->init.busy==0 );
430   ENC(db) = SCHEMA_ENC(db);
431   assert( db->nDb>0 );
432   /* Do the main schema first */
433   if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
434     rc = sqlite3InitOne(db, 0, pzErrMsg, 0);
435     if( rc ) return rc;
436   }
437   /* All other schemas after the main schema. The "temp" schema must be last */
438   for(i=db->nDb-1; i>0; i--){
439     assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );
440     if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
441       rc = sqlite3InitOne(db, i, pzErrMsg, 0);
442       if( rc ) return rc;
443     }
444   }
445   if( commit_internal ){
446     sqlite3CommitInternalChanges(db);
447   }
448   return SQLITE_OK;
449 }
450 
451 /*
452 ** This routine is a no-op if the database schema is already initialized.
453 ** Otherwise, the schema is loaded. An error code is returned.
454 */
455 int sqlite3ReadSchema(Parse *pParse){
456   int rc = SQLITE_OK;
457   sqlite3 *db = pParse->db;
458   assert( sqlite3_mutex_held(db->mutex) );
459   if( !db->init.busy ){
460     rc = sqlite3Init(db, &pParse->zErrMsg);
461     if( rc!=SQLITE_OK ){
462       pParse->rc = rc;
463       pParse->nErr++;
464     }else if( db->noSharedCache ){
465       db->mDbFlags |= DBFLAG_SchemaKnownOk;
466     }
467   }
468   return rc;
469 }
470 
471 
472 /*
473 ** Check schema cookies in all databases.  If any cookie is out
474 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
475 ** make no changes to pParse->rc.
476 */
477 static void schemaIsValid(Parse *pParse){
478   sqlite3 *db = pParse->db;
479   int iDb;
480   int rc;
481   int cookie;
482 
483   assert( pParse->checkSchema );
484   assert( sqlite3_mutex_held(db->mutex) );
485   for(iDb=0; iDb<db->nDb; iDb++){
486     int openedTransaction = 0;         /* True if a transaction is opened */
487     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
488     if( pBt==0 ) continue;
489 
490     /* If there is not already a read-only (or read-write) transaction opened
491     ** on the b-tree database, open one now. If a transaction is opened, it
492     ** will be closed immediately after reading the meta-value. */
493     if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_NONE ){
494       rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
495       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
496         sqlite3OomFault(db);
497       }
498       if( rc!=SQLITE_OK ) return;
499       openedTransaction = 1;
500     }
501 
502     /* Read the schema cookie from the database. If it does not match the
503     ** value stored as part of the in-memory schema representation,
504     ** set Parse.rc to SQLITE_SCHEMA. */
505     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
506     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
507     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
508       sqlite3ResetOneSchema(db, iDb);
509       pParse->rc = SQLITE_SCHEMA;
510     }
511 
512     /* Close the transaction, if one was opened. */
513     if( openedTransaction ){
514       sqlite3BtreeCommit(pBt);
515     }
516   }
517 }
518 
519 /*
520 ** Convert a schema pointer into the iDb index that indicates
521 ** which database file in db->aDb[] the schema refers to.
522 **
523 ** If the same database is attached more than once, the first
524 ** attached database is returned.
525 */
526 int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
527   int i = -32768;
528 
529   /* If pSchema is NULL, then return -32768. This happens when code in
530   ** expr.c is trying to resolve a reference to a transient table (i.e. one
531   ** created by a sub-select). In this case the return value of this
532   ** function should never be used.
533   **
534   ** We return -32768 instead of the more usual -1 simply because using
535   ** -32768 as the incorrect index into db->aDb[] is much
536   ** more likely to cause a segfault than -1 (of course there are assert()
537   ** statements too, but it never hurts to play the odds) and
538   ** -32768 will still fit into a 16-bit signed integer.
539   */
540   assert( sqlite3_mutex_held(db->mutex) );
541   if( pSchema ){
542     for(i=0; 1; i++){
543       assert( i<db->nDb );
544       if( db->aDb[i].pSchema==pSchema ){
545         break;
546       }
547     }
548     assert( i>=0 && i<db->nDb );
549   }
550   return i;
551 }
552 
553 /*
554 ** Deallocate a single AggInfo object
555 */
556 static void agginfoFree(sqlite3 *db, AggInfo *p){
557   sqlite3DbFree(db, p->aCol);
558   sqlite3DbFree(db, p->aFunc);
559   sqlite3DbFree(db, p);
560 }
561 
562 /*
563 ** Free all memory allocations in the pParse object
564 */
565 void sqlite3ParserReset(Parse *pParse){
566   sqlite3 *db = pParse->db;
567   AggInfo *pThis = pParse->pAggList;
568   while( pThis ){
569     AggInfo *pNext = pThis->pNext;
570     agginfoFree(db, pThis);
571     pThis = pNext;
572   }
573   while( pParse->pCleanup ){
574     ParseCleanup *pCleanup = pParse->pCleanup;
575     pParse->pCleanup = pCleanup->pNext;
576     pCleanup->xCleanup(db, pCleanup->pPtr);
577     sqlite3DbFree(db, pCleanup);
578   }
579   sqlite3DbFree(db, pParse->aLabel);
580   if( pParse->pConstExpr ){
581     sqlite3ExprListDelete(db, pParse->pConstExpr);
582   }
583   if( db ){
584     assert( db->lookaside.bDisable >= pParse->disableLookaside );
585     db->lookaside.bDisable -= pParse->disableLookaside;
586     db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue;
587   }
588   pParse->disableLookaside = 0;
589 }
590 
591 /*
592 ** Add a new cleanup operation to a Parser.  The cleanup should happen when
593 ** the parser object is destroyed.  But, beware: the cleanup might happen
594 ** immediately.
595 **
596 ** Use this mechanism for uncommon cleanups.  There is a higher setup
597 ** cost for this mechansim (an extra malloc), so it should not be used
598 ** for common cleanups that happen on most calls.  But for less
599 ** common cleanups, we save a single NULL-pointer comparison in
600 ** sqlite3ParserReset(), which reduces the total CPU cycle count.
601 **
602 ** If a memory allocation error occurs, then the cleanup happens immediately.
603 ** When eithr SQLITE_DEBUG or SQLITE_COVERAGE_TEST are defined, the
604 ** pParse->earlyCleanup flag is set in that case.  Calling code show verify
605 ** that test cases exist for which this happens, to guard against possible
606 ** use-after-free errors following an OOM.  The preferred way to do this is
607 ** to immediately follow the call to this routine with:
608 **
609 **       testcase( pParse->earlyCleanup );
610 */
611 void sqlite3ParserAddCleanup(
612   Parse *pParse,                      /* Destroy when this Parser finishes */
613   void (*xCleanup)(sqlite3*,void*),   /* The cleanup routine */
614   void *pPtr                          /* Pointer to object to be cleaned up */
615 ){
616   ParseCleanup *pCleanup = sqlite3DbMallocRaw(pParse->db, sizeof(*pCleanup));
617   if( pCleanup ){
618     pCleanup->pNext = pParse->pCleanup;
619     pParse->pCleanup = pCleanup;
620     pCleanup->pPtr = pPtr;
621     pCleanup->xCleanup = xCleanup;
622   }else{
623     xCleanup(pParse->db, pPtr);
624 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
625     pParse->earlyCleanup = 1;
626 #endif
627   }
628 }
629 
630 /*
631 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
632 */
633 static int sqlite3Prepare(
634   sqlite3 *db,              /* Database handle. */
635   const char *zSql,         /* UTF-8 encoded SQL statement. */
636   int nBytes,               /* Length of zSql in bytes. */
637   u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
638   Vdbe *pReprepare,         /* VM being reprepared */
639   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
640   const char **pzTail       /* OUT: End of parsed string */
641 ){
642   char *zErrMsg = 0;        /* Error message */
643   int rc = SQLITE_OK;       /* Result code */
644   int i;                    /* Loop counter */
645   Parse sParse;             /* Parsing context */
646 
647   memset(&sParse, 0, PARSE_HDR_SZ);
648   memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
649   sParse.pReprepare = pReprepare;
650   assert( ppStmt && *ppStmt==0 );
651   /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
652   assert( sqlite3_mutex_held(db->mutex) );
653 
654   /* For a long-term use prepared statement avoid the use of
655   ** lookaside memory.
656   */
657   if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
658     sParse.disableLookaside++;
659     DisableLookaside;
660   }
661   sParse.disableVtab = (prepFlags & SQLITE_PREPARE_NO_VTAB)!=0;
662 
663   /* Check to verify that it is possible to get a read lock on all
664   ** database schemas.  The inability to get a read lock indicates that
665   ** some other database connection is holding a write-lock, which in
666   ** turn means that the other connection has made uncommitted changes
667   ** to the schema.
668   **
669   ** Were we to proceed and prepare the statement against the uncommitted
670   ** schema changes and if those schema changes are subsequently rolled
671   ** back and different changes are made in their place, then when this
672   ** prepared statement goes to run the schema cookie would fail to detect
673   ** the schema change.  Disaster would follow.
674   **
675   ** This thread is currently holding mutexes on all Btrees (because
676   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
677   ** is not possible for another thread to start a new schema change
678   ** while this routine is running.  Hence, we do not need to hold
679   ** locks on the schema, we just need to make sure nobody else is
680   ** holding them.
681   **
682   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
683   ** but it does *not* override schema lock detection, so this all still
684   ** works even if READ_UNCOMMITTED is set.
685   */
686   if( !db->noSharedCache ){
687     for(i=0; i<db->nDb; i++) {
688       Btree *pBt = db->aDb[i].pBt;
689       if( pBt ){
690         assert( sqlite3BtreeHoldsMutex(pBt) );
691         rc = sqlite3BtreeSchemaLocked(pBt);
692         if( rc ){
693           const char *zDb = db->aDb[i].zDbSName;
694           sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
695           testcase( db->flags & SQLITE_ReadUncommit );
696           goto end_prepare;
697         }
698       }
699     }
700   }
701 
702   sqlite3VtabUnlockList(db);
703 
704   sParse.db = db;
705   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
706     char *zSqlCopy;
707     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
708     testcase( nBytes==mxLen );
709     testcase( nBytes==mxLen+1 );
710     if( nBytes>mxLen ){
711       sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
712       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
713       goto end_prepare;
714     }
715     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
716     if( zSqlCopy ){
717       sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
718       sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
719       sqlite3DbFree(db, zSqlCopy);
720     }else{
721       sParse.zTail = &zSql[nBytes];
722     }
723   }else{
724     sqlite3RunParser(&sParse, zSql, &zErrMsg);
725   }
726   assert( 0==sParse.nQueryLoop );
727 
728   if( pzTail ){
729     *pzTail = sParse.zTail;
730   }
731 
732   if( db->init.busy==0 ){
733     sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
734   }
735   if( db->mallocFailed ){
736     sParse.rc = SQLITE_NOMEM_BKPT;
737   }
738   if( sParse.rc!=SQLITE_OK && sParse.rc!=SQLITE_DONE ){
739     if( sParse.checkSchema ){
740       schemaIsValid(&sParse);
741     }
742     if( sParse.pVdbe ){
743       sqlite3VdbeFinalize(sParse.pVdbe);
744     }
745     assert( 0==(*ppStmt) );
746     rc = sParse.rc;
747     if( zErrMsg ){
748       sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
749       sqlite3DbFree(db, zErrMsg);
750     }else{
751       sqlite3Error(db, rc);
752     }
753   }else{
754     assert( zErrMsg==0 );
755     *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
756     rc = SQLITE_OK;
757     sqlite3ErrorClear(db);
758   }
759 
760 
761   /* Delete any TriggerPrg structures allocated while parsing this statement. */
762   while( sParse.pTriggerPrg ){
763     TriggerPrg *pT = sParse.pTriggerPrg;
764     sParse.pTriggerPrg = pT->pNext;
765     sqlite3DbFree(db, pT);
766   }
767 
768 end_prepare:
769 
770   sqlite3ParserReset(&sParse);
771   return rc;
772 }
773 static int sqlite3LockAndPrepare(
774   sqlite3 *db,              /* Database handle. */
775   const char *zSql,         /* UTF-8 encoded SQL statement. */
776   int nBytes,               /* Length of zSql in bytes. */
777   u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
778   Vdbe *pOld,               /* VM being reprepared */
779   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
780   const char **pzTail       /* OUT: End of parsed string */
781 ){
782   int rc;
783   int cnt = 0;
784 
785 #ifdef SQLITE_ENABLE_API_ARMOR
786   if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
787 #endif
788   *ppStmt = 0;
789   if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
790     return SQLITE_MISUSE_BKPT;
791   }
792   sqlite3_mutex_enter(db->mutex);
793   sqlite3BtreeEnterAll(db);
794   do{
795     /* Make multiple attempts to compile the SQL, until it either succeeds
796     ** or encounters a permanent error.  A schema problem after one schema
797     ** reset is considered a permanent error. */
798     rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
799     assert( rc==SQLITE_OK || *ppStmt==0 );
800   }while( rc==SQLITE_ERROR_RETRY
801        || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
802   sqlite3BtreeLeaveAll(db);
803   rc = sqlite3ApiExit(db, rc);
804   assert( (rc&db->errMask)==rc );
805   db->busyHandler.nBusy = 0;
806   sqlite3_mutex_leave(db->mutex);
807   return rc;
808 }
809 
810 
811 /*
812 ** Rerun the compilation of a statement after a schema change.
813 **
814 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
815 ** if the statement cannot be recompiled because another connection has
816 ** locked the sqlite3_schema table, return SQLITE_LOCKED. If any other error
817 ** occurs, return SQLITE_SCHEMA.
818 */
819 int sqlite3Reprepare(Vdbe *p){
820   int rc;
821   sqlite3_stmt *pNew;
822   const char *zSql;
823   sqlite3 *db;
824   u8 prepFlags;
825 
826   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
827   zSql = sqlite3_sql((sqlite3_stmt *)p);
828   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
829   db = sqlite3VdbeDb(p);
830   assert( sqlite3_mutex_held(db->mutex) );
831   prepFlags = sqlite3VdbePrepareFlags(p);
832   rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
833   if( rc ){
834     if( rc==SQLITE_NOMEM ){
835       sqlite3OomFault(db);
836     }
837     assert( pNew==0 );
838     return rc;
839   }else{
840     assert( pNew!=0 );
841   }
842   sqlite3VdbeSwap((Vdbe*)pNew, p);
843   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
844   sqlite3VdbeResetStepResult((Vdbe*)pNew);
845   sqlite3VdbeFinalize((Vdbe*)pNew);
846   return SQLITE_OK;
847 }
848 
849 
850 /*
851 ** Two versions of the official API.  Legacy and new use.  In the legacy
852 ** version, the original SQL text is not saved in the prepared statement
853 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
854 ** sqlite3_step().  In the new version, the original SQL text is retained
855 ** and the statement is automatically recompiled if an schema change
856 ** occurs.
857 */
858 int sqlite3_prepare(
859   sqlite3 *db,              /* Database handle. */
860   const char *zSql,         /* UTF-8 encoded SQL statement. */
861   int nBytes,               /* Length of zSql in bytes. */
862   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
863   const char **pzTail       /* OUT: End of parsed string */
864 ){
865   int rc;
866   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
867   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
868   return rc;
869 }
870 int sqlite3_prepare_v2(
871   sqlite3 *db,              /* Database handle. */
872   const char *zSql,         /* UTF-8 encoded SQL statement. */
873   int nBytes,               /* Length of zSql in bytes. */
874   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
875   const char **pzTail       /* OUT: End of parsed string */
876 ){
877   int rc;
878   /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
879   ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
880   ** parameter.
881   **
882   ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
883   rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
884                              ppStmt,pzTail);
885   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
886   return rc;
887 }
888 int sqlite3_prepare_v3(
889   sqlite3 *db,              /* Database handle. */
890   const char *zSql,         /* UTF-8 encoded SQL statement. */
891   int nBytes,               /* Length of zSql in bytes. */
892   unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
893   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
894   const char **pzTail       /* OUT: End of parsed string */
895 ){
896   int rc;
897   /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
898   ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
899   ** which is a bit array consisting of zero or more of the
900   ** SQLITE_PREPARE_* flags.
901   **
902   ** Proof by comparison to the implementation of sqlite3_prepare_v2()
903   ** directly above. */
904   rc = sqlite3LockAndPrepare(db,zSql,nBytes,
905                  SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
906                  0,ppStmt,pzTail);
907   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
908   return rc;
909 }
910 
911 
912 #ifndef SQLITE_OMIT_UTF16
913 /*
914 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
915 */
916 static int sqlite3Prepare16(
917   sqlite3 *db,              /* Database handle. */
918   const void *zSql,         /* UTF-16 encoded SQL statement. */
919   int nBytes,               /* Length of zSql in bytes. */
920   u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
921   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
922   const void **pzTail       /* OUT: End of parsed string */
923 ){
924   /* This function currently works by first transforming the UTF-16
925   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
926   ** tricky bit is figuring out the pointer to return in *pzTail.
927   */
928   char *zSql8;
929   const char *zTail8 = 0;
930   int rc = SQLITE_OK;
931 
932 #ifdef SQLITE_ENABLE_API_ARMOR
933   if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
934 #endif
935   *ppStmt = 0;
936   if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
937     return SQLITE_MISUSE_BKPT;
938   }
939   if( nBytes>=0 ){
940     int sz;
941     const char *z = (const char*)zSql;
942     for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
943     nBytes = sz;
944   }
945   sqlite3_mutex_enter(db->mutex);
946   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
947   if( zSql8 ){
948     rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
949   }
950 
951   if( zTail8 && pzTail ){
952     /* If sqlite3_prepare returns a tail pointer, we calculate the
953     ** equivalent pointer into the UTF-16 string by counting the unicode
954     ** characters between zSql8 and zTail8, and then returning a pointer
955     ** the same number of characters into the UTF-16 string.
956     */
957     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
958     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
959   }
960   sqlite3DbFree(db, zSql8);
961   rc = sqlite3ApiExit(db, rc);
962   sqlite3_mutex_leave(db->mutex);
963   return rc;
964 }
965 
966 /*
967 ** Two versions of the official API.  Legacy and new use.  In the legacy
968 ** version, the original SQL text is not saved in the prepared statement
969 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
970 ** sqlite3_step().  In the new version, the original SQL text is retained
971 ** and the statement is automatically recompiled if an schema change
972 ** occurs.
973 */
974 int sqlite3_prepare16(
975   sqlite3 *db,              /* Database handle. */
976   const void *zSql,         /* UTF-16 encoded SQL statement. */
977   int nBytes,               /* Length of zSql in bytes. */
978   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
979   const void **pzTail       /* OUT: End of parsed string */
980 ){
981   int rc;
982   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
983   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
984   return rc;
985 }
986 int sqlite3_prepare16_v2(
987   sqlite3 *db,              /* Database handle. */
988   const void *zSql,         /* UTF-16 encoded SQL statement. */
989   int nBytes,               /* Length of zSql in bytes. */
990   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
991   const void **pzTail       /* OUT: End of parsed string */
992 ){
993   int rc;
994   rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
995   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
996   return rc;
997 }
998 int sqlite3_prepare16_v3(
999   sqlite3 *db,              /* Database handle. */
1000   const void *zSql,         /* UTF-16 encoded SQL statement. */
1001   int nBytes,               /* Length of zSql in bytes. */
1002   unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
1003   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
1004   const void **pzTail       /* OUT: End of parsed string */
1005 ){
1006   int rc;
1007   rc = sqlite3Prepare16(db,zSql,nBytes,
1008          SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
1009          ppStmt,pzTail);
1010   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
1011   return rc;
1012 }
1013 
1014 #endif /* SQLITE_OMIT_UTF16 */
1015