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