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