attach.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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.63 2007/10/03 08:46:44 danielk1977 Exp $
  15. */
  16. #include "sqliteInt.h"
  17. #ifndef SQLITE_OMIT_ATTACH
  18. /*
  19. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  20. ** is slightly different from resolving a normal SQL expression, because simple
  21. ** identifiers are treated as strings, not possible column names or aliases.
  22. **
  23. ** i.e. if the parser sees:
  24. **
  25. ** ATTACH DATABASE abc AS def
  26. **
  27. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  28. ** looking for columns of the same name.
  29. **
  30. ** This only applies to the root node of pExpr, so the statement:
  31. **
  32. ** ATTACH DATABASE abc||def AS 'db2'
  33. **
  34. ** will fail because neither abc or def can be resolved.
  35. */
  36. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  37. {
  38. int rc = SQLITE_OK;
  39. if( pExpr ){
  40. if( pExpr->op!=TK_ID ){
  41. rc = sqlite3ExprResolveNames(pName, pExpr);
  42. if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
  43. sqlite3ErrorMsg(pName->pParse, "invalid name: \"%T\"", &pExpr->span);
  44. return SQLITE_ERROR;
  45. }
  46. }else{
  47. pExpr->op = TK_STRING;
  48. }
  49. }
  50. return rc;
  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 argc,
  66. sqlite3_value **argv
  67. ){
  68. int i;
  69. int rc = 0;
  70. sqlite3 *db = sqlite3_user_data(context);
  71. const char *zName;
  72. const char *zFile;
  73. Db *aNew;
  74. char *zErrDyn = 0;
  75. char zErr[128];
  76. zFile = (const char *)sqlite3_value_text(argv[0]);
  77. zName = (const char *)sqlite3_value_text(argv[1]);
  78. if( zFile==0 ) zFile = "";
  79. if( zName==0 ) zName = "";
  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>=SQLITE_MAX_ATTACHED+2 ){
  87. sqlite3_snprintf(
  88. sizeof(zErr), zErr, "too many attached databases - max %d",
  89. SQLITE_MAX_ATTACHED
  90. );
  91. goto attach_error;
  92. }
  93. if( !db->autoCommit ){
  94. sqlite3_snprintf(sizeof(zErr), zErr,
  95. "cannot ATTACH database within transaction");
  96. goto attach_error;
  97. }
  98. for(i=0; i<db->nDb; i++){
  99. char *z = db->aDb[i].zName;
  100. if( z && zName && sqlite3StrICmp(z, zName)==0 ){
  101. sqlite3_snprintf(sizeof(zErr), zErr,
  102. "database %s is already in use", zName);
  103. goto attach_error;
  104. }
  105. }
  106. /* Allocate the new entry in the db->aDb[] array and initialise the schema
  107. ** hash tables.
  108. */
  109. if( db->aDb==db->aDbStatic ){
  110. aNew = sqlite3_malloc( sizeof(db->aDb[0])*3 );
  111. if( aNew==0 ){
  112. db->mallocFailed = 1;
  113. return;
  114. }
  115. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  116. }else{
  117. aNew = sqlite3_realloc(db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  118. if( aNew==0 ){
  119. db->mallocFailed = 1;
  120. return;
  121. }
  122. }
  123. db->aDb = aNew;
  124. aNew = &db->aDb[db->nDb++];
  125. memset(aNew, 0, sizeof(*aNew));
  126. /* Open the database file. If the btree is successfully opened, use
  127. ** it to obtain the database schema. At this point the schema may
  128. ** or may not be initialised.
  129. */
  130. rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
  131. db->openFlags | SQLITE_OPEN_MAIN_DB,
  132. &aNew->pBt);
  133. if( rc==SQLITE_OK ){
  134. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  135. if( !aNew->pSchema ){
  136. rc = SQLITE_NOMEM;
  137. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  138. sqlite3_snprintf(sizeof(zErr), zErr,
  139. "attached databases must use the same text encoding as main database");
  140. goto attach_error;
  141. }
  142. sqlite3PagerLockingMode(sqlite3BtreePager(aNew->pBt), db->dfltLockMode);
  143. }
  144. aNew->zName = sqlite3DbStrDup(db, zName);
  145. aNew->safety_level = 3;
  146. #if SQLITE_HAS_CODEC
  147. {
  148. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  149. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  150. int nKey;
  151. char *zKey;
  152. int t = sqlite3_value_type(argv[2]);
  153. switch( t ){
  154. case SQLITE_INTEGER:
  155. case SQLITE_FLOAT:
  156. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  157. rc = SQLITE_ERROR;
  158. break;
  159. case SQLITE_TEXT:
  160. case SQLITE_BLOB:
  161. nKey = sqlite3_value_bytes(argv[2]);
  162. zKey = (char *)sqlite3_value_blob(argv[2]);
  163. sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  164. break;
  165. case SQLITE_NULL:
  166. /* No key specified. Use the key from the main database */
  167. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  168. sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  169. break;
  170. }
  171. }
  172. #endif
  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 || rc==SQLITE_IOERR_NOMEM ){
  194. db->mallocFailed = 1;
  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. return;
  202. attach_error:
  203. /* Return an error if we get here */
  204. if( zErrDyn ){
  205. sqlite3_result_error(context, zErrDyn, -1);
  206. sqlite3_free(zErrDyn);
  207. }else{
  208. zErr[sizeof(zErr)-1] = 0;
  209. sqlite3_result_error(context, zErr, -1);
  210. }
  211. }
  212. /*
  213. ** An SQL user-function registered to do the work of an DETACH statement. The
  214. ** three arguments to the function come directly from a detach statement:
  215. **
  216. ** DETACH DATABASE x
  217. **
  218. ** SELECT sqlite_detach(x)
  219. */
  220. static void detachFunc(
  221. sqlite3_context *context,
  222. int argc,
  223. sqlite3_value **argv
  224. ){
  225. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  226. sqlite3 *db = sqlite3_user_data(context);
  227. int i;
  228. Db *pDb = 0;
  229. char zErr[128];
  230. if( zName==0 ) zName = "";
  231. for(i=0; i<db->nDb; i++){
  232. pDb = &db->aDb[i];
  233. if( pDb->pBt==0 ) continue;
  234. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  235. }
  236. if( i>=db->nDb ){
  237. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  238. goto detach_error;
  239. }
  240. if( i<2 ){
  241. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  242. goto detach_error;
  243. }
  244. if( !db->autoCommit ){
  245. sqlite3_snprintf(sizeof(zErr), zErr,
  246. "cannot DETACH database within transaction");
  247. goto detach_error;
  248. }
  249. if( sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  250. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  251. goto detach_error;
  252. }
  253. sqlite3BtreeClose(pDb->pBt);
  254. pDb->pBt = 0;
  255. pDb->pSchema = 0;
  256. sqlite3ResetInternalSchema(db, 0);
  257. return;
  258. detach_error:
  259. sqlite3_result_error(context, zErr, -1);
  260. }
  261. /*
  262. ** This procedure generates VDBE code for a single invocation of either the
  263. ** sqlite_detach() or sqlite_attach() SQL user functions.
  264. */
  265. static void codeAttach(
  266. Parse *pParse, /* The parser context */
  267. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  268. const char *zFunc, /* Either "sqlite_attach" or "sqlite_detach */
  269. int nFunc, /* Number of args to pass to zFunc */
  270. Expr *pAuthArg, /* Expression to pass to authorization callback */
  271. Expr *pFilename, /* Name of database file */
  272. Expr *pDbname, /* Name of the database to use internally */
  273. Expr *pKey /* Database key for encryption extension */
  274. ){
  275. int rc;
  276. NameContext sName;
  277. Vdbe *v;
  278. FuncDef *pFunc;
  279. sqlite3* db = pParse->db;
  280. #ifndef SQLITE_OMIT_AUTHORIZATION
  281. assert( db->mallocFailed || pAuthArg );
  282. if( pAuthArg ){
  283. char *zAuthArg = sqlite3NameFromToken(db, &pAuthArg->span);
  284. if( !zAuthArg ){
  285. goto attach_end;
  286. }
  287. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  288. sqlite3_free(zAuthArg);
  289. if(rc!=SQLITE_OK ){
  290. goto attach_end;
  291. }
  292. }
  293. #endif /* SQLITE_OMIT_AUTHORIZATION */
  294. memset(&sName, 0, sizeof(NameContext));
  295. sName.pParse = pParse;
  296. if(
  297. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  298. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  299. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  300. ){
  301. pParse->nErr++;
  302. goto attach_end;
  303. }
  304. v = sqlite3GetVdbe(pParse);
  305. sqlite3ExprCode(pParse, pFilename);
  306. sqlite3ExprCode(pParse, pDbname);
  307. sqlite3ExprCode(pParse, pKey);
  308. assert( v || db->mallocFailed );
  309. if( v ){
  310. sqlite3VdbeAddOp(v, OP_Function, 0, nFunc);
  311. pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0);
  312. sqlite3VdbeChangeP3(v, -1, (char *)pFunc, P3_FUNCDEF);
  313. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  314. ** statement only). For DETACH, set it to false (expire all existing
  315. ** statements).
  316. */
  317. sqlite3VdbeAddOp(v, OP_Expire, (type==SQLITE_ATTACH), 0);
  318. }
  319. attach_end:
  320. sqlite3ExprDelete(pFilename);
  321. sqlite3ExprDelete(pDbname);
  322. sqlite3ExprDelete(pKey);
  323. }
  324. /*
  325. ** Called by the parser to compile a DETACH statement.
  326. **
  327. ** DETACH pDbname
  328. */
  329. void sqlite3Detach(Parse *pParse, Expr *pDbname){
  330. codeAttach(pParse, SQLITE_DETACH, "sqlite_detach", 1, pDbname, 0, 0, pDbname);
  331. }
  332. /*
  333. ** Called by the parser to compile an ATTACH statement.
  334. **
  335. ** ATTACH p AS pDbname KEY pKey
  336. */
  337. void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  338. codeAttach(pParse, SQLITE_ATTACH, "sqlite_attach", 3, p, p, pDbname, pKey);
  339. }
  340. #endif /* SQLITE_OMIT_ATTACH */
  341. /*
  342. ** Register the functions sqlite_attach and sqlite_detach.
  343. */
  344. void sqlite3AttachFunctions(sqlite3 *db){
  345. #ifndef SQLITE_OMIT_ATTACH
  346. static const int enc = SQLITE_UTF8;
  347. sqlite3CreateFunc(db, "sqlite_attach", 3, enc, db, attachFunc, 0, 0);
  348. sqlite3CreateFunc(db, "sqlite_detach", 1, enc, db, detachFunc, 0, 0);
  349. #endif
  350. }
  351. /*
  352. ** Initialize a DbFixer structure. This routine must be called prior
  353. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  354. **
  355. ** The return value indicates whether or not fixation is required. TRUE
  356. ** means we do need to fix the database references, FALSE means we do not.
  357. */
  358. int sqlite3FixInit(
  359. DbFixer *pFix, /* The fixer to be initialized */
  360. Parse *pParse, /* Error messages will be written here */
  361. int iDb, /* This is the database that must be used */
  362. const char *zType, /* "view", "trigger", or "index" */
  363. const Token *pName /* Name of the view, trigger, or index */
  364. ){
  365. sqlite3 *db;
  366. if( iDb<0 || iDb==1 ) return 0;
  367. db = pParse->db;
  368. assert( db->nDb>iDb );
  369. pFix->pParse = pParse;
  370. pFix->zDb = db->aDb[iDb].zName;
  371. pFix->zType = zType;
  372. pFix->pName = pName;
  373. return 1;
  374. }
  375. /*
  376. ** The following set of routines walk through the parse tree and assign
  377. ** a specific database to all table references where the database name
  378. ** was left unspecified in the original SQL statement. The pFix structure
  379. ** must have been initialized by a prior call to sqlite3FixInit().
  380. **
  381. ** These routines are used to make sure that an index, trigger, or
  382. ** view in one database does not refer to objects in a different database.
  383. ** (Exception: indices, triggers, and views in the TEMP database are
  384. ** allowed to refer to anything.) If a reference is explicitly made
  385. ** to an object in a different database, an error message is added to
  386. ** pParse->zErrMsg and these routines return non-zero. If everything
  387. ** checks out, these routines return 0.
  388. */
  389. int sqlite3FixSrcList(
  390. DbFixer *pFix, /* Context of the fixation */
  391. SrcList *pList /* The Source list to check and modify */
  392. ){
  393. int i;
  394. const char *zDb;
  395. struct SrcList_item *pItem;
  396. if( pList==0 ) return 0;
  397. zDb = pFix->zDb;
  398. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  399. if( pItem->zDatabase==0 ){
  400. pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
  401. }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
  402. sqlite3ErrorMsg(pFix->pParse,
  403. "%s %T cannot reference objects in database %s",
  404. pFix->zType, pFix->pName, pItem->zDatabase);
  405. return 1;
  406. }
  407. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  408. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  409. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  410. #endif
  411. }
  412. return 0;
  413. }
  414. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  415. int sqlite3FixSelect(
  416. DbFixer *pFix, /* Context of the fixation */
  417. Select *pSelect /* The SELECT statement to be fixed to one database */
  418. ){
  419. while( pSelect ){
  420. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  421. return 1;
  422. }
  423. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  424. return 1;
  425. }
  426. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  427. return 1;
  428. }
  429. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  430. return 1;
  431. }
  432. pSelect = pSelect->pPrior;
  433. }
  434. return 0;
  435. }
  436. int sqlite3FixExpr(
  437. DbFixer *pFix, /* Context of the fixation */
  438. Expr *pExpr /* The expression to be fixed to one database */
  439. ){
  440. while( pExpr ){
  441. if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
  442. return 1;
  443. }
  444. if( sqlite3FixExprList(pFix, pExpr->pList) ){
  445. return 1;
  446. }
  447. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  448. return 1;
  449. }
  450. pExpr = pExpr->pLeft;
  451. }
  452. return 0;
  453. }
  454. int sqlite3FixExprList(
  455. DbFixer *pFix, /* Context of the fixation */
  456. ExprList *pList /* The expression to be fixed to one database */
  457. ){
  458. int i;
  459. struct ExprList_item *pItem;
  460. if( pList==0 ) return 0;
  461. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  462. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  463. return 1;
  464. }
  465. }
  466. return 0;
  467. }
  468. #endif
  469. #ifndef SQLITE_OMIT_TRIGGER
  470. int sqlite3FixTriggerStep(
  471. DbFixer *pFix, /* Context of the fixation */
  472. TriggerStep *pStep /* The trigger step be fixed to one database */
  473. ){
  474. while( pStep ){
  475. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  476. return 1;
  477. }
  478. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  479. return 1;
  480. }
  481. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  482. return 1;
  483. }
  484. pStep = pStep->pNext;
  485. }
  486. return 0;
  487. }
  488. #endif