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