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