1
0

spaceanal.tcl 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. # Run this TCL script using "testfixture" in order get a report that shows
  2. # how much disk space is used by a particular data to actually store data
  3. # versus how much space is unused.
  4. #
  5. if {[catch {
  6. # Get the name of the database to analyze
  7. #
  8. proc usage {} {
  9. set argv0 [file rootname [file tail [info nameofexecutable]]]
  10. puts stderr "Usage: $argv0 database-name"
  11. exit 1
  12. }
  13. set file_to_analyze {}
  14. set flags(-pageinfo) 0
  15. set flags(-stats) 0
  16. append argv {}
  17. foreach arg $argv {
  18. if {[regexp {^-+pageinfo$} $arg]} {
  19. set flags(-pageinfo) 1
  20. } elseif {[regexp {^-+stats$} $arg]} {
  21. set flags(-stats) 1
  22. } elseif {[regexp {^-} $arg]} {
  23. puts stderr "Unknown option: $arg"
  24. usage
  25. } elseif {$file_to_analyze!=""} {
  26. usage
  27. } else {
  28. set file_to_analyze $arg
  29. }
  30. }
  31. if {$file_to_analyze==""} usage
  32. set root_filename $file_to_analyze
  33. regexp {^file:(//)?([^?]*)} $file_to_analyze all x1 root_filename
  34. if {![file exists $root_filename]} {
  35. puts stderr "No such file: $root_filename"
  36. exit 1
  37. }
  38. if {![file readable $root_filename]} {
  39. puts stderr "File is not readable: $root_filename"
  40. exit 1
  41. }
  42. set true_file_size [file size $root_filename]
  43. if {$true_file_size<512} {
  44. puts stderr "Empty or malformed database: $root_filename"
  45. exit 1
  46. }
  47. # Compute the total file size assuming test_multiplexor is being used.
  48. # Assume that SQLITE_ENABLE_8_3_NAMES might be enabled
  49. #
  50. set extension [file extension $root_filename]
  51. set pattern $root_filename
  52. append pattern {[0-3][0-9][0-9]}
  53. foreach f [glob -nocomplain $pattern] {
  54. incr true_file_size [file size $f]
  55. set extension {}
  56. }
  57. if {[string length $extension]>=2 && [string length $extension]<=4} {
  58. set pattern [file rootname $root_filename]
  59. append pattern {.[0-3][0-9][0-9]}
  60. foreach f [glob -nocomplain $pattern] {
  61. incr true_file_size [file size $f]
  62. }
  63. }
  64. # Open the database
  65. #
  66. if {[catch {sqlite3 db $file_to_analyze -uri 1} msg]} {
  67. puts stderr "error trying to open $file_to_analyze: $msg"
  68. exit 1
  69. }
  70. register_dbstat_vtab db
  71. db eval {SELECT count(*) FROM sqlite_master}
  72. set pageSize [expr {wide([db one {PRAGMA page_size}])}]
  73. if {$flags(-pageinfo)} {
  74. db eval {CREATE VIRTUAL TABLE temp.stat USING dbstat}
  75. db eval {SELECT name, path, pageno FROM temp.stat ORDER BY pageno} {
  76. puts "$pageno $name $path"
  77. }
  78. exit 0
  79. }
  80. if {$flags(-stats)} {
  81. db eval {CREATE VIRTUAL TABLE temp.stat USING dbstat}
  82. puts "BEGIN;"
  83. puts "CREATE TABLE stats("
  84. puts " name STRING, /* Name of table or index */"
  85. puts " path INTEGER, /* Path to page from root */"
  86. puts " pageno INTEGER, /* Page number */"
  87. puts " pagetype STRING, /* 'internal', 'leaf' or 'overflow' */"
  88. puts " ncell INTEGER, /* Cells on page (0 for overflow) */"
  89. puts " payload INTEGER, /* Bytes of payload on this page */"
  90. puts " unused INTEGER, /* Bytes of unused space on this page */"
  91. puts " mx_payload INTEGER, /* Largest payload size of all cells */"
  92. puts " pgoffset INTEGER, /* Offset of page in file */"
  93. puts " pgsize INTEGER /* Size of the page */"
  94. puts ");"
  95. db eval {SELECT quote(name) || ',' ||
  96. quote(path) || ',' ||
  97. quote(pageno) || ',' ||
  98. quote(pagetype) || ',' ||
  99. quote(ncell) || ',' ||
  100. quote(payload) || ',' ||
  101. quote(unused) || ',' ||
  102. quote(mx_payload) || ',' ||
  103. quote(pgoffset) || ',' ||
  104. quote(pgsize) AS x FROM stat} {
  105. puts "INSERT INTO stats VALUES($x);"
  106. }
  107. puts "COMMIT;"
  108. exit 0
  109. }
  110. # In-memory database for collecting statistics. This script loops through
  111. # the tables and indices in the database being analyzed, adding a row for each
  112. # to an in-memory database (for which the schema is shown below). It then
  113. # queries the in-memory db to produce the space-analysis report.
  114. #
  115. sqlite3 mem :memory:
  116. set tabledef {CREATE TABLE space_used(
  117. name clob, -- Name of a table or index in the database file
  118. tblname clob, -- Name of associated table
  119. is_index boolean, -- TRUE if it is an index, false for a table
  120. nentry int, -- Number of entries in the BTree
  121. leaf_entries int, -- Number of leaf entries
  122. payload int, -- Total amount of data stored in this table or index
  123. ovfl_payload int, -- Total amount of data stored on overflow pages
  124. ovfl_cnt int, -- Number of entries that use overflow
  125. mx_payload int, -- Maximum payload size
  126. int_pages int, -- Number of interior pages used
  127. leaf_pages int, -- Number of leaf pages used
  128. ovfl_pages int, -- Number of overflow pages used
  129. int_unused int, -- Number of unused bytes on interior pages
  130. leaf_unused int, -- Number of unused bytes on primary pages
  131. ovfl_unused int, -- Number of unused bytes on overflow pages
  132. gap_cnt int, -- Number of gaps in the page layout
  133. compressed_size int -- Total bytes stored on disk
  134. );}
  135. mem eval $tabledef
  136. # Create a temporary "dbstat" virtual table.
  137. #
  138. db eval {CREATE VIRTUAL TABLE temp.stat USING dbstat}
  139. db eval {CREATE TEMP TABLE dbstat AS SELECT * FROM temp.stat
  140. ORDER BY name, path}
  141. db eval {DROP TABLE temp.stat}
  142. proc isleaf {pagetype is_index} {
  143. return [expr {$pagetype == "leaf" || ($pagetype == "internal" && $is_index)}]
  144. }
  145. proc isoverflow {pagetype is_index} {
  146. return [expr {$pagetype == "overflow"}]
  147. }
  148. proc isinternal {pagetype is_index} {
  149. return [expr {$pagetype == "internal" && $is_index==0}]
  150. }
  151. db func isleaf isleaf
  152. db func isinternal isinternal
  153. db func isoverflow isoverflow
  154. set isCompressed 0
  155. set compressOverhead 0
  156. set sql { SELECT name, tbl_name FROM sqlite_master WHERE rootpage>0 }
  157. foreach {name tblname} [concat sqlite_master sqlite_master [db eval $sql]] {
  158. set is_index [expr {$name!=$tblname}]
  159. db eval {
  160. SELECT
  161. sum(ncell) AS nentry,
  162. sum(isleaf(pagetype, $is_index) * ncell) AS leaf_entries,
  163. sum(payload) AS payload,
  164. sum(isoverflow(pagetype, $is_index) * payload) AS ovfl_payload,
  165. sum(path LIKE '%+000000') AS ovfl_cnt,
  166. max(mx_payload) AS mx_payload,
  167. sum(isinternal(pagetype, $is_index)) AS int_pages,
  168. sum(isleaf(pagetype, $is_index)) AS leaf_pages,
  169. sum(isoverflow(pagetype, $is_index)) AS ovfl_pages,
  170. sum(isinternal(pagetype, $is_index) * unused) AS int_unused,
  171. sum(isleaf(pagetype, $is_index) * unused) AS leaf_unused,
  172. sum(isoverflow(pagetype, $is_index) * unused) AS ovfl_unused,
  173. sum(pgsize) AS compressed_size
  174. FROM temp.dbstat WHERE name = $name
  175. } break
  176. set total_pages [expr {$leaf_pages+$int_pages+$ovfl_pages}]
  177. set storage [expr {$total_pages*$pageSize}]
  178. if {!$isCompressed && $storage>$compressed_size} {
  179. set isCompressed 1
  180. set compressOverhead 14
  181. }
  182. # Column 'gap_cnt' is set to the number of non-contiguous entries in the
  183. # list of pages visited if the b-tree structure is traversed in a top-down
  184. # fashion (each node visited before its child-tree is passed). Any overflow
  185. # chains present are traversed from start to finish before any child-tree
  186. # is.
  187. #
  188. set gap_cnt 0
  189. set prev 0
  190. db eval {
  191. SELECT pageno, pagetype FROM temp.dbstat
  192. WHERE name=$name
  193. ORDER BY pageno
  194. } {
  195. if {$prev>0 && $pagetype=="leaf" && $pageno!=$prev+1} {
  196. incr gap_cnt
  197. }
  198. set prev $pageno
  199. }
  200. mem eval {
  201. INSERT INTO space_used VALUES(
  202. $name,
  203. $tblname,
  204. $is_index,
  205. $nentry,
  206. $leaf_entries,
  207. $payload,
  208. $ovfl_payload,
  209. $ovfl_cnt,
  210. $mx_payload,
  211. $int_pages,
  212. $leaf_pages,
  213. $ovfl_pages,
  214. $int_unused,
  215. $leaf_unused,
  216. $ovfl_unused,
  217. $gap_cnt,
  218. $compressed_size
  219. );
  220. }
  221. }
  222. proc integerify {real} {
  223. if {[string is double -strict $real]} {
  224. return [expr {wide($real)}]
  225. } else {
  226. return 0
  227. }
  228. }
  229. mem function int integerify
  230. # Quote a string for use in an SQL query. Examples:
  231. #
  232. # [quote {hello world}] == {'hello world'}
  233. # [quote {hello world's}] == {'hello world''s'}
  234. #
  235. proc quote {txt} {
  236. return [string map {' ''} $txt]
  237. }
  238. # Output a title line
  239. #
  240. proc titleline {title} {
  241. if {$title==""} {
  242. puts [string repeat * 79]
  243. } else {
  244. set len [string length $title]
  245. set stars [string repeat * [expr 79-$len-5]]
  246. puts "*** $title $stars"
  247. }
  248. }
  249. # Generate a single line of output in the statistics section of the
  250. # report.
  251. #
  252. proc statline {title value {extra {}}} {
  253. set len [string length $title]
  254. set dots [string repeat . [expr 50-$len]]
  255. set len [string length $value]
  256. set sp2 [string range { } $len end]
  257. if {$extra ne ""} {
  258. set extra " $extra"
  259. }
  260. puts "$title$dots $value$sp2$extra"
  261. }
  262. # Generate a formatted percentage value for $num/$denom
  263. #
  264. proc percent {num denom {of {}}} {
  265. if {$denom==0.0} {return ""}
  266. set v [expr {$num*100.0/$denom}]
  267. set of {}
  268. if {$v==100.0 || $v<0.001 || ($v>1.0 && $v<99.0)} {
  269. return [format {%5.1f%% %s} $v $of]
  270. } elseif {$v<0.1 || $v>99.9} {
  271. return [format {%7.3f%% %s} $v $of]
  272. } else {
  273. return [format {%6.2f%% %s} $v $of]
  274. }
  275. }
  276. proc divide {num denom} {
  277. if {$denom==0} {return 0.0}
  278. return [format %.2f [expr double($num)/double($denom)]]
  279. }
  280. # Generate a subreport that covers some subset of the database.
  281. # the $where clause determines which subset to analyze.
  282. #
  283. proc subreport {title where showFrag} {
  284. global pageSize file_pgcnt compressOverhead
  285. # Query the in-memory database for the sum of various statistics
  286. # for the subset of tables/indices identified by the WHERE clause in
  287. # $where. Note that even if the WHERE clause matches no rows, the
  288. # following query returns exactly one row (because it is an aggregate).
  289. #
  290. # The results of the query are stored directly by SQLite into local
  291. # variables (i.e. $nentry, $nleaf etc.).
  292. #
  293. mem eval "
  294. SELECT
  295. int(sum(nentry)) AS nentry,
  296. int(sum(leaf_entries)) AS nleaf,
  297. int(sum(payload)) AS payload,
  298. int(sum(ovfl_payload)) AS ovfl_payload,
  299. max(mx_payload) AS mx_payload,
  300. int(sum(ovfl_cnt)) as ovfl_cnt,
  301. int(sum(leaf_pages)) AS leaf_pages,
  302. int(sum(int_pages)) AS int_pages,
  303. int(sum(ovfl_pages)) AS ovfl_pages,
  304. int(sum(leaf_unused)) AS leaf_unused,
  305. int(sum(int_unused)) AS int_unused,
  306. int(sum(ovfl_unused)) AS ovfl_unused,
  307. int(sum(gap_cnt)) AS gap_cnt,
  308. int(sum(compressed_size)) AS compressed_size
  309. FROM space_used WHERE $where" {} {}
  310. # Output the sub-report title, nicely decorated with * characters.
  311. #
  312. puts ""
  313. titleline $title
  314. puts ""
  315. # Calculate statistics and store the results in TCL variables, as follows:
  316. #
  317. # total_pages: Database pages consumed.
  318. # total_pages_percent: Pages consumed as a percentage of the file.
  319. # storage: Bytes consumed.
  320. # payload_percent: Payload bytes used as a percentage of $storage.
  321. # total_unused: Unused bytes on pages.
  322. # avg_payload: Average payload per btree entry.
  323. # avg_fanout: Average fanout for internal pages.
  324. # avg_unused: Average unused bytes per btree entry.
  325. # ovfl_cnt_percent: Percentage of btree entries that use overflow pages.
  326. #
  327. set total_pages [expr {$leaf_pages+$int_pages+$ovfl_pages}]
  328. set total_pages_percent [percent $total_pages $file_pgcnt]
  329. set storage [expr {$total_pages*$pageSize}]
  330. set payload_percent [percent $payload $storage {of storage consumed}]
  331. set total_unused [expr {$ovfl_unused+$int_unused+$leaf_unused}]
  332. set avg_payload [divide $payload $nleaf]
  333. set avg_unused [divide $total_unused $nleaf]
  334. if {$int_pages>0} {
  335. # TODO: Is this formula correct?
  336. set nTab [mem eval "
  337. SELECT count(*) FROM (
  338. SELECT DISTINCT tblname FROM space_used WHERE $where AND is_index=0
  339. )
  340. "]
  341. set avg_fanout [mem eval "
  342. SELECT (sum(leaf_pages+int_pages)-$nTab)/sum(int_pages) FROM space_used
  343. WHERE $where AND is_index = 0
  344. "]
  345. set avg_fanout [format %.2f $avg_fanout]
  346. }
  347. set ovfl_cnt_percent [percent $ovfl_cnt $nleaf {of all entries}]
  348. # Print out the sub-report statistics.
  349. #
  350. statline {Percentage of total database} $total_pages_percent
  351. statline {Number of entries} $nleaf
  352. statline {Bytes of storage consumed} $storage
  353. if {$compressed_size!=$storage} {
  354. set compressed_size [expr {$compressed_size+$compressOverhead*$total_pages}]
  355. set pct [expr {$compressed_size*100.0/$storage}]
  356. set pct [format {%5.1f%%} $pct]
  357. statline {Bytes used after compression} $compressed_size $pct
  358. }
  359. statline {Bytes of payload} $payload $payload_percent
  360. statline {Average payload per entry} $avg_payload
  361. statline {Average unused bytes per entry} $avg_unused
  362. if {[info exists avg_fanout]} {
  363. statline {Average fanout} $avg_fanout
  364. }
  365. if {$showFrag && $total_pages>1} {
  366. set fragmentation [percent $gap_cnt [expr {$total_pages-1}]]
  367. statline {Non-sequential pages} $gap_cnt $fragmentation
  368. }
  369. statline {Maximum payload per entry} $mx_payload
  370. statline {Entries that use overflow} $ovfl_cnt $ovfl_cnt_percent
  371. if {$int_pages>0} {
  372. statline {Index pages used} $int_pages
  373. }
  374. statline {Primary pages used} $leaf_pages
  375. statline {Overflow pages used} $ovfl_pages
  376. statline {Total pages used} $total_pages
  377. if {$int_unused>0} {
  378. set int_unused_percent [
  379. percent $int_unused [expr {$int_pages*$pageSize}] {of index space}]
  380. statline "Unused bytes on index pages" $int_unused $int_unused_percent
  381. }
  382. statline "Unused bytes on primary pages" $leaf_unused [
  383. percent $leaf_unused [expr {$leaf_pages*$pageSize}] {of primary space}]
  384. statline "Unused bytes on overflow pages" $ovfl_unused [
  385. percent $ovfl_unused [expr {$ovfl_pages*$pageSize}] {of overflow space}]
  386. statline "Unused bytes on all pages" $total_unused [
  387. percent $total_unused $storage {of all space}]
  388. return 1
  389. }
  390. # Calculate the overhead in pages caused by auto-vacuum.
  391. #
  392. # This procedure calculates and returns the number of pages used by the
  393. # auto-vacuum 'pointer-map'. If the database does not support auto-vacuum,
  394. # then 0 is returned. The two arguments are the size of the database file in
  395. # pages and the page size used by the database (in bytes).
  396. proc autovacuum_overhead {filePages pageSize} {
  397. # Set $autovacuum to non-zero for databases that support auto-vacuum.
  398. set autovacuum [db one {PRAGMA auto_vacuum}]
  399. # If the database is not an auto-vacuum database or the file consists
  400. # of one page only then there is no overhead for auto-vacuum. Return zero.
  401. if {0==$autovacuum || $filePages==1} {
  402. return 0
  403. }
  404. # The number of entries on each pointer map page. The layout of the
  405. # database file is one pointer-map page, followed by $ptrsPerPage other
  406. # pages, followed by a pointer-map page etc. The first pointer-map page
  407. # is the second page of the file overall.
  408. set ptrsPerPage [expr double($pageSize/5)]
  409. # Return the number of pointer map pages in the database.
  410. return [expr wide(ceil( ($filePages-1.0)/($ptrsPerPage+1.0) ))]
  411. }
  412. # Calculate the summary statistics for the database and store the results
  413. # in TCL variables. They are output below. Variables are as follows:
  414. #
  415. # pageSize: Size of each page in bytes.
  416. # file_bytes: File size in bytes.
  417. # file_pgcnt: Number of pages in the file.
  418. # file_pgcnt2: Number of pages in the file (calculated).
  419. # av_pgcnt: Pages consumed by the auto-vacuum pointer-map.
  420. # av_percent: Percentage of the file consumed by auto-vacuum pointer-map.
  421. # inuse_pgcnt: Data pages in the file.
  422. # inuse_percent: Percentage of pages used to store data.
  423. # free_pgcnt: Free pages calculated as (<total pages> - <in-use pages>)
  424. # free_pgcnt2: Free pages in the file according to the file header.
  425. # free_percent: Percentage of file consumed by free pages (calculated).
  426. # free_percent2: Percentage of file consumed by free pages (header).
  427. # ntable: Number of tables in the db.
  428. # nindex: Number of indices in the db.
  429. # nautoindex: Number of indices created automatically.
  430. # nmanindex: Number of indices created manually.
  431. # user_payload: Number of bytes of payload in table btrees
  432. # (not including sqlite_master)
  433. # user_percent: $user_payload as a percentage of total file size.
  434. ### The following, setting $file_bytes based on the actual size of the file
  435. ### on disk, causes this tool to choke on zipvfs databases. So set it based
  436. ### on the return of [PRAGMA page_count] instead.
  437. if 0 {
  438. set file_bytes [file size $file_to_analyze]
  439. set file_pgcnt [expr {$file_bytes/$pageSize}]
  440. }
  441. set file_pgcnt [db one {PRAGMA page_count}]
  442. set file_bytes [expr {$file_pgcnt * $pageSize}]
  443. set av_pgcnt [autovacuum_overhead $file_pgcnt $pageSize]
  444. set av_percent [percent $av_pgcnt $file_pgcnt]
  445. set sql {SELECT sum(leaf_pages+int_pages+ovfl_pages) FROM space_used}
  446. set inuse_pgcnt [expr wide([mem eval $sql])]
  447. set inuse_percent [percent $inuse_pgcnt $file_pgcnt]
  448. set free_pgcnt [expr {$file_pgcnt-$inuse_pgcnt-$av_pgcnt}]
  449. set free_percent [percent $free_pgcnt $file_pgcnt]
  450. set free_pgcnt2 [db one {PRAGMA freelist_count}]
  451. set free_percent2 [percent $free_pgcnt2 $file_pgcnt]
  452. set file_pgcnt2 [expr {$inuse_pgcnt+$free_pgcnt2+$av_pgcnt}]
  453. set ntable [db eval {SELECT count(*)+1 FROM sqlite_master WHERE type='table'}]
  454. set nindex [db eval {SELECT count(*) FROM sqlite_master WHERE type='index'}]
  455. set sql {SELECT count(*) FROM sqlite_master WHERE name LIKE 'sqlite_autoindex%'}
  456. set nautoindex [db eval $sql]
  457. set nmanindex [expr {$nindex-$nautoindex}]
  458. # set total_payload [mem eval "SELECT sum(payload) FROM space_used"]
  459. set user_payload [mem one {SELECT int(sum(payload)) FROM space_used
  460. WHERE NOT is_index AND name NOT LIKE 'sqlite_master'}]
  461. set user_percent [percent $user_payload $file_bytes]
  462. # Output the summary statistics calculated above.
  463. #
  464. puts "/** Disk-Space Utilization Report For $root_filename"
  465. puts ""
  466. statline {Page size in bytes} $pageSize
  467. statline {Pages in the whole file (measured)} $file_pgcnt
  468. statline {Pages in the whole file (calculated)} $file_pgcnt2
  469. statline {Pages that store data} $inuse_pgcnt $inuse_percent
  470. statline {Pages on the freelist (per header)} $free_pgcnt2 $free_percent2
  471. statline {Pages on the freelist (calculated)} $free_pgcnt $free_percent
  472. statline {Pages of auto-vacuum overhead} $av_pgcnt $av_percent
  473. statline {Number of tables in the database} $ntable
  474. statline {Number of indices} $nindex
  475. statline {Number of defined indices} $nmanindex
  476. statline {Number of implied indices} $nautoindex
  477. if {$isCompressed} {
  478. statline {Size of uncompressed content in bytes} $file_bytes
  479. set efficiency [percent $true_file_size $file_bytes]
  480. statline {Size of compressed file on disk} $true_file_size $efficiency
  481. } else {
  482. statline {Size of the file in bytes} $file_bytes
  483. }
  484. statline {Bytes of user payload stored} $user_payload $user_percent
  485. # Output table rankings
  486. #
  487. puts ""
  488. titleline "Page counts for all tables with their indices"
  489. puts ""
  490. mem eval {SELECT tblname, count(*) AS cnt,
  491. int(sum(int_pages+leaf_pages+ovfl_pages)) AS size
  492. FROM space_used GROUP BY tblname ORDER BY size+0 DESC, tblname} {} {
  493. statline [string toupper $tblname] $size [percent $size $file_pgcnt]
  494. }
  495. puts ""
  496. titleline "Page counts for all tables and indices separately"
  497. puts ""
  498. mem eval {
  499. SELECT
  500. upper(name) AS nm,
  501. int(int_pages+leaf_pages+ovfl_pages) AS size
  502. FROM space_used
  503. ORDER BY size+0 DESC, name} {} {
  504. statline $nm $size [percent $size $file_pgcnt]
  505. }
  506. if {$isCompressed} {
  507. puts ""
  508. titleline "Bytes of disk space used after compression"
  509. puts ""
  510. set csum 0
  511. mem eval {SELECT tblname,
  512. int(sum(compressed_size)) +
  513. $compressOverhead*sum(int_pages+leaf_pages+ovfl_pages)
  514. AS csize
  515. FROM space_used GROUP BY tblname ORDER BY csize+0 DESC, tblname} {} {
  516. incr csum $csize
  517. statline [string toupper $tblname] $csize [percent $csize $true_file_size]
  518. }
  519. set overhead [expr {$true_file_size - $csum}]
  520. if {$overhead>0} {
  521. statline {Header and free space} $overhead [percent $overhead $true_file_size]
  522. }
  523. }
  524. # Output subreports
  525. #
  526. if {$nindex>0} {
  527. subreport {All tables and indices} 1 0
  528. }
  529. subreport {All tables} {NOT is_index} 0
  530. if {$nindex>0} {
  531. subreport {All indices} {is_index} 0
  532. }
  533. foreach tbl [mem eval {SELECT name FROM space_used WHERE NOT is_index
  534. ORDER BY name}] {
  535. set qn [quote $tbl]
  536. set name [string toupper $tbl]
  537. set n [mem eval {SELECT count(*) FROM space_used WHERE tblname=$tbl}]
  538. if {$n>1} {
  539. set idxlist [mem eval "SELECT name FROM space_used
  540. WHERE tblname='$qn' AND is_index
  541. ORDER BY 1"]
  542. subreport "Table $name and all its indices" "tblname='$qn'" 0
  543. subreport "Table $name w/o any indices" "name='$qn'" 1
  544. if {[llength $idxlist]>1} {
  545. subreport "Indices of table $name" "tblname='$qn' AND is_index" 0
  546. }
  547. foreach idx $idxlist {
  548. set qidx [quote $idx]
  549. subreport "Index [string toupper $idx] of table $name" "name='$qidx'" 1
  550. }
  551. } else {
  552. subreport "Table $name" "name='$qn'" 1
  553. }
  554. }
  555. # Output instructions on what the numbers above mean.
  556. #
  557. puts ""
  558. titleline Definitions
  559. puts {
  560. Page size in bytes
  561. The number of bytes in a single page of the database file.
  562. Usually 1024.
  563. Number of pages in the whole file
  564. }
  565. puts " The number of $pageSize-byte pages that go into forming the complete
  566. database"
  567. puts {
  568. Pages that store data
  569. The number of pages that store data, either as primary B*Tree pages or
  570. as overflow pages. The number at the right is the data pages divided by
  571. the total number of pages in the file.
  572. Pages on the freelist
  573. The number of pages that are not currently in use but are reserved for
  574. future use. The percentage at the right is the number of freelist pages
  575. divided by the total number of pages in the file.
  576. Pages of auto-vacuum overhead
  577. The number of pages that store data used by the database to facilitate
  578. auto-vacuum. This is zero for databases that do not support auto-vacuum.
  579. Number of tables in the database
  580. The number of tables in the database, including the SQLITE_MASTER table
  581. used to store schema information.
  582. Number of indices
  583. The total number of indices in the database.
  584. Number of defined indices
  585. The number of indices created using an explicit CREATE INDEX statement.
  586. Number of implied indices
  587. The number of indices used to implement PRIMARY KEY or UNIQUE constraints
  588. on tables.
  589. Size of the file in bytes
  590. The total amount of disk space used by the entire database files.
  591. Bytes of user payload stored
  592. The total number of bytes of user payload stored in the database. The
  593. schema information in the SQLITE_MASTER table is not counted when
  594. computing this number. The percentage at the right shows the payload
  595. divided by the total file size.
  596. Percentage of total database
  597. The amount of the complete database file that is devoted to storing
  598. information described by this category.
  599. Number of entries
  600. The total number of B-Tree key/value pairs stored under this category.
  601. Bytes of storage consumed
  602. The total amount of disk space required to store all B-Tree entries
  603. under this category. The is the total number of pages used times
  604. the pages size.
  605. Bytes of payload
  606. The amount of payload stored under this category. Payload is the data
  607. part of table entries and the key part of index entries. The percentage
  608. at the right is the bytes of payload divided by the bytes of storage
  609. consumed.
  610. Average payload per entry
  611. The average amount of payload on each entry. This is just the bytes of
  612. payload divided by the number of entries.
  613. Average unused bytes per entry
  614. The average amount of free space remaining on all pages under this
  615. category on a per-entry basis. This is the number of unused bytes on
  616. all pages divided by the number of entries.
  617. Non-sequential pages
  618. The number of pages in the table or index that are out of sequence.
  619. Many filesystems are optimized for sequential file access so a small
  620. number of non-sequential pages might result in faster queries,
  621. especially for larger database files that do not fit in the disk cache.
  622. Note that after running VACUUM, the root page of each table or index is
  623. at the beginning of the database file and all other pages are in a
  624. separate part of the database file, resulting in a single non-
  625. sequential page.
  626. Maximum payload per entry
  627. The largest payload size of any entry.
  628. Entries that use overflow
  629. The number of entries that user one or more overflow pages.
  630. Total pages used
  631. This is the number of pages used to hold all information in the current
  632. category. This is the sum of index, primary, and overflow pages.
  633. Index pages used
  634. This is the number of pages in a table B-tree that hold only key (rowid)
  635. information and no data.
  636. Primary pages used
  637. This is the number of B-tree pages that hold both key and data.
  638. Overflow pages used
  639. The total number of overflow pages used for this category.
  640. Unused bytes on index pages
  641. The total number of bytes of unused space on all index pages. The
  642. percentage at the right is the number of unused bytes divided by the
  643. total number of bytes on index pages.
  644. Unused bytes on primary pages
  645. The total number of bytes of unused space on all primary pages. The
  646. percentage at the right is the number of unused bytes divided by the
  647. total number of bytes on primary pages.
  648. Unused bytes on overflow pages
  649. The total number of bytes of unused space on all overflow pages. The
  650. percentage at the right is the number of unused bytes divided by the
  651. total number of bytes on overflow pages.
  652. Unused bytes on all pages
  653. The total number of bytes of unused space on all primary and overflow
  654. pages. The percentage at the right is the number of unused bytes
  655. divided by the total number of bytes.
  656. }
  657. # Output a dump of the in-memory database. This can be used for more
  658. # complex offline analysis.
  659. #
  660. titleline {}
  661. puts "The entire text of this report can be sourced into any SQL database"
  662. puts "engine for further analysis. All of the text above is an SQL comment."
  663. puts "The data used to generate this report follows:"
  664. puts "*/"
  665. puts "BEGIN;"
  666. puts $tabledef
  667. unset -nocomplain x
  668. mem eval {SELECT * FROM space_used} x {
  669. puts -nonewline "INSERT INTO space_used VALUES"
  670. set sep (
  671. foreach col $x(*) {
  672. set v $x($col)
  673. if {$v=="" || ![string is double $v]} {set v [quote $v]}
  674. puts -nonewline $sep$v
  675. set sep ,
  676. }
  677. puts ");"
  678. }
  679. puts "COMMIT;"
  680. } err]} {
  681. puts "ERROR: $err"
  682. puts $errorInfo
  683. exit 1
  684. }