blob: 1510b344e208c55e3a11c70d3347d6b3bc5115bf [file] [log] [blame]
danielk1977fa256a32005-05-25 04:11:56 +00001/*
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**
drh4d91a702006-01-04 15:54:36 +000016** $Id: prepare.c,v 1.12 2006/01/04 15:54:36 drh Exp $
danielk1977fa256a32005-05-25 04:11:56 +000017*/
18#include "sqliteInt.h"
19#include "os.h"
20#include <ctype.h>
21
22/*
23** Fill the InitData structure with an error message that indicates
24** that the database is corrupt.
25*/
26static void corruptSchema(InitData *pData, const char *zExtra){
danielk1977261919c2005-12-06 12:52:59 +000027 if( !sqlite3Tsd()->mallocFailed ){
danielk1977fa256a32005-05-25 04:11:56 +000028 sqlite3SetString(pData->pzErrMsg, "malformed database schema",
29 zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0);
30 }
31}
32
33/*
34** This is the callback routine for the code that initializes the
35** database. See sqlite3Init() below for additional information.
36** This routine is also called from the OP_ParseSchema opcode of the VDBE.
37**
38** Each callback contains the following information:
39**
40** argv[0] = name of thing being created
41** argv[1] = root page number for table or index. NULL for trigger or view.
42** argv[2] = SQL text for the CREATE statement.
43** argv[3] = "1" for temporary files, "0" for main database, "2" or more
44** for auxiliary database files.
45**
46*/
47int sqlite3InitCallback(void *pInit, int argc, char **argv, char **azColName){
48 InitData *pData = (InitData*)pInit;
49 sqlite3 *db = pData->db;
50 int iDb;
51
52 assert( argc==4 );
53 if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
54 if( argv[1]==0 || argv[3]==0 ){
55 corruptSchema(pData, 0);
56 return 1;
57 }
58 iDb = atoi(argv[3]);
59 assert( iDb>=0 && iDb<db->nDb );
60 if( argv[2] && argv[2][0] ){
61 /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
62 ** But because db->init.busy is set to 1, no VDBE code is generated
63 ** or executed. All the parser does is build the internal data
64 ** structures that describe the table, index, or view.
65 */
66 char *zErr;
67 int rc;
68 assert( db->init.busy );
69 db->init.iDb = iDb;
70 db->init.newTnum = atoi(argv[1]);
71 rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
72 db->init.iDb = 0;
73 if( SQLITE_OK!=rc ){
danielk1977261919c2005-12-06 12:52:59 +000074 if( rc==SQLITE_NOMEM ){
75 sqlite3Tsd()->mallocFailed = 1;
76 }else{
77 corruptSchema(pData, zErr);
78 }
danielk1977fa256a32005-05-25 04:11:56 +000079 sqlite3_free(zErr);
80 return rc;
81 }
82 }else{
83 /* If the SQL column is blank it means this is an index that
84 ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
85 ** constraint for a CREATE TABLE. The index should have already
86 ** been created when we processed the CREATE TABLE. All we have
87 ** to do here is record the root page number for that index.
88 */
89 Index *pIndex;
90 pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
91 if( pIndex==0 || pIndex->tnum!=0 ){
92 /* This can occur if there exists an index on a TEMP table which
93 ** has the same name as another index on a permanent index. Since
94 ** the permanent table is hidden by the TEMP table, we can also
95 ** safely ignore the index on the permanent table.
96 */
97 /* Do Nothing */;
98 }else{
99 pIndex->tnum = atoi(argv[1]);
100 }
101 }
102 return 0;
103}
104
105/*
106** Attempt to read the database schema and initialize internal
107** data structures for a single database file. The index of the
108** database file is given by iDb. iDb==0 is used for the main
109** database. iDb==1 should never be used. iDb>=2 is used for
110** auxiliary databases. Return one of the SQLITE_ error codes to
111** indicate success or failure.
112*/
113static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
114 int rc;
115 BtCursor *curMain;
116 int size;
117 Table *pTab;
drhfdd6e852005-12-16 01:06:16 +0000118 Db *pDb;
danielk1977fa256a32005-05-25 04:11:56 +0000119 char const *azArg[5];
120 char zDbNum[30];
121 int meta[10];
122 InitData initData;
123 char const *zMasterSchema;
124 char const *zMasterName = SCHEMA_TABLE(iDb);
125
126 /*
127 ** The master database table has a structure like this
128 */
129 static const char master_schema[] =
130 "CREATE TABLE sqlite_master(\n"
131 " type text,\n"
132 " name text,\n"
133 " tbl_name text,\n"
134 " rootpage integer,\n"
135 " sql text\n"
136 ")"
137 ;
138#ifndef SQLITE_OMIT_TEMPDB
139 static const char temp_master_schema[] =
140 "CREATE TEMP TABLE sqlite_temp_master(\n"
141 " type text,\n"
142 " name text,\n"
143 " tbl_name text,\n"
144 " rootpage integer,\n"
145 " sql text\n"
146 ")"
147 ;
148#else
149 #define temp_master_schema 0
150#endif
151
152 assert( iDb>=0 && iDb<db->nDb );
153
154 /* zMasterSchema and zInitScript are set to point at the master schema
155 ** and initialisation script appropriate for the database being
156 ** initialised. zMasterName is the name of the master table.
157 */
158 if( !OMIT_TEMPDB && iDb==1 ){
159 zMasterSchema = temp_master_schema;
160 }else{
161 zMasterSchema = master_schema;
162 }
163 zMasterName = SCHEMA_TABLE(iDb);
164
165 /* Construct the schema tables. */
166 sqlite3SafetyOff(db);
167 azArg[0] = zMasterName;
168 azArg[1] = "1";
169 azArg[2] = zMasterSchema;
170 sprintf(zDbNum, "%d", iDb);
171 azArg[3] = zDbNum;
172 azArg[4] = 0;
173 initData.db = db;
174 initData.pzErrMsg = pzErrMsg;
175 rc = sqlite3InitCallback(&initData, 4, (char **)azArg, 0);
176 if( rc!=SQLITE_OK ){
177 sqlite3SafetyOn(db);
178 return rc;
179 }
180 pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
181 if( pTab ){
182 pTab->readOnly = 1;
183 }
184 sqlite3SafetyOn(db);
185
186 /* Create a cursor to hold the database open
187 */
drhfdd6e852005-12-16 01:06:16 +0000188 pDb = &db->aDb[iDb];
189 if( pDb->pBt==0 ){
danielk1977fa256a32005-05-25 04:11:56 +0000190 if( !OMIT_TEMPDB && iDb==1 ) DbSetProperty(db, 1, DB_SchemaLoaded);
191 return SQLITE_OK;
192 }
drhfdd6e852005-12-16 01:06:16 +0000193 rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, 0, &curMain);
danielk1977fa256a32005-05-25 04:11:56 +0000194 if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
195 sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
196 return rc;
197 }
198
199 /* Get the database meta information.
200 **
201 ** Meta values are as follows:
202 ** meta[0] Schema cookie. Changes with each schema change.
203 ** meta[1] File format of schema layer.
204 ** meta[2] Size of the page cache.
205 ** meta[3] Use freelist if 0. Autovacuum if greater than zero.
206 ** meta[4] Db text encoding. 1:UTF-8 3:UTF-16 LE 4:UTF-16 BE
207 ** meta[5] The user cookie. Used by the application.
208 ** meta[6]
209 ** meta[7]
210 ** meta[8]
211 ** meta[9]
212 **
213 ** Note: The hash defined SQLITE_UTF* symbols in sqliteInt.h correspond to
214 ** the possible values of meta[4].
215 */
216 if( rc==SQLITE_OK ){
217 int i;
218 for(i=0; rc==SQLITE_OK && i<sizeof(meta)/sizeof(meta[0]); i++){
drhfdd6e852005-12-16 01:06:16 +0000219 rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
danielk1977fa256a32005-05-25 04:11:56 +0000220 }
221 if( rc ){
222 sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0);
223 sqlite3BtreeCloseCursor(curMain);
224 return rc;
225 }
226 }else{
227 memset(meta, 0, sizeof(meta));
228 }
drhfdd6e852005-12-16 01:06:16 +0000229 pDb->schema_cookie = meta[0];
danielk1977fa256a32005-05-25 04:11:56 +0000230
231 /* If opening a non-empty database, check the text encoding. For the
232 ** main database, set sqlite3.enc to the encoding of the main database.
233 ** For an attached db, it is an error if the encoding is not the same
234 ** as sqlite3.enc.
235 */
236 if( meta[4] ){ /* text encoding */
237 if( iDb==0 ){
238 /* If opening the main database, set db->enc. */
239 db->enc = (u8)meta[4];
240 db->pDfltColl = sqlite3FindCollSeq(db, db->enc, "BINARY", 6, 0);
241 }else{
242 /* If opening an attached database, the encoding much match db->enc */
243 if( meta[4]!=db->enc ){
244 sqlite3BtreeCloseCursor(curMain);
245 sqlite3SetString(pzErrMsg, "attached databases must use the same"
246 " text encoding as main database", (char*)0);
247 return SQLITE_ERROR;
248 }
249 }
250 }
251
252 size = meta[2];
253 if( size==0 ){ size = MAX_PAGES; }
drhfdd6e852005-12-16 01:06:16 +0000254 pDb->cache_size = size;
255 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->cache_size);
danielk1977fa256a32005-05-25 04:11:56 +0000256
257 /*
258 ** file_format==1 Version 3.0.0.
drhfdd6e852005-12-16 01:06:16 +0000259 ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
260 ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
drhd946db02005-12-29 19:23:06 +0000261 ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
danielk1977fa256a32005-05-25 04:11:56 +0000262 */
drhfdd6e852005-12-16 01:06:16 +0000263 pDb->file_format = meta[1];
264 if( pDb->file_format==0 ){
265 pDb->file_format = 1;
266 }
drhd946db02005-12-29 19:23:06 +0000267 if( pDb->file_format>SQLITE_MAX_FILE_FORMAT ){
danielk1977fa256a32005-05-25 04:11:56 +0000268 sqlite3BtreeCloseCursor(curMain);
269 sqlite3SetString(pzErrMsg, "unsupported file format", (char*)0);
270 return SQLITE_ERROR;
271 }
272
danielk1977fa256a32005-05-25 04:11:56 +0000273
274 /* Read the schema information out of the schema tables
275 */
276 assert( db->init.busy );
277 if( rc==SQLITE_EMPTY ){
278 /* For an empty database, there is nothing to read */
279 rc = SQLITE_OK;
280 }else{
281 char *zSql;
282 zSql = sqlite3MPrintf(
283 "SELECT name, rootpage, sql, '%s' FROM '%q'.%s",
284 zDbNum, db->aDb[iDb].zName, zMasterName);
285 sqlite3SafetyOff(db);
286 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
287 sqlite3SafetyOn(db);
288 sqliteFree(zSql);
drh497e4462005-07-23 03:18:40 +0000289#ifndef SQLITE_OMIT_ANALYZE
290 if( rc==SQLITE_OK ){
291 sqlite3AnalysisLoad(db, iDb);
292 }
293#endif
danielk1977fa256a32005-05-25 04:11:56 +0000294 sqlite3BtreeCloseCursor(curMain);
295 }
danielk1977261919c2005-12-06 12:52:59 +0000296 if( sqlite3Tsd()->mallocFailed ){
danielk1977fa256a32005-05-25 04:11:56 +0000297 sqlite3SetString(pzErrMsg, "out of memory", (char*)0);
298 rc = SQLITE_NOMEM;
299 sqlite3ResetInternalSchema(db, 0);
300 }
301 if( rc==SQLITE_OK ){
302 DbSetProperty(db, iDb, DB_SchemaLoaded);
303 }else{
304 sqlite3ResetInternalSchema(db, iDb);
305 }
306 return rc;
307}
308
309/*
310** Initialize all database files - the main database file, the file
311** used to store temporary tables, and any additional database files
312** created using ATTACH statements. Return a success code. If an
313** error occurs, write an error message into *pzErrMsg.
314**
315** After the database is initialized, the SQLITE_Initialized
316** bit is set in the flags field of the sqlite structure.
317*/
318int sqlite3Init(sqlite3 *db, char **pzErrMsg){
319 int i, rc;
320
321 if( db->init.busy ) return SQLITE_OK;
322 assert( (db->flags & SQLITE_Initialized)==0 );
323 rc = SQLITE_OK;
324 db->init.busy = 1;
325 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
326 if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
327 rc = sqlite3InitOne(db, i, pzErrMsg);
328 if( rc ){
329 sqlite3ResetInternalSchema(db, i);
330 }
331 }
332
333 /* Once all the other databases have been initialised, load the schema
334 ** for the TEMP database. This is loaded last, as the TEMP database
335 ** schema may contain references to objects in other databases.
336 */
337#ifndef SQLITE_OMIT_TEMPDB
338 if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
339 rc = sqlite3InitOne(db, 1, pzErrMsg);
340 if( rc ){
341 sqlite3ResetInternalSchema(db, 1);
342 }
343 }
344#endif
345
346 db->init.busy = 0;
347 if( rc==SQLITE_OK ){
348 db->flags |= SQLITE_Initialized;
349 sqlite3CommitInternalChanges(db);
350 }
351
352 if( rc!=SQLITE_OK ){
353 db->flags &= ~SQLITE_Initialized;
354 }
355 return rc;
356}
357
358/*
359** This routine is a no-op if the database schema is already initialised.
360** Otherwise, the schema is loaded. An error code is returned.
361*/
362int sqlite3ReadSchema(Parse *pParse){
363 int rc = SQLITE_OK;
364 sqlite3 *db = pParse->db;
365 if( !db->init.busy ){
366 if( (db->flags & SQLITE_Initialized)==0 ){
367 rc = sqlite3Init(db, &pParse->zErrMsg);
368 }
369 }
drh8b3d9902005-08-19 00:14:42 +0000370 assert( rc!=SQLITE_OK || (db->flags & SQLITE_Initialized) || db->init.busy );
danielk1977fa256a32005-05-25 04:11:56 +0000371 if( rc!=SQLITE_OK ){
372 pParse->rc = rc;
373 pParse->nErr++;
374 }
375 return rc;
376}
377
378
379/*
380** Check schema cookies in all databases. If any cookie is out
381** of date, return 0. If all schema cookies are current, return 1.
382*/
383static int schemaIsValid(sqlite3 *db){
384 int iDb;
385 int rc;
386 BtCursor *curTemp;
387 int cookie;
388 int allOk = 1;
389
390 for(iDb=0; allOk && iDb<db->nDb; iDb++){
391 Btree *pBt;
392 pBt = db->aDb[iDb].pBt;
393 if( pBt==0 ) continue;
394 rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, 0, &curTemp);
395 if( rc==SQLITE_OK ){
396 rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
397 if( rc==SQLITE_OK && cookie!=db->aDb[iDb].schema_cookie ){
398 allOk = 0;
399 }
400 sqlite3BtreeCloseCursor(curTemp);
401 }
402 }
403 return allOk;
404}
405
406/*
407** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
408*/
409int sqlite3_prepare(
410 sqlite3 *db, /* Database handle. */
411 const char *zSql, /* UTF-8 encoded SQL statement. */
412 int nBytes, /* Length of zSql in bytes. */
413 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
414 const char** pzTail /* OUT: End of parsed string */
415){
416 Parse sParse;
417 char *zErrMsg = 0;
418 int rc = SQLITE_OK;
419
danielk1977261919c2005-12-06 12:52:59 +0000420 assert(!sqlite3Tsd()->mallocFailed);
danielk1977fa256a32005-05-25 04:11:56 +0000421
422 assert( ppStmt );
423 *ppStmt = 0;
424 if( sqlite3SafetyOn(db) ){
425 return SQLITE_MISUSE;
426 }
427
428 memset(&sParse, 0, sizeof(sParse));
429 sParse.db = db;
430 sqlite3RunParser(&sParse, zSql, &zErrMsg);
431
danielk1977261919c2005-12-06 12:52:59 +0000432 if( sqlite3Tsd()->mallocFailed ){
433 sParse.rc = SQLITE_NOMEM;
danielk1977fa256a32005-05-25 04:11:56 +0000434 }
435 if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
drh4d91a702006-01-04 15:54:36 +0000436 if( sParse.checkSchema && !schemaIsValid(db) ){
danielk1977fa256a32005-05-25 04:11:56 +0000437 sParse.rc = SQLITE_SCHEMA;
438 }
439 if( sParse.rc==SQLITE_SCHEMA ){
440 sqlite3ResetInternalSchema(db, 0);
441 }
442 if( pzTail ) *pzTail = sParse.zTail;
443 rc = sParse.rc;
444
445#ifndef SQLITE_OMIT_EXPLAIN
446 if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
drhecc92422005-09-10 16:46:12 +0000447 if( sParse.explain==2 ){
448 sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
449 sqlite3VdbeSetColName(sParse.pVdbe, 0, "order", P3_STATIC);
450 sqlite3VdbeSetColName(sParse.pVdbe, 1, "from", P3_STATIC);
451 sqlite3VdbeSetColName(sParse.pVdbe, 2, "detail", P3_STATIC);
452 }else{
453 sqlite3VdbeSetNumCols(sParse.pVdbe, 5);
454 sqlite3VdbeSetColName(sParse.pVdbe, 0, "addr", P3_STATIC);
455 sqlite3VdbeSetColName(sParse.pVdbe, 1, "opcode", P3_STATIC);
456 sqlite3VdbeSetColName(sParse.pVdbe, 2, "p1", P3_STATIC);
457 sqlite3VdbeSetColName(sParse.pVdbe, 3, "p2", P3_STATIC);
458 sqlite3VdbeSetColName(sParse.pVdbe, 4, "p3", P3_STATIC);
459 }
danielk1977fa256a32005-05-25 04:11:56 +0000460 }
461#endif
462
danielk1977fa256a32005-05-25 04:11:56 +0000463 if( sqlite3SafetyOff(db) ){
464 rc = SQLITE_MISUSE;
465 }
466 if( rc==SQLITE_OK ){
467 *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
468 }else if( sParse.pVdbe ){
469 sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
470 }
471
472 if( zErrMsg ){
473 sqlite3Error(db, rc, "%s", zErrMsg);
474 sqliteFree(zErrMsg);
475 }else{
476 sqlite3Error(db, rc, 0);
477 }
danielk1977261919c2005-12-06 12:52:59 +0000478
479 /* We must check for malloc failure last of all, in case malloc() failed
480 ** inside of the sqlite3Error() call above or something.
481 */
482 if( sqlite3Tsd()->mallocFailed ){
483 rc = SQLITE_NOMEM;
484 sqlite3Error(db, rc, 0);
485 }
486
danielk19772e588c72005-12-09 14:25:08 +0000487 sqlite3MallocClearFailed();
danielk1977fa256a32005-05-25 04:11:56 +0000488 return rc;
489}
490
491#ifndef SQLITE_OMIT_UTF16
492/*
493** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
494*/
495int sqlite3_prepare16(
496 sqlite3 *db, /* Database handle. */
497 const void *zSql, /* UTF-8 encoded SQL statement. */
498 int nBytes, /* Length of zSql in bytes. */
499 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
500 const void **pzTail /* OUT: End of parsed string */
501){
502 /* This function currently works by first transforming the UTF-16
503 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
504 ** tricky bit is figuring out the pointer to return in *pzTail.
505 */
drhaf9a7c22005-12-15 03:04:10 +0000506 char *zSql8 = 0;
507 char *zTail8 = 0;
danielk1977fa256a32005-05-25 04:11:56 +0000508 int rc;
danielk1977fa256a32005-05-25 04:11:56 +0000509
510 if( sqlite3SafetyCheck(db) ){
511 return SQLITE_MISUSE;
512 }
drhaf9a7c22005-12-15 03:04:10 +0000513 zSql8 = sqlite3utf16to8(zSql, nBytes);
danielk1977fa256a32005-05-25 04:11:56 +0000514 if( !zSql8 ){
515 sqlite3Error(db, SQLITE_NOMEM, 0);
516 return SQLITE_NOMEM;
517 }
518 rc = sqlite3_prepare(db, zSql8, -1, ppStmt, &zTail8);
519
520 if( zTail8 && pzTail ){
521 /* If sqlite3_prepare returns a tail pointer, we calculate the
522 ** equivalent pointer into the UTF-16 string by counting the unicode
523 ** characters between zSql8 and zTail8, and then returning a pointer
524 ** the same number of characters into the UTF-16 string.
525 */
526 int chars_parsed = sqlite3utf8CharLen(zSql8, zTail8-zSql8);
527 *pzTail = (u8 *)zSql + sqlite3utf16ByteLen(zSql, chars_parsed);
528 }
drhaf9a7c22005-12-15 03:04:10 +0000529 sqliteFree(zSql8);
danielk1977fa256a32005-05-25 04:11:56 +0000530 return rc;
531}
532#endif /* SQLITE_OMIT_UTF16 */