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