xref: /sqlite-3.40.0/src/attach.c (revision 6695f47e)
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.
10 **
11 *************************************************************************
12 ** This file contains code used to implement the ATTACH and DETACH commands.
13 */
14 #include "sqliteInt.h"
15 
16 #ifndef SQLITE_OMIT_ATTACH
17 /*
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.
21 **
22 ** i.e. if the parser sees:
23 **
24 **     ATTACH DATABASE abc AS def
25 **
26 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
27 ** looking for columns of the same name.
28 **
29 ** This only applies to the root node of pExpr, so the statement:
30 **
31 **     ATTACH DATABASE abc||def AS 'db2'
32 **
33 ** will fail because neither abc or def can be resolved.
34 */
35 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
36 {
37   int rc = SQLITE_OK;
38   if( pExpr ){
39     if( pExpr->op!=TK_ID ){
40       rc = sqlite3ResolveExprNames(pName, pExpr);
41       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
42         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
43         return SQLITE_ERROR;
44       }
45     }else{
46       pExpr->op = TK_STRING;
47     }
48   }
49   return rc;
50 }
51 
52 /*
53 ** An SQL user-function registered to do the work of an ATTACH statement. The
54 ** three arguments to the function come directly from an attach statement:
55 **
56 **     ATTACH DATABASE x AS y KEY z
57 **
58 **     SELECT sqlite_attach(x, y, z)
59 **
60 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
61 ** third argument.
62 */
63 static void attachFunc(
64   sqlite3_context *context,
65   int NotUsed,
66   sqlite3_value **argv
67 ){
68   int i;
69   int rc = 0;
70   sqlite3 *db = sqlite3_context_db_handle(context);
71   const char *zName;
72   const char *zFile;
73   Db *aNew;
74   char *zErrDyn = 0;
75 
76   UNUSED_PARAMETER(NotUsed);
77 
78   zFile = (const char *)sqlite3_value_text(argv[0]);
79   zName = (const char *)sqlite3_value_text(argv[1]);
80   if( zFile==0 ) zFile = "";
81   if( zName==0 ) zName = "";
82 
83   /* Check for the following errors:
84   **
85   **     * Too many attached databases,
86   **     * Transaction currently open
87   **     * Specified database name already being used.
88   */
89   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
90     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
91       db->aLimit[SQLITE_LIMIT_ATTACHED]
92     );
93     goto attach_error;
94   }
95   if( !db->autoCommit ){
96     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
97     goto attach_error;
98   }
99   for(i=0; i<db->nDb; i++){
100     char *z = db->aDb[i].zName;
101     assert( z && zName );
102     if( sqlite3StrICmp(z, zName)==0 ){
103       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
104       goto attach_error;
105     }
106   }
107 
108   /* Allocate the new entry in the db->aDb[] array and initialise the schema
109   ** hash tables.
110   */
111   if( db->aDb==db->aDbStatic ){
112     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
113     if( aNew==0 ) return;
114     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
115   }else{
116     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
117     if( aNew==0 ) return;
118   }
119   db->aDb = aNew;
120   aNew = &db->aDb[db->nDb];
121   memset(aNew, 0, sizeof(*aNew));
122 
123   /* Open the database file. If the btree is successfully opened, use
124   ** it to obtain the database schema. At this point the schema may
125   ** or may not be initialised.
126   */
127   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
128                            db->openFlags | SQLITE_OPEN_MAIN_DB,
129                            &aNew->pBt);
130   db->nDb++;
131   if( rc==SQLITE_CONSTRAINT ){
132     rc = SQLITE_ERROR;
133     zErrDyn = sqlite3MPrintf(db, "database is already attached");
134   }else if( rc==SQLITE_OK ){
135     Pager *pPager;
136     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
137     if( !aNew->pSchema ){
138       rc = SQLITE_NOMEM;
139     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
140       zErrDyn = sqlite3MPrintf(db,
141         "attached databases must use the same text encoding as main database");
142       rc = SQLITE_ERROR;
143     }
144     pPager = sqlite3BtreePager(aNew->pBt);
145     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
146     sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
147   }
148   aNew->zName = sqlite3DbStrDup(db, zName);
149   aNew->safety_level = 3;
150 
151 #if SQLITE_HAS_CODEC
152   if( rc==SQLITE_OK ){
153     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
154     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
155     int nKey;
156     char *zKey;
157     int t = sqlite3_value_type(argv[2]);
158     switch( t ){
159       case SQLITE_INTEGER:
160       case SQLITE_FLOAT:
161         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
162         rc = SQLITE_ERROR;
163         break;
164 
165       case SQLITE_TEXT:
166       case SQLITE_BLOB:
167         nKey = sqlite3_value_bytes(argv[2]);
168         zKey = (char *)sqlite3_value_blob(argv[2]);
169         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
170         break;
171 
172       case SQLITE_NULL:
173         /* No key specified.  Use the key from the main database */
174         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
175         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
176         break;
177     }
178   }
179 #endif
180 
181   /* If the file was opened successfully, read the schema for the new database.
182   ** If this fails, or if opening the file failed, then close the file and
183   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
184   ** we found it.
185   */
186   if( rc==SQLITE_OK ){
187     (void)sqlite3SafetyOn(db);
188     sqlite3BtreeEnterAll(db);
189     rc = sqlite3Init(db, &zErrDyn);
190     sqlite3BtreeLeaveAll(db);
191     (void)sqlite3SafetyOff(db);
192   }
193   if( rc ){
194     int iDb = db->nDb - 1;
195     assert( iDb>=2 );
196     if( db->aDb[iDb].pBt ){
197       sqlite3BtreeClose(db->aDb[iDb].pBt);
198       db->aDb[iDb].pBt = 0;
199       db->aDb[iDb].pSchema = 0;
200     }
201     sqlite3ResetInternalSchema(db, 0);
202     db->nDb = iDb;
203     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
204       db->mallocFailed = 1;
205       sqlite3DbFree(db, zErrDyn);
206       zErrDyn = sqlite3MPrintf(db, "out of memory");
207     }else if( zErrDyn==0 ){
208       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
209     }
210     goto attach_error;
211   }
212 
213   return;
214 
215 attach_error:
216   /* Return an error if we get here */
217   if( zErrDyn ){
218     sqlite3_result_error(context, zErrDyn, -1);
219     sqlite3DbFree(db, zErrDyn);
220   }
221   if( rc ) sqlite3_result_error_code(context, rc);
222 }
223 
224 /*
225 ** An SQL user-function registered to do the work of an DETACH statement. The
226 ** three arguments to the function come directly from a detach statement:
227 **
228 **     DETACH DATABASE x
229 **
230 **     SELECT sqlite_detach(x)
231 */
232 static void detachFunc(
233   sqlite3_context *context,
234   int NotUsed,
235   sqlite3_value **argv
236 ){
237   const char *zName = (const char *)sqlite3_value_text(argv[0]);
238   sqlite3 *db = sqlite3_context_db_handle(context);
239   int i;
240   Db *pDb = 0;
241   char zErr[128];
242 
243   UNUSED_PARAMETER(NotUsed);
244 
245   if( zName==0 ) zName = "";
246   for(i=0; i<db->nDb; i++){
247     pDb = &db->aDb[i];
248     if( pDb->pBt==0 ) continue;
249     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
250   }
251 
252   if( i>=db->nDb ){
253     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
254     goto detach_error;
255   }
256   if( i<2 ){
257     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
258     goto detach_error;
259   }
260   if( !db->autoCommit ){
261     sqlite3_snprintf(sizeof(zErr), zErr,
262                      "cannot DETACH database within transaction");
263     goto detach_error;
264   }
265   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
266     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
267     goto detach_error;
268   }
269 
270   sqlite3BtreeClose(pDb->pBt);
271   pDb->pBt = 0;
272   pDb->pSchema = 0;
273   sqlite3ResetInternalSchema(db, 0);
274   return;
275 
276 detach_error:
277   sqlite3_result_error(context, zErr, -1);
278 }
279 
280 /*
281 ** This procedure generates VDBE code for a single invocation of either the
282 ** sqlite_detach() or sqlite_attach() SQL user functions.
283 */
284 static void codeAttach(
285   Parse *pParse,       /* The parser context */
286   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
287   FuncDef *pFunc,      /* FuncDef wrapper for detachFunc() or attachFunc() */
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 */
292 ){
293   int rc;
294   NameContext sName;
295   Vdbe *v;
296   sqlite3* db = pParse->db;
297   int regArgs;
298 
299   memset(&sName, 0, sizeof(NameContext));
300   sName.pParse = pParse;
301 
302   if(
303       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
304       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
305       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
306   ){
307     pParse->nErr++;
308     goto attach_end;
309   }
310 
311 #ifndef SQLITE_OMIT_AUTHORIZATION
312   if( pAuthArg ){
313     char *zAuthArg = pAuthArg->u.zToken;
314     if( NEVER(zAuthArg==0) ){
315       goto attach_end;
316     }
317     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
318     if(rc!=SQLITE_OK ){
319       goto attach_end;
320     }
321   }
322 #endif /* SQLITE_OMIT_AUTHORIZATION */
323 
324 
325   v = sqlite3GetVdbe(pParse);
326   regArgs = sqlite3GetTempRange(pParse, 4);
327   sqlite3ExprCode(pParse, pFilename, regArgs);
328   sqlite3ExprCode(pParse, pDbname, regArgs+1);
329   sqlite3ExprCode(pParse, pKey, regArgs+2);
330 
331   assert( v || db->mallocFailed );
332   if( v ){
333     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
334     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
335     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
336     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
337 
338     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
339     ** statement only). For DETACH, set it to false (expire all existing
340     ** statements).
341     */
342     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
343   }
344 
345 attach_end:
346   sqlite3ExprDelete(db, pFilename);
347   sqlite3ExprDelete(db, pDbname);
348   sqlite3ExprDelete(db, pKey);
349 }
350 
351 /*
352 ** Called by the parser to compile a DETACH statement.
353 **
354 **     DETACH pDbname
355 */
356 void sqlite3Detach(Parse *pParse, Expr *pDbname){
357   static FuncDef detach_func = {
358     1,                /* nArg */
359     SQLITE_UTF8,      /* iPrefEnc */
360     0,                /* flags */
361     0,                /* pUserData */
362     0,                /* pNext */
363     detachFunc,       /* xFunc */
364     0,                /* xStep */
365     0,                /* xFinalize */
366     "sqlite_detach",  /* zName */
367     0                 /* pHash */
368   };
369   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
370 }
371 
372 /*
373 ** Called by the parser to compile an ATTACH statement.
374 **
375 **     ATTACH p AS pDbname KEY pKey
376 */
377 void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
378   static FuncDef attach_func = {
379     3,                /* nArg */
380     SQLITE_UTF8,      /* iPrefEnc */
381     0,                /* flags */
382     0,                /* pUserData */
383     0,                /* pNext */
384     attachFunc,       /* xFunc */
385     0,                /* xStep */
386     0,                /* xFinalize */
387     "sqlite_attach",  /* zName */
388     0                 /* pHash */
389   };
390   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
391 }
392 #endif /* SQLITE_OMIT_ATTACH */
393 
394 /*
395 ** Initialize a DbFixer structure.  This routine must be called prior
396 ** to passing the structure to one of the sqliteFixAAAA() routines below.
397 **
398 ** The return value indicates whether or not fixation is required.  TRUE
399 ** means we do need to fix the database references, FALSE means we do not.
400 */
401 int sqlite3FixInit(
402   DbFixer *pFix,      /* The fixer to be initialized */
403   Parse *pParse,      /* Error messages will be written here */
404   int iDb,            /* This is the database that must be used */
405   const char *zType,  /* "view", "trigger", or "index" */
406   const Token *pName  /* Name of the view, trigger, or index */
407 ){
408   sqlite3 *db;
409 
410   if( NEVER(iDb<0) || iDb==1 ) return 0;
411   db = pParse->db;
412   assert( db->nDb>iDb );
413   pFix->pParse = pParse;
414   pFix->zDb = db->aDb[iDb].zName;
415   pFix->zType = zType;
416   pFix->pName = pName;
417   return 1;
418 }
419 
420 /*
421 ** The following set of routines walk through the parse tree and assign
422 ** a specific database to all table references where the database name
423 ** was left unspecified in the original SQL statement.  The pFix structure
424 ** must have been initialized by a prior call to sqlite3FixInit().
425 **
426 ** These routines are used to make sure that an index, trigger, or
427 ** view in one database does not refer to objects in a different database.
428 ** (Exception: indices, triggers, and views in the TEMP database are
429 ** allowed to refer to anything.)  If a reference is explicitly made
430 ** to an object in a different database, an error message is added to
431 ** pParse->zErrMsg and these routines return non-zero.  If everything
432 ** checks out, these routines return 0.
433 */
434 int sqlite3FixSrcList(
435   DbFixer *pFix,       /* Context of the fixation */
436   SrcList *pList       /* The Source list to check and modify */
437 ){
438   int i;
439   const char *zDb;
440   struct SrcList_item *pItem;
441 
442   if( NEVER(pList==0) ) return 0;
443   zDb = pFix->zDb;
444   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
445     if( pItem->zDatabase==0 ){
446       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
447     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
448       sqlite3ErrorMsg(pFix->pParse,
449          "%s %T cannot reference objects in database %s",
450          pFix->zType, pFix->pName, pItem->zDatabase);
451       return 1;
452     }
453 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
454     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
455     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
456 #endif
457   }
458   return 0;
459 }
460 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
461 int sqlite3FixSelect(
462   DbFixer *pFix,       /* Context of the fixation */
463   Select *pSelect      /* The SELECT statement to be fixed to one database */
464 ){
465   while( pSelect ){
466     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
467       return 1;
468     }
469     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
470       return 1;
471     }
472     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
473       return 1;
474     }
475     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
476       return 1;
477     }
478     pSelect = pSelect->pPrior;
479   }
480   return 0;
481 }
482 int sqlite3FixExpr(
483   DbFixer *pFix,     /* Context of the fixation */
484   Expr *pExpr        /* The expression to be fixed to one database */
485 ){
486   while( pExpr ){
487     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
488     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
489       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
490     }else{
491       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
492     }
493     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
494       return 1;
495     }
496     pExpr = pExpr->pLeft;
497   }
498   return 0;
499 }
500 int sqlite3FixExprList(
501   DbFixer *pFix,     /* Context of the fixation */
502   ExprList *pList    /* The expression to be fixed to one database */
503 ){
504   int i;
505   struct ExprList_item *pItem;
506   if( pList==0 ) return 0;
507   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
508     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
509       return 1;
510     }
511   }
512   return 0;
513 }
514 #endif
515 
516 #ifndef SQLITE_OMIT_TRIGGER
517 int sqlite3FixTriggerStep(
518   DbFixer *pFix,     /* Context of the fixation */
519   TriggerStep *pStep /* The trigger step be fixed to one database */
520 ){
521   while( pStep ){
522     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
523       return 1;
524     }
525     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
526       return 1;
527     }
528     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
529       return 1;
530     }
531     pStep = pStep->pNext;
532   }
533   return 0;
534 }
535 #endif
536