summaryrefslogtreecommitdiff
path: root/src/invidious/database/migration.cr
blob: 921d8f38b638bcf2cac0b22f4626b6b0bf0bcfa5 (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
abstract class Invidious::Database::Migration
  macro inherited
    Migrator.migrations << self
  end

  @@version : Int64?

  def self.version(version : Int32 | Int64)
    @@version = version.to_i64
  end

  getter? completed = false

  def initialize(@db : DB::Database)
  end

  abstract def up(conn : DB::Connection)

  def migrate
    # migrator already ignores completed migrations
    # but this is an extra check to make sure a migration doesn't run twice
    return if completed?

    @db.transaction do |txn|
      up(txn.connection)
      track(txn.connection)
      @completed = true
    end
  end

  def version : Int64
    @@version.not_nil!
  end

  private def track(conn : DB::Connection)
    conn.exec("INSERT INTO #{Migrator::MIGRATIONS_TABLE} (version) VALUES ($1)", version)
  end
end