Files
w04_29_FarrelRevalino_database/internal/store/snippet_store.go
T
2026-09-28 18:27:16 +07:00

87 lines
1.9 KiB
Go

package store
import (
"context"
"sync"
"5803025029/w04/internal/models"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
type SnippetStore struct {
conn *pgx.Conn
mu *sync.Mutex
}
func NewSnippetStore(conn *pgx.Conn, optMu ...*sync.Mutex) *SnippetStore {
var mu *sync.Mutex
if len(optMu) > 0 && optMu[0] != nil {
mu = optMu[0]
} else {
mu = &sync.Mutex{}
}
return &SnippetStore{conn: conn, mu: mu}
}
func (s *SnippetStore) Create(ctx context.Context, snippet *models.Snippet) error {
s.mu.Lock()
defer s.mu.Unlock()
if snippet.ID == "" {
snippet.ID = uuid.New().String()
}
query := `INSERT INTO snippets (id, title, content, user_id) VALUES ($1, $2, $3, $4)`
_, err := s.conn.Exec(ctx, query, snippet.ID, snippet.Title, snippet.Content, snippet.UserID)
return err
}
func (s *SnippetStore) GetByID(ctx context.Context, id string) (*models.Snippet, error) {
s.mu.Lock()
defer s.mu.Unlock()
var sn models.Snippet
query := `SELECT id, title, content, user_id FROM snippets WHERE id = $1`
err := s.conn.QueryRow(ctx, query, id).Scan(&sn.ID, &sn.Title, &sn.Content, &sn.UserID)
if err != nil {
return nil, err
}
return &sn, nil
}
func (s *SnippetStore) GetAll(ctx context.Context) ([]*models.Snippet, error) {
s.mu.Lock()
defer s.mu.Unlock()
query := `SELECT id, title, content, user_id FROM snippets`
rows, err := s.conn.Query(ctx, query)
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) Delete(ctx context.Context, id string) error {
s.mu.Lock()
defer s.mu.Unlock()
query := `DELETE FROM snippets WHERE id = $1`
_, err := s.conn.Exec(ctx, query, id)
return err
}