wasCSharpSQLite – Blame information for rev 1

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 office 1 using System;
2 using System.Diagnostics;
3 using System.Text;
4  
5 using u8 = System.Byte;
6 using u32 = System.UInt32;
7  
8 namespace Community.CsharpSqlite
9 {
10 using sqlite3_value = Sqlite3.Mem;
11  
12 public partial class Sqlite3
13 {
14 /*
15 ** 2003 April 6
16 **
17 ** The author disclaims copyright to this source code. In place of
18 ** a legal notice, here is a blessing:
19 **
20 ** May you do good and not evil.
21 ** May you find forgiveness for yourself and forgive others.
22 ** May you share freely, never taking more than you give.
23 **
24 *************************************************************************
25 ** This file contains code used to implement the ATTACH and DETACH commands.
26 *************************************************************************
27 ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
28 ** C#-SQLite is an independent reimplementation of the SQLite software library
29 **
30 ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
31 **
32 *************************************************************************
33 */
34 //#include "sqliteInt.h"
35  
36 #if !SQLITE_OMIT_ATTACH
37 /*
38 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
39 ** is slightly different from resolving a normal SQL expression, because simple
40 ** identifiers are treated as strings, not possible column names or aliases.
41 **
42 ** i.e. if the parser sees:
43 **
44 ** ATTACH DATABASE abc AS def
45 **
46 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
47 ** looking for columns of the same name.
48 **
49 ** This only applies to the root node of pExpr, so the statement:
50 **
51 ** ATTACH DATABASE abc||def AS 'db2'
52 **
53 ** will fail because neither abc or def can be resolved.
54 */
55 static int resolveAttachExpr( NameContext pName, Expr pExpr )
56 {
57 int rc = SQLITE_OK;
58 if ( pExpr != null )
59 {
60 if ( pExpr.op != TK_ID )
61 {
62 rc = sqlite3ResolveExprNames( pName, ref pExpr );
63 if ( rc == SQLITE_OK && sqlite3ExprIsConstant( pExpr ) == 0 )
64 {
65 sqlite3ErrorMsg( pName.pParse, "invalid name: \"%s\"", pExpr.u.zToken );
66 return SQLITE_ERROR;
67 }
68 }
69 else
70 {
71 pExpr.op = TK_STRING;
72 }
73 }
74 return rc;
75 }
76  
77 /*
78 ** An SQL user-function registered to do the work of an ATTACH statement. The
79 ** three arguments to the function come directly from an attach statement:
80 **
81 ** ATTACH DATABASE x AS y KEY z
82 **
83 ** SELECT sqlite_attach(x, y, z)
84 **
85 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
86 ** third argument.
87 */
88 static void attachFunc(
89 sqlite3_context context,
90 int NotUsed,
91 sqlite3_value[] argv
92 )
93 {
94 int i;
95 int rc = 0;
96 sqlite3 db = sqlite3_context_db_handle( context );
97 string zName;
98 string zFile;
99 string zPath = string.Empty;
100 string zErr = string.Empty;
101 int flags;
102  
103 Db aNew = null;
104 string zErrDyn = string.Empty;
105 sqlite3_vfs pVfs = null;
106  
107 UNUSED_PARAMETER( NotUsed );
108  
109 zFile = argv[0].z != null && ( argv[0].z.Length > 0 ) && argv[0].flags != MEM_Null ? sqlite3_value_text( argv[0] ) : string.Empty;
110 zName = argv[1].z != null && ( argv[1].z.Length > 0 ) && argv[1].flags != MEM_Null ? sqlite3_value_text( argv[1] ) : string.Empty;
111 //if( zFile==null ) zFile = string.Empty;
112 //if ( zName == null ) zName = string.Empty;
113  
114 /* Check for the following errors:
115 **
116 ** * Too many attached databases,
117 ** * Transaction currently open
118 ** * Specified database name already being used.
119 */
120 if ( db.nDb >= db.aLimit[SQLITE_LIMIT_ATTACHED] + 2 )
121 {
122 zErrDyn = sqlite3MPrintf( db, "too many attached databases - max %d",
123 db.aLimit[SQLITE_LIMIT_ATTACHED]
124 );
125 goto attach_error;
126 }
127 if ( 0 == db.autoCommit )
128 {
129 zErrDyn = sqlite3MPrintf( db, "cannot ATTACH database within transaction" );
130 goto attach_error;
131 }
132 for ( i = 0; i < db.nDb; i++ )
133 {
134 string z = db.aDb[i].zName;
135 Debug.Assert( z != null && zName != null );
136 if ( z.Equals( zName, StringComparison.OrdinalIgnoreCase ) )
137 {
138 zErrDyn = sqlite3MPrintf( db, "database %s is already in use", zName );
139 goto attach_error;
140 }
141 }
142  
143 /* Allocate the new entry in the db.aDb[] array and initialise the schema
144 ** hash tables.
145 */
146 /* Allocate the new entry in the db.aDb[] array and initialise the schema
147 ** hash tables.
148 */
149 //if( db.aDb==db.aDbStatic ){
150 // aNew = sqlite3DbMallocRaw(db, sizeof(db.aDb[0])*3 );
151 // if( aNew==0 ) return;
152 // memcpy(aNew, db.aDb, sizeof(db.aDb[0])*2);
153 //}else {
154 if ( db.aDb.Length <= db.nDb )
155 Array.Resize( ref db.aDb, db.nDb + 1 );//aNew = sqlite3DbRealloc(db, db.aDb, sizeof(db.aDb[0])*(db.nDb+1) );
156 if ( db.aDb == null )
157 return; // if( aNew==0 ) return;
158 //}
159 db.aDb[db.nDb] = new Db();//db.aDb = aNew;
160 aNew = db.aDb[db.nDb];//memset(aNew, 0, sizeof(*aNew));
161 // memset(aNew, 0, sizeof(*aNew));
162  
163 /* Open the database file. If the btree is successfully opened, use
164 ** it to obtain the database schema. At this point the schema may
165 ** or may not be initialised.
166 */
167 flags = (int)db.openFlags;
168 rc = sqlite3ParseUri( db.pVfs.zName, zFile, ref flags, ref pVfs, ref zPath, ref zErr );
169 if ( rc != SQLITE_OK )
170 {
171 //if ( rc == SQLITE_NOMEM )
172 //db.mallocFailed = 1;
173 sqlite3_result_error( context, zErr, -1 );
174 //sqlite3_free( zErr );
175 return;
176 }
177 Debug.Assert( pVfs != null);
178 flags |= SQLITE_OPEN_MAIN_DB;
179 rc = sqlite3BtreeOpen( pVfs, zPath, db, ref aNew.pBt, 0, (int)flags );
180 //sqlite3_free( zPath );
181  
182 db.nDb++;
183 if ( rc == SQLITE_CONSTRAINT )
184 {
185 rc = SQLITE_ERROR;
186 zErrDyn = sqlite3MPrintf( db, "database is already attached" );
187 }
188 else if ( rc == SQLITE_OK )
189 {
190 Pager pPager;
191 aNew.pSchema = sqlite3SchemaGet( db, aNew.pBt );
192 //if ( aNew.pSchema == null )
193 //{
194 // rc = SQLITE_NOMEM;
195 //}
196 //else
197 if ( aNew.pSchema.file_format != 0 && aNew.pSchema.enc != ENC( db ) )
198 {
199 zErrDyn = sqlite3MPrintf( db,
200 "attached databases must use the same text encoding as main database" );
201 rc = SQLITE_ERROR;
202 }
203 pPager = sqlite3BtreePager( aNew.pBt );
204 sqlite3PagerLockingMode( pPager, db.dfltLockMode );
205 sqlite3BtreeSecureDelete( aNew.pBt,
206 sqlite3BtreeSecureDelete( db.aDb[0].pBt, -1 ) );
207 }
208 aNew.safety_level = 3;
209 aNew.zName = zName;//sqlite3DbStrDup(db, zName);
210 //if( rc==SQLITE_OK && aNew.zName==0 ){
211 // rc = SQLITE_NOMEM;
212 //}
213  
214 #if SQLITE_HAS_CODEC
215 if ( rc == SQLITE_OK )
216 {
217 //extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
218 //extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
219 int nKey;
220 string zKey;
221 int t = sqlite3_value_type( argv[2] );
222 switch ( t )
223 {
224 case SQLITE_INTEGER:
225 case SQLITE_FLOAT:
226 zErrDyn = "Invalid key value"; //sqlite3DbStrDup( db, "Invalid key value" );
227 rc = SQLITE_ERROR;
228 break;
229  
230 case SQLITE_TEXT:
231 case SQLITE_BLOB:
232 nKey = sqlite3_value_bytes( argv[2] );
233 zKey = sqlite3_value_blob( argv[2] ).ToString(); // (char *)sqlite3_value_blob(argv[2]);
234 rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey );
235 break;
236  
237 case SQLITE_NULL:
238 /* No key specified. Use the key from the main database */
239 sqlite3CodecGetKey( db, 0, out zKey, out nKey ); //sqlite3CodecGetKey(db, 0, (void**)&zKey, nKey);
240 if ( nKey > 0 || sqlite3BtreeGetReserve( db.aDb[0].pBt ) > 0 )
241 {
242 rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey );
243 }
244 break;
245 }
246 }
247 #endif
248  
249 /* If the file was opened successfully, read the schema for the new database.
250 ** If this fails, or if opening the file failed, then close the file and
251 ** remove the entry from the db.aDb[] array. i.e. put everything back the way
252 ** we found it.
253 */
254 if ( rc == SQLITE_OK )
255 {
256 sqlite3BtreeEnterAll( db );
257 rc = sqlite3Init( db, ref zErrDyn );
258 sqlite3BtreeLeaveAll( db );
259 }
260 if ( rc != 0 )
261 {
262 int iDb = db.nDb - 1;
263 Debug.Assert( iDb >= 2 );
264 if ( db.aDb[iDb].pBt != null )
265 {
266 sqlite3BtreeClose( ref db.aDb[iDb].pBt );
267 db.aDb[iDb].pBt = null;
268 db.aDb[iDb].pSchema = null;
269 }
270 sqlite3ResetInternalSchema( db, -1 );
271 db.nDb = iDb;
272 if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM )
273 {
274 //// db.mallocFailed = 1;
275 sqlite3DbFree( db, ref zErrDyn );
276 zErrDyn = sqlite3MPrintf( db, "out of memory" );
277 }
278 else if ( zErrDyn.Length == 0 )
279 {
280 zErrDyn = sqlite3MPrintf( db, "unable to open database: %s", zFile );
281 }
282 goto attach_error;
283 }
284  
285 return;
286  
287 attach_error:
288 /* Return an error if we get here */
289 if ( zErrDyn.Length > 0 )
290 {
291 sqlite3_result_error( context, zErrDyn, -1 );
292 sqlite3DbFree( db, ref zErrDyn );
293 }
294 if ( rc != 0 )
295 sqlite3_result_error_code( context, rc );
296 }
297  
298 /*
299 ** An SQL user-function registered to do the work of an DETACH statement. The
300 ** three arguments to the function come directly from a detach statement:
301 **
302 ** DETACH DATABASE x
303 **
304 ** SELECT sqlite_detach(x)
305 */
306 static void detachFunc(
307 sqlite3_context context,
308 int NotUsed,
309 sqlite3_value[] argv
310 )
311 {
312 string zName = !string.IsNullOrEmpty(argv[0].z) ? sqlite3_value_text( argv[0] ) : string.Empty;//(sqlite3_value_text(argv[0]);
313 sqlite3 db = sqlite3_context_db_handle( context );
314 int i;
315 Db pDb = null;
316 StringBuilder zErr = new StringBuilder( 200 );
317  
318 UNUSED_PARAMETER( NotUsed );
319  
320 zName = zName ?? string.Empty;
321 for ( i = 0; i < db.nDb; i++ )
322 {
323 pDb = db.aDb[i];
324 if ( pDb.pBt == null )
325 continue;
326 if ( pDb.zName.Equals( zName, StringComparison.OrdinalIgnoreCase ) )
327 break;
328 }
329  
330 if ( i >= db.nDb )
331 {
332 sqlite3_snprintf( 200, zErr, "no such database: %s", zName );
333 goto detach_error;
334 }
335 if ( i < 2 )
336 {
337 sqlite3_snprintf( 200, zErr, "cannot detach database %s", zName );
338 goto detach_error;
339 }
340 if ( 0 == db.autoCommit )
341 {
342 sqlite3_snprintf( 200, zErr,
343 "cannot DETACH database within transaction" );
344 goto detach_error;
345 }
346 if ( sqlite3BtreeIsInReadTrans( pDb.pBt ) || sqlite3BtreeIsInBackup( pDb.pBt ) )
347 {
348 sqlite3_snprintf( 200, zErr, "database %s is locked", zName );
349 goto detach_error;
350 }
351  
352 sqlite3BtreeClose( ref pDb.pBt );
353 pDb.pBt = null;
354 pDb.pSchema = null;
355 sqlite3ResetInternalSchema( db, -1 );
356 return;
357  
358 detach_error:
359 sqlite3_result_error( context, zErr.ToString(), -1 );
360 }
361  
362 /*
363 ** This procedure generates VDBE code for a single invocation of either the
364 ** sqlite_detach() or sqlite_attach() SQL user functions.
365 */
366 static void codeAttach(
367 Parse pParse, /* The parser context */
368 int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
369 FuncDef pFunc, /* FuncDef wrapper for detachFunc() or attachFunc() */
370 Expr pAuthArg, /* Expression to pass to authorization callback */
371 Expr pFilename, /* Name of database file */
372 Expr pDbname, /* Name of the database to use internally */
373 Expr pKey /* Database key for encryption extension */
374 )
375 {
376 NameContext sName;
377 Vdbe v;
378 sqlite3 db = pParse.db;
379 int regArgs;
380  
381 sName = new NameContext();// memset( &sName, 0, sizeof(NameContext));
382 sName.pParse = pParse;
383  
384 if (
385 SQLITE_OK != resolveAttachExpr( sName, pFilename ) ||
386 SQLITE_OK != resolveAttachExpr( sName, pDbname ) ||
387 SQLITE_OK != resolveAttachExpr( sName, pKey )
388 )
389 {
390 pParse.nErr++;
391 goto attach_end;
392 }
393  
394 #if !SQLITE_OMIT_AUTHORIZATION
395 if( pAuthArg ){
396 char *zAuthArg;
397 if( pAuthArg->op==TK_STRING ){
398 zAuthArg = pAuthArg->u.zToken;
399 }else{
400 zAuthArg = 0;
401 }
402 int rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
403 if(rc!=SQLITE_OK ){
404 goto attach_end;
405 }
406 }
407 #endif //* SQLITE_OMIT_AUTHORIZATION */
408  
409 v = sqlite3GetVdbe( pParse );
410 regArgs = sqlite3GetTempRange( pParse, 4 );
411 sqlite3ExprCode( pParse, pFilename, regArgs );
412 sqlite3ExprCode( pParse, pDbname, regArgs + 1 );
413 sqlite3ExprCode( pParse, pKey, regArgs + 2 );
414  
415 Debug.Assert( v != null /*|| db.mallocFailed != 0 */ );
416 if ( v != null )
417 {
418 sqlite3VdbeAddOp3( v, OP_Function, 0, regArgs + 3 - pFunc.nArg, regArgs + 3 );
419 Debug.Assert( pFunc.nArg == -1 || ( pFunc.nArg & 0xff ) == pFunc.nArg );
420 sqlite3VdbeChangeP5( v, (u8)( pFunc.nArg ) );
421 sqlite3VdbeChangeP4( v, -1, pFunc, P4_FUNCDEF );
422  
423 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
424 ** statement only). For DETACH, set it to false (expire all existing
425 ** statements).
426 */
427 sqlite3VdbeAddOp1( v, OP_Expire, ( type == SQLITE_ATTACH ) ? 1 : 0 );
428 }
429  
430 attach_end:
431 sqlite3ExprDelete( db, ref pFilename );
432 sqlite3ExprDelete( db, ref pDbname );
433 sqlite3ExprDelete( db, ref pKey );
434 }
435  
436 /*
437 ** Called by the parser to compile a DETACH statement.
438 **
439 ** DETACH pDbname
440 */
441 static FuncDef detach_func = new FuncDef(
442 1, /* nArg */
443 SQLITE_UTF8, /* iPrefEnc */
444 0, /* flags */
445 null, /* pUserData */
446 null, /* pNext */
447 detachFunc, /* xFunc */
448 null, /* xStep */
449 null, /* xFinalize */
450 "sqlite_detach", /* zName */
451 null, /* pHash */
452 null /* pDestructor */
453 );
454 static void sqlite3Detach( Parse pParse, Expr pDbname )
455 {
456 codeAttach( pParse, SQLITE_DETACH, detach_func, pDbname, null, null, pDbname );
457 }
458  
459 /*
460 ** Called by the parser to compile an ATTACH statement.
461 **
462 ** ATTACH p AS pDbname KEY pKey
463 */
464 static FuncDef attach_func = new FuncDef(
465 3, /* nArg */
466 SQLITE_UTF8, /* iPrefEnc */
467 0, /* flags */
468 null, /* pUserData */
469 null, /* pNext */
470 attachFunc, /* xFunc */
471 null, /* xStep */
472 null, /* xFinalize */
473 "sqlite_attach", /* zName */
474 null, /* pHash */
475 null /* pDestructor */
476 );
477 static void sqlite3Attach( Parse pParse, Expr p, Expr pDbname, Expr pKey )
478 {
479 codeAttach( pParse, SQLITE_ATTACH, attach_func, p, p, pDbname, pKey );
480 }
481 #endif // * SQLITE_OMIT_ATTACH */
482  
483 /*
484 ** Initialize a DbFixer structure. This routine must be called prior
485 ** to passing the structure to one of the sqliteFixAAAA() routines below.
486 **
487 ** The return value indicates whether or not fixation is required. TRUE
488 ** means we do need to fix the database references, FALSE means we do not.
489 */
490 static int sqlite3FixInit(
491 DbFixer pFix, /* The fixer to be initialized */
492 Parse pParse, /* Error messages will be written here */
493 int iDb, /* This is the database that must be used */
494 string zType, /* "view", "trigger", or "index" */
495 Token pName /* Name of the view, trigger, or index */
496 )
497 {
498 sqlite3 db;
499  
500 if ( NEVER( iDb < 0 ) || iDb == 1 )
501 return 0;
502 db = pParse.db;
503 Debug.Assert( db.nDb > iDb );
504 pFix.pParse = pParse;
505 pFix.zDb = db.aDb[iDb].zName;
506 pFix.zType = zType;
507 pFix.pName = pName;
508 return 1;
509 }
510  
511 /*
512 ** The following set of routines walk through the parse tree and assign
513 ** a specific database to all table references where the database name
514 ** was left unspecified in the original SQL statement. The pFix structure
515 ** must have been initialized by a prior call to sqlite3FixInit().
516 **
517 ** These routines are used to make sure that an index, trigger, or
518 ** view in one database does not refer to objects in a different database.
519 ** (Exception: indices, triggers, and views in the TEMP database are
520 ** allowed to refer to anything.) If a reference is explicitly made
521 ** to an object in a different database, an error message is added to
522 ** pParse.zErrMsg and these routines return non-zero. If everything
523 ** checks out, these routines return 0.
524 */
525 static int sqlite3FixSrcList(
526 DbFixer pFix, /* Context of the fixation */
527 SrcList pList /* The Source list to check and modify */
528 )
529 {
530 int i;
531 string zDb;
532 SrcList_item pItem;
533  
534 if ( NEVER( pList == null ) )
535 return 0;
536 zDb = pFix.zDb;
537 for ( i = 0; i < pList.nSrc; i++ )
538 {//, pItem++){
539 pItem = pList.a[i];
540 if ( pItem.zDatabase == null )
541 {
542 pItem.zDatabase = zDb;// sqlite3DbStrDup( pFix.pParse.db, zDb );
543 }
544 else if ( !pItem.zDatabase.Equals( zDb ,StringComparison.OrdinalIgnoreCase ) )
545 {
546 sqlite3ErrorMsg( pFix.pParse,
547 "%s %T cannot reference objects in database %s",
548 pFix.zType, pFix.pName, pItem.zDatabase );
549 return 1;
550 }
551 #if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER
552 if ( sqlite3FixSelect( pFix, pItem.pSelect ) != 0 )
553 return 1;
554 if ( sqlite3FixExpr( pFix, pItem.pOn ) != 0 )
555 return 1;
556 #endif
557 }
558 return 0;
559 }
560 #if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER
561 static int sqlite3FixSelect(
562 DbFixer pFix, /* Context of the fixation */
563 Select pSelect /* The SELECT statement to be fixed to one database */
564 )
565 {
566 while ( pSelect != null )
567 {
568 if ( sqlite3FixExprList( pFix, pSelect.pEList ) != 0 )
569 {
570 return 1;
571 }
572 if ( sqlite3FixSrcList( pFix, pSelect.pSrc ) != 0 )
573 {
574 return 1;
575 }
576 if ( sqlite3FixExpr( pFix, pSelect.pWhere ) != 0 )
577 {
578 return 1;
579 }
580 if ( sqlite3FixExpr( pFix, pSelect.pHaving ) != 0 )
581 {
582 return 1;
583 }
584 pSelect = pSelect.pPrior;
585 }
586 return 0;
587 }
588 static int sqlite3FixExpr(
589 DbFixer pFix, /* Context of the fixation */
590 Expr pExpr /* The expression to be fixed to one database */
591 )
592 {
593 while ( pExpr != null )
594 {
595 if ( ExprHasAnyProperty( pExpr, EP_TokenOnly ) )
596 break;
597 if ( ExprHasProperty( pExpr, EP_xIsSelect ) )
598 {
599 if ( sqlite3FixSelect( pFix, pExpr.x.pSelect ) != 0 )
600 return 1;
601 }
602 else
603 {
604 if ( sqlite3FixExprList( pFix, pExpr.x.pList ) != 0 )
605 return 1;
606 }
607 if ( sqlite3FixExpr( pFix, pExpr.pRight ) != 0 )
608 {
609 return 1;
610 }
611 pExpr = pExpr.pLeft;
612 }
613 return 0;
614 }
615 static int sqlite3FixExprList(
616 DbFixer pFix, /* Context of the fixation */
617 ExprList pList /* The expression to be fixed to one database */
618 )
619 {
620 int i;
621 ExprList_item pItem;
622 if ( pList == null )
623 return 0;
624 for ( i = 0; i < pList.nExpr; i++ )//, pItem++ )
625 {
626 pItem = pList.a[i];
627 if ( sqlite3FixExpr( pFix, pItem.pExpr ) != 0 )
628 {
629 return 1;
630 }
631 }
632 return 0;
633 }
634 #endif
635  
636 #if !SQLITE_OMIT_TRIGGER
637 static int sqlite3FixTriggerStep(
638 DbFixer pFix, /* Context of the fixation */
639 TriggerStep pStep /* The trigger step be fixed to one database */
640 )
641 {
642 while ( pStep != null )
643 {
644 if ( sqlite3FixSelect( pFix, pStep.pSelect ) != 0 )
645 {
646 return 1;
647 }
648 if ( sqlite3FixExpr( pFix, pStep.pWhere ) != 0 )
649 {
650 return 1;
651 }
652 if ( sqlite3FixExprList( pFix, pStep.pExprList ) != 0 )
653 {
654 return 1;
655 }
656 pStep = pStep.pNext;
657 }
658 return 0;
659 }
660 #endif
661  
662 }
663 }