xref: /sqlite-3.40.0/src/dbstat.c (revision f9dc5f77)
1 /*
2 ** 2010 July 12
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 **
13 ** This file contains an implementation of the "dbstat" virtual table.
14 **
15 ** The dbstat virtual table is used to extract low-level formatting
16 ** information from an SQLite database in order to implement the
17 ** "sqlite3_analyzer" utility.  See the ../tool/spaceanal.tcl script
18 ** for an example implementation.
19 **
20 ** Additional information is available on the "dbstat.html" page of the
21 ** official SQLite documentation.
22 */
23 
24 #include "sqliteInt.h"   /* Requires access to internal data structures */
25 #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
26     && !defined(SQLITE_OMIT_VIRTUALTABLE)
27 
28 /*
29 ** Page paths:
30 **
31 **   The value of the 'path' column describes the path taken from the
32 **   root-node of the b-tree structure to each page. The value of the
33 **   root-node path is '/'.
34 **
35 **   The value of the path for the left-most child page of the root of
36 **   a b-tree is '/000/'. (Btrees store content ordered from left to right
37 **   so the pages to the left have smaller keys than the pages to the right.)
38 **   The next to left-most child of the root page is
39 **   '/001', and so on, each sibling page identified by a 3-digit hex
40 **   value. The children of the 451st left-most sibling have paths such
41 **   as '/1c2/000/, '/1c2/001/' etc.
42 **
43 **   Overflow pages are specified by appending a '+' character and a
44 **   six-digit hexadecimal value to the path to the cell they are linked
45 **   from. For example, the three overflow pages in a chain linked from
46 **   the left-most cell of the 450th child of the root page are identified
47 **   by the paths:
48 **
49 **      '/1c2/000+000000'         // First page in overflow chain
50 **      '/1c2/000+000001'         // Second page in overflow chain
51 **      '/1c2/000+000002'         // Third page in overflow chain
52 **
53 **   If the paths are sorted using the BINARY collation sequence, then
54 **   the overflow pages associated with a cell will appear earlier in the
55 **   sort-order than its child page:
56 **
57 **      '/1c2/000/'               // Left-most child of 451st child of root
58 */
59 #define VTAB_SCHEMA                                                         \
60   "CREATE TABLE xx( "                                                       \
61   "  name       TEXT,             /* Name of table or index */"             \
62   "  path       TEXT,             /* Path to page from root */"             \
63   "  pageno     INTEGER,          /* Page number */"                        \
64   "  pagetype   TEXT,             /* 'internal', 'leaf' or 'overflow' */"   \
65   "  ncell      INTEGER,          /* Cells on page (0 for overflow) */"     \
66   "  payload    INTEGER,          /* Bytes of payload on this page */"      \
67   "  unused     INTEGER,          /* Bytes of unused space on this page */" \
68   "  mx_payload INTEGER,          /* Largest payload size of all cells */"  \
69   "  pgoffset   INTEGER,          /* Offset of page in file */"             \
70   "  pgsize     INTEGER,          /* Size of the page */"                   \
71   "  schema     TEXT HIDDEN       /* Database schema being analyzed */"     \
72   ");"
73 
74 
75 typedef struct StatTable StatTable;
76 typedef struct StatCursor StatCursor;
77 typedef struct StatPage StatPage;
78 typedef struct StatCell StatCell;
79 
80 struct StatCell {
81   int nLocal;                     /* Bytes of local payload */
82   u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
83   int nOvfl;                      /* Entries in aOvfl[] */
84   u32 *aOvfl;                     /* Array of overflow page numbers */
85   int nLastOvfl;                  /* Bytes of payload on final overflow page */
86   int iOvfl;                      /* Iterates through aOvfl[] */
87 };
88 
89 struct StatPage {
90   u32 iPgno;
91   DbPage *pPg;
92   int iCell;
93 
94   char *zPath;                    /* Path to this page */
95 
96   /* Variables populated by statDecodePage(): */
97   u8 flags;                       /* Copy of flags byte */
98   int nCell;                      /* Number of cells on page */
99   int nUnused;                    /* Number of unused bytes on page */
100   StatCell *aCell;                /* Array of parsed cells */
101   u32 iRightChildPg;              /* Right-child page number (or 0) */
102   int nMxPayload;                 /* Largest payload of any cell on this page */
103 };
104 
105 struct StatCursor {
106   sqlite3_vtab_cursor base;
107   sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
108   int isEof;                      /* After pStmt has returned SQLITE_DONE */
109   int iDb;                        /* Schema used for this query */
110 
111   StatPage aPage[32];
112   int iPage;                      /* Current entry in aPage[] */
113 
114   /* Values to return. */
115   char *zName;                    /* Value of 'name' column */
116   char *zPath;                    /* Value of 'path' column */
117   u32 iPageno;                    /* Value of 'pageno' column */
118   char *zPagetype;                /* Value of 'pagetype' column */
119   int nCell;                      /* Value of 'ncell' column */
120   int nPayload;                   /* Value of 'payload' column */
121   int nUnused;                    /* Value of 'unused' column */
122   int nMxPayload;                 /* Value of 'mx_payload' column */
123   i64 iOffset;                    /* Value of 'pgOffset' column */
124   int szPage;                     /* Value of 'pgSize' column */
125 };
126 
127 struct StatTable {
128   sqlite3_vtab base;
129   sqlite3 *db;
130   int iDb;                        /* Index of database to analyze */
131 };
132 
133 #ifndef get2byte
134 # define get2byte(x)   ((x)[0]<<8 | (x)[1])
135 #endif
136 
137 /*
138 ** Connect to or create a statvfs virtual table.
139 */
140 static int statConnect(
141   sqlite3 *db,
142   void *pAux,
143   int argc, const char *const*argv,
144   sqlite3_vtab **ppVtab,
145   char **pzErr
146 ){
147   StatTable *pTab = 0;
148   int rc = SQLITE_OK;
149   int iDb;
150 
151   if( argc>=4 ){
152     Token nm;
153     sqlite3TokenInit(&nm, (char*)argv[3]);
154     iDb = sqlite3FindDb(db, &nm);
155     if( iDb<0 ){
156       *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
157       return SQLITE_ERROR;
158     }
159   }else{
160     iDb = 0;
161   }
162   rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
163   if( rc==SQLITE_OK ){
164     pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
165     if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
166   }
167 
168   assert( rc==SQLITE_OK || pTab==0 );
169   if( rc==SQLITE_OK ){
170     memset(pTab, 0, sizeof(StatTable));
171     pTab->db = db;
172     pTab->iDb = iDb;
173   }
174 
175   *ppVtab = (sqlite3_vtab*)pTab;
176   return rc;
177 }
178 
179 /*
180 ** Disconnect from or destroy a statvfs virtual table.
181 */
182 static int statDisconnect(sqlite3_vtab *pVtab){
183   sqlite3_free(pVtab);
184   return SQLITE_OK;
185 }
186 
187 /*
188 ** There is no "best-index". This virtual table always does a linear
189 ** scan.  However, a schema=? constraint should cause this table to
190 ** operate on a different database schema, so check for it.
191 **
192 ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
193 */
194 static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
195   int i;
196 
197   pIdxInfo->estimatedCost = 1.0e6;  /* Initial cost estimate */
198 
199   /* Look for a valid schema=? constraint.  If found, change the idxNum to
200   ** 1 and request the value of that constraint be sent to xFilter.  And
201   ** lower the cost estimate to encourage the constrained version to be
202   ** used.
203   */
204   for(i=0; i<pIdxInfo->nConstraint; i++){
205     if( pIdxInfo->aConstraint[i].usable==0 ) continue;
206     if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
207     if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
208     pIdxInfo->idxNum = 1;
209     pIdxInfo->estimatedCost = 1.0;
210     pIdxInfo->aConstraintUsage[i].argvIndex = 1;
211     pIdxInfo->aConstraintUsage[i].omit = 1;
212     break;
213   }
214 
215 
216   /* Records are always returned in ascending order of (name, path).
217   ** If this will satisfy the client, set the orderByConsumed flag so that
218   ** SQLite does not do an external sort.
219   */
220   if( ( pIdxInfo->nOrderBy==1
221      && pIdxInfo->aOrderBy[0].iColumn==0
222      && pIdxInfo->aOrderBy[0].desc==0
223      ) ||
224       ( pIdxInfo->nOrderBy==2
225      && pIdxInfo->aOrderBy[0].iColumn==0
226      && pIdxInfo->aOrderBy[0].desc==0
227      && pIdxInfo->aOrderBy[1].iColumn==1
228      && pIdxInfo->aOrderBy[1].desc==0
229      )
230   ){
231     pIdxInfo->orderByConsumed = 1;
232   }
233 
234   return SQLITE_OK;
235 }
236 
237 /*
238 ** Open a new statvfs cursor.
239 */
240 static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
241   StatTable *pTab = (StatTable *)pVTab;
242   StatCursor *pCsr;
243 
244   pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
245   if( pCsr==0 ){
246     return SQLITE_NOMEM_BKPT;
247   }else{
248     memset(pCsr, 0, sizeof(StatCursor));
249     pCsr->base.pVtab = pVTab;
250     pCsr->iDb = pTab->iDb;
251   }
252 
253   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
254   return SQLITE_OK;
255 }
256 
257 static void statClearCells(StatPage *p){
258   int i;
259   if( p->aCell ){
260     for(i=0; i<p->nCell; i++){
261       sqlite3_free(p->aCell[i].aOvfl);
262     }
263     sqlite3_free(p->aCell);
264   }
265   p->nCell = 0;
266   p->aCell = 0;
267 }
268 
269 static void statClearPage(StatPage *p){
270   statClearCells(p);
271   sqlite3PagerUnref(p->pPg);
272   sqlite3_free(p->zPath);
273   memset(p, 0, sizeof(StatPage));
274 }
275 
276 static void statResetCsr(StatCursor *pCsr){
277   int i;
278   sqlite3_reset(pCsr->pStmt);
279   for(i=0; i<ArraySize(pCsr->aPage); i++){
280     statClearPage(&pCsr->aPage[i]);
281   }
282   pCsr->iPage = 0;
283   sqlite3_free(pCsr->zPath);
284   pCsr->zPath = 0;
285   pCsr->isEof = 0;
286 }
287 
288 /*
289 ** Close a statvfs cursor.
290 */
291 static int statClose(sqlite3_vtab_cursor *pCursor){
292   StatCursor *pCsr = (StatCursor *)pCursor;
293   statResetCsr(pCsr);
294   sqlite3_finalize(pCsr->pStmt);
295   sqlite3_free(pCsr);
296   return SQLITE_OK;
297 }
298 
299 static void getLocalPayload(
300   int nUsable,                    /* Usable bytes per page */
301   u8 flags,                       /* Page flags */
302   int nTotal,                     /* Total record (payload) size */
303   int *pnLocal                    /* OUT: Bytes stored locally */
304 ){
305   int nLocal;
306   int nMinLocal;
307   int nMaxLocal;
308 
309   if( flags==0x0D ){              /* Table leaf node */
310     nMinLocal = (nUsable - 12) * 32 / 255 - 23;
311     nMaxLocal = nUsable - 35;
312   }else{                          /* Index interior and leaf nodes */
313     nMinLocal = (nUsable - 12) * 32 / 255 - 23;
314     nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
315   }
316 
317   nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
318   if( nLocal>nMaxLocal ) nLocal = nMinLocal;
319   *pnLocal = nLocal;
320 }
321 
322 static int statDecodePage(Btree *pBt, StatPage *p){
323   int nUnused;
324   int iOff;
325   int nHdr;
326   int isLeaf;
327   int szPage;
328 
329   u8 *aData = sqlite3PagerGetData(p->pPg);
330   u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
331 
332   p->flags = aHdr[0];
333   if( p->flags==0x0A || p->flags==0x0D ){
334     isLeaf = 1;
335     nHdr = 8;
336   }else if( p->flags==0x05 || p->flags==0x02 ){
337     isLeaf = 0;
338     nHdr = 12;
339   }else{
340     goto statPageIsCorrupt;
341   }
342   if( p->iPgno==1 ) nHdr += 100;
343   p->nCell = get2byte(&aHdr[3]);
344   p->nMxPayload = 0;
345   szPage = sqlite3BtreeGetPageSize(pBt);
346 
347   nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
348   nUnused += (int)aHdr[7];
349   iOff = get2byte(&aHdr[1]);
350   while( iOff ){
351     int iNext;
352     if( iOff>=szPage ) goto statPageIsCorrupt;
353     nUnused += get2byte(&aData[iOff+2]);
354     iNext = get2byte(&aData[iOff]);
355     if( iNext<iOff+4 && iNext>0 ) goto statPageIsCorrupt;
356     iOff = iNext;
357   }
358   p->nUnused = nUnused;
359   p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
360 
361   if( p->nCell ){
362     int i;                        /* Used to iterate through cells */
363     int nUsable;                  /* Usable bytes per page */
364 
365     sqlite3BtreeEnter(pBt);
366     nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
367     sqlite3BtreeLeave(pBt);
368     p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
369     if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
370     memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
371 
372     for(i=0; i<p->nCell; i++){
373       StatCell *pCell = &p->aCell[i];
374 
375       iOff = get2byte(&aData[nHdr+i*2]);
376       if( iOff<nHdr || iOff>=szPage ) goto statPageIsCorrupt;
377       if( !isLeaf ){
378         pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
379         iOff += 4;
380       }
381       if( p->flags==0x05 ){
382         /* A table interior node. nPayload==0. */
383       }else{
384         u32 nPayload;             /* Bytes of payload total (local+overflow) */
385         int nLocal;               /* Bytes of payload stored locally */
386         iOff += getVarint32(&aData[iOff], nPayload);
387         if( p->flags==0x0D ){
388           u64 dummy;
389           iOff += sqlite3GetVarint(&aData[iOff], &dummy);
390         }
391         if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
392         getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
393         if( nLocal<0 ) goto statPageIsCorrupt;
394         pCell->nLocal = nLocal;
395         assert( nPayload>=(u32)nLocal );
396         assert( nLocal<=(nUsable-35) );
397         if( nPayload>(u32)nLocal ){
398           int j;
399           int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
400           if( iOff+nLocal>nUsable ) goto statPageIsCorrupt;
401           pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
402           pCell->nOvfl = nOvfl;
403           pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
404           if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
405           pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
406           for(j=1; j<nOvfl; j++){
407             int rc;
408             u32 iPrev = pCell->aOvfl[j-1];
409             DbPage *pPg = 0;
410             rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
411             if( rc!=SQLITE_OK ){
412               assert( pPg==0 );
413               return rc;
414             }
415             pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
416             sqlite3PagerUnref(pPg);
417           }
418         }
419       }
420     }
421   }
422 
423   return SQLITE_OK;
424 
425 statPageIsCorrupt:
426   p->flags = 0;
427   statClearCells(p);
428   return SQLITE_OK;
429 }
430 
431 /*
432 ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
433 ** the current value of pCsr->iPageno.
434 */
435 static void statSizeAndOffset(StatCursor *pCsr){
436   StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
437   Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
438   Pager *pPager = sqlite3BtreePager(pBt);
439   sqlite3_file *fd;
440   sqlite3_int64 x[2];
441 
442   /* The default page size and offset */
443   pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
444   pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
445 
446   /* If connected to a ZIPVFS backend, override the page size and
447   ** offset with actual values obtained from ZIPVFS.
448   */
449   fd = sqlite3PagerFile(pPager);
450   x[0] = pCsr->iPageno;
451   if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
452     pCsr->iOffset = x[0];
453     pCsr->szPage = (int)x[1];
454   }
455 }
456 
457 /*
458 ** Move a statvfs cursor to the next entry in the file.
459 */
460 static int statNext(sqlite3_vtab_cursor *pCursor){
461   int rc;
462   int nPayload;
463   char *z;
464   StatCursor *pCsr = (StatCursor *)pCursor;
465   StatTable *pTab = (StatTable *)pCursor->pVtab;
466   Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
467   Pager *pPager = sqlite3BtreePager(pBt);
468 
469   sqlite3_free(pCsr->zPath);
470   pCsr->zPath = 0;
471 
472 statNextRestart:
473   if( pCsr->aPage[0].pPg==0 ){
474     rc = sqlite3_step(pCsr->pStmt);
475     if( rc==SQLITE_ROW ){
476       int nPage;
477       u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
478       sqlite3PagerPagecount(pPager, &nPage);
479       if( nPage==0 ){
480         pCsr->isEof = 1;
481         return sqlite3_reset(pCsr->pStmt);
482       }
483       rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
484       pCsr->aPage[0].iPgno = iRoot;
485       pCsr->aPage[0].iCell = 0;
486       pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
487       pCsr->iPage = 0;
488       if( z==0 ) rc = SQLITE_NOMEM_BKPT;
489     }else{
490       pCsr->isEof = 1;
491       return sqlite3_reset(pCsr->pStmt);
492     }
493   }else{
494 
495     /* Page p itself has already been visited. */
496     StatPage *p = &pCsr->aPage[pCsr->iPage];
497 
498     while( p->iCell<p->nCell ){
499       StatCell *pCell = &p->aCell[p->iCell];
500       if( pCell->iOvfl<pCell->nOvfl ){
501         int nUsable;
502         sqlite3BtreeEnter(pBt);
503         nUsable = sqlite3BtreeGetPageSize(pBt) -
504                         sqlite3BtreeGetReserveNoMutex(pBt);
505         sqlite3BtreeLeave(pBt);
506         pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
507         pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
508         pCsr->zPagetype = "overflow";
509         pCsr->nCell = 0;
510         pCsr->nMxPayload = 0;
511         pCsr->zPath = z = sqlite3_mprintf(
512             "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
513         );
514         if( pCell->iOvfl<pCell->nOvfl-1 ){
515           pCsr->nUnused = 0;
516           pCsr->nPayload = nUsable - 4;
517         }else{
518           pCsr->nPayload = pCell->nLastOvfl;
519           pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
520         }
521         pCell->iOvfl++;
522         statSizeAndOffset(pCsr);
523         return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
524       }
525       if( p->iRightChildPg ) break;
526       p->iCell++;
527     }
528 
529     if( !p->iRightChildPg || p->iCell>p->nCell ){
530       statClearPage(p);
531       if( pCsr->iPage==0 ) return statNext(pCursor);
532       pCsr->iPage--;
533       goto statNextRestart; /* Tail recursion */
534     }
535     pCsr->iPage++;
536     assert( p==&pCsr->aPage[pCsr->iPage-1] );
537 
538     if( p->iCell==p->nCell ){
539       p[1].iPgno = p->iRightChildPg;
540     }else{
541       p[1].iPgno = p->aCell[p->iCell].iChildPg;
542     }
543     rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
544     p[1].iCell = 0;
545     p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
546     p->iCell++;
547     if( z==0 ) rc = SQLITE_NOMEM_BKPT;
548   }
549 
550 
551   /* Populate the StatCursor fields with the values to be returned
552   ** by the xColumn() and xRowid() methods.
553   */
554   if( rc==SQLITE_OK ){
555     int i;
556     StatPage *p = &pCsr->aPage[pCsr->iPage];
557     pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
558     pCsr->iPageno = p->iPgno;
559 
560     rc = statDecodePage(pBt, p);
561     if( rc==SQLITE_OK ){
562       statSizeAndOffset(pCsr);
563 
564       switch( p->flags ){
565         case 0x05:             /* table internal */
566         case 0x02:             /* index internal */
567           pCsr->zPagetype = "internal";
568           break;
569         case 0x0D:             /* table leaf */
570         case 0x0A:             /* index leaf */
571           pCsr->zPagetype = "leaf";
572           break;
573         default:
574           pCsr->zPagetype = "corrupted";
575           break;
576       }
577       pCsr->nCell = p->nCell;
578       pCsr->nUnused = p->nUnused;
579       pCsr->nMxPayload = p->nMxPayload;
580       pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
581       if( z==0 ) rc = SQLITE_NOMEM_BKPT;
582       nPayload = 0;
583       for(i=0; i<p->nCell; i++){
584         nPayload += p->aCell[i].nLocal;
585       }
586       pCsr->nPayload = nPayload;
587     }
588   }
589 
590   return rc;
591 }
592 
593 static int statEof(sqlite3_vtab_cursor *pCursor){
594   StatCursor *pCsr = (StatCursor *)pCursor;
595   return pCsr->isEof;
596 }
597 
598 static int statFilter(
599   sqlite3_vtab_cursor *pCursor,
600   int idxNum, const char *idxStr,
601   int argc, sqlite3_value **argv
602 ){
603   StatCursor *pCsr = (StatCursor *)pCursor;
604   StatTable *pTab = (StatTable*)(pCursor->pVtab);
605   char *zSql;
606   int rc = SQLITE_OK;
607   char *zMaster;
608 
609   if( idxNum==1 ){
610     const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
611     pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
612     if( pCsr->iDb<0 ){
613       sqlite3_free(pCursor->pVtab->zErrMsg);
614       pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
615       return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
616     }
617   }else{
618     pCsr->iDb = pTab->iDb;
619   }
620   statResetCsr(pCsr);
621   sqlite3_finalize(pCsr->pStmt);
622   pCsr->pStmt = 0;
623   zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
624   zSql = sqlite3_mprintf(
625       "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
626       "  UNION ALL  "
627       "SELECT name, rootpage, type"
628       "  FROM \"%w\".%s WHERE rootpage!=0"
629       "  ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
630   if( zSql==0 ){
631     return SQLITE_NOMEM_BKPT;
632   }else{
633     rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
634     sqlite3_free(zSql);
635   }
636 
637   if( rc==SQLITE_OK ){
638     rc = statNext(pCursor);
639   }
640   return rc;
641 }
642 
643 static int statColumn(
644   sqlite3_vtab_cursor *pCursor,
645   sqlite3_context *ctx,
646   int i
647 ){
648   StatCursor *pCsr = (StatCursor *)pCursor;
649   switch( i ){
650     case 0:            /* name */
651       sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
652       break;
653     case 1:            /* path */
654       sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
655       break;
656     case 2:            /* pageno */
657       sqlite3_result_int64(ctx, pCsr->iPageno);
658       break;
659     case 3:            /* pagetype */
660       sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
661       break;
662     case 4:            /* ncell */
663       sqlite3_result_int(ctx, pCsr->nCell);
664       break;
665     case 5:            /* payload */
666       sqlite3_result_int(ctx, pCsr->nPayload);
667       break;
668     case 6:            /* unused */
669       sqlite3_result_int(ctx, pCsr->nUnused);
670       break;
671     case 7:            /* mx_payload */
672       sqlite3_result_int(ctx, pCsr->nMxPayload);
673       break;
674     case 8:            /* pgoffset */
675       sqlite3_result_int64(ctx, pCsr->iOffset);
676       break;
677     case 9:            /* pgsize */
678       sqlite3_result_int(ctx, pCsr->szPage);
679       break;
680     default: {          /* schema */
681       sqlite3 *db = sqlite3_context_db_handle(ctx);
682       int iDb = pCsr->iDb;
683       sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
684       break;
685     }
686   }
687   return SQLITE_OK;
688 }
689 
690 static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
691   StatCursor *pCsr = (StatCursor *)pCursor;
692   *pRowid = pCsr->iPageno;
693   return SQLITE_OK;
694 }
695 
696 /*
697 ** Invoke this routine to register the "dbstat" virtual table module
698 */
699 int sqlite3DbstatRegister(sqlite3 *db){
700   static sqlite3_module dbstat_module = {
701     0,                            /* iVersion */
702     statConnect,                  /* xCreate */
703     statConnect,                  /* xConnect */
704     statBestIndex,                /* xBestIndex */
705     statDisconnect,               /* xDisconnect */
706     statDisconnect,               /* xDestroy */
707     statOpen,                     /* xOpen - open a cursor */
708     statClose,                    /* xClose - close a cursor */
709     statFilter,                   /* xFilter - configure scan constraints */
710     statNext,                     /* xNext - advance a cursor */
711     statEof,                      /* xEof - check for end of scan */
712     statColumn,                   /* xColumn - read data */
713     statRowid,                    /* xRowid - read data */
714     0,                            /* xUpdate */
715     0,                            /* xBegin */
716     0,                            /* xSync */
717     0,                            /* xCommit */
718     0,                            /* xRollback */
719     0,                            /* xFindMethod */
720     0,                            /* xRename */
721     0,                            /* xSavepoint */
722     0,                            /* xRelease */
723     0,                            /* xRollbackTo */
724     0                             /* xShadowName */
725   };
726   return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
727 }
728 #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
729 int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
730 #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
731