Skip to content

Commit

Permalink
migration - 202102111035-template-revisions
Browse files Browse the repository at this point in the history
Fixes: tinkerbell#413

The migration introduces template revisions. A template can have multiple
revisions, which are stored in the 'template_revisions' table.

The migration also transforms the existing templates to the new
template-revisions structure. Therefore ensuring that end users do not
face any issues with the introduction of revisions.

Signed-off-by: Gaurav Gahlot <[email protected]>
  • Loading branch information
gauravgahlot committed Mar 11, 2021
1 parent c4e5d39 commit 3f1cbe1
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
60 changes: 60 additions & 0 deletions db/migration/202102111035-template-revisions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package migration

import migrate "github.com/rubenv/sql-migrate"

// Get202102111035 introduces template revisions.
//
// Fixes: https://github.com/tinkerbell/tink/issues/413
//
// The migration introduces template revisions. A template can have multiple
// revisions, which are stored in the 'template_revisions' table.
//
// The migration also transforms the existing templates to the new
// template-revisions structure. Therefore ensuring that end users do not
// face any issues with the introduction of revisions.
func Get202102111035() *migrate.Migration {
return &migrate.Migration{
Id: "202102111035-template-revisions",
Up: []string{`
CREATE TABLE IF NOT EXISTS template_revisions(
template_id UUID
, revision SMALLINT DEFAULT 1
, data BYTEA
, created_at TIMESTAMPTZ DEFAULT now()
, deleted_at TIMESTAMPTZ
, PRIMARY KEY(template_id, revision)
);
CREATE INDEX IF NOT EXISTS idx_template_revisions_template_id ON template_revisions (template_id);
ALTER TABLE template ADD COLUMN revision INT DEFAULT 1;
CREATE OR REPLACE FUNCTION migrate_to_template_revisions()
RETURNS void AS $$
DECLARE
template_count integer;
revisions_count integer;
BEGIN
SELECT COUNT(id) INTO template_count
FROM template WHERE deleted_at IS NULL;
INSERT INTO template_revisions(template_id, data, created_at)
SELECT id, data, created_at
FROM template
WHERE template.deleted_at IS NULL;
SELECT COUNT(template_id) INTO revisions_count
FROM template_revisions WHERE deleted_at IS NULL;
IF revisions_count != template_count THEN
RAISE EXCEPTION 'failed to migrate templates';
END IF;
ALTER TABLE template DROP COLUMN data;
END;
$$ LANGUAGE plpgsql;
SELECT migrate_to_template_revisions();
`},
}
}
1 change: 1 addition & 0 deletions db/migration/migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ var migrations = []func() *migrate.Migration{
Get202012041103,
Get202012091055,
Get2020121691335,
Get202102111035,
}

func GetMigrations() *migrate.MemoryMigrationSource {
Expand Down

0 comments on commit 3f1cbe1

Please sign in to comment.