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