This repository was archived by the owner on Feb 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpg.mk
More file actions
88 lines (74 loc) · 2.4 KB
/
pg.mk
File metadata and controls
88 lines (74 loc) · 2.4 KB
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
GO_MOD = $(shell head -n 1 go.mod|sed "s/^module //g")
MOD_NAME = $(shell basename $(GO_MOD))
DB_BASE_URL ?= postgres://$(PG_USER):$(PG_PWD)@${PG_SERVICE}
export DB_URL = $(DB_BASE_URL)/$(MOD_NAME)?sslmode=disable
MIGRATION_PATH = data/migration
MIGRATE = @migrate -database "$(DB_URL)" -path $(MIGRATION_PATH)
CREATE_DB = 'create database "$(MOD_NAME)"'
DROP_DB = 'drop database if exists "$(MOD_NAME)"'
# Wait for postgres to be up
db.is-up:
@$(call _info,Waiting for Postgres…)
@dockerize -wait tcp://$(PG_SERVICE):5432 -timeout 60s
.PHONY: db.is-up
# Reset database (rollback, migrate)
db.reset: db.is-up db.rollback db.migrate
.PHONY: db.reset
# Create database
db.create: db.is-up
@$(call _info,Creating DB $(MOD_NAME)…)
@echo ">" $(CREATE_DB)
@psql $(DB_BASE_URL) -c $(CREATE_DB)
ifdef DB_SCHEMA
@echo ">" $(DB_SCHEMA)
@psql $(DB_URL) -f $(DB_SCHEMA)
endif
.PHONY: db.create
# Drop database
db.drop: db.is-up
@$(call _info,Dropping DB $(MOD_NAME)…)
@echo ">" $(DROP_DB)
@psql $(DB_BASE_URL) -c $(DROP_DB)
.PHONY: db.drop
# Generate migration with NAME=<migration_name>
db.generate: db.is-up
$(if $(NAME),,$(error NAME env var must be set to a migration name.))
@$(call _info,Generating DB $(MOD_NAME)…)
$(MIGRATE) create -ext sql -dir $(MIGRATION_PATH) $(NAME)
@find $(MIGRATION_PATH)/*$(NAME)* -newerct '1 second ago' -print
.PHONY: db.generate
# Apply all or N=<n> database migrations
db.migrate: db.is-up
$(if $(N), \
@$(call _info,Running migrations up to $(N) on DB $(MOD_NAME)…), \
@$(call _info,Running all migrations on DB $(MOD_NAME)…) \
)
$(MIGRATE) up $(N)
.PHONY: db.migrate
# Rollback all or N=<n> database migrations
db.rollback: db.is-up
$(if $(N), \
@$(call _info,Rolling back migrations down to $(N) on DB $(MOD_NAME)…), \
@$(call _info,Rolling back all migrations on DB $(MOD_NAME)…) \
)
$(MIGRATE) down $(N)
.PHONY: db.rollback
# Set migration version V=<v> without running migration
db.force: db.is-up
$(if $(V),,$(error V env var must be set.))
@$(call _info,Force DB $(MOD_NAME) to migration $(V)…)
$(MIGRATE) force $(V)
$(MIGRATE) version
.PHONY: db.force
# Show current migration version
db.version: db.is-up
@$(call _info,$(MOD_NAME) DB version…)
$(MIGRATE) version
.PHONY: db.version
ifdef SEED
# Seed database with SEED
db.seed: db.is-up
@$(call _info,Seeding DB $(MOD_NAME)…)
@SVC_NAME=$(GO_MOD) DB_ENDPOINT=writer go run $(SEED)
.PHONY: db.seed
endif