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