forked from mtusi2026/mtusi2026lab2
Перевести API на PostgreSQL и сохраняемые Bearer-сессии
This commit is contained in:
+102
@@ -0,0 +1,102 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationFiles embed.FS
|
||||
|
||||
func databaseURL() (string, error) {
|
||||
if path := os.Getenv("DATABASE_URL_FILE"); path != "" {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(string(data)), nil
|
||||
}
|
||||
if url := os.Getenv("DATABASE_URL"); url != "" {
|
||||
return url, nil
|
||||
}
|
||||
return "", errors.New("DATABASE_URL_FILE or DATABASE_URL is required")
|
||||
}
|
||||
|
||||
func openDatabase(ctx context.Context) (*pgxpool.Pool, error) {
|
||||
url, err := databaseURL()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.MaxConns = 10
|
||||
cfg.ConnConfig.ConnectTimeout = 5 * time.Second
|
||||
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = db.Ping(ctx); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err = applyMigrations(ctx, db); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func applyMigrations(ctx context.Context, db *pgxpool.Pool) error {
|
||||
files, err := migrationFiles.ReadDir("migrations")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sort.Slice(files, func(i, j int) bool { return files[i].Name() < files[j].Name() })
|
||||
tx, err := db.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(20426002)"); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY)"); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, file := range files {
|
||||
var exists bool
|
||||
if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=$1)", file.Name()).Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
if exists {
|
||||
continue
|
||||
}
|
||||
sql, readErr := migrationFiles.ReadFile("migrations/" + file.Name())
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
if _, err = tx.Exec(ctx, string(sql)); err != nil {
|
||||
return fmt.Errorf("migration %s: %w", file.Name(), err)
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES($1)", file.Name()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func uniqueViolation(err error) bool {
|
||||
var pgerr *pgconn.PgError
|
||||
return errors.As(err, &pgerr) && pgerr.Code == "23505"
|
||||
}
|
||||
Reference in New Issue
Block a user