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