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