xref: /sqlite-3.40.0/src/attach.c (revision fb32c44e)
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 ** If the db->init.reopenMemdb flags is set, then instead of attaching a
60 ** new database, close the database on db->init.iDb and reopen it as an
61 ** empty MemDB.
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   char *zPath = 0;
74   char *zErr = 0;
75   unsigned int flags;
76   Db *aNew;                 /* New array of Db pointers */
77   Db *pNew;                 /* Db object for the newly attached database */
78   char *zErrDyn = 0;
79   sqlite3_vfs *pVfs;
80 
81   UNUSED_PARAMETER(NotUsed);
82   zFile = (const char *)sqlite3_value_text(argv[0]);
83   zName = (const char *)sqlite3_value_text(argv[1]);
84   if( zFile==0 ) zFile = "";
85   if( zName==0 ) zName = "";
86 
87 #ifdef SQLITE_ENABLE_DESERIALIZE
88 # define REOPEN_AS_MEMDB(db)  (db->init.reopenMemdb)
89 #else
90 # define REOPEN_AS_MEMDB(db)  (0)
91 #endif
92 
93   if( REOPEN_AS_MEMDB(db) ){
94     /* This is not a real ATTACH.  Instead, this routine is being called
95     ** from sqlite3_deserialize() to close database db->init.iDb and
96     ** reopen it as a MemDB */
97     pVfs = sqlite3_vfs_find("memdb");
98     if( pVfs==0 ) return;
99     pNew = &db->aDb[db->init.iDb];
100     if( pNew->pBt ) sqlite3BtreeClose(pNew->pBt);
101     pNew->pBt = 0;
102     pNew->pSchema = 0;
103     rc = sqlite3BtreeOpen(pVfs, "x", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB);
104   }else{
105     /* This is a real ATTACH
106     **
107     ** Check for the following errors:
108     **
109     **     * Too many attached databases,
110     **     * Transaction currently open
111     **     * Specified database name already being used.
112     */
113     if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
114       zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
115         db->aLimit[SQLITE_LIMIT_ATTACHED]
116       );
117       goto attach_error;
118     }
119     for(i=0; i<db->nDb; i++){
120       char *z = db->aDb[i].zDbSName;
121       assert( z && zName );
122       if( sqlite3StrICmp(z, zName)==0 ){
123         zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
124         goto attach_error;
125       }
126     }
127 
128     /* Allocate the new entry in the db->aDb[] array and initialize the schema
129     ** hash tables.
130     */
131     if( db->aDb==db->aDbStatic ){
132       aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
133       if( aNew==0 ) return;
134       memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
135     }else{
136       aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
137       if( aNew==0 ) return;
138     }
139     db->aDb = aNew;
140     pNew = &db->aDb[db->nDb];
141     memset(pNew, 0, sizeof(*pNew));
142 
143     /* Open the database file. If the btree is successfully opened, use
144     ** it to obtain the database schema. At this point the schema may
145     ** or may not be initialized.
146     */
147     flags = db->openFlags;
148     rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
149     if( rc!=SQLITE_OK ){
150       if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
151       sqlite3_result_error(context, zErr, -1);
152       sqlite3_free(zErr);
153       return;
154     }
155     assert( pVfs );
156     flags |= SQLITE_OPEN_MAIN_DB;
157     rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
158     sqlite3_free( zPath );
159     db->nDb++;
160   }
161   db->skipBtreeMutex = 0;
162   if( rc==SQLITE_CONSTRAINT ){
163     rc = SQLITE_ERROR;
164     zErrDyn = sqlite3MPrintf(db, "database is already attached");
165   }else if( rc==SQLITE_OK ){
166     Pager *pPager;
167     pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
168     if( !pNew->pSchema ){
169       rc = SQLITE_NOMEM_BKPT;
170     }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
171       zErrDyn = sqlite3MPrintf(db,
172         "attached databases must use the same text encoding as main database");
173       rc = SQLITE_ERROR;
174     }
175     sqlite3BtreeEnter(pNew->pBt);
176     pPager = sqlite3BtreePager(pNew->pBt);
177     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
178     sqlite3BtreeSecureDelete(pNew->pBt,
179                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
180 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
181     sqlite3BtreeSetPagerFlags(pNew->pBt,
182                       PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
183 #endif
184     sqlite3BtreeLeave(pNew->pBt);
185   }
186   pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
187   if( !REOPEN_AS_MEMDB(db) ) pNew->zDbSName = sqlite3DbStrDup(db, zName);
188   if( rc==SQLITE_OK && pNew->zDbSName==0 ){
189     rc = SQLITE_NOMEM_BKPT;
190   }
191 
192 
193 #ifdef SQLITE_HAS_CODEC
194   if( rc==SQLITE_OK ){
195     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
196     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
197     int nKey;
198     char *zKey;
199     int t = sqlite3_value_type(argv[2]);
200     switch( t ){
201       case SQLITE_INTEGER:
202       case SQLITE_FLOAT:
203         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
204         rc = SQLITE_ERROR;
205         break;
206 
207       case SQLITE_TEXT:
208       case SQLITE_BLOB:
209         nKey = sqlite3_value_bytes(argv[2]);
210         zKey = (char *)sqlite3_value_blob(argv[2]);
211         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
212         break;
213 
214       case SQLITE_NULL:
215         /* No key specified.  Use the key from the main database */
216         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
217         if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
218           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
219         }
220         break;
221     }
222   }
223 #endif
224 
225   /* If the file was opened successfully, read the schema for the new database.
226   ** If this fails, or if opening the file failed, then close the file and
227   ** remove the entry from the db->aDb[] array. i.e. put everything back the
228   ** way we found it.
229   */
230   if( rc==SQLITE_OK ){
231     sqlite3BtreeEnterAll(db);
232     db->init.iDb = 0;
233     rc = sqlite3Init(db, &zErrDyn);
234     sqlite3BtreeLeaveAll(db);
235     assert( zErrDyn==0 || rc!=SQLITE_OK );
236   }
237 #ifdef SQLITE_USER_AUTHENTICATION
238   if( rc==SQLITE_OK ){
239     u8 newAuth = 0;
240     rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
241     if( newAuth<db->auth.authLevel ){
242       rc = SQLITE_AUTH_USER;
243     }
244   }
245 #endif
246   if( rc ){
247     if( !REOPEN_AS_MEMDB(db) ){
248       int iDb = db->nDb - 1;
249       assert( iDb>=2 );
250       if( db->aDb[iDb].pBt ){
251         sqlite3BtreeClose(db->aDb[iDb].pBt);
252         db->aDb[iDb].pBt = 0;
253         db->aDb[iDb].pSchema = 0;
254       }
255       sqlite3ResetAllSchemasOfConnection(db);
256       db->nDb = iDb;
257       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
258         sqlite3OomFault(db);
259         sqlite3DbFree(db, zErrDyn);
260         zErrDyn = sqlite3MPrintf(db, "out of memory");
261       }else if( zErrDyn==0 ){
262         zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
263       }
264     }
265     goto attach_error;
266   }
267 
268   return;
269 
270 attach_error:
271   /* Return an error if we get here */
272   if( zErrDyn ){
273     sqlite3_result_error(context, zErrDyn, -1);
274     sqlite3DbFree(db, zErrDyn);
275   }
276   if( rc ) sqlite3_result_error_code(context, rc);
277 }
278 
279 /*
280 ** An SQL user-function registered to do the work of an DETACH statement. The
281 ** three arguments to the function come directly from a detach statement:
282 **
283 **     DETACH DATABASE x
284 **
285 **     SELECT sqlite_detach(x)
286 */
287 static void detachFunc(
288   sqlite3_context *context,
289   int NotUsed,
290   sqlite3_value **argv
291 ){
292   const char *zName = (const char *)sqlite3_value_text(argv[0]);
293   sqlite3 *db = sqlite3_context_db_handle(context);
294   int i;
295   Db *pDb = 0;
296   char zErr[128];
297 
298   UNUSED_PARAMETER(NotUsed);
299 
300   if( zName==0 ) zName = "";
301   for(i=0; i<db->nDb; i++){
302     pDb = &db->aDb[i];
303     if( pDb->pBt==0 ) continue;
304     if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
305   }
306 
307   if( i>=db->nDb ){
308     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
309     goto detach_error;
310   }
311   if( i<2 ){
312     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
313     goto detach_error;
314   }
315   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
316     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
317     goto detach_error;
318   }
319 
320   sqlite3BtreeClose(pDb->pBt);
321   pDb->pBt = 0;
322   pDb->pSchema = 0;
323   sqlite3CollapseDatabaseArray(db);
324   return;
325 
326 detach_error:
327   sqlite3_result_error(context, zErr, -1);
328 }
329 
330 /*
331 ** This procedure generates VDBE code for a single invocation of either the
332 ** sqlite_detach() or sqlite_attach() SQL user functions.
333 */
334 static void codeAttach(
335   Parse *pParse,       /* The parser context */
336   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
337   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
338   Expr *pAuthArg,      /* Expression to pass to authorization callback */
339   Expr *pFilename,     /* Name of database file */
340   Expr *pDbname,       /* Name of the database to use internally */
341   Expr *pKey           /* Database key for encryption extension */
342 ){
343   int rc;
344   NameContext sName;
345   Vdbe *v;
346   sqlite3* db = pParse->db;
347   int regArgs;
348 
349   if( pParse->nErr ) goto attach_end;
350   memset(&sName, 0, sizeof(NameContext));
351   sName.pParse = pParse;
352 
353   if(
354       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
355       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
356       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
357   ){
358     goto attach_end;
359   }
360 
361 #ifndef SQLITE_OMIT_AUTHORIZATION
362   if( pAuthArg ){
363     char *zAuthArg;
364     if( pAuthArg->op==TK_STRING ){
365       zAuthArg = pAuthArg->u.zToken;
366     }else{
367       zAuthArg = 0;
368     }
369     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
370     if(rc!=SQLITE_OK ){
371       goto attach_end;
372     }
373   }
374 #endif /* SQLITE_OMIT_AUTHORIZATION */
375 
376 
377   v = sqlite3GetVdbe(pParse);
378   regArgs = sqlite3GetTempRange(pParse, 4);
379   sqlite3ExprCode(pParse, pFilename, regArgs);
380   sqlite3ExprCode(pParse, pDbname, regArgs+1);
381   sqlite3ExprCode(pParse, pKey, regArgs+2);
382 
383   assert( v || db->mallocFailed );
384   if( v ){
385     sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
386                       (char *)pFunc, P4_FUNCDEF);
387     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
388     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
389 
390     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
391     ** statement only). For DETACH, set it to false (expire all existing
392     ** statements).
393     */
394     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
395   }
396 
397 attach_end:
398   sqlite3ExprDelete(db, pFilename);
399   sqlite3ExprDelete(db, pDbname);
400   sqlite3ExprDelete(db, pKey);
401 }
402 
403 /*
404 ** Called by the parser to compile a DETACH statement.
405 **
406 **     DETACH pDbname
407 */
408 void sqlite3Detach(Parse *pParse, Expr *pDbname){
409   static const FuncDef detach_func = {
410     1,                /* nArg */
411     SQLITE_UTF8,      /* funcFlags */
412     0,                /* pUserData */
413     0,                /* pNext */
414     detachFunc,       /* xSFunc */
415     0,                /* xFinalize */
416     "sqlite_detach",  /* zName */
417     {0}
418   };
419   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
420 }
421 
422 /*
423 ** Called by the parser to compile an ATTACH statement.
424 **
425 **     ATTACH p AS pDbname KEY pKey
426 */
427 void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
428   static const FuncDef attach_func = {
429     3,                /* nArg */
430     SQLITE_UTF8,      /* funcFlags */
431     0,                /* pUserData */
432     0,                /* pNext */
433     attachFunc,       /* xSFunc */
434     0,                /* xFinalize */
435     "sqlite_attach",  /* zName */
436     {0}
437   };
438   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
439 }
440 #endif /* SQLITE_OMIT_ATTACH */
441 
442 /*
443 ** Initialize a DbFixer structure.  This routine must be called prior
444 ** to passing the structure to one of the sqliteFixAAAA() routines below.
445 */
446 void sqlite3FixInit(
447   DbFixer *pFix,      /* The fixer to be initialized */
448   Parse *pParse,      /* Error messages will be written here */
449   int iDb,            /* This is the database that must be used */
450   const char *zType,  /* "view", "trigger", or "index" */
451   const Token *pName  /* Name of the view, trigger, or index */
452 ){
453   sqlite3 *db;
454 
455   db = pParse->db;
456   assert( db->nDb>iDb );
457   pFix->pParse = pParse;
458   pFix->zDb = db->aDb[iDb].zDbSName;
459   pFix->pSchema = db->aDb[iDb].pSchema;
460   pFix->zType = zType;
461   pFix->pName = pName;
462   pFix->bVarOnly = (iDb==1);
463 }
464 
465 /*
466 ** The following set of routines walk through the parse tree and assign
467 ** a specific database to all table references where the database name
468 ** was left unspecified in the original SQL statement.  The pFix structure
469 ** must have been initialized by a prior call to sqlite3FixInit().
470 **
471 ** These routines are used to make sure that an index, trigger, or
472 ** view in one database does not refer to objects in a different database.
473 ** (Exception: indices, triggers, and views in the TEMP database are
474 ** allowed to refer to anything.)  If a reference is explicitly made
475 ** to an object in a different database, an error message is added to
476 ** pParse->zErrMsg and these routines return non-zero.  If everything
477 ** checks out, these routines return 0.
478 */
479 int sqlite3FixSrcList(
480   DbFixer *pFix,       /* Context of the fixation */
481   SrcList *pList       /* The Source list to check and modify */
482 ){
483   int i;
484   const char *zDb;
485   struct SrcList_item *pItem;
486 
487   if( NEVER(pList==0) ) return 0;
488   zDb = pFix->zDb;
489   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
490     if( pFix->bVarOnly==0 ){
491       if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
492         sqlite3ErrorMsg(pFix->pParse,
493             "%s %T cannot reference objects in database %s",
494             pFix->zType, pFix->pName, pItem->zDatabase);
495         return 1;
496       }
497       sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
498       pItem->zDatabase = 0;
499       pItem->pSchema = pFix->pSchema;
500     }
501 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
502     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
503     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
504 #endif
505     if( pItem->fg.isTabFunc && sqlite3FixExprList(pFix, pItem->u1.pFuncArg) ){
506       return 1;
507     }
508   }
509   return 0;
510 }
511 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
512 int sqlite3FixSelect(
513   DbFixer *pFix,       /* Context of the fixation */
514   Select *pSelect      /* The SELECT statement to be fixed to one database */
515 ){
516   while( pSelect ){
517     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
518       return 1;
519     }
520     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
521       return 1;
522     }
523     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
524       return 1;
525     }
526     if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
527       return 1;
528     }
529     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
530       return 1;
531     }
532     if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
533       return 1;
534     }
535     if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
536       return 1;
537     }
538     if( pSelect->pWith ){
539       int i;
540       for(i=0; i<pSelect->pWith->nCte; i++){
541         if( sqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){
542           return 1;
543         }
544       }
545     }
546     pSelect = pSelect->pPrior;
547   }
548   return 0;
549 }
550 int sqlite3FixExpr(
551   DbFixer *pFix,     /* Context of the fixation */
552   Expr *pExpr        /* The expression to be fixed to one database */
553 ){
554   while( pExpr ){
555     if( pExpr->op==TK_VARIABLE ){
556       if( pFix->pParse->db->init.busy ){
557         pExpr->op = TK_NULL;
558       }else{
559         sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
560         return 1;
561       }
562     }
563     if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
564     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
565       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
566     }else{
567       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
568     }
569     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
570       return 1;
571     }
572     pExpr = pExpr->pLeft;
573   }
574   return 0;
575 }
576 int sqlite3FixExprList(
577   DbFixer *pFix,     /* Context of the fixation */
578   ExprList *pList    /* The expression to be fixed to one database */
579 ){
580   int i;
581   struct ExprList_item *pItem;
582   if( pList==0 ) return 0;
583   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
584     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
585       return 1;
586     }
587   }
588   return 0;
589 }
590 #endif
591 
592 #ifndef SQLITE_OMIT_TRIGGER
593 int sqlite3FixTriggerStep(
594   DbFixer *pFix,     /* Context of the fixation */
595   TriggerStep *pStep /* The trigger step be fixed to one database */
596 ){
597   while( pStep ){
598     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
599       return 1;
600     }
601     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
602       return 1;
603     }
604     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
605       return 1;
606     }
607     pStep = pStep->pNext;
608   }
609   return 0;
610 }
611 #endif
612