Upgrades to utility code for new formats, and a few more database tweaks.
[cumulus.git] / contrib / upgrade0.6-localdb.sql
1 -- SQL script for upgrading the local database to the format expected for LBS
2 -- version 0.6.
3 --
4 -- This script should be loaded after connecting to the database to be
5 -- upgraded.
6
7 -- Database schema changes: the size and mtime columns were added to the
8 -- segments table, and the segments_used table was added.  Rather than upgrade
9 -- the segments table in-place, we create a new table and then rename it over
10 -- the old segments table.
11 create table segments_new (
12     segmentid integer primary key,
13     segment text unique not null,
14     path text,
15     checksum text,
16     mtime real,
17     size integer
18 );
19
20 create table segments_used (
21     snapshotid integer not null,
22     segmentid integer not null,
23     utilization real
24 );
25
26 -- Compute the size of each of the segments, if possible, based on our
27 -- knowledge of the objects stored in them.
28 insert into segments_new
29 select segmentid, segment, path, checksum, mtime, size
30 from
31     (select segmentid, segment, path, checksum from segments)
32 left join
33     (select segmentid, sum(size) as size, max(timestamp) as mtime
34      from block_index group by segmentid)
35 using (segmentid);
36
37 drop table segments;
38 alter table segments_new rename to segments;
39
40 -- Populate the segments_used table based upon data contained in
41 -- snapshot_contents--this is roughly the same calculation that is actually
42 -- done, only now this calculation is done when a snapshot is created.
43 insert into segments_used
44 select snapshotid, segmentid, cast(used as real) / size as utilization
45 from
46     (select snapshotid, segmentid, sum(size) as used
47      from snapshot_contents join block_index using (blockid)
48      group by snapshotid, segmentid)
49 join
50     (select segmentid, size from segments)
51 using (segmentid);
52
53 -- The snapshot_contents table is obsolete.
54 drop table snapshot_contents;
55
56 -- Upgrade database views.
57 drop view cleaning_order;
58 drop view segment_info;
59
60 create view segment_info as
61 select segmentid, mtime, size, cast(size * utilization as integer) as used,
62        utilization
63 from segments join
64      (select segmentid, max(utilization) as utilization
65       from segments_used group by segmentid)
66 using (segmentid);