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 code used to implement the ATTACH and DETACH commands.
16 #include "sqliteInt.h"
18 #ifndef SQLITE_OMIT_ATTACH
20 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
21 ** is slightly different from resolving a normal SQL expression, because simple
22 ** identifiers are treated as strings, not possible column names or aliases.
24 ** i.e. if the parser sees:
26 ** ATTACH DATABASE abc AS def
28 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
29 ** looking for columns of the same name.
31 ** This only applies to the root node of pExpr, so the statement:
33 ** ATTACH DATABASE abc||def AS 'db2'
35 ** will fail because neither abc or def can be resolved.
37 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
41 if( pExpr->op!=TK_ID ){
42 rc = sqlite3ExprResolveNames(pName, pExpr);
43 if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
44 sqlite3ErrorMsg(pName->pParse, "invalid name: \"%T\"", &pExpr->span);
48 pExpr->op = TK_STRING;
55 ** An SQL user-function registered to do the work of an ATTACH statement. The
56 ** three arguments to the function come directly from an attach statement:
58 ** ATTACH DATABASE x AS y KEY z
60 ** SELECT sqlite_attach(x, y, z)
62 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
65 static void attachFunc(
66 sqlite3_context *context,
72 sqlite3 *db = sqlite3_user_data(context);
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>=SQLITE_MAX_ATTACHED+2 ){
92 sizeof(zErr), zErr, "too many attached databases - max %d",
97 if( !db->autoCommit ){
98 sqlite3_snprintf(sizeof(zErr), zErr,
99 "cannot ATTACH database within transaction");
102 for(i=0; i<db->nDb; i++){
103 char *z = db->aDb[i].zName;
104 if( z && zName && sqlite3StrICmp(z, zName)==0 ){
105 sqlite3_snprintf(sizeof(zErr), zErr,
106 "database %s is already in use", zName);
111 /* Allocate the new entry in the db->aDb[] array and initialise the schema
114 if( db->aDb==db->aDbStatic ){
115 aNew = sqlite3_malloc( sizeof(db->aDb[0])*3 );
117 db->mallocFailed = 1;
120 memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
122 aNew = sqlite3_realloc(db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
124 db->mallocFailed = 1;
129 aNew = &db->aDb[db->nDb++];
130 memset(aNew, 0, sizeof(*aNew));
132 /* Open the database file. If the btree is successfully opened, use
133 ** it to obtain the database schema. At this point the schema may
134 ** or may not be initialised.
136 rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
137 db->openFlags | SQLITE_OPEN_MAIN_DB,
140 aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
141 if( !aNew->pSchema ){
143 }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
144 sqlite3_snprintf(sizeof(zErr), zErr,
145 "attached databases must use the same text encoding as main database");
148 sqlite3PagerLockingMode(sqlite3BtreePager(aNew->pBt), db->dfltLockMode);
150 aNew->zName = sqlite3DbStrDup(db, zName);
151 aNew->safety_level = 3;
155 extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
156 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
159 int t = sqlite3_value_type(argv[2]);
163 zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
169 nKey = sqlite3_value_bytes(argv[2]);
170 zKey = (char *)sqlite3_value_blob(argv[2]);
171 sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
175 /* No key specified. Use the key from the main database */
176 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
177 sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
183 /* If the file was opened successfully, read the schema for the new database.
184 ** If this fails, or if opening the file failed, then close the file and
185 ** remove the entry from the db->aDb[] array. i.e. put everything back the way
190 rc = sqlite3Init(db, &zErrDyn);
191 sqlite3SafetyOff(db);
194 int iDb = db->nDb - 1;
196 if( db->aDb[iDb].pBt ){
197 sqlite3BtreeClose(db->aDb[iDb].pBt);
198 db->aDb[iDb].pBt = 0;
199 db->aDb[iDb].pSchema = 0;
201 sqlite3ResetInternalSchema(db, 0);
203 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
204 db->mallocFailed = 1;
205 sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
207 sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
215 /* Return an error if we get here */
217 sqlite3_result_error(context, zErrDyn, -1);
218 sqlite3_free(zErrDyn);
220 zErr[sizeof(zErr)-1] = 0;
221 sqlite3_result_error(context, zErr, -1);
226 ** An SQL user-function registered to do the work of an DETACH statement. The
227 ** three arguments to the function come directly from a detach statement:
231 ** SELECT sqlite_detach(x)
233 static void detachFunc(
234 sqlite3_context *context,
238 const char *zName = (const char *)sqlite3_value_text(argv[0]);
239 sqlite3 *db = sqlite3_user_data(context);
244 if( zName==0 ) zName = "";
245 for(i=0; i<db->nDb; i++){
247 if( pDb->pBt==0 ) continue;
248 if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
252 sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
256 sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
259 if( !db->autoCommit ){
260 sqlite3_snprintf(sizeof(zErr), zErr,
261 "cannot DETACH database within transaction");
264 if( sqlite3BtreeIsInReadTrans(pDb->pBt) ){
265 sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
269 sqlite3BtreeClose(pDb->pBt);
272 sqlite3ResetInternalSchema(db, 0);
276 sqlite3_result_error(context, zErr, -1);
280 ** This procedure generates VDBE code for a single invocation of either the
281 ** sqlite_detach() or sqlite_attach() SQL user functions.
283 static void codeAttach(
284 Parse *pParse, /* The parser context */
285 int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
286 const char *zFunc, /* Either "sqlite_attach" or "sqlite_detach */
287 int nFunc, /* Number of args to pass to zFunc */
288 Expr *pAuthArg, /* Expression to pass to authorization callback */
289 Expr *pFilename, /* Name of database file */
290 Expr *pDbname, /* Name of the database to use internally */
291 Expr *pKey /* Database key for encryption extension */
297 sqlite3* db = pParse->db;
299 #ifndef SQLITE_OMIT_AUTHORIZATION
300 assert( db->mallocFailed || pAuthArg );
302 char *zAuthArg = sqlite3NameFromToken(db, &pAuthArg->span);
306 rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
307 sqlite3_free(zAuthArg);
312 #endif /* SQLITE_OMIT_AUTHORIZATION */
314 memset(&sName, 0, sizeof(NameContext));
315 sName.pParse = pParse;
318 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
319 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
320 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
326 v = sqlite3GetVdbe(pParse);
327 sqlite3ExprCode(pParse, pFilename);
328 sqlite3ExprCode(pParse, pDbname);
329 sqlite3ExprCode(pParse, pKey);
331 assert( v || db->mallocFailed );
333 sqlite3VdbeAddOp(v, OP_Function, 0, nFunc);
334 pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0);
335 sqlite3VdbeChangeP3(v, -1, (char *)pFunc, P3_FUNCDEF);
337 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
338 ** statement only). For DETACH, set it to false (expire all existing
341 sqlite3VdbeAddOp(v, OP_Expire, (type==SQLITE_ATTACH), 0);
345 sqlite3ExprDelete(pFilename);
346 sqlite3ExprDelete(pDbname);
347 sqlite3ExprDelete(pKey);
351 ** Called by the parser to compile a DETACH statement.
355 void sqlite3Detach(Parse *pParse, Expr *pDbname){
356 codeAttach(pParse, SQLITE_DETACH, "sqlite_detach", 1, pDbname, 0, 0, pDbname);
360 ** Called by the parser to compile an ATTACH statement.
362 ** ATTACH p AS pDbname KEY pKey
364 void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
365 codeAttach(pParse, SQLITE_ATTACH, "sqlite_attach", 3, p, p, pDbname, pKey);
367 #endif /* SQLITE_OMIT_ATTACH */
370 ** Register the functions sqlite_attach and sqlite_detach.
372 void sqlite3AttachFunctions(sqlite3 *db){
373 #ifndef SQLITE_OMIT_ATTACH
374 static const int enc = SQLITE_UTF8;
375 sqlite3CreateFunc(db, "sqlite_attach", 3, enc, db, attachFunc, 0, 0);
376 sqlite3CreateFunc(db, "sqlite_detach", 1, enc, db, detachFunc, 0, 0);
381 ** Initialize a DbFixer structure. This routine must be called prior
382 ** to passing the structure to one of the sqliteFixAAAA() routines below.
384 ** The return value indicates whether or not fixation is required. TRUE
385 ** means we do need to fix the database references, FALSE means we do not.
388 DbFixer *pFix, /* The fixer to be initialized */
389 Parse *pParse, /* Error messages will be written here */
390 int iDb, /* This is the database that must be used */
391 const char *zType, /* "view", "trigger", or "index" */
392 const Token *pName /* Name of the view, trigger, or index */
396 if( iDb<0 || iDb==1 ) return 0;
398 assert( db->nDb>iDb );
399 pFix->pParse = pParse;
400 pFix->zDb = db->aDb[iDb].zName;
407 ** The following set of routines walk through the parse tree and assign
408 ** a specific database to all table references where the database name
409 ** was left unspecified in the original SQL statement. The pFix structure
410 ** must have been initialized by a prior call to sqlite3FixInit().
412 ** These routines are used to make sure that an index, trigger, or
413 ** view in one database does not refer to objects in a different database.
414 ** (Exception: indices, triggers, and views in the TEMP database are
415 ** allowed to refer to anything.) If a reference is explicitly made
416 ** to an object in a different database, an error message is added to
417 ** pParse->zErrMsg and these routines return non-zero. If everything
418 ** checks out, these routines return 0.
420 int sqlite3FixSrcList(
421 DbFixer *pFix, /* Context of the fixation */
422 SrcList *pList /* The Source list to check and modify */
426 struct SrcList_item *pItem;
428 if( pList==0 ) return 0;
430 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
431 if( pItem->zDatabase==0 ){
432 pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
433 }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
434 sqlite3ErrorMsg(pFix->pParse,
435 "%s %T cannot reference objects in database %s",
436 pFix->zType, pFix->pName, pItem->zDatabase);
439 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
440 if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
441 if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
446 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
447 int sqlite3FixSelect(
448 DbFixer *pFix, /* Context of the fixation */
449 Select *pSelect /* The SELECT statement to be fixed to one database */
452 if( sqlite3FixExprList(pFix, pSelect->pEList) ){
455 if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
458 if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
461 if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
464 pSelect = pSelect->pPrior;
469 DbFixer *pFix, /* Context of the fixation */
470 Expr *pExpr /* The expression to be fixed to one database */
473 if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
476 if( sqlite3FixExprList(pFix, pExpr->pList) ){
479 if( sqlite3FixExpr(pFix, pExpr->pRight) ){
482 pExpr = pExpr->pLeft;
486 int sqlite3FixExprList(
487 DbFixer *pFix, /* Context of the fixation */
488 ExprList *pList /* The expression to be fixed to one database */
491 struct ExprList_item *pItem;
492 if( pList==0 ) return 0;
493 for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
494 if( sqlite3FixExpr(pFix, pItem->pExpr) ){
502 #ifndef SQLITE_OMIT_TRIGGER
503 int sqlite3FixTriggerStep(
504 DbFixer *pFix, /* Context of the fixation */
505 TriggerStep *pStep /* The trigger step be fixed to one database */
508 if( sqlite3FixSelect(pFix, pStep->pSelect) ){
511 if( sqlite3FixExpr(pFix, pStep->pWhere) ){
514 if( sqlite3FixExprList(pFix, pStep->pExprList) ){
517 pStep = pStep->pNext;