Files
Control-plane/internal/org/repository.go
T
Mephimeow 2da484d781
ci / build (push) Successful in 2m58s
ci / build (pull_request) Successful in 2m47s
refactor: migrate from raw pgx to GORM, unify ErrNoRows, cleanup auth
2026-06-14 16:41:33 +00:00

72 lines
1.8 KiB
Go

package org
import (
"context"
"time"
"github.com/google/uuid"
"gorm.io/gorm"
)
type OrgRepository interface {
Create(ctx context.Context, org *Organization) error
FindByID(ctx context.Context, id string) (*Organization, error)
FindAll(ctx context.Context, limit, offset int) ([]Organization, error)
Count(ctx context.Context) (int, error)
Update(ctx context.Context, org *Organization) error
Delete(ctx context.Context, id string) (bool, error)
}
type Repository struct {
db *gorm.DB
}
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
}
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
return r.db.WithContext(ctx).Create(org).Error
}
func (r *Repository) FindByID(ctx context.Context, id string) (*Organization, error) {
var org Organization
err := r.db.WithContext(ctx).Where("id = ?", id).First(&org).Error
if err != nil {
return nil, err
}
return &org, nil
}
func (r *Repository) FindAll(ctx context.Context, limit, offset int) ([]Organization, error) {
var orgs []Organization
err := r.db.WithContext(ctx).
Order("created_at DESC").
Limit(limit).
Offset(offset).
Find(&orgs).Error
return orgs, err
}
func (r *Repository) Count(ctx context.Context) (int, error) {
var total int64
err := r.db.WithContext(ctx).Model(&Organization{}).Count(&total).Error
return int(total), err
}
func (r *Repository) Update(ctx context.Context, org *Organization) error {
return r.db.WithContext(ctx).Model(org).Update("name", org.Name).Error
}
func (r *Repository) Delete(ctx context.Context, id string) (bool, error) {
result := r.db.WithContext(ctx).Delete(&Organization{}, "id = ?", id)
if result.Error != nil {
return false, result.Error
}
return result.RowsAffected > 0, nil
}