added some govno to postgres

This commit is contained in:
Mephimeow
2026-06-13 18:31:22 +00:00
committed by zero@thinky
parent 56ab583223
commit 57ce3dea5f
20 changed files with 2174 additions and 163 deletions
+157
View File
@@ -0,0 +1,157 @@
package org
import (
"errors"
"log"
"net/http"
"github.com/gin-gonic/gin"
)
type Handler struct {
service *Service
}
func NewHandler(service *Service) *Handler {
return &Handler{service: service}
}
// @Summary Create organization
// @Description Create a new organization
// @Tags organizations
// @Accept json
// @Produce json
// @Security Bearer
// @Param request body CreateOrgRequest true "Organization details"
// @Success 201 {object} OrgResponse
// @Failure 400 {object} ErrorResponse
// @Failure 409 {object} ErrorResponse
// @Router /api/organizations [post]
func (h *Handler) Create(c *gin.Context) {
var req CreateOrgRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
return
}
org, err := h.service.Create(c.Request.Context(), req)
if err != nil {
if errors.Is(err, ErrSlugExists) {
c.JSON(http.StatusConflict, ErrorResponse{Error: err.Error()})
return
}
log.Printf("create org error: %v", err)
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "internal server error"})
return
}
c.JSON(http.StatusCreated, OrgResponse{Organization: *org})
}
// @Summary Get organization by ID
// @Description Get organization details
// @Tags organizations
// @Accept json
// @Produce json
// @Security Bearer
// @Param id path string true "Organization ID"
// @Success 200 {object} OrgResponse
// @Failure 404 {object} ErrorResponse
// @Router /api/organizations/{id} [get]
func (h *Handler) GetByID(c *gin.Context) {
id := c.Param("id")
org, err := h.service.GetByID(c.Request.Context(), id)
if err != nil {
if errors.Is(err, ErrNotFound) {
c.JSON(http.StatusNotFound, ErrorResponse{Error: err.Error()})
return
}
log.Printf("get org error: %v", err)
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "internal server error"})
return
}
c.JSON(http.StatusOK, OrgResponse{Organization: *org})
}
// @Summary List organizations
// @Description Get all organizations
// @Tags organizations
// @Accept json
// @Produce json
// @Security Bearer
// @Success 200 {object} OrgListResponse
// @Failure 500 {object} ErrorResponse
// @Router /api/organizations [get]
func (h *Handler) List(c *gin.Context) {
resp, err := h.service.List(c.Request.Context())
if err != nil {
log.Printf("list orgs error: %v", err)
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "internal server error"})
return
}
c.JSON(http.StatusOK, resp)
}
// @Summary Update organization
// @Description Update organization name
// @Tags organizations
// @Accept json
// @Produce json
// @Security Bearer
// @Param id path string true "Organization ID"
// @Param request body UpdateOrgRequest true "New organization details"
// @Success 200 {object} OrgResponse
// @Failure 400 {object} ErrorResponse
// @Failure 404 {object} ErrorResponse
// @Router /api/organizations/{id} [put]
func (h *Handler) Update(c *gin.Context) {
id := c.Param("id")
var req UpdateOrgRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
return
}
org, err := h.service.Update(c.Request.Context(), id, req)
if err != nil {
if errors.Is(err, ErrNotFound) {
c.JSON(http.StatusNotFound, ErrorResponse{Error: err.Error()})
return
}
log.Printf("update org error: %v", err)
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "internal server error"})
return
}
c.JSON(http.StatusOK, OrgResponse{Organization: *org})
}
// @Summary Delete organization
// @Description Delete an organization
// @Tags organizations
// @Accept json
// @Produce json
// @Security Bearer
// @Param id path string true "Organization ID"
// @Success 200 {object} map[string]string
// @Failure 404 {object} ErrorResponse
// @Router /api/organizations/{id} [delete]
func (h *Handler) Delete(c *gin.Context) {
id := c.Param("id")
if err := h.service.Delete(c.Request.Context(), id); err != nil {
if errors.Is(err, ErrNotFound) {
c.JSON(http.StatusNotFound, ErrorResponse{Error: err.Error()})
return
}
log.Printf("delete org error: %v", err)
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "internal server error"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "organization deleted"})
}
+33
View File
@@ -0,0 +1,33 @@
package org
import "time"
type Organization struct {
ID string `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type CreateOrgRequest struct {
Name string `json:"name" binding:"required,min=2,max=100" example:"My Corp"`
Slug string `json:"slug" binding:"required,min=2,max=50" example:"my-corp"`
}
type UpdateOrgRequest struct {
Name string `json:"name" binding:"required,min=2,max=100" example:"My Corp Updated"`
}
type OrgResponse struct {
Organization Organization `json:"organization"`
}
type OrgListResponse struct {
Organizations []Organization `json:"organizations"`
Total int `json:"total"`
}
type ErrorResponse struct {
Error string `json:"error"`
}
+77
View File
@@ -0,0 +1,77 @@
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
}
+102
View File
@@ -0,0 +1,102 @@
package org
import (
"context"
"errors"
"fmt"
"strings"
)
var (
ErrNotFound = errors.New("organization not found")
ErrSlugExists = errors.New("slug already taken")
)
type Service struct {
repo *Repository
}
func NewService(repo *Repository) *Service {
return &Service{repo: repo}
}
func (s *Service) Create(ctx context.Context, req CreateOrgRequest) (*Organization, error) {
req.Slug = strings.ToLower(strings.TrimSpace(req.Slug))
org := &Organization{
Name: req.Name,
Slug: req.Slug,
}
if err := s.repo.Create(ctx, org); err != nil {
if isUniqueViolation(err) {
return nil, ErrSlugExists
}
return nil, fmt.Errorf("failed to create organization: %w", err)
}
return org, nil
}
func (s *Service) GetByID(ctx context.Context, id string) (*Organization, error) {
org, err := s.repo.FindByID(ctx, id)
if err != nil {
if errors.Is(err, ErrNoRows) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("failed to find organization: %w", err)
}
return org, nil
}
func (s *Service) List(ctx context.Context) (*OrgListResponse, error) {
orgs, err := s.repo.FindAll(ctx)
if err != nil {
return nil, fmt.Errorf("failed to list organizations: %w", err)
}
if orgs == nil {
orgs = []Organization{}
}
return &OrgListResponse{
Organizations: orgs,
Total: len(orgs),
}, nil
}
func (s *Service) Update(ctx context.Context, id string, req UpdateOrgRequest) (*Organization, error) {
org, err := s.repo.FindByID(ctx, id)
if err != nil {
if errors.Is(err, ErrNoRows) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("failed to find organization: %w", err)
}
org.Name = req.Name
if err := s.repo.Update(ctx, org); err != nil {
return nil, fmt.Errorf("failed to update organization: %w", err)
}
return org, nil
}
func (s *Service) Delete(ctx context.Context, id string) error {
org, err := s.repo.FindByID(ctx, id)
if err != nil {
if errors.Is(err, ErrNoRows) {
return ErrNotFound
}
return fmt.Errorf("failed to find organization: %w", err)
}
if err := s.repo.Delete(ctx, org.ID); err != nil {
return fmt.Errorf("failed to delete organization: %w", err)
}
return nil
}
func isUniqueViolation(err error) bool {
return err != nil && (strings.Contains(err.Error(), "unique") || strings.Contains(err.Error(), "23505"))
}