xref: /sqlite-3.40.0/src/attach.c (revision 9a243e69)
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     }else{
42       pExpr->op = TK_STRING;
43     }
44   }
45   return rc;
46 }
47 
48 /*
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:
51 **
52 **     ATTACH DATABASE x AS y KEY z
53 **
54 **     SELECT sqlite_attach(x, y, z)
55 **
56 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
57 ** third argument.
58 */
59 static void attachFunc(
60   sqlite3_context *context,
61   int NotUsed,
62   sqlite3_value **argv
63 ){
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;
76 
77   UNUSED_PARAMETER(NotUsed);
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     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
92       db->aLimit[SQLITE_LIMIT_ATTACHED]
93     );
94     goto attach_error;
95   }
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;
102     }
103   }
104 
105   /* Allocate the new entry in the db->aDb[] array and initialize the schema
106   ** hash tables.
107   */
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;
115   }
116   db->aDb = aNew;
117   pNew = &db->aDb[db->nDb];
118   memset(pNew, 0, sizeof(*pNew));
119 
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.
123   */
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;
131   }
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;
150     }
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);
161   }
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;
166   }
167 
168 
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;
182 
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;
189 
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);
195         }
196         break;
197     }
198   }
199 #endif
200 
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.
205   */
206   if( rc==SQLITE_OK ){
207     sqlite3BtreeEnterAll(db);
208     rc = sqlite3Init(db, &zErrDyn);
209     sqlite3BtreeLeaveAll(db);
210   }
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;
217     }
218   }
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;
227     }
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);
236     }
237     goto attach_error;
238   }
239 
240   return;
241 
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);
247   }
248   if( rc ) sqlite3_result_error_code(context, rc);
249 }
250 
251 /*
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:
254 **
255 **     DETACH DATABASE x
256 **
257 **     SELECT sqlite_detach(x)
258 */
259 static void detachFunc(
260   sqlite3_context *context,
261   int NotUsed,
262   sqlite3_value **argv
263 ){
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];
269 
270   UNUSED_PARAMETER(NotUsed);
271 
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;
277   }
278 
279   if( i>=db->nDb ){
280     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
281     goto detach_error;
282   }
283   if( i<2 ){
284     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
285     goto detach_error;
286   }
287   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
288     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
289     goto detach_error;
290   }
291 
292   sqlite3BtreeClose(pDb->pBt);
293   pDb->pBt = 0;
294   pDb->pSchema = 0;
295   sqlite3CollapseDatabaseArray(db);
296   return;
297 
298 detach_error:
299   sqlite3_result_error(context, zErr, -1);
300 }
301 
302 /*
303 ** This procedure generates VDBE code for a single invocation of either the
304 ** sqlite_detach() or sqlite_attach() SQL user functions.
305 */
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 */
314 ){
315   int rc;
316   NameContext sName;
317   Vdbe *v;
318   sqlite3* db = pParse->db;
319   int regArgs;
320 
321   if( pParse->nErr ) goto attach_end;
322   memset(&sName, 0, sizeof(NameContext));
323   sName.pParse = pParse;
324 
325   if(
326       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
327       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
328       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
329   ){
330     goto attach_end;
331   }
332 
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;
340     }
341     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
342     if(rc!=SQLITE_OK ){
343       goto attach_end;
344     }
345   }
346 #endif /* SQLITE_OMIT_AUTHORIZATION */
347 
348 
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);
354 
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));
361 
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).
365     */
366     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
367   }
368 
369 attach_end:
370   sqlite3ExprDelete(db, pFilename);
371   sqlite3ExprDelete(db, pDbname);
372   sqlite3ExprDelete(db, pKey);
373 }
374 
375 /*
376 ** Called by the parser to compile a DETACH statement.
377 **
378 **     DETACH pDbname
379 */
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 */
389     {0}
390   };
391   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
392 }
393 
394 /*
395 ** Called by the parser to compile an ATTACH statement.
396 **
397 **     ATTACH p AS pDbname KEY pKey
398 */
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 */
408     {0}
409   };
410   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
411 }
412 #endif /* SQLITE_OMIT_ATTACH */
413 
414 /*
415 ** Initialize a DbFixer structure.  This routine must be called prior
416 ** to passing the structure to one of the sqliteFixAAAA() routines below.
417 */
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 */
424 ){
425   sqlite3 *db;
426 
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);
435 }
436 
437 /*
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().
442 **
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.
450 */
451 int sqlite3FixSrcList(
452   DbFixer *pFix,       /* Context of the fixation */
453   SrcList *pList       /* The Source list to check and modify */
454 ){
455   int i;
456   const char *zDb;
457   struct SrcList_item *pItem;
458 
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;
468       }
469       sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
470       pItem->zDatabase = 0;
471       pItem->pSchema = pFix->pSchema;
472     }
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
477   }
478   return 0;
479 }
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 */
484 ){
485   while( pSelect ){
486     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
487       return 1;
488     }
489     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
490       return 1;
491     }
492     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
493       return 1;
494     }
495     if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
496       return 1;
497     }
498     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
499       return 1;
500     }
501     if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
502       return 1;
503     }
504     if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
505       return 1;
506     }
507     if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
508       return 1;
509     }
510     pSelect = pSelect->pPrior;
511   }
512   return 0;
513 }
514 int sqlite3FixExpr(
515   DbFixer *pFix,     /* Context of the fixation */
516   Expr *pExpr        /* The expression to be fixed to one database */
517 ){
518   while( pExpr ){
519     if( pExpr->op==TK_VARIABLE ){
520       if( pFix->pParse->db->init.busy ){
521         pExpr->op = TK_NULL;
522       }else{
523         sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
524         return 1;
525       }
526     }
527     if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
528     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
529       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
530     }else{
531       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
532     }
533     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
534       return 1;
535     }
536     pExpr = pExpr->pLeft;
537   }
538   return 0;
539 }
540 int sqlite3FixExprList(
541   DbFixer *pFix,     /* Context of the fixation */
542   ExprList *pList    /* The expression to be fixed to one database */
543 ){
544   int i;
545   struct ExprList_item *pItem;
546   if( pList==0 ) return 0;
547   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
548     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
549       return 1;
550     }
551   }
552   return 0;
553 }
554 #endif
555 
556 #ifndef SQLITE_OMIT_TRIGGER
557 int sqlite3FixTriggerStep(
558   DbFixer *pFix,     /* Context of the fixation */
559   TriggerStep *pStep /* The trigger step be fixed to one database */
560 ){
561   while( pStep ){
562     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
563       return 1;
564     }
565     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
566       return 1;
567     }
568     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
569       return 1;
570     }
571     pStep = pStep->pNext;
572   }
573   return 0;
574 }
575 #endif
576