78 lines
1.9 KiB
Go
78 lines
1.9 KiB
Go
package org
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
var ErrNoRows = pgx.ErrNoRows
|
|
|
|
type Repository struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewRepository(pool *pgxpool.Pool) *Repository {
|
|
return &Repository{pool: pool}
|
|
}
|
|
|
|
func (r *Repository) Create(ctx context.Context, org *Organization) error {
|
|
org.ID = uuid.New().String()
|
|
now := time.Now().UTC()
|
|
org.CreatedAt = now
|
|
org.UpdatedAt = now
|
|
_, err := r.pool.Exec(ctx,
|
|
`INSERT INTO organizations (id, name, slug, created_at, updated_at) VALUES ($1, $2, $3, $4, $5)`,
|
|
org.ID, org.Name, org.Slug, org.CreatedAt, org.UpdatedAt,
|
|
)
|
|
return err
|
|
}
|
|
|
|
func (r *Repository) FindByID(ctx context.Context, id string) (*Organization, error) {
|
|
var org Organization
|
|
err := r.pool.QueryRow(ctx,
|
|
`SELECT id, name, slug, created_at, updated_at FROM organizations WHERE id = $1`, id,
|
|
).Scan(&org.ID, &org.Name, &org.Slug, &org.CreatedAt, &org.UpdatedAt)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &org, nil
|
|
}
|
|
|
|
func (r *Repository) FindAll(ctx context.Context) ([]Organization, error) {
|
|
rows, err := r.pool.Query(ctx,
|
|
`SELECT id, name, slug, created_at, updated_at FROM organizations ORDER BY created_at DESC`,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var orgs []Organization
|
|
for rows.Next() {
|
|
var org Organization
|
|
if err := rows.Scan(&org.ID, &org.Name, &org.Slug, &org.CreatedAt, &org.UpdatedAt); err != nil {
|
|
return nil, err
|
|
}
|
|
orgs = append(orgs, org)
|
|
}
|
|
return orgs, rows.Err()
|
|
}
|
|
|
|
func (r *Repository) Update(ctx context.Context, org *Organization) error {
|
|
org.UpdatedAt = time.Now().UTC()
|
|
_, err := r.pool.Exec(ctx,
|
|
`UPDATE organizations SET name = $1, updated_at = $2 WHERE id = $3`,
|
|
org.Name, org.UpdatedAt, org.ID,
|
|
)
|
|
return err
|
|
}
|
|
|
|
func (r *Repository) Delete(ctx context.Context, id string) error {
|
|
_, err := r.pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, id)
|
|
return err
|
|
}
|