feat(app) lab2 prepared for mr

This commit is contained in:
imadev
2026-10-23 18:55:20 +03:00
parent 1db3953226
commit f6e74247fd
57 changed files with 2367 additions and 660 deletions
+127
View File
@@ -0,0 +1,127 @@
// AGENT: A tiny migration runner instead of a framework: one advisory lock,
// one schema_migrations row per file, each file in its own transaction.
package database
import (
"context"
"embed"
"fmt"
"io/fs"
"sort"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
//go:embed migrations/*.sql
var migrationFiles embed.FS
const migrationLockID int64 = 728_2026
func Connect(ctx context.Context, url string, maxConns int32, wait time.Duration) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(url)
if err != nil {
return nil, fmt.Errorf("parse DATABASE_URL: %w", err)
}
cfg.MaxConns = maxConns
cfg.MinConns = 1
cfg.MaxConnLifetime = 30 * time.Minute
cfg.MaxConnIdleTime = 5 * time.Minute
cfg.HealthCheckPeriod = 30 * time.Second
cfg.ConnConfig.ConnectTimeout = 3 * time.Second
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("create pool: %w", err)
}
// AGENT: Compose may start the API while PostgreSQL is still booting. A bounded
// retry keeps the container from crash-looping without hiding a permanent error.
deadline := time.Now().Add(wait)
for {
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
err = pool.Ping(pingCtx)
cancel()
if err == nil {
return pool, nil
}
if time.Now().After(deadline) || ctx.Err() != nil {
pool.Close()
return nil, fmt.Errorf("postgres is not reachable: %w", err)
}
time.Sleep(500 * time.Millisecond)
}
}
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
conn, err := pool.Acquire(ctx)
if err != nil {
return fmt.Errorf("acquire migration connection: %w", err)
}
defer conn.Release()
if _, err = conn.Exec(ctx, "SELECT pg_advisory_lock($1)", migrationLockID); err != nil {
return fmt.Errorf("acquire migration lock: %w", err)
}
defer func() {
unlockCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
_, _ = conn.Exec(unlockCtx, "SELECT pg_advisory_unlock($1)", migrationLockID)
}()
if _, err = conn.Exec(ctx, `
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
)`); err != nil {
return fmt.Errorf("create schema_migrations: %w", err)
}
entries, err := fs.ReadDir(migrationFiles, "migrations")
if err != nil {
return fmt.Errorf("read embedded migrations: %w", err)
}
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
for _, entry := range entries {
if entry.IsDir() {
continue
}
var applied bool
if err = conn.QueryRow(ctx,
"SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)", entry.Name(),
).Scan(&applied); err != nil {
return fmt.Errorf("check migration %s: %w", entry.Name(), err)
}
if applied {
continue
}
body, readErr := migrationFiles.ReadFile("migrations/" + entry.Name())
if readErr != nil {
return fmt.Errorf("read migration %s: %w", entry.Name(), readErr)
}
tx, beginErr := conn.Begin(ctx)
if beginErr != nil {
return fmt.Errorf("begin migration %s: %w", entry.Name(), beginErr)
}
if _, execErr := tx.Exec(ctx, string(body)); execErr != nil {
_ = tx.Rollback(ctx)
return fmt.Errorf("apply migration %s: %w", entry.Name(), execErr)
}
if _, insertErr := tx.Exec(ctx,
"INSERT INTO schema_migrations (version) VALUES ($1)", entry.Name(),
); insertErr != nil {
_ = tx.Rollback(ctx)
return fmt.Errorf("record migration %s: %w", entry.Name(), insertErr)
}
if commitErr := tx.Commit(ctx); commitErr != nil {
return fmt.Errorf("commit migration %s: %w", entry.Name(), commitErr)
}
}
return nil
}
@@ -0,0 +1,46 @@
-- AGENT: Single versioned baseline migration for lab 2. The application records
-- applied versions in schema_migrations, so rerunning it never duplicates rows.
-- The unique username constraint is the authoritative defence against the
-- concurrent-registration race, not a SELECT followed by an INSERT.
CREATE TABLE IF NOT EXISTS users (
id uuid PRIMARY KEY,
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT users_username_key UNIQUE (username),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100)
);
CREATE TABLE IF NOT EXISTS chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100)
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX IF NOT EXISTS chat_members_user_idx
ON chat_members (user_id, chat_id);
CREATE TABLE IF NOT EXISTS messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
text text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000)
);
-- AGENT: This composite index matches the only history predicate and sort order:
-- (chat_id, created_at, id). It lets each keyset page seek directly to the cursor
-- instead of scanning the chat history from the beginning.
CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx
ON messages (chat_id, created_at, id);