4
** The author disclaims copyright to this source code. In place of
5
** a legal notice, here is a blessing:
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.
11
*************************************************************************
12
** This file contains the implementation of the sqlite3_prepare()
13
** interface, and routines that contribute to loading the database schema
16
** $Id: prepare.c,v 1.40 2006/09/23 20:36:02 drh Exp $
18
#include "sqliteInt.h"
23
** Fill the InitData structure with an error message that indicates
24
** that the database is corrupt.
26
static void corruptSchema(InitData *pData, const char *zExtra){
27
if( !sqlite3MallocFailed() ){
28
sqlite3SetString(pData->pzErrMsg, "malformed database schema",
29
zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0);
31
pData->rc = SQLITE_CORRUPT;
35
** This is the callback routine for the code that initializes the
36
** database. See sqlite3Init() below for additional information.
37
** This routine is also called from the OP_ParseSchema opcode of the VDBE.
39
** Each callback contains the following information:
41
** argv[0] = name of thing being created
42
** argv[1] = root page number for table or index. 0 for trigger or view.
43
** argv[2] = SQL text for the CREATE statement.
46
int sqlite3InitCallback(void *pInit, int argc, char **argv, char **azColName){
47
InitData *pData = (InitData*)pInit;
48
sqlite3 *db = pData->db;
51
pData->rc = SQLITE_OK;
52
DbClearProperty(db, iDb, DB_Empty);
53
if( sqlite3MallocFailed() ){
54
corruptSchema(pData, 0);
59
if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
61
corruptSchema(pData, 0);
64
assert( iDb>=0 && iDb<db->nDb );
65
if( argv[2] && argv[2][0] ){
66
/* Call the parser to process a CREATE TABLE, INDEX or VIEW.
67
** But because db->init.busy is set to 1, no VDBE code is generated
68
** or executed. All the parser does is build the internal data
69
** structures that describe the table, index, or view.
73
assert( db->init.busy );
75
db->init.newTnum = atoi(argv[1]);
76
rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
78
assert( rc!=SQLITE_OK || zErr==0 );
81
if( rc==SQLITE_NOMEM ){
82
sqlite3FailedMalloc();
83
}else if( rc!=SQLITE_INTERRUPT ){
84
corruptSchema(pData, zErr);
90
/* If the SQL column is blank it means this is an index that
91
** was created to be the PRIMARY KEY or to fulfill a UNIQUE
92
** constraint for a CREATE TABLE. The index should have already
93
** been created when we processed the CREATE TABLE. All we have
94
** to do here is record the root page number for that index.
97
pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
98
if( pIndex==0 || pIndex->tnum!=0 ){
99
/* This can occur if there exists an index on a TEMP table which
100
** has the same name as another index on a permanent index. Since
101
** the permanent table is hidden by the TEMP table, we can also
102
** safely ignore the index on the permanent table.
106
pIndex->tnum = atoi(argv[1]);
113
** Attempt to read the database schema and initialize internal
114
** data structures for a single database file. The index of the
115
** database file is given by iDb. iDb==0 is used for the main
116
** database. iDb==1 should never be used. iDb>=2 is used for
117
** auxiliary databases. Return one of the SQLITE_ error codes to
118
** indicate success or failure.
120
static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
126
char const *azArg[4];
129
char const *zMasterSchema;
130
char const *zMasterName = SCHEMA_TABLE(iDb);
133
** The master database table has a structure like this
135
static const char master_schema[] =
136
"CREATE TABLE sqlite_master(\n"
140
" rootpage integer,\n"
144
#ifndef SQLITE_OMIT_TEMPDB
145
static const char temp_master_schema[] =
146
"CREATE TEMP TABLE sqlite_temp_master(\n"
150
" rootpage integer,\n"
155
#define temp_master_schema 0
158
assert( iDb>=0 && iDb<db->nDb );
159
assert( db->aDb[iDb].pSchema );
161
/* zMasterSchema and zInitScript are set to point at the master schema
162
** and initialisation script appropriate for the database being
163
** initialised. zMasterName is the name of the master table.
165
if( !OMIT_TEMPDB && iDb==1 ){
166
zMasterSchema = temp_master_schema;
168
zMasterSchema = master_schema;
170
zMasterName = SCHEMA_TABLE(iDb);
172
/* Construct the schema tables. */
173
sqlite3SafetyOff(db);
174
azArg[0] = zMasterName;
176
azArg[2] = zMasterSchema;
180
initData.pzErrMsg = pzErrMsg;
181
rc = sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
186
pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
192
/* Create a cursor to hold the database open
196
if( !OMIT_TEMPDB && iDb==1 ){
197
DbSetProperty(db, 1, DB_SchemaLoaded);
201
rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, 0, &curMain);
202
if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
203
sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
207
/* Get the database meta information.
209
** Meta values are as follows:
210
** meta[0] Schema cookie. Changes with each schema change.
211
** meta[1] File format of schema layer.
212
** meta[2] Size of the page cache.
213
** meta[3] Use freelist if 0. Autovacuum if greater than zero.
214
** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
215
** meta[5] The user cookie. Used by the application.
221
** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
222
** the possible values of meta[4].
226
for(i=0; rc==SQLITE_OK && i<sizeof(meta)/sizeof(meta[0]); i++){
227
rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
230
sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
231
sqlite3BtreeCloseCursor(curMain);
235
memset(meta, 0, sizeof(meta));
237
pDb->pSchema->schema_cookie = meta[0];
239
/* If opening a non-empty database, check the text encoding. For the
240
** main database, set sqlite3.enc to the encoding of the main database.
241
** For an attached db, it is an error if the encoding is not the same
244
if( meta[4] ){ /* text encoding */
246
/* If opening the main database, set ENC(db). */
247
ENC(db) = (u8)meta[4];
248
db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
250
/* If opening an attached database, the encoding much match ENC(db) */
251
if( meta[4]!=ENC(db) ){
252
sqlite3BtreeCloseCursor(curMain);
253
sqlite3SetString(pzErrMsg, "attached databases must use the same"
254
" text encoding as main database", (char*)0);
259
DbSetProperty(db, iDb, DB_Empty);
261
pDb->pSchema->enc = ENC(db);
264
if( size==0 ){ size = MAX_PAGES; }
265
pDb->pSchema->cache_size = size;
266
sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
269
** file_format==1 Version 3.0.0.
270
** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
271
** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
272
** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
274
pDb->pSchema->file_format = meta[1];
275
if( pDb->pSchema->file_format==0 ){
276
pDb->pSchema->file_format = 1;
278
if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
279
sqlite3BtreeCloseCursor(curMain);
280
sqlite3SetString(pzErrMsg, "unsupported file format", (char*)0);
285
/* Read the schema information out of the schema tables
287
assert( db->init.busy );
288
if( rc==SQLITE_EMPTY ){
289
/* For an empty database, there is nothing to read */
293
zSql = sqlite3MPrintf(
294
"SELECT name, rootpage, sql FROM '%q'.%s",
295
db->aDb[iDb].zName, zMasterName);
296
sqlite3SafetyOff(db);
297
rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
298
if( rc==SQLITE_ABORT ) rc = initData.rc;
301
#ifndef SQLITE_OMIT_ANALYZE
303
sqlite3AnalysisLoad(db, iDb);
306
sqlite3BtreeCloseCursor(curMain);
308
if( sqlite3MallocFailed() ){
309
/* sqlite3SetString(pzErrMsg, "out of memory", (char*)0); */
311
sqlite3ResetInternalSchema(db, 0);
314
DbSetProperty(db, iDb, DB_SchemaLoaded);
316
sqlite3ResetInternalSchema(db, iDb);
322
** Initialize all database files - the main database file, the file
323
** used to store temporary tables, and any additional database files
324
** created using ATTACH statements. Return a success code. If an
325
** error occurs, write an error message into *pzErrMsg.
327
** After a database is initialized, the DB_SchemaLoaded bit is set
328
** bit is set in the flags field of the Db structure. If the database
329
** file was of zero-length, then the DB_Empty flag is also set.
331
int sqlite3Init(sqlite3 *db, char **pzErrMsg){
333
int called_initone = 0;
335
if( db->init.busy ) return SQLITE_OK;
338
for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
339
if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
340
rc = sqlite3InitOne(db, i, pzErrMsg);
342
sqlite3ResetInternalSchema(db, i);
347
/* Once all the other databases have been initialised, load the schema
348
** for the TEMP database. This is loaded last, as the TEMP database
349
** schema may contain references to objects in other databases.
351
#ifndef SQLITE_OMIT_TEMPDB
352
if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
353
rc = sqlite3InitOne(db, 1, pzErrMsg);
355
sqlite3ResetInternalSchema(db, 1);
362
if( rc==SQLITE_OK && called_initone ){
363
sqlite3CommitInternalChanges(db);
370
** This routine is a no-op if the database schema is already initialised.
371
** Otherwise, the schema is loaded. An error code is returned.
373
int sqlite3ReadSchema(Parse *pParse){
375
sqlite3 *db = pParse->db;
376
if( !db->init.busy ){
377
rc = sqlite3Init(db, &pParse->zErrMsg);
388
** Check schema cookies in all databases. If any cookie is out
389
** of date, return 0. If all schema cookies are current, return 1.
391
static int schemaIsValid(sqlite3 *db){
398
for(iDb=0; allOk && iDb<db->nDb; iDb++){
400
pBt = db->aDb[iDb].pBt;
401
if( pBt==0 ) continue;
402
rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, 0, &curTemp);
404
rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
405
if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
408
sqlite3BtreeCloseCursor(curTemp);
415
** Convert a schema pointer into the iDb index that indicates
416
** which database file in db->aDb[] the schema refers to.
418
** If the same database is attached more than once, the first
419
** attached database is returned.
421
int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
424
/* If pSchema is NULL, then return -1000000. This happens when code in
425
** expr.c is trying to resolve a reference to a transient table (i.e. one
426
** created by a sub-select). In this case the return value of this
427
** function should never be used.
429
** We return -1000000 instead of the more usual -1 simply because using
430
** -1000000 as incorrectly using -1000000 index into db->aDb[] is much
431
** more likely to cause a segfault than -1 (of course there are assert()
432
** statements too, but it never hurts to play the odds).
435
for(i=0; i<db->nDb; i++){
436
if( db->aDb[i].pSchema==pSchema ){
440
assert( i>=0 &&i>=0 && i<db->nDb );
446
** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
449
sqlite3 *db, /* Database handle. */
450
const char *zSql, /* UTF-8 encoded SQL statement. */
451
int nBytes, /* Length of zSql in bytes. */
452
sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
453
const char** pzTail /* OUT: End of parsed string */
460
/* Assert that malloc() has not failed */
461
assert( !sqlite3MallocFailed() );
465
if( sqlite3SafetyOn(db) ){
466
return SQLITE_MISUSE;
469
/* If any attached database schemas are locked, do not proceed with
470
** compilation. Instead return SQLITE_LOCKED immediately.
472
for(i=0; i<db->nDb; i++) {
473
Btree *pBt = db->aDb[i].pBt;
474
if( pBt && sqlite3BtreeSchemaLocked(pBt) ){
475
const char *zDb = db->aDb[i].zName;
476
sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb);
477
sqlite3SafetyOff(db);
478
return SQLITE_LOCKED;
482
memset(&sParse, 0, sizeof(sParse));
484
if( nBytes>=0 && zSql[nBytes]!=0 ){
485
char *zSqlCopy = sqlite3StrNDup(zSql, nBytes);
486
sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
487
sParse.zTail += zSql - zSqlCopy;
488
sqliteFree(zSqlCopy);
490
sqlite3RunParser(&sParse, zSql, &zErrMsg);
493
if( sqlite3MallocFailed() ){
494
sParse.rc = SQLITE_NOMEM;
496
if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
497
if( sParse.checkSchema && !schemaIsValid(db) ){
498
sParse.rc = SQLITE_SCHEMA;
500
if( sParse.rc==SQLITE_SCHEMA ){
501
sqlite3ResetInternalSchema(db, 0);
503
if( sqlite3MallocFailed() ){
504
sParse.rc = SQLITE_NOMEM;
506
if( pzTail ) *pzTail = sParse.zTail;
509
#ifndef SQLITE_OMIT_EXPLAIN
510
if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
511
if( sParse.explain==2 ){
512
sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
513
sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", P3_STATIC);
514
sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", P3_STATIC);
515
sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", P3_STATIC);
517
sqlite3VdbeSetNumCols(sParse.pVdbe, 5);
518
sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", P3_STATIC);
519
sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", P3_STATIC);
520
sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", P3_STATIC);
521
sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", P3_STATIC);
522
sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", P3_STATIC);
527
if( sqlite3SafetyOff(db) ){
531
*ppStmt = (sqlite3_stmt*)sParse.pVdbe;
532
}else if( sParse.pVdbe ){
533
sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
537
sqlite3Error(db, rc, "%s", zErrMsg);
540
sqlite3Error(db, rc, 0);
543
rc = sqlite3ApiExit(db, rc);
544
sqlite3ReleaseThreadData();
545
assert( (rc&db->errMask)==rc );
549
#ifndef SQLITE_OMIT_UTF16
551
** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
553
int sqlite3_prepare16(
554
sqlite3 *db, /* Database handle. */
555
const void *zSql, /* UTF-8 encoded SQL statement. */
556
int nBytes, /* Length of zSql in bytes. */
557
sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
558
const void **pzTail /* OUT: End of parsed string */
560
/* This function currently works by first transforming the UTF-16
561
** encoded string to UTF-8, then invoking sqlite3_prepare(). The
562
** tricky bit is figuring out the pointer to return in *pzTail.
565
const char *zTail8 = 0;
568
if( sqlite3SafetyCheck(db) ){
569
return SQLITE_MISUSE;
571
zSql8 = sqlite3utf16to8(zSql, nBytes);
573
rc = sqlite3_prepare(db, zSql8, -1, ppStmt, &zTail8);
576
if( zTail8 && pzTail ){
577
/* If sqlite3_prepare returns a tail pointer, we calculate the
578
** equivalent pointer into the UTF-16 string by counting the unicode
579
** characters between zSql8 and zTail8, and then returning a pointer
580
** the same number of characters into the UTF-16 string.
582
int chars_parsed = sqlite3utf8CharLen(zSql8, zTail8-zSql8);
583
*pzTail = (u8 *)zSql + sqlite3utf16ByteLen(zSql, chars_parsed);
586
return sqlite3ApiExit(db, rc);
588
#endif /* SQLITE_OMIT_UTF16 */