Files
2026-06-06 18:52:20 +03:00

95 lines
2.6 KiB
Go

package postgres
import (
"context"
"database/sql"
"errors"
"github.com/google/uuid"
"m8sh.su/d/jules/database"
)
type Users struct {
conn *sql.DB
}
func (u *Users) Create(ctx context.Context, user *database.User) error {
_, err := u.conn.ExecContext(ctx, `
INSERT INTO users (
id, preferred_chat, language, timezone,
llm_count, search_count, notification_count,
count_updated_at, bind_code, contact_code, role
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
`, user.ID, user.PreferredChat, user.Language, user.Timezone,
user.LLMCount, user.SearchCount, user.NotificationCount,
user.CountUpdatedAt, user.BindCode, user.ContactCode, user.Role)
return err
}
func (u *Users) Get(ctx context.Context, key uuid.UUID, lookup database.UserLookup) (*database.User, error) {
var column string
switch lookup {
case database.UserLookupByID:
column = "id"
case database.UserLookupByBindCode:
column = "bind_code"
case database.UserLookupByContactCode:
column = "contact_code"
default:
return nil, errors.New("invalid lookup type")
}
var user database.User
err := u.conn.QueryRowContext(ctx, `
SELECT id, preferred_chat, language, timezone,
llm_count, search_count, notification_count,
count_updated_at, bind_code, contact_code, role
FROM users
WHERE `+column+` = $1
`, key).Scan(
&user.ID, &user.PreferredChat, &user.Language, &user.Timezone,
&user.LLMCount, &user.SearchCount, &user.NotificationCount,
&user.CountUpdatedAt, &user.BindCode, &user.ContactCode, &user.Role,
)
if errors.Is(err, sql.ErrNoRows) {
return nil, database.ErrNotFound
}
if err != nil {
return nil, err
}
return &user, nil
}
func (u *Users) Update(ctx context.Context, user *database.User) error {
result, err := u.conn.ExecContext(ctx, `
UPDATE users
SET preferred_chat = $1, language = $2, timezone = $3,
llm_count = $4, search_count = $5, notification_count = $6,
count_updated_at = $7, bind_code = $8, contact_code = $9, role = $10
WHERE id = $11
`, user.PreferredChat, user.Language, user.Timezone,
user.LLMCount, user.SearchCount, user.NotificationCount,
user.CountUpdatedAt, user.BindCode, user.ContactCode, user.Role, user.ID)
if err != nil {
return err
}
rows, _ := result.RowsAffected()
if rows == 0 {
return database.ErrNotFound
}
return nil
}
func (u *Users) Delete(ctx context.Context, id uuid.UUID) error {
result, err := u.conn.ExecContext(ctx, `DELETE FROM users WHERE id = $1`, id)
if err != nil {
return err
}
rows, _ := result.RowsAffected()
if rows == 0 {
return database.ErrNotFound
}
return nil
}