Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(246)

Side by Side Diff: third_party/sqlite/src/prepare.c

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

Powered by Google App Engine
This is Rietveld 408576698