xref: /sqlite-3.40.0/src/test_fs.c (revision 92af1ebc)
1 /*
2 ** 2013 Jan 11
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 ** Code for testing the virtual table interfaces.  This code
13 ** is not included in the SQLite library.  It is used for automated
14 ** testing of the SQLite library.
15 **
16 ** The FS virtual table is created as follows:
17 **
18 **   CREATE VIRTUAL TABLE tbl USING fs(idx);
19 **
20 ** where idx is the name of a table in the db with 2 columns.  The virtual
21 ** table also has two columns - file path and file contents.
22 **
23 ** The first column of table idx must be an IPK, and the second contains file
24 ** paths. For example:
25 **
26 **   CREATE TABLE idx(id INTEGER PRIMARY KEY, path TEXT);
27 **   INSERT INTO idx VALUES(4, '/etc/passwd');
28 **
29 ** Adding the row to the idx table automatically creates a row in the
30 ** virtual table with rowid=4, path=/etc/passwd and a text field that
31 ** contains data read from file /etc/passwd on disk.
32 **
33 *************************************************************************
34 ** Virtual table module "fsdir"
35 **
36 ** This module is designed to be used as a read-only eponymous virtual table.
37 ** Its schema is as follows:
38 **
39 **   CREATE TABLE fsdir(dir TEXT, name TEXT);
40 **
41 ** When queried, a WHERE term of the form "dir = $dir" must be provided. The
42 ** virtual table then appears to have one row for each entry in file-system
43 ** directory $dir. Column dir contains a copy of $dir, and column "name"
44 ** contains the name of the directory entry.
45 **
46 ** If the specified $dir cannot be opened or is not a directory, it is not
47 ** an error. The virtual table appears to be empty in this case.
48 **
49 *************************************************************************
50 ** Virtual table module "fstree"
51 **
52 ** This module is also a read-only eponymous virtual table with the
53 ** following schema:
54 **
55 **   CREATE TABLE fstree(path TEXT, size INT, data BLOB);
56 **
57 ** Running a "SELECT * FROM fstree" query on this table returns the entire
58 ** contents of the file-system, starting at "/". To restrict the search
59 ** space, the virtual table supports LIKE and GLOB constraints on the
60 ** 'path' column. For example:
61 **
62 **   SELECT * FROM fstree WHERE path LIKE '/home/dan/sqlite/%'
63 */
64 #include "sqliteInt.h"
65 #include "tcl.h"
66 
67 #include <stdlib.h>
68 #include <string.h>
69 #include <sys/types.h>
70 #include <sys/stat.h>
71 #include <fcntl.h>
72 
73 #if SQLITE_OS_UNIX
74 # include <unistd.h>
75 # include <dirent.h>
76 # ifndef DIRENT
77 #  define DIRENT dirent
78 # endif
79 #endif
80 #if SQLITE_OS_WIN
81 # include <io.h>
82 # include "test_windirent.h"
83 # ifndef S_ISREG
84 #  define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
85 # endif
86 #endif
87 
88 #ifndef SQLITE_OMIT_VIRTUALTABLE
89 
90 typedef struct fs_vtab fs_vtab;
91 typedef struct fs_cursor fs_cursor;
92 
93 /*
94 ** A fs virtual-table object
95 */
96 struct fs_vtab {
97   sqlite3_vtab base;
98   sqlite3 *db;
99   char *zDb;                      /* Name of db containing zTbl */
100   char *zTbl;                     /* Name of docid->file map table */
101 };
102 
103 /* A fs cursor object */
104 struct fs_cursor {
105   sqlite3_vtab_cursor base;
106   sqlite3_stmt *pStmt;
107   char *zBuf;
108   int nBuf;
109   int nAlloc;
110 };
111 
112 /*************************************************************************
113 ** Start of fsdir implementation.
114 */
115 typedef struct FsdirVtab FsdirVtab;
116 typedef struct FsdirCsr FsdirCsr;
117 struct FsdirVtab {
118   sqlite3_vtab base;
119 };
120 
121 struct FsdirCsr {
122   sqlite3_vtab_cursor base;
123   char *zDir;                     /* Buffer containing directory scanned */
124   DIR *pDir;                      /* Open directory */
125   sqlite3_int64 iRowid;
126   struct DIRENT entry;            /* Current entry */
127 };
128 
129 /*
130 ** This function is the implementation of both the xConnect and xCreate
131 ** methods of the fsdir virtual table.
132 **
133 ** The argv[] array contains the following:
134 **
135 **   argv[0]   -> module name  ("fs")
136 **   argv[1]   -> database name
137 **   argv[2]   -> table name
138 **   argv[...] -> other module argument fields.
139 */
140 static int fsdirConnect(
141   sqlite3 *db,
142   void *pAux,
143   int argc, const char *const*argv,
144   sqlite3_vtab **ppVtab,
145   char **pzErr
146 ){
147   FsdirVtab *pTab;
148 
149   if( argc!=3 ){
150     *pzErr = sqlite3_mprintf("wrong number of arguments");
151     return SQLITE_ERROR;
152   }
153 
154   pTab = (FsdirVtab *)sqlite3_malloc(sizeof(FsdirVtab));
155   if( !pTab ) return SQLITE_NOMEM;
156   memset(pTab, 0, sizeof(FsdirVtab));
157 
158   *ppVtab = &pTab->base;
159   sqlite3_declare_vtab(db, "CREATE TABLE xyz(dir, name);");
160 
161   return SQLITE_OK;
162 }
163 
164 /*
165 ** xDestroy/xDisconnect implementation.
166 */
167 static int fsdirDisconnect(sqlite3_vtab *pVtab){
168   sqlite3_free(pVtab);
169   return SQLITE_OK;
170 }
171 
172 /*
173 ** xBestIndex implementation. The only constraint supported is:
174 **
175 **   (dir = ?)
176 */
177 static int fsdirBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
178   int ii;
179 
180   pIdxInfo->estimatedCost = 1000000000.0;
181 
182   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
183     struct sqlite3_index_constraint const *p = &pIdxInfo->aConstraint[ii];
184     if( p->iColumn==0 && p->usable && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
185       struct sqlite3_index_constraint_usage *pUsage;
186       pUsage = &pIdxInfo->aConstraintUsage[ii];
187       pUsage->omit = 1;
188       pUsage->argvIndex = 1;
189       pIdxInfo->idxNum = 1;
190       pIdxInfo->estimatedCost = 1.0;
191       break;
192     }
193   }
194 
195   return SQLITE_OK;
196 }
197 
198 /*
199 ** xOpen implementation.
200 **
201 ** Open a new fsdir cursor.
202 */
203 static int fsdirOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
204   FsdirCsr *pCur;
205   pCur = (FsdirCsr*)sqlite3_malloc(sizeof(FsdirCsr));
206   if( pCur==0 ) return SQLITE_NOMEM;
207   memset(pCur, 0, sizeof(FsdirCsr));
208   *ppCursor = &pCur->base;
209   return SQLITE_OK;
210 }
211 
212 /*
213 ** Close a fsdir cursor.
214 */
215 static int fsdirClose(sqlite3_vtab_cursor *cur){
216   FsdirCsr *pCur = (FsdirCsr*)cur;
217   if( pCur->pDir ) closedir(pCur->pDir);
218   sqlite3_free(pCur->zDir);
219   sqlite3_free(pCur);
220   return SQLITE_OK;
221 }
222 
223 /*
224 ** Skip the cursor to the next entry.
225 */
226 static int fsdirNext(sqlite3_vtab_cursor *cur){
227   FsdirCsr *pCsr = (FsdirCsr*)cur;
228 
229   if( pCsr->pDir ){
230     struct DIRENT *pRes = 0;
231     readdir_r(pCsr->pDir, &pCsr->entry, &pRes);
232     if( pRes==0 ){
233       closedir(pCsr->pDir);
234       pCsr->pDir = 0;
235     }
236     pCsr->iRowid++;
237   }
238 
239   return SQLITE_OK;
240 }
241 
242 /*
243 ** xFilter method implementation.
244 */
245 static int fsdirFilter(
246   sqlite3_vtab_cursor *pVtabCursor,
247   int idxNum, const char *idxStr,
248   int argc, sqlite3_value **argv
249 ){
250   FsdirCsr *pCsr = (FsdirCsr*)pVtabCursor;
251   const char *zDir;
252   int nDir;
253 
254 
255   if( idxNum!=1 || argc!=1 ){
256     return SQLITE_ERROR;
257   }
258 
259   pCsr->iRowid = 0;
260   sqlite3_free(pCsr->zDir);
261   if( pCsr->pDir ){
262     closedir(pCsr->pDir);
263     pCsr->pDir = 0;
264   }
265 
266   zDir = (const char*)sqlite3_value_text(argv[0]);
267   nDir = sqlite3_value_bytes(argv[0]);
268   pCsr->zDir = sqlite3_malloc(nDir+1);
269   if( pCsr->zDir==0 ) return SQLITE_NOMEM;
270   memcpy(pCsr->zDir, zDir, nDir+1);
271 
272   pCsr->pDir = opendir(pCsr->zDir);
273   return fsdirNext(pVtabCursor);
274 }
275 
276 /*
277 ** xEof method implementation.
278 */
279 static int fsdirEof(sqlite3_vtab_cursor *cur){
280   FsdirCsr *pCsr = (FsdirCsr*)cur;
281   return pCsr->pDir==0;
282 }
283 
284 /*
285 ** xColumn method implementation.
286 */
287 static int fsdirColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
288   FsdirCsr *pCsr = (FsdirCsr*)cur;
289   switch( i ){
290     case 0: /* dir */
291       sqlite3_result_text(ctx, pCsr->zDir, -1, SQLITE_STATIC);
292       break;
293 
294     case 1: /* name */
295       sqlite3_result_text(ctx, pCsr->entry.d_name, -1, SQLITE_TRANSIENT);
296       break;
297 
298     default:
299       assert( 0 );
300   }
301 
302   return SQLITE_OK;
303 }
304 
305 /*
306 ** xRowid method implementation.
307 */
308 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
309   FsdirCsr *pCsr = (FsdirCsr*)cur;
310   *pRowid = pCsr->iRowid;
311   return SQLITE_OK;
312 }
313 /*
314 ** End of fsdir implementation.
315 *************************************************************************/
316 
317 /*************************************************************************
318 ** Start of fstree implementation.
319 */
320 typedef struct FstreeVtab FstreeVtab;
321 typedef struct FstreeCsr FstreeCsr;
322 struct FstreeVtab {
323   sqlite3_vtab base;
324   sqlite3 *db;
325 };
326 
327 struct FstreeCsr {
328   sqlite3_vtab_cursor base;
329   sqlite3_stmt *pStmt;            /* Statement to list paths */
330   int fd;                         /* File descriptor open on current path */
331 };
332 
333 /*
334 ** This function is the implementation of both the xConnect and xCreate
335 ** methods of the fstree virtual table.
336 **
337 ** The argv[] array contains the following:
338 **
339 **   argv[0]   -> module name  ("fs")
340 **   argv[1]   -> database name
341 **   argv[2]   -> table name
342 **   argv[...] -> other module argument fields.
343 */
344 static int fstreeConnect(
345   sqlite3 *db,
346   void *pAux,
347   int argc, const char *const*argv,
348   sqlite3_vtab **ppVtab,
349   char **pzErr
350 ){
351   FstreeVtab *pTab;
352 
353   if( argc!=3 ){
354     *pzErr = sqlite3_mprintf("wrong number of arguments");
355     return SQLITE_ERROR;
356   }
357 
358   pTab = (FstreeVtab *)sqlite3_malloc(sizeof(FstreeVtab));
359   if( !pTab ) return SQLITE_NOMEM;
360   memset(pTab, 0, sizeof(FstreeVtab));
361   pTab->db = db;
362 
363   *ppVtab = &pTab->base;
364   sqlite3_declare_vtab(db, "CREATE TABLE xyz(path, size, data);");
365 
366   return SQLITE_OK;
367 }
368 
369 /*
370 ** xDestroy/xDisconnect implementation.
371 */
372 static int fstreeDisconnect(sqlite3_vtab *pVtab){
373   sqlite3_free(pVtab);
374   return SQLITE_OK;
375 }
376 
377 /*
378 ** xBestIndex implementation. The only constraint supported is:
379 **
380 **   (dir = ?)
381 */
382 static int fstreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
383   int ii;
384 
385   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
386     struct sqlite3_index_constraint const *p = &pIdxInfo->aConstraint[ii];
387     if( p->iColumn==0 && p->usable && (
388           p->op==SQLITE_INDEX_CONSTRAINT_GLOB
389        || p->op==SQLITE_INDEX_CONSTRAINT_LIKE
390        || p->op==SQLITE_INDEX_CONSTRAINT_EQ
391     )){
392       struct sqlite3_index_constraint_usage *pUsage;
393       pUsage = &pIdxInfo->aConstraintUsage[ii];
394       pIdxInfo->idxNum = p->op;
395       pUsage->argvIndex = 1;
396       pIdxInfo->estimatedCost = 100000.0;
397       return SQLITE_OK;
398     }
399   }
400 
401   pIdxInfo->estimatedCost = 1000000000.0;
402   return SQLITE_OK;
403 }
404 
405 /*
406 ** xOpen implementation.
407 **
408 ** Open a new fstree cursor.
409 */
410 static int fstreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
411   FstreeCsr *pCur;
412   pCur = (FstreeCsr*)sqlite3_malloc(sizeof(FstreeCsr));
413   if( pCur==0 ) return SQLITE_NOMEM;
414   memset(pCur, 0, sizeof(FstreeCsr));
415   pCur->fd = -1;
416   *ppCursor = &pCur->base;
417   return SQLITE_OK;
418 }
419 
420 static void fstreeCloseFd(FstreeCsr *pCsr){
421   if( pCsr->fd>=0 ){
422     close(pCsr->fd);
423     pCsr->fd = -1;
424   }
425 }
426 
427 /*
428 ** Close a fstree cursor.
429 */
430 static int fstreeClose(sqlite3_vtab_cursor *cur){
431   FstreeCsr *pCsr = (FstreeCsr*)cur;
432   sqlite3_finalize(pCsr->pStmt);
433   fstreeCloseFd(pCsr);
434   sqlite3_free(pCsr);
435   return SQLITE_OK;
436 }
437 
438 /*
439 ** Skip the cursor to the next entry.
440 */
441 static int fstreeNext(sqlite3_vtab_cursor *cur){
442   FstreeCsr *pCsr = (FstreeCsr*)cur;
443   int rc;
444 
445   fstreeCloseFd(pCsr);
446   rc = sqlite3_step(pCsr->pStmt);
447   if( rc!=SQLITE_ROW ){
448     rc = sqlite3_finalize(pCsr->pStmt);
449     pCsr->pStmt = 0;
450   }else{
451     rc = SQLITE_OK;
452     pCsr->fd = open((const char*)sqlite3_column_text(pCsr->pStmt, 0), O_RDONLY);
453   }
454 
455   return rc;
456 }
457 
458 /*
459 ** xFilter method implementation.
460 */
461 static int fstreeFilter(
462   sqlite3_vtab_cursor *pVtabCursor,
463   int idxNum, const char *idxStr,
464   int argc, sqlite3_value **argv
465 ){
466   FstreeCsr *pCsr = (FstreeCsr*)pVtabCursor;
467   FstreeVtab *pTab = (FstreeVtab*)(pCsr->base.pVtab);
468   int rc;
469   const char *zSql =
470 "WITH r(d) AS ("
471 "  SELECT CASE WHEN dir=?2 THEN ?3 ELSE dir END || '/' || name "
472 "    FROM fsdir WHERE dir=?1 AND name NOT LIKE '.%'"
473 "  UNION ALL"
474 "  SELECT dir || '/' || name FROM r, fsdir WHERE dir=d AND name NOT LIKE '.%'"
475 ") SELECT d FROM r;";
476 
477   char *zRoot;
478   int nRoot;
479   char *zPrefix;
480   int nPrefix;
481   const char *zDir;
482   int nDir;
483   char aWild[2] = { '\0', '\0' };
484 
485 #if SQLITE_OS_WIN
486   zRoot = sqlite3_mprintf("%s%c", getenv("SystemDrive"), '/');
487   nRoot = strlen(zRoot);
488   zPrefix = sqlite3_mprintf("%s", getenv("SystemDrive"));
489   nPrefix = strlen(zPrefix);
490 #else
491   zRoot = "/";
492   nRoot = 1;
493   zPrefix = "";
494   nPrefix = 0;
495 #endif
496 
497   zDir = zRoot;
498   nDir = nRoot;
499 
500   fstreeCloseFd(pCsr);
501   sqlite3_finalize(pCsr->pStmt);
502   pCsr->pStmt = 0;
503   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
504   if( rc!=SQLITE_OK ) return rc;
505 
506   if( idxNum ){
507     const char *zQuery = (const char*)sqlite3_value_text(argv[0]);
508     switch( idxNum ){
509       case SQLITE_INDEX_CONSTRAINT_GLOB:
510         aWild[0] = '*';
511         aWild[1] = '?';
512         break;
513       case SQLITE_INDEX_CONSTRAINT_LIKE:
514         aWild[0] = '_';
515         aWild[1] = '%';
516         break;
517     }
518 
519     if( sqlite3_strnicmp(zQuery, zPrefix, nPrefix)==0 ){
520       int i;
521       for(i=nPrefix; zQuery[i]; i++){
522         if( zQuery[i]==aWild[0] || zQuery[i]==aWild[1] ) break;
523         if( zQuery[i]=='/' ) nDir = i;
524       }
525       zDir = zQuery;
526     }
527   }
528 
529   sqlite3_bind_text(pCsr->pStmt, 1, zDir, nDir, SQLITE_TRANSIENT);
530   sqlite3_bind_text(pCsr->pStmt, 2, zRoot, nRoot, SQLITE_TRANSIENT);
531   sqlite3_bind_text(pCsr->pStmt, 3, zPrefix, nPrefix, SQLITE_TRANSIENT);
532 
533 #if SQLITE_OS_WIN
534   sqlite3_free(zPrefix);
535   sqlite3_free(zRoot);
536 #endif
537 
538   return fstreeNext(pVtabCursor);
539 }
540 
541 /*
542 ** xEof method implementation.
543 */
544 static int fstreeEof(sqlite3_vtab_cursor *cur){
545   FstreeCsr *pCsr = (FstreeCsr*)cur;
546   return pCsr->pStmt==0;
547 }
548 
549 /*
550 ** xColumn method implementation.
551 */
552 static int fstreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
553   FstreeCsr *pCsr = (FstreeCsr*)cur;
554   if( i==0 ){      /* path */
555     sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pStmt, 0));
556   }else{
557     struct stat sBuf;
558     fstat(pCsr->fd, &sBuf);
559 
560     if( S_ISREG(sBuf.st_mode) ){
561       if( i==1 ){
562         sqlite3_result_int64(ctx, sBuf.st_size);
563       }else{
564         int nRead;
565         char *aBuf = sqlite3_malloc(sBuf.st_mode+1);
566         if( !aBuf ) return SQLITE_NOMEM;
567         nRead = read(pCsr->fd, aBuf, sBuf.st_mode);
568         if( nRead!=sBuf.st_mode ){
569           return SQLITE_IOERR;
570         }
571         sqlite3_result_blob(ctx, aBuf, nRead, SQLITE_TRANSIENT);
572         sqlite3_free(aBuf);
573       }
574     }
575   }
576 
577   return SQLITE_OK;
578 }
579 
580 /*
581 ** xRowid method implementation.
582 */
583 static int fstreeRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
584   *pRowid = 0;
585   return SQLITE_OK;
586 }
587 /*
588 ** End of fstree implementation.
589 *************************************************************************/
590 
591 
592 
593 
594 /*
595 ** This function is the implementation of both the xConnect and xCreate
596 ** methods of the fs virtual table.
597 **
598 ** The argv[] array contains the following:
599 **
600 **   argv[0]   -> module name  ("fs")
601 **   argv[1]   -> database name
602 **   argv[2]   -> table name
603 **   argv[...] -> other module argument fields.
604 */
605 static int fsConnect(
606   sqlite3 *db,
607   void *pAux,
608   int argc, const char *const*argv,
609   sqlite3_vtab **ppVtab,
610   char **pzErr
611 ){
612   fs_vtab *pVtab;
613   int nByte;
614   const char *zTbl;
615   const char *zDb = argv[1];
616 
617   if( argc!=4 ){
618     *pzErr = sqlite3_mprintf("wrong number of arguments");
619     return SQLITE_ERROR;
620   }
621   zTbl = argv[3];
622 
623   nByte = sizeof(fs_vtab) + (int)strlen(zTbl) + 1 + (int)strlen(zDb) + 1;
624   pVtab = (fs_vtab *)sqlite3MallocZero( nByte );
625   if( !pVtab ) return SQLITE_NOMEM;
626 
627   pVtab->zTbl = (char *)&pVtab[1];
628   pVtab->zDb = &pVtab->zTbl[strlen(zTbl)+1];
629   pVtab->db = db;
630   memcpy(pVtab->zTbl, zTbl, strlen(zTbl));
631   memcpy(pVtab->zDb, zDb, strlen(zDb));
632   *ppVtab = &pVtab->base;
633   sqlite3_declare_vtab(db, "CREATE TABLE x(path TEXT, data TEXT)");
634 
635   return SQLITE_OK;
636 }
637 /* Note that for this virtual table, the xCreate and xConnect
638 ** methods are identical. */
639 
640 static int fsDisconnect(sqlite3_vtab *pVtab){
641   sqlite3_free(pVtab);
642   return SQLITE_OK;
643 }
644 /* The xDisconnect and xDestroy methods are also the same */
645 
646 /*
647 ** Open a new fs cursor.
648 */
649 static int fsOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
650   fs_cursor *pCur;
651   pCur = sqlite3MallocZero(sizeof(fs_cursor));
652   *ppCursor = &pCur->base;
653   return SQLITE_OK;
654 }
655 
656 /*
657 ** Close a fs cursor.
658 */
659 static int fsClose(sqlite3_vtab_cursor *cur){
660   fs_cursor *pCur = (fs_cursor *)cur;
661   sqlite3_finalize(pCur->pStmt);
662   sqlite3_free(pCur->zBuf);
663   sqlite3_free(pCur);
664   return SQLITE_OK;
665 }
666 
667 static int fsNext(sqlite3_vtab_cursor *cur){
668   fs_cursor *pCur = (fs_cursor *)cur;
669   int rc;
670 
671   rc = sqlite3_step(pCur->pStmt);
672   if( rc==SQLITE_ROW || rc==SQLITE_DONE ) rc = SQLITE_OK;
673 
674   return rc;
675 }
676 
677 static int fsFilter(
678   sqlite3_vtab_cursor *pVtabCursor,
679   int idxNum, const char *idxStr,
680   int argc, sqlite3_value **argv
681 ){
682   int rc;
683   fs_cursor *pCur = (fs_cursor *)pVtabCursor;
684   fs_vtab *p = (fs_vtab *)(pVtabCursor->pVtab);
685 
686   assert( (idxNum==0 && argc==0) || (idxNum==1 && argc==1) );
687   if( idxNum==1 ){
688     char *zStmt = sqlite3_mprintf(
689         "SELECT * FROM %Q.%Q WHERE rowid=?", p->zDb, p->zTbl);
690     if( !zStmt ) return SQLITE_NOMEM;
691     rc = sqlite3_prepare_v2(p->db, zStmt, -1, &pCur->pStmt, 0);
692     sqlite3_free(zStmt);
693     if( rc==SQLITE_OK ){
694       sqlite3_bind_value(pCur->pStmt, 1, argv[0]);
695     }
696   }else{
697     char *zStmt = sqlite3_mprintf("SELECT * FROM %Q.%Q", p->zDb, p->zTbl);
698     if( !zStmt ) return SQLITE_NOMEM;
699     rc = sqlite3_prepare_v2(p->db, zStmt, -1, &pCur->pStmt, 0);
700     sqlite3_free(zStmt);
701   }
702 
703   if( rc==SQLITE_OK ){
704     rc = fsNext(pVtabCursor);
705   }
706   return rc;
707 }
708 
709 static int fsColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
710   fs_cursor *pCur = (fs_cursor*)cur;
711 
712   assert( i==0 || i==1 || i==2 );
713   if( i==0 ){
714     sqlite3_result_value(ctx, sqlite3_column_value(pCur->pStmt, 0));
715   }else{
716     const char *zFile = (const char *)sqlite3_column_text(pCur->pStmt, 1);
717     struct stat sbuf;
718     int fd;
719 
720     int n;
721     fd = open(zFile, O_RDONLY);
722     if( fd<0 ) return SQLITE_IOERR;
723     fstat(fd, &sbuf);
724 
725     if( sbuf.st_size>=pCur->nAlloc ){
726       int nNew = sbuf.st_size*2;
727       char *zNew;
728       if( nNew<1024 ) nNew = 1024;
729 
730       zNew = sqlite3Realloc(pCur->zBuf, nNew);
731       if( zNew==0 ){
732         close(fd);
733         return SQLITE_NOMEM;
734       }
735       pCur->zBuf = zNew;
736       pCur->nAlloc = nNew;
737     }
738 
739     n = (int)read(fd, pCur->zBuf, sbuf.st_size);
740     close(fd);
741     if( n!=sbuf.st_size ) return SQLITE_ERROR;
742     pCur->nBuf = sbuf.st_size;
743     pCur->zBuf[pCur->nBuf] = '\0';
744 
745     sqlite3_result_text(ctx, pCur->zBuf, -1, SQLITE_TRANSIENT);
746   }
747   return SQLITE_OK;
748 }
749 
750 static int fsRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
751   fs_cursor *pCur = (fs_cursor*)cur;
752   *pRowid = sqlite3_column_int64(pCur->pStmt, 0);
753   return SQLITE_OK;
754 }
755 
756 static int fsEof(sqlite3_vtab_cursor *cur){
757   fs_cursor *pCur = (fs_cursor*)cur;
758   return (sqlite3_data_count(pCur->pStmt)==0);
759 }
760 
761 static int fsBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
762   int ii;
763 
764   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
765     struct sqlite3_index_constraint const *pCons = &pIdxInfo->aConstraint[ii];
766     if( pCons->iColumn<0 && pCons->usable
767            && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
768       struct sqlite3_index_constraint_usage *pUsage;
769       pUsage = &pIdxInfo->aConstraintUsage[ii];
770       pUsage->omit = 0;
771       pUsage->argvIndex = 1;
772       pIdxInfo->idxNum = 1;
773       pIdxInfo->estimatedCost = 1.0;
774       break;
775     }
776   }
777 
778   return SQLITE_OK;
779 }
780 
781 /*
782 ** A virtual table module that provides read-only access to a
783 ** Tcl global variable namespace.
784 */
785 static sqlite3_module fsModule = {
786   0,                         /* iVersion */
787   fsConnect,
788   fsConnect,
789   fsBestIndex,
790   fsDisconnect,
791   fsDisconnect,
792   fsOpen,                      /* xOpen - open a cursor */
793   fsClose,                     /* xClose - close a cursor */
794   fsFilter,                    /* xFilter - configure scan constraints */
795   fsNext,                      /* xNext - advance a cursor */
796   fsEof,                       /* xEof - check for end of scan */
797   fsColumn,                    /* xColumn - read data */
798   fsRowid,                     /* xRowid - read data */
799   0,                           /* xUpdate */
800   0,                           /* xBegin */
801   0,                           /* xSync */
802   0,                           /* xCommit */
803   0,                           /* xRollback */
804   0,                           /* xFindMethod */
805   0,                           /* xRename */
806 };
807 
808 static sqlite3_module fsdirModule = {
809   0,                              /* iVersion */
810   fsdirConnect,                   /* xCreate */
811   fsdirConnect,                   /* xConnect */
812   fsdirBestIndex,                 /* xBestIndex */
813   fsdirDisconnect,                /* xDisconnect */
814   fsdirDisconnect,                /* xDestroy */
815   fsdirOpen,                      /* xOpen - open a cursor */
816   fsdirClose,                     /* xClose - close a cursor */
817   fsdirFilter,                    /* xFilter - configure scan constraints */
818   fsdirNext,                      /* xNext - advance a cursor */
819   fsdirEof,                       /* xEof - check for end of scan */
820   fsdirColumn,                    /* xColumn - read data */
821   fsdirRowid,                     /* xRowid - read data */
822   0,                              /* xUpdate */
823   0,                              /* xBegin */
824   0,                              /* xSync */
825   0,                              /* xCommit */
826   0,                              /* xRollback */
827   0,                              /* xFindMethod */
828   0,                              /* xRename */
829 };
830 
831 static sqlite3_module fstreeModule = {
832   0,                              /* iVersion */
833   fstreeConnect,                  /* xCreate */
834   fstreeConnect,                  /* xConnect */
835   fstreeBestIndex,                /* xBestIndex */
836   fstreeDisconnect,               /* xDisconnect */
837   fstreeDisconnect,               /* xDestroy */
838   fstreeOpen,                     /* xOpen - open a cursor */
839   fstreeClose,                    /* xClose - close a cursor */
840   fstreeFilter,                   /* xFilter - configure scan constraints */
841   fstreeNext,                     /* xNext - advance a cursor */
842   fstreeEof,                      /* xEof - check for end of scan */
843   fstreeColumn,                   /* xColumn - read data */
844   fstreeRowid,                    /* xRowid - read data */
845   0,                              /* xUpdate */
846   0,                              /* xBegin */
847   0,                              /* xSync */
848   0,                              /* xCommit */
849   0,                              /* xRollback */
850   0,                              /* xFindMethod */
851   0,                              /* xRename */
852 };
853 
854 /*
855 ** Decode a pointer to an sqlite3 object.
856 */
857 extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb);
858 
859 /*
860 ** Register the echo virtual table module.
861 */
862 static int register_fs_module(
863   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
864   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
865   int objc,              /* Number of arguments */
866   Tcl_Obj *CONST objv[]  /* Command arguments */
867 ){
868   sqlite3 *db;
869   if( objc!=2 ){
870     Tcl_WrongNumArgs(interp, 1, objv, "DB");
871     return TCL_ERROR;
872   }
873   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
874 #ifndef SQLITE_OMIT_VIRTUALTABLE
875   sqlite3_create_module(db, "fs", &fsModule, (void *)interp);
876   sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
877   sqlite3_create_module(db, "fstree", &fstreeModule, 0);
878 #endif
879   return TCL_OK;
880 }
881 
882 #endif
883 
884 
885 /*
886 ** Register commands with the TCL interpreter.
887 */
888 int Sqlitetestfs_Init(Tcl_Interp *interp){
889 #ifndef SQLITE_OMIT_VIRTUALTABLE
890   static struct {
891      char *zName;
892      Tcl_ObjCmdProc *xProc;
893      void *clientData;
894   } aObjCmd[] = {
895      { "register_fs_module",   register_fs_module, 0 },
896   };
897   int i;
898   for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
899     Tcl_CreateObjCommand(interp, aObjCmd[i].zName,
900         aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
901   }
902 #endif
903   return TCL_OK;
904 }
905