]> git.ipfire.org Git - thirdparty/sqlite.git/blame - src/prepare.c
Add an sqlite3FaultSim(300) call to the sqlite3ParserAddCleanup() routine
[thirdparty/sqlite.git] / src / prepare.c
CommitLineData
fa256a33 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.
fa256a33 15*/
16#include "sqliteInt.h"
fa256a33 17
18/*
19** Fill the InitData structure with an error message that indicates
20** that the database is corrupt.
21*/
34533150 22static void corruptSchema(
23 InitData *pData, /* Initialization context */
6a5a13df 24 char **azObj, /* Type and name of object being parsed */
34533150 25 const char *zExtra /* Error information */
26){
c456e57a 27 sqlite3 *db = pData->db;
1595abcd 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 */
ac894af8 32 }else if( pData->mInitFlags & (INITFLAG_AlterMask) ){
33 static const char *azAlterType[] = {
34 "rename",
35 "drop column",
36 "add column"
37 };
6a5a13df 38 *pData->pzErrMsg = sqlite3MPrintf(db,
39 "error in %s %s after %s: %s", azObj[0], azObj[1],
ac894af8 40 azAlterType[(pData->mInitFlags&INITFLAG_AlterMask)-1],
6a5a13df 41 zExtra
42 );
1595abcd 43 pData->rc = SQLITE_ERROR;
44 }else if( db->flags & SQLITE_WriteSchema ){
45 pData->rc = SQLITE_CORRUPT_BKPT;
46 }else{
22c17b8b 47 char *z;
6a5a13df 48 const char *zObj = azObj[1] ? azObj[1] : "?";
17a936f8 49 z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
1e9c47be 50 if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
22c17b8b 51 *pData->pzErrMsg = z;
1595abcd 52 pData->rc = SQLITE_CORRUPT_BKPT;
fa256a33 53 }
54}
55
8d40673c 56/*
57** Check to see if any sibling index (another index on the same table)
58** of pIndex has the same root page number, and if it does, return true.
59** This would indicate a corrupt schema.
60*/
61int sqlite3IndexHasDuplicateRootPage(Index *pIndex){
62 Index *p;
63 for(p=pIndex->pTable->pIndex; p; p=p->pNext){
64 if( p->tnum==pIndex->tnum && p!=pIndex ) return 1;
65 }
66 return 0;
67}
68
a22d2fca 69/* forward declaration */
70static int sqlite3Prepare(
71 sqlite3 *db, /* Database handle. */
72 const char *zSql, /* UTF-8 encoded SQL statement. */
73 int nBytes, /* Length of zSql in bytes. */
74 u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
75 Vdbe *pReprepare, /* VM being reprepared */
76 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
77 const char **pzTail /* OUT: End of parsed string */
78);
79
80
fa256a33 81/*
82** This is the callback routine for the code that initializes the
83** database. See sqlite3Init() below for additional information.
84** This routine is also called from the OP_ParseSchema opcode of the VDBE.
85**
86** Each callback contains the following information:
87**
c5a93d4c 88** argv[0] = type of object: "table", "index", "trigger", or "view".
89** argv[1] = name of thing being created
90** argv[2] = associated table if an index or trigger
91** argv[3] = root page number for table or index. 0 for trigger or view.
92** argv[4] = SQL text for the CREATE statement.
fa256a33 93**
94*/
62c14b34 95int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
fa256a33 96 InitData *pData = (InitData*)pInit;
97 sqlite3 *db = pData->db;
ece3c728 98 int iDb = pData->iDb;
fa256a33 99
c5a93d4c 100 assert( argc==5 );
f3d3c27a 101 UNUSED_PARAMETER2(NotUsed, argc);
b1ab8ea7 102 assert( sqlite3_mutex_held(db->mutex) );
0ea2d42a 103 db->mDbFlags |= DBFLAG_EncodingFixed;
6000e08d 104 if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
6b86e51e 105 pData->nInitRow++;
17435752 106 if( db->mallocFailed ){
6a5a13df 107 corruptSchema(pData, argv, 0);
9da742f9 108 return 1;
da184236 109 }
110
ff9b2e75 111 assert( iDb>=0 && iDb<db->nDb );
c5a93d4c 112 if( argv[3]==0 ){
6a5a13df 113 corruptSchema(pData, argv, 0);
630fc34c 114 }else if( argv[4]
115 && 'c'==sqlite3UpperToLower[(unsigned char)argv[4][0]]
116 && 'r'==sqlite3UpperToLower[(unsigned char)argv[4][1]] ){
fa256a33 117 /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
118 ** But because db->init.busy is set to 1, no VDBE code is generated
119 ** or executed. All the parser does is build the internal data
120 ** structures that describe the table, index, or view.
630fc34c 121 **
122 ** No other valid SQL statement, other than the variable CREATE statements,
123 ** can begin with the letters "C" and "R". Thus, it is not possible run
124 ** any other kind of statement while parsing the schema, even a corrupt
125 ** schema.
fa256a33 126 */
fa256a33 127 int rc;
9ef5e770 128 u8 saved_iDb = db->init.iDb;
6498f0bb 129 sqlite3_stmt *pStmt;
9e55d47d 130 TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
6498f0bb 131
fa256a33 132 assert( db->init.busy );
133 db->init.iDb = iDb;
69306bf4 134 if( sqlite3GetUInt32(argv[3], &db->init.newTnum)==0
135 || (db->init.newTnum>pData->mxPage && pData->mxPage>0)
136 ){
ca439a49 137 if( sqlite3Config.bExtraSchemaChecks ){
6a5a13df 138 corruptSchema(pData, argv, "invalid rootpage");
ca439a49 139 }
3b3ddbae 140 }
3d5f74b2 141 db->init.orphanTrigger = 0;
2a6a72a8 142 db->init.azInit = (const char**)argv;
a22d2fca 143 pStmt = 0;
144 TESTONLY(rcp = ) sqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, 0);
9859c427 145 rc = db->errCode;
146 assert( (rc&0xFF)==(rcp&0xFF) );
9ef5e770 147 db->init.iDb = saved_iDb;
c9461ecc 148 /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */
fa256a33 149 if( SQLITE_OK!=rc ){
3d5f74b2 150 if( db->init.orphanTrigger ){
151 assert( iDb==1 );
152 }else{
d4da4936 153 if( rc > pData->rc ) pData->rc = rc;
3d5f74b2 154 if( rc==SQLITE_NOMEM ){
4a642b60 155 sqlite3OomFault(db);
9859c427 156 }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
6a5a13df 157 corruptSchema(pData, argv, sqlite3_errmsg(db));
3d5f74b2 158 }
261919cc 159 }
fa256a33 160 }
2a6a72a8 161 db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
6498f0bb 162 sqlite3_finalize(pStmt);
c5a93d4c 163 }else if( argv[1]==0 || (argv[4]!=0 && argv[4][0]!=0) ){
6a5a13df 164 corruptSchema(pData, argv, 0);
fa256a33 165 }else{
166 /* If the SQL column is blank it means this is an index that
167 ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
168 ** constraint for a CREATE TABLE. The index should have already
169 ** been created when we processed the CREATE TABLE. All we have
170 ** to do here is record the root page number for that index.
171 */
172 Index *pIndex;
c5a93d4c 173 pIndex = sqlite3FindIndex(db, argv[1], db->aDb[iDb].zDbSName);
69306bf4 174 if( pIndex==0 ){
6a5a13df 175 corruptSchema(pData, argv, "orphan index");
69306bf4 176 }else
177 if( sqlite3GetUInt32(argv[3],&pIndex->tnum)==0
69ab18d2 178 || pIndex->tnum<2
48bf2d72 179 || pIndex->tnum>pData->mxPage
8d40673c 180 || sqlite3IndexHasDuplicateRootPage(pIndex)
69ab18d2 181 ){
ca439a49 182 if( sqlite3Config.bExtraSchemaChecks ){
6a5a13df 183 corruptSchema(pData, argv, "invalid rootpage");
ca439a49 184 }
fa256a33 185 }
186 }
187 return 0;
188}
189
190/*
191** Attempt to read the database schema and initialize internal
192** data structures for a single database file. The index of the
193** database file is given by iDb. iDb==0 is used for the main
194** database. iDb==1 should never be used. iDb>=2 is used for
195** auxiliary databases. Return one of the SQLITE_ error codes to
196** indicate success or failure.
197*/
1595abcd 198int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){
fa256a33 199 int rc;
8a939190 200 int i;
ba2bba3c 201#ifndef SQLITE_OMIT_DEPRECATED
fa256a33 202 int size;
ba2bba3c 203#endif
fdd6e85a 204 Db *pDb;
c5a93d4c 205 char const *azArg[6];
0d19f7ac 206 int meta[5];
fa256a33 207 InitData initData;
067b92ba 208 const char *zSchemaTabName;
94b30733 209 int openedTransaction = 0;
0ea2d42a 210 int mask = ((db->mDbFlags & DBFLAG_EncodingFixed) | ~DBFLAG_EncodingFixed);
fa256a33 211
b2c8559f 212 assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
fa256a33 213 assert( iDb>=0 && iDb<db->nDb );
14db2665 214 assert( db->aDb[iDb].pSchema );
b1ab8ea7 215 assert( sqlite3_mutex_held(db->mutex) );
4eab8b7b 216 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
da184236 217
36494b8b 218 db->init.busy = 1;
219
1e32bed3 220 /* Construct the in-memory representation schema tables (sqlite_schema or
221 ** sqlite_temp_schema) by invoking the parser directly. The appropriate
055f298a 222 ** table name will be inserted automatically by the parser so we can just
223 ** use the abbreviation "x" here. The parser will also automatically tag
224 ** the schema table as read-only. */
c5a93d4c 225 azArg[0] = "table";
067b92ba 226 azArg[1] = zSchemaTabName = SCHEMA_TABLE(iDb);
c5a93d4c 227 azArg[2] = azArg[1];
228 azArg[3] = "1";
229 azArg[4] = "CREATE TABLE x(type text,name text,tbl_name text,"
36494b8b 230 "rootpage int,sql text)";
c5a93d4c 231 azArg[5] = 0;
fa256a33 232 initData.db = db;
ece3c728 233 initData.iDb = iDb;
c456e57a 234 initData.rc = SQLITE_OK;
fa256a33 235 initData.pzErrMsg = pzErrMsg;
1595abcd 236 initData.mInitFlags = mFlags;
6b86e51e 237 initData.nInitRow = 0;
3b3ddbae 238 initData.mxPage = 0;
c5a93d4c 239 sqlite3InitCallback(&initData, 5, (char **)azArg, 0);
0ea2d42a 240 db->mDbFlags &= mask;
c456e57a 241 if( initData.rc ){
a1644fd8 242 rc = initData.rc;
243 goto error_out;
fa256a33 244 }
fa256a33 245
246 /* Create a cursor to hold the database open
247 */
fdd6e85a 248 pDb = &db->aDb[iDb];
249 if( pDb->pBt==0 ){
36494b8b 250 assert( iDb==1 );
251 DbSetProperty(db, 1, DB_SchemaLoaded);
252 rc = SQLITE_OK;
253 goto error_out;
fa256a33 254 }
602b466e 255
256 /* If there is not already a read-only (or read-write) transaction opened
257 ** on the b-tree database, open one now. If a transaction is opened, it
258 ** will be closed before this function returns. */
b1ab8ea7 259 sqlite3BtreeEnter(pDb->pBt);
99744fa4 260 if( sqlite3BtreeTxnState(pDb->pBt)==SQLITE_TXN_NONE ){
bb2d9b1b 261 rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);
602b466e 262 if( rc!=SQLITE_OK ){
22c17b8b 263 sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
602b466e 264 goto initone_error_out;
265 }
266 openedTransaction = 1;
602b466e 267 }
fa256a33 268
269 /* Get the database meta information.
270 **
271 ** Meta values are as follows:
272 ** meta[0] Schema cookie. Changes with each schema change.
273 ** meta[1] File format of schema layer.
274 ** meta[2] Size of the page cache.
27731d7c 275 ** meta[3] Largest rootpage (auto/incr_vacuum mode)
8159a35f 276 ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
27731d7c 277 ** meta[5] User version
278 ** meta[6] Incremental vacuum mode
279 ** meta[7] unused
280 ** meta[8] unused
281 ** meta[9] unused
fa256a33 282 **
f248e211 283 ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
fa256a33 284 ** the possible values of meta[4].
285 */
602b466e 286 for(i=0; i<ArraySize(meta); i++){
287 sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
0d19f7ac 288 }
0314cf3a 289 if( (db->flags & SQLITE_ResetDatabase)!=0 ){
290 memset(meta, 0, sizeof(meta));
291 }
0d19f7ac 292 pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
fa256a33 293
294 /* If opening a non-empty database, check the text encoding. For the
295 ** main database, set sqlite3.enc to the encoding of the main database.
296 ** For an attached db, it is an error if the encoding is not the same
297 ** as sqlite3.enc.
298 */
0d19f7ac 299 if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
0ea2d42a 300 if( iDb==0 && (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
c5e47ac2 301 u8 encoding;
42a630b1 302#ifndef SQLITE_OMIT_UTF16
14db2665 303 /* If opening the main database, set ENC(db). */
c5e47ac2 304 encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
305 if( encoding==0 ) encoding = SQLITE_UTF8;
dbd4d5fc 306#else
42a630b1 307 encoding = SQLITE_UTF8;
dbd4d5fc 308#endif
359c5ac1 309 if( db->nVdbeActive>0 && encoding!=ENC(db)
310 && (db->mDbFlags & DBFLAG_Vacuum)==0
311 ){
d993b15a 312 rc = SQLITE_LOCKED;
313 goto initone_error_out;
314 }else{
315 sqlite3SetTextEncoding(db, encoding);
316 }
fa256a33 317 }else{
14db2665 318 /* If opening an attached database, the encoding much match ENC(db) */
0ea2d42a 319 if( (meta[BTREE_TEXT_ENCODING-1] & 3)!=ENC(db) ){
f089aa45 320 sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
321 " text encoding as main database");
cd3e8f7c 322 rc = SQLITE_ERROR;
701bb3b4 323 goto initone_error_out;
fa256a33 324 }
325 }
326 }
14db2665 327 pDb->pSchema->enc = ENC(db);
fa256a33 328
8cf6c554 329 if( pDb->pSchema->cache_size==0 ){
e73c9149 330#ifndef SQLITE_OMIT_DEPRECATED
d50ffc41 331 size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
8cf6c554 332 if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
8cf6c554 333 pDb->pSchema->cache_size = size;
e73c9149 334#else
335 pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
336#endif
8cf6c554 337 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
338 }
fa256a33 339
340 /*
341 ** file_format==1 Version 3.0.0.
fdd6e85a 342 ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
343 ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
d946db00 344 ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
fa256a33 345 */
0d19f7ac 346 pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
da184236 347 if( pDb->pSchema->file_format==0 ){
348 pDb->pSchema->file_format = 1;
fdd6e85a 349 }
da184236 350 if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
f089aa45 351 sqlite3SetString(pzErrMsg, db, "unsupported file format");
cd3e8f7c 352 rc = SQLITE_ERROR;
701bb3b4 353 goto initone_error_out;
fa256a33 354 }
355
4aa2bfe6 356 /* Ticket #2804: When we open a database in the newer file format,
357 ** clear the legacy_file_format pragma flag so that a VACUUM will
358 ** not downgrade the database and thus invalidate any descending
359 ** indices that the user might have created.
360 */
0d19f7ac 361 if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
d5b44d60 362 db->flags &= ~(u64)SQLITE_LegacyFileFmt;
4aa2bfe6 363 }
fa256a33 364
365 /* Read the schema information out of the schema tables
366 */
367 assert( db->init.busy );
3b3ddbae 368 initData.mxPage = sqlite3BtreeLastPage(pDb->pBt);
9da742f9 369 {
fa256a33 370 char *zSql;
1e536953 371 zSql = sqlite3MPrintf(db,
c5a93d4c 372 "SELECT*FROM\"%w\".%s ORDER BY rowid",
067b92ba 373 db->aDb[iDb].zDbSName, zSchemaTabName);
a6d0ffc3 374#ifndef SQLITE_OMIT_AUTHORIZATION
375 {
32c6a48b 376 sqlite3_xauth xAuth;
a6d0ffc3 377 xAuth = db->xAuth;
378 db->xAuth = 0;
379#endif
380 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
381#ifndef SQLITE_OMIT_AUTHORIZATION
382 db->xAuth = xAuth;
383 }
384#endif
c456e57a 385 if( rc==SQLITE_OK ) rc = initData.rc;
633e6d57 386 sqlite3DbFree(db, zSql);
497e446d 387#ifndef SQLITE_OMIT_ANALYZE
388 if( rc==SQLITE_OK ){
389 sqlite3AnalysisLoad(db, iDb);
390 }
391#endif
fa256a33 392 }
7a7cefa0 393 assert( pDb == &(db->aDb[iDb]) );
17435752 394 if( db->mallocFailed ){
fad3039c 395 rc = SQLITE_NOMEM_BKPT;
81028a45 396 sqlite3ResetAllSchemasOfConnection(db);
7a7cefa0 397 pDb = &db->aDb[iDb];
569143c8 398 }else
5705b41f 399 if( rc==SQLITE_OK || ((db->flags&SQLITE_NoSchemaError) && rc!=SQLITE_NOMEM)){
569143c8 400 /* Hack: If the SQLITE_NoSchemaError flag is set, then consider
401 ** the schema loaded, even if errors (other than OOM) occurred. In
402 ** this situation the current sqlite3_prepare() operation will fail,
403 ** but the following one will attempt to compile the supplied statement
404 ** against whatever subset of the schema was loaded before the error
405 ** occurred.
406 **
407 ** The primary purpose of this is to allow access to the sqlite_schema
408 ** table even when its contents have been corrupted.
34c68fba 409 */
fa256a33 410 DbSetProperty(db, iDb, DB_SchemaLoaded);
34c68fba 411 rc = SQLITE_OK;
fa256a33 412 }
cd3e8f7c 413
414 /* Jump here for an error that occurs after successfully allocating
415 ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
416 ** before that point, jump to error_out.
417 */
701bb3b4 418initone_error_out:
602b466e 419 if( openedTransaction ){
420 sqlite3BtreeCommit(pDb->pBt);
421 }
b1ab8ea7 422 sqlite3BtreeLeave(pDb->pBt);
a1644fd8 423
424error_out:
36494b8b 425 if( rc ){
426 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
427 sqlite3OomFault(db);
428 }
429 sqlite3ResetOneSchema(db, iDb);
a1644fd8 430 }
36494b8b 431 db->init.busy = 0;
fa256a33 432 return rc;
433}
434
435/*
436** Initialize all database files - the main database file, the file
437** used to store temporary tables, and any additional database files
438** created using ATTACH statements. Return a success code. If an
439** error occurs, write an error message into *pzErrMsg.
440**
e7259296 441** After a database is initialized, the DB_SchemaLoaded bit is set
0ea2d42a 442** bit is set in the flags field of the Db structure.
fa256a33 443*/
444int sqlite3Init(sqlite3 *db, char **pzErrMsg){
445 int i, rc;
8257aa8d 446 int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
fa256a33 447
b1ab8ea7 448 assert( sqlite3_mutex_held(db->mutex) );
9bd3cc46 449 assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
09e60541 450 assert( db->init.busy==0 );
9bd3cc46 451 ENC(db) = SCHEMA_ENC(db);
36494b8b 452 assert( db->nDb>0 );
453 /* Do the main schema first */
454 if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
1595abcd 455 rc = sqlite3InitOne(db, 0, pzErrMsg, 0);
36494b8b 456 if( rc ) return rc;
fa256a33 457 }
36494b8b 458 /* All other schemas after the main schema. The "temp" schema must be last */
459 for(i=db->nDb-1; i>0; i--){
32158724 460 assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );
36494b8b 461 if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
1595abcd 462 rc = sqlite3InitOne(db, i, pzErrMsg, 0);
36494b8b 463 if( rc ) return rc;
fa256a33 464 }
465 }
36494b8b 466 if( commit_internal ){
fa256a33 467 sqlite3CommitInternalChanges(db);
468 }
36494b8b 469 return SQLITE_OK;
fa256a33 470}
471
472/*
48864df9 473** This routine is a no-op if the database schema is already initialized.
fa256a33 474** Otherwise, the schema is loaded. An error code is returned.
475*/
476int sqlite3ReadSchema(Parse *pParse){
477 int rc = SQLITE_OK;
478 sqlite3 *db = pParse->db;
b1ab8ea7 479 assert( sqlite3_mutex_held(db->mutex) );
fa256a33 480 if( !db->init.busy ){
b82e7eda 481 rc = sqlite3Init(db, &pParse->zErrMsg);
b2c8559f 482 if( rc!=SQLITE_OK ){
483 pParse->rc = rc;
484 pParse->nErr++;
485 }else if( db->noSharedCache ){
486 db->mDbFlags |= DBFLAG_SchemaKnownOk;
487 }
fa256a33 488 }
489 return rc;
490}
491
492
493/*
494** Check schema cookies in all databases. If any cookie is out
1adecdf8 495** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
496** make no changes to pParse->rc.
fa256a33 497*/
602b466e 498static void schemaIsValid(Parse *pParse){
499 sqlite3 *db = pParse->db;
fa256a33 500 int iDb;
501 int rc;
fa256a33 502 int cookie;
fa256a33 503
602b466e 504 assert( pParse->checkSchema );
505 assert( sqlite3_mutex_held(db->mutex) );
506 for(iDb=0; iDb<db->nDb; iDb++){
507 int openedTransaction = 0; /* True if a transaction is opened */
508 Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
509 if( pBt==0 ) continue;
510
511 /* If there is not already a read-only (or read-write) transaction opened
512 ** on the b-tree database, open one now. If a transaction is opened, it
513 ** will be closed immediately after reading the meta-value. */
99744fa4 514 if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_NONE ){
bb2d9b1b 515 rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
1adecdf8 516 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
4a642b60 517 sqlite3OomFault(db);
2389048f 518 pParse->rc = SQLITE_NOMEM;
602b466e 519 }
520 if( rc!=SQLITE_OK ) return;
521 openedTransaction = 1;
522 }
523
524 /* Read the schema cookie from the database. If it does not match the
d77f56ef 525 ** value stored as part of the in-memory schema representation,
602b466e 526 ** set Parse.rc to SQLITE_SCHEMA. */
527 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
2120608e 528 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
602b466e 529 if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
873a8405 530 if( DbHasProperty(db, iDb, DB_SchemaLoaded) ) pParse->rc = SQLITE_SCHEMA;
81028a45 531 sqlite3ResetOneSchema(db, iDb);
602b466e 532 }
533
534 /* Close the transaction, if one was opened. */
535 if( openedTransaction ){
536 sqlite3BtreeCommit(pBt);
537 }
538 }
fa256a33 539}
540
f248e211 541/*
542** Convert a schema pointer into the iDb index that indicates
543** which database file in db->aDb[] the schema refers to.
544**
545** If the same database is attached more than once, the first
546** attached database is returned.
547*/
e501b89a 548int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
bdd4f7d9 549 int i = -32768;
198bf391 550
bdd4f7d9 551 /* If pSchema is NULL, then return -32768. This happens when code in
198bf391 552 ** expr.c is trying to resolve a reference to a transient table (i.e. one
553 ** created by a sub-select). In this case the return value of this
554 ** function should never be used.
555 **
bdd4f7d9 556 ** We return -32768 instead of the more usual -1 simply because using
557 ** -32768 as the incorrect index into db->aDb[] is much
198bf391 558 ** more likely to cause a segfault than -1 (of course there are assert()
bdd4f7d9 559 ** statements too, but it never hurts to play the odds) and
560 ** -32768 will still fit into a 16-bit signed integer.
198bf391 561 */
b1ab8ea7 562 assert( sqlite3_mutex_held(db->mutex) );
198bf391 563 if( pSchema ){
9d9c41e2 564 for(i=0; 1; i++){
565 assert( i<db->nDb );
198bf391 566 if( db->aDb[i].pSchema==pSchema ){
567 break;
568 }
569 }
1c767f0d 570 assert( i>=0 && i<db->nDb );
198bf391 571 }
572 return i;
573}
574
f30a969b 575/*
576** Free all memory allocations in the pParse object
577*/
c692df27 578void sqlite3ParseObjectReset(Parse *pParse){
6903bf6d 579 sqlite3 *db = pParse->db;
1da88b5c 580 assert( db!=0 );
581 assert( db->pParse==pParse );
16118265 582 assert( pParse->nested==0 );
583#ifndef SQLITE_OMIT_SHARED_CACHE
41ce47c4 584 if( pParse->aTableLock ) sqlite3DbNNFreeNN(db, pParse->aTableLock);
16118265 585#endif
cf3c078f 586 while( pParse->pCleanup ){
5e5683ae 587 ParseCleanup *pCleanup = pParse->pCleanup;
588 pParse->pCleanup = pCleanup->pNext;
589 pCleanup->xCleanup(db, pCleanup->pPtr);
41ce47c4 590 sqlite3DbNNFreeNN(db, pCleanup);
cf3c078f 591 }
41ce47c4 592 if( pParse->aLabel ) sqlite3DbNNFreeNN(db, pParse->aLabel);
cf3c078f 593 if( pParse->pConstExpr ){
594 sqlite3ExprListDelete(db, pParse->pConstExpr);
595 }
1da88b5c 596 assert( db->lookaside.bDisable >= pParse->disableLookaside );
597 db->lookaside.bDisable -= pParse->disableLookaside;
598 db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue;
599 assert( pParse->db->pParse==pParse );
600 db->pParse = pParse->pOuterParse;
f30a969b 601}
602
cf3c078f 603/*
604** Add a new cleanup operation to a Parser. The cleanup should happen when
21d4f5b5 605** the parser object is destroyed. But, beware: the cleanup might happen
606** immediately.
cf3c078f 607**
608** Use this mechanism for uncommon cleanups. There is a higher setup
bc91738e 609** cost for this mechanism (an extra malloc), so it should not be used
21d4f5b5 610** for common cleanups that happen on most calls. But for less
cf3c078f 611** common cleanups, we save a single NULL-pointer comparison in
c692df27 612** sqlite3ParseObjectReset(), which reduces the total CPU cycle count.
cf3c078f 613**
614** If a memory allocation error occurs, then the cleanup happens immediately.
6d0053cf 615** When either SQLITE_DEBUG or SQLITE_COVERAGE_TEST are defined, the
21d4f5b5 616** pParse->earlyCleanup flag is set in that case. Calling code show verify
617** that test cases exist for which this happens, to guard against possible
618** use-after-free errors following an OOM. The preferred way to do this is
619** to immediately follow the call to this routine with:
620**
621** testcase( pParse->earlyCleanup );
6d0053cf 622**
623** This routine returns a copy of its pPtr input (the third parameter)
624** except if an early cleanup occurs, in which case it returns NULL. So
625** another way to check for early cleanup is to check the return value.
626** Or, stop using the pPtr parameter with this call and use only its
627** return value thereafter. Something like this:
628**
629** pObj = sqlite3ParserAddCleanup(pParse, destructor, pObj);
cf3c078f 630*/
a79e2a2d 631void *sqlite3ParserAddCleanup(
21d4f5b5 632 Parse *pParse, /* Destroy when this Parser finishes */
633 void (*xCleanup)(sqlite3*,void*), /* The cleanup routine */
634 void *pPtr /* Pointer to object to be cleaned up */
cf3c078f 635){
7e60106d 636 ParseCleanup *pCleanup;
637 if( sqlite3FaultSim(300) ){
638 pCleanup = 0;
639 }else{
640 pCleanup = sqlite3DbMallocRaw(pParse->db, sizeof(*pCleanup));
641 }
cf3c078f 642 if( pCleanup ){
643 pCleanup->pNext = pParse->pCleanup;
644 pParse->pCleanup = pCleanup;
645 pCleanup->pPtr = pPtr;
646 pCleanup->xCleanup = xCleanup;
647 }else{
648 xCleanup(pParse->db, pPtr);
a79e2a2d 649 pPtr = 0;
21d4f5b5 650#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
651 pParse->earlyCleanup = 1;
652#endif
cf3c078f 653 }
a79e2a2d 654 return pPtr;
cf3c078f 655}
656
c692df27 657/*
658** Turn bulk memory into a valid Parse object and link that Parse object
659** into database connection db.
660**
661** Call sqlite3ParseObjectReset() to undo this operation.
662**
663** Caution: Do not confuse this routine with sqlite3ParseObjectInit() which
664** is generated by Lemon.
665*/
666void sqlite3ParseObjectInit(Parse *pParse, sqlite3 *db){
667 memset(PARSE_HDR(pParse), 0, PARSE_HDR_SZ);
668 memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
669 assert( db->pParse!=pParse );
670 pParse->pOuterParse = db->pParse;
671 db->pParse = pParse;
672 pParse->db = db;
75863ec1 673 if( db->mallocFailed ) sqlite3ErrorMsg(pParse, "out of memory");
c692df27 674}
675
87b7ac04 676/*
677** Maximum number of times that we will try again to prepare a statement
678** that returns SQLITE_ERROR_RETRY.
679*/
680#ifndef SQLITE_MAX_PREPARE_RETRY
681# define SQLITE_MAX_PREPARE_RETRY 25
682#endif
683
fa256a33 684/*
685** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
686*/
3a00f907 687static int sqlite3Prepare(
fa256a33 688 sqlite3 *db, /* Database handle. */
689 const char *zSql, /* UTF-8 encoded SQL statement. */
690 int nBytes, /* Length of zSql in bytes. */
2c2f392d 691 u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
937d0dea 692 Vdbe *pReprepare, /* VM being reprepared */
fa256a33 693 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
b900aaf3 694 const char **pzTail /* OUT: End of parsed string */
fa256a33 695){
e7b34707 696 int rc = SQLITE_OK; /* Result code */
697 int i; /* Loop counter */
cb43a937 698 Parse sParse; /* Parsing context */
e7b34707 699
c692df27 700 /* sqlite3ParseObjectInit(&sParse, db); // inlined for performance */
701 memset(PARSE_HDR(&sParse), 0, PARSE_HDR_SZ);
cb43a937 702 memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
c692df27 703 sParse.pOuterParse = db->pParse;
704 db->pParse = &sParse;
705 sParse.db = db;
e393f6ef 706 if( pReprepare ){
707 sParse.pReprepare = pReprepare;
708 sParse.explain = sqlite3_stmt_isexplain((sqlite3_stmt*)pReprepare);
709 }else{
710 assert( sParse.pReprepare==0 );
711 }
860e077a 712 assert( ppStmt && *ppStmt==0 );
d9eb39e6 713 if( db->mallocFailed ){
714 sqlite3ErrorMsg(&sParse, "out of memory");
715 db->errCode = rc = SQLITE_NOMEM;
716 goto end_prepare;
717 }
b21c8cd4 718 assert( sqlite3_mutex_held(db->mutex) );
fa256a33 719
2c2f392d 720 /* For a long-term use prepared statement avoid the use of
721 ** lookaside memory.
722 */
723 if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
724 sParse.disableLookaside++;
31f69626 725 DisableLookaside;
2c2f392d 726 }
7424aeff 727 sParse.prepFlags = prepFlags & 0xff;
2c2f392d 728
c74d0b1d 729 /* Check to verify that it is possible to get a read lock on all
730 ** database schemas. The inability to get a read lock indicates that
731 ** some other database connection is holding a write-lock, which in
732 ** turn means that the other connection has made uncommitted changes
733 ** to the schema.
734 **
735 ** Were we to proceed and prepare the statement against the uncommitted
736 ** schema changes and if those schema changes are subsequently rolled
737 ** back and different changes are made in their place, then when this
738 ** prepared statement goes to run the schema cookie would fail to detect
739 ** the schema change. Disaster would follow.
740 **
741 ** This thread is currently holding mutexes on all Btrees (because
742 ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
743 ** is not possible for another thread to start a new schema change
744 ** while this routine is running. Hence, we do not need to hold
745 ** locks on the schema, we just need to make sure nobody else is
746 ** holding them.
747 **
748 ** Note that setting READ_UNCOMMITTED overrides most lock detection,
749 ** but it does *not* override schema lock detection, so this all still
750 ** works even if READ_UNCOMMITTED is set.
c87d34d0 751 */
705e7334 752 if( !db->noSharedCache ){
753 for(i=0; i<db->nDb; i++) {
754 Btree *pBt = db->aDb[i].pBt;
755 if( pBt ){
756 assert( sqlite3BtreeHoldsMutex(pBt) );
757 rc = sqlite3BtreeSchemaLocked(pBt);
758 if( rc ){
759 const char *zDb = db->aDb[i].zDbSName;
760 sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
761 testcase( db->flags & SQLITE_ReadUncommit );
762 goto end_prepare;
763 }
b1ab8ea7 764 }
c87d34d0 765 }
766 }
e7b34707 767
7d34b8d6 768#ifndef SQLITE_OMIT_VIRTUALTABLE
769 if( db->pDisconnect ) sqlite3VtabUnlockList(db);
770#endif
e7b34707 771
d2d88bbd 772 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
e5c941b8 773 char *zSqlCopy;
bb4957f8 774 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
58fbb314 775 testcase( nBytes==mxLen );
776 testcase( nBytes==mxLen+1 );
bb4957f8 777 if( nBytes>mxLen ){
13f40da3 778 sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
e7b34707 779 rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
780 goto end_prepare;
e5c941b8 781 }
17435752 782 zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
276fdbfd 783 if( zSqlCopy ){
54bc6381 784 sqlite3RunParser(&sParse, zSqlCopy);
cb43a937 785 sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
98a4d5a7 786 sqlite3DbFree(db, zSqlCopy);
3a2c8c8b 787 }else{
cb43a937 788 sParse.zTail = &zSql[nBytes];
276fdbfd 789 }
9051a420 790 }else{
54bc6381 791 sqlite3RunParser(&sParse, zSql);
9051a420 792 }
cb43a937 793 assert( 0==sParse.nQueryLoop );
fa256a33 794
b900aaf3 795 if( pzTail ){
cb43a937 796 *pzTail = sParse.zTail;
b900aaf3 797 }
fa256a33 798
6ab3a2ec 799 if( db->init.busy==0 ){
2c2f392d 800 sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
7e29e956 801 }
f3ce2483 802 if( db->mallocFailed ){
803 sParse.rc = SQLITE_NOMEM_BKPT;
ad3930be 804 sParse.checkSchema = 0;
f3ce2483 805 }
88efc796 806 if( sParse.rc!=SQLITE_OK && sParse.rc!=SQLITE_DONE ){
24a82ead 807 if( sParse.checkSchema && db->init.busy==0 ){
88efc796 808 schemaIsValid(&sParse);
809 }
810 if( sParse.pVdbe ){
811 sqlite3VdbeFinalize(sParse.pVdbe);
812 }
813 assert( 0==(*ppStmt) );
814 rc = sParse.rc;
54bc6381 815 if( sParse.zErrMsg ){
816 sqlite3ErrorWithMsg(db, rc, "%s", sParse.zErrMsg);
817 sqlite3DbFree(db, sParse.zErrMsg);
88efc796 818 }else{
819 sqlite3Error(db, rc);
820 }
7e29e956 821 }else{
54bc6381 822 assert( sParse.zErrMsg==0 );
cb43a937 823 *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
88efc796 824 rc = SQLITE_OK;
825 sqlite3ErrorClear(db);
fa256a33 826 }
827
261919cc 828
65a7cd16 829 /* Delete any TriggerPrg structures allocated while parsing this statement. */
cb43a937 830 while( sParse.pTriggerPrg ){
831 TriggerPrg *pT = sParse.pTriggerPrg;
832 sParse.pTriggerPrg = pT->pNext;
165921a7 833 sqlite3DbFree(db, pT);
834 }
835
e7b34707 836end_prepare:
837
c692df27 838 sqlite3ParseObjectReset(&sParse);
fa256a33 839 return rc;
840}
b21c8cd4 841static int sqlite3LockAndPrepare(
842 sqlite3 *db, /* Database handle. */
843 const char *zSql, /* UTF-8 encoded SQL statement. */
844 int nBytes, /* Length of zSql in bytes. */
2c2f392d 845 u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
937d0dea 846 Vdbe *pOld, /* VM being reprepared */
b21c8cd4 847 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
848 const char **pzTail /* OUT: End of parsed string */
849){
850 int rc;
7e8515d8 851 int cnt = 0;
9ca95730 852
853#ifdef SQLITE_ENABLE_API_ARMOR
854 if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
855#endif
860e077a 856 *ppStmt = 0;
9ca95730 857 if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
413c3d36 858 return SQLITE_MISUSE_BKPT;
27641703 859 }
b21c8cd4 860 sqlite3_mutex_enter(db->mutex);
b1ab8ea7 861 sqlite3BtreeEnterAll(db);
7e8515d8 862 do{
863 /* Make multiple attempts to compile the SQL, until it either succeeds
864 ** or encounters a permanent error. A schema problem after one schema
865 ** reset is considered a permanent error. */
2c2f392d 866 rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
7e8515d8 867 assert( rc==SQLITE_OK || *ppStmt==0 );
15561b91 868 if( rc==SQLITE_OK || db->mallocFailed ) break;
87b7ac04 869 }while( (rc==SQLITE_ERROR_RETRY && (cnt++)<SQLITE_MAX_PREPARE_RETRY)
7e8515d8 870 || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
b1ab8ea7 871 sqlite3BtreeLeaveAll(db);
7e8515d8 872 rc = sqlite3ApiExit(db, rc);
873 assert( (rc&db->errMask)==rc );
2b06b076 874 db->busyHandler.nBusy = 0;
b21c8cd4 875 sqlite3_mutex_leave(db->mutex);
003d419b 876 assert( rc==SQLITE_OK || (*ppStmt)==0 );
b21c8cd4 877 return rc;
878}
fa256a33 879
8bee11a4 880
b900aaf3 881/*
882** Rerun the compilation of a statement after a schema change.
65a2ea11 883**
884** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
885** if the statement cannot be recompiled because another connection has
1e32bed3 886** locked the sqlite3_schema table, return SQLITE_LOCKED. If any other error
65a2ea11 887** occurs, return SQLITE_SCHEMA.
b900aaf3 888*/
889int sqlite3Reprepare(Vdbe *p){
890 int rc;
4f0c5878 891 sqlite3_stmt *pNew;
b900aaf3 892 const char *zSql;
893 sqlite3 *db;
2c2f392d 894 u8 prepFlags;
b21c8cd4 895
b1ab8ea7 896 assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
d0e2a854 897 zSql = sqlite3_sql((sqlite3_stmt *)p);
c4dd3fd2 898 assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
b900aaf3 899 db = sqlite3VdbeDb(p);
b21c8cd4 900 assert( sqlite3_mutex_held(db->mutex) );
2c2f392d 901 prepFlags = sqlite3VdbePrepareFlags(p);
902 rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
b900aaf3 903 if( rc ){
8e556520 904 if( rc==SQLITE_NOMEM ){
4a642b60 905 sqlite3OomFault(db);
8e556520 906 }
b900aaf3 907 assert( pNew==0 );
a6129fa7 908 return rc;
b900aaf3 909 }else{
910 assert( pNew!=0 );
911 }
4f0c5878 912 sqlite3VdbeSwap((Vdbe*)pNew, p);
145834a4 913 sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
4f0c5878 914 sqlite3VdbeResetStepResult((Vdbe*)pNew);
915 sqlite3VdbeFinalize((Vdbe*)pNew);
65a2ea11 916 return SQLITE_OK;
b900aaf3 917}
918
919
920/*
921** Two versions of the official API. Legacy and new use. In the legacy
922** version, the original SQL text is not saved in the prepared statement
923** and so if a schema change occurs, SQLITE_SCHEMA is returned by
924** sqlite3_step(). In the new version, the original SQL text is retained
925** and the statement is automatically recompiled if an schema change
926** occurs.
927*/
928int sqlite3_prepare(
929 sqlite3 *db, /* Database handle. */
930 const char *zSql, /* UTF-8 encoded SQL statement. */
931 int nBytes, /* Length of zSql in bytes. */
932 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
933 const char **pzTail /* OUT: End of parsed string */
934){
17eaae74 935 int rc;
937d0dea 936 rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
58edb657 937 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
17eaae74 938 return rc;
b900aaf3 939}
940int sqlite3_prepare_v2(
941 sqlite3 *db, /* Database handle. */
942 const char *zSql, /* UTF-8 encoded SQL statement. */
943 int nBytes, /* Length of zSql in bytes. */
944 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
945 const char **pzTail /* OUT: End of parsed string */
946){
17eaae74 947 int rc;
3cef3649 948 /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
949 ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
950 ** parameter.
951 **
952 ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
2c2f392d 953 rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
954 ppStmt,pzTail);
3cef3649 955 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
2c2f392d 956 return rc;
957}
958int sqlite3_prepare_v3(
959 sqlite3 *db, /* Database handle. */
960 const char *zSql, /* UTF-8 encoded SQL statement. */
961 int nBytes, /* Length of zSql in bytes. */
962 unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
963 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
964 const char **pzTail /* OUT: End of parsed string */
965){
966 int rc;
3cef3649 967 /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
968 ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
969 ** which is a bit array consisting of zero or more of the
970 ** SQLITE_PREPARE_* flags.
971 **
972 ** Proof by comparison to the implementation of sqlite3_prepare_v2()
973 ** directly above. */
2c2f392d 974 rc = sqlite3LockAndPrepare(db,zSql,nBytes,
975 SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
976 0,ppStmt,pzTail);
3cef3649 977 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
17eaae74 978 return rc;
b900aaf3 979}
980
981
fa256a33 982#ifndef SQLITE_OMIT_UTF16
983/*
984** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
985*/
b900aaf3 986static int sqlite3Prepare16(
fa256a33 987 sqlite3 *db, /* Database handle. */
0ecdeb24 988 const void *zSql, /* UTF-16 encoded SQL statement. */
fa256a33 989 int nBytes, /* Length of zSql in bytes. */
2c2f392d 990 u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
fa256a33 991 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
992 const void **pzTail /* OUT: End of parsed string */
993){
994 /* This function currently works by first transforming the UTF-16
995 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
996 ** tricky bit is figuring out the pointer to return in *pzTail.
997 */
54f0198e 998 char *zSql8;
c87d34d0 999 const char *zTail8 = 0;
54f0198e 1000 int rc = SQLITE_OK;
fa256a33 1001
9ca95730 1002#ifdef SQLITE_ENABLE_API_ARMOR
1003 if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
1004#endif
769e97e0 1005 *ppStmt = 0;
9ca95730 1006 if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
413c3d36 1007 return SQLITE_MISUSE_BKPT;
fa256a33 1008 }
7232ad07 1009 if( nBytes>=0 ){
1010 int sz;
1011 const char *z = (const char*)zSql;
1012 for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
1013 nBytes = sz;
1014 }
b21c8cd4 1015 sqlite3_mutex_enter(db->mutex);
b7dca7d7 1016 zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
54f0198e 1017 if( zSql8 ){
2c2f392d 1018 rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
fa256a33 1019 }
fa256a33 1020
1021 if( zTail8 && pzTail ){
1022 /* If sqlite3_prepare returns a tail pointer, we calculate the
1023 ** equivalent pointer into the UTF-16 string by counting the unicode
1024 ** characters between zSql8 and zTail8, and then returning a pointer
1025 ** the same number of characters into the UTF-16 string.
1026 */
ea678832 1027 int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
ee85813c 1028 *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
fa256a33 1029 }
633e6d57 1030 sqlite3DbFree(db, zSql8);
b21c8cd4 1031 rc = sqlite3ApiExit(db, rc);
1032 sqlite3_mutex_leave(db->mutex);
1033 return rc;
fa256a33 1034}
b900aaf3 1035
1036/*
1037** Two versions of the official API. Legacy and new use. In the legacy
1038** version, the original SQL text is not saved in the prepared statement
1039** and so if a schema change occurs, SQLITE_SCHEMA is returned by
1040** sqlite3_step(). In the new version, the original SQL text is retained
1041** and the statement is automatically recompiled if an schema change
1042** occurs.
1043*/
1044int sqlite3_prepare16(
1045 sqlite3 *db, /* Database handle. */
0ecdeb24 1046 const void *zSql, /* UTF-16 encoded SQL statement. */
b900aaf3 1047 int nBytes, /* Length of zSql in bytes. */
1048 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
1049 const void **pzTail /* OUT: End of parsed string */
1050){
17eaae74 1051 int rc;
1052 rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
58edb657 1053 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
17eaae74 1054 return rc;
b900aaf3 1055}
1056int sqlite3_prepare16_v2(
1057 sqlite3 *db, /* Database handle. */
0ecdeb24 1058 const void *zSql, /* UTF-16 encoded SQL statement. */
b900aaf3 1059 int nBytes, /* Length of zSql in bytes. */
1060 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
1061 const void **pzTail /* OUT: End of parsed string */
1062){
17eaae74 1063 int rc;
2c2f392d 1064 rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
1065 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
1066 return rc;
1067}
1068int sqlite3_prepare16_v3(
1069 sqlite3 *db, /* Database handle. */
1070 const void *zSql, /* UTF-16 encoded SQL statement. */
1071 int nBytes, /* Length of zSql in bytes. */
1072 unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
1073 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
1074 const void **pzTail /* OUT: End of parsed string */
1075){
1076 int rc;
1077 rc = sqlite3Prepare16(db,zSql,nBytes,
1078 SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
1079 ppStmt,pzTail);
58edb657 1080 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
17eaae74 1081 return rc;
b900aaf3 1082}
1083
fa256a33 1084#endif /* SQLITE_OMIT_UTF16 */