-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpg.go
More file actions
539 lines (496 loc) · 13.5 KB
/
pg.go
File metadata and controls
539 lines (496 loc) · 13.5 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
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
package pg
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
log "github.com/sirupsen/logrus"
"io"
"io/fs"
"os"
"sort"
"strconv"
"strings"
"time"
)
type migrationStatus = string
type SslMode = string
const (
EnvDatabaseAddress = "DB_ADDRESS"
EnvDatabaseAddressDefault = "localhost:5432"
EnvDatabaseUsername = "DB_USERNAME"
EnvDatabaseUsernameDefault = "postgres"
EnvDatabasePassword = "DB_PASSWORD"
EnvDatabasePasswordDefault = "postgres"
EnvDatabaseName = "DB_NAME"
EnvDatabaseNameDefault = "postgres"
EnvDatabaseSchema = "DB_SCHEMA"
EnvDatabaseSchemaDefault = ""
EnvDatabaseMigrationSchema = "DB_MIGRATION_SCHEMA"
EnvDatabaseMigrationSchemaDefault = ""
EnvDatabaseSslMode = "DB_SSL_MODE"
EnvDatabaseSslModeDefault = SslModeDisable
EnvDatabaseSslRootCert = "DB_SSL_ROOT_CERT"
EnvDatabaseSslRootCertDefault = ""
EnvDatabaseSslCert = "DB_SSL_CERT"
EnvDatabaseSslCertDefault = ""
EnvDatabaseSslKey = "DB_SSL_KEY"
EnvDatabaseSslKeyDefault = ""
EnvMigrationsEnabled = "DB_MIGRATIONS_ENABLED"
EnvMigrationsEnabledDefault = true
EnvChangelogSchema = "DB_CHANGELOG_SCHEMA"
EnvChangelogSchemaDefault = "public"
EnvChangelogTable = "DB_CHANGELOG_TABLE"
EnvChangelogTableDefault = "changelog"
EnvMigrationsDirectory = "DB_MIGRATIONS_DIRECTORY"
EnvMigrationsDirectoryDefault = "db"
statusCompleted migrationStatus = "COMPLETED"
statusError migrationStatus = "ERROR"
statusNew migrationStatus = "NEW"
SslModeDisable SslMode = "disable"
SslModeRequire SslMode = "require"
SslModeVerifyFull SslMode = "verify-full"
SslModeVerifyCA SslMode = "verify-ca"
SslModePrefer SslMode = "prefer"
SslModeAllow SslMode = "allow"
)
type Configuration struct {
Address string
Username string
Password string
Name string
Schema string
MigrationSchema string
SslMode SslMode
SslRootCert string
SslCert string
SslKey string
MigrationsEnabled bool
ChangelogSchema string
ChangelogTable string
MigrationsDirectory string
}
func CreateConfigurationFromEnv() Configuration {
address := os.Getenv(EnvDatabaseAddress)
if address == "" {
address = EnvDatabaseAddressDefault
}
username := os.Getenv(EnvDatabaseUsername)
if username == "" {
username = EnvDatabaseUsernameDefault
}
password := os.Getenv(EnvDatabasePassword)
if password == "" {
password = EnvDatabasePasswordDefault
}
name := os.Getenv(EnvDatabaseName)
if name == "" {
name = EnvDatabaseNameDefault
}
schema := os.Getenv(EnvDatabaseSchema)
if schema == "" {
schema = EnvDatabaseSchemaDefault
}
migrationSchema := os.Getenv(EnvDatabaseMigrationSchema)
if migrationSchema == "" {
migrationSchema = EnvDatabaseMigrationSchemaDefault
}
sslMode := os.Getenv(EnvDatabaseSslMode)
if sslMode == "" {
sslMode = EnvDatabaseSslModeDefault
}
sslRootCert := os.Getenv(EnvDatabaseSslRootCert)
if sslRootCert == "" {
sslRootCert = EnvDatabaseSslRootCertDefault
}
sslCert := os.Getenv(EnvDatabaseSslCert)
if sslCert == "" {
sslCert = EnvDatabaseSslCertDefault
}
sslKey := os.Getenv(EnvDatabaseSslKey)
if sslKey == "" {
sslKey = EnvDatabaseSslKeyDefault
}
migrationsEnabled, err := strconv.ParseBool(os.Getenv(EnvMigrationsEnabled))
if err != nil {
migrationsEnabled = EnvMigrationsEnabledDefault
}
changelogSchema := os.Getenv(EnvChangelogSchema)
if changelogSchema == "" {
changelogSchema = EnvChangelogSchemaDefault
}
changelogTable := os.Getenv(EnvChangelogTable)
if changelogTable == "" {
changelogTable = EnvChangelogTableDefault
}
migrationsDirectory := os.Getenv(EnvMigrationsDirectory)
if migrationsDirectory == "" {
migrationsDirectory = EnvMigrationsDirectoryDefault
}
return Configuration{
Address: address,
Username: username,
Password: password,
Name: name,
Schema: schema,
MigrationSchema: migrationSchema,
SslMode: sslMode,
SslRootCert: sslRootCert,
SslCert: sslCert,
SslKey: sslKey,
MigrationsEnabled: migrationsEnabled,
ChangelogSchema: changelogSchema,
ChangelogTable: changelogTable,
MigrationsDirectory: migrationsDirectory,
}
}
func (c Configuration) schemaTable() string {
if c.ChangelogSchema == "" {
return c.ChangelogTable
}
return c.ChangelogSchema + "." + c.ChangelogTable
}
func Connect() (*pgxpool.Pool, error) {
c := CreateConfigurationFromEnv()
return ConnectWithConfig(c)
}
func ConnectWithConfig(c Configuration) (*pgxpool.Pool, error) {
url := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s", c.Username, c.Password, c.Address, c.Name, c.SslMode)
if c.SslRootCert != "" {
url += "&sslrootcert=" + c.SslRootCert
}
if c.SslCert != "" {
url += "&sslcert=" + c.SslCert
}
if c.SslKey != "" {
url += "&sslkey=" + c.SslKey
}
config, err := pgxpool.ParseConfig(url)
if err != nil {
return nil, err
}
if c.Schema != "" {
config.ConnConfig.RuntimeParams["search_path"] = c.Schema
}
pool, err := pgxpool.NewWithConfig(context.Background(), config)
if err != nil {
return nil, err
}
if c.MigrationsEnabled {
dm := createDatabaseMigrator(pool, c)
err = dm.Migrate()
if err != nil {
return nil, err
}
}
return pool, nil
}
type databaseMigrator struct {
PgxPool *pgxpool.Pool
Configuration Configuration
}
func createDatabaseMigrator(pgxPool *pgxpool.Pool, config Configuration) *databaseMigrator {
return &databaseMigrator{
PgxPool: pgxPool,
Configuration: config,
}
}
type migration struct {
Id []int
Name string
Filename string
}
func (dbm *databaseMigrator) Migrate() error {
err := dbm.initChangelogTable()
if err != nil {
return err
}
migrations, err := dbm.getMigrations()
if err != nil {
return err
}
tx, err := dbm.PgxPool.Begin(context.Background())
if err != nil {
return err
}
defer func() {
if p := recover(); p != nil {
_ = tx.Rollback(context.Background())
panic(p)
}
}()
_, err = tx.Exec(context.Background(), dbm.replaceEnv("LOCK TABLE {SCHEMA_TABLE} IN ACCESS EXCLUSIVE MODE"))
if err != nil {
return err
}
if dbm.Configuration.MigrationSchema != "" {
exists, err := dbm.schemaExists(dbm.Configuration.MigrationSchema)
if err != nil {
return err
}
if !exists {
err = dbm.createSchema(dbm.Configuration.MigrationSchema)
if err != nil {
return err
}
}
_, err = tx.Exec(context.Background(), "SET search_path TO "+dbm.Configuration.MigrationSchema)
if err != nil {
return err
}
}
for _, migration := range migrations {
err = dbm.applyMigration(migration, tx)
if err != nil {
return err
}
}
err = tx.Commit(context.Background())
if err != nil {
return err
}
return nil
}
func Map[T, R any](list []T, fn func(T) R) []R {
result := make([]R, 0, len(list))
for _, t := range list {
result = append(result, fn(t))
}
return result
}
func (dbm *databaseMigrator) applyMigration(migration migration, tx pgx.Tx) error {
log.Printf("Applying migration %v", migration.Filename)
id := strings.Join(Map(migration.Id, strconv.Itoa), ".")
status, err := dbm.getMigrationStatus(id, tx)
if err != nil {
return err
}
if status == statusCompleted {
log.Printf("Migration %v already applied", migration.Filename)
return nil
}
scriptFile, err := os.Open(dbm.Configuration.MigrationsDirectory + string(os.PathSeparator) + migration.Filename)
if err != nil {
log.Printf("Error opening migration file %v: %v", migration.Filename, err)
return err
}
defer func(scriptFile *os.File) {
_ = scriptFile.Close()
}(scriptFile)
bytes, err := io.ReadAll(scriptFile)
if err != nil {
log.Printf("Error reading migration file %v: %v", migration.Filename, err)
return err
}
script := string(bytes)
_, migrationError := tx.Exec(context.Background(), script)
if migrationError != nil {
status = statusError
} else {
status = statusCompleted
}
log.Printf("Migration status: %v", status)
err = dbm.updateMigrationStatus(id, migration, status, tx)
if err != nil {
return err
}
return migrationError
}
func (dbm *databaseMigrator) getMigrationStatus(id string, tx pgx.Tx) (migrationStatus, error) {
//goland:noinspection SqlResolve
query := dbm.replaceEnv("SELECT status FROM {SCHEMA_TABLE} WHERE id = $1 FOR UPDATE")
row := tx.QueryRow(context.Background(), query, id)
var migrationStatus migrationStatus
err := row.Scan(&migrationStatus)
if errors.Is(err, pgx.ErrNoRows) {
return statusNew, nil
}
if err != nil {
return "", err
}
return migrationStatus, nil
}
func (dbm *databaseMigrator) updateMigrationStatus(id string, migration migration, status migrationStatus, tx pgx.Tx) error {
//goland:noinspection SqlResolve
insert := dbm.replaceEnv("INSERT INTO {SCHEMA_TABLE} (id, name, filename, status, timestamp) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (id) DO UPDATE SET status = $4, timestamp = $5")
_, err := tx.Exec(context.Background(), insert, id, migration.Name, migration.Filename, status, time.Now())
if err != nil {
log.Printf("Error inserting migration info %v: %v", migration.Filename, err)
return err
}
return nil
}
func (dbm *databaseMigrator) getMigrations() ([]migration, error) {
migrationsDir := dbm.Configuration.MigrationsDirectory
entries, err := os.ReadDir(migrationsDir)
if errors.Is(err, fs.ErrNotExist) {
log.Warnf("Directory %v does not exist", dbm.Configuration.MigrationsDirectory)
return make([]migration, 0), nil
}
if err != nil {
return nil, err
}
migrations := make([]migration, 0)
for i := range entries {
entry := entries[i]
if !entry.IsDir() {
if strings.HasSuffix(entry.Name(), ".sql") {
parts := strings.Split(entry.Name(), "_")
ids := make([]int, 0)
for _, part := range parts {
v, err := strconv.Atoi(part)
if err == nil {
ids = append(ids, v)
} else {
break
}
}
names := make([]string, 0)
for i := 0; i < len(parts)-len(ids); i++ {
names = append(names, parts[i+len(ids)])
}
name := strings.TrimSuffix(strings.Join(names, " "), ".sql")
migration := migration{
Id: ids,
Name: name,
Filename: entry.Name(),
}
migrations = append(migrations, migration)
}
}
}
sort.Slice(migrations, func(i, j int) bool {
m1 := migrations[i].Id
m2 := migrations[j].Id
for i := 0; i < min(len(m1), len(m2)); i++ {
i1 := m1[i]
i2 := m2[i]
if i1 < i2 {
return true
}
if i1 > i2 {
return false
}
}
if len(m1) < len(m2) {
return true
}
return false
})
return migrations, nil
}
func (dbm *databaseMigrator) initChangelogTable() error {
exists, err := dbm.tableExists(dbm.Configuration.ChangelogSchema, dbm.Configuration.ChangelogTable)
if err != nil {
return err
}
if !exists {
err = dbm.createChangelogTable()
if err != nil {
return err
}
}
return nil
}
func (dbm *databaseMigrator) schemaExists(schema string) (bool, error) {
querySql := "SELECT EXISTS (SELECT FROM information_schema.schemata WHERE schemata.schema_name = $1)"
row := dbm.PgxPool.QueryRow(context.Background(), querySql, schema)
var exists bool
err := row.Scan(&exists)
if err != nil {
return false, err
}
return exists, nil
}
func (dbm *databaseMigrator) tableExists(schema string, table string) (bool, error) {
//goland:noinspection SqlResolve
querySql := "SELECT EXISTS (SELECT FROM pg_tables WHERE schemaname = $1 AND tablename = $2)"
row := dbm.PgxPool.QueryRow(context.Background(), querySql, schema, table)
var exists bool
err := row.Scan(&exists)
if err != nil {
return false, err
}
return exists, nil
}
func (dbm *databaseMigrator) createSchema(schema string) error {
_, err := dbm.PgxPool.Exec(context.Background(), "CREATE SCHEMA IF NOT EXISTS "+schema)
if err != nil {
return err
}
return nil
}
func (dbm *databaseMigrator) createChangelogTable() error {
tx, err := dbm.PgxPool.Begin(context.Background())
if err != nil {
return err
}
defer func() {
if p := recover(); p != nil {
_ = tx.Rollback(context.Background())
panic(p)
}
}()
script := `
CREATE SCHEMA IF NOT EXISTS {SCHEMA};
CREATE TABLE IF NOT EXISTS {SCHEMA_TABLE}
(
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
filename TEXT NOT NULL,
status TEXT NOT NULL,
timestamp TIMESTAMPTZ NOT NULL
);
`
_, err = tx.Exec(context.Background(), dbm.replaceEnv(script))
if err != nil {
return err
}
err = tx.Commit(context.Background())
if err != nil {
return err
}
return nil
}
func (dbm *databaseMigrator) replaceEnv(s string) string {
s = strings.ReplaceAll(s, "{SCHEMA_TABLE}", dbm.Configuration.schemaTable())
s = strings.ReplaceAll(s, "{SCHEMA}", dbm.Configuration.ChangelogSchema)
return s
}
func DoInTransaction[R any](pool *pgxpool.Pool, fn func(tx pgx.Tx) (*R, error)) (*R, error) {
tx, err := pool.Begin(context.Background())
if err != nil {
return nil, err
}
defer func(tx pgx.Tx, ctx context.Context) {
_ = tx.Rollback(ctx)
}(tx, context.Background())
result, err := fn(tx)
if err != nil {
return nil, err
}
err = tx.Commit(context.Background())
if err != nil {
return nil, err
}
return result, nil
}
func DoInTransactionNoResult(pool *pgxpool.Pool, fn func(tx pgx.Tx) error) error {
tx, err := pool.Begin(context.Background())
if err != nil {
return err
}
defer func(tx pgx.Tx, ctx context.Context) {
_ = tx.Rollback(ctx)
}(tx, context.Background())
err = fn(tx)
if err != nil {
return err
}
err = tx.Commit(context.Background())
if err != nil {
return err
}
return nil
}