4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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.
11 *************************************************************************
12 ** This file contains code used to implement the ATTACH and DETACH commands.
14 #include "sqliteInt.h"
16 #ifndef SQLITE_OMIT_ATTACH
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.
22 ** i.e. if the parser sees:
24 ** ATTACH DATABASE abc AS def
26 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
27 ** looking for columns of the same name.
29 ** This only applies to the root node of pExpr, so the statement:
31 ** ATTACH DATABASE abc||def AS 'db2'
33 ** will fail because neither abc or def can be resolved.
35 static int resolveAttachExpr(NameContext
*pName
, Expr
*pExpr
)
39 if( pExpr
->op
!=TK_ID
){
40 rc
= sqlite3ResolveExprNames(pName
, pExpr
);
42 pExpr
->op
= TK_STRING
;
49 ** An SQL user-function registered to do the work of an ATTACH statement. The
50 ** three arguments to the function come directly from an attach statement:
52 ** ATTACH DATABASE x AS y KEY z
54 ** SELECT sqlite_attach(x, y, z)
56 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
59 static void attachFunc(
60 sqlite3_context
*context
,
66 sqlite3
*db
= sqlite3_context_db_handle(context
);
72 Db
*aNew
; /* New array of Db pointers */
73 Db
*pNew
; /* Db object for the newly attached database */
77 UNUSED_PARAMETER(NotUsed
);
79 zFile
= (const char *)sqlite3_value_text(argv
[0]);
80 zName
= (const char *)sqlite3_value_text(argv
[1]);
81 if( zFile
==0 ) zFile
= "";
82 if( zName
==0 ) zName
= "";
84 /* Check for the following errors:
86 ** * Too many attached databases,
87 ** * Transaction currently open
88 ** * Specified database name already being used.
90 if( db
->nDb
>=db
->aLimit
[SQLITE_LIMIT_ATTACHED
]+2 ){
91 zErrDyn
= sqlite3MPrintf(db
, "too many attached databases - max %d",
92 db
->aLimit
[SQLITE_LIMIT_ATTACHED
]
96 for(i
=0; i
<db
->nDb
; i
++){
97 char *z
= db
->aDb
[i
].zDbSName
;
99 if( sqlite3StrICmp(z
, zName
)==0 ){
100 zErrDyn
= sqlite3MPrintf(db
, "database %s is already in use", zName
);
105 /* Allocate the new entry in the db->aDb[] array and initialize the schema
108 if( db
->aDb
==db
->aDbStatic
){
109 aNew
= sqlite3DbMallocRawNN(db
, sizeof(db
->aDb
[0])*3 );
110 if( aNew
==0 ) return;
111 memcpy(aNew
, db
->aDb
, sizeof(db
->aDb
[0])*2);
113 aNew
= sqlite3DbRealloc(db
, db
->aDb
, sizeof(db
->aDb
[0])*(db
->nDb
+1) );
114 if( aNew
==0 ) return;
117 pNew
= &db
->aDb
[db
->nDb
];
118 memset(pNew
, 0, sizeof(*pNew
));
120 /* Open the database file. If the btree is successfully opened, use
121 ** it to obtain the database schema. At this point the schema may
122 ** or may not be initialized.
124 flags
= db
->openFlags
;
125 rc
= sqlite3ParseUri(db
->pVfs
->zName
, zFile
, &flags
, &pVfs
, &zPath
, &zErr
);
127 if( rc
==SQLITE_NOMEM
) sqlite3OomFault(db
);
128 sqlite3_result_error(context
, zErr
, -1);
133 flags
|= SQLITE_OPEN_MAIN_DB
;
134 rc
= sqlite3BtreeOpen(pVfs
, zPath
, db
, &pNew
->pBt
, 0, flags
);
135 sqlite3_free( zPath
);
137 db
->skipBtreeMutex
= 0;
138 if( rc
==SQLITE_CONSTRAINT
){
140 zErrDyn
= sqlite3MPrintf(db
, "database is already attached");
141 }else if( rc
==SQLITE_OK
){
143 pNew
->pSchema
= sqlite3SchemaGet(db
, pNew
->pBt
);
144 if( !pNew
->pSchema
){
145 rc
= SQLITE_NOMEM_BKPT
;
146 }else if( pNew
->pSchema
->file_format
&& pNew
->pSchema
->enc
!=ENC(db
) ){
147 zErrDyn
= sqlite3MPrintf(db
,
148 "attached databases must use the same text encoding as main database");
151 sqlite3BtreeEnter(pNew
->pBt
);
152 pPager
= sqlite3BtreePager(pNew
->pBt
);
153 sqlite3PagerLockingMode(pPager
, db
->dfltLockMode
);
154 sqlite3BtreeSecureDelete(pNew
->pBt
,
155 sqlite3BtreeSecureDelete(db
->aDb
[0].pBt
,-1) );
156 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
157 sqlite3BtreeSetPagerFlags(pNew
->pBt
,
158 PAGER_SYNCHRONOUS_FULL
| (db
->flags
& PAGER_FLAGS_MASK
));
160 sqlite3BtreeLeave(pNew
->pBt
);
162 pNew
->safety_level
= SQLITE_DEFAULT_SYNCHRONOUS
+1;
163 pNew
->zDbSName
= sqlite3DbStrDup(db
, zName
);
164 if( rc
==SQLITE_OK
&& pNew
->zDbSName
==0 ){
165 rc
= SQLITE_NOMEM_BKPT
;
169 #ifdef SQLITE_HAS_CODEC
171 extern int sqlite3CodecAttach(sqlite3
*, int, const void*, int);
172 extern void sqlite3CodecGetKey(sqlite3
*, int, void**, int*);
175 int t
= sqlite3_value_type(argv
[2]);
179 zErrDyn
= sqlite3DbStrDup(db
, "Invalid key value");
185 nKey
= sqlite3_value_bytes(argv
[2]);
186 zKey
= (char *)sqlite3_value_blob(argv
[2]);
187 rc
= sqlite3CodecAttach(db
, db
->nDb
-1, zKey
, nKey
);
191 /* No key specified. Use the key from the main database */
192 sqlite3CodecGetKey(db
, 0, (void**)&zKey
, &nKey
);
193 if( nKey
|| sqlite3BtreeGetOptimalReserve(db
->aDb
[0].pBt
)>0 ){
194 rc
= sqlite3CodecAttach(db
, db
->nDb
-1, zKey
, nKey
);
201 /* If the file was opened successfully, read the schema for the new database.
202 ** If this fails, or if opening the file failed, then close the file and
203 ** remove the entry from the db->aDb[] array. i.e. put everything back the way
207 sqlite3BtreeEnterAll(db
);
208 rc
= sqlite3Init(db
, &zErrDyn
);
209 sqlite3BtreeLeaveAll(db
);
211 #ifdef SQLITE_USER_AUTHENTICATION
214 rc
= sqlite3UserAuthCheckLogin(db
, zName
, &newAuth
);
215 if( newAuth
<db
->auth
.authLevel
){
216 rc
= SQLITE_AUTH_USER
;
221 int iDb
= db
->nDb
- 1;
223 if( db
->aDb
[iDb
].pBt
){
224 sqlite3BtreeClose(db
->aDb
[iDb
].pBt
);
225 db
->aDb
[iDb
].pBt
= 0;
226 db
->aDb
[iDb
].pSchema
= 0;
228 sqlite3ResetAllSchemasOfConnection(db
);
230 if( rc
==SQLITE_NOMEM
|| rc
==SQLITE_IOERR_NOMEM
){
232 sqlite3DbFree(db
, zErrDyn
);
233 zErrDyn
= sqlite3MPrintf(db
, "out of memory");
234 }else if( zErrDyn
==0 ){
235 zErrDyn
= sqlite3MPrintf(db
, "unable to open database: %s", zFile
);
243 /* Return an error if we get here */
245 sqlite3_result_error(context
, zErrDyn
, -1);
246 sqlite3DbFree(db
, zErrDyn
);
248 if( rc
) sqlite3_result_error_code(context
, rc
);
252 ** An SQL user-function registered to do the work of an DETACH statement. The
253 ** three arguments to the function come directly from a detach statement:
257 ** SELECT sqlite_detach(x)
259 static void detachFunc(
260 sqlite3_context
*context
,
264 const char *zName
= (const char *)sqlite3_value_text(argv
[0]);
265 sqlite3
*db
= sqlite3_context_db_handle(context
);
270 UNUSED_PARAMETER(NotUsed
);
272 if( zName
==0 ) zName
= "";
273 for(i
=0; i
<db
->nDb
; i
++){
275 if( pDb
->pBt
==0 ) continue;
276 if( sqlite3StrICmp(pDb
->zDbSName
, zName
)==0 ) break;
280 sqlite3_snprintf(sizeof(zErr
),zErr
, "no such database: %s", zName
);
284 sqlite3_snprintf(sizeof(zErr
),zErr
, "cannot detach database %s", zName
);
287 if( sqlite3BtreeIsInReadTrans(pDb
->pBt
) || sqlite3BtreeIsInBackup(pDb
->pBt
) ){
288 sqlite3_snprintf(sizeof(zErr
),zErr
, "database %s is locked", zName
);
292 sqlite3BtreeClose(pDb
->pBt
);
295 sqlite3CollapseDatabaseArray(db
);
299 sqlite3_result_error(context
, zErr
, -1);
303 ** This procedure generates VDBE code for a single invocation of either the
304 ** sqlite_detach() or sqlite_attach() SQL user functions.
306 static void codeAttach(
307 Parse
*pParse
, /* The parser context */
308 int type
, /* Either SQLITE_ATTACH or SQLITE_DETACH */
309 FuncDef
const *pFunc
,/* FuncDef wrapper for detachFunc() or attachFunc() */
310 Expr
*pAuthArg
, /* Expression to pass to authorization callback */
311 Expr
*pFilename
, /* Name of database file */
312 Expr
*pDbname
, /* Name of the database to use internally */
313 Expr
*pKey
/* Database key for encryption extension */
318 sqlite3
* db
= pParse
->db
;
321 if( pParse
->nErr
) goto attach_end
;
322 memset(&sName
, 0, sizeof(NameContext
));
323 sName
.pParse
= pParse
;
326 SQLITE_OK
!=(rc
= resolveAttachExpr(&sName
, pFilename
)) ||
327 SQLITE_OK
!=(rc
= resolveAttachExpr(&sName
, pDbname
)) ||
328 SQLITE_OK
!=(rc
= resolveAttachExpr(&sName
, pKey
))
333 #ifndef SQLITE_OMIT_AUTHORIZATION
336 if( pAuthArg
->op
==TK_STRING
){
337 zAuthArg
= pAuthArg
->u
.zToken
;
341 rc
= sqlite3AuthCheck(pParse
, type
, zAuthArg
, 0, 0);
346 #endif /* SQLITE_OMIT_AUTHORIZATION */
349 v
= sqlite3GetVdbe(pParse
);
350 regArgs
= sqlite3GetTempRange(pParse
, 4);
351 sqlite3ExprCode(pParse
, pFilename
, regArgs
);
352 sqlite3ExprCode(pParse
, pDbname
, regArgs
+1);
353 sqlite3ExprCode(pParse
, pKey
, regArgs
+2);
355 assert( v
|| db
->mallocFailed
);
357 sqlite3VdbeAddOp4(v
, OP_Function0
, 0, regArgs
+3-pFunc
->nArg
, regArgs
+3,
358 (char *)pFunc
, P4_FUNCDEF
);
359 assert( pFunc
->nArg
==-1 || (pFunc
->nArg
&0xff)==pFunc
->nArg
);
360 sqlite3VdbeChangeP5(v
, (u8
)(pFunc
->nArg
));
362 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
363 ** statement only). For DETACH, set it to false (expire all existing
366 sqlite3VdbeAddOp1(v
, OP_Expire
, (type
==SQLITE_ATTACH
));
370 sqlite3ExprDelete(db
, pFilename
);
371 sqlite3ExprDelete(db
, pDbname
);
372 sqlite3ExprDelete(db
, pKey
);
376 ** Called by the parser to compile a DETACH statement.
380 void sqlite3Detach(Parse
*pParse
, Expr
*pDbname
){
381 static const FuncDef detach_func
= {
383 SQLITE_UTF8
, /* funcFlags */
386 detachFunc
, /* xSFunc */
388 "sqlite_detach", /* zName */
391 codeAttach(pParse
, SQLITE_DETACH
, &detach_func
, pDbname
, 0, 0, pDbname
);
395 ** Called by the parser to compile an ATTACH statement.
397 ** ATTACH p AS pDbname KEY pKey
399 void sqlite3Attach(Parse
*pParse
, Expr
*p
, Expr
*pDbname
, Expr
*pKey
){
400 static const FuncDef attach_func
= {
402 SQLITE_UTF8
, /* funcFlags */
405 attachFunc
, /* xSFunc */
407 "sqlite_attach", /* zName */
410 codeAttach(pParse
, SQLITE_ATTACH
, &attach_func
, p
, p
, pDbname
, pKey
);
412 #endif /* SQLITE_OMIT_ATTACH */
415 ** Initialize a DbFixer structure. This routine must be called prior
416 ** to passing the structure to one of the sqliteFixAAAA() routines below.
419 DbFixer
*pFix
, /* The fixer to be initialized */
420 Parse
*pParse
, /* Error messages will be written here */
421 int iDb
, /* This is the database that must be used */
422 const char *zType
, /* "view", "trigger", or "index" */
423 const Token
*pName
/* Name of the view, trigger, or index */
428 assert( db
->nDb
>iDb
);
429 pFix
->pParse
= pParse
;
430 pFix
->zDb
= db
->aDb
[iDb
].zDbSName
;
431 pFix
->pSchema
= db
->aDb
[iDb
].pSchema
;
434 pFix
->bVarOnly
= (iDb
==1);
438 ** The following set of routines walk through the parse tree and assign
439 ** a specific database to all table references where the database name
440 ** was left unspecified in the original SQL statement. The pFix structure
441 ** must have been initialized by a prior call to sqlite3FixInit().
443 ** These routines are used to make sure that an index, trigger, or
444 ** view in one database does not refer to objects in a different database.
445 ** (Exception: indices, triggers, and views in the TEMP database are
446 ** allowed to refer to anything.) If a reference is explicitly made
447 ** to an object in a different database, an error message is added to
448 ** pParse->zErrMsg and these routines return non-zero. If everything
449 ** checks out, these routines return 0.
451 int sqlite3FixSrcList(
452 DbFixer
*pFix
, /* Context of the fixation */
453 SrcList
*pList
/* The Source list to check and modify */
457 struct SrcList_item
*pItem
;
459 if( NEVER(pList
==0) ) return 0;
461 for(i
=0, pItem
=pList
->a
; i
<pList
->nSrc
; i
++, pItem
++){
462 if( pFix
->bVarOnly
==0 ){
463 if( pItem
->zDatabase
&& sqlite3StrICmp(pItem
->zDatabase
, zDb
) ){
464 sqlite3ErrorMsg(pFix
->pParse
,
465 "%s %T cannot reference objects in database %s",
466 pFix
->zType
, pFix
->pName
, pItem
->zDatabase
);
469 sqlite3DbFree(pFix
->pParse
->db
, pItem
->zDatabase
);
470 pItem
->zDatabase
= 0;
471 pItem
->pSchema
= pFix
->pSchema
;
473 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
474 if( sqlite3FixSelect(pFix
, pItem
->pSelect
) ) return 1;
475 if( sqlite3FixExpr(pFix
, pItem
->pOn
) ) return 1;
480 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
481 int sqlite3FixSelect(
482 DbFixer
*pFix
, /* Context of the fixation */
483 Select
*pSelect
/* The SELECT statement to be fixed to one database */
486 if( sqlite3FixExprList(pFix
, pSelect
->pEList
) ){
489 if( sqlite3FixSrcList(pFix
, pSelect
->pSrc
) ){
492 if( sqlite3FixExpr(pFix
, pSelect
->pWhere
) ){
495 if( sqlite3FixExprList(pFix
, pSelect
->pGroupBy
) ){
498 if( sqlite3FixExpr(pFix
, pSelect
->pHaving
) ){
501 if( sqlite3FixExprList(pFix
, pSelect
->pOrderBy
) ){
504 if( sqlite3FixExpr(pFix
, pSelect
->pLimit
) ){
507 if( sqlite3FixExpr(pFix
, pSelect
->pOffset
) ){
510 pSelect
= pSelect
->pPrior
;
515 DbFixer
*pFix
, /* Context of the fixation */
516 Expr
*pExpr
/* The expression to be fixed to one database */
519 if( pExpr
->op
==TK_VARIABLE
){
520 if( pFix
->pParse
->db
->init
.busy
){
523 sqlite3ErrorMsg(pFix
->pParse
, "%s cannot use variables", pFix
->zType
);
527 if( ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Leaf
) ) break;
528 if( ExprHasProperty(pExpr
, EP_xIsSelect
) ){
529 if( sqlite3FixSelect(pFix
, pExpr
->x
.pSelect
) ) return 1;
531 if( sqlite3FixExprList(pFix
, pExpr
->x
.pList
) ) return 1;
533 if( sqlite3FixExpr(pFix
, pExpr
->pRight
) ){
536 pExpr
= pExpr
->pLeft
;
540 int sqlite3FixExprList(
541 DbFixer
*pFix
, /* Context of the fixation */
542 ExprList
*pList
/* The expression to be fixed to one database */
545 struct ExprList_item
*pItem
;
546 if( pList
==0 ) return 0;
547 for(i
=0, pItem
=pList
->a
; i
<pList
->nExpr
; i
++, pItem
++){
548 if( sqlite3FixExpr(pFix
, pItem
->pExpr
) ){
556 #ifndef SQLITE_OMIT_TRIGGER
557 int sqlite3FixTriggerStep(
558 DbFixer
*pFix
, /* Context of the fixation */
559 TriggerStep
*pStep
/* The trigger step be fixed to one database */
562 if( sqlite3FixSelect(pFix
, pStep
->pSelect
) ){
565 if( sqlite3FixExpr(pFix
, pStep
->pWhere
) ){
568 if( sqlite3FixExprList(pFix
, pStep
->pExprList
) ){
571 pStep
= pStep
->pNext
;