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