aboutsummaryrefslogtreecommitdiff
path: root/src/guff/database-updater.cr
blob: 74af00581927c7c796b3fd23ebfae89719afaf6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
require "./database"

module Guff
  class DatabaseUpdater
    SQL = {
      get_version: "
        SELECT value
          FROM metadata
         WHERE name = 'version'
      ",

      set_version_delete: "
        DELETE FROM metadata WHERE name = 'version'
      ",

      set_version_insert: "
        INSERT INTO metadata(name, value) VALUES ('version', ?)
      ",
    }

    def self.run(path, config)
      new(path, config).run
    end

    def initialize(
      @path   : String,
      @config : Config
    )
      @db = Database.new(@path)
    end

    def run
      # get version from database
      db_version = @db.table_exists?("metadata") ? get_version : 0
      app_version = MIGRATIONS.size - 1

      if db_version < app_version
        puts "starting db migration (db = %d, app = %d)" % [
          db_version,
          app_version
        ]

        (db_version + 1).upto(app_version) do |v|
          migrate_to(v)
        end
      end
    end

    private def migrate_to(version)
      # map version number to migration id
      m = MIGRATIONS[version]
      puts "  * migration: %s" % [m[:id]]

      @db.transaction do
        # exec queries
        (m[:sql] as Array(String)).each do |sql|
          @db.query(sql)
        end

        # update database version
        set_version(version)
      end
    end

    private def get_version
      (@db.one(SQL[:get_version]) || 0).to_i
    end

    private def set_version(version)
      @db.query(SQL[:set_version_delete])
      @db.query(SQL[:set_version_insert], [version.to_s])
    end
  end
end