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/tool/spaceanal.tcl # 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 / tool / spaceanal.tcl` 920 lines ยท 31175 bytes Raw Blame History 1 # Run this TCL script using an SQLite-enabled TCL interpreter to get a report 2 # on how much disk space is used by a particular data to actually store data 3 # versus how much space is unused. 4 # 5 # The dbstat virtual table is required. 6 # 7 8 if {[catch { 9 10 # Argument $tname is the name of a table within the database opened by 11 # database handle [db]. Return true if it is a WITHOUT ROWID table, or 12 # false otherwise. 13 # 14 proc is_without_rowid {tname} { 15 set t [string map {' ''} $tname] 16 db eval "PRAGMA index_list = '$t'" o { 17 if {$o(origin) == "pk"} { 18 set n $o(name) 19 if {0==[db one { SELECT count(*) FROM sqlite_schema WHERE name=$n }]} { 20 return 1 21 } 22 } 23 } 24 return 0 25 } 26 27 # Read and run TCL commands from standard input. Used to implement 28 # the --tclsh option. 29 # 30 proc tclsh {} { 31 set line {} 32 while {![eof stdin]} { 33 if {$line!=""} { 34 puts -nonewline "> " 35 } else { 36 puts -nonewline "% " 37 } 38 flush stdout 39 append line [gets stdin] 40 if {[info complete $line]} { 41 if {[catch {uplevel #0 $line} result]} { 42 puts stderr "Error: $result" 43 } elseif {$result!=""} { 44 puts $result 45 } 46 set line {} 47 } else { 48 append line \n 49 } 50 } 51 } 52 53 54 # Get the name of the database to analyze 55 # 56 proc usage {} { 57 set argv0 [file rootname [file tail [info nameofexecutable]]] 58 puts stderr "Usage: $argv0 ?--pageinfo? ?--stats? database-filename" 59 puts stderr { 60 Analyze the SQLite3 database file specified by the "database-filename" 61 argument and output a report detailing size and storage efficiency 62 information for the database and its constituent tables and indexes. 63 64 Options: 65 66 --pageinfo Show how each page of the database-file is used 67 68 --stats Output SQL text that creates a new database containing 69 statistics about the database that was analyzed 70 71 --tclsh Run the built-in TCL interpreter interactively (for debugging) 72 73 --version Show the version number of SQLite 74 } 75 exit 1 76 } 77 78 # Exit with given code, but first close db if open. 79 # 80 proc exit_clean {exit_code} { 81 if {0 < [llength [info commands db]]} { 82 db close 83 } 84 exit $exit_code 85 } 86 87 set file_to_analyze {} 88 set flags(-pageinfo) 0 89 set flags(-stats) 0 90 set flags(-debug) 0 91 append argv {} 92 foreach arg $argv { 93 if {[regexp {^-+pageinfo$} $arg]} { 94 set flags(-pageinfo) 1 95 } elseif {[regexp {^-+stats$} $arg]} { 96 set flags(-stats) 1 97 } elseif {[regexp {^-+debug$} $arg]} { 98 set flags(-debug) 1 99 } elseif {[regexp {^-+tclsh$} $arg]} { 100 tclsh 101 exit 0 102 } elseif {[regexp {^-+version$} $arg]} { 103 sqlite3 mem :memory: 104 puts [mem one {SELECT sqlite_version()||' '||sqlite_source_id()}] 105 mem close 106 exit 0 107 } elseif {[regexp {^-} $arg]} { 108 puts stderr "Unknown option: $arg" 109 usage 110 } elseif {$file_to_analyze!=""} { 111 usage 112 } else { 113 set file_to_analyze $arg 114 } 115 } 116 if {$file_to_analyze==""} usage 117 set root_filename $file_to_analyze 118 regexp {^file:(//)?([^?]*)} $file_to_analyze all x1 root_filename 119 if {![file exists $root_filename]} { 120 puts stderr "No such file: $root_filename" 121 exit 1 122 } 123 if {![file readable $root_filename]} { 124 puts stderr "File is not readable: $root_filename" 125 exit 1 126 } 127 set true_file_size [file size $root_filename] 128 if {$true_file_size<512} { 129 puts stderr "Empty or malformed database: $root_filename" 130 exit 1 131 } 132 133 # Compute the total file size assuming test_multiplexor is being used. 134 # Assume that SQLITE_ENABLE_8_3_NAMES might be enabled 135 # 136 set extension [file extension $root_filename] 137 set pattern $root_filename 138 append pattern {[0-3][0-9][0-9]} 139 foreach f [glob -nocomplain $pattern] { 140 incr true_file_size [file size $f] 141 set extension {} 142 } 143 if {[string length $extension]>=2 && [string length $extension]<=4} { 144 set pattern [file rootname $root_filename] 145 append pattern {.[0-3][0-9][0-9]} 146 foreach f [glob -nocomplain $pattern] { 147 incr true_file_size [file size $f] 148 } 149 } 150 151 # Open the database 152 # 153 if {[catch {sqlite3 db $file_to_analyze -uri 1} msg]} { 154 puts stderr "error trying to open $file_to_analyze: $msg" 155 exit 1 156 } 157 if {$flags(-debug)} { 158 proc dbtrace {txt} {puts $txt; flush stdout;} 159 db trace ::dbtrace 160 } 161 162 # Make sure all required compile-time options are available 163 # 164 if {![db exists {SELECT 1 FROM pragma_compile_options 165 WHERE compile_options='ENABLE_DBSTAT_VTAB'}]} { 166 puts "The SQLite database engine linked with this application\ 167 lacks required capabilities. Recompile using the\ 168 -DSQLITE_ENABLE_DBSTAT_VTAB compile-time option to fix\ 169 this problem." 170 exit_clean 1 171 } 172 173 db eval {SELECT count(*) FROM sqlite_schema} 174 set pageSize [expr {wide([db one {PRAGMA page_size}])}] 175 176 if {$flags(-pageinfo)} { 177 db eval {CREATE VIRTUAL TABLE temp.stat USING dbstat} 178 db eval {SELECT name, path, pageno FROM temp.stat ORDER BY pageno} { 179 puts "$pageno $name $path" 180 } 181 exit_clean 0 182 } 183 if {$flags(-stats)} { 184 db eval {CREATE VIRTUAL TABLE temp.stat USING dbstat} 185 puts "BEGIN;" 186 puts "CREATE TABLE stats(" 187 puts " name STRING, /* Name of table or index */" 188 puts " path INTEGER, /* Path to page from root */" 189 puts " pageno INTEGER, /* Page number */" 190 puts " pagetype STRING, /* 'internal', 'leaf' or 'overflow' */" 191 puts " ncell INTEGER, /* Cells on page (0 for overflow) */" 192 puts " payload INTEGER, /* Bytes of payload on this page */" 193 puts " unused INTEGER, /* Bytes of unused space on this page */" 194 puts " mx_payload INTEGER, /* Largest payload size of all cells */" 195 puts " pgoffset INTEGER, /* Offset of page in file */" 196 puts " pgsize INTEGER /* Size of the page */" 197 puts ");" 198 db eval {SELECT quote(name) || ',' || 199 quote(path) || ',' || 200 quote(pageno) || ',' || 201 quote(pagetype) || ',' || 202 quote(ncell) || ',' || 203 quote(payload) || ',' || 204 quote(unused) || ',' || 205 quote(mx_payload) || ',' || 206 quote(pgoffset) || ',' || 207 quote(pgsize) AS x FROM stat} { 208 puts "INSERT INTO stats VALUES($x);" 209 } 210 puts "COMMIT;" 211 exit_clean 0 212 } 213 214 215 # In-memory database for collecting statistics. This script loops through 216 # the tables and indices in the database being analyzed, adding a row for each 217 # to an in-memory database (for which the schema is shown below). It then 218 # queries the in-memory db to produce the space-analysis report. 219 # 220 sqlite3 mem :memory: 221 if {$flags(-debug)} { 222 proc dbtrace {txt} {puts $txt; flush stdout;} 223 mem trace ::dbtrace 224 } 225 set tabledef {CREATE TABLE space_used( 226 name clob, -- Name of a table or index in the database file 227 tblname clob, -- Name of associated table 228 is_index boolean, -- TRUE if it is an index, false for a table 229 is_without_rowid boolean, -- TRUE if WITHOUT ROWID table 230 nentry int, -- Number of entries in the BTree 231 leaf_entries int, -- Number of leaf entries 232 depth int, -- Depth of the b-tree 233 payload int, -- Total amount of data stored in this table or index 234 ovfl_payload int, -- Total amount of data stored on overflow pages 235 ovfl_cnt int, -- Number of entries that use overflow 236 mx_payload int, -- Maximum payload size 237 int_pages int, -- Number of interior pages used 238 leaf_pages int, -- Number of leaf pages used 239 ovfl_pages int, -- Number of overflow pages used 240 int_unused int, -- Number of unused bytes on interior pages 241 leaf_unused int, -- Number of unused bytes on primary pages 242 ovfl_unused int, -- Number of unused bytes on overflow pages 243 gap_cnt int, -- Number of gaps in the page layout 244 compressed_size int -- Total bytes stored on disk 245 );} 246 mem eval $tabledef 247 248 # Create a temporary "dbstat" virtual table. 249 # 250 db eval {CREATE VIRTUAL TABLE temp.stat USING dbstat} 251 db eval {CREATE TEMP TABLE dbstat AS SELECT * FROM temp.stat 252 ORDER BY name, path} 253 db eval {DROP TABLE temp.stat} 254 255 set isCompressed 0 256 set compressOverhead 0 257 set depth 0 258 set sql { SELECT name, tbl_name FROM sqlite_schema WHERE rootpage>0 } 259 foreach {name tblname} [concat sqlite_schema sqlite_schema [db eval $sql]] { 260 261 set is_index [expr {$name!=$tblname}] 262 set is_without_rowid [is_without_rowid $name] 263 db eval { 264 SELECT 265 sum(ncell) AS nentry, 266 sum((pagetype=='leaf')*ncell) AS leaf_entries, 267 sum(payload) AS payload, 268 sum((pagetype=='overflow') * payload) AS ovfl_payload, 269 sum(path LIKE '%+000000') AS ovfl_cnt, 270 max(mx_payload) AS mx_payload, 271 sum(pagetype=='internal') AS int_pages, 272 sum(pagetype=='leaf') AS leaf_pages, 273 sum(pagetype=='overflow') AS ovfl_pages, 274 sum((pagetype=='internal') * unused) AS int_unused, 275 sum((pagetype=='leaf') * unused) AS leaf_unused, 276 sum((pagetype=='overflow') * unused) AS ovfl_unused, 277 sum(pgsize) AS compressed_size, 278 max((length(CASE WHEN path LIKE '%+%' THEN '' ELSE path END)+3)/4) 279 AS depth 280 FROM temp.dbstat WHERE name = $name 281 } break 282 283 set total_pages [expr {$leaf_pages+$int_pages+$ovfl_pages}] 284 set storage [expr {$total_pages*$pageSize}] 285 if {!$isCompressed && $storage>$compressed_size} { 286 set isCompressed 1 287 set compressOverhead 14 288 } 289 290 # Column 'gap_cnt' is set to the number of non-contiguous entries in the 291 # list of pages visited if the b-tree structure is traversed in a top-down 292 # fashion (each node visited before its child-tree is passed). Any overflow 293 # chains present are traversed from start to finish before any child-tree 294 # is. 295 # 296 set gap_cnt 0 297 set prev 0 298 db eval { 299 SELECT pageno, pagetype FROM temp.dbstat 300 WHERE name=$name 301 ORDER BY pageno 302 } { 303 if {$prev>0 && $pagetype=="leaf" && $pageno!=$prev+1} { 304 incr gap_cnt 305 } 306 set prev $pageno 307 } 308 mem eval { 309 INSERT INTO space_used VALUES( 310 $name, 311 $tblname, 312 $is_index, 313 $is_without_rowid, 314 $nentry, 315 $leaf_entries, 316 $depth, 317 $payload, 318 $ovfl_payload, 319 $ovfl_cnt, 320 $mx_payload, 321 $int_pages, 322 $leaf_pages, 323 $ovfl_pages, 324 $int_unused, 325 $leaf_unused, 326 $ovfl_unused, 327 $gap_cnt, 328 $compressed_size 329 ); 330 } 331 } 332 333 proc integerify {real} { 334 if {[string is double -strict $real]} { 335 return [expr {wide($real)}] 336 } else { 337 return 0 338 } 339 } 340 mem function int integerify 341 342 # Quote a string for use in an SQL query. Examples: 343 # 344 # [quote {hello world}] == {'hello world'} 345 # [quote {hello world's}] == {'hello world''s'} 346 # 347 proc quote {txt} { 348 return [string map {' ''} $txt] 349 } 350 351 # Output a title line 352 # 353 proc titleline {title} { 354 set title [string map {*/ +/} $title] 355 if {$title==""} { 356 puts [string repeat * 79] 357 } else { 358 set len [string length $title] 359 set stars [string repeat * [expr 79-$len-5]] 360 puts "*** $title $stars" 361 } 362 } 363 364 # Generate a single line of output in the statistics section of the 365 # report. 366 # 367 proc statline {title value {extra {}}} { 368 set title [string map {*/ +/} $title] 369 set len [string length $title] 370 set dots [string repeat . [expr 50-$len]] 371 set len [string length $value] 372 set sp2 [string range { } $len end] 373 if {$extra ne ""} { 374 set extra " $extra" 375 } 376 puts "$title$dots $value$sp2$extra" 377 } 378 379 # Generate a formatted percentage value for $num/$denom 380 # 381 proc percent {num denom {of {}}} { 382 if {$denom==0.0} {return ""} 383 set v [expr {$num*100.0/$denom}] 384 set of {} 385 if {$v==100.0 || $v<0.001 || ($v>1.0 && $v<99.0)} { 386 return [format {%5.1f%% %s} $v $of] 387 } elseif {$v<0.1 || $v>99.9} { 388 return [format {%7.3f%% %s} $v $of] 389 } else { 390 return [format {%6.2f%% %s} $v $of] 391 } 392 } 393 394 proc divide {num denom} { 395 if {$denom==0} {return 0.0} 396 return [format %.2f [expr double($num)/double($denom)]] 397 } 398 399 # Generate a subreport that covers some subset of the database. 400 # the $where clause determines which subset to analyze. 401 # 402 proc subreport {title where showFrag} { 403 global pageSize file_pgcnt compressOverhead 404 405 # Query the in-memory database for the sum of various statistics 406 # for the subset of tables/indices identified by the WHERE clause in 407 # $where. Note that even if the WHERE clause matches no rows, the 408 # following query returns exactly one row (because it is an aggregate). 409 # 410 # The results of the query are stored directly by SQLite into local 411 # variables (i.e. $nentry, $payload etc.). 412 # 413 mem eval " 414 SELECT 415 int(sum( 416 CASE WHEN (is_without_rowid OR is_index) THEN nentry 417 ELSE leaf_entries 418 END 419 )) AS nentry, 420 int(sum(payload)) AS payload, 421 int(sum(ovfl_payload)) AS ovfl_payload, 422 max(mx_payload) AS mx_payload, 423 int(sum(ovfl_cnt)) as ovfl_cnt, 424 int(sum(leaf_pages)) AS leaf_pages, 425 int(sum(int_pages)) AS int_pages, 426 int(sum(ovfl_pages)) AS ovfl_pages, 427 int(sum(leaf_unused)) AS leaf_unused, 428 int(sum(int_unused)) AS int_unused, 429 int(sum(ovfl_unused)) AS ovfl_unused, 430 int(sum(gap_cnt)) AS gap_cnt, 431 int(sum(compressed_size)) AS compressed_size, 432 int(max(depth)) AS depth, 433 count(*) AS cnt 434 FROM space_used WHERE $where" {} {} 435 436 # Output the sub-report title, nicely decorated with * characters. 437 # 438 puts "" 439 titleline $title 440 puts "" 441 442 # Calculate statistics and store the results in TCL variables, as follows: 443 # 444 # total_pages: Database pages consumed. 445 # total_pages_percent: Pages consumed as a percentage of the file. 446 # storage: Bytes consumed. 447 # payload_percent: Payload bytes used as a percentage of $storage. 448 # total_unused: Unused bytes on pages. 449 # avg_payload: Average payload per btree entry. 450 # avg_fanout: Average fanout for internal pages. 451 # avg_unused: Average unused bytes per btree entry. 452 # avg_meta: Average metadata overhead per entry. 453 # ovfl_cnt_percent: Percentage of btree entries that use overflow pages. 454 # 455 set total_pages [expr {$leaf_pages+$int_pages+$ovfl_pages}] 456 set total_pages_percent [percent $total_pages $file_pgcnt] 457 set storage [expr {$total_pages*$pageSize}] 458 set payload_percent [percent $payload $storage {of storage consumed}] 459 set total_unused [expr {$ovfl_unused+$int_unused+$leaf_unused}] 460 set avg_payload [divide $payload $nentry] 461 set avg_unused [divide $total_unused $nentry] 462 set total_meta [expr {$storage - $payload - $total_unused}] 463 set total_meta [expr {$total_meta + 4*($ovfl_pages - $ovfl_cnt)}] 464 set meta_percent [percent $total_meta $storage {of metadata}] 465 set avg_meta [divide $total_meta $nentry] 466 if {$int_pages>0} { 467 # TODO: Is this formula correct? 468 set nTab [mem eval " 469 SELECT count(*) FROM ( 470 SELECT DISTINCT tblname FROM space_used WHERE $where AND is_index=0 471 ) 472 "] 473 set avg_fanout [mem eval " 474 SELECT (sum(leaf_pages+int_pages)-$nTab)/sum(int_pages) FROM space_used 475 WHERE $where 476 "] 477 set avg_fanout [format %.2f $avg_fanout] 478 } 479 set ovfl_cnt_percent [percent $ovfl_cnt $nentry {of all entries}] 480 481 # Print out the sub-report statistics. 482 # 483 statline {Percentage of total database} $total_pages_percent 484 statline {Number of entries} $nentry 485 statline {Bytes of storage consumed} $storage 486 if {$compressed_size!=$storage} { 487 set compressed_size [expr {$compressed_size+$compressOverhead*$total_pages}] 488 set pct [expr {$compressed_size*100.0/$storage}] 489 set pct [format {%5.1f%%} $pct] 490 statline {Bytes used after compression} $compressed_size $pct 491 } 492 statline {Bytes of payload} $payload $payload_percent 493 statline {Bytes of metadata} $total_meta $meta_percent 494 if {$cnt==1} {statline {B-tree depth} $depth} 495 statline {Average payload per entry} $avg_payload 496 statline {Average unused bytes per entry} $avg_unused 497 statline {Average metadata per entry} $avg_meta 498 if {[info exists avg_fanout]} { 499 statline {Average fanout} $avg_fanout 500 } 501 if {$showFrag && $total_pages>1} { 502 set fragmentation [percent $gap_cnt [expr {$total_pages-1}]] 503 statline {Non-sequential pages} $gap_cnt $fragmentation 504 } 505 statline {Maximum payload per entry} $mx_payload 506 statline {Entries that use overflow} $ovfl_cnt $ovfl_cnt_percent 507 if {$int_pages>0} { 508 statline {Index pages used} $int_pages 509 } 510 statline {Primary pages used} $leaf_pages 511 statline {Overflow pages used} $ovfl_pages 512 statline {Total pages used} $total_pages 513 if {$int_unused>0} { 514 set int_unused_percent [ 515 percent $int_unused [expr {$int_pages*$pageSize}] {of index space}] 516 statline "Unused bytes on index pages" $int_unused $int_unused_percent 517 } 518 statline "Unused bytes on primary pages" $leaf_unused [ 519 percent $leaf_unused [expr {$leaf_pages*$pageSize}] {of primary space}] 520 statline "Unused bytes on overflow pages" $ovfl_unused [ 521 percent $ovfl_unused [expr {$ovfl_pages*$pageSize}] {of overflow space}] 522 statline "Unused bytes on all pages" $total_unused [ 523 percent $total_unused $storage {of all space}] 524 return 1 525 } 526 527 # Calculate the overhead in pages caused by auto-vacuum. 528 # 529 # This procedure calculates and returns the number of pages used by the 530 # auto-vacuum 'pointer-map'. If the database does not support auto-vacuum, 531 # then 0 is returned. The two arguments are the size of the database file in 532 # pages and the page size used by the database (in bytes). 533 proc autovacuum_overhead {filePages pageSize} { 534 535 # Set $autovacuum to non-zero for databases that support auto-vacuum. 536 set autovacuum [db one {PRAGMA auto_vacuum}] 537 538 # If the database is not an auto-vacuum database or the file consists 539 # of one page only then there is no overhead for auto-vacuum. Return zero. 540 if {0==$autovacuum || $filePages==1} { 541 return 0 542 } 543 544 # The number of entries on each pointer map page. The layout of the 545 # database file is one pointer-map page, followed by $ptrsPerPage other 546 # pages, followed by a pointer-map page etc. The first pointer-map page 547 # is the second page of the file overall. 548 set ptrsPerPage [expr double($pageSize/5)] 549 550 # Return the number of pointer map pages in the database. 551 return [expr wide(ceil( ($filePages-1.0)/($ptrsPerPage+1.0) ))] 552 } 553 554 555 # Calculate the summary statistics for the database and store the results 556 # in TCL variables. They are output below. Variables are as follows: 557 # 558 # pageSize: Size of each page in bytes. 559 # file_bytes: File size in bytes. 560 # file_pgcnt: Number of pages in the file. 561 # file_pgcnt2: Number of pages in the file (calculated). 562 # av_pgcnt: Pages consumed by the auto-vacuum pointer-map. 563 # av_percent: Percentage of the file consumed by auto-vacuum pointer-map. 564 # inuse_pgcnt: Data pages in the file. 565 # inuse_percent: Percentage of pages used to store data. 566 # free_pgcnt: Free pages calculated as ( - ) 567 # free_pgcnt2: Free pages in the file according to the file header. 568 # free_percent: Percentage of file consumed by free pages (calculated). 569 # free_percent2: Percentage of file consumed by free pages (header). 570 # ntable: Number of tables in the db. 571 # nindex: Number of indices in the db. 572 # nautoindex: Number of indices created automatically. 573 # nmanindex: Number of indices created manually. 574 # user_payload: Number of bytes of payload in table btrees 575 # (not including sqlite_schema) 576 # user_percent: $user_payload as a percentage of total file size. 577 578 ### The following, setting $file_bytes based on the actual size of the file 579 ### on disk, causes this tool to choke on zipvfs databases. So set it based 580 ### on the return of [PRAGMA page_count] instead. 581 if 0 { 582 set file_bytes [file size $file_to_analyze] 583 set file_pgcnt [expr {$file_bytes/$pageSize}] 584 } 585 set file_pgcnt [db one {PRAGMA page_count}] 586 set file_bytes [expr {$file_pgcnt * $pageSize}] 587 588 set av_pgcnt [autovacuum_overhead $file_pgcnt $pageSize] 589 set av_percent [percent $av_pgcnt $file_pgcnt] 590 591 set sql {SELECT sum(leaf_pages+int_pages+ovfl_pages) FROM space_used} 592 set inuse_pgcnt [expr wide([mem eval $sql])] 593 set inuse_percent [percent $inuse_pgcnt $file_pgcnt] 594 595 set free_pgcnt [expr {$file_pgcnt-$inuse_pgcnt-$av_pgcnt}] 596 if {$file_bytes>`1073741824` && $free_pgcnt>0} {incr free_pgcnt -1} 597 set free_percent [percent $free_pgcnt $file_pgcnt] 598 set free_pgcnt2 [db one {PRAGMA freelist_count}] 599 set free_percent2 [percent $free_pgcnt2 $file_pgcnt] 600 601 set file_pgcnt2 [expr {$inuse_pgcnt+$free_pgcnt2+$av_pgcnt}] 602 603 # Account for the lockbyte page 604 if {$file_pgcnt2*$pageSize>`1073742335`} {incr file_pgcnt2} 605 606 set ntable [db eval {SELECT count(*)+1 FROM sqlite_schema WHERE type='table'}] 607 set nindex [db eval {SELECT count(*) FROM sqlite_schema WHERE type='index'}] 608 set sql {SELECT count(*) FROM sqlite_schema WHERE name LIKE 'sqlite_autoindex%'} 609 set nautoindex [db eval $sql] 610 set nmanindex [expr {$nindex-$nautoindex}] 611 set nwithoutrowid [db eval {SELECT count(*) FROM pragma_table_list WHERE wr}] 612 613 # set total_payload [mem eval "SELECT sum(payload) FROM space_used"] 614 set user_payload [mem one {SELECT int(sum(payload)) FROM space_used 615 WHERE NOT is_index AND name NOT LIKE 'sqlite_schema'}] 616 set user_percent [percent $user_payload $file_bytes] 617 618 # Output the summary statistics calculated above. 619 # 620 regsub -all {[^-a-zA-Z0-9_,~./]} $root_filename _ sanitized_filename 621 puts "/** Disk-Space Utilization Report For $sanitized_filename" 622 puts "" 623 statline {Page size in bytes} $pageSize 624 statline {Pages in the whole file (measured)} $file_pgcnt 625 statline {Pages in the whole file (calculated)} $file_pgcnt2 626 statline {Pages that store data} $inuse_pgcnt $inuse_percent 627 statline {Pages on the freelist (per header)} $free_pgcnt2 $free_percent2 628 statline {Pages on the freelist (calculated)} $free_pgcnt $free_percent 629 statline {Pages of auto-vacuum overhead} $av_pgcnt $av_percent 630 statline {Number of tables in the database} $ntable 631 statline {Number of WITHOUT ROWID tables} $nwithoutrowid 632 statline {Number of indices} $nindex 633 statline {Number of defined indices} $nmanindex 634 statline {Number of implied indices} $nautoindex 635 if {$isCompressed} { 636 statline {Size of uncompressed content in bytes} $file_bytes 637 set efficiency [percent $true_file_size $file_bytes] 638 statline {Size of compressed file on disk} $true_file_size $efficiency 639 } else { 640 statline {Size of the file in bytes} $file_bytes 641 } 642 statline {Bytes of user payload stored} $user_payload $user_percent 643 644 # Output table rankings 645 # 646 puts "" 647 titleline "Page counts for all tables with their indices" 648 puts "" 649 mem eval {SELECT tblname, count(*) AS cnt, 650 int(sum(int_pages+leaf_pages+ovfl_pages)) AS size 651 FROM space_used GROUP BY tblname ORDER BY size+0 DESC, tblname} {} { 652 statline [string toupper $tblname] $size [percent $size $file_pgcnt] 653 } 654 puts "" 655 titleline "Page counts for all tables and indices separately" 656 puts "" 657 mem eval { 658 SELECT 659 upper(name) AS nm, 660 int(int_pages+leaf_pages+ovfl_pages) AS size 661 FROM space_used 662 ORDER BY size+0 DESC, name} {} { 663 statline $nm $size [percent $size $file_pgcnt] 664 } 665 if {$isCompressed} { 666 puts "" 667 titleline "Bytes of disk space used after compression" 668 puts "" 669 set csum 0 670 mem eval {SELECT tblname, 671 int(sum(compressed_size)) + 672 $compressOverhead*sum(int_pages+leaf_pages+ovfl_pages) 673 AS csize 674 FROM space_used GROUP BY tblname ORDER BY csize+0 DESC, tblname} {} { 675 incr csum $csize 676 statline [string toupper $tblname] $csize [percent $csize $true_file_size] 677 } 678 set overhead [expr {$true_file_size - $csum}] 679 if {$overhead>0} { 680 statline {Header and free space} $overhead [percent $overhead $true_file_size] 681 } 682 } 683 684 # Output subreports 685 # 686 if {$nindex>0} { 687 subreport {All tables and indices} 1 0 688 } 689 subreport {All tables} {NOT is_index} 0 690 if {$nwithoutrowid>0} { 691 subreport {All WITHOUT ROWID tables} {is_without_rowid} 0 692 set nrowidtab [db eval {SELECT count(*) FROM pragma_table_list 693 WHERE type='table' AND NOT wr}] 694 if {$nrowidtab>0} { 695 subreport {ALL rowid tables} {NOT is_without_rowid AND NOT is_index} 0 696 } 697 } 698 if {$nindex>0} { 699 subreport {All indices} {is_index} 0 700 } 701 foreach tbl [mem eval {SELECT DISTINCT tblname name FROM space_used 702 ORDER BY name}] { 703 set qn [quote $tbl] 704 set name [string toupper $tbl] 705 set n [mem eval {SELECT count(*) FROM space_used WHERE tblname=$tbl}] 706 if {$n>1} { 707 set idxlist [mem eval "SELECT name FROM space_used 708 WHERE tblname='$qn' AND is_index 709 ORDER BY 1"] 710 subreport "Table $name and all its indices" "tblname='$qn'" 0 711 subreport "Table $name w/o any indices" "name='$qn'" 1 712 if {[llength $idxlist]>1} { 713 subreport "Indices of table $name" "tblname='$qn' AND is_index" 0 714 } 715 foreach idx $idxlist { 716 set qidx [quote $idx] 717 subreport "Index [string toupper $idx] of table $name" "name='$qidx'" 1 718 } 719 } else { 720 subreport "Table $name" "name='$qn'" 1 721 } 722 } 723 724 # Output instructions on what the numbers above mean. 725 # 726 puts "" 727 titleline Definitions 728 puts { 729 Page size in bytes 730 731 The number of bytes in a single page of the database file. 732 Usually 1024. 733 734 Number of pages in the whole file 735 } 736 puts " The number of $pageSize-byte pages that go into forming the complete 737 database" 738 puts { 739 Pages that store data 740 741 The number of pages that store data, either as primary B*Tree pages or 742 as overflow pages. The number at the right is the data pages divided by 743 the total number of pages in the file. 744 745 Pages on the freelist 746 747 The number of pages that are not currently in use but are reserved for 748 future use. The percentage at the right is the number of freelist pages 749 divided by the total number of pages in the file. 750 751 Pages of auto-vacuum overhead 752 753 The number of pages that store data used by the database to facilitate 754 auto-vacuum. This is zero for databases that do not support auto-vacuum. 755 756 Number of tables in the database 757 758 The number of tables in the database, including the SQLITE_SCHEMA table 759 used to store schema information. 760 761 Number of indices 762 763 The total number of indices in the database. 764 765 Number of defined indices 766 767 The number of indices created using an explicit CREATE INDEX statement. 768 769 Number of implied indices 770 771 The number of indices used to implement PRIMARY KEY or UNIQUE constraints 772 on tables. 773 774 Size of the file in bytes 775 776 The total amount of disk space used by the entire database files. 777 778 Bytes of user payload stored 779 780 The total number of bytes of user payload stored in the database. The 781 schema information in the SQLITE_SCHEMA table is not counted when 782 computing this number. The percentage at the right shows the payload 783 divided by the total file size. 784 785 Percentage of total database 786 787 The amount of the complete database file that is devoted to storing 788 information described by this category. 789 790 Number of entries 791 792 The total number of B-Tree key/value pairs stored under this category. 793 794 Bytes of storage consumed 795 796 The total amount of disk space required to store all B-Tree entries 797 under this category. The is the total number of pages used times 798 the pages size. 799 800 Bytes of payload 801 802 The amount of payload stored under this category. Payload is the data 803 part of table entries and the key part of index entries. The percentage 804 at the right is the bytes of payload divided by the bytes of storage 805 consumed. 806 807 Bytes of metadata 808 809 The amount of formatting and structural information stored in the 810 table or index. Metadata includes the btree page header, the cell pointer 811 array, the size field for each cell, the left child pointer or non-leaf 812 cells, the overflow pointers for overflow cells, and the rowid value for 813 rowid table cells. In other words, metadata is everything that is neither 814 unused space nor content. The record header in the payload is counted as 815 content, not metadata. 816 817 Average payload per entry 818 819 The average amount of payload on each entry. This is just the bytes of 820 payload divided by the number of entries. 821 822 Average unused bytes per entry 823 824 The average amount of free space remaining on all pages under this 825 category on a per-entry basis. This is the number of unused bytes on 826 all pages divided by the number of entries. 827 828 Non-sequential pages 829 830 The number of pages in the table or index that are out of sequence. 831 Many filesystems are optimized for sequential file access so a small 832 number of non-sequential pages might result in faster queries, 833 especially for larger database files that do not fit in the disk cache. 834 Note that after running VACUUM, the root page of each table or index is 835 at the beginning of the database file and all other pages are in a 836 separate part of the database file, resulting in a single non- 837 sequential page. 838 839 Maximum payload per entry 840 841 The largest payload size of any entry. 842 843 Entries that use overflow 844 845 The number of entries that user one or more overflow pages. 846 847 Total pages used 848 849 This is the number of pages used to hold all information in the current 850 category. This is the sum of index, primary, and overflow pages. 851 852 Index pages used 853 854 This is the number of pages in a table B-tree that hold only key (rowid) 855 information and no data. 856 857 Primary pages used 858 859 This is the number of B-tree pages that hold both key and data. 860 861 Overflow pages used 862 863 The total number of overflow pages used for this category. 864 865 Unused bytes on index pages 866 867 The total number of bytes of unused space on all index pages. The 868 percentage at the right is the number of unused bytes divided by the 869 total number of bytes on index pages. 870 871 Unused bytes on primary pages 872 873 The total number of bytes of unused space on all primary pages. The 874 percentage at the right is the number of unused bytes divided by the 875 total number of bytes on primary pages. 876 877 Unused bytes on overflow pages 878 879 The total number of bytes of unused space on all overflow pages. The 880 percentage at the right is the number of unused bytes divided by the 881 total number of bytes on overflow pages. 882 883 Unused bytes on all pages 884 885 The total number of bytes of unused space on all primary and overflow 886 pages. The percentage at the right is the number of unused bytes 887 divided by the total number of bytes. 888 } 889 890 # Output a dump of the in-memory database. This can be used for more 891 # complex offline analysis. 892 # 893 titleline {} 894 puts "The entire text of this report can be sourced into any SQL database" 895 puts "engine for further analysis. All of the text above is an SQL comment." 896 puts "The data used to generate this report follows:" 897 puts "*/" 898 puts "BEGIN;" 899 puts $tabledef 900 unset -nocomplain x 901 mem eval {SELECT * FROM space_used} x { 902 puts -nonewline "INSERT INTO space_used VALUES" 903 set sep ( 904 foreach col $x(*) { 905 set v $x($col) 906 if {$v=="" || ![string is double $v]} {set v '[quote $v]'} 907 puts -nonewline $sep$v 908 set sep , 909 } 910 puts ");" 911 } 912 puts "COMMIT;" 913 914 } err]} { 915 puts "ERROR: $err" 916 puts $errorInfo 917 exit_clean 1 918 } 919 920 exit_clean 0