// Package forwardproxy provides CRUD against the forward_proxy_acls // table. Renderer in internal/squid consumes the same rows to emit // /etc/edgeguard/squid/squid.conf. package forwardproxy import ( "context" "errors" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "git.netcell-it.de/projekte/edgeguard-native/internal/models" ) var ErrNotFound = errors.New("forward-proxy ACL not found") type Repo struct { Pool *pgxpool.Pool } func New(pool *pgxpool.Pool) *Repo { return &Repo{Pool: pool} } const baseSelect = ` SELECT id, name, acl_type, value, action, priority, active, comment, created_at, updated_at FROM forward_proxy_acls ` func (r *Repo) List(ctx context.Context) ([]models.ForwardProxyACL, error) { rows, err := r.Pool.Query(ctx, baseSelect+" ORDER BY priority DESC, id ASC") if err != nil { return nil, err } defer rows.Close() out := make([]models.ForwardProxyACL, 0, 8) for rows.Next() { a, err := scan(rows) if err != nil { return nil, err } out = append(out, *a) } return out, rows.Err() } func (r *Repo) Get(ctx context.Context, id int64) (*models.ForwardProxyACL, error) { row := r.Pool.QueryRow(ctx, baseSelect+" WHERE id = $1", id) a, err := scan(row) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } return nil, err } return a, nil } func (r *Repo) Create(ctx context.Context, a models.ForwardProxyACL) (*models.ForwardProxyACL, error) { row := r.Pool.QueryRow(ctx, ` INSERT INTO forward_proxy_acls (name, acl_type, value, action, priority, active, comment) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id, name, acl_type, value, action, priority, active, comment, created_at, updated_at`, a.Name, a.ACLType, a.Value, a.Action, a.Priority, a.Active, a.Comment) return scan(row) } func (r *Repo) Update(ctx context.Context, id int64, a models.ForwardProxyACL) (*models.ForwardProxyACL, error) { row := r.Pool.QueryRow(ctx, ` UPDATE forward_proxy_acls SET name = $1, acl_type = $2, value = $3, action = $4, priority = $5, active = $6, comment = $7, updated_at = NOW() WHERE id = $8 RETURNING id, name, acl_type, value, action, priority, active, comment, created_at, updated_at`, a.Name, a.ACLType, a.Value, a.Action, a.Priority, a.Active, a.Comment, id) out, err := scan(row) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } return nil, err } return out, nil } func (r *Repo) Delete(ctx context.Context, id int64) error { tag, err := r.Pool.Exec(ctx, `DELETE FROM forward_proxy_acls WHERE id = $1`, id) if err != nil { return err } if tag.RowsAffected() == 0 { return ErrNotFound } return nil } func scan(row interface{ Scan(...any) error }) (*models.ForwardProxyACL, error) { var a models.ForwardProxyACL if err := row.Scan( &a.ID, &a.Name, &a.ACLType, &a.Value, &a.Action, &a.Priority, &a.Active, &a.Comment, &a.CreatedAt, &a.UpdatedAt, ); err != nil { return nil, err } return &a, nil }