63 lines
1.2 KiB
Go
63 lines
1.2 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
|
|
"github.com/d1nch8g/jules/database"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type Facts struct {
|
|
conn *sql.DB
|
|
}
|
|
|
|
func (f *Facts) Add(ctx context.Context, userID uuid.UUID, value string) error {
|
|
_, err := f.conn.ExecContext(ctx, `
|
|
INSERT INTO facts (user_id, value)
|
|
VALUES ($1, $2)
|
|
ON CONFLICT (user_id, value) DO NOTHING
|
|
`, userID, value)
|
|
return err
|
|
}
|
|
|
|
func (f *Facts) List(ctx context.Context, userID uuid.UUID) ([]database.Fact, error) {
|
|
rows, err := f.conn.QueryContext(ctx, `
|
|
SELECT user_id, value
|
|
FROM facts
|
|
WHERE user_id = $1
|
|
`, userID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var facts []database.Fact
|
|
for rows.Next() {
|
|
var fact database.Fact
|
|
if err := rows.Scan(&fact.UserID, &fact.Value); err != nil {
|
|
return nil, err
|
|
}
|
|
facts = append(facts, fact)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return facts, nil
|
|
}
|
|
|
|
func (f *Facts) Delete(ctx context.Context, userID uuid.UUID, value string) error {
|
|
result, err := f.conn.ExecContext(ctx, `
|
|
DELETE FROM facts
|
|
WHERE user_id = $1 AND value = $2
|
|
`, userID, value)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
rows, _ := result.RowsAffected()
|
|
if rows == 0 {
|
|
return database.ErrNotFound
|
|
}
|
|
return nil
|
|
}
|