Back to index

lightning-sunbird  0.9+nobinonly
attach.c
Go to the documentation of this file.
00001 /*
00002 ** 2003 April 6
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** This file contains code used to implement the ATTACH and DETACH commands.
00013 **
00014 ** $Id: attach.c,v 1.51 2006/04/10 13:37:47 drh Exp $
00015 */
00016 #include "sqliteInt.h"
00017 
00018 /*
00019 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
00020 ** is slightly different from resolving a normal SQL expression, because simple
00021 ** identifiers are treated as strings, not possible column names or aliases.
00022 **
00023 ** i.e. if the parser sees:
00024 **
00025 **     ATTACH DATABASE abc AS def
00026 **
00027 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
00028 ** looking for columns of the same name.
00029 **
00030 ** This only applies to the root node of pExpr, so the statement:
00031 **
00032 **     ATTACH DATABASE abc||def AS 'db2'
00033 **
00034 ** will fail because neither abc or def can be resolved.
00035 */
00036 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
00037 {
00038   int rc = SQLITE_OK;
00039   if( pExpr ){
00040     if( pExpr->op!=TK_ID ){
00041       rc = sqlite3ExprResolveNames(pName, pExpr);
00042     }else{
00043       pExpr->op = TK_STRING;
00044     }
00045   }
00046   return rc;
00047 }
00048 
00049 /*
00050 ** An SQL user-function registered to do the work of an ATTACH statement. The
00051 ** three arguments to the function come directly from an attach statement:
00052 **
00053 **     ATTACH DATABASE x AS y KEY z
00054 **
00055 **     SELECT sqlite_attach(x, y, z)
00056 **
00057 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
00058 ** third argument.
00059 */
00060 static void attachFunc(
00061   sqlite3_context *context,
00062   int argc,
00063   sqlite3_value **argv
00064 ){
00065   int i;
00066   int rc = 0;
00067   sqlite3 *db = sqlite3_user_data(context);
00068   const char *zName;
00069   const char *zFile;
00070   Db *aNew;
00071   char zErr[128];
00072   char *zErrDyn = 0;
00073 
00074   zFile = (const char *)sqlite3_value_text(argv[0]);
00075   zName = (const char *)sqlite3_value_text(argv[1]);
00076 
00077   /* Check for the following errors:
00078   **
00079   **     * Too many attached databases,
00080   **     * Transaction currently open
00081   **     * Specified database name already being used.
00082   */
00083   if( db->nDb>=MAX_ATTACHED+2 ){
00084     sqlite3_snprintf(
00085       127, zErr, "too many attached databases - max %d", MAX_ATTACHED
00086     );
00087     goto attach_error;
00088   }
00089   if( !db->autoCommit ){
00090     strcpy(zErr, "cannot ATTACH database within transaction");
00091     goto attach_error;
00092   }
00093   for(i=0; i<db->nDb; i++){
00094     char *z = db->aDb[i].zName;
00095     if( z && sqlite3StrICmp(z, zName)==0 ){
00096       sqlite3_snprintf(127, zErr, "database %s is already in use", zName);
00097       goto attach_error;
00098     }
00099   }
00100 
00101   /* Allocate the new entry in the db->aDb[] array and initialise the schema
00102   ** hash tables.
00103   */
00104   if( db->aDb==db->aDbStatic ){
00105     aNew = sqliteMalloc( sizeof(db->aDb[0])*3 );
00106     if( aNew==0 ){
00107       return;
00108     }
00109     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
00110   }else{
00111     aNew = sqliteRealloc(db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
00112     if( aNew==0 ){
00113       return;
00114     } 
00115   }
00116   db->aDb = aNew;
00117   aNew = &db->aDb[db->nDb++];
00118   memset(aNew, 0, sizeof(*aNew));
00119 
00120   /* Open the database file. If the btree is successfully opened, use
00121   ** it to obtain the database schema. At this point the schema may
00122   ** or may not be initialised.
00123   */
00124   rc = sqlite3BtreeFactory(db, zFile, 0, MAX_PAGES, &aNew->pBt);
00125   if( rc==SQLITE_OK ){
00126     aNew->pSchema = sqlite3SchemaGet(aNew->pBt);
00127     if( !aNew->pSchema ){
00128       rc = SQLITE_NOMEM;
00129     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
00130       strcpy(zErr, 
00131         "attached databases must use the same text encoding as main database");
00132       goto attach_error;
00133     }
00134   }
00135   aNew->zName = sqliteStrDup(zName);
00136   aNew->safety_level = 3;
00137 
00138 #if SQLITE_HAS_CODEC
00139   {
00140     extern int sqlite3CodecAttach(sqlite3*, int, void*, int);
00141     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
00142     int nKey;
00143     char *zKey;
00144     int t = sqlite3_value_type(argv[2]);
00145     switch( t ){
00146       case SQLITE_INTEGER:
00147       case SQLITE_FLOAT:
00148         zErrDyn = sqliteStrDup("Invalid key value");
00149         rc = SQLITE_ERROR;
00150         break;
00151         
00152       case SQLITE_TEXT:
00153       case SQLITE_BLOB:
00154         nKey = sqlite3_value_bytes(argv[2]);
00155         zKey = (char *)sqlite3_value_blob(argv[2]);
00156         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
00157         break;
00158 
00159       case SQLITE_NULL:
00160         /* No key specified.  Use the key from the main database */
00161         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
00162         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
00163         break;
00164     }
00165   }
00166 #endif
00167 
00168   /* If the file was opened successfully, read the schema for the new database.
00169   ** If this fails, or if opening the file failed, then close the file and 
00170   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
00171   ** we found it.
00172   */
00173   if( rc==SQLITE_OK ){
00174     sqlite3SafetyOn(db);
00175     rc = sqlite3Init(db, &zErrDyn);
00176     sqlite3SafetyOff(db);
00177   }
00178   if( rc ){
00179     int iDb = db->nDb - 1;
00180     assert( iDb>=2 );
00181     if( db->aDb[iDb].pBt ){
00182       sqlite3BtreeClose(db->aDb[iDb].pBt);
00183       db->aDb[iDb].pBt = 0;
00184       db->aDb[iDb].pSchema = 0;
00185     }
00186     sqlite3ResetInternalSchema(db, 0);
00187     db->nDb = iDb;
00188     if( rc==SQLITE_NOMEM ){
00189       if( !sqlite3MallocFailed() ) sqlite3FailedMalloc();
00190       sqlite3_snprintf(127, zErr, "out of memory");
00191     }else{
00192       sqlite3_snprintf(127, zErr, "unable to open database: %s", zFile);
00193     }
00194     goto attach_error;
00195   }
00196   
00197   return;
00198 
00199 attach_error:
00200   /* Return an error if we get here */
00201   if( zErrDyn ){
00202     sqlite3_result_error(context, zErrDyn, -1);
00203     sqliteFree(zErrDyn);
00204   }else{
00205     zErr[sizeof(zErr)-1] = 0;
00206     sqlite3_result_error(context, zErr, -1);
00207   }
00208 }
00209 
00210 /*
00211 ** An SQL user-function registered to do the work of an DETACH statement. The
00212 ** three arguments to the function come directly from a detach statement:
00213 **
00214 **     DETACH DATABASE x
00215 **
00216 **     SELECT sqlite_detach(x)
00217 */
00218 static void detachFunc(
00219   sqlite3_context *context,
00220   int argc,
00221   sqlite3_value **argv
00222 ){
00223   const char *zName = (const char *)sqlite3_value_text(argv[0]);
00224   sqlite3 *db = sqlite3_user_data(context);
00225   int i;
00226   Db *pDb = 0;
00227   char zErr[128];
00228 
00229   assert(zName);
00230   for(i=0; i<db->nDb; i++){
00231     pDb = &db->aDb[i];
00232     if( pDb->pBt==0 ) continue;
00233     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
00234   }
00235 
00236   if( i>=db->nDb ){
00237     sqlite3_snprintf(sizeof(zErr), zErr, "no such database: %s", zName);
00238     goto detach_error;
00239   }
00240   if( i<2 ){
00241     sqlite3_snprintf(sizeof(zErr), zErr, "cannot detach database %s", zName);
00242     goto detach_error;
00243   }
00244   if( !db->autoCommit ){
00245     strcpy(zErr, "cannot DETACH database within transaction");
00246     goto detach_error;
00247   }
00248 
00249   sqlite3BtreeClose(pDb->pBt);
00250   pDb->pBt = 0;
00251   pDb->pSchema = 0;
00252   sqlite3ResetInternalSchema(db, 0);
00253   return;
00254 
00255 detach_error:
00256   sqlite3_result_error(context, zErr, -1);
00257 }
00258 
00259 /*
00260 ** This procedure generates VDBE code for a single invocation of either the
00261 ** sqlite_detach() or sqlite_attach() SQL user functions.
00262 */
00263 static void codeAttach(
00264   Parse *pParse,       /* The parser context */
00265   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
00266   const char *zFunc,   /* Either "sqlite_attach" or "sqlite_detach */
00267   int nFunc,           /* Number of args to pass to zFunc */
00268   Expr *pAuthArg,      /* Expression to pass to authorization callback */
00269   Expr *pFilename,     /* Name of database file */
00270   Expr *pDbname,       /* Name of the database to use internally */
00271   Expr *pKey           /* Database key for encryption extension */
00272 ){
00273   int rc;
00274   NameContext sName;
00275   Vdbe *v;
00276   FuncDef *pFunc;
00277   sqlite3* db = pParse->db;
00278 
00279 #ifndef SQLITE_OMIT_AUTHORIZATION
00280   assert( sqlite3MallocFailed() || pAuthArg );
00281   if( pAuthArg ){
00282     char *zAuthArg = sqlite3NameFromToken(&pAuthArg->span);
00283     if( !zAuthArg ){
00284       goto attach_end;
00285     }
00286     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
00287     sqliteFree(zAuthArg);
00288     if(rc!=SQLITE_OK ){
00289       goto attach_end;
00290     }
00291   }
00292 #endif /* SQLITE_OMIT_AUTHORIZATION */
00293 
00294   memset(&sName, 0, sizeof(NameContext));
00295   sName.pParse = pParse;
00296 
00297   if( 
00298       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
00299       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
00300       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
00301   ){
00302     pParse->nErr++;
00303     goto attach_end;
00304   }
00305 
00306   v = sqlite3GetVdbe(pParse);
00307   sqlite3ExprCode(pParse, pFilename);
00308   sqlite3ExprCode(pParse, pDbname);
00309   sqlite3ExprCode(pParse, pKey);
00310 
00311   assert( v || sqlite3MallocFailed() );
00312   if( v ){
00313     sqlite3VdbeAddOp(v, OP_Function, 0, nFunc);
00314     pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0);
00315     sqlite3VdbeChangeP3(v, -1, (char *)pFunc, P3_FUNCDEF);
00316 
00317     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
00318     ** statement only). For DETACH, set it to false (expire all existing
00319     ** statements).
00320     */
00321     sqlite3VdbeAddOp(v, OP_Expire, (type==SQLITE_ATTACH), 0);
00322   }
00323   
00324 attach_end:
00325   sqlite3ExprDelete(pFilename);
00326   sqlite3ExprDelete(pDbname);
00327   sqlite3ExprDelete(pKey);
00328 }
00329 
00330 /*
00331 ** Called by the parser to compile a DETACH statement.
00332 **
00333 **     DETACH pDbname
00334 */
00335 void sqlite3Detach(Parse *pParse, Expr *pDbname){
00336   codeAttach(pParse, SQLITE_DETACH, "sqlite_detach", 1, pDbname, 0, 0, pDbname);
00337 }
00338 
00339 /*
00340 ** Called by the parser to compile an ATTACH statement.
00341 **
00342 **     ATTACH p AS pDbname KEY pKey
00343 */
00344 void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
00345   codeAttach(pParse, SQLITE_ATTACH, "sqlite_attach", 3, p, p, pDbname, pKey);
00346 }
00347 
00348 /*
00349 ** Register the functions sqlite_attach and sqlite_detach.
00350 */
00351 void sqlite3AttachFunctions(sqlite3 *db){
00352   static const int enc = SQLITE_UTF8;
00353   sqlite3CreateFunc(db, "sqlite_attach", 3, enc, db, attachFunc, 0, 0);
00354   sqlite3CreateFunc(db, "sqlite_detach", 1, enc, db, detachFunc, 0, 0);
00355 }
00356 
00357 /*
00358 ** Initialize a DbFixer structure.  This routine must be called prior
00359 ** to passing the structure to one of the sqliteFixAAAA() routines below.
00360 **
00361 ** The return value indicates whether or not fixation is required.  TRUE
00362 ** means we do need to fix the database references, FALSE means we do not.
00363 */
00364 int sqlite3FixInit(
00365   DbFixer *pFix,      /* The fixer to be initialized */
00366   Parse *pParse,      /* Error messages will be written here */
00367   int iDb,            /* This is the database that must be used */
00368   const char *zType,  /* "view", "trigger", or "index" */
00369   const Token *pName  /* Name of the view, trigger, or index */
00370 ){
00371   sqlite3 *db;
00372 
00373   if( iDb<0 || iDb==1 ) return 0;
00374   db = pParse->db;
00375   assert( db->nDb>iDb );
00376   pFix->pParse = pParse;
00377   pFix->zDb = db->aDb[iDb].zName;
00378   pFix->zType = zType;
00379   pFix->pName = pName;
00380   return 1;
00381 }
00382 
00383 /*
00384 ** The following set of routines walk through the parse tree and assign
00385 ** a specific database to all table references where the database name
00386 ** was left unspecified in the original SQL statement.  The pFix structure
00387 ** must have been initialized by a prior call to sqlite3FixInit().
00388 **
00389 ** These routines are used to make sure that an index, trigger, or
00390 ** view in one database does not refer to objects in a different database.
00391 ** (Exception: indices, triggers, and views in the TEMP database are
00392 ** allowed to refer to anything.)  If a reference is explicitly made
00393 ** to an object in a different database, an error message is added to
00394 ** pParse->zErrMsg and these routines return non-zero.  If everything
00395 ** checks out, these routines return 0.
00396 */
00397 int sqlite3FixSrcList(
00398   DbFixer *pFix,       /* Context of the fixation */
00399   SrcList *pList       /* The Source list to check and modify */
00400 ){
00401   int i;
00402   const char *zDb;
00403   struct SrcList_item *pItem;
00404 
00405   if( pList==0 ) return 0;
00406   zDb = pFix->zDb;
00407   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
00408     if( pItem->zDatabase==0 ){
00409       pItem->zDatabase = sqliteStrDup(zDb);
00410     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
00411       sqlite3ErrorMsg(pFix->pParse,
00412          "%s %T cannot reference objects in database %s",
00413          pFix->zType, pFix->pName, pItem->zDatabase);
00414       return 1;
00415     }
00416 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
00417     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
00418     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
00419 #endif
00420   }
00421   return 0;
00422 }
00423 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
00424 int sqlite3FixSelect(
00425   DbFixer *pFix,       /* Context of the fixation */
00426   Select *pSelect      /* The SELECT statement to be fixed to one database */
00427 ){
00428   while( pSelect ){
00429     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
00430       return 1;
00431     }
00432     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
00433       return 1;
00434     }
00435     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
00436       return 1;
00437     }
00438     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
00439       return 1;
00440     }
00441     pSelect = pSelect->pPrior;
00442   }
00443   return 0;
00444 }
00445 int sqlite3FixExpr(
00446   DbFixer *pFix,     /* Context of the fixation */
00447   Expr *pExpr        /* The expression to be fixed to one database */
00448 ){
00449   while( pExpr ){
00450     if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
00451       return 1;
00452     }
00453     if( sqlite3FixExprList(pFix, pExpr->pList) ){
00454       return 1;
00455     }
00456     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
00457       return 1;
00458     }
00459     pExpr = pExpr->pLeft;
00460   }
00461   return 0;
00462 }
00463 int sqlite3FixExprList(
00464   DbFixer *pFix,     /* Context of the fixation */
00465   ExprList *pList    /* The expression to be fixed to one database */
00466 ){
00467   int i;
00468   struct ExprList_item *pItem;
00469   if( pList==0 ) return 0;
00470   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
00471     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
00472       return 1;
00473     }
00474   }
00475   return 0;
00476 }
00477 #endif
00478 
00479 #ifndef SQLITE_OMIT_TRIGGER
00480 int sqlite3FixTriggerStep(
00481   DbFixer *pFix,     /* Context of the fixation */
00482   TriggerStep *pStep /* The trigger step be fixed to one database */
00483 ){
00484   while( pStep ){
00485     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
00486       return 1;
00487     }
00488     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
00489       return 1;
00490     }
00491     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
00492       return 1;
00493     }
00494     pStep = pStep->pNext;
00495   }
00496   return 0;
00497 }
00498 #endif