From e1f2cb01e0093e68771acc6b28e88c50602ade84 Mon Sep 17 00:00:00 2001 From: kk10 Date: Sun, 4 Oct 2026 21:25:07 +0300 Subject: [PATCH] feat(db): add schema, sqlc queries and generated code --- Dockerfile.migrate | 2 +- {migrations => db/migrations}/00001_init.sql | 0 db/queries/chats.sql | 62 +++++++ db/queries/messages.sql | 31 ++++ db/queries/sessions.sql | 24 +++ db/queries/users.sql | 21 +++ internal/db/chats.sql.go | 183 +++++++++++++++++++ internal/db/db.go | 42 ++--- internal/db/messages.sql.go | 110 +++++++++++ internal/db/models.go | 45 +++++ internal/db/querier.go | 30 +++ internal/db/sessions.sql.go | 85 +++++++++ internal/db/users.sql.go | 101 ++++++++++ sqlc.yaml | 31 ++++ 14 files changed, 744 insertions(+), 23 deletions(-) rename {migrations => db/migrations}/00001_init.sql (100%) create mode 100644 db/queries/chats.sql create mode 100644 db/queries/messages.sql create mode 100644 db/queries/sessions.sql create mode 100644 db/queries/users.sql create mode 100644 internal/db/chats.sql.go create mode 100644 internal/db/messages.sql.go create mode 100644 internal/db/models.go create mode 100644 internal/db/querier.go create mode 100644 internal/db/sessions.sql.go create mode 100644 internal/db/users.sql.go create mode 100644 sqlc.yaml diff --git a/Dockerfile.migrate b/Dockerfile.migrate index 8bcb4171..48e8f7ae 100644 --- a/Dockerfile.migrate +++ b/Dockerfile.migrate @@ -4,5 +4,5 @@ RUN go install github.com/pressly/goose/v3/cmd/goose@v3.28.0 FROM alpine:3.24 COPY --from=build /go/bin/goose /usr/local/bin/goose -COPY migrations /migrations +COPY db/migrations /migrations ENTRYPOINT ["sh", "-c", "goose -dir /migrations postgres \"$(cat /run/secrets/database_url)\" up"] diff --git a/migrations/00001_init.sql b/db/migrations/00001_init.sql similarity index 100% rename from migrations/00001_init.sql rename to db/migrations/00001_init.sql diff --git a/db/queries/chats.sql b/db/queries/chats.sql new file mode 100644 index 00000000..5609c446 --- /dev/null +++ b/db/queries/chats.sql @@ -0,0 +1,62 @@ +-- name: CreateChat :one +INSERT INTO chats ( + id, + title +) VALUES ( + sqlc.arg(id), + sqlc.arg(title) +) +RETURNING *; + +-- name: AddChatMembers :exec +INSERT INTO chat_members ( + chat_id, + user_id +) +SELECT + sqlc.arg(chat_id)::uuid, + unnest(sqlc.arg(user_ids)::uuid[]); + +-- name: IsChatMember :one +SELECT EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = sqlc.arg(chat_id) + AND user_id = sqlc.arg(user_id) +); + +-- name: GetChat :one +SELECT + c.*, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +WHERE c.id = sqlc.arg(id) + AND EXISTS ( + SELECT 1 FROM chat_members m + WHERE m.chat_id = c.id + AND m.user_id = sqlc.arg(user_id) + ); + +-- name: ListChats :many +SELECT + c.*, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +JOIN chat_members m ON m.chat_id = c.id +WHERE m.user_id = sqlc.arg(user_id) + AND ( + sqlc.narg(after_created_at)::timestamptz IS NULL + OR (c.created_at, c.id) > ( + sqlc.narg(after_created_at)::timestamptz, + sqlc.narg(after_id)::uuid + ) + ) +ORDER BY c.created_at, c.id +LIMIT sqlc.arg(lim); diff --git a/db/queries/messages.sql b/db/queries/messages.sql new file mode 100644 index 00000000..adb03546 --- /dev/null +++ b/db/queries/messages.sql @@ -0,0 +1,31 @@ +-- name: CreateMessage :one +INSERT INTO messages ( + id, + chat_id, + sender_id, + text +) +SELECT + sqlc.arg(id)::uuid, + sqlc.arg(chat_id)::uuid, + sqlc.arg(sender_id)::uuid, + sqlc.arg(text)::text +WHERE EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = sqlc.arg(chat_id) + AND user_id = sqlc.arg(sender_id) +) +RETURNING *; + +-- name: ListMessages :many +SELECT * FROM messages +WHERE chat_id = sqlc.arg(chat_id) + AND ( + sqlc.narg(after_created_at)::timestamptz IS NULL + OR (created_at, id) > ( + sqlc.narg(after_created_at)::timestamptz, + sqlc.narg(after_id)::uuid + ) + ) +ORDER BY created_at, id +LIMIT sqlc.arg(lim); diff --git a/db/queries/sessions.sql b/db/queries/sessions.sql new file mode 100644 index 00000000..64a0bfa4 --- /dev/null +++ b/db/queries/sessions.sql @@ -0,0 +1,24 @@ +-- name: CreateSession :exec +INSERT INTO sessions ( + token_hash, + user_id, + expires_at +) VALUES ( + sqlc.arg(token_hash), + sqlc.arg(user_id), + sqlc.arg(expires_at) +); + +-- name: GetSessionUser :one +SELECT u.id, u.username, u.display_name, u.created_at FROM sessions s +JOIN users u ON u.id = s.user_id +WHERE s.token_hash = sqlc.arg(token_hash) + AND s.expires_at > now(); + +-- name: DeleteSession :exec +DELETE FROM sessions +WHERE token_hash = sqlc.arg(token_hash); + +-- name: DeleteExpiredSessions :execrows +DELETE FROM sessions +WHERE expires_at <= now(); diff --git a/db/queries/users.sql b/db/queries/users.sql new file mode 100644 index 00000000..d6e9c030 --- /dev/null +++ b/db/queries/users.sql @@ -0,0 +1,21 @@ +-- name: CreateUser :one +INSERT INTO users ( + id, + username, + display_name, + password_hash +) VALUES ( + sqlc.arg(id), + sqlc.arg(username), + sqlc.arg(display_name), + sqlc.arg(password_hash) +) +RETURNING id, username, display_name, created_at; + +-- name: GetUser :one +SELECT id, username, display_name, created_at FROM users +WHERE id = sqlc.arg(id); + +-- name: GetUserByUsername :one +SELECT * FROM users +WHERE username = sqlc.arg(username); diff --git a/internal/db/chats.sql.go b/internal/db/chats.sql.go new file mode 100644 index 00000000..cf3dc388 --- /dev/null +++ b/internal/db/chats.sql.go @@ -0,0 +1,183 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: chats.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const addChatMembers = `-- name: AddChatMembers :exec +INSERT INTO chat_members ( + chat_id, + user_id +) +SELECT + $1::uuid, + unnest($2::uuid[]) +` + +type AddChatMembersParams struct { + ChatID uuid.UUID + UserIds []uuid.UUID +} + +func (q *Queries) AddChatMembers(ctx context.Context, arg AddChatMembersParams) error { + _, err := q.db.Exec(ctx, addChatMembers, arg.ChatID, arg.UserIds) + return err +} + +const createChat = `-- name: CreateChat :one +INSERT INTO chats ( + id, + title +) VALUES ( + $1, + $2 +) +RETURNING id, title, created_at +` + +type CreateChatParams struct { + ID uuid.UUID + Title string +} + +func (q *Queries) CreateChat(ctx context.Context, arg CreateChatParams) (Chat, error) { + row := q.db.QueryRow(ctx, createChat, arg.ID, arg.Title) + var i Chat + err := row.Scan(&i.ID, &i.Title, &i.CreatedAt) + return i, err +} + +const getChat = `-- name: GetChat :one +SELECT + c.id, c.title, c.created_at, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +WHERE c.id = $1 + AND EXISTS ( + SELECT 1 FROM chat_members m + WHERE m.chat_id = c.id + AND m.user_id = $2 + ) +` + +type GetChatParams struct { + ID uuid.UUID + UserID uuid.UUID +} + +type GetChatRow struct { + ID uuid.UUID + Title string + CreatedAt time.Time + MemberIds []uuid.UUID +} + +func (q *Queries) GetChat(ctx context.Context, arg GetChatParams) (GetChatRow, error) { + row := q.db.QueryRow(ctx, getChat, arg.ID, arg.UserID) + var i GetChatRow + err := row.Scan( + &i.ID, + &i.Title, + &i.CreatedAt, + &i.MemberIds, + ) + return i, err +} + +const isChatMember = `-- name: IsChatMember :one +SELECT EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = $1 + AND user_id = $2 +) +` + +type IsChatMemberParams struct { + ChatID uuid.UUID + UserID uuid.UUID +} + +func (q *Queries) IsChatMember(ctx context.Context, arg IsChatMemberParams) (bool, error) { + row := q.db.QueryRow(ctx, isChatMember, arg.ChatID, arg.UserID) + var exists bool + err := row.Scan(&exists) + return exists, err +} + +const listChats = `-- name: ListChats :many +SELECT + c.id, c.title, c.created_at, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +JOIN chat_members m ON m.chat_id = c.id +WHERE m.user_id = $1 + AND ( + $2::timestamptz IS NULL + OR (c.created_at, c.id) > ( + $2::timestamptz, + $3::uuid + ) + ) +ORDER BY c.created_at, c.id +LIMIT $4 +` + +type ListChatsParams struct { + UserID uuid.UUID + AfterCreatedAt *time.Time + AfterID *uuid.UUID + Lim int32 +} + +type ListChatsRow struct { + ID uuid.UUID + Title string + CreatedAt time.Time + MemberIds []uuid.UUID +} + +func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error) { + rows, err := q.db.Query(ctx, listChats, + arg.UserID, + arg.AfterCreatedAt, + arg.AfterID, + arg.Lim, + ) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListChatsRow{} + for rows.Next() { + var i ListChatsRow + if err := rows.Scan( + &i.ID, + &i.Title, + &i.CreatedAt, + &i.MemberIds, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/db/db.go b/internal/db/db.go index 64aabc9d..468d1fa3 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -1,34 +1,32 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + package db import ( "context" - "fmt" - "time" - "github.com/jackc/pgx/v5/pgxpool" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" ) -func New(ctx context.Context, url string) (*pgxpool.Pool, error) { - cfg, err := pgxpool.ParseConfig(url) - if err != nil { - return nil, fmt.Errorf("parse database url: %w", err) - } +type DBTX interface { + Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error) + Query(context.Context, string, ...interface{}) (pgx.Rows, error) + QueryRow(context.Context, string, ...interface{}) pgx.Row +} - cfg.MaxConns = 10 - cfg.ConnConfig.ConnectTimeout = 5 * time.Second - cfg.ConnConfig.RuntimeParams["statement_timeout"] = "5000" +func New(db DBTX) *Queries { + return &Queries{db: db} +} - pool, err := pgxpool.NewWithConfig(ctx, cfg) - if err != nil { - return nil, fmt.Errorf("create pool: %w", err) - } +type Queries struct { + db DBTX +} - pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second) - defer cancel() - if err := pool.Ping(pingCtx); err != nil { - pool.Close() - return nil, fmt.Errorf("ping database: %w", err) +func (q *Queries) WithTx(tx pgx.Tx) *Queries { + return &Queries{ + db: tx, } - - return pool, nil } diff --git a/internal/db/messages.sql.go b/internal/db/messages.sql.go new file mode 100644 index 00000000..babd80ad --- /dev/null +++ b/internal/db/messages.sql.go @@ -0,0 +1,110 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: messages.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const createMessage = `-- name: CreateMessage :one +INSERT INTO messages ( + id, + chat_id, + sender_id, + text +) +SELECT + $1::uuid, + $2::uuid, + $3::uuid, + $4::text +WHERE EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = $2 + AND user_id = $3 +) +RETURNING id, chat_id, sender_id, text, created_at +` + +type CreateMessageParams struct { + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string +} + +func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) { + row := q.db.QueryRow(ctx, createMessage, + arg.ID, + arg.ChatID, + arg.SenderID, + arg.Text, + ) + var i Message + err := row.Scan( + &i.ID, + &i.ChatID, + &i.SenderID, + &i.Text, + &i.CreatedAt, + ) + return i, err +} + +const listMessages = `-- name: ListMessages :many +SELECT id, chat_id, sender_id, text, created_at FROM messages +WHERE chat_id = $1 + AND ( + $2::timestamptz IS NULL + OR (created_at, id) > ( + $2::timestamptz, + $3::uuid + ) + ) +ORDER BY created_at, id +LIMIT $4 +` + +type ListMessagesParams struct { + ChatID uuid.UUID + AfterCreatedAt *time.Time + AfterID *uuid.UUID + Lim int32 +} + +func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]Message, error) { + rows, err := q.db.Query(ctx, listMessages, + arg.ChatID, + arg.AfterCreatedAt, + arg.AfterID, + arg.Lim, + ) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Message{} + for rows.Next() { + var i Message + if err := rows.Scan( + &i.ID, + &i.ChatID, + &i.SenderID, + &i.Text, + &i.CreatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/db/models.go b/internal/db/models.go new file mode 100644 index 00000000..c9a085e4 --- /dev/null +++ b/internal/db/models.go @@ -0,0 +1,45 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package db + +import ( + "time" + + "github.com/google/uuid" +) + +type Chat struct { + ID uuid.UUID + Title string + CreatedAt time.Time +} + +type ChatMember struct { + ChatID uuid.UUID + UserID uuid.UUID +} + +type Message struct { + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string + CreatedAt time.Time +} + +type Session struct { + TokenHash string + UserID uuid.UUID + CreatedAt time.Time + ExpiresAt time.Time +} + +type User struct { + ID uuid.UUID + Username string + DisplayName string + PasswordHash string + CreatedAt time.Time +} diff --git a/internal/db/querier.go b/internal/db/querier.go new file mode 100644 index 00000000..0d5993a2 --- /dev/null +++ b/internal/db/querier.go @@ -0,0 +1,30 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package db + +import ( + "context" + + "github.com/google/uuid" +) + +type Querier interface { + AddChatMembers(ctx context.Context, arg AddChatMembersParams) error + CreateChat(ctx context.Context, arg CreateChatParams) (Chat, error) + CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) + CreateSession(ctx context.Context, arg CreateSessionParams) error + CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) + DeleteExpiredSessions(ctx context.Context) (int64, error) + DeleteSession(ctx context.Context, tokenHash string) error + GetChat(ctx context.Context, arg GetChatParams) (GetChatRow, error) + GetSessionUser(ctx context.Context, tokenHash string) (GetSessionUserRow, error) + GetUser(ctx context.Context, id uuid.UUID) (GetUserRow, error) + GetUserByUsername(ctx context.Context, username string) (User, error) + IsChatMember(ctx context.Context, arg IsChatMemberParams) (bool, error) + ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error) + ListMessages(ctx context.Context, arg ListMessagesParams) ([]Message, error) +} + +var _ Querier = (*Queries)(nil) diff --git a/internal/db/sessions.sql.go b/internal/db/sessions.sql.go new file mode 100644 index 00000000..5567e1be --- /dev/null +++ b/internal/db/sessions.sql.go @@ -0,0 +1,85 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: sessions.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const createSession = `-- name: CreateSession :exec +INSERT INTO sessions ( + token_hash, + user_id, + expires_at +) VALUES ( + $1, + $2, + $3 +) +` + +type CreateSessionParams struct { + TokenHash string + UserID uuid.UUID + ExpiresAt time.Time +} + +func (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) error { + _, err := q.db.Exec(ctx, createSession, arg.TokenHash, arg.UserID, arg.ExpiresAt) + return err +} + +const deleteExpiredSessions = `-- name: DeleteExpiredSessions :execrows +DELETE FROM sessions +WHERE expires_at <= now() +` + +func (q *Queries) DeleteExpiredSessions(ctx context.Context) (int64, error) { + result, err := q.db.Exec(ctx, deleteExpiredSessions) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const deleteSession = `-- name: DeleteSession :exec +DELETE FROM sessions +WHERE token_hash = $1 +` + +func (q *Queries) DeleteSession(ctx context.Context, tokenHash string) error { + _, err := q.db.Exec(ctx, deleteSession, tokenHash) + return err +} + +const getSessionUser = `-- name: GetSessionUser :one +SELECT u.id, u.username, u.display_name, u.created_at FROM sessions s +JOIN users u ON u.id = s.user_id +WHERE s.token_hash = $1 + AND s.expires_at > now() +` + +type GetSessionUserRow struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} + +func (q *Queries) GetSessionUser(ctx context.Context, tokenHash string) (GetSessionUserRow, error) { + row := q.db.QueryRow(ctx, getSessionUser, tokenHash) + var i GetSessionUserRow + err := row.Scan( + &i.ID, + &i.Username, + &i.DisplayName, + &i.CreatedAt, + ) + return i, err +} diff --git a/internal/db/users.sql.go b/internal/db/users.sql.go new file mode 100644 index 00000000..ec8a97f9 --- /dev/null +++ b/internal/db/users.sql.go @@ -0,0 +1,101 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: users.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const createUser = `-- name: CreateUser :one +INSERT INTO users ( + id, + username, + display_name, + password_hash +) VALUES ( + $1, + $2, + $3, + $4 +) +RETURNING id, username, display_name, created_at +` + +type CreateUserParams struct { + ID uuid.UUID + Username string + DisplayName string + PasswordHash string +} + +type CreateUserRow struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} + +func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) { + row := q.db.QueryRow(ctx, createUser, + arg.ID, + arg.Username, + arg.DisplayName, + arg.PasswordHash, + ) + var i CreateUserRow + err := row.Scan( + &i.ID, + &i.Username, + &i.DisplayName, + &i.CreatedAt, + ) + return i, err +} + +const getUser = `-- name: GetUser :one +SELECT id, username, display_name, created_at FROM users +WHERE id = $1 +` + +type GetUserRow struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} + +func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (GetUserRow, error) { + row := q.db.QueryRow(ctx, getUser, id) + var i GetUserRow + err := row.Scan( + &i.ID, + &i.Username, + &i.DisplayName, + &i.CreatedAt, + ) + return i, err +} + +const getUserByUsername = `-- name: GetUserByUsername :one +SELECT id, username, display_name, password_hash, created_at FROM users +WHERE username = $1 +` + +func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User, error) { + row := q.db.QueryRow(ctx, getUserByUsername, username) + var i User + err := row.Scan( + &i.ID, + &i.Username, + &i.DisplayName, + &i.PasswordHash, + &i.CreatedAt, + ) + return i, err +} diff --git a/sqlc.yaml b/sqlc.yaml new file mode 100644 index 00000000..85494b59 --- /dev/null +++ b/sqlc.yaml @@ -0,0 +1,31 @@ +version: "2" +sql: + - engine: "postgresql" + queries: "db/queries" + schema: "db/migrations" + gen: + go: + package: "db" + out: "internal/db" + sql_package: "pgx/v5" + emit_interface: true + emit_empty_slices: true + emit_pointers_for_null_types: true + overrides: + - db_type: "uuid" + go_type: "github.com/google/uuid.UUID" + - db_type: "uuid" + nullable: true + go_type: + import: "github.com/google/uuid" + type: "UUID" + pointer: true + + - db_type: "timestamptz" + go_type: "time.Time" + - db_type: "timestamptz" + nullable: true + go_type: + import: "time" + type: "Time" + pointer: true