/
sql.go
249 lines (202 loc) · 5.41 KB
/
sql.go
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package sql
import (
"context"
_ "embed"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"github.com/jackc/pgx/v5"
"github.com/magefile/mage/sh"
"github.com/ttab/mage/internal"
)
const (
sqlTools = "ghcr.io/ttab/elephant-sqltools:v0.1.3"
postgresImage = "docker.io/pgvector/pgvector:pg16"
)
// SqlcCommand returns a command function that runs sqlc in docker with the
// current working directory mounted.
func SqlcCommand() func(args ...string) error {
uid := os.Getuid()
gid := os.Getgid()
cwd := internal.MustGetWD()
return sh.RunCmd("docker", "run", "--rm",
"-v", fmt.Sprintf("%s:/usr/src", cwd),
"-u", fmt.Sprintf("%d:%d", uid, gid),
sqlTools, "sqlc",
)
}
// SqlcCommand returns a command function that runs tern in docker with host
// networking and the current working directory mounted.
func TernCommand() func(args ...string) error {
cwd := internal.MustGetWD()
return sh.RunCmd("docker", "run", "--rm",
"-v", fmt.Sprintf("%s:/usr/src", cwd),
"--network", "host",
sqlTools, "tern",
)
}
// Generate uses sqlc to compile the SQL queries in postgres/queries.sql to Go,
// adding he default sqlc.yaml file if necessary.
func Generate() error {
hasConfig, err := internal.FileExists("sqlc.yaml")
if err != nil {
return err
}
if !hasConfig {
err := SqlcConfig()
if err != nil {
return fmt.Errorf("add default config: %w", err)
}
}
sqlc := SqlcCommand()
err = sqlc("--experimental", "generate")
if err != nil {
return fmt.Errorf("sqlc: %w", err)
}
return nil
}
//go:embed sqlc.yaml
var defaultSqlcConfig []byte
// SqlcConfig adds the default sqlc config.
func SqlcConfig() error {
err := os.WriteFile("sqlc.yaml", defaultSqlcConfig, 0o600)
if err != nil {
return fmt.Errorf("write sqlc.yaml: %w", err)
}
return nil
}
// Migrate the database to the latest version using the migrations in
// "./schema".
func Migrate() error {
connString := mustGetConnString()
tern := TernCommand()
err := tern("migrate", "--migrations", "schema",
"--conn-string", connString)
if err != nil {
return fmt.Errorf("run migration: %w", err)
}
err = DumpSchema()
if err != nil {
return fmt.Errorf("dump schema after migration: %w", err)
}
return nil
}
// Rollback to the specific schema version.
func Rollback(to int) error {
connString := mustGetConnString()
tern := TernCommand()
err := tern("migrate", "--migrations", "schema",
"--conn-string", connString,
"--destination", strconv.Itoa(to))
if err != nil {
return fmt.Errorf("run migration: %w", err)
}
err = DumpSchema()
if err != nil {
return fmt.Errorf("dump schema after rollback: %w", err)
}
return nil
}
// DumpSchema writes the current database schema to "./postgres/schema.sql".
func DumpSchema() error {
connString := mustGetConnString()
outFile, err := os.Create(filepath.Join("postgres", "schema.sql"))
if err != nil {
return fmt.Errorf("create schema file: %w", err)
}
ok, err := sh.Exec(nil, outFile, os.Stderr,
"docker", "run", "--rm", "--network", "host",
postgresImage,
"pg_dump", connString,
"--schema-only", "--no-owner", "--no-privileges",
)
if err != nil {
return fmt.Errorf("run pg_dump: %w", err)
}
if !ok {
return errors.New("failed to run pg_dump in docker")
}
return nil
}
// Postgres creates a local Postgres instance using docker.
func Postgres(name string) error {
uid := os.Getuid()
gid := os.Getgid()
stateDir := os.Getenv("STATE_DIR")
if stateDir == "" {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("get home directory: %w", err)
}
stateDir = filepath.Join(homeDir, "localstate")
}
instanceName := "postgres-" + name
dataDir := filepath.Join(stateDir, instanceName)
err := os.MkdirAll(dataDir, 0o700)
if err != nil {
return fmt.Errorf("create local state directory: %w", err)
}
err = internal.StopContainerIfExists(instanceName)
if err != nil {
return fmt.Errorf("stop existing container: %w", err)
}
err = sh.Run("docker", "run", "-d", "--rm",
"--name", instanceName,
"--user", fmt.Sprintf("%d:%d", uid, gid),
"-e", "POSTGRES_USER=admin",
"-e", "POSTGRES_PASSWORD=pass",
"-e", "PGDATA=/var/lib/postgresql/data/pgdata",
"-v", fmt.Sprintf("%s:/var/lib/postgresql/data", dataDir),
"-p", "5432:5432",
postgresImage,
"-c", "wal_level=logical",
"-c", "log_lock_waits=on",
)
if err != nil {
return fmt.Errorf("start postgres: %w", err)
}
return nil
}
// DB calls DBWithName using the current directory name as the database name.
func DB() error {
cwd := internal.MustGetWD()
name := filepath.Base(cwd)
return DBWithName(name)
}
// DBWithName creates a database and login role with the same name and the
// password 'pass'.
func DBWithName(name string) error {
ctx := context.Background()
conn, err := pgx.Connect(ctx, "postgres://admin:pass@localhost")
if err != nil {
return fmt.Errorf("connect to database: %w", err)
}
_, err = conn.Exec(ctx, fmt.Sprintf(
"CREATE ROLE %q WITH LOGIN PASSWORD 'pass'",
name,
))
if err != nil {
return fmt.Errorf("create login role: %w", err)
}
_, err = conn.Exec(ctx, fmt.Sprintf(
"CREATE DATABASE %q WITH OWNER %q",
name, name,
))
if err != nil {
return fmt.Errorf("create database: %w", err)
}
return nil
}
func mustGetConnString() string {
connString := os.Getenv("CONN_STRING")
if connString == "" {
cwd := internal.MustGetWD()
name := filepath.Base(cwd)
connString = fmt.Sprintf(
"postgres://%s:pass@localhost/%s",
name, name)
}
return connString
}