xref: /sqlite-3.40.0/src/attach.c (revision 5665b3ea)
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.60 2007/05/09 20:31:30 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_user_data(context);
73   const char *zName;
74   const char *zFile;
75   Db *aNew;
76   char zErr[128];
77   char *zErrDyn = 0;
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>=SQLITE_MAX_ATTACHED+2 ){
91     sqlite3_snprintf(
92       sizeof(zErr), zErr, "too many attached databases - max %d",
93       SQLITE_MAX_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, "database %s is already in use", zName);
106       goto attach_error;
107     }
108   }
109 
110   /* Allocate the new entry in the db->aDb[] array and initialise the schema
111   ** hash tables.
112   */
113   if( db->aDb==db->aDbStatic ){
114     aNew = sqliteMalloc( sizeof(db->aDb[0])*3 );
115     if( aNew==0 ){
116       return;
117     }
118     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
119   }else{
120     aNew = sqliteRealloc(db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
121     if( aNew==0 ){
122       return;
123     }
124   }
125   db->aDb = aNew;
126   aNew = &db->aDb[db->nDb++];
127   memset(aNew, 0, sizeof(*aNew));
128 
129   /* Open the database file. If the btree is successfully opened, use
130   ** it to obtain the database schema. At this point the schema may
131   ** or may not be initialised.
132   */
133   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE, &aNew->pBt);
134   if( rc==SQLITE_OK ){
135     aNew->pSchema = sqlite3SchemaGet(aNew->pBt);
136     if( !aNew->pSchema ){
137       rc = SQLITE_NOMEM;
138     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
139       sqlite3_snprintf(sizeof(zErr), zErr,
140         "attached databases must use the same text encoding as main database");
141       goto attach_error;
142     }
143     sqlite3PagerLockingMode(sqlite3BtreePager(aNew->pBt), db->dfltLockMode);
144   }
145   aNew->zName = sqliteStrDup(zName);
146   aNew->safety_level = 3;
147 
148 #if SQLITE_HAS_CODEC
149   {
150     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
151     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
152     int nKey;
153     char *zKey;
154     int t = sqlite3_value_type(argv[2]);
155     switch( t ){
156       case SQLITE_INTEGER:
157       case SQLITE_FLOAT:
158         zErrDyn = sqliteStrDup("Invalid key value");
159         rc = SQLITE_ERROR;
160         break;
161 
162       case SQLITE_TEXT:
163       case SQLITE_BLOB:
164         nKey = sqlite3_value_bytes(argv[2]);
165         zKey = (char *)sqlite3_value_blob(argv[2]);
166         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
167         break;
168 
169       case SQLITE_NULL:
170         /* No key specified.  Use the key from the main database */
171         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
172         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
173         break;
174     }
175   }
176 #endif
177 
178   /* If the file was opened successfully, read the schema for the new database.
179   ** If this fails, or if opening the file failed, then close the file and
180   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
181   ** we found it.
182   */
183   if( rc==SQLITE_OK ){
184     sqlite3SafetyOn(db);
185     rc = sqlite3Init(db, &zErrDyn);
186     sqlite3SafetyOff(db);
187   }
188   if( rc ){
189     int iDb = db->nDb - 1;
190     assert( iDb>=2 );
191     if( db->aDb[iDb].pBt ){
192       sqlite3BtreeClose(db->aDb[iDb].pBt);
193       db->aDb[iDb].pBt = 0;
194       db->aDb[iDb].pSchema = 0;
195     }
196     sqlite3ResetInternalSchema(db, 0);
197     db->nDb = iDb;
198     if( rc==SQLITE_NOMEM ){
199       sqlite3FailedMalloc();
200       sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
201     }else{
202       sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
203     }
204     goto attach_error;
205   }
206 
207   return;
208 
209 attach_error:
210   /* Return an error if we get here */
211   if( zErrDyn ){
212     sqlite3_result_error(context, zErrDyn, -1);
213     sqliteFree(zErrDyn);
214   }else{
215     zErr[sizeof(zErr)-1] = 0;
216     sqlite3_result_error(context, zErr, -1);
217   }
218 }
219 
220 /*
221 ** An SQL user-function registered to do the work of an DETACH statement. The
222 ** three arguments to the function come directly from a detach statement:
223 **
224 **     DETACH DATABASE x
225 **
226 **     SELECT sqlite_detach(x)
227 */
228 static void detachFunc(
229   sqlite3_context *context,
230   int argc,
231   sqlite3_value **argv
232 ){
233   const char *zName = (const char *)sqlite3_value_text(argv[0]);
234   sqlite3 *db = sqlite3_user_data(context);
235   int i;
236   Db *pDb = 0;
237   char zErr[128];
238 
239   if( zName==0 ) zName = "";
240   for(i=0; i<db->nDb; i++){
241     pDb = &db->aDb[i];
242     if( pDb->pBt==0 ) continue;
243     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
244   }
245 
246   if( i>=db->nDb ){
247     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
248     goto detach_error;
249   }
250   if( i<2 ){
251     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
252     goto detach_error;
253   }
254   if( !db->autoCommit ){
255     sqlite3_snprintf(sizeof(zErr), zErr,
256                      "cannot DETACH database within transaction");
257     goto detach_error;
258   }
259   if( sqlite3BtreeIsInReadTrans(pDb->pBt) ){
260     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
261     goto detach_error;
262   }
263 
264   sqlite3BtreeClose(pDb->pBt);
265   pDb->pBt = 0;
266   pDb->pSchema = 0;
267   sqlite3ResetInternalSchema(db, 0);
268   return;
269 
270 detach_error:
271   sqlite3_result_error(context, zErr, -1);
272 }
273 
274 /*
275 ** This procedure generates VDBE code for a single invocation of either the
276 ** sqlite_detach() or sqlite_attach() SQL user functions.
277 */
278 static void codeAttach(
279   Parse *pParse,       /* The parser context */
280   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
281   const char *zFunc,   /* Either "sqlite_attach" or "sqlite_detach */
282   int nFunc,           /* Number of args to pass to zFunc */
283   Expr *pAuthArg,      /* Expression to pass to authorization callback */
284   Expr *pFilename,     /* Name of database file */
285   Expr *pDbname,       /* Name of the database to use internally */
286   Expr *pKey           /* Database key for encryption extension */
287 ){
288   int rc;
289   NameContext sName;
290   Vdbe *v;
291   FuncDef *pFunc;
292   sqlite3* db = pParse->db;
293 
294 #ifndef SQLITE_OMIT_AUTHORIZATION
295   assert( sqlite3MallocFailed() || pAuthArg );
296   if( pAuthArg ){
297     char *zAuthArg = sqlite3NameFromToken(&pAuthArg->span);
298     if( !zAuthArg ){
299       goto attach_end;
300     }
301     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
302     sqliteFree(zAuthArg);
303     if(rc!=SQLITE_OK ){
304       goto attach_end;
305     }
306   }
307 #endif /* SQLITE_OMIT_AUTHORIZATION */
308 
309   memset(&sName, 0, sizeof(NameContext));
310   sName.pParse = pParse;
311 
312   if(
313       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
314       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
315       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
316   ){
317     pParse->nErr++;
318     goto attach_end;
319   }
320 
321   v = sqlite3GetVdbe(pParse);
322   sqlite3ExprCode(pParse, pFilename);
323   sqlite3ExprCode(pParse, pDbname);
324   sqlite3ExprCode(pParse, pKey);
325 
326   assert( v || sqlite3MallocFailed() );
327   if( v ){
328     sqlite3VdbeAddOp(v, OP_Function, 0, nFunc);
329     pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0);
330     sqlite3VdbeChangeP3(v, -1, (char *)pFunc, P3_FUNCDEF);
331 
332     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
333     ** statement only). For DETACH, set it to false (expire all existing
334     ** statements).
335     */
336     sqlite3VdbeAddOp(v, OP_Expire, (type==SQLITE_ATTACH), 0);
337   }
338 
339 attach_end:
340   sqlite3ExprDelete(pFilename);
341   sqlite3ExprDelete(pDbname);
342   sqlite3ExprDelete(pKey);
343 }
344 
345 /*
346 ** Called by the parser to compile a DETACH statement.
347 **
348 **     DETACH pDbname
349 */
350 void sqlite3Detach(Parse *pParse, Expr *pDbname){
351   codeAttach(pParse, SQLITE_DETACH, "sqlite_detach", 1, pDbname, 0, 0, pDbname);
352 }
353 
354 /*
355 ** Called by the parser to compile an ATTACH statement.
356 **
357 **     ATTACH p AS pDbname KEY pKey
358 */
359 void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
360   codeAttach(pParse, SQLITE_ATTACH, "sqlite_attach", 3, p, p, pDbname, pKey);
361 }
362 #endif /* SQLITE_OMIT_ATTACH */
363 
364 /*
365 ** Register the functions sqlite_attach and sqlite_detach.
366 */
367 void sqlite3AttachFunctions(sqlite3 *db){
368 #ifndef SQLITE_OMIT_ATTACH
369   static const int enc = SQLITE_UTF8;
370   sqlite3CreateFunc(db, "sqlite_attach", 3, enc, db, attachFunc, 0, 0);
371   sqlite3CreateFunc(db, "sqlite_detach", 1, enc, db, detachFunc, 0, 0);
372 #endif
373 }
374 
375 /*
376 ** Initialize a DbFixer structure.  This routine must be called prior
377 ** to passing the structure to one of the sqliteFixAAAA() routines below.
378 **
379 ** The return value indicates whether or not fixation is required.  TRUE
380 ** means we do need to fix the database references, FALSE means we do not.
381 */
382 int sqlite3FixInit(
383   DbFixer *pFix,      /* The fixer to be initialized */
384   Parse *pParse,      /* Error messages will be written here */
385   int iDb,            /* This is the database that must be used */
386   const char *zType,  /* "view", "trigger", or "index" */
387   const Token *pName  /* Name of the view, trigger, or index */
388 ){
389   sqlite3 *db;
390 
391   if( iDb<0 || iDb==1 ) return 0;
392   db = pParse->db;
393   assert( db->nDb>iDb );
394   pFix->pParse = pParse;
395   pFix->zDb = db->aDb[iDb].zName;
396   pFix->zType = zType;
397   pFix->pName = pName;
398   return 1;
399 }
400 
401 /*
402 ** The following set of routines walk through the parse tree and assign
403 ** a specific database to all table references where the database name
404 ** was left unspecified in the original SQL statement.  The pFix structure
405 ** must have been initialized by a prior call to sqlite3FixInit().
406 **
407 ** These routines are used to make sure that an index, trigger, or
408 ** view in one database does not refer to objects in a different database.
409 ** (Exception: indices, triggers, and views in the TEMP database are
410 ** allowed to refer to anything.)  If a reference is explicitly made
411 ** to an object in a different database, an error message is added to
412 ** pParse->zErrMsg and these routines return non-zero.  If everything
413 ** checks out, these routines return 0.
414 */
415 int sqlite3FixSrcList(
416   DbFixer *pFix,       /* Context of the fixation */
417   SrcList *pList       /* The Source list to check and modify */
418 ){
419   int i;
420   const char *zDb;
421   struct SrcList_item *pItem;
422 
423   if( pList==0 ) return 0;
424   zDb = pFix->zDb;
425   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
426     if( pItem->zDatabase==0 ){
427       pItem->zDatabase = sqliteStrDup(zDb);
428     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
429       sqlite3ErrorMsg(pFix->pParse,
430          "%s %T cannot reference objects in database %s",
431          pFix->zType, pFix->pName, pItem->zDatabase);
432       return 1;
433     }
434 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
435     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
436     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
437 #endif
438   }
439   return 0;
440 }
441 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
442 int sqlite3FixSelect(
443   DbFixer *pFix,       /* Context of the fixation */
444   Select *pSelect      /* The SELECT statement to be fixed to one database */
445 ){
446   while( pSelect ){
447     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
448       return 1;
449     }
450     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
451       return 1;
452     }
453     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
454       return 1;
455     }
456     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
457       return 1;
458     }
459     pSelect = pSelect->pPrior;
460   }
461   return 0;
462 }
463 int sqlite3FixExpr(
464   DbFixer *pFix,     /* Context of the fixation */
465   Expr *pExpr        /* The expression to be fixed to one database */
466 ){
467   while( pExpr ){
468     if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
469       return 1;
470     }
471     if( sqlite3FixExprList(pFix, pExpr->pList) ){
472       return 1;
473     }
474     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
475       return 1;
476     }
477     pExpr = pExpr->pLeft;
478   }
479   return 0;
480 }
481 int sqlite3FixExprList(
482   DbFixer *pFix,     /* Context of the fixation */
483   ExprList *pList    /* The expression to be fixed to one database */
484 ){
485   int i;
486   struct ExprList_item *pItem;
487   if( pList==0 ) return 0;
488   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
489     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
490       return 1;
491     }
492   }
493   return 0;
494 }
495 #endif
496 
497 #ifndef SQLITE_OMIT_TRIGGER
498 int sqlite3FixTriggerStep(
499   DbFixer *pFix,     /* Context of the fixation */
500   TriggerStep *pStep /* The trigger step be fixed to one database */
501 ){
502   while( pStep ){
503     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
504       return 1;
505     }
506     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
507       return 1;
508     }
509     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
510       return 1;
511     }
512     pStep = pStep->pNext;
513   }
514   return 0;
515 }
516 #endif
517