added some govno to postgres

This commit is contained in:
Mephimeow
2026-06-13 18:31:22 +00:00
committed by zero@thinky
parent 56ab583223
commit 57ce3dea5f
20 changed files with 2174 additions and 163 deletions
+16 -29
View File
@@ -17,30 +17,6 @@ func NewRepository(pool *pgxpool.Pool) *Repository {
return &Repository{pool: pool}
}
func (r *Repository) Migrate(ctx context.Context) error {
schema := `
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY,
username TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS refresh_tokens (
id UUID PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires_at ON refresh_tokens(expires_at);
`
_, err := r.pool.Exec(ctx, schema)
return err
}
func (r *Repository) CreateUser(ctx context.Context, user *User) error {
user.ID = uuid.New().String()
user.CreatedAt = time.Now().UTC()
@@ -86,7 +62,7 @@ func (r *Repository) CreateRefreshToken(ctx context.Context, doc *RefreshTokenDo
func (r *Repository) FindRefreshTokenByHash(ctx context.Context, hash string) (*RefreshTokenDoc, error) {
var doc RefreshTokenDoc
err := r.pool.QueryRow(ctx,
`SELECT id, user_id, token_hash, expires_at, created_at FROM refresh_tokens WHERE token_hash = $1`, hash,
`SELECT id, user_id, token_hash, expires_at, created_at FROM refresh_tokens WHERE token_hash = $1 AND expires_at > NOW()`, hash,
).Scan(&doc.ID, &doc.UserID, &doc.TokenHash, &doc.ExpiresAt, &doc.CreatedAt)
if err != nil {
return nil, err
@@ -99,6 +75,21 @@ func (r *Repository) DeleteRefreshToken(ctx context.Context, id string) error {
return err
}
func (r *Repository) UpdateUserUsername(ctx context.Context, id, username string) error {
_, err := r.pool.Exec(ctx, `UPDATE users SET username = $1 WHERE id = $2`, username, id)
return err
}
func (r *Repository) UpdateUserPassword(ctx context.Context, id, passwordHash string) error {
_, err := r.pool.Exec(ctx, `UPDATE users SET password_hash = $1 WHERE id = $2`, passwordHash, id)
return err
}
func (r *Repository) DeleteExpiredRefreshTokens(ctx context.Context) error {
_, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE expires_at <= NOW()`)
return err
}
func (r *Repository) DeleteRefreshTokenByHash(ctx context.Context, hash string) (bool, error) {
tag, err := r.pool.Exec(ctx, `DELETE FROM refresh_tokens WHERE token_hash = $1`, hash)
if err != nil {
@@ -107,8 +98,4 @@ func (r *Repository) DeleteRefreshTokenByHash(ctx context.Context, hash string)
return tag.RowsAffected() > 0, nil
}
func (r *Repository) EnsureIndexes(ctx context.Context) error {
return r.Migrate(ctx)
}
var ErrNoRows = pgx.ErrNoRows