xref: /sqlite-3.40.0/src/test_fs.c (revision 8ccdef6b)
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   /* Allocate an extra 256 bytes because it is undefined how big dirent.d_name
206   ** is and we need enough space.  Linux provides plenty already, but
207   ** Solaris only provides one byte. */
208   pCur = (FsdirCsr*)sqlite3_malloc(sizeof(FsdirCsr)+256);
209   if( pCur==0 ) return SQLITE_NOMEM;
210   memset(pCur, 0, sizeof(FsdirCsr));
211   *ppCursor = &pCur->base;
212   return SQLITE_OK;
213 }
214 
215 /*
216 ** Close a fsdir cursor.
217 */
218 static int fsdirClose(sqlite3_vtab_cursor *cur){
219   FsdirCsr *pCur = (FsdirCsr*)cur;
220   if( pCur->pDir ) closedir(pCur->pDir);
221   sqlite3_free(pCur->zDir);
222   sqlite3_free(pCur);
223   return SQLITE_OK;
224 }
225 
226 /*
227 ** Skip the cursor to the next entry.
228 */
229 static int fsdirNext(sqlite3_vtab_cursor *cur){
230   FsdirCsr *pCsr = (FsdirCsr*)cur;
231 
232   if( pCsr->pDir ){
233     struct DIRENT *pRes = 0;
234     readdir_r(pCsr->pDir, &pCsr->entry, &pRes);
235     if( pRes==0 ){
236       closedir(pCsr->pDir);
237       pCsr->pDir = 0;
238     }
239     pCsr->iRowid++;
240   }
241 
242   return SQLITE_OK;
243 }
244 
245 /*
246 ** xFilter method implementation.
247 */
248 static int fsdirFilter(
249   sqlite3_vtab_cursor *pVtabCursor,
250   int idxNum, const char *idxStr,
251   int argc, sqlite3_value **argv
252 ){
253   FsdirCsr *pCsr = (FsdirCsr*)pVtabCursor;
254   const char *zDir;
255   int nDir;
256 
257 
258   if( idxNum!=1 || argc!=1 ){
259     return SQLITE_ERROR;
260   }
261 
262   pCsr->iRowid = 0;
263   sqlite3_free(pCsr->zDir);
264   if( pCsr->pDir ){
265     closedir(pCsr->pDir);
266     pCsr->pDir = 0;
267   }
268 
269   zDir = (const char*)sqlite3_value_text(argv[0]);
270   nDir = sqlite3_value_bytes(argv[0]);
271   pCsr->zDir = sqlite3_malloc(nDir+1);
272   if( pCsr->zDir==0 ) return SQLITE_NOMEM;
273   memcpy(pCsr->zDir, zDir, nDir+1);
274 
275   pCsr->pDir = opendir(pCsr->zDir);
276   return fsdirNext(pVtabCursor);
277 }
278 
279 /*
280 ** xEof method implementation.
281 */
282 static int fsdirEof(sqlite3_vtab_cursor *cur){
283   FsdirCsr *pCsr = (FsdirCsr*)cur;
284   return pCsr->pDir==0;
285 }
286 
287 /*
288 ** xColumn method implementation.
289 */
290 static int fsdirColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
291   FsdirCsr *pCsr = (FsdirCsr*)cur;
292   switch( i ){
293     case 0: /* dir */
294       sqlite3_result_text(ctx, pCsr->zDir, -1, SQLITE_STATIC);
295       break;
296 
297     case 1: /* name */
298       sqlite3_result_text(ctx, pCsr->entry.d_name, -1, SQLITE_TRANSIENT);
299       break;
300 
301     default:
302       assert( 0 );
303   }
304 
305   return SQLITE_OK;
306 }
307 
308 /*
309 ** xRowid method implementation.
310 */
311 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
312   FsdirCsr *pCsr = (FsdirCsr*)cur;
313   *pRowid = pCsr->iRowid;
314   return SQLITE_OK;
315 }
316 /*
317 ** End of fsdir implementation.
318 *************************************************************************/
319 
320 /*************************************************************************
321 ** Start of fstree implementation.
322 */
323 typedef struct FstreeVtab FstreeVtab;
324 typedef struct FstreeCsr FstreeCsr;
325 struct FstreeVtab {
326   sqlite3_vtab base;
327   sqlite3 *db;
328 };
329 
330 struct FstreeCsr {
331   sqlite3_vtab_cursor base;
332   sqlite3_stmt *pStmt;            /* Statement to list paths */
333   int fd;                         /* File descriptor open on current path */
334 };
335 
336 /*
337 ** This function is the implementation of both the xConnect and xCreate
338 ** methods of the fstree virtual table.
339 **
340 ** The argv[] array contains the following:
341 **
342 **   argv[0]   -> module name  ("fs")
343 **   argv[1]   -> database name
344 **   argv[2]   -> table name
345 **   argv[...] -> other module argument fields.
346 */
347 static int fstreeConnect(
348   sqlite3 *db,
349   void *pAux,
350   int argc, const char *const*argv,
351   sqlite3_vtab **ppVtab,
352   char **pzErr
353 ){
354   FstreeVtab *pTab;
355 
356   if( argc!=3 ){
357     *pzErr = sqlite3_mprintf("wrong number of arguments");
358     return SQLITE_ERROR;
359   }
360 
361   pTab = (FstreeVtab *)sqlite3_malloc(sizeof(FstreeVtab));
362   if( !pTab ) return SQLITE_NOMEM;
363   memset(pTab, 0, sizeof(FstreeVtab));
364   pTab->db = db;
365 
366   *ppVtab = &pTab->base;
367   sqlite3_declare_vtab(db, "CREATE TABLE xyz(path, size, data);");
368 
369   return SQLITE_OK;
370 }
371 
372 /*
373 ** xDestroy/xDisconnect implementation.
374 */
375 static int fstreeDisconnect(sqlite3_vtab *pVtab){
376   sqlite3_free(pVtab);
377   return SQLITE_OK;
378 }
379 
380 /*
381 ** xBestIndex implementation. The only constraint supported is:
382 **
383 **   (dir = ?)
384 */
385 static int fstreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
386   int ii;
387 
388   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
389     struct sqlite3_index_constraint const *p = &pIdxInfo->aConstraint[ii];
390     if( p->iColumn==0 && p->usable && (
391           p->op==SQLITE_INDEX_CONSTRAINT_GLOB
392        || p->op==SQLITE_INDEX_CONSTRAINT_LIKE
393        || p->op==SQLITE_INDEX_CONSTRAINT_EQ
394     )){
395       struct sqlite3_index_constraint_usage *pUsage;
396       pUsage = &pIdxInfo->aConstraintUsage[ii];
397       pIdxInfo->idxNum = p->op;
398       pUsage->argvIndex = 1;
399       pIdxInfo->estimatedCost = 100000.0;
400       return SQLITE_OK;
401     }
402   }
403 
404   pIdxInfo->estimatedCost = 1000000000.0;
405   return SQLITE_OK;
406 }
407 
408 /*
409 ** xOpen implementation.
410 **
411 ** Open a new fstree cursor.
412 */
413 static int fstreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
414   FstreeCsr *pCur;
415   pCur = (FstreeCsr*)sqlite3_malloc(sizeof(FstreeCsr));
416   if( pCur==0 ) return SQLITE_NOMEM;
417   memset(pCur, 0, sizeof(FstreeCsr));
418   pCur->fd = -1;
419   *ppCursor = &pCur->base;
420   return SQLITE_OK;
421 }
422 
423 static void fstreeCloseFd(FstreeCsr *pCsr){
424   if( pCsr->fd>=0 ){
425     close(pCsr->fd);
426     pCsr->fd = -1;
427   }
428 }
429 
430 /*
431 ** Close a fstree cursor.
432 */
433 static int fstreeClose(sqlite3_vtab_cursor *cur){
434   FstreeCsr *pCsr = (FstreeCsr*)cur;
435   sqlite3_finalize(pCsr->pStmt);
436   fstreeCloseFd(pCsr);
437   sqlite3_free(pCsr);
438   return SQLITE_OK;
439 }
440 
441 /*
442 ** Skip the cursor to the next entry.
443 */
444 static int fstreeNext(sqlite3_vtab_cursor *cur){
445   FstreeCsr *pCsr = (FstreeCsr*)cur;
446   int rc;
447 
448   fstreeCloseFd(pCsr);
449   rc = sqlite3_step(pCsr->pStmt);
450   if( rc!=SQLITE_ROW ){
451     rc = sqlite3_finalize(pCsr->pStmt);
452     pCsr->pStmt = 0;
453   }else{
454     rc = SQLITE_OK;
455     pCsr->fd = open((const char*)sqlite3_column_text(pCsr->pStmt, 0), O_RDONLY);
456   }
457 
458   return rc;
459 }
460 
461 /*
462 ** xFilter method implementation.
463 */
464 static int fstreeFilter(
465   sqlite3_vtab_cursor *pVtabCursor,
466   int idxNum, const char *idxStr,
467   int argc, sqlite3_value **argv
468 ){
469   FstreeCsr *pCsr = (FstreeCsr*)pVtabCursor;
470   FstreeVtab *pTab = (FstreeVtab*)(pCsr->base.pVtab);
471   int rc;
472   const char *zSql =
473 "WITH r(d) AS ("
474 "  SELECT CASE WHEN dir=?2 THEN ?3 ELSE dir END || '/' || name "
475 "    FROM fsdir WHERE dir=?1 AND name NOT LIKE '.%'"
476 "  UNION ALL"
477 "  SELECT dir || '/' || name FROM r, fsdir WHERE dir=d AND name NOT LIKE '.%'"
478 ") SELECT d FROM r;";
479 
480   char *zRoot;
481   int nRoot;
482   char *zPrefix;
483   int nPrefix;
484   const char *zDir;
485   int nDir;
486   char aWild[2] = { '\0', '\0' };
487 
488 #if SQLITE_OS_WIN
489   zRoot = sqlite3_mprintf("%s%c", getenv("SystemDrive"), '/');
490   nRoot = strlen(zRoot);
491   zPrefix = sqlite3_mprintf("%s", getenv("SystemDrive"));
492   nPrefix = strlen(zPrefix);
493 #else
494   zRoot = "/";
495   nRoot = 1;
496   zPrefix = "";
497   nPrefix = 0;
498 #endif
499 
500   zDir = zRoot;
501   nDir = nRoot;
502 
503   fstreeCloseFd(pCsr);
504   sqlite3_finalize(pCsr->pStmt);
505   pCsr->pStmt = 0;
506   rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
507   if( rc!=SQLITE_OK ) return rc;
508 
509   if( idxNum ){
510     const char *zQuery = (const char*)sqlite3_value_text(argv[0]);
511     switch( idxNum ){
512       case SQLITE_INDEX_CONSTRAINT_GLOB:
513         aWild[0] = '*';
514         aWild[1] = '?';
515         break;
516       case SQLITE_INDEX_CONSTRAINT_LIKE:
517         aWild[0] = '_';
518         aWild[1] = '%';
519         break;
520     }
521 
522     if( sqlite3_strnicmp(zQuery, zPrefix, nPrefix)==0 ){
523       int i;
524       for(i=nPrefix; zQuery[i]; i++){
525         if( zQuery[i]==aWild[0] || zQuery[i]==aWild[1] ) break;
526         if( zQuery[i]=='/' ) nDir = i;
527       }
528       zDir = zQuery;
529     }
530   }
531 
532   sqlite3_bind_text(pCsr->pStmt, 1, zDir, nDir, SQLITE_TRANSIENT);
533   sqlite3_bind_text(pCsr->pStmt, 2, zRoot, nRoot, SQLITE_TRANSIENT);
534   sqlite3_bind_text(pCsr->pStmt, 3, zPrefix, nPrefix, SQLITE_TRANSIENT);
535 
536 #if SQLITE_OS_WIN
537   sqlite3_free(zPrefix);
538   sqlite3_free(zRoot);
539 #endif
540 
541   return fstreeNext(pVtabCursor);
542 }
543 
544 /*
545 ** xEof method implementation.
546 */
547 static int fstreeEof(sqlite3_vtab_cursor *cur){
548   FstreeCsr *pCsr = (FstreeCsr*)cur;
549   return pCsr->pStmt==0;
550 }
551 
552 /*
553 ** xColumn method implementation.
554 */
555 static int fstreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
556   FstreeCsr *pCsr = (FstreeCsr*)cur;
557   if( i==0 ){      /* path */
558     sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pStmt, 0));
559   }else{
560     struct stat sBuf;
561     fstat(pCsr->fd, &sBuf);
562 
563     if( S_ISREG(sBuf.st_mode) ){
564       if( i==1 ){
565         sqlite3_result_int64(ctx, sBuf.st_size);
566       }else{
567         int nRead;
568         char *aBuf = sqlite3_malloc(sBuf.st_mode+1);
569         if( !aBuf ) return SQLITE_NOMEM;
570         nRead = read(pCsr->fd, aBuf, sBuf.st_mode);
571         if( nRead!=sBuf.st_mode ){
572           return SQLITE_IOERR;
573         }
574         sqlite3_result_blob(ctx, aBuf, nRead, SQLITE_TRANSIENT);
575         sqlite3_free(aBuf);
576       }
577     }
578   }
579 
580   return SQLITE_OK;
581 }
582 
583 /*
584 ** xRowid method implementation.
585 */
586 static int fstreeRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
587   *pRowid = 0;
588   return SQLITE_OK;
589 }
590 /*
591 ** End of fstree implementation.
592 *************************************************************************/
593 
594 
595 
596 
597 /*
598 ** This function is the implementation of both the xConnect and xCreate
599 ** methods of the fs virtual table.
600 **
601 ** The argv[] array contains the following:
602 **
603 **   argv[0]   -> module name  ("fs")
604 **   argv[1]   -> database name
605 **   argv[2]   -> table name
606 **   argv[...] -> other module argument fields.
607 */
608 static int fsConnect(
609   sqlite3 *db,
610   void *pAux,
611   int argc, const char *const*argv,
612   sqlite3_vtab **ppVtab,
613   char **pzErr
614 ){
615   fs_vtab *pVtab;
616   int nByte;
617   const char *zTbl;
618   const char *zDb = argv[1];
619 
620   if( argc!=4 ){
621     *pzErr = sqlite3_mprintf("wrong number of arguments");
622     return SQLITE_ERROR;
623   }
624   zTbl = argv[3];
625 
626   nByte = sizeof(fs_vtab) + (int)strlen(zTbl) + 1 + (int)strlen(zDb) + 1;
627   pVtab = (fs_vtab *)sqlite3MallocZero( nByte );
628   if( !pVtab ) return SQLITE_NOMEM;
629 
630   pVtab->zTbl = (char *)&pVtab[1];
631   pVtab->zDb = &pVtab->zTbl[strlen(zTbl)+1];
632   pVtab->db = db;
633   memcpy(pVtab->zTbl, zTbl, strlen(zTbl));
634   memcpy(pVtab->zDb, zDb, strlen(zDb));
635   *ppVtab = &pVtab->base;
636   sqlite3_declare_vtab(db, "CREATE TABLE x(path TEXT, data TEXT)");
637 
638   return SQLITE_OK;
639 }
640 /* Note that for this virtual table, the xCreate and xConnect
641 ** methods are identical. */
642 
643 static int fsDisconnect(sqlite3_vtab *pVtab){
644   sqlite3_free(pVtab);
645   return SQLITE_OK;
646 }
647 /* The xDisconnect and xDestroy methods are also the same */
648 
649 /*
650 ** Open a new fs cursor.
651 */
652 static int fsOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
653   fs_cursor *pCur;
654   pCur = sqlite3MallocZero(sizeof(fs_cursor));
655   *ppCursor = &pCur->base;
656   return SQLITE_OK;
657 }
658 
659 /*
660 ** Close a fs cursor.
661 */
662 static int fsClose(sqlite3_vtab_cursor *cur){
663   fs_cursor *pCur = (fs_cursor *)cur;
664   sqlite3_finalize(pCur->pStmt);
665   sqlite3_free(pCur->zBuf);
666   sqlite3_free(pCur);
667   return SQLITE_OK;
668 }
669 
670 static int fsNext(sqlite3_vtab_cursor *cur){
671   fs_cursor *pCur = (fs_cursor *)cur;
672   int rc;
673 
674   rc = sqlite3_step(pCur->pStmt);
675   if( rc==SQLITE_ROW || rc==SQLITE_DONE ) rc = SQLITE_OK;
676 
677   return rc;
678 }
679 
680 static int fsFilter(
681   sqlite3_vtab_cursor *pVtabCursor,
682   int idxNum, const char *idxStr,
683   int argc, sqlite3_value **argv
684 ){
685   int rc;
686   fs_cursor *pCur = (fs_cursor *)pVtabCursor;
687   fs_vtab *p = (fs_vtab *)(pVtabCursor->pVtab);
688 
689   assert( (idxNum==0 && argc==0) || (idxNum==1 && argc==1) );
690   if( idxNum==1 ){
691     char *zStmt = sqlite3_mprintf(
692         "SELECT * FROM %Q.%Q WHERE rowid=?", p->zDb, p->zTbl);
693     if( !zStmt ) return SQLITE_NOMEM;
694     rc = sqlite3_prepare_v2(p->db, zStmt, -1, &pCur->pStmt, 0);
695     sqlite3_free(zStmt);
696     if( rc==SQLITE_OK ){
697       sqlite3_bind_value(pCur->pStmt, 1, argv[0]);
698     }
699   }else{
700     char *zStmt = sqlite3_mprintf("SELECT * FROM %Q.%Q", p->zDb, p->zTbl);
701     if( !zStmt ) return SQLITE_NOMEM;
702     rc = sqlite3_prepare_v2(p->db, zStmt, -1, &pCur->pStmt, 0);
703     sqlite3_free(zStmt);
704   }
705 
706   if( rc==SQLITE_OK ){
707     rc = fsNext(pVtabCursor);
708   }
709   return rc;
710 }
711 
712 static int fsColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
713   fs_cursor *pCur = (fs_cursor*)cur;
714 
715   assert( i==0 || i==1 || i==2 );
716   if( i==0 ){
717     sqlite3_result_value(ctx, sqlite3_column_value(pCur->pStmt, 0));
718   }else{
719     const char *zFile = (const char *)sqlite3_column_text(pCur->pStmt, 1);
720     struct stat sbuf;
721     int fd;
722 
723     int n;
724     fd = open(zFile, O_RDONLY);
725     if( fd<0 ) return SQLITE_IOERR;
726     fstat(fd, &sbuf);
727 
728     if( sbuf.st_size>=pCur->nAlloc ){
729       int nNew = sbuf.st_size*2;
730       char *zNew;
731       if( nNew<1024 ) nNew = 1024;
732 
733       zNew = sqlite3Realloc(pCur->zBuf, nNew);
734       if( zNew==0 ){
735         close(fd);
736         return SQLITE_NOMEM;
737       }
738       pCur->zBuf = zNew;
739       pCur->nAlloc = nNew;
740     }
741 
742     n = (int)read(fd, pCur->zBuf, sbuf.st_size);
743     close(fd);
744     if( n!=sbuf.st_size ) return SQLITE_ERROR;
745     pCur->nBuf = sbuf.st_size;
746     pCur->zBuf[pCur->nBuf] = '\0';
747 
748     sqlite3_result_text(ctx, pCur->zBuf, -1, SQLITE_TRANSIENT);
749   }
750   return SQLITE_OK;
751 }
752 
753 static int fsRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
754   fs_cursor *pCur = (fs_cursor*)cur;
755   *pRowid = sqlite3_column_int64(pCur->pStmt, 0);
756   return SQLITE_OK;
757 }
758 
759 static int fsEof(sqlite3_vtab_cursor *cur){
760   fs_cursor *pCur = (fs_cursor*)cur;
761   return (sqlite3_data_count(pCur->pStmt)==0);
762 }
763 
764 static int fsBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
765   int ii;
766 
767   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
768     struct sqlite3_index_constraint const *pCons = &pIdxInfo->aConstraint[ii];
769     if( pCons->iColumn<0 && pCons->usable
770            && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
771       struct sqlite3_index_constraint_usage *pUsage;
772       pUsage = &pIdxInfo->aConstraintUsage[ii];
773       pUsage->omit = 0;
774       pUsage->argvIndex = 1;
775       pIdxInfo->idxNum = 1;
776       pIdxInfo->estimatedCost = 1.0;
777       break;
778     }
779   }
780 
781   return SQLITE_OK;
782 }
783 
784 /*
785 ** A virtual table module that provides read-only access to a
786 ** Tcl global variable namespace.
787 */
788 static sqlite3_module fsModule = {
789   0,                         /* iVersion */
790   fsConnect,
791   fsConnect,
792   fsBestIndex,
793   fsDisconnect,
794   fsDisconnect,
795   fsOpen,                      /* xOpen - open a cursor */
796   fsClose,                     /* xClose - close a cursor */
797   fsFilter,                    /* xFilter - configure scan constraints */
798   fsNext,                      /* xNext - advance a cursor */
799   fsEof,                       /* xEof - check for end of scan */
800   fsColumn,                    /* xColumn - read data */
801   fsRowid,                     /* xRowid - read data */
802   0,                           /* xUpdate */
803   0,                           /* xBegin */
804   0,                           /* xSync */
805   0,                           /* xCommit */
806   0,                           /* xRollback */
807   0,                           /* xFindMethod */
808   0,                           /* xRename */
809 };
810 
811 static sqlite3_module fsdirModule = {
812   0,                              /* iVersion */
813   fsdirConnect,                   /* xCreate */
814   fsdirConnect,                   /* xConnect */
815   fsdirBestIndex,                 /* xBestIndex */
816   fsdirDisconnect,                /* xDisconnect */
817   fsdirDisconnect,                /* xDestroy */
818   fsdirOpen,                      /* xOpen - open a cursor */
819   fsdirClose,                     /* xClose - close a cursor */
820   fsdirFilter,                    /* xFilter - configure scan constraints */
821   fsdirNext,                      /* xNext - advance a cursor */
822   fsdirEof,                       /* xEof - check for end of scan */
823   fsdirColumn,                    /* xColumn - read data */
824   fsdirRowid,                     /* xRowid - read data */
825   0,                              /* xUpdate */
826   0,                              /* xBegin */
827   0,                              /* xSync */
828   0,                              /* xCommit */
829   0,                              /* xRollback */
830   0,                              /* xFindMethod */
831   0,                              /* xRename */
832 };
833 
834 static sqlite3_module fstreeModule = {
835   0,                              /* iVersion */
836   fstreeConnect,                  /* xCreate */
837   fstreeConnect,                  /* xConnect */
838   fstreeBestIndex,                /* xBestIndex */
839   fstreeDisconnect,               /* xDisconnect */
840   fstreeDisconnect,               /* xDestroy */
841   fstreeOpen,                     /* xOpen - open a cursor */
842   fstreeClose,                    /* xClose - close a cursor */
843   fstreeFilter,                   /* xFilter - configure scan constraints */
844   fstreeNext,                     /* xNext - advance a cursor */
845   fstreeEof,                      /* xEof - check for end of scan */
846   fstreeColumn,                   /* xColumn - read data */
847   fstreeRowid,                    /* xRowid - read data */
848   0,                              /* xUpdate */
849   0,                              /* xBegin */
850   0,                              /* xSync */
851   0,                              /* xCommit */
852   0,                              /* xRollback */
853   0,                              /* xFindMethod */
854   0,                              /* xRename */
855 };
856 
857 /*
858 ** Decode a pointer to an sqlite3 object.
859 */
860 extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb);
861 
862 /*
863 ** Register the echo virtual table module.
864 */
865 static int register_fs_module(
866   ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
867   Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
868   int objc,              /* Number of arguments */
869   Tcl_Obj *CONST objv[]  /* Command arguments */
870 ){
871   sqlite3 *db;
872   if( objc!=2 ){
873     Tcl_WrongNumArgs(interp, 1, objv, "DB");
874     return TCL_ERROR;
875   }
876   if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
877 #ifndef SQLITE_OMIT_VIRTUALTABLE
878   sqlite3_create_module(db, "fs", &fsModule, (void *)interp);
879   sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
880   sqlite3_create_module(db, "fstree", &fstreeModule, 0);
881 #endif
882   return TCL_OK;
883 }
884 
885 #endif
886 
887 
888 /*
889 ** Register commands with the TCL interpreter.
890 */
891 int Sqlitetestfs_Init(Tcl_Interp *interp){
892 #ifndef SQLITE_OMIT_VIRTUALTABLE
893   static struct {
894      char *zName;
895      Tcl_ObjCmdProc *xProc;
896      void *clientData;
897   } aObjCmd[] = {
898      { "register_fs_module",   register_fs_module, 0 },
899   };
900   int i;
901   for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
902     Tcl_CreateObjCommand(interp, aObjCmd[i].zName,
903         aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
904   }
905 #endif
906   return TCL_OK;
907 }
908