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