xref: /sqlite-3.40.0/src/dbstat.c (revision e99cb2da)
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 storage
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 static const char zDbstatSchema[] =
60   "CREATE TABLE x("
61   " name       TEXT,"          /*  0 Name of table or index */
62   " path       TEXT,"          /*  1 Path to page from root (NULL for agg) */
63   " pageno     INTEGER,"       /*  2 Page number (page count for aggregates) */
64   " pagetype   TEXT,"          /*  3 'internal', 'leaf', 'overflow', or NULL */
65   " ncell      INTEGER,"       /*  4 Cells on page (0 for overflow) */
66   " payload    INTEGER,"       /*  5 Bytes of payload on this page */
67   " unused     INTEGER,"       /*  6 Bytes of unused space on this page */
68   " mx_payload INTEGER,"       /*  7 Largest payload size of all cells */
69   " pgoffset   INTEGER,"       /*  8 Offset of page in file (NULL for agg) */
70   " pgsize     INTEGER,"       /*  9 Size of the page (sum for aggregate) */
71   " schema     TEXT HIDDEN,"   /* 10 Database schema being analyzed */
72   " aggregate  BOOLEAN HIDDEN" /* 11 aggregate info for each table */
73   ")"
74 ;
75 
76 /* Forward reference to data structured used in this module */
77 typedef struct StatTable StatTable;
78 typedef struct StatCursor StatCursor;
79 typedef struct StatPage StatPage;
80 typedef struct StatCell StatCell;
81 
82 /* Size information for a single cell within a btree page */
83 struct StatCell {
84   int nLocal;                     /* Bytes of local payload */
85   u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
86   int nOvfl;                      /* Entries in aOvfl[] */
87   u32 *aOvfl;                     /* Array of overflow page numbers */
88   int nLastOvfl;                  /* Bytes of payload on final overflow page */
89   int iOvfl;                      /* Iterates through aOvfl[] */
90 };
91 
92 /* Size information for a single btree page */
93 struct StatPage {
94   u32 iPgno;                      /* Page number */
95   DbPage *pPg;                    /* Page content */
96   int iCell;                      /* Current cell */
97 
98   char *zPath;                    /* Path to this page */
99 
100   /* Variables populated by statDecodePage(): */
101   u8 flags;                       /* Copy of flags byte */
102   int nCell;                      /* Number of cells on page */
103   int nUnused;                    /* Number of unused bytes on page */
104   StatCell *aCell;                /* Array of parsed cells */
105   u32 iRightChildPg;              /* Right-child page number (or 0) */
106   int nMxPayload;                 /* Largest payload of any cell on the page */
107 };
108 
109 /* The cursor for scanning the dbstat virtual table */
110 struct StatCursor {
111   sqlite3_vtab_cursor base;       /* base class.  MUST BE FIRST! */
112   sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
113   u8 isEof;                       /* After pStmt has returned SQLITE_DONE */
114   u8 isAgg;                       /* Aggregate results for each table */
115   int iDb;                        /* Schema used for this query */
116 
117   StatPage aPage[32];             /* Pages in path to current page */
118   int iPage;                      /* Current entry in aPage[] */
119 
120   /* Values to return. */
121   u32 iPageno;                    /* Value of 'pageno' column */
122   char *zName;                    /* Value of 'name' column */
123   char *zPath;                    /* Value of 'path' column */
124   char *zPagetype;                /* Value of 'pagetype' column */
125   int nPage;                      /* Number of pages in current btree */
126   int nCell;                      /* Value of 'ncell' column */
127   int nMxPayload;                 /* Value of 'mx_payload' column */
128   i64 nUnused;                    /* Value of 'unused' column */
129   i64 nPayload;                   /* Value of 'payload' column */
130   i64 iOffset;                    /* Value of 'pgOffset' column */
131   i64 szPage;                     /* Value of 'pgSize' column */
132 };
133 
134 /* An instance of the DBSTAT virtual table */
135 struct StatTable {
136   sqlite3_vtab base;              /* base class.  MUST BE FIRST! */
137   sqlite3 *db;                    /* Database connection that owns this vtab */
138   int iDb;                        /* Index of database to analyze */
139 };
140 
141 #ifndef get2byte
142 # define get2byte(x)   ((x)[0]<<8 | (x)[1])
143 #endif
144 
145 /*
146 ** Connect to or create a new DBSTAT virtual table.
147 */
148 static int statConnect(
149   sqlite3 *db,
150   void *pAux,
151   int argc, const char *const*argv,
152   sqlite3_vtab **ppVtab,
153   char **pzErr
154 ){
155   StatTable *pTab = 0;
156   int rc = SQLITE_OK;
157   int iDb;
158 
159   if( argc>=4 ){
160     Token nm;
161     sqlite3TokenInit(&nm, (char*)argv[3]);
162     iDb = sqlite3FindDb(db, &nm);
163     if( iDb<0 ){
164       *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
165       return SQLITE_ERROR;
166     }
167   }else{
168     iDb = 0;
169   }
170   rc = sqlite3_declare_vtab(db, zDbstatSchema);
171   if( rc==SQLITE_OK ){
172     pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
173     if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
174   }
175 
176   assert( rc==SQLITE_OK || pTab==0 );
177   if( rc==SQLITE_OK ){
178     memset(pTab, 0, sizeof(StatTable));
179     pTab->db = db;
180     pTab->iDb = iDb;
181   }
182 
183   *ppVtab = (sqlite3_vtab*)pTab;
184   return rc;
185 }
186 
187 /*
188 ** Disconnect from or destroy the DBSTAT virtual table.
189 */
190 static int statDisconnect(sqlite3_vtab *pVtab){
191   sqlite3_free(pVtab);
192   return SQLITE_OK;
193 }
194 
195 /*
196 ** Compute the best query strategy and return the result in idxNum.
197 **
198 **   idxNum-Bit        Meaning
199 **   ----------        ----------------------------------------------
200 **      0x01           There is a schema=? term in the WHERE clause
201 **      0x02           There is a name=? term in the WHERE clause
202 **      0x04           There is an aggregate=? term in the WHERE clause
203 **      0x08           Output should be ordered by name and path
204 */
205 static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
206   int i;
207   int iSchema = -1;
208   int iName = -1;
209   int iAgg = -1;
210 
211   /* Look for a valid schema=? constraint.  If found, change the idxNum to
212   ** 1 and request the value of that constraint be sent to xFilter.  And
213   ** lower the cost estimate to encourage the constrained version to be
214   ** used.
215   */
216   for(i=0; i<pIdxInfo->nConstraint; i++){
217     if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
218     if( pIdxInfo->aConstraint[i].usable==0 ){
219       /* Force DBSTAT table should always be the right-most table in a join */
220       return SQLITE_CONSTRAINT;
221     }
222     switch( pIdxInfo->aConstraint[i].iColumn ){
223       case 0: {    /* name */
224         iName = i;
225         break;
226       }
227       case 10: {   /* schema */
228         iSchema = i;
229         break;
230       }
231       case 11: {   /* aggregate */
232         iAgg = i;
233         break;
234       }
235     }
236   }
237   i = 0;
238   if( iSchema>=0 ){
239     pIdxInfo->aConstraintUsage[iSchema].argvIndex = ++i;
240     pIdxInfo->aConstraintUsage[iSchema].omit = 1;
241     pIdxInfo->idxNum |= 0x01;
242   }
243   if( iName>=0 ){
244     pIdxInfo->aConstraintUsage[iName].argvIndex = ++i;
245     pIdxInfo->aConstraintUsage[iName].omit = 1;
246     pIdxInfo->idxNum |= 0x02;
247   }
248   if( iAgg>=0 ){
249     pIdxInfo->aConstraintUsage[iAgg].argvIndex = ++i;
250     pIdxInfo->aConstraintUsage[iAgg].omit = 1;
251     pIdxInfo->idxNum |= 0x04;
252   }
253   pIdxInfo->estimatedCost = 1.0;
254 
255   /* Records are always returned in ascending order of (name, path).
256   ** If this will satisfy the client, set the orderByConsumed flag so that
257   ** SQLite does not do an external sort.
258   */
259   if( ( pIdxInfo->nOrderBy==1
260      && pIdxInfo->aOrderBy[0].iColumn==0
261      && pIdxInfo->aOrderBy[0].desc==0
262      ) ||
263       ( pIdxInfo->nOrderBy==2
264      && pIdxInfo->aOrderBy[0].iColumn==0
265      && pIdxInfo->aOrderBy[0].desc==0
266      && pIdxInfo->aOrderBy[1].iColumn==1
267      && pIdxInfo->aOrderBy[1].desc==0
268      )
269   ){
270     pIdxInfo->orderByConsumed = 1;
271     pIdxInfo->idxNum |= 0x08;
272   }
273 
274   return SQLITE_OK;
275 }
276 
277 /*
278 ** Open a new DBSTAT cursor.
279 */
280 static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
281   StatTable *pTab = (StatTable *)pVTab;
282   StatCursor *pCsr;
283 
284   pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
285   if( pCsr==0 ){
286     return SQLITE_NOMEM_BKPT;
287   }else{
288     memset(pCsr, 0, sizeof(StatCursor));
289     pCsr->base.pVtab = pVTab;
290     pCsr->iDb = pTab->iDb;
291   }
292 
293   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
294   return SQLITE_OK;
295 }
296 
297 static void statClearCells(StatPage *p){
298   int i;
299   if( p->aCell ){
300     for(i=0; i<p->nCell; i++){
301       sqlite3_free(p->aCell[i].aOvfl);
302     }
303     sqlite3_free(p->aCell);
304   }
305   p->nCell = 0;
306   p->aCell = 0;
307 }
308 
309 static void statClearPage(StatPage *p){
310   statClearCells(p);
311   sqlite3PagerUnref(p->pPg);
312   sqlite3_free(p->zPath);
313   memset(p, 0, sizeof(StatPage));
314 }
315 
316 static void statResetCsr(StatCursor *pCsr){
317   int i;
318   sqlite3_reset(pCsr->pStmt);
319   for(i=0; i<ArraySize(pCsr->aPage); i++){
320     statClearPage(&pCsr->aPage[i]);
321   }
322   pCsr->iPage = 0;
323   sqlite3_free(pCsr->zPath);
324   pCsr->zPath = 0;
325   pCsr->isEof = 0;
326 }
327 
328 /* Resize the space-used counters inside of the cursor */
329 static void statResetCounts(StatCursor *pCsr){
330   pCsr->nCell = 0;
331   pCsr->nMxPayload = 0;
332   pCsr->nUnused = 0;
333   pCsr->nPayload = 0;
334   pCsr->szPage = 0;
335   pCsr->nPage = 0;
336 }
337 
338 /*
339 ** Close a DBSTAT cursor.
340 */
341 static int statClose(sqlite3_vtab_cursor *pCursor){
342   StatCursor *pCsr = (StatCursor *)pCursor;
343   statResetCsr(pCsr);
344   sqlite3_finalize(pCsr->pStmt);
345   sqlite3_free(pCsr);
346   return SQLITE_OK;
347 }
348 
349 /*
350 ** For a single cell on a btree page, compute the number of bytes of
351 ** content (payload) stored on that page.  That is to say, compute the
352 ** number of bytes of content not found on overflow pages.
353 */
354 static int getLocalPayload(
355   int nUsable,                    /* Usable bytes per page */
356   u8 flags,                       /* Page flags */
357   int nTotal                      /* Total record (payload) size */
358 ){
359   int nLocal;
360   int nMinLocal;
361   int nMaxLocal;
362 
363   if( flags==0x0D ){              /* Table leaf node */
364     nMinLocal = (nUsable - 12) * 32 / 255 - 23;
365     nMaxLocal = nUsable - 35;
366   }else{                          /* Index interior and leaf nodes */
367     nMinLocal = (nUsable - 12) * 32 / 255 - 23;
368     nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
369   }
370 
371   nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
372   if( nLocal>nMaxLocal ) nLocal = nMinLocal;
373   return nLocal;
374 }
375 
376 /* Populate the StatPage object with information about the all
377 ** cells found on the page currently under analysis.
378 */
379 static int statDecodePage(Btree *pBt, StatPage *p){
380   int nUnused;
381   int iOff;
382   int nHdr;
383   int isLeaf;
384   int szPage;
385 
386   u8 *aData = sqlite3PagerGetData(p->pPg);
387   u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
388 
389   p->flags = aHdr[0];
390   if( p->flags==0x0A || p->flags==0x0D ){
391     isLeaf = 1;
392     nHdr = 8;
393   }else if( p->flags==0x05 || p->flags==0x02 ){
394     isLeaf = 0;
395     nHdr = 12;
396   }else{
397     goto statPageIsCorrupt;
398   }
399   if( p->iPgno==1 ) nHdr += 100;
400   p->nCell = get2byte(&aHdr[3]);
401   p->nMxPayload = 0;
402   szPage = sqlite3BtreeGetPageSize(pBt);
403 
404   nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
405   nUnused += (int)aHdr[7];
406   iOff = get2byte(&aHdr[1]);
407   while( iOff ){
408     int iNext;
409     if( iOff>=szPage ) goto statPageIsCorrupt;
410     nUnused += get2byte(&aData[iOff+2]);
411     iNext = get2byte(&aData[iOff]);
412     if( iNext<iOff+4 && iNext>0 ) goto statPageIsCorrupt;
413     iOff = iNext;
414   }
415   p->nUnused = nUnused;
416   p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
417 
418   if( p->nCell ){
419     int i;                        /* Used to iterate through cells */
420     int nUsable;                  /* Usable bytes per page */
421 
422     sqlite3BtreeEnter(pBt);
423     nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
424     sqlite3BtreeLeave(pBt);
425     p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
426     if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
427     memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
428 
429     for(i=0; i<p->nCell; i++){
430       StatCell *pCell = &p->aCell[i];
431 
432       iOff = get2byte(&aData[nHdr+i*2]);
433       if( iOff<nHdr || iOff>=szPage ) goto statPageIsCorrupt;
434       if( !isLeaf ){
435         pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
436         iOff += 4;
437       }
438       if( p->flags==0x05 ){
439         /* A table interior node. nPayload==0. */
440       }else{
441         u32 nPayload;             /* Bytes of payload total (local+overflow) */
442         int nLocal;               /* Bytes of payload stored locally */
443         iOff += getVarint32(&aData[iOff], nPayload);
444         if( p->flags==0x0D ){
445           u64 dummy;
446           iOff += sqlite3GetVarint(&aData[iOff], &dummy);
447         }
448         if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
449         nLocal = getLocalPayload(nUsable, p->flags, nPayload);
450         if( nLocal<0 ) goto statPageIsCorrupt;
451         pCell->nLocal = nLocal;
452         assert( nPayload>=(u32)nLocal );
453         assert( nLocal<=(nUsable-35) );
454         if( nPayload>(u32)nLocal ){
455           int j;
456           int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
457           if( iOff+nLocal>nUsable ) goto statPageIsCorrupt;
458           pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
459           pCell->nOvfl = nOvfl;
460           pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
461           if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
462           pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
463           for(j=1; j<nOvfl; j++){
464             int rc;
465             u32 iPrev = pCell->aOvfl[j-1];
466             DbPage *pPg = 0;
467             rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
468             if( rc!=SQLITE_OK ){
469               assert( pPg==0 );
470               return rc;
471             }
472             pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
473             sqlite3PagerUnref(pPg);
474           }
475         }
476       }
477     }
478   }
479 
480   return SQLITE_OK;
481 
482 statPageIsCorrupt:
483   p->flags = 0;
484   statClearCells(p);
485   return SQLITE_OK;
486 }
487 
488 /*
489 ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
490 ** the current value of pCsr->iPageno.
491 */
492 static void statSizeAndOffset(StatCursor *pCsr){
493   StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
494   Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
495   Pager *pPager = sqlite3BtreePager(pBt);
496   sqlite3_file *fd;
497   sqlite3_int64 x[2];
498 
499   /* If connected to a ZIPVFS backend, find the page size and
500   ** offset from ZIPVFS.
501   */
502   fd = sqlite3PagerFile(pPager);
503   x[0] = pCsr->iPageno;
504   if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
505     pCsr->iOffset = x[0];
506     pCsr->szPage += x[1];
507   }else{
508     /* Not ZIPVFS: The default page size and offset */
509     pCsr->szPage += sqlite3BtreeGetPageSize(pBt);
510     pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
511   }
512 }
513 
514 /*
515 ** Move a DBSTAT cursor to the next entry.  Normally, the next
516 ** entry will be the next page, but in aggregated mode (pCsr->isAgg!=0),
517 ** the next entry is the next btree.
518 */
519 static int statNext(sqlite3_vtab_cursor *pCursor){
520   int rc;
521   int nPayload;
522   char *z;
523   StatCursor *pCsr = (StatCursor *)pCursor;
524   StatTable *pTab = (StatTable *)pCursor->pVtab;
525   Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
526   Pager *pPager = sqlite3BtreePager(pBt);
527 
528   sqlite3_free(pCsr->zPath);
529   pCsr->zPath = 0;
530 
531 statNextRestart:
532   if( pCsr->aPage[0].pPg==0 ){
533     /* Start measuring space on the next btree */
534     statResetCounts(pCsr);
535     rc = sqlite3_step(pCsr->pStmt);
536     if( rc==SQLITE_ROW ){
537       int nPage;
538       u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
539       sqlite3PagerPagecount(pPager, &nPage);
540       if( nPage==0 ){
541         pCsr->isEof = 1;
542         return sqlite3_reset(pCsr->pStmt);
543       }
544       rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
545       pCsr->aPage[0].iPgno = iRoot;
546       pCsr->aPage[0].iCell = 0;
547       if( !pCsr->isAgg ){
548         pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
549         if( z==0 ) rc = SQLITE_NOMEM_BKPT;
550       }
551       pCsr->iPage = 0;
552       pCsr->nPage = 1;
553     }else{
554       pCsr->isEof = 1;
555       return sqlite3_reset(pCsr->pStmt);
556     }
557   }else{
558     /* Continue analyzing the btree previously started */
559     StatPage *p = &pCsr->aPage[pCsr->iPage];
560     if( !pCsr->isAgg ) statResetCounts(pCsr);
561     while( p->iCell<p->nCell ){
562       StatCell *pCell = &p->aCell[p->iCell];
563       while( pCell->iOvfl<pCell->nOvfl ){
564         int nUsable, iOvfl;
565         sqlite3BtreeEnter(pBt);
566         nUsable = sqlite3BtreeGetPageSize(pBt) -
567                         sqlite3BtreeGetReserveNoMutex(pBt);
568         sqlite3BtreeLeave(pBt);
569         pCsr->nPage++;
570         statSizeAndOffset(pCsr);
571         if( pCell->iOvfl<pCell->nOvfl-1 ){
572           pCsr->nPayload += nUsable - 4;
573         }else{
574           pCsr->nPayload += pCell->nLastOvfl;
575           pCsr->nUnused += nUsable - 4 - pCell->nLastOvfl;
576         }
577         iOvfl = pCell->iOvfl;
578         pCell->iOvfl++;
579         if( !pCsr->isAgg ){
580           pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
581           pCsr->iPageno = pCell->aOvfl[iOvfl];
582           pCsr->zPagetype = "overflow";
583           pCsr->zPath = z = sqlite3_mprintf(
584               "%s%.3x+%.6x", p->zPath, p->iCell, iOvfl
585           );
586           return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
587         }
588       }
589       if( p->iRightChildPg ) break;
590       p->iCell++;
591     }
592 
593     if( !p->iRightChildPg || p->iCell>p->nCell ){
594       statClearPage(p);
595       if( pCsr->iPage>0 ){
596         pCsr->iPage--;
597       }else if( pCsr->isAgg ){
598         /* label-statNext-done:  When computing aggregate space usage over
599         ** an entire btree, this is the exit point from this function */
600         return SQLITE_OK;
601       }
602       goto statNextRestart; /* Tail recursion */
603     }
604     pCsr->iPage++;
605     if( pCsr->iPage>=ArraySize(pCsr->aPage) ){
606       statResetCsr(pCsr);
607       return SQLITE_CORRUPT_BKPT;
608     }
609     assert( p==&pCsr->aPage[pCsr->iPage-1] );
610 
611     if( p->iCell==p->nCell ){
612       p[1].iPgno = p->iRightChildPg;
613     }else{
614       p[1].iPgno = p->aCell[p->iCell].iChildPg;
615     }
616     rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
617     pCsr->nPage++;
618     p[1].iCell = 0;
619     if( !pCsr->isAgg ){
620       p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
621       if( z==0 ) rc = SQLITE_NOMEM_BKPT;
622     }
623     p->iCell++;
624   }
625 
626 
627   /* Populate the StatCursor fields with the values to be returned
628   ** by the xColumn() and xRowid() methods.
629   */
630   if( rc==SQLITE_OK ){
631     int i;
632     StatPage *p = &pCsr->aPage[pCsr->iPage];
633     pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
634     pCsr->iPageno = p->iPgno;
635 
636     rc = statDecodePage(pBt, p);
637     if( rc==SQLITE_OK ){
638       statSizeAndOffset(pCsr);
639 
640       switch( p->flags ){
641         case 0x05:             /* table internal */
642         case 0x02:             /* index internal */
643           pCsr->zPagetype = "internal";
644           break;
645         case 0x0D:             /* table leaf */
646         case 0x0A:             /* index leaf */
647           pCsr->zPagetype = "leaf";
648           break;
649         default:
650           pCsr->zPagetype = "corrupted";
651           break;
652       }
653       pCsr->nCell += p->nCell;
654       pCsr->nUnused += p->nUnused;
655       if( p->nMxPayload>pCsr->nMxPayload ) pCsr->nMxPayload = p->nMxPayload;
656       if( !pCsr->isAgg ){
657         pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
658         if( z==0 ) rc = SQLITE_NOMEM_BKPT;
659       }
660       nPayload = 0;
661       for(i=0; i<p->nCell; i++){
662         nPayload += p->aCell[i].nLocal;
663       }
664       pCsr->nPayload += nPayload;
665 
666       /* If computing aggregate space usage by btree, continue with the
667       ** next page.  The loop will exit via the return at label-statNext-done
668       */
669       if( pCsr->isAgg ) goto statNextRestart;
670     }
671   }
672 
673   return rc;
674 }
675 
676 static int statEof(sqlite3_vtab_cursor *pCursor){
677   StatCursor *pCsr = (StatCursor *)pCursor;
678   return pCsr->isEof;
679 }
680 
681 /* Initialize a cursor according to the query plan idxNum using the
682 ** arguments in argv[0].  See statBestIndex() for a description of the
683 ** meaning of the bits in idxNum.
684 */
685 static int statFilter(
686   sqlite3_vtab_cursor *pCursor,
687   int idxNum, const char *idxStr,
688   int argc, sqlite3_value **argv
689 ){
690   StatCursor *pCsr = (StatCursor *)pCursor;
691   StatTable *pTab = (StatTable*)(pCursor->pVtab);
692   sqlite3_str *pSql;      /* Query of btrees to analyze */
693   char *zSql;             /* String value of pSql */
694   int iArg = 0;           /* Count of argv[] parameters used so far */
695   int rc = SQLITE_OK;     /* Result of this operation */
696   const char *zName = 0;  /* Only provide analysis of this table */
697 
698   statResetCsr(pCsr);
699   sqlite3_finalize(pCsr->pStmt);
700   pCsr->pStmt = 0;
701   if( idxNum & 0x01 ){
702     /* schema=? constraint is present.  Get its value */
703     const char *zDbase = (const char*)sqlite3_value_text(argv[iArg++]);
704     pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
705     if( pCsr->iDb<0 ){
706       sqlite3_free(pCursor->pVtab->zErrMsg);
707       pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
708       return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
709     }
710   }else{
711     pCsr->iDb = pTab->iDb;
712   }
713   if( idxNum & 0x02 ){
714     /* name=? constraint is present */
715     zName = (const char*)sqlite3_value_text(argv[iArg++]);
716   }
717   if( idxNum & 0x04 ){
718     /* aggregate=? constraint is present */
719     pCsr->isAgg = sqlite3_value_double(argv[iArg++])!=0.0;
720   }else{
721     pCsr->isAgg = 0;
722   }
723   pSql = sqlite3_str_new(pTab->db);
724   sqlite3_str_appendf(pSql,
725       "SELECT * FROM ("
726         "SELECT 'sqlite_master' AS name,1 AS rootpage,'table' AS type"
727         " UNION ALL "
728         "SELECT name,rootpage,type"
729         " FROM \"%w\".sqlite_master WHERE rootpage!=0)",
730       pTab->db->aDb[pCsr->iDb].zDbSName);
731   if( zName ){
732     sqlite3_str_appendf(pSql, "WHERE name=%Q", zName);
733   }
734   if( idxNum & 0x08 ){
735     sqlite3_str_appendf(pSql, " ORDER BY name");
736   }
737   zSql = sqlite3_str_finish(pSql);
738   if( zSql==0 ){
739     return SQLITE_NOMEM_BKPT;
740   }else{
741     rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
742     sqlite3_free(zSql);
743   }
744 
745   if( rc==SQLITE_OK ){
746     rc = statNext(pCursor);
747   }
748   return rc;
749 }
750 
751 static int statColumn(
752   sqlite3_vtab_cursor *pCursor,
753   sqlite3_context *ctx,
754   int i
755 ){
756   StatCursor *pCsr = (StatCursor *)pCursor;
757   switch( i ){
758     case 0:            /* name */
759       sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
760       break;
761     case 1:            /* path */
762       if( !pCsr->isAgg ){
763         sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
764       }
765       break;
766     case 2:            /* pageno */
767       if( pCsr->isAgg ){
768         sqlite3_result_int64(ctx, pCsr->nPage);
769       }else{
770         sqlite3_result_int64(ctx, pCsr->iPageno);
771       }
772       break;
773     case 3:            /* pagetype */
774       if( !pCsr->isAgg ){
775         sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
776       }
777       break;
778     case 4:            /* ncell */
779       sqlite3_result_int(ctx, pCsr->nCell);
780       break;
781     case 5:            /* payload */
782       sqlite3_result_int(ctx, pCsr->nPayload);
783       break;
784     case 6:            /* unused */
785       sqlite3_result_int(ctx, pCsr->nUnused);
786       break;
787     case 7:            /* mx_payload */
788       sqlite3_result_int(ctx, pCsr->nMxPayload);
789       break;
790     case 8:            /* pgoffset */
791       if( !pCsr->isAgg ){
792         sqlite3_result_int64(ctx, pCsr->iOffset);
793       }
794       break;
795     case 9:            /* pgsize */
796       sqlite3_result_int(ctx, pCsr->szPage);
797       break;
798     case 10: {         /* schema */
799       sqlite3 *db = sqlite3_context_db_handle(ctx);
800       int iDb = pCsr->iDb;
801       sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
802       break;
803     }
804     default: {         /* aggregate */
805       sqlite3_result_int(ctx, pCsr->isAgg);
806       break;
807     }
808   }
809   return SQLITE_OK;
810 }
811 
812 static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
813   StatCursor *pCsr = (StatCursor *)pCursor;
814   *pRowid = pCsr->iPageno;
815   return SQLITE_OK;
816 }
817 
818 /*
819 ** Invoke this routine to register the "dbstat" virtual table module
820 */
821 int sqlite3DbstatRegister(sqlite3 *db){
822   static sqlite3_module dbstat_module = {
823     0,                            /* iVersion */
824     statConnect,                  /* xCreate */
825     statConnect,                  /* xConnect */
826     statBestIndex,                /* xBestIndex */
827     statDisconnect,               /* xDisconnect */
828     statDisconnect,               /* xDestroy */
829     statOpen,                     /* xOpen - open a cursor */
830     statClose,                    /* xClose - close a cursor */
831     statFilter,                   /* xFilter - configure scan constraints */
832     statNext,                     /* xNext - advance a cursor */
833     statEof,                      /* xEof - check for end of scan */
834     statColumn,                   /* xColumn - read data */
835     statRowid,                    /* xRowid - read data */
836     0,                            /* xUpdate */
837     0,                            /* xBegin */
838     0,                            /* xSync */
839     0,                            /* xCommit */
840     0,                            /* xRollback */
841     0,                            /* xFindMethod */
842     0,                            /* xRename */
843     0,                            /* xSavepoint */
844     0,                            /* xRelease */
845     0,                            /* xRollbackTo */
846     0                             /* xShadowName */
847   };
848   return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
849 }
850 #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
851 int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
852 #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
853