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