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