Remove a superfluous "#if 1". No logic changes.
[sqlite.git] / src / attach.c
blobf3d68553b6fb189954930bbdcb26804e796c68d6
1 /*
2 ** 2003 April 6
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.
11 *************************************************************************
12 ** This file contains code used to implement the ATTACH and DETACH commands.
14 #include "sqliteInt.h"
16 #ifndef SQLITE_OMIT_ATTACH
18 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
19 ** is slightly different from resolving a normal SQL expression, because simple
20 ** identifiers are treated as strings, not possible column names or aliases.
22 ** i.e. if the parser sees:
24 ** ATTACH DATABASE abc AS def
26 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
27 ** looking for columns of the same name.
29 ** This only applies to the root node of pExpr, so the statement:
31 ** ATTACH DATABASE abc||def AS 'db2'
33 ** will fail because neither abc or def can be resolved.
35 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
37 int rc = SQLITE_OK;
38 if( pExpr ){
39 if( pExpr->op!=TK_ID ){
40 rc = sqlite3ResolveExprNames(pName, pExpr);
41 }else{
42 pExpr->op = TK_STRING;
45 return rc;
49 ** An SQL user-function registered to do the work of an ATTACH statement. The
50 ** three arguments to the function come directly from an attach statement:
52 ** ATTACH DATABASE x AS y KEY z
54 ** SELECT sqlite_attach(x, y, z)
56 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
57 ** third argument.
59 static void attachFunc(
60 sqlite3_context *context,
61 int NotUsed,
62 sqlite3_value **argv
64 int i;
65 int rc = 0;
66 sqlite3 *db = sqlite3_context_db_handle(context);
67 const char *zName;
68 const char *zFile;
69 char *zPath = 0;
70 char *zErr = 0;
71 unsigned int flags;
72 Db *aNew; /* New array of Db pointers */
73 Db *pNew; /* Db object for the newly attached database */
74 char *zErrDyn = 0;
75 sqlite3_vfs *pVfs;
77 UNUSED_PARAMETER(NotUsed);
79 zFile = (const char *)sqlite3_value_text(argv[0]);
80 zName = (const char *)sqlite3_value_text(argv[1]);
81 if( zFile==0 ) zFile = "";
82 if( zName==0 ) zName = "";
84 /* Check for the following errors:
86 ** * Too many attached databases,
87 ** * Transaction currently open
88 ** * Specified database name already being used.
90 if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
91 zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
92 db->aLimit[SQLITE_LIMIT_ATTACHED]
94 goto attach_error;
96 for(i=0; i<db->nDb; i++){
97 char *z = db->aDb[i].zDbSName;
98 assert( z && zName );
99 if( sqlite3StrICmp(z, zName)==0 ){
100 zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
101 goto attach_error;
105 /* Allocate the new entry in the db->aDb[] array and initialize the schema
106 ** hash tables.
108 if( db->aDb==db->aDbStatic ){
109 aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
110 if( aNew==0 ) return;
111 memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
112 }else{
113 aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
114 if( aNew==0 ) return;
116 db->aDb = aNew;
117 pNew = &db->aDb[db->nDb];
118 memset(pNew, 0, sizeof(*pNew));
120 /* Open the database file. If the btree is successfully opened, use
121 ** it to obtain the database schema. At this point the schema may
122 ** or may not be initialized.
124 flags = db->openFlags;
125 rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
126 if( rc!=SQLITE_OK ){
127 if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
128 sqlite3_result_error(context, zErr, -1);
129 sqlite3_free(zErr);
130 return;
132 assert( pVfs );
133 flags |= SQLITE_OPEN_MAIN_DB;
134 rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
135 sqlite3_free( zPath );
136 db->nDb++;
137 db->skipBtreeMutex = 0;
138 if( rc==SQLITE_CONSTRAINT ){
139 rc = SQLITE_ERROR;
140 zErrDyn = sqlite3MPrintf(db, "database is already attached");
141 }else if( rc==SQLITE_OK ){
142 Pager *pPager;
143 pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
144 if( !pNew->pSchema ){
145 rc = SQLITE_NOMEM_BKPT;
146 }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
147 zErrDyn = sqlite3MPrintf(db,
148 "attached databases must use the same text encoding as main database");
149 rc = SQLITE_ERROR;
151 sqlite3BtreeEnter(pNew->pBt);
152 pPager = sqlite3BtreePager(pNew->pBt);
153 sqlite3PagerLockingMode(pPager, db->dfltLockMode);
154 sqlite3BtreeSecureDelete(pNew->pBt,
155 sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
156 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
157 sqlite3BtreeSetPagerFlags(pNew->pBt,
158 PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
159 #endif
160 sqlite3BtreeLeave(pNew->pBt);
162 pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
163 pNew->zDbSName = sqlite3DbStrDup(db, zName);
164 if( rc==SQLITE_OK && pNew->zDbSName==0 ){
165 rc = SQLITE_NOMEM_BKPT;
169 #ifdef SQLITE_HAS_CODEC
170 if( rc==SQLITE_OK ){
171 extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
172 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
173 int nKey;
174 char *zKey;
175 int t = sqlite3_value_type(argv[2]);
176 switch( t ){
177 case SQLITE_INTEGER:
178 case SQLITE_FLOAT:
179 zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
180 rc = SQLITE_ERROR;
181 break;
183 case SQLITE_TEXT:
184 case SQLITE_BLOB:
185 nKey = sqlite3_value_bytes(argv[2]);
186 zKey = (char *)sqlite3_value_blob(argv[2]);
187 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
188 break;
190 case SQLITE_NULL:
191 /* No key specified. Use the key from the main database */
192 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
193 if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
194 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
196 break;
199 #endif
201 /* If the file was opened successfully, read the schema for the new database.
202 ** If this fails, or if opening the file failed, then close the file and
203 ** remove the entry from the db->aDb[] array. i.e. put everything back the way
204 ** we found it.
206 if( rc==SQLITE_OK ){
207 sqlite3BtreeEnterAll(db);
208 rc = sqlite3Init(db, &zErrDyn);
209 sqlite3BtreeLeaveAll(db);
211 #ifdef SQLITE_USER_AUTHENTICATION
212 if( rc==SQLITE_OK ){
213 u8 newAuth = 0;
214 rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
215 if( newAuth<db->auth.authLevel ){
216 rc = SQLITE_AUTH_USER;
219 #endif
220 if( rc ){
221 int iDb = db->nDb - 1;
222 assert( iDb>=2 );
223 if( db->aDb[iDb].pBt ){
224 sqlite3BtreeClose(db->aDb[iDb].pBt);
225 db->aDb[iDb].pBt = 0;
226 db->aDb[iDb].pSchema = 0;
228 sqlite3ResetAllSchemasOfConnection(db);
229 db->nDb = iDb;
230 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
231 sqlite3OomFault(db);
232 sqlite3DbFree(db, zErrDyn);
233 zErrDyn = sqlite3MPrintf(db, "out of memory");
234 }else if( zErrDyn==0 ){
235 zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
237 goto attach_error;
240 return;
242 attach_error:
243 /* Return an error if we get here */
244 if( zErrDyn ){
245 sqlite3_result_error(context, zErrDyn, -1);
246 sqlite3DbFree(db, zErrDyn);
248 if( rc ) sqlite3_result_error_code(context, rc);
252 ** An SQL user-function registered to do the work of an DETACH statement. The
253 ** three arguments to the function come directly from a detach statement:
255 ** DETACH DATABASE x
257 ** SELECT sqlite_detach(x)
259 static void detachFunc(
260 sqlite3_context *context,
261 int NotUsed,
262 sqlite3_value **argv
264 const char *zName = (const char *)sqlite3_value_text(argv[0]);
265 sqlite3 *db = sqlite3_context_db_handle(context);
266 int i;
267 Db *pDb = 0;
268 char zErr[128];
270 UNUSED_PARAMETER(NotUsed);
272 if( zName==0 ) zName = "";
273 for(i=0; i<db->nDb; i++){
274 pDb = &db->aDb[i];
275 if( pDb->pBt==0 ) continue;
276 if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
279 if( i>=db->nDb ){
280 sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
281 goto detach_error;
283 if( i<2 ){
284 sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
285 goto detach_error;
287 if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
288 sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
289 goto detach_error;
292 sqlite3BtreeClose(pDb->pBt);
293 pDb->pBt = 0;
294 pDb->pSchema = 0;
295 sqlite3CollapseDatabaseArray(db);
296 return;
298 detach_error:
299 sqlite3_result_error(context, zErr, -1);
303 ** This procedure generates VDBE code for a single invocation of either the
304 ** sqlite_detach() or sqlite_attach() SQL user functions.
306 static void codeAttach(
307 Parse *pParse, /* The parser context */
308 int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
309 FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
310 Expr *pAuthArg, /* Expression to pass to authorization callback */
311 Expr *pFilename, /* Name of database file */
312 Expr *pDbname, /* Name of the database to use internally */
313 Expr *pKey /* Database key for encryption extension */
315 int rc;
316 NameContext sName;
317 Vdbe *v;
318 sqlite3* db = pParse->db;
319 int regArgs;
321 if( pParse->nErr ) goto attach_end;
322 memset(&sName, 0, sizeof(NameContext));
323 sName.pParse = pParse;
325 if(
326 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
327 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
328 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
330 goto attach_end;
333 #ifndef SQLITE_OMIT_AUTHORIZATION
334 if( pAuthArg ){
335 char *zAuthArg;
336 if( pAuthArg->op==TK_STRING ){
337 zAuthArg = pAuthArg->u.zToken;
338 }else{
339 zAuthArg = 0;
341 rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
342 if(rc!=SQLITE_OK ){
343 goto attach_end;
346 #endif /* SQLITE_OMIT_AUTHORIZATION */
349 v = sqlite3GetVdbe(pParse);
350 regArgs = sqlite3GetTempRange(pParse, 4);
351 sqlite3ExprCode(pParse, pFilename, regArgs);
352 sqlite3ExprCode(pParse, pDbname, regArgs+1);
353 sqlite3ExprCode(pParse, pKey, regArgs+2);
355 assert( v || db->mallocFailed );
356 if( v ){
357 sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
358 (char *)pFunc, P4_FUNCDEF);
359 assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
360 sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
362 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
363 ** statement only). For DETACH, set it to false (expire all existing
364 ** statements).
366 sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
369 attach_end:
370 sqlite3ExprDelete(db, pFilename);
371 sqlite3ExprDelete(db, pDbname);
372 sqlite3ExprDelete(db, pKey);
376 ** Called by the parser to compile a DETACH statement.
378 ** DETACH pDbname
380 void sqlite3Detach(Parse *pParse, Expr *pDbname){
381 static const FuncDef detach_func = {
382 1, /* nArg */
383 SQLITE_UTF8, /* funcFlags */
384 0, /* pUserData */
385 0, /* pNext */
386 detachFunc, /* xSFunc */
387 0, /* xFinalize */
388 "sqlite_detach", /* zName */
391 codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
395 ** Called by the parser to compile an ATTACH statement.
397 ** ATTACH p AS pDbname KEY pKey
399 void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
400 static const FuncDef attach_func = {
401 3, /* nArg */
402 SQLITE_UTF8, /* funcFlags */
403 0, /* pUserData */
404 0, /* pNext */
405 attachFunc, /* xSFunc */
406 0, /* xFinalize */
407 "sqlite_attach", /* zName */
410 codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
412 #endif /* SQLITE_OMIT_ATTACH */
415 ** Initialize a DbFixer structure. This routine must be called prior
416 ** to passing the structure to one of the sqliteFixAAAA() routines below.
418 void sqlite3FixInit(
419 DbFixer *pFix, /* The fixer to be initialized */
420 Parse *pParse, /* Error messages will be written here */
421 int iDb, /* This is the database that must be used */
422 const char *zType, /* "view", "trigger", or "index" */
423 const Token *pName /* Name of the view, trigger, or index */
425 sqlite3 *db;
427 db = pParse->db;
428 assert( db->nDb>iDb );
429 pFix->pParse = pParse;
430 pFix->zDb = db->aDb[iDb].zDbSName;
431 pFix->pSchema = db->aDb[iDb].pSchema;
432 pFix->zType = zType;
433 pFix->pName = pName;
434 pFix->bVarOnly = (iDb==1);
438 ** The following set of routines walk through the parse tree and assign
439 ** a specific database to all table references where the database name
440 ** was left unspecified in the original SQL statement. The pFix structure
441 ** must have been initialized by a prior call to sqlite3FixInit().
443 ** These routines are used to make sure that an index, trigger, or
444 ** view in one database does not refer to objects in a different database.
445 ** (Exception: indices, triggers, and views in the TEMP database are
446 ** allowed to refer to anything.) If a reference is explicitly made
447 ** to an object in a different database, an error message is added to
448 ** pParse->zErrMsg and these routines return non-zero. If everything
449 ** checks out, these routines return 0.
451 int sqlite3FixSrcList(
452 DbFixer *pFix, /* Context of the fixation */
453 SrcList *pList /* The Source list to check and modify */
455 int i;
456 const char *zDb;
457 struct SrcList_item *pItem;
459 if( NEVER(pList==0) ) return 0;
460 zDb = pFix->zDb;
461 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
462 if( pFix->bVarOnly==0 ){
463 if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
464 sqlite3ErrorMsg(pFix->pParse,
465 "%s %T cannot reference objects in database %s",
466 pFix->zType, pFix->pName, pItem->zDatabase);
467 return 1;
469 sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
470 pItem->zDatabase = 0;
471 pItem->pSchema = pFix->pSchema;
473 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
474 if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
475 if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
476 #endif
478 return 0;
480 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
481 int sqlite3FixSelect(
482 DbFixer *pFix, /* Context of the fixation */
483 Select *pSelect /* The SELECT statement to be fixed to one database */
485 while( pSelect ){
486 if( sqlite3FixExprList(pFix, pSelect->pEList) ){
487 return 1;
489 if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
490 return 1;
492 if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
493 return 1;
495 if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
496 return 1;
498 if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
499 return 1;
501 if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
502 return 1;
504 if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
505 return 1;
507 if( pSelect->pWith ){
508 int i;
509 for(i=0; i<pSelect->pWith->nCte; i++){
510 if( sqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){
511 return 1;
515 pSelect = pSelect->pPrior;
517 return 0;
519 int sqlite3FixExpr(
520 DbFixer *pFix, /* Context of the fixation */
521 Expr *pExpr /* The expression to be fixed to one database */
523 while( pExpr ){
524 if( pExpr->op==TK_VARIABLE ){
525 if( pFix->pParse->db->init.busy ){
526 pExpr->op = TK_NULL;
527 }else{
528 sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
529 return 1;
532 if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
533 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
534 if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
535 }else{
536 if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
538 if( sqlite3FixExpr(pFix, pExpr->pRight) ){
539 return 1;
541 pExpr = pExpr->pLeft;
543 return 0;
545 int sqlite3FixExprList(
546 DbFixer *pFix, /* Context of the fixation */
547 ExprList *pList /* The expression to be fixed to one database */
549 int i;
550 struct ExprList_item *pItem;
551 if( pList==0 ) return 0;
552 for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
553 if( sqlite3FixExpr(pFix, pItem->pExpr) ){
554 return 1;
557 return 0;
559 #endif
561 #ifndef SQLITE_OMIT_TRIGGER
562 int sqlite3FixTriggerStep(
563 DbFixer *pFix, /* Context of the fixation */
564 TriggerStep *pStep /* The trigger step be fixed to one database */
566 while( pStep ){
567 if( sqlite3FixSelect(pFix, pStep->pSelect) ){
568 return 1;
570 if( sqlite3FixExpr(pFix, pStep->pWhere) ){
571 return 1;
573 if( sqlite3FixExprList(pFix, pStep->pExprList) ){
574 return 1;
576 pStep = pStep->pNext;
578 return 0;
580 #endif