blob: 78173c3976a5ce8ccf5182137e60a1b370ced7ec [file] [log] [blame]
dan599e9d22010-07-12 08:39:37 +00001/*
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******************************************************************************
drh3a0f13f2010-07-12 16:47:48 +000012**
13** This file contains an implementation of the "dbstat" virtual table.
14**
drhad84bd82019-11-19 14:01:51 +000015** The dbstat virtual table is used to extract low-level storage
drh3a0f13f2010-07-12 16:47:48 +000016** 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.
drha46a4a62015-09-08 21:12:53 +000019**
20** Additional information is available on the "dbstat.html" page of the
21** official SQLite documentation.
dan599e9d22010-07-12 08:39:37 +000022*/
23
drh8755a5f2015-05-12 19:10:18 +000024#include "sqliteInt.h" /* Requires access to internal data structures */
drh1a4a6802015-05-04 18:31:09 +000025#if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
drh59ba6e82015-05-05 10:46:02 +000026 && !defined(SQLITE_OMIT_VIRTUALTABLE)
dan6d3eb822010-07-12 18:12:41 +000027
dan599e9d22010-07-12 08:39:37 +000028/*
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
drh3a0f13f2010-07-12 16:47:48 +000036** 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
dan599e9d22010-07-12 08:39:37 +000039** '/001', and so on, each sibling page identified by a 3-digit hex
drh3a0f13f2010-07-12 16:47:48 +000040** value. The children of the 451st left-most sibling have paths such
dan599e9d22010-07-12 08:39:37 +000041** 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**
drh3a0f13f2010-07-12 16:47:48 +000057** '/1c2/000/' // Left-most child of 451st child of root
dan599e9d22010-07-12 08:39:37 +000058*/
drh012b15e2019-11-19 18:48:11 +000059static 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;
dan599e9d22010-07-12 08:39:37 +000075
drhad84bd82019-11-19 14:01:51 +000076/* Forward reference to data structured used in this module */
dan599e9d22010-07-12 08:39:37 +000077typedef struct StatTable StatTable;
78typedef struct StatCursor StatCursor;
79typedef struct StatPage StatPage;
80typedef struct StatCell StatCell;
81
drhad84bd82019-11-19 14:01:51 +000082/* Size information for a single cell within a btree page */
dan599e9d22010-07-12 08:39:37 +000083struct 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
drhad84bd82019-11-19 14:01:51 +000092/* Size information for a single btree page */
dan599e9d22010-07-12 08:39:37 +000093struct StatPage {
drhad84bd82019-11-19 14:01:51 +000094 u32 iPgno; /* Page number */
95 DbPage *pPg; /* Page content */
96 int iCell; /* Current cell */
dan599e9d22010-07-12 08:39:37 +000097
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) */
drhad84bd82019-11-19 14:01:51 +0000106 int nMxPayload; /* Largest payload of any cell on the page */
dan599e9d22010-07-12 08:39:37 +0000107};
108
drhad84bd82019-11-19 14:01:51 +0000109/* The cursor for scanning the dbstat virtual table */
dan599e9d22010-07-12 08:39:37 +0000110struct StatCursor {
drhad84bd82019-11-19 14:01:51 +0000111 sqlite3_vtab_cursor base; /* base class. MUST BE FIRST! */
dan599e9d22010-07-12 08:39:37 +0000112 sqlite3_stmt *pStmt; /* Iterates through set of root pages */
drh012b15e2019-11-19 18:48:11 +0000113 u8 isEof; /* After pStmt has returned SQLITE_DONE */
114 u8 isAgg; /* Aggregate results for each table */
drha46a4a62015-09-08 21:12:53 +0000115 int iDb; /* Schema used for this query */
dan599e9d22010-07-12 08:39:37 +0000116
drhad84bd82019-11-19 14:01:51 +0000117 StatPage aPage[32]; /* Pages in path to current page */
dan599e9d22010-07-12 08:39:37 +0000118 int iPage; /* Current entry in aPage[] */
119
120 /* Values to return. */
drh012b15e2019-11-19 18:48:11 +0000121 u32 iPageno; /* Value of 'pageno' column */
dan599e9d22010-07-12 08:39:37 +0000122 char *zName; /* Value of 'name' column */
123 char *zPath; /* Value of 'path' column */
dan599e9d22010-07-12 08:39:37 +0000124 char *zPagetype; /* Value of 'pagetype' column */
drh012b15e2019-11-19 18:48:11 +0000125 int nPage; /* Number of pages in current btree */
dan599e9d22010-07-12 08:39:37 +0000126 int nCell; /* Value of 'ncell' column */
dan599e9d22010-07-12 08:39:37 +0000127 int nMxPayload; /* Value of 'mx_payload' column */
drh012b15e2019-11-19 18:48:11 +0000128 i64 nUnused; /* Value of 'unused' column */
129 i64 nPayload; /* Value of 'payload' column */
drh4c9f1292011-09-28 00:50:14 +0000130 i64 iOffset; /* Value of 'pgOffset' column */
drh012b15e2019-11-19 18:48:11 +0000131 i64 szPage; /* Value of 'pgSize' column */
dan599e9d22010-07-12 08:39:37 +0000132};
133
drhad84bd82019-11-19 14:01:51 +0000134/* An instance of the DBSTAT virtual table */
dan599e9d22010-07-12 08:39:37 +0000135struct StatTable {
drhad84bd82019-11-19 14:01:51 +0000136 sqlite3_vtab base; /* base class. MUST BE FIRST! */
137 sqlite3 *db; /* Database connection that owns this vtab */
drh857df262015-05-07 14:41:56 +0000138 int iDb; /* Index of database to analyze */
dan599e9d22010-07-12 08:39:37 +0000139};
140
141#ifndef get2byte
142# define get2byte(x) ((x)[0]<<8 | (x)[1])
143#endif
144
145/*
drhad84bd82019-11-19 14:01:51 +0000146** Connect to or create a new DBSTAT virtual table.
dan599e9d22010-07-12 08:39:37 +0000147*/
148static int statConnect(
149 sqlite3 *db,
150 void *pAux,
151 int argc, const char *const*argv,
152 sqlite3_vtab **ppVtab,
153 char **pzErr
154){
dan995f8b92015-04-27 19:53:55 +0000155 StatTable *pTab = 0;
156 int rc = SQLITE_OK;
drh857df262015-05-07 14:41:56 +0000157 int iDb;
dan599e9d22010-07-12 08:39:37 +0000158
drh857df262015-05-07 14:41:56 +0000159 if( argc>=4 ){
drh40aced52016-01-22 17:48:09 +0000160 Token nm;
161 sqlite3TokenInit(&nm, (char*)argv[3]);
162 iDb = sqlite3FindDb(db, &nm);
drh857df262015-05-07 14:41:56 +0000163 if( iDb<0 ){
164 *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
165 return SQLITE_ERROR;
166 }
167 }else{
168 iDb = 0;
169 }
drh2b1c2aa2020-01-07 19:45:40 +0000170 sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
drh012b15e2019-11-19 18:48:11 +0000171 rc = sqlite3_declare_vtab(db, zDbstatSchema);
dan995f8b92015-04-27 19:53:55 +0000172 if( rc==SQLITE_OK ){
drhf3cdcdc2015-04-29 16:50:28 +0000173 pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
mistachkinfad30392016-02-13 23:43:46 +0000174 if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
dan995f8b92015-04-27 19:53:55 +0000175 }
dan599e9d22010-07-12 08:39:37 +0000176
dan995f8b92015-04-27 19:53:55 +0000177 assert( rc==SQLITE_OK || pTab==0 );
178 if( rc==SQLITE_OK ){
179 memset(pTab, 0, sizeof(StatTable));
180 pTab->db = db;
drh857df262015-05-07 14:41:56 +0000181 pTab->iDb = iDb;
dan995f8b92015-04-27 19:53:55 +0000182 }
183
184 *ppVtab = (sqlite3_vtab*)pTab;
185 return rc;
dan599e9d22010-07-12 08:39:37 +0000186}
187
188/*
drhad84bd82019-11-19 14:01:51 +0000189** Disconnect from or destroy the DBSTAT virtual table.
dan599e9d22010-07-12 08:39:37 +0000190*/
191static int statDisconnect(sqlite3_vtab *pVtab){
192 sqlite3_free(pVtab);
193 return SQLITE_OK;
194}
195
196/*
drhad84bd82019-11-19 14:01:51 +0000197** Compute the best query strategy and return the result in idxNum.
drha46a4a62015-09-08 21:12:53 +0000198**
drhad84bd82019-11-19 14:01:51 +0000199** idxNum-Bit Meaning
200** ---------- ----------------------------------------------
201** 0x01 There is a schema=? term in the WHERE clause
202** 0x02 There is a name=? term in the WHERE clause
203** 0x04 There is an aggregate=? term in the WHERE clause
204** 0x08 Output should be ordered by name and path
dan599e9d22010-07-12 08:39:37 +0000205*/
206static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
drha46a4a62015-09-08 21:12:53 +0000207 int i;
drhad84bd82019-11-19 14:01:51 +0000208 int iSchema = -1;
209 int iName = -1;
210 int iAgg = -1;
drha46a4a62015-09-08 21:12:53 +0000211
drha46a4a62015-09-08 21:12:53 +0000212 /* Look for a valid schema=? constraint. If found, change the idxNum to
213 ** 1 and request the value of that constraint be sent to xFilter. And
214 ** lower the cost estimate to encourage the constrained version to be
215 ** used.
216 */
217 for(i=0; i<pIdxInfo->nConstraint; i++){
drh20b3fc42018-11-16 20:18:07 +0000218 if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
drhad84bd82019-11-19 14:01:51 +0000219 if( pIdxInfo->aConstraint[i].usable==0 ){
220 /* Force DBSTAT table should always be the right-most table in a join */
221 return SQLITE_CONSTRAINT;
222 }
223 switch( pIdxInfo->aConstraint[i].iColumn ){
224 case 0: { /* name */
225 iName = i;
226 break;
227 }
228 case 10: { /* schema */
229 iSchema = i;
230 break;
231 }
232 case 11: { /* aggregate */
233 iAgg = i;
234 break;
235 }
236 }
drha46a4a62015-09-08 21:12:53 +0000237 }
drhad84bd82019-11-19 14:01:51 +0000238 i = 0;
239 if( iSchema>=0 ){
240 pIdxInfo->aConstraintUsage[iSchema].argvIndex = ++i;
dan00bd55e2020-03-20 20:54:28 +0000241 pIdxInfo->aConstraintUsage[iSchema].omit = 1;
drhad84bd82019-11-19 14:01:51 +0000242 pIdxInfo->idxNum |= 0x01;
243 }
244 if( iName>=0 ){
245 pIdxInfo->aConstraintUsage[iName].argvIndex = ++i;
drhad84bd82019-11-19 14:01:51 +0000246 pIdxInfo->idxNum |= 0x02;
247 }
248 if( iAgg>=0 ){
249 pIdxInfo->aConstraintUsage[iAgg].argvIndex = ++i;
drhad84bd82019-11-19 14:01:51 +0000250 pIdxInfo->idxNum |= 0x04;
251 }
252 pIdxInfo->estimatedCost = 1.0;
dan599e9d22010-07-12 08:39:37 +0000253
254 /* Records are always returned in ascending order of (name, path).
255 ** If this will satisfy the client, set the orderByConsumed flag so that
256 ** SQLite does not do an external sort.
257 */
258 if( ( pIdxInfo->nOrderBy==1
259 && pIdxInfo->aOrderBy[0].iColumn==0
260 && pIdxInfo->aOrderBy[0].desc==0
261 ) ||
262 ( pIdxInfo->nOrderBy==2
263 && pIdxInfo->aOrderBy[0].iColumn==0
264 && pIdxInfo->aOrderBy[0].desc==0
265 && pIdxInfo->aOrderBy[1].iColumn==1
266 && pIdxInfo->aOrderBy[1].desc==0
267 )
268 ){
269 pIdxInfo->orderByConsumed = 1;
drhad84bd82019-11-19 14:01:51 +0000270 pIdxInfo->idxNum |= 0x08;
dan599e9d22010-07-12 08:39:37 +0000271 }
272
dan599e9d22010-07-12 08:39:37 +0000273 return SQLITE_OK;
274}
275
276/*
drh012b15e2019-11-19 18:48:11 +0000277** Open a new DBSTAT cursor.
dan599e9d22010-07-12 08:39:37 +0000278*/
279static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
280 StatTable *pTab = (StatTable *)pVTab;
281 StatCursor *pCsr;
dan599e9d22010-07-12 08:39:37 +0000282
drhf3cdcdc2015-04-29 16:50:28 +0000283 pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
dan995f8b92015-04-27 19:53:55 +0000284 if( pCsr==0 ){
mistachkinfad30392016-02-13 23:43:46 +0000285 return SQLITE_NOMEM_BKPT;
dan995f8b92015-04-27 19:53:55 +0000286 }else{
287 memset(pCsr, 0, sizeof(StatCursor));
288 pCsr->base.pVtab = pVTab;
drha46a4a62015-09-08 21:12:53 +0000289 pCsr->iDb = pTab->iDb;
dan599e9d22010-07-12 08:39:37 +0000290 }
291
292 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
drha46a4a62015-09-08 21:12:53 +0000293 return SQLITE_OK;
dan599e9d22010-07-12 08:39:37 +0000294}
295
drh5aa20372018-10-29 18:33:42 +0000296static void statClearCells(StatPage *p){
dan599e9d22010-07-12 08:39:37 +0000297 int i;
dan995f8b92015-04-27 19:53:55 +0000298 if( p->aCell ){
299 for(i=0; i<p->nCell; i++){
300 sqlite3_free(p->aCell[i].aOvfl);
301 }
302 sqlite3_free(p->aCell);
dan599e9d22010-07-12 08:39:37 +0000303 }
drh5aa20372018-10-29 18:33:42 +0000304 p->nCell = 0;
305 p->aCell = 0;
306}
307
308static void statClearPage(StatPage *p){
309 statClearCells(p);
dan599e9d22010-07-12 08:39:37 +0000310 sqlite3PagerUnref(p->pPg);
dan599e9d22010-07-12 08:39:37 +0000311 sqlite3_free(p->zPath);
312 memset(p, 0, sizeof(StatPage));
313}
314
315static void statResetCsr(StatCursor *pCsr){
316 int i;
317 sqlite3_reset(pCsr->pStmt);
318 for(i=0; i<ArraySize(pCsr->aPage); i++){
319 statClearPage(&pCsr->aPage[i]);
320 }
321 pCsr->iPage = 0;
322 sqlite3_free(pCsr->zPath);
323 pCsr->zPath = 0;
drha46a4a62015-09-08 21:12:53 +0000324 pCsr->isEof = 0;
dan599e9d22010-07-12 08:39:37 +0000325}
326
drh012b15e2019-11-19 18:48:11 +0000327/* Resize the space-used counters inside of the cursor */
328static void statResetCounts(StatCursor *pCsr){
329 pCsr->nCell = 0;
330 pCsr->nMxPayload = 0;
331 pCsr->nUnused = 0;
332 pCsr->nPayload = 0;
333 pCsr->szPage = 0;
334 pCsr->nPage = 0;
335}
336
dan599e9d22010-07-12 08:39:37 +0000337/*
drh012b15e2019-11-19 18:48:11 +0000338** Close a DBSTAT cursor.
dan599e9d22010-07-12 08:39:37 +0000339*/
340static int statClose(sqlite3_vtab_cursor *pCursor){
341 StatCursor *pCsr = (StatCursor *)pCursor;
342 statResetCsr(pCsr);
343 sqlite3_finalize(pCsr->pStmt);
344 sqlite3_free(pCsr);
345 return SQLITE_OK;
346}
347
drhad84bd82019-11-19 14:01:51 +0000348/*
349** For a single cell on a btree page, compute the number of bytes of
350** content (payload) stored on that page. That is to say, compute the
351** number of bytes of content not found on overflow pages.
352*/
353static int getLocalPayload(
dan599e9d22010-07-12 08:39:37 +0000354 int nUsable, /* Usable bytes per page */
355 u8 flags, /* Page flags */
drhad84bd82019-11-19 14:01:51 +0000356 int nTotal /* Total record (payload) size */
dan599e9d22010-07-12 08:39:37 +0000357){
358 int nLocal;
359 int nMinLocal;
360 int nMaxLocal;
361
362 if( flags==0x0D ){ /* Table leaf node */
363 nMinLocal = (nUsable - 12) * 32 / 255 - 23;
364 nMaxLocal = nUsable - 35;
365 }else{ /* Index interior and leaf nodes */
366 nMinLocal = (nUsable - 12) * 32 / 255 - 23;
367 nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
368 }
369
370 nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
371 if( nLocal>nMaxLocal ) nLocal = nMinLocal;
drhad84bd82019-11-19 14:01:51 +0000372 return nLocal;
dan599e9d22010-07-12 08:39:37 +0000373}
374
drh012b15e2019-11-19 18:48:11 +0000375/* Populate the StatPage object with information about the all
376** cells found on the page currently under analysis.
377*/
dan599e9d22010-07-12 08:39:37 +0000378static int statDecodePage(Btree *pBt, StatPage *p){
379 int nUnused;
380 int iOff;
381 int nHdr;
382 int isLeaf;
drh4c9f1292011-09-28 00:50:14 +0000383 int szPage;
dan599e9d22010-07-12 08:39:37 +0000384
385 u8 *aData = sqlite3PagerGetData(p->pPg);
386 u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
387
388 p->flags = aHdr[0];
drhf8881582018-10-29 16:07:10 +0000389 if( p->flags==0x0A || p->flags==0x0D ){
390 isLeaf = 1;
391 nHdr = 8;
392 }else if( p->flags==0x05 || p->flags==0x02 ){
393 isLeaf = 0;
394 nHdr = 12;
395 }else{
396 goto statPageIsCorrupt;
397 }
398 if( p->iPgno==1 ) nHdr += 100;
dan599e9d22010-07-12 08:39:37 +0000399 p->nCell = get2byte(&aHdr[3]);
400 p->nMxPayload = 0;
drhf8881582018-10-29 16:07:10 +0000401 szPage = sqlite3BtreeGetPageSize(pBt);
dan599e9d22010-07-12 08:39:37 +0000402
403 nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
404 nUnused += (int)aHdr[7];
405 iOff = get2byte(&aHdr[1]);
406 while( iOff ){
drhf8881582018-10-29 16:07:10 +0000407 int iNext;
408 if( iOff>=szPage ) goto statPageIsCorrupt;
dan599e9d22010-07-12 08:39:37 +0000409 nUnused += get2byte(&aData[iOff+2]);
drhf8881582018-10-29 16:07:10 +0000410 iNext = get2byte(&aData[iOff]);
411 if( iNext<iOff+4 && iNext>0 ) goto statPageIsCorrupt;
412 iOff = iNext;
dan599e9d22010-07-12 08:39:37 +0000413 }
414 p->nUnused = nUnused;
415 p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
416
417 if( p->nCell ){
418 int i; /* Used to iterate through cells */
drhad0961b2015-02-21 00:19:25 +0000419 int nUsable; /* Usable bytes per page */
dan599e9d22010-07-12 08:39:37 +0000420
drhad0961b2015-02-21 00:19:25 +0000421 sqlite3BtreeEnter(pBt);
422 nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
423 sqlite3BtreeLeave(pBt);
drhf3cdcdc2015-04-29 16:50:28 +0000424 p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
mistachkinfad30392016-02-13 23:43:46 +0000425 if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
dan599e9d22010-07-12 08:39:37 +0000426 memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
427
428 for(i=0; i<p->nCell; i++){
429 StatCell *pCell = &p->aCell[i];
430
431 iOff = get2byte(&aData[nHdr+i*2]);
drhf8881582018-10-29 16:07:10 +0000432 if( iOff<nHdr || iOff>=szPage ) goto statPageIsCorrupt;
dan599e9d22010-07-12 08:39:37 +0000433 if( !isLeaf ){
434 pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
435 iOff += 4;
436 }
437 if( p->flags==0x05 ){
438 /* A table interior node. nPayload==0. */
439 }else{
440 u32 nPayload; /* Bytes of payload total (local+overflow) */
441 int nLocal; /* Bytes of payload stored locally */
442 iOff += getVarint32(&aData[iOff], nPayload);
443 if( p->flags==0x0D ){
444 u64 dummy;
445 iOff += sqlite3GetVarint(&aData[iOff], &dummy);
446 }
drh7da5fcb2012-03-30 14:59:43 +0000447 if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
drhad84bd82019-11-19 14:01:51 +0000448 nLocal = getLocalPayload(nUsable, p->flags, nPayload);
drhf8881582018-10-29 16:07:10 +0000449 if( nLocal<0 ) goto statPageIsCorrupt;
dan599e9d22010-07-12 08:39:37 +0000450 pCell->nLocal = nLocal;
drh26d8b0f2012-05-11 15:53:18 +0000451 assert( nPayload>=(u32)nLocal );
dan599e9d22010-07-12 08:39:37 +0000452 assert( nLocal<=(nUsable-35) );
drh7da5fcb2012-03-30 14:59:43 +0000453 if( nPayload>(u32)nLocal ){
dan599e9d22010-07-12 08:39:37 +0000454 int j;
455 int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
drhf0a21722020-03-19 17:27:52 +0000456 if( iOff+nLocal>nUsable || nPayload>0x7fffffff ){
457 goto statPageIsCorrupt;
458 }
dan599e9d22010-07-12 08:39:37 +0000459 pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
460 pCell->nOvfl = nOvfl;
drhf3cdcdc2015-04-29 16:50:28 +0000461 pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
mistachkinfad30392016-02-13 23:43:46 +0000462 if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
dan599e9d22010-07-12 08:39:37 +0000463 pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
464 for(j=1; j<nOvfl; j++){
465 int rc;
466 u32 iPrev = pCell->aOvfl[j-1];
467 DbPage *pPg = 0;
drh9584f582015-11-04 20:22:37 +0000468 rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
dan599e9d22010-07-12 08:39:37 +0000469 if( rc!=SQLITE_OK ){
470 assert( pPg==0 );
471 return rc;
472 }
473 pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
474 sqlite3PagerUnref(pPg);
475 }
476 }
477 }
478 }
479 }
480
481 return SQLITE_OK;
drhf8881582018-10-29 16:07:10 +0000482
483statPageIsCorrupt:
484 p->flags = 0;
drh5aa20372018-10-29 18:33:42 +0000485 statClearCells(p);
drhf8881582018-10-29 16:07:10 +0000486 return SQLITE_OK;
dan599e9d22010-07-12 08:39:37 +0000487}
488
dan599e9d22010-07-12 08:39:37 +0000489/*
dan2cf7e0a2011-10-05 17:36:27 +0000490** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
491** the current value of pCsr->iPageno.
492*/
493static void statSizeAndOffset(StatCursor *pCsr){
494 StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
drh857df262015-05-07 14:41:56 +0000495 Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
dan2cf7e0a2011-10-05 17:36:27 +0000496 Pager *pPager = sqlite3BtreePager(pBt);
497 sqlite3_file *fd;
498 sqlite3_int64 x[2];
499
drh012b15e2019-11-19 18:48:11 +0000500 /* If connected to a ZIPVFS backend, find the page size and
501 ** offset from ZIPVFS.
dan2cf7e0a2011-10-05 17:36:27 +0000502 */
503 fd = sqlite3PagerFile(pPager);
504 x[0] = pCsr->iPageno;
drhafb39a42018-03-29 13:47:01 +0000505 if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
dan2cf7e0a2011-10-05 17:36:27 +0000506 pCsr->iOffset = x[0];
drh012b15e2019-11-19 18:48:11 +0000507 pCsr->szPage += x[1];
508 }else{
509 /* Not ZIPVFS: The default page size and offset */
510 pCsr->szPage += sqlite3BtreeGetPageSize(pBt);
511 pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
dan2cf7e0a2011-10-05 17:36:27 +0000512 }
513}
514
515/*
drh012b15e2019-11-19 18:48:11 +0000516** Move a DBSTAT cursor to the next entry. Normally, the next
517** entry will be the next page, but in aggregated mode (pCsr->isAgg!=0),
518** the next entry is the next btree.
dan599e9d22010-07-12 08:39:37 +0000519*/
520static int statNext(sqlite3_vtab_cursor *pCursor){
521 int rc;
522 int nPayload;
drh5f36a832015-05-07 18:29:04 +0000523 char *z;
dan599e9d22010-07-12 08:39:37 +0000524 StatCursor *pCsr = (StatCursor *)pCursor;
525 StatTable *pTab = (StatTable *)pCursor->pVtab;
drha46a4a62015-09-08 21:12:53 +0000526 Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
dan599e9d22010-07-12 08:39:37 +0000527 Pager *pPager = sqlite3BtreePager(pBt);
528
529 sqlite3_free(pCsr->zPath);
530 pCsr->zPath = 0;
531
drha4641712013-11-02 11:34:58 +0000532statNextRestart:
dan599e9d22010-07-12 08:39:37 +0000533 if( pCsr->aPage[0].pPg==0 ){
drh012b15e2019-11-19 18:48:11 +0000534 /* Start measuring space on the next btree */
535 statResetCounts(pCsr);
dan599e9d22010-07-12 08:39:37 +0000536 rc = sqlite3_step(pCsr->pStmt);
537 if( rc==SQLITE_ROW ){
dan763afe62010-08-03 06:42:39 +0000538 int nPage;
drh7da5fcb2012-03-30 14:59:43 +0000539 u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
dan763afe62010-08-03 06:42:39 +0000540 sqlite3PagerPagecount(pPager, &nPage);
541 if( nPage==0 ){
542 pCsr->isEof = 1;
543 return sqlite3_reset(pCsr->pStmt);
544 }
drh9584f582015-11-04 20:22:37 +0000545 rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
dan599e9d22010-07-12 08:39:37 +0000546 pCsr->aPage[0].iPgno = iRoot;
547 pCsr->aPage[0].iCell = 0;
drh012b15e2019-11-19 18:48:11 +0000548 if( !pCsr->isAgg ){
549 pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
550 if( z==0 ) rc = SQLITE_NOMEM_BKPT;
551 }
dan599e9d22010-07-12 08:39:37 +0000552 pCsr->iPage = 0;
drh012b15e2019-11-19 18:48:11 +0000553 pCsr->nPage = 1;
dan599e9d22010-07-12 08:39:37 +0000554 }else{
555 pCsr->isEof = 1;
556 return sqlite3_reset(pCsr->pStmt);
557 }
558 }else{
drh012b15e2019-11-19 18:48:11 +0000559 /* Continue analyzing the btree previously started */
dan599e9d22010-07-12 08:39:37 +0000560 StatPage *p = &pCsr->aPage[pCsr->iPage];
drh012b15e2019-11-19 18:48:11 +0000561 if( !pCsr->isAgg ) statResetCounts(pCsr);
dan599e9d22010-07-12 08:39:37 +0000562 while( p->iCell<p->nCell ){
563 StatCell *pCell = &p->aCell[p->iCell];
drh012b15e2019-11-19 18:48:11 +0000564 while( pCell->iOvfl<pCell->nOvfl ){
565 int nUsable, iOvfl;
drhad0961b2015-02-21 00:19:25 +0000566 sqlite3BtreeEnter(pBt);
567 nUsable = sqlite3BtreeGetPageSize(pBt) -
568 sqlite3BtreeGetReserveNoMutex(pBt);
569 sqlite3BtreeLeave(pBt);
drh012b15e2019-11-19 18:48:11 +0000570 pCsr->nPage++;
dan2cf7e0a2011-10-05 17:36:27 +0000571 statSizeAndOffset(pCsr);
drh012b15e2019-11-19 18:48:11 +0000572 if( pCell->iOvfl<pCell->nOvfl-1 ){
573 pCsr->nPayload += nUsable - 4;
574 }else{
575 pCsr->nPayload += pCell->nLastOvfl;
576 pCsr->nUnused += nUsable - 4 - pCell->nLastOvfl;
577 }
578 iOvfl = pCell->iOvfl;
579 pCell->iOvfl++;
580 if( !pCsr->isAgg ){
581 pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
582 pCsr->iPageno = pCell->aOvfl[iOvfl];
583 pCsr->zPagetype = "overflow";
584 pCsr->zPath = z = sqlite3_mprintf(
585 "%s%.3x+%.6x", p->zPath, p->iCell, iOvfl
586 );
587 return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
588 }
dan599e9d22010-07-12 08:39:37 +0000589 }
590 if( p->iRightChildPg ) break;
591 p->iCell++;
592 }
593
drha4641712013-11-02 11:34:58 +0000594 if( !p->iRightChildPg || p->iCell>p->nCell ){
dan599e9d22010-07-12 08:39:37 +0000595 statClearPage(p);
drh012b15e2019-11-19 18:48:11 +0000596 if( pCsr->iPage>0 ){
597 pCsr->iPage--;
598 }else if( pCsr->isAgg ){
599 /* label-statNext-done: When computing aggregate space usage over
600 ** an entire btree, this is the exit point from this function */
601 return SQLITE_OK;
602 }
drha4641712013-11-02 11:34:58 +0000603 goto statNextRestart; /* Tail recursion */
dan599e9d22010-07-12 08:39:37 +0000604 }
605 pCsr->iPage++;
drh8eaf5652019-01-09 11:19:41 +0000606 if( pCsr->iPage>=ArraySize(pCsr->aPage) ){
607 statResetCsr(pCsr);
608 return SQLITE_CORRUPT_BKPT;
609 }
dan599e9d22010-07-12 08:39:37 +0000610 assert( p==&pCsr->aPage[pCsr->iPage-1] );
611
612 if( p->iCell==p->nCell ){
613 p[1].iPgno = p->iRightChildPg;
614 }else{
615 p[1].iPgno = p->aCell[p->iCell].iChildPg;
616 }
drh9584f582015-11-04 20:22:37 +0000617 rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
drh012b15e2019-11-19 18:48:11 +0000618 pCsr->nPage++;
dan599e9d22010-07-12 08:39:37 +0000619 p[1].iCell = 0;
drh012b15e2019-11-19 18:48:11 +0000620 if( !pCsr->isAgg ){
621 p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
622 if( z==0 ) rc = SQLITE_NOMEM_BKPT;
623 }
dan599e9d22010-07-12 08:39:37 +0000624 p->iCell++;
625 }
626
627
628 /* Populate the StatCursor fields with the values to be returned
629 ** by the xColumn() and xRowid() methods.
630 */
631 if( rc==SQLITE_OK ){
632 int i;
633 StatPage *p = &pCsr->aPage[pCsr->iPage];
634 pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
635 pCsr->iPageno = p->iPgno;
636
dan995f8b92015-04-27 19:53:55 +0000637 rc = statDecodePage(pBt, p);
638 if( rc==SQLITE_OK ){
639 statSizeAndOffset(pCsr);
drh4c9f1292011-09-28 00:50:14 +0000640
dan995f8b92015-04-27 19:53:55 +0000641 switch( p->flags ){
642 case 0x05: /* table internal */
643 case 0x02: /* index internal */
644 pCsr->zPagetype = "internal";
645 break;
646 case 0x0D: /* table leaf */
647 case 0x0A: /* index leaf */
648 pCsr->zPagetype = "leaf";
649 break;
650 default:
651 pCsr->zPagetype = "corrupted";
652 break;
653 }
drh012b15e2019-11-19 18:48:11 +0000654 pCsr->nCell += p->nCell;
655 pCsr->nUnused += p->nUnused;
656 if( p->nMxPayload>pCsr->nMxPayload ) pCsr->nMxPayload = p->nMxPayload;
657 if( !pCsr->isAgg ){
658 pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
659 if( z==0 ) rc = SQLITE_NOMEM_BKPT;
660 }
dan995f8b92015-04-27 19:53:55 +0000661 nPayload = 0;
662 for(i=0; i<p->nCell; i++){
663 nPayload += p->aCell[i].nLocal;
664 }
drh012b15e2019-11-19 18:48:11 +0000665 pCsr->nPayload += nPayload;
666
667 /* If computing aggregate space usage by btree, continue with the
668 ** next page. The loop will exit via the return at label-statNext-done
669 */
670 if( pCsr->isAgg ) goto statNextRestart;
dan599e9d22010-07-12 08:39:37 +0000671 }
dan599e9d22010-07-12 08:39:37 +0000672 }
673
674 return rc;
675}
676
677static int statEof(sqlite3_vtab_cursor *pCursor){
678 StatCursor *pCsr = (StatCursor *)pCursor;
679 return pCsr->isEof;
680}
681
drhad84bd82019-11-19 14:01:51 +0000682/* Initialize a cursor according to the query plan idxNum using the
683** arguments in argv[0]. See statBestIndex() for a description of the
684** meaning of the bits in idxNum.
685*/
dan599e9d22010-07-12 08:39:37 +0000686static int statFilter(
687 sqlite3_vtab_cursor *pCursor,
688 int idxNum, const char *idxStr,
689 int argc, sqlite3_value **argv
690){
dan599e9d22010-07-12 08:39:37 +0000691 StatCursor *pCsr = (StatCursor *)pCursor;
drha46a4a62015-09-08 21:12:53 +0000692 StatTable *pTab = (StatTable*)(pCursor->pVtab);
drhad84bd82019-11-19 14:01:51 +0000693 sqlite3_str *pSql; /* Query of btrees to analyze */
694 char *zSql; /* String value of pSql */
695 int iArg = 0; /* Count of argv[] parameters used so far */
696 int rc = SQLITE_OK; /* Result of this operation */
697 const char *zName = 0; /* Only provide analysis of this table */
dan599e9d22010-07-12 08:39:37 +0000698
drhad84bd82019-11-19 14:01:51 +0000699 statResetCsr(pCsr);
700 sqlite3_finalize(pCsr->pStmt);
701 pCsr->pStmt = 0;
702 if( idxNum & 0x01 ){
703 /* schema=? constraint is present. Get its value */
704 const char *zDbase = (const char*)sqlite3_value_text(argv[iArg++]);
drha46a4a62015-09-08 21:12:53 +0000705 pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
706 if( pCsr->iDb<0 ){
drh2e5bedd2020-01-04 19:14:48 +0000707 pCsr->iDb = 0;
708 pCsr->isEof = 1;
709 return SQLITE_OK;
drha46a4a62015-09-08 21:12:53 +0000710 }
711 }else{
712 pCsr->iDb = pTab->iDb;
713 }
drhad84bd82019-11-19 14:01:51 +0000714 if( idxNum & 0x02 ){
715 /* name=? constraint is present */
716 zName = (const char*)sqlite3_value_text(argv[iArg++]);
717 }
718 if( idxNum & 0x04 ){
719 /* aggregate=? constraint is present */
720 pCsr->isAgg = sqlite3_value_double(argv[iArg++])!=0.0;
721 }else{
722 pCsr->isAgg = 0;
723 }
724 pSql = sqlite3_str_new(pTab->db);
725 sqlite3_str_appendf(pSql,
726 "SELECT * FROM ("
drh1e32bed2020-06-19 13:33:53 +0000727 "SELECT 'sqlite_schema' AS name,1 AS rootpage,'table' AS type"
drhad84bd82019-11-19 14:01:51 +0000728 " UNION ALL "
729 "SELECT name,rootpage,type"
drh1e32bed2020-06-19 13:33:53 +0000730 " FROM \"%w\".sqlite_schema WHERE rootpage!=0)",
drhad84bd82019-11-19 14:01:51 +0000731 pTab->db->aDb[pCsr->iDb].zDbSName);
732 if( zName ){
733 sqlite3_str_appendf(pSql, "WHERE name=%Q", zName);
734 }
735 if( idxNum & 0x08 ){
736 sqlite3_str_appendf(pSql, " ORDER BY name");
737 }
738 zSql = sqlite3_str_finish(pSql);
drha46a4a62015-09-08 21:12:53 +0000739 if( zSql==0 ){
mistachkinfad30392016-02-13 23:43:46 +0000740 return SQLITE_NOMEM_BKPT;
drha46a4a62015-09-08 21:12:53 +0000741 }else{
742 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
743 sqlite3_free(zSql);
744 }
745
746 if( rc==SQLITE_OK ){
747 rc = statNext(pCursor);
748 }
749 return rc;
dan599e9d22010-07-12 08:39:37 +0000750}
751
752static int statColumn(
753 sqlite3_vtab_cursor *pCursor,
754 sqlite3_context *ctx,
755 int i
756){
757 StatCursor *pCsr = (StatCursor *)pCursor;
758 switch( i ){
759 case 0: /* name */
drh5f36a832015-05-07 18:29:04 +0000760 sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
dan599e9d22010-07-12 08:39:37 +0000761 break;
762 case 1: /* path */
drh012b15e2019-11-19 18:48:11 +0000763 if( !pCsr->isAgg ){
764 sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
765 }
dan599e9d22010-07-12 08:39:37 +0000766 break;
767 case 2: /* pageno */
drh012b15e2019-11-19 18:48:11 +0000768 if( pCsr->isAgg ){
769 sqlite3_result_int64(ctx, pCsr->nPage);
770 }else{
771 sqlite3_result_int64(ctx, pCsr->iPageno);
772 }
dan599e9d22010-07-12 08:39:37 +0000773 break;
774 case 3: /* pagetype */
drh012b15e2019-11-19 18:48:11 +0000775 if( !pCsr->isAgg ){
776 sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
777 }
dan599e9d22010-07-12 08:39:37 +0000778 break;
779 case 4: /* ncell */
780 sqlite3_result_int(ctx, pCsr->nCell);
781 break;
782 case 5: /* payload */
783 sqlite3_result_int(ctx, pCsr->nPayload);
784 break;
785 case 6: /* unused */
786 sqlite3_result_int(ctx, pCsr->nUnused);
787 break;
788 case 7: /* mx_payload */
789 sqlite3_result_int(ctx, pCsr->nMxPayload);
790 break;
drh4c9f1292011-09-28 00:50:14 +0000791 case 8: /* pgoffset */
drh012b15e2019-11-19 18:48:11 +0000792 if( !pCsr->isAgg ){
793 sqlite3_result_int64(ctx, pCsr->iOffset);
794 }
drh4c9f1292011-09-28 00:50:14 +0000795 break;
drha46a4a62015-09-08 21:12:53 +0000796 case 9: /* pgsize */
drh4c9f1292011-09-28 00:50:14 +0000797 sqlite3_result_int(ctx, pCsr->szPage);
798 break;
drhad84bd82019-11-19 14:01:51 +0000799 case 10: { /* schema */
drha46a4a62015-09-08 21:12:53 +0000800 sqlite3 *db = sqlite3_context_db_handle(ctx);
801 int iDb = pCsr->iDb;
drh69c33822016-08-18 14:33:11 +0000802 sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
drha46a4a62015-09-08 21:12:53 +0000803 break;
804 }
drhad84bd82019-11-19 14:01:51 +0000805 default: { /* aggregate */
806 sqlite3_result_int(ctx, pCsr->isAgg);
807 break;
808 }
dan599e9d22010-07-12 08:39:37 +0000809 }
810 return SQLITE_OK;
811}
812
813static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
814 StatCursor *pCsr = (StatCursor *)pCursor;
815 *pRowid = pCsr->iPageno;
816 return SQLITE_OK;
817}
818
drh1a4a6802015-05-04 18:31:09 +0000819/*
820** Invoke this routine to register the "dbstat" virtual table module
821*/
drh3e0327d2015-05-11 11:59:15 +0000822int sqlite3DbstatRegister(sqlite3 *db){
dan599e9d22010-07-12 08:39:37 +0000823 static sqlite3_module dbstat_module = {
824 0, /* iVersion */
825 statConnect, /* xCreate */
826 statConnect, /* xConnect */
827 statBestIndex, /* xBestIndex */
828 statDisconnect, /* xDisconnect */
829 statDisconnect, /* xDestroy */
830 statOpen, /* xOpen - open a cursor */
831 statClose, /* xClose - close a cursor */
832 statFilter, /* xFilter - configure scan constraints */
833 statNext, /* xNext - advance a cursor */
834 statEof, /* xEof - check for end of scan */
835 statColumn, /* xColumn - read data */
836 statRowid, /* xRowid - read data */
837 0, /* xUpdate */
838 0, /* xBegin */
839 0, /* xSync */
840 0, /* xCommit */
841 0, /* xRollback */
842 0, /* xFindMethod */
843 0, /* xRename */
drh7ccf95d2017-07-12 18:05:54 +0000844 0, /* xSavepoint */
845 0, /* xRelease */
846 0, /* xRollbackTo */
drh84c501b2018-11-05 23:01:45 +0000847 0 /* xShadowName */
dan599e9d22010-07-12 08:39:37 +0000848 };
dand154a432015-04-30 20:26:53 +0000849 return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
dan599e9d22010-07-12 08:39:37 +0000850}
drh10819252015-05-12 14:22:05 +0000851#elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
drh6582ae52015-05-12 12:24:50 +0000852int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
drh1a4a6802015-05-04 18:31:09 +0000853#endif /* SQLITE_ENABLE_DBSTAT_VTAB */