Simplifications to the implementation of the sum() SQL function.
[sqlite.git] / src / attach.c
blob42ae53694269c128cb74cf7153b628edbf3524da
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.
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)
37 int rc = SQLITE_OK;
38 if( pExpr ){
39 if( pExpr->op!=TK_ID ){
40 rc = sqlite3ResolveExprNames(pName, pExpr);
41 }else{
42 pExpr->op = TK_STRING;
45 return rc;
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
57 ** third argument.
59 ** If the db->init.reopenMemdb flags is set, then instead of attaching a
60 ** new database, close the database on db->init.iDb and reopen it as an
61 ** empty MemDB.
63 static void attachFunc(
64 sqlite3_context *context,
65 int NotUsed,
66 sqlite3_value **argv
68 int i;
69 int rc = 0;
70 sqlite3 *db = sqlite3_context_db_handle(context);
71 const char *zName;
72 const char *zFile;
73 char *zPath = 0;
74 char *zErr = 0;
75 unsigned int flags;
76 Db *aNew; /* New array of Db pointers */
77 Db *pNew; /* Db object for the newly attached database */
78 char *zErrDyn = 0;
79 sqlite3_vfs *pVfs;
81 UNUSED_PARAMETER(NotUsed);
82 zFile = (const char *)sqlite3_value_text(argv[0]);
83 zName = (const char *)sqlite3_value_text(argv[1]);
84 if( zFile==0 ) zFile = "";
85 if( zName==0 ) zName = "";
87 #ifdef SQLITE_ENABLE_DESERIALIZE
88 # define REOPEN_AS_MEMDB(db) (db->init.reopenMemdb)
89 #else
90 # define REOPEN_AS_MEMDB(db) (0)
91 #endif
93 if( REOPEN_AS_MEMDB(db) ){
94 /* This is not a real ATTACH. Instead, this routine is being called
95 ** from sqlite3_deserialize() to close database db->init.iDb and
96 ** reopen it as a MemDB */
97 pVfs = sqlite3_vfs_find("memdb");
98 if( pVfs==0 ) return;
99 pNew = &db->aDb[db->init.iDb];
100 if( pNew->pBt ) sqlite3BtreeClose(pNew->pBt);
101 pNew->pBt = 0;
102 pNew->pSchema = 0;
103 rc = sqlite3BtreeOpen(pVfs, "x", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB);
104 }else{
105 /* This is a real ATTACH
107 ** Check for the following errors:
109 ** * Too many attached databases,
110 ** * Transaction currently open
111 ** * Specified database name already being used.
113 if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
114 zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
115 db->aLimit[SQLITE_LIMIT_ATTACHED]
117 goto attach_error;
119 for(i=0; i<db->nDb; i++){
120 char *z = db->aDb[i].zDbSName;
121 assert( z && zName );
122 if( sqlite3StrICmp(z, zName)==0 ){
123 zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
124 goto attach_error;
128 /* Allocate the new entry in the db->aDb[] array and initialize the schema
129 ** hash tables.
131 if( db->aDb==db->aDbStatic ){
132 aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
133 if( aNew==0 ) return;
134 memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
135 }else{
136 aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
137 if( aNew==0 ) return;
139 db->aDb = aNew;
140 pNew = &db->aDb[db->nDb];
141 memset(pNew, 0, sizeof(*pNew));
143 /* Open the database file. If the btree is successfully opened, use
144 ** it to obtain the database schema. At this point the schema may
145 ** or may not be initialized.
147 flags = db->openFlags;
148 rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
149 if( rc!=SQLITE_OK ){
150 if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
151 sqlite3_result_error(context, zErr, -1);
152 sqlite3_free(zErr);
153 return;
155 assert( pVfs );
156 flags |= SQLITE_OPEN_MAIN_DB;
157 rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
158 sqlite3_free( zPath );
159 db->nDb++;
161 db->noSharedCache = 0;
162 if( rc==SQLITE_CONSTRAINT ){
163 rc = SQLITE_ERROR;
164 zErrDyn = sqlite3MPrintf(db, "database is already attached");
165 }else if( rc==SQLITE_OK ){
166 Pager *pPager;
167 pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
168 if( !pNew->pSchema ){
169 rc = SQLITE_NOMEM_BKPT;
170 }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
171 zErrDyn = sqlite3MPrintf(db,
172 "attached databases must use the same text encoding as main database");
173 rc = SQLITE_ERROR;
175 sqlite3BtreeEnter(pNew->pBt);
176 pPager = sqlite3BtreePager(pNew->pBt);
177 sqlite3PagerLockingMode(pPager, db->dfltLockMode);
178 sqlite3BtreeSecureDelete(pNew->pBt,
179 sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
180 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
181 sqlite3BtreeSetPagerFlags(pNew->pBt,
182 PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
183 #endif
184 sqlite3BtreeLeave(pNew->pBt);
186 pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
187 if( !REOPEN_AS_MEMDB(db) ) pNew->zDbSName = sqlite3DbStrDup(db, zName);
188 if( rc==SQLITE_OK && pNew->zDbSName==0 ){
189 rc = SQLITE_NOMEM_BKPT;
193 #ifdef SQLITE_HAS_CODEC
194 if( rc==SQLITE_OK ){
195 extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
196 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
197 int nKey;
198 char *zKey;
199 int t = sqlite3_value_type(argv[2]);
200 switch( t ){
201 case SQLITE_INTEGER:
202 case SQLITE_FLOAT:
203 zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
204 rc = SQLITE_ERROR;
205 break;
207 case SQLITE_TEXT:
208 case SQLITE_BLOB:
209 nKey = sqlite3_value_bytes(argv[2]);
210 zKey = (char *)sqlite3_value_blob(argv[2]);
211 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
212 break;
214 case SQLITE_NULL:
215 /* No key specified. Use the key from the main database */
216 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
217 if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
218 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
220 break;
223 #endif
225 /* If the file was opened successfully, read the schema for the new database.
226 ** If this fails, or if opening the file failed, then close the file and
227 ** remove the entry from the db->aDb[] array. i.e. put everything back the
228 ** way we found it.
230 if( rc==SQLITE_OK ){
231 sqlite3BtreeEnterAll(db);
232 db->init.iDb = 0;
233 db->mDbFlags &= ~(DBFLAG_SchemaKnownOk);
234 rc = sqlite3Init(db, &zErrDyn);
235 sqlite3BtreeLeaveAll(db);
236 assert( zErrDyn==0 || rc!=SQLITE_OK );
238 #ifdef SQLITE_USER_AUTHENTICATION
239 if( rc==SQLITE_OK ){
240 u8 newAuth = 0;
241 rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
242 if( newAuth<db->auth.authLevel ){
243 rc = SQLITE_AUTH_USER;
246 #endif
247 if( rc ){
248 if( !REOPEN_AS_MEMDB(db) ){
249 int iDb = db->nDb - 1;
250 assert( iDb>=2 );
251 if( db->aDb[iDb].pBt ){
252 sqlite3BtreeClose(db->aDb[iDb].pBt);
253 db->aDb[iDb].pBt = 0;
254 db->aDb[iDb].pSchema = 0;
256 sqlite3ResetAllSchemasOfConnection(db);
257 db->nDb = iDb;
258 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
259 sqlite3OomFault(db);
260 sqlite3DbFree(db, zErrDyn);
261 zErrDyn = sqlite3MPrintf(db, "out of memory");
262 }else if( zErrDyn==0 ){
263 zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
266 goto attach_error;
269 return;
271 attach_error:
272 /* Return an error if we get here */
273 if( zErrDyn ){
274 sqlite3_result_error(context, zErrDyn, -1);
275 sqlite3DbFree(db, zErrDyn);
277 if( rc ) sqlite3_result_error_code(context, rc);
281 ** An SQL user-function registered to do the work of an DETACH statement. The
282 ** three arguments to the function come directly from a detach statement:
284 ** DETACH DATABASE x
286 ** SELECT sqlite_detach(x)
288 static void detachFunc(
289 sqlite3_context *context,
290 int NotUsed,
291 sqlite3_value **argv
293 const char *zName = (const char *)sqlite3_value_text(argv[0]);
294 sqlite3 *db = sqlite3_context_db_handle(context);
295 int i;
296 Db *pDb = 0;
297 char zErr[128];
299 UNUSED_PARAMETER(NotUsed);
301 if( zName==0 ) zName = "";
302 for(i=0; i<db->nDb; i++){
303 pDb = &db->aDb[i];
304 if( pDb->pBt==0 ) continue;
305 if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
308 if( i>=db->nDb ){
309 sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
310 goto detach_error;
312 if( i<2 ){
313 sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
314 goto detach_error;
316 if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
317 sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
318 goto detach_error;
321 sqlite3BtreeClose(pDb->pBt);
322 pDb->pBt = 0;
323 pDb->pSchema = 0;
324 sqlite3CollapseDatabaseArray(db);
325 return;
327 detach_error:
328 sqlite3_result_error(context, zErr, -1);
332 ** This procedure generates VDBE code for a single invocation of either the
333 ** sqlite_detach() or sqlite_attach() SQL user functions.
335 static void codeAttach(
336 Parse *pParse, /* The parser context */
337 int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
338 FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
339 Expr *pAuthArg, /* Expression to pass to authorization callback */
340 Expr *pFilename, /* Name of database file */
341 Expr *pDbname, /* Name of the database to use internally */
342 Expr *pKey /* Database key for encryption extension */
344 int rc;
345 NameContext sName;
346 Vdbe *v;
347 sqlite3* db = pParse->db;
348 int regArgs;
350 if( pParse->nErr ) goto attach_end;
351 memset(&sName, 0, sizeof(NameContext));
352 sName.pParse = pParse;
354 if(
355 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
356 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
357 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
359 goto attach_end;
362 #ifndef SQLITE_OMIT_AUTHORIZATION
363 if( pAuthArg ){
364 char *zAuthArg;
365 if( pAuthArg->op==TK_STRING ){
366 zAuthArg = pAuthArg->u.zToken;
367 }else{
368 zAuthArg = 0;
370 rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
371 if(rc!=SQLITE_OK ){
372 goto attach_end;
375 #endif /* SQLITE_OMIT_AUTHORIZATION */
378 v = sqlite3GetVdbe(pParse);
379 regArgs = sqlite3GetTempRange(pParse, 4);
380 sqlite3ExprCode(pParse, pFilename, regArgs);
381 sqlite3ExprCode(pParse, pDbname, regArgs+1);
382 sqlite3ExprCode(pParse, pKey, regArgs+2);
384 assert( v || db->mallocFailed );
385 if( v ){
386 sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
387 (char *)pFunc, P4_FUNCDEF);
388 assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
389 sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
391 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
392 ** statement only). For DETACH, set it to false (expire all existing
393 ** statements).
395 sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
398 attach_end:
399 sqlite3ExprDelete(db, pFilename);
400 sqlite3ExprDelete(db, pDbname);
401 sqlite3ExprDelete(db, pKey);
405 ** Called by the parser to compile a DETACH statement.
407 ** DETACH pDbname
409 void sqlite3Detach(Parse *pParse, Expr *pDbname){
410 static const FuncDef detach_func = {
411 1, /* nArg */
412 SQLITE_UTF8, /* funcFlags */
413 0, /* pUserData */
414 0, /* pNext */
415 detachFunc, /* xSFunc */
416 0, /* xFinalize */
417 0, 0, /* xValue, xInverse */
418 "sqlite_detach", /* zName */
421 codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
425 ** Called by the parser to compile an ATTACH statement.
427 ** ATTACH p AS pDbname KEY pKey
429 void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
430 static const FuncDef attach_func = {
431 3, /* nArg */
432 SQLITE_UTF8, /* funcFlags */
433 0, /* pUserData */
434 0, /* pNext */
435 attachFunc, /* xSFunc */
436 0, /* xFinalize */
437 0, 0, /* xValue, xInverse */
438 "sqlite_attach", /* zName */
441 codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
443 #endif /* SQLITE_OMIT_ATTACH */
446 ** Initialize a DbFixer structure. This routine must be called prior
447 ** to passing the structure to one of the sqliteFixAAAA() routines below.
449 void sqlite3FixInit(
450 DbFixer *pFix, /* The fixer to be initialized */
451 Parse *pParse, /* Error messages will be written here */
452 int iDb, /* This is the database that must be used */
453 const char *zType, /* "view", "trigger", or "index" */
454 const Token *pName /* Name of the view, trigger, or index */
456 sqlite3 *db;
458 db = pParse->db;
459 assert( db->nDb>iDb );
460 pFix->pParse = pParse;
461 pFix->zDb = db->aDb[iDb].zDbSName;
462 pFix->pSchema = db->aDb[iDb].pSchema;
463 pFix->zType = zType;
464 pFix->pName = pName;
465 pFix->bVarOnly = (iDb==1);
469 ** The following set of routines walk through the parse tree and assign
470 ** a specific database to all table references where the database name
471 ** was left unspecified in the original SQL statement. The pFix structure
472 ** must have been initialized by a prior call to sqlite3FixInit().
474 ** These routines are used to make sure that an index, trigger, or
475 ** view in one database does not refer to objects in a different database.
476 ** (Exception: indices, triggers, and views in the TEMP database are
477 ** allowed to refer to anything.) If a reference is explicitly made
478 ** to an object in a different database, an error message is added to
479 ** pParse->zErrMsg and these routines return non-zero. If everything
480 ** checks out, these routines return 0.
482 int sqlite3FixSrcList(
483 DbFixer *pFix, /* Context of the fixation */
484 SrcList *pList /* The Source list to check and modify */
486 int i;
487 const char *zDb;
488 struct SrcList_item *pItem;
490 if( NEVER(pList==0) ) return 0;
491 zDb = pFix->zDb;
492 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
493 if( pFix->bVarOnly==0 ){
494 if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
495 sqlite3ErrorMsg(pFix->pParse,
496 "%s %T cannot reference objects in database %s",
497 pFix->zType, pFix->pName, pItem->zDatabase);
498 return 1;
500 sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
501 pItem->zDatabase = 0;
502 pItem->pSchema = pFix->pSchema;
504 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
505 if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
506 if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
507 #endif
508 if( pItem->fg.isTabFunc && sqlite3FixExprList(pFix, pItem->u1.pFuncArg) ){
509 return 1;
512 return 0;
514 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
515 int sqlite3FixSelect(
516 DbFixer *pFix, /* Context of the fixation */
517 Select *pSelect /* The SELECT statement to be fixed to one database */
519 while( pSelect ){
520 if( sqlite3FixExprList(pFix, pSelect->pEList) ){
521 return 1;
523 if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
524 return 1;
526 if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
527 return 1;
529 if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
530 return 1;
532 if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
533 return 1;
535 if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
536 return 1;
538 if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
539 return 1;
541 if( pSelect->pWith ){
542 int i;
543 for(i=0; i<pSelect->pWith->nCte; i++){
544 if( sqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){
545 return 1;
549 pSelect = pSelect->pPrior;
551 return 0;
553 int sqlite3FixExpr(
554 DbFixer *pFix, /* Context of the fixation */
555 Expr *pExpr /* The expression to be fixed to one database */
557 while( pExpr ){
558 if( pExpr->op==TK_VARIABLE ){
559 if( pFix->pParse->db->init.busy ){
560 pExpr->op = TK_NULL;
561 }else{
562 sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
563 return 1;
566 if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
567 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
568 if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
569 }else{
570 if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
572 if( sqlite3FixExpr(pFix, pExpr->pRight) ){
573 return 1;
575 pExpr = pExpr->pLeft;
577 return 0;
579 int sqlite3FixExprList(
580 DbFixer *pFix, /* Context of the fixation */
581 ExprList *pList /* The expression to be fixed to one database */
583 int i;
584 struct ExprList_item *pItem;
585 if( pList==0 ) return 0;
586 for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
587 if( sqlite3FixExpr(pFix, pItem->pExpr) ){
588 return 1;
591 return 0;
593 #endif
595 #ifndef SQLITE_OMIT_TRIGGER
596 int sqlite3FixTriggerStep(
597 DbFixer *pFix, /* Context of the fixation */
598 TriggerStep *pStep /* The trigger step be fixed to one database */
600 while( pStep ){
601 if( sqlite3FixSelect(pFix, pStep->pSelect) ){
602 return 1;
604 if( sqlite3FixExpr(pFix, pStep->pWhere) ){
605 return 1;
607 if( sqlite3FixExprList(pFix, pStep->pExprList) ){
608 return 1;
610 #ifndef SQLITE_OMIT_UPSERT
611 if( pStep->pUpsert ){
612 Upsert *pUp = pStep->pUpsert;
613 if( sqlite3FixExprList(pFix, pUp->pUpsertTarget)
614 || sqlite3FixExpr(pFix, pUp->pUpsertTargetWhere)
615 || sqlite3FixExprList(pFix, pUp->pUpsertSet)
616 || sqlite3FixExpr(pFix, pUp->pUpsertWhere)
618 return 1;
621 #endif
622 pStep = pStep->pNext;
624 return 0;
626 #endif