tabel user

This commit is contained in:
Yovan
2026-10-03 19:23:22 +07:00
parent 662aaec022
commit 14283c2b61
5 changed files with 75 additions and 8 deletions
+25
View File
@@ -50,6 +50,31 @@ func (s *SnippetStore) GetByID(ctx context.Context, id string) (*models.Snippet,
return &sn, nil
}
func (s *SnippetStore) GetByUserID(ctx context.Context, userID string) ([]*models.Snippet, error) {
s.mu.Lock()
defer s.mu.Unlock()
query := `SELECT id, title, content, user_id FROM snippets WHERE user_id = $1`
rows, err := s.conn.Query(ctx, query, userID)
if err != nil {
return nil, err
}
defer rows.Close()
snippets := make([]*models.Snippet, 0)
for rows.Next() {
var sn models.Snippet
if err := rows.Scan(&sn.ID, &sn.Title, &sn.Content, &sn.UserID); err != nil {
return nil, err
}
snippets = append(snippets, &sn)
}
if err := rows.Err(); err != nil {
return nil, err
}
return snippets, nil
}
func (s *SnippetStore) GetAll(ctx context.Context) ([]*models.Snippet, error) {
s.mu.Lock()
defer s.mu.Unlock()
+13 -1
View File
@@ -2,13 +2,18 @@ package store
import (
"context"
"errors"
"sync"
"5803025020/w04/internal/models"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// ErrUsernameTaken dikembalikan saat Create() gagal karena username sudah dipakai (unique constraint).
var ErrUsernameTaken = errors.New("username already exists")
type UserStore struct {
conn *pgx.Conn
mu *sync.Mutex
@@ -34,7 +39,14 @@ func (s *UserStore) Create(ctx context.Context, user *models.User) error {
query := `INSERT INTO users (id, username, password_hash) VALUES ($1, $2, $3)`
_, err := s.conn.Exec(ctx, query, user.ID, user.Username, user.PasswordHash)
return err
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return ErrUsernameTaken
}
return err
}
return nil
}
func (s *UserStore) GetByUsername(ctx context.Context, username string) (*models.User, error) {