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