package main import ( "context" "crypto/sha256" "embed" "encoding/hex" "errors" "fmt" "sort" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" ) //go:embed migrations/*.sql var migrations embed.FS func migrate(ctx context.Context, db *pgxpool.Pool) error { conn, err := db.Acquire(ctx) if err != nil { return err } defer conn.Release() if _, err = conn.Exec(ctx, "SELECT pg_advisory_lock(202602)"); err != nil { return err } defer conn.Exec(context.Background(), "SELECT pg_advisory_unlock(202602)") if _, err = conn.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())"); err != nil { return err } entries, err := migrations.ReadDir("migrations") if err != nil { return err } sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() }) for _, entry := range entries { raw, err := migrations.ReadFile("migrations/" + entry.Name()) if err != nil { return err } sum := sha256.Sum256(raw) checksum := hex.EncodeToString(sum[:]) var previous string err = conn.QueryRow(ctx, "SELECT checksum FROM schema_migrations WHERE version=$1", entry.Name()).Scan(&previous) if err == nil { if previous != checksum { return fmt.Errorf("migration checksum mismatch: %s", entry.Name()) } continue } if !errors.Is(err, pgx.ErrNoRows) { return err } tx, err := conn.Begin(ctx) if err != nil { return err } if _, err = tx.Exec(ctx, string(raw)); err == nil { _, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version,checksum) VALUES($1,$2)", entry.Name(), checksum) } if err != nil { tx.Rollback(ctx) return err } if err = tx.Commit(ctx); err != nil { return err } } return nil } func dbError(err error) error { if err == nil { return nil } if errors.Is(err, pgx.ErrNoRows) { return missing() } var pe *pgconn.PgError if errors.As(err, &pe) { switch pe.Code { case "23505": return apiError{409, "conflict", "Username already exists"} case "23503", "23514", "22P02", "22021": return invalid() } } return unavailable() } func stamp(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000000Z") } // pgx BytesScanner preserves every validated UTF-8 code point, including NUL. type utf8String struct{ dst *string } func (s utf8String) ScanBytes(value []byte) error { *s.dst = string(value) return nil } func scanUser(row pgx.Row) (User, error) { var u User var t time.Time err := row.Scan(&u.ID, &u.Username, utf8String{&u.DisplayName}, &t) u.CreatedAt = stamp(t) return u, dbError(err) } func (a *App) user(ctx context.Context, id string) (User, error) { return scanUser(a.db.QueryRow(ctx, "SELECT id::text,username,display_name,created_at FROM users WHERE id=$1", id)) } func (a *App) createChat(ctx context.Context, title string, ids []string) (Chat, error) { c := Chat{ID: uuid(), Title: title, MemberIDs: ids} var t time.Time tx, err := a.db.Begin(ctx) if err != nil { return c, unavailable() } defer tx.Rollback(ctx) err = tx.QueryRow(ctx, "INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at", c.ID, []byte(title)).Scan(&t) if err != nil { return c, dbError(err) } // FK failure on any participant rolls back the chat and earlier participants. for _, id := range ids { if _, err = tx.Exec(ctx, "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", c.ID, id); err != nil { return c, dbError(err) } } if err = tx.Commit(ctx); err != nil { return c, unavailable() } c.CreatedAt = stamp(t) return c, nil } func (a *App) chat(ctx context.Context, id, user string) (Chat, error) { c := Chat{} var t time.Time err := a.db.QueryRow(ctx, `SELECT c.id::text,c.title,c.created_at, ARRAY(SELECT user_id::text FROM chat_members WHERE chat_id=c.id ORDER BY user_id) FROM chats c WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$2)`, id, user).Scan(&c.ID, utf8String{&c.Title}, &t, &c.MemberIDs) c.CreatedAt = stamp(t) return c, dbError(err) } func boundary(c cursor) (time.Time, string, error) { if c.ID == "" { return time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC), "00000000-0000-0000-0000-000000000000", nil } t, err := time.Parse(time.RFC3339Nano, c.Time) if err != nil { return t, "", invalid() } id, err := normalizeID(c.ID) return t, id, err } func (a *App) history(ctx context.Context, id string, limit int, c cursor, scope string) (Page[Message], error) { result := Page[Message]{Items: []Message{}} t, last, err := boundary(c) if err != nil { return result, err } rows, err := a.db.Query(ctx, `SELECT id::text,chat_id::text,sender_id::text,text,created_at,ARRAY(SELECT unnest(attachment_ids)::text) FROM messages WHERE chat_id=$1 AND (created_at,id)>($2,$3) ORDER BY messages.created_at,messages.id LIMIT $4`, id, t, last, limit+1) if err != nil { return result, unavailable() } defer rows.Close() for rows.Next() { var m Message var created time.Time if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, utf8String{&m.Text}, &created, &m.AttachmentIDs); err != nil { return result, unavailable() } m.CreatedAt = stamp(created) result.Items = append(result.Items, m) } if rows.Err() != nil { return result, unavailable() } if len(result.Items) > limit { result.Items = result.Items[:limit] m := result.Items[limit-1] next := a.encodeCursor(scope, m.CreatedAt, m.ID) result.NextCursor = &next } return result, nil } func (a *App) listChats(ctx context.Context, user string, limit int, c cursor, scope string) (Page[Chat], error) { result := Page[Chat]{Items: []Chat{}} t, last, err := boundary(c) if err != nil { return result, err } rows, err := a.db.Query(ctx, `SELECT c.id::text,c.title,c.created_at, ARRAY(SELECT user_id::text FROM chat_members WHERE chat_id=c.id ORDER BY user_id) FROM chats c JOIN chat_members own ON own.chat_id=c.id AND own.user_id=$1 WHERE (c.created_at,c.id)>($2,$3) ORDER BY c.created_at,c.id LIMIT $4`, user, t, last, limit+1) if err != nil { return result, unavailable() } defer rows.Close() for rows.Next() { var chat Chat var created time.Time if err = rows.Scan(&chat.ID, utf8String{&chat.Title}, &created, &chat.MemberIDs); err != nil { return result, unavailable() } chat.CreatedAt = stamp(created) result.Items = append(result.Items, chat) } if rows.Err() != nil { return result, unavailable() } if len(result.Items) > limit { result.Items = result.Items[:limit] v := result.Items[limit-1] next := a.encodeCursor(scope, v.CreatedAt, v.ID) result.NextCursor = &next } return result, nil }