Files
imap-copier/internal/store/endpoints.go
T
vasyanskandClaude Opus 5 8bc7ff026d Add endpoint deletion
The endpoints screen could only create and edit servers, so a mistyped
or retired endpoint stayed in the list forever.

Tasks reference endpoints without ON DELETE CASCADE, so a referenced
endpoint is refused with 409 and a count of the tasks using it rather
than cascading away migration history. The foreign-key violation is
mapped to the same status to cover a task created between check and
delete.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 11:50:12 +07:00

71 lines
2.2 KiB
Go

package store
import "context"
type Endpoint struct {
ID int64 `json:"id"`
RoleLabel string `json:"role_label"`
Host string `json:"host"`
Port int `json:"port"`
TLSMode string `json:"tls_mode"`
}
func (s *Store) CreateEndpoint(ctx context.Context, e Endpoint) (int64, error) {
var id int64
err := s.Pool.QueryRow(ctx,
`INSERT INTO endpoints (role_label, host, port, tls_mode)
VALUES ($1,$2,$3,$4) RETURNING id`,
e.RoleLabel, e.Host, e.Port, e.TLSMode).Scan(&id)
return id, err
}
func (s *Store) UpdateEndpoint(ctx context.Context, e Endpoint) error {
_, err := s.Pool.Exec(ctx,
`UPDATE endpoints SET role_label=$2, host=$3, port=$4, tls_mode=$5 WHERE id=$1`,
e.ID, e.RoleLabel, e.Host, e.Port, e.TLSMode)
return err
}
// CountTasksUsingEndpoint reports how many tasks reference the endpoint on
// either side, so a delete can be refused with a meaningful message instead of
// surfacing a raw foreign-key violation.
func (s *Store) CountTasksUsingEndpoint(ctx context.Context, id int64) (int, error) {
var n int
err := s.Pool.QueryRow(ctx,
`SELECT count(*) FROM tasks WHERE src_endpoint_id=$1 OR dst_endpoint_id=$1`, id).Scan(&n)
return n, err
}
// DeleteEndpoint removes an endpoint. Tasks reference endpoints without ON
// DELETE CASCADE, so Postgres rejects the delete while any task still uses it.
func (s *Store) DeleteEndpoint(ctx context.Context, id int64) error {
_, err := s.Pool.Exec(ctx, `DELETE FROM endpoints WHERE id=$1`, id)
return err
}
func (s *Store) GetEndpoint(ctx context.Context, id int64) (Endpoint, error) {
var e Endpoint
err := s.Pool.QueryRow(ctx,
`SELECT id, role_label, host, port, tls_mode FROM endpoints WHERE id=$1`, id).
Scan(&e.ID, &e.RoleLabel, &e.Host, &e.Port, &e.TLSMode)
return e, err
}
func (s *Store) ListEndpoints(ctx context.Context) ([]Endpoint, error) {
rows, err := s.Pool.Query(ctx,
`SELECT id, role_label, host, port, tls_mode FROM endpoints ORDER BY id`)
if err != nil {
return nil, err
}
defer rows.Close()
out := []Endpoint{}
for rows.Next() {
var e Endpoint
if err := rows.Scan(&e.ID, &e.RoleLabel, &e.Host, &e.Port, &e.TLSMode); err != nil {
return nil, err
}
out = append(out, e)
}
return out, rows.Err()
}