d1449ac418516ba92294d4711328b2e856b5ce8d
[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.  The intent column was also added to the snapshots
11 -- table.
12 create table segments_new (
13     segmentid integer primary key,
14     segment text unique not null,
15     path text,
16     checksum text,
17     mtime real,
18     size integer
19 );
20
21 create table segments_used (
22     snapshotid integer not null,
23     segmentid integer not null,
24     utilization real
25 );
26
27 alter table snapshots add column intent real;
28
29 -- Initialize the intent column; set all old snapshots to have intent 1
30 -- (intended to be a daily snapshot).
31 update snapshots set intent = 1;
32
33 -- Compute the size of each of the segments, if possible, based on our
34 -- knowledge of the objects stored in them.
35 insert into segments_new
36 select segmentid, segment, path, checksum, mtime, size
37 from
38     (select segmentid, segment, path, checksum from segments)
39 left join
40     (select segmentid, sum(size) as size, max(timestamp) as mtime
41      from block_index group by segmentid)
42 using (segmentid);
43
44 drop table segments;
45 alter table segments_new rename to segments;
46
47 -- Populate the segments_used table based upon data contained in
48 -- snapshot_contents--this is roughly the same calculation that is actually
49 -- done, only now this calculation is done when a snapshot is created.
50 insert into segments_used
51 select snapshotid, segmentid, cast(used as real) / size as utilization
52 from
53     (select snapshotid, segmentid, sum(size) as used
54      from snapshot_contents join block_index using (blockid)
55      group by snapshotid, segmentid)
56 join
57     (select segmentid, size from segments)
58 using (segmentid);
59
60 -- The snapshot_contents table is obsolete.
61 drop table snapshot_contents;
62
63 -- Upgrade database views.
64 drop view cleaning_order;
65 drop view segment_info;
66
67 create view segment_info as
68 select segmentid, mtime, size, cast(size * utilization as integer) as used,
69        utilization
70 from segments join
71      (select segmentid, max(utilization) as utilization
72       from segments_used group by segmentid)
73 using (segmentid);