blob: fd59670adaeea38a3d7b4746599c62c72dca4f8a [file] [log] [blame]
drh3e27c022004-07-23 00:01:38 +00001# 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
drha7531c62006-01-24 02:19:53 +00006if {[catch {
drh3e27c022004-07-23 00:01:38 +00007# Get the name of the database to analyze
8#
drhb7708942011-10-05 18:18:13 +00009proc usage {} {
10 set argv0 [file rootname [file tail [info nameofexecutable]]]
drh3e27c022004-07-23 00:01:38 +000011 puts stderr "Usage: $argv0 database-name"
12 exit 1
13}
drhb7708942011-10-05 18:18:13 +000014set file_to_analyze {}
15set flags(-pageinfo) 0
drha624fd52011-10-05 19:46:03 +000016set flags(-stats) 0
drhb7708942011-10-05 18:18:13 +000017append argv {}
18foreach arg $argv {
19 if {[regexp {^-+pageinfo$} $arg]} {
20 set flags(-pageinfo) 1
drha624fd52011-10-05 19:46:03 +000021 } elseif {[regexp {^-+stats$} $arg]} {
22 set flags(-stats) 1
drhb7708942011-10-05 18:18:13 +000023 } elseif {[regexp {^-} $arg]} {
24 puts stderr "Unknown option: $arg"
25 usage
26 } elseif {$file_to_analyze!=""} {
27 usage
28 } else {
29 set file_to_analyze $arg
30 }
31}
32if {$file_to_analyze==""} usage
drh3e27c022004-07-23 00:01:38 +000033if {![file exists $file_to_analyze]} {
34 puts stderr "No such file: $file_to_analyze"
35 exit 1
36}
37if {![file readable $file_to_analyze]} {
38 puts stderr "File is not readable: $file_to_analyze"
39 exit 1
40}
drhb7708942011-10-05 18:18:13 +000041set true_file_size [file size $file_to_analyze]
42if {$true_file_size<512} {
drh3e27c022004-07-23 00:01:38 +000043 puts stderr "Empty or malformed database: $file_to_analyze"
44 exit 1
45}
46
drh36c06322011-10-10 16:06:35 +000047# Compute the total file size assuming test_multiplexor is being used.
48# Assume that SQLITE_ENABLE_8_3_NAMES might be enabled
49#
50set extension [file extension $file_to_analyze]
51set pattern $file_to_analyze
drh37002622012-04-06 00:09:27 +000052append pattern {[0-3][0-9][0-9]}
drh36c06322011-10-10 16:06:35 +000053foreach f [glob -nocomplain $pattern] {
54 incr true_file_size [file size $f]
55 set extension {}
56}
57if {[string length $extension]>=2 && [string length $extension]<=4} {
58 set pattern [file rootname $file_to_analyze]
drh37002622012-04-06 00:09:27 +000059 append pattern {.[0-3][0-9][0-9]}
drh36c06322011-10-10 16:06:35 +000060 foreach f [glob -nocomplain $pattern] {
61 incr true_file_size [file size $f]
62 }
63}
64
drh3e27c022004-07-23 00:01:38 +000065# Open the database
66#
mistachkinac43e1a2011-09-15 00:40:11 +000067sqlite3 db $file_to_analyze
dan599e9d22010-07-12 08:39:37 +000068register_dbstat_vtab db
69
drh565621a2011-09-21 20:10:42 +000070db eval {SELECT count(*) FROM sqlite_master}
drhf08f3842011-09-27 13:40:26 +000071set pageSize [expr {wide([db one {PRAGMA page_size}])}]
drh3e27c022004-07-23 00:01:38 +000072
drha624fd52011-10-05 19:46:03 +000073if {$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}
80if {$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
danielk19770ba87cb2004-11-09 07:42:11 +0000111# In-memory database for collecting statistics. This script loops through
112# the tables and indices in the database being analyzed, adding a row for each
113# to an in-memory database (for which the schema is shown below). It then
114# queries the in-memory db to produce the space-analysis report.
drh3e27c022004-07-23 00:01:38 +0000115#
116sqlite3 mem :memory:
drh4515a452011-08-31 17:46:50 +0000117set tabledef {CREATE TABLE space_used(
drh3e27c022004-07-23 00:01:38 +0000118 name clob, -- Name of a table or index in the database file
119 tblname clob, -- Name of associated table
120 is_index boolean, -- TRUE if it is an index, false for a table
121 nentry int, -- Number of entries in the BTree
122 leaf_entries int, -- Number of leaf entries
123 payload int, -- Total amount of data stored in this table or index
124 ovfl_payload int, -- Total amount of data stored on overflow pages
125 ovfl_cnt int, -- Number of entries that use overflow
126 mx_payload int, -- Maximum payload size
127 int_pages int, -- Number of interior pages used
128 leaf_pages int, -- Number of leaf pages used
129 ovfl_pages int, -- Number of overflow pages used
130 int_unused int, -- Number of unused bytes on interior pages
131 leaf_unused int, -- Number of unused bytes on primary pages
drh50c67062007-02-10 19:22:35 +0000132 ovfl_unused int, -- Number of unused bytes on overflow pages
drh4c9f1292011-09-28 00:50:14 +0000133 gap_cnt int, -- Number of gaps in the page layout
134 compressed_size int -- Total bytes stored on disk
drh3e27c022004-07-23 00:01:38 +0000135);}
136mem eval $tabledef
137
dan599e9d22010-07-12 08:39:37 +0000138# Create a temporary "dbstat" virtual table.
139#
drh565621a2011-09-21 20:10:42 +0000140db eval {CREATE VIRTUAL TABLE temp.stat USING dbstat}
141db eval {CREATE TEMP TABLE dbstat AS SELECT * FROM temp.stat
142 ORDER BY name, path}
143db eval {DROP TABLE temp.stat}
dan599e9d22010-07-12 08:39:37 +0000144
145proc isleaf {pagetype is_index} {
146 return [expr {$pagetype == "leaf" || ($pagetype == "internal" && $is_index)}]
147}
148proc isoverflow {pagetype is_index} {
149 return [expr {$pagetype == "overflow"}]
150}
151proc isinternal {pagetype is_index} {
152 return [expr {$pagetype == "internal" && $is_index==0}]
153}
154
155db func isleaf isleaf
156db func isinternal isinternal
157db func isoverflow isoverflow
158
drhb7708942011-10-05 18:18:13 +0000159set isCompressed 0
160set compressOverhead 0
dan599e9d22010-07-12 08:39:37 +0000161set sql { SELECT name, tbl_name FROM sqlite_master WHERE rootpage>0 }
162foreach {name tblname} [concat sqlite_master sqlite_master [db eval $sql]] {
163
164 set is_index [expr {$name!=$tblname}]
165 db eval {
166 SELECT
167 sum(ncell) AS nentry,
168 sum(isleaf(pagetype, $is_index) * ncell) AS leaf_entries,
169 sum(payload) AS payload,
170 sum(isoverflow(pagetype, $is_index) * payload) AS ovfl_payload,
171 sum(path LIKE '%+000000') AS ovfl_cnt,
172 max(mx_payload) AS mx_payload,
173 sum(isinternal(pagetype, $is_index)) AS int_pages,
174 sum(isleaf(pagetype, $is_index)) AS leaf_pages,
175 sum(isoverflow(pagetype, $is_index)) AS ovfl_pages,
176 sum(isinternal(pagetype, $is_index) * unused) AS int_unused,
177 sum(isleaf(pagetype, $is_index) * unused) AS leaf_unused,
drh4c9f1292011-09-28 00:50:14 +0000178 sum(isoverflow(pagetype, $is_index) * unused) AS ovfl_unused,
179 sum(pgsize) AS compressed_size
dan599e9d22010-07-12 08:39:37 +0000180 FROM temp.dbstat WHERE name = $name
181 } break
182
drhb7708942011-10-05 18:18:13 +0000183 set total_pages [expr {$leaf_pages+$int_pages+$ovfl_pages}]
184 set storage [expr {$total_pages*$pageSize}]
185 if {!$isCompressed && $storage>$compressed_size} {
186 set isCompressed 1
187 set compressOverhead 14
188 }
189
dan599e9d22010-07-12 08:39:37 +0000190 # Column 'gap_cnt' is set to the number of non-contiguous entries in the
191 # list of pages visited if the b-tree structure is traversed in a top-down
192 # fashion (each node visited before its child-tree is passed). Any overflow
193 # chains present are traversed from start to finish before any child-tree
194 # is.
195 #
196 set gap_cnt 0
197 set pglist [db eval {
198 SELECT pageno FROM temp.dbstat WHERE name = $name ORDER BY rowid
199 }]
200 set prev [lindex $pglist 0]
201 foreach pgno [lrange $pglist 1 end] {
202 if {$pgno != $prev+1} {incr gap_cnt}
203 set prev $pgno
204 }
205
206 mem eval {
207 INSERT INTO space_used VALUES(
208 $name,
209 $tblname,
210 $is_index,
211 $nentry,
212 $leaf_entries,
213 $payload,
214 $ovfl_payload,
215 $ovfl_cnt,
216 $mx_payload,
217 $int_pages,
218 $leaf_pages,
219 $ovfl_pages,
220 $int_unused,
221 $leaf_unused,
222 $ovfl_unused,
drh4c9f1292011-09-28 00:50:14 +0000223 $gap_cnt,
224 $compressed_size
dan599e9d22010-07-12 08:39:37 +0000225 );
226 }
227}
228
danielk197724c92532005-02-01 10:36:40 +0000229proc integerify {real} {
drh03496882007-12-04 13:41:51 +0000230 if {[string is double -strict $real]} {
drhf08f3842011-09-27 13:40:26 +0000231 return [expr {wide($real)}]
drh03496882007-12-04 13:41:51 +0000232 } else {
233 return 0
234 }
danielk197724c92532005-02-01 10:36:40 +0000235}
236mem function int integerify
237
danielk19770ba87cb2004-11-09 07:42:11 +0000238# Quote a string for use in an SQL query. Examples:
drh3e27c022004-07-23 00:01:38 +0000239#
danielk19770ba87cb2004-11-09 07:42:11 +0000240# [quote {hello world}] == {'hello world'}
241# [quote {hello world's}] == {'hello world''s'}
drh3e27c022004-07-23 00:01:38 +0000242#
danielk19770ba87cb2004-11-09 07:42:11 +0000243proc quote {txt} {
drh3e27c022004-07-23 00:01:38 +0000244 regsub -all ' $txt '' q
245 return '$q'
246}
247
drh3e27c022004-07-23 00:01:38 +0000248# Generate a single line of output in the statistics section of the
249# report.
250#
251proc statline {title value {extra {}}} {
252 set len [string length $title]
253 set dots [string range {......................................} $len end]
254 set len [string length $value]
255 set sp2 [string range { } $len end]
256 if {$extra ne ""} {
257 set extra " $extra"
258 }
259 puts "$title$dots $value$sp2$extra"
260}
261
262# Generate a formatted percentage value for $num/$denom
263#
264proc percent {num denom {of {}}} {
265 if {$denom==0.0} {return ""}
266 set v [expr {$num*100.0/$denom}]
267 set of {}
drhfaf60c72005-03-29 13:18:16 +0000268 if {$v==100.0 || $v<0.001 || ($v>1.0 && $v<99.0)} {
drh3e27c022004-07-23 00:01:38 +0000269 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
danielk197724c92532005-02-01 10:36:40 +0000277proc divide {num denom} {
278 if {$denom==0} {return 0.0}
279 return [format %.2f [expr double($num)/double($denom)]]
280}
281
drh3e27c022004-07-23 00:01:38 +0000282# Generate a subreport that covers some subset of the database.
283# the $where clause determines which subset to analyze.
284#
285proc subreport {title where} {
drhb7708942011-10-05 18:18:13 +0000286 global pageSize file_pgcnt compressOverhead
danielk19770ba87cb2004-11-09 07:42:11 +0000287
288 # Query the in-memory database for the sum of various statistics
289 # for the subset of tables/indices identified by the WHERE clause in
290 # $where. Note that even if the WHERE clause matches no rows, the
291 # following query returns exactly one row (because it is an aggregate).
292 #
293 # The results of the query are stored directly by SQLite into local
294 # variables (i.e. $nentry, $nleaf etc.).
295 #
drh3e27c022004-07-23 00:01:38 +0000296 mem eval "
297 SELECT
danielk197724c92532005-02-01 10:36:40 +0000298 int(sum(nentry)) AS nentry,
299 int(sum(leaf_entries)) AS nleaf,
300 int(sum(payload)) AS payload,
301 int(sum(ovfl_payload)) AS ovfl_payload,
drh3e27c022004-07-23 00:01:38 +0000302 max(mx_payload) AS mx_payload,
danielk197724c92532005-02-01 10:36:40 +0000303 int(sum(ovfl_cnt)) as ovfl_cnt,
304 int(sum(leaf_pages)) AS leaf_pages,
305 int(sum(int_pages)) AS int_pages,
306 int(sum(ovfl_pages)) AS ovfl_pages,
307 int(sum(leaf_unused)) AS leaf_unused,
308 int(sum(int_unused)) AS int_unused,
drh50c67062007-02-10 19:22:35 +0000309 int(sum(ovfl_unused)) AS ovfl_unused,
drh4c9f1292011-09-28 00:50:14 +0000310 int(sum(gap_cnt)) AS gap_cnt,
311 int(sum(compressed_size)) AS compressed_size
danielk19770ba87cb2004-11-09 07:42:11 +0000312 FROM space_used WHERE $where" {} {}
313
314 # Output the sub-report title, nicely decorated with * characters.
315 #
drh3e27c022004-07-23 00:01:38 +0000316 puts ""
317 set len [string length $title]
danielk19770ba87cb2004-11-09 07:42:11 +0000318 set stars [string repeat * [expr 65-$len]]
drh3e27c022004-07-23 00:01:38 +0000319 puts "*** $title $stars"
320 puts ""
danielk19770ba87cb2004-11-09 07:42:11 +0000321
322 # Calculate statistics and store the results in TCL variables, as follows:
323 #
324 # total_pages: Database pages consumed.
325 # total_pages_percent: Pages consumed as a percentage of the file.
326 # storage: Bytes consumed.
327 # payload_percent: Payload bytes used as a percentage of $storage.
328 # total_unused: Unused bytes on pages.
329 # avg_payload: Average payload per btree entry.
330 # avg_fanout: Average fanout for internal pages.
331 # avg_unused: Average unused bytes per btree entry.
332 # ovfl_cnt_percent: Percentage of btree entries that use overflow pages.
333 #
drh3e27c022004-07-23 00:01:38 +0000334 set total_pages [expr {$leaf_pages+$int_pages+$ovfl_pages}]
danielk19770ba87cb2004-11-09 07:42:11 +0000335 set total_pages_percent [percent $total_pages $file_pgcnt]
drh3e27c022004-07-23 00:01:38 +0000336 set storage [expr {$total_pages*$pageSize}]
danielk19770ba87cb2004-11-09 07:42:11 +0000337 set payload_percent [percent $payload $storage {of storage consumed}]
338 set total_unused [expr {$ovfl_unused+$int_unused+$leaf_unused}]
danielk197724c92532005-02-01 10:36:40 +0000339 set avg_payload [divide $payload $nleaf]
340 set avg_unused [divide $total_unused $nleaf]
drh3e27c022004-07-23 00:01:38 +0000341 if {$int_pages>0} {
danielk19770ba87cb2004-11-09 07:42:11 +0000342 # TODO: Is this formula correct?
danielk197724c92532005-02-01 10:36:40 +0000343 set nTab [mem eval "
344 SELECT count(*) FROM (
345 SELECT DISTINCT tblname FROM space_used WHERE $where AND is_index=0
346 )
347 "]
348 set avg_fanout [mem eval "
349 SELECT (sum(leaf_pages+int_pages)-$nTab)/sum(int_pages) FROM space_used
350 WHERE $where AND is_index = 0
351 "]
352 set avg_fanout [format %.2f $avg_fanout]
drh3e27c022004-07-23 00:01:38 +0000353 }
danielk19770ba87cb2004-11-09 07:42:11 +0000354 set ovfl_cnt_percent [percent $ovfl_cnt $nleaf {of all entries}]
355
356 # Print out the sub-report statistics.
357 #
358 statline {Percentage of total database} $total_pages_percent
359 statline {Number of entries} $nleaf
360 statline {Bytes of storage consumed} $storage
drh4c9f1292011-09-28 00:50:14 +0000361 if {$compressed_size!=$storage} {
drhb7708942011-10-05 18:18:13 +0000362 set compressed_size [expr {$compressed_size+$compressOverhead*$total_pages}]
drh4c9f1292011-09-28 00:50:14 +0000363 set pct [expr {$compressed_size*100.0/$storage}]
364 set pct [format {%5.1f%%} $pct]
365 statline {Bytes used after compression} $compressed_size $pct
366 }
danielk19770ba87cb2004-11-09 07:42:11 +0000367 statline {Bytes of payload} $payload $payload_percent
368 statline {Average payload per entry} $avg_payload
369 statline {Average unused bytes per entry} $avg_unused
370 if {[info exists avg_fanout]} {
371 statline {Average fanout} $avg_fanout
372 }
drh50c67062007-02-10 19:22:35 +0000373 if {$total_pages>1} {
drh0a0b77b2007-02-13 01:38:31 +0000374 set fragmentation [percent $gap_cnt [expr {$total_pages-1}] {fragmentation}]
drh50c67062007-02-10 19:22:35 +0000375 statline {Fragmentation} $fragmentation
376 }
danielk19770ba87cb2004-11-09 07:42:11 +0000377 statline {Maximum payload per entry} $mx_payload
378 statline {Entries that use overflow} $ovfl_cnt $ovfl_cnt_percent
drh3e27c022004-07-23 00:01:38 +0000379 if {$int_pages>0} {
danielk19770ba87cb2004-11-09 07:42:11 +0000380 statline {Index pages used} $int_pages
drh3e27c022004-07-23 00:01:38 +0000381 }
danielk19770ba87cb2004-11-09 07:42:11 +0000382 statline {Primary pages used} $leaf_pages
383 statline {Overflow pages used} $ovfl_pages
384 statline {Total pages used} $total_pages
drh3e27c022004-07-23 00:01:38 +0000385 if {$int_unused>0} {
drh4515a452011-08-31 17:46:50 +0000386 set int_unused_percent [
387 percent $int_unused [expr {$int_pages*$pageSize}] {of index space}]
danielk19770ba87cb2004-11-09 07:42:11 +0000388 statline "Unused bytes on index pages" $int_unused $int_unused_percent
drh3e27c022004-07-23 00:01:38 +0000389 }
drh4515a452011-08-31 17:46:50 +0000390 statline "Unused bytes on primary pages" $leaf_unused [
391 percent $leaf_unused [expr {$leaf_pages*$pageSize}] {of primary space}]
392 statline "Unused bytes on overflow pages" $ovfl_unused [
393 percent $ovfl_unused [expr {$ovfl_pages*$pageSize}] {of overflow space}]
394 statline "Unused bytes on all pages" $total_unused [
395 percent $total_unused $storage {of all space}]
drh3e27c022004-07-23 00:01:38 +0000396 return 1
397}
398
danielk197716254452004-11-08 16:15:09 +0000399# Calculate the overhead in pages caused by auto-vacuum.
400#
401# This procedure calculates and returns the number of pages used by the
402# auto-vacuum 'pointer-map'. If the database does not support auto-vacuum,
403# then 0 is returned. The two arguments are the size of the database file in
danielk19770ba87cb2004-11-09 07:42:11 +0000404# pages and the page size used by the database (in bytes).
danielk197716254452004-11-08 16:15:09 +0000405proc autovacuum_overhead {filePages pageSize} {
406
dan599e9d22010-07-12 08:39:37 +0000407 # Set $autovacuum to non-zero for databases that support auto-vacuum.
408 set autovacuum [db one {PRAGMA auto_vacuum}]
danielk197716254452004-11-08 16:15:09 +0000409
410 # If the database is not an auto-vacuum database or the file consists
411 # of one page only then there is no overhead for auto-vacuum. Return zero.
dan599e9d22010-07-12 08:39:37 +0000412 if {0==$autovacuum || $filePages==1} {
danielk197716254452004-11-08 16:15:09 +0000413 return 0
414 }
415
416 # The number of entries on each pointer map page. The layout of the
417 # database file is one pointer-map page, followed by $ptrsPerPage other
418 # pages, followed by a pointer-map page etc. The first pointer-map page
419 # is the second page of the file overall.
420 set ptrsPerPage [expr double($pageSize/5)]
421
422 # Return the number of pointer map pages in the database.
drhf08f3842011-09-27 13:40:26 +0000423 return [expr wide(ceil( ($filePages-1.0)/($ptrsPerPage+1.0) ))]
danielk197716254452004-11-08 16:15:09 +0000424}
425
danielk197716254452004-11-08 16:15:09 +0000426
danielk19770ba87cb2004-11-09 07:42:11 +0000427# Calculate the summary statistics for the database and store the results
428# in TCL variables. They are output below. Variables are as follows:
danielk197716254452004-11-08 16:15:09 +0000429#
430# pageSize: Size of each page in bytes.
431# file_bytes: File size in bytes.
432# file_pgcnt: Number of pages in the file.
433# file_pgcnt2: Number of pages in the file (calculated).
434# av_pgcnt: Pages consumed by the auto-vacuum pointer-map.
435# av_percent: Percentage of the file consumed by auto-vacuum pointer-map.
436# inuse_pgcnt: Data pages in the file.
437# inuse_percent: Percentage of pages used to store data.
438# free_pgcnt: Free pages calculated as (<total pages> - <in-use pages>)
439# free_pgcnt2: Free pages in the file according to the file header.
440# free_percent: Percentage of file consumed by free pages (calculated).
441# free_percent2: Percentage of file consumed by free pages (header).
442# ntable: Number of tables in the db.
443# nindex: Number of indices in the db.
444# nautoindex: Number of indices created automatically.
445# nmanindex: Number of indices created manually.
danielk19770ba87cb2004-11-09 07:42:11 +0000446# user_payload: Number of bytes of payload in table btrees
447# (not including sqlite_master)
448# user_percent: $user_payload as a percentage of total file size.
danielk197716254452004-11-08 16:15:09 +0000449
dan64b41c72011-09-26 19:32:47 +0000450### The following, setting $file_bytes based on the actual size of the file
451### on disk, causes this tool to choke on zipvfs databases. So set it based
452### on the return of [PRAGMA page_count] instead.
453if 0 {
454 set file_bytes [file size $file_to_analyze]
455 set file_pgcnt [expr {$file_bytes/$pageSize}]
456}
457set file_pgcnt [db one {PRAGMA page_count}]
drhf08f3842011-09-27 13:40:26 +0000458set file_bytes [expr {$file_pgcnt * $pageSize}]
danielk197716254452004-11-08 16:15:09 +0000459
460set av_pgcnt [autovacuum_overhead $file_pgcnt $pageSize]
461set av_percent [percent $av_pgcnt $file_pgcnt]
462
danielk19770ba87cb2004-11-09 07:42:11 +0000463set sql {SELECT sum(leaf_pages+int_pages+ovfl_pages) FROM space_used}
drhf08f3842011-09-27 13:40:26 +0000464set inuse_pgcnt [expr wide([mem eval $sql])]
danielk197716254452004-11-08 16:15:09 +0000465set inuse_percent [percent $inuse_pgcnt $file_pgcnt]
466
drhf08f3842011-09-27 13:40:26 +0000467set free_pgcnt [expr {$file_pgcnt-$inuse_pgcnt-$av_pgcnt}]
danielk197716254452004-11-08 16:15:09 +0000468set free_percent [percent $free_pgcnt $file_pgcnt]
dan599e9d22010-07-12 08:39:37 +0000469set free_pgcnt2 [db one {PRAGMA freelist_count}]
danielk197716254452004-11-08 16:15:09 +0000470set free_percent2 [percent $free_pgcnt2 $file_pgcnt]
471
472set file_pgcnt2 [expr {$inuse_pgcnt+$free_pgcnt2+$av_pgcnt}]
drh3e27c022004-07-23 00:01:38 +0000473
474set ntable [db eval {SELECT count(*)+1 FROM sqlite_master WHERE type='table'}]
drh3e27c022004-07-23 00:01:38 +0000475set nindex [db eval {SELECT count(*) FROM sqlite_master WHERE type='index'}]
danielk19770ba87cb2004-11-09 07:42:11 +0000476set sql {SELECT count(*) FROM sqlite_master WHERE name LIKE 'sqlite_autoindex%'}
477set nautoindex [db eval $sql]
danielk197716254452004-11-08 16:15:09 +0000478set nmanindex [expr {$nindex-$nautoindex}]
479
480# set total_payload [mem eval "SELECT sum(payload) FROM space_used"]
danielk197724c92532005-02-01 10:36:40 +0000481set user_payload [mem one {SELECT int(sum(payload)) FROM space_used
drh3e27c022004-07-23 00:01:38 +0000482 WHERE NOT is_index AND name NOT LIKE 'sqlite_master'}]
danielk19770ba87cb2004-11-09 07:42:11 +0000483set user_percent [percent $user_payload $file_bytes]
danielk197716254452004-11-08 16:15:09 +0000484
danielk19770ba87cb2004-11-09 07:42:11 +0000485# Output the summary statistics calculated above.
486#
487puts "/** Disk-Space Utilization Report For $file_to_analyze"
drh35c12832006-10-03 12:08:54 +0000488catch {
489 puts "*** As of [clock format [clock seconds] -format {%Y-%b-%d %H:%M:%S}]"
490}
danielk19770ba87cb2004-11-09 07:42:11 +0000491puts ""
danielk197716254452004-11-08 16:15:09 +0000492statline {Page size in bytes} $pageSize
493statline {Pages in the whole file (measured)} $file_pgcnt
494statline {Pages in the whole file (calculated)} $file_pgcnt2
495statline {Pages that store data} $inuse_pgcnt $inuse_percent
496statline {Pages on the freelist (per header)} $free_pgcnt2 $free_percent2
497statline {Pages on the freelist (calculated)} $free_pgcnt $free_percent
498statline {Pages of auto-vacuum overhead} $av_pgcnt $av_percent
499statline {Number of tables in the database} $ntable
500statline {Number of indices} $nindex
501statline {Number of named indices} $nmanindex
502statline {Automatically generated indices} $nautoindex
drhb7708942011-10-05 18:18:13 +0000503if {$isCompressed} {
504 statline {Size of uncompressed content in bytes} $file_bytes
505 set efficiency [percent $true_file_size $file_bytes]
506 statline {Size of compressed file on disk} $true_file_size $efficiency
507} else {
508 statline {Size of the file in bytes} $file_bytes
509}
danielk19770ba87cb2004-11-09 07:42:11 +0000510statline {Bytes of user payload stored} $user_payload $user_percent
drh3e27c022004-07-23 00:01:38 +0000511
512# Output table rankings
513#
514puts ""
515puts "*** Page counts for all tables with their indices ********************"
516puts ""
517mem eval {SELECT tblname, count(*) AS cnt,
danielk197724c92532005-02-01 10:36:40 +0000518 int(sum(int_pages+leaf_pages+ovfl_pages)) AS size
drhfaf60c72005-03-29 13:18:16 +0000519 FROM space_used GROUP BY tblname ORDER BY size+0 DESC, tblname} {} {
drh3e27c022004-07-23 00:01:38 +0000520 statline [string toupper $tblname] $size [percent $size $file_pgcnt]
521}
drhb7708942011-10-05 18:18:13 +0000522if {$isCompressed} {
523 puts ""
524 puts "*** Bytes of disk space used after compression ***********************"
525 puts ""
526 set csum 0
527 mem eval {SELECT tblname,
528 int(sum(compressed_size)) +
529 $compressOverhead*sum(int_pages+leaf_pages+ovfl_pages)
530 AS csize
531 FROM space_used GROUP BY tblname ORDER BY csize+0 DESC, tblname} {} {
532 incr csum $csize
533 statline [string toupper $tblname] $csize [percent $csize $true_file_size]
534 }
535 set overhead [expr {$true_file_size - $csum}]
536 if {$overhead>0} {
537 statline {Header and free space} $overhead [percent $overhead $true_file_size]
538 }
539}
drh3e27c022004-07-23 00:01:38 +0000540
541# Output subreports
542#
543if {$nindex>0} {
544 subreport {All tables and indices} 1
545}
546subreport {All tables} {NOT is_index}
547if {$nindex>0} {
548 subreport {All indices} {is_index}
549}
550foreach tbl [mem eval {SELECT name FROM space_used WHERE NOT is_index
551 ORDER BY name}] {
552 regsub ' $tbl '' qn
553 set name [string toupper $tbl]
554 set n [mem eval "SELECT count(*) FROM space_used WHERE tblname='$qn'"]
555 if {$n>1} {
556 subreport "Table $name and all its indices" "tblname='$qn'"
557 subreport "Table $name w/o any indices" "name='$qn'"
558 subreport "Indices of table $name" "tblname='$qn' AND is_index"
559 } else {
560 subreport "Table $name" "name='$qn'"
561 }
562}
563
564# Output instructions on what the numbers above mean.
565#
566puts {
567*** Definitions ******************************************************
568
569Page size in bytes
570
571 The number of bytes in a single page of the database file.
572 Usually 1024.
573
574Number of pages in the whole file
575}
drh4515a452011-08-31 17:46:50 +0000576puts " The number of $pageSize-byte pages that go into forming the complete
drh3e27c022004-07-23 00:01:38 +0000577 database"
drh4515a452011-08-31 17:46:50 +0000578puts {
drh3e27c022004-07-23 00:01:38 +0000579Pages that store data
580
581 The number of pages that store data, either as primary B*Tree pages or
582 as overflow pages. The number at the right is the data pages divided by
583 the total number of pages in the file.
584
585Pages on the freelist
586
587 The number of pages that are not currently in use but are reserved for
588 future use. The percentage at the right is the number of freelist pages
589 divided by the total number of pages in the file.
590
danielk197716254452004-11-08 16:15:09 +0000591Pages of auto-vacuum overhead
592
593 The number of pages that store data used by the database to facilitate
594 auto-vacuum. This is zero for databases that do not support auto-vacuum.
595
drh3e27c022004-07-23 00:01:38 +0000596Number of tables in the database
597
598 The number of tables in the database, including the SQLITE_MASTER table
599 used to store schema information.
600
601Number of indices
602
603 The total number of indices in the database.
604
605Number of named indices
606
607 The number of indices created using an explicit CREATE INDEX statement.
608
609Automatically generated indices
610
611 The number of indices used to implement PRIMARY KEY or UNIQUE constraints
612 on tables.
613
614Size of the file in bytes
615
616 The total amount of disk space used by the entire database files.
617
618Bytes of user payload stored
619
620 The total number of bytes of user payload stored in the database. The
621 schema information in the SQLITE_MASTER table is not counted when
622 computing this number. The percentage at the right shows the payload
623 divided by the total file size.
624
625Percentage of total database
626
627 The amount of the complete database file that is devoted to storing
628 information described by this category.
629
630Number of entries
631
632 The total number of B-Tree key/value pairs stored under this category.
633
634Bytes of storage consumed
635
636 The total amount of disk space required to store all B-Tree entries
637 under this category. The is the total number of pages used times
638 the pages size.
639
640Bytes of payload
641
642 The amount of payload stored under this category. Payload is the data
643 part of table entries and the key part of index entries. The percentage
644 at the right is the bytes of payload divided by the bytes of storage
645 consumed.
646
647Average payload per entry
648
649 The average amount of payload on each entry. This is just the bytes of
650 payload divided by the number of entries.
651
652Average unused bytes per entry
653
654 The average amount of free space remaining on all pages under this
655 category on a per-entry basis. This is the number of unused bytes on
656 all pages divided by the number of entries.
657
drhfc6e0c92007-02-13 01:41:52 +0000658Fragmentation
659
660 The percentage of pages in the table or index that are not
661 consecutive in the disk file. Many filesystems are optimized
662 for sequential file access so smaller fragmentation numbers
663 sometimes result in faster queries, especially for larger
664 database files that do not fit in the disk cache.
665
drh3e27c022004-07-23 00:01:38 +0000666Maximum payload per entry
667
668 The largest payload size of any entry.
669
670Entries that use overflow
671
672 The number of entries that user one or more overflow pages.
673
674Total pages used
675
676 This is the number of pages used to hold all information in the current
677 category. This is the sum of index, primary, and overflow pages.
678
679Index pages used
680
681 This is the number of pages in a table B-tree that hold only key (rowid)
682 information and no data.
683
684Primary pages used
685
686 This is the number of B-tree pages that hold both key and data.
687
688Overflow pages used
689
690 The total number of overflow pages used for this category.
691
692Unused bytes on index pages
693
694 The total number of bytes of unused space on all index pages. The
695 percentage at the right is the number of unused bytes divided by the
696 total number of bytes on index pages.
697
698Unused bytes on primary pages
699
700 The total number of bytes of unused space on all primary pages. The
701 percentage at the right is the number of unused bytes divided by the
702 total number of bytes on primary pages.
703
704Unused bytes on overflow pages
705
706 The total number of bytes of unused space on all overflow pages. The
707 percentage at the right is the number of unused bytes divided by the
708 total number of bytes on overflow pages.
709
710Unused bytes on all pages
711
712 The total number of bytes of unused space on all primary and overflow
713 pages. The percentage at the right is the number of unused bytes
714 divided by the total number of bytes.
715}
716
danielk19770ba87cb2004-11-09 07:42:11 +0000717# Output a dump of the in-memory database. This can be used for more
718# complex offline analysis.
drh3e27c022004-07-23 00:01:38 +0000719#
720puts "**********************************************************************"
721puts "The entire text of this report can be sourced into any SQL database"
722puts "engine for further analysis. All of the text above is an SQL comment."
723puts "The data used to generate this report follows:"
724puts "*/"
725puts "BEGIN;"
726puts $tabledef
727unset -nocomplain x
728mem eval {SELECT * FROM space_used} x {
729 puts -nonewline "INSERT INTO space_used VALUES"
730 set sep (
731 foreach col $x(*) {
732 set v $x($col)
733 if {$v=="" || ![string is double $v]} {set v [quote $v]}
734 puts -nonewline $sep$v
735 set sep ,
736 }
737 puts ");"
738}
739puts "COMMIT;"
drha7531c62006-01-24 02:19:53 +0000740
741} err]} {
742 puts "ERROR: $err"
743 puts $errorInfo
744 exit 1
745}