99 lines
2.3 KiB
Go
99 lines
2.3 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"sync"
|
|
|
|
"5803025015/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 {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
return &sn, nil
|
|
}
|
|
|
|
// ListByOwner returns only the snippets belonging to ownerID.
|
|
// Return value is always non-nil (empty slice when none).
|
|
func (s *SnippetStore) ListByOwner(ctx context.Context, ownerID 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, ownerID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
snippets := make([]*models.Snippet, 0) // non-nil!
|
|
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`
|
|
tag, err := s.conn.Exec(ctx, query, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|