~yerinalexey/gobin

ref: 478164c98843185c65508a38552befc51838da7b gobin/gobin-migrate -rwxr-xr-x 2.0 KiB
478164c9 — Alexey Yerin Add option to set log file 8 months ago
                                                                                
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/bin/sh

# Migrator script for gobin

set -e

MIGRATION_PATH="${MIGRATION_PATH:-./migrations}"

if [ -z "$DATABASE_URI" ]; then
  printf 'DATABASE_URI environment variable is not set\n'
  exit 1
fi

# Helper functions
run_sql() {
  psql "$@" "$DATABASE_URI"
}

is_migrated() {
  name="$1"

  printf '%s' "$migrations" | fgrep "$name" >/dev/null
}

apply_migration() {
  name="$1"

  if is_migrated "$name"; then
    printf '%s: already applied, skipping\n' "$name"
    return
  fi

  file="$MIGRATION_PATH/$name/up.sql"

  if [ ! -f "$file" ]; then
    printf 'Migration has not been found: %s\n' "$file"
    exit 1
  fi

  printf 'Applying migration %s\n' "$name"

  run_sql -f "$file" && \
    run_sql -c "insert into _gobin_migrations (name) values ('$name');" >/dev/null
}

revert_migration() {
  name="$1"

  if ! is_migrated "$name"; then
    printf '%s: not applied, skipping\n' "$name"
    return
  fi

  file="$MIGRATION_PATH/$name/down.sql"

  if [ ! -f "$file" ]; then
    printf 'Reverse migration has not been found: %s\n' "$file"
    exit 1
  fi

  printf 'Reverting migration %s\n' "$name"

  run_sql -f "$file" && \
    run_sql -c "delete from _gobin_migrations where name='$name';" >/dev/null
}

up_migrations() {
  for name in `ls "$MIGRATION_PATH"`; do
    apply_migration "$name"
  done
}

# Create migrations table
run_sql -c '
create table if not exists _gobin_migrations (
  name varchar(255) primary key,
  created_at timestamp default now()
);' 2>/dev/null >/dev/null

migrations="$(run_sql --csv -c 'select name from _gobin_migrations;' | \
  tail -n +2)"

case "$1" in
  apply)
    name="$2"

    if [ -z "$name" ]; then
      printf 'Usage: gobin-migrate apply NAME'
      exit
    fi

    apply_migration "$name"
    ;;
  revert)
    name="$2"

    if [ -z "$name" ]; then
      printf 'Usage: gobin-migrate revert NAME'
      exit
    fi

    revert_migration "$name"
    ;;
  up)
    up_migrations
    ;;
  *)
    printf 'Usage: gobin-migrate <up|apply|revert> ARGUMENTS\n'
    ;;
esac