Добавить схему PostgreSQL, миграции и тестовое окружение

This commit is contained in:
2026-10-06 14:46:31 +03:00
parent 5c3f2bfad0
commit a552f15aa7
9 changed files with 731 additions and 26 deletions
+79
View File
@@ -0,0 +1,79 @@
// Package postgres opens the connection pool and applies the schema.
//
// Pool size and server-side timeouts are constants rather than settings: they
// bound how long one request can hold a connection, and the request deadline
// of the API is chosen against them.
package postgres
import (
"context"
"errors"
"fmt"
"strconv"
"time"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/pgx/v5/stdlib"
"github.com/pressly/goose/v3"
"github.com/pressly/goose/v3/lock"
"messenger/migrations"
)
const (
maxConns = 10
connectTimeout = 3 * time.Second
statementTimeout = 5 * time.Second
idleInTxTimeout = 10 * time.Second
)
const codeUniqueViolation = "23505"
func NewPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, fmt.Errorf("parse database url: %w", err)
}
cfg.MaxConns = maxConns
cfg.ConnConfig.ConnectTimeout = connectTimeout
cfg.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(statementTimeout.Milliseconds(), 10)
cfg.ConnConfig.RuntimeParams["idle_in_transaction_session_timeout"] = strconv.FormatInt(idleInTxTimeout.Milliseconds(), 10)
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("create pool: %w", err)
}
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping database: %w", err)
}
return pool, nil
}
// Migrate applies pending migrations. A session advisory lock serialises
// concurrent starts, so several API replicas may call it at once; applied
// versions are recorded, which makes a repeated run a no-op.
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
db := stdlib.OpenDBFromPool(pool)
defer db.Close()
locker, err := lock.NewPostgresSessionLocker()
if err != nil {
return fmt.Errorf("migration lock: %w", err)
}
provider, err := goose.NewProvider(goose.DialectPostgres, db, migrations.FS, goose.WithSessionLocker(locker))
if err != nil {
return fmt.Errorf("load migrations: %w", err)
}
if _, err := provider.Up(ctx); err != nil {
return fmt.Errorf("apply migrations: %w", err)
}
return nil
}
// IsUniqueViolation reports whether err is a unique violation of the named
// constraint.
func IsUniqueViolation(err error, constraint string) bool {
pgErr, ok := errors.AsType[*pgconn.PgError](err)
return ok && pgErr.Code == codeUniqueViolation && pgErr.ConstraintName == constraint
}
+135
View File
@@ -0,0 +1,135 @@
package postgres_test
import (
"context"
"errors"
"fmt"
"os"
"testing"
"messenger/internal/platform/postgres"
"messenger/internal/testenv"
)
var db *testenv.DB
func TestMain(m *testing.M) {
var err error
db, err = testenv.StartPostgres(context.Background())
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
code := m.Run()
db.Close()
os.Exit(code)
}
func TestMigrateIsRepeatable(t *testing.T) {
ctx := context.Background()
if err := postgres.Migrate(ctx, db.Pool); err != nil {
t.Fatalf("second migrate: %v", err)
}
var version int64
if err := db.Pool.QueryRow(ctx, `SELECT max(version_id) FROM goose_db_version`).Scan(&version); err != nil {
t.Fatal(err)
}
if version != 1 {
t.Fatalf("schema version = %d, want 1", version)
}
for _, table := range []string{"users", "chats", "chat_members", "messages"} {
var exists bool
if err := db.Pool.QueryRow(ctx, `SELECT to_regclass('public.' || $1) IS NOT NULL`, table).Scan(&exists); err != nil {
t.Fatal(err)
}
if !exists {
t.Fatalf("table %s is missing", table)
}
}
}
func TestPoolAppliesLimitsAndTimeouts(t *testing.T) {
if got := db.Pool.Config().MaxConns; got != 10 {
t.Fatalf("MaxConns = %d, want 10", got)
}
ctx := context.Background()
for setting, want := range map[string]string{
"statement_timeout": "5s",
"idle_in_transaction_session_timeout": "10s",
} {
var got string
if err := db.Pool.QueryRow(ctx, "SHOW "+setting).Scan(&got); err != nil {
t.Fatal(err)
}
if got != want {
t.Fatalf("%s = %q, want %q", setting, got, want)
}
}
}
func TestResetEmptiesEveryTableButKeepsSchemaVersion(t *testing.T) {
ctx := context.Background()
_, err := db.Pool.Exec(ctx, `
WITH u AS (
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ('0190f1d2-0000-7000-8000-000000000001', 'reset_check', 'Reset', 'x', now())
RETURNING id
), c AS (
INSERT INTO chats (id, title, created_at)
VALUES ('0190f1d2-0000-7000-8000-000000000002', 'Reset', now())
RETURNING id
), m AS (
INSERT INTO chat_members (chat_id, user_id) SELECT c.id, u.id FROM c, u
)
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT '0190f1d2-0000-7000-8000-000000000003', c.id, u.id, 'hi', now() FROM c, u`)
if err != nil {
t.Fatal(err)
}
db.Reset(t)
for _, table := range []string{"users", "chats", "chat_members", "messages"} {
var n int
if err := db.Pool.QueryRow(ctx, "SELECT count(*) FROM "+table).Scan(&n); err != nil {
t.Fatal(err)
}
if n != 0 {
t.Fatalf("%s has %d rows after Reset", table, n)
}
}
var versions int
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM goose_db_version`).Scan(&versions); err != nil {
t.Fatal(err)
}
if versions == 0 {
t.Fatal("Reset wiped the schema version table")
}
}
func TestIsUniqueViolation(t *testing.T) {
db.Reset(t)
ctx := context.Background()
insert := `INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1, 'taken', 'Taken', 'x', now())`
if _, err := db.Pool.Exec(ctx, insert, "0190f1d2-0000-7000-8000-000000000011"); err != nil {
t.Fatal(err)
}
_, dup := db.Pool.Exec(ctx, insert, "0190f1d2-0000-7000-8000-000000000012")
if dup == nil {
t.Fatal("duplicate username was accepted")
}
if !postgres.IsUniqueViolation(dup, "users_username_key") {
t.Fatalf("not recognised as a username violation: %v", dup)
}
if postgres.IsUniqueViolation(dup, "some_other_key") {
t.Fatal("matched a different constraint")
}
if postgres.IsUniqueViolation(fmt.Errorf("wrapped: %w", dup), "users_username_key") == false {
t.Fatal("wrapped error not recognised")
}
if postgres.IsUniqueViolation(errors.New("plain"), "users_username_key") || postgres.IsUniqueViolation(nil, "users_username_key") {
t.Fatal("non-database error recognised as a violation")
}
}
+128
View File
@@ -0,0 +1,128 @@
// Package testenv starts disposable PostgreSQL and Valkey containers for tests
// that exercise the real stores. Only _test files import it, so it never
// reaches the server binary. The images match compose.yaml.
package testenv
import (
"context"
"fmt"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"github.com/testcontainers/testcontainers-go"
tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres"
tcvalkey "github.com/testcontainers/testcontainers-go/modules/valkey"
"messenger/internal/platform/postgres"
)
const (
PostgresImage = "postgres:18.6-alpine3.24@sha256:77f585114c32fbca283dc835b0596f4e52b51b4c6662d7810b2f4084f60a1873"
ValkeyImage = "valkey/valkey:9.1.2-alpine3.24@sha256:48332870af354a799964c0012ae1194a0bf2bf894eb508f945810596dc2d8d11"
)
// DB is a migrated PostgreSQL instance.
type DB struct {
Pool *pgxpool.Pool
DSN string
container *tcpostgres.PostgresContainer
}
func StartPostgres(ctx context.Context) (*DB, error) {
c, err := tcpostgres.Run(ctx, PostgresImage,
tcpostgres.WithDatabase("messenger"),
tcpostgres.WithUsername("messenger"),
tcpostgres.WithPassword("messenger"),
tcpostgres.BasicWaitStrategies(),
)
if err != nil {
return nil, fmt.Errorf("start postgres: %w", err)
}
db := &DB{container: c}
db.DSN, err = c.ConnectionString(ctx, "sslmode=disable")
if err != nil {
db.Close()
return nil, fmt.Errorf("postgres address: %w", err)
}
db.Pool, err = postgres.NewPool(ctx, db.DSN)
if err != nil {
db.Close()
return nil, err
}
if err := postgres.Migrate(ctx, db.Pool); err != nil {
db.Close()
return nil, err
}
return db, nil
}
// Reset empties every application table, so each test starts from an empty
// schema. The table list comes from the catalog: a table added by a later
// migration cannot be forgotten here.
func (d *DB) Reset(t testing.TB) {
t.Helper()
ctx := context.Background()
var tables string
err := d.Pool.QueryRow(ctx, `
SELECT coalesce(string_agg(format('%I.%I', schemaname, tablename), ', '), '')
FROM pg_tables
WHERE schemaname = 'public' AND tablename <> 'goose_db_version'`).Scan(&tables)
if err != nil {
t.Fatalf("list tables: %v", err)
}
if tables == "" {
return
}
if _, err := d.Pool.Exec(ctx, "TRUNCATE "+tables+" CASCADE"); err != nil {
t.Fatalf("truncate: %v", err)
}
}
func (d *DB) Close() {
if d.Pool != nil {
d.Pool.Close()
}
_ = testcontainers.TerminateContainer(d.container)
}
// KV is a Valkey instance without persistence or password.
type KV struct {
Client *redis.Client
URL string
container *tcvalkey.ValkeyContainer
}
func StartValkey(ctx context.Context) (*KV, error) {
c, err := tcvalkey.Run(ctx, ValkeyImage)
if err != nil {
return nil, fmt.Errorf("start valkey: %w", err)
}
kv := &KV{container: c}
kv.URL, err = c.ConnectionString(ctx)
if err != nil {
kv.Close()
return nil, fmt.Errorf("valkey address: %w", err)
}
opts, err := redis.ParseURL(kv.URL)
if err != nil {
kv.Close()
return nil, fmt.Errorf("valkey url: %w", err)
}
kv.Client = redis.NewClient(opts)
return kv, nil
}
func (k *KV) Reset(t testing.TB) {
t.Helper()
if err := k.Client.FlushDB(context.Background()).Err(); err != nil {
t.Fatalf("flushdb: %v", err)
}
}
func (k *KV) Close() {
if k.Client != nil {
_ = k.Client.Close()
}
_ = testcontainers.TerminateContainer(k.container)
}
+29
View File
@@ -0,0 +1,29 @@
package testenv_test
import (
"context"
"testing"
"messenger/internal/testenv"
)
func TestValkeyStartsAndResetFlushesKeys(t *testing.T) {
ctx := context.Background()
kv, err := testenv.StartValkey(ctx)
if err != nil {
t.Fatal(err)
}
defer kv.Close()
if err := kv.Client.Set(ctx, "probe", "1", 0).Err(); err != nil {
t.Fatal(err)
}
kv.Reset(t)
n, err := kv.Client.DBSize(ctx).Result()
if err != nil {
t.Fatal(err)
}
if n != 0 {
t.Fatalf("%d keys left after Reset", n)
}
}