dc39e3a5d3
First step of #1, and it goes first for one reason: #4 adds a team_id to nearly every table, and doing that twice -- once for SQLite, once for Postgres -- is work nobody gets paid for. The teams migrations now only have to be written against one database. The ten SQLite migrations are replaced by a single Postgres baseline rather than ported one by one. They were incremental in a way that has no value on a fresh install: 004 adds columns 008 drops again, and 008's backfill rewrites data a Postgres database never had. The history stays in git; the schema they add up to is now 001_baseline.sql. Timestamps stay BIGINT unix seconds and are NOT converted to timestamptz. Everything in Go already speaks epochs, so converting would have been a second, larger change riding along inside this one. It is worth doing on its own. The JSON columns did move to jsonb, because #4 will want to filter and index on labels. Most of the port is mechanical -- 170 placeholders from ? to $1 -- but four things needed more than a search and replace: * Dynamically built WHERE clauses cannot keep their numbering straight by hand, so they hand out placeholders through sqlArgs instead. A filter can now be added or reordered without renumbering anything. * SUM(resolved_at IS NULL) was SQLite counting a boolean as 0 or 1. Postgres has no sum(boolean), and this was breaking every dead man's switch -- silently, since the sweeper only logs. Now COUNT(*) FILTER. * unixepoch() became FLOOR(EXTRACT(EPOCH FROM now()))::bigint. The FLOOR is load-bearing: a bare cast rounds half up, so a row written at .6 of a second claimed a timestamp a second in the future and disagreed with the time.Now().Unix() the Go side stamps. * The unique-violation check matched SQLite's error text. It matches SQLSTATE 23505 now, so a renamed constraint cannot turn a 409 back into a 500. Tests need a real Postgres, because there is no in-memory Postgres the way there was an in-memory SQLite. Each test gets its own schema on a shared server -- cheaper than a database each, and still isolated. TERDUT_TEST_DSN says where it is; `make test-db` starts one locally and ci.yaml runs one as a service container. An unset DSN fails the suite rather than skipping it: a run that quietly tests nothing is worse than one that does not run. TestMigration_BackfillCarriesAckAndComments is deleted along with the migrations it replayed. What it protected -- an upgrade not losing acknowledgements and comments -- now belongs to scripts/sqlite-to-postgres.go, which is build-tagged so the SQLite driver stays out of the server binary. Both are meant to be deleted once this install has migrated. The chart loses the PVC, the data volume and the python backup sidecar, and requires database.dsnSecret.name: it provisions no database and cannot guess where the credentials live, so a render without it is meant to fail. Backups move to where Postgres actually runs. The other half of that -- the postgresql CR, the k8up pg_dump annotation and the network policy -- is a change to the wrapper chart in Ryuvia/charts and is not in here. Verified rather than assumed: the gate is green with -race against Postgres 17, govulncheck and gitleaks are clean, and the migration script was run end to end against a SQLite database built at the old schema and seeded in every table. Ids survive, so incidents keep their numbers and every foreign key still points where it did; the identity sequences are moved past the copied ids, and a webhook after the migration opened incident 12 rather than colliding at 1.
219 lines
6.3 KiB
Go
219 lines
6.3 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.ryuvia.com/niklas/terdut-server/internal/models"
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
func handleCreateSchedule(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
UserID int64 `json:"user_id"`
|
|
Dates []string `json:"dates"`
|
|
|
|
// Replace takes dates that somebody else already holds. It defaults
|
|
// to off so that the plain call cannot quietly move a shift off the
|
|
// person expecting to be paged for it — reassigning has to be asked
|
|
// for.
|
|
Replace bool `json:"replace"`
|
|
}
|
|
if err := decodeJSON(r, &req); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid request body"))
|
|
return
|
|
}
|
|
if req.UserID == 0 {
|
|
respond(w, http.StatusBadRequest, errResp("user_id is required"))
|
|
return
|
|
}
|
|
if len(req.Dates) == 0 {
|
|
respond(w, http.StatusBadRequest, errResp("dates must not be empty"))
|
|
return
|
|
}
|
|
for _, d := range req.Dates {
|
|
if _, err := time.Parse("2006-01-02", d); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid date: "+d+" (expected YYYY-MM-DD)"))
|
|
return
|
|
}
|
|
}
|
|
|
|
// Verify the user exists.
|
|
var exists int
|
|
if err := db.QueryRowContext(r.Context(), "SELECT 1 FROM users WHERE id = $1", req.UserID).Scan(&exists); err != nil {
|
|
respond(w, http.StatusNotFound, errResp("user not found"))
|
|
return
|
|
}
|
|
|
|
// All-or-nothing, in both directions: without replace, one taken date
|
|
// rejects the whole request; with it, either every date moves or none
|
|
// does. The rota must never be left with a hole where a shift used to
|
|
// be, so the delete and the insert share one transaction.
|
|
tx, err := db.BeginTx(r.Context(), nil)
|
|
if err != nil {
|
|
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
|
return
|
|
}
|
|
defer tx.Rollback()
|
|
|
|
for _, d := range req.Dates {
|
|
if req.Replace {
|
|
if _, err := tx.ExecContext(r.Context(),
|
|
"DELETE FROM schedule_entries WHERE date = $1", d); err != nil {
|
|
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
|
return
|
|
}
|
|
}
|
|
if _, err := tx.ExecContext(r.Context(),
|
|
"INSERT INTO schedule_entries (user_id, date) VALUES ($1, $2)", req.UserID, d); err != nil {
|
|
if isUniqueViolation(err) {
|
|
respond(w, http.StatusConflict,
|
|
errResp("date already assigned: "+d+" (pass replace to take it)"))
|
|
return
|
|
}
|
|
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
|
return
|
|
}
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
|
return
|
|
}
|
|
|
|
// Return the newly created entries.
|
|
dateSet := make(map[string]bool, len(req.Dates))
|
|
for _, d := range req.Dates {
|
|
dateSet[d] = true
|
|
}
|
|
all, err := scheduleRange(r.Context(), db, req.Dates[0], req.Dates[len(req.Dates)-1])
|
|
if err != nil {
|
|
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
|
return
|
|
}
|
|
created := []models.ScheduleEntry{}
|
|
for _, e := range all {
|
|
if dateSet[e.Date] {
|
|
created = append(created, e)
|
|
}
|
|
}
|
|
respond(w, http.StatusCreated, created)
|
|
}
|
|
}
|
|
|
|
func handleListSchedule(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
q := r.URL.Query()
|
|
from, to := q.Get("from"), q.Get("to")
|
|
|
|
if from != "" {
|
|
if _, err := time.Parse("2006-01-02", from); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid from date (expected YYYY-MM-DD)"))
|
|
return
|
|
}
|
|
}
|
|
if to != "" {
|
|
if _, err := time.Parse("2006-01-02", to); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid to date (expected YYYY-MM-DD)"))
|
|
return
|
|
}
|
|
}
|
|
|
|
entries, err := scheduleRange(r.Context(), db, from, to)
|
|
if err != nil {
|
|
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
|
return
|
|
}
|
|
respond(w, http.StatusOK, entries)
|
|
}
|
|
}
|
|
|
|
func handleDeleteSchedule(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
|
if err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid schedule id"))
|
|
return
|
|
}
|
|
res, err := db.ExecContext(r.Context(), "DELETE FROM schedule_entries WHERE id = $1", id)
|
|
if err != nil {
|
|
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
|
return
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
respond(w, http.StatusNotFound, errResp("schedule entry not found"))
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
}
|
|
|
|
func handleCurrentSchedule(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
today := time.Now().UTC().Format("2006-01-02")
|
|
|
|
var e models.ScheduleEntry
|
|
var ts int64
|
|
err := db.QueryRowContext(r.Context(), `
|
|
SELECT s.id, s.user_id, u.username, s.date, s.created_at
|
|
FROM schedule_entries s
|
|
JOIN users u ON u.id = s.user_id
|
|
WHERE s.date = $1`, today).Scan(&e.ID, &e.UserID, &e.Username, &e.Date, &ts)
|
|
if err == sql.ErrNoRows {
|
|
respond(w, http.StatusNotFound, errResp("no one is on call today"))
|
|
return
|
|
}
|
|
if err != nil {
|
|
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
|
return
|
|
}
|
|
e.CreatedAt = time.Unix(ts, 0).UTC()
|
|
respond(w, http.StatusOK, e)
|
|
}
|
|
}
|
|
|
|
// scheduleRange returns schedule entries ordered by date.
|
|
// from and to are YYYY-MM-DD strings; an empty string means unbounded on that side.
|
|
func scheduleRange(ctx context.Context, db *sql.DB, from, to string) ([]models.ScheduleEntry, error) {
|
|
where := []string{}
|
|
args := &sqlArgs{}
|
|
if from != "" {
|
|
where = append(where, "s.date >= "+args.add(from))
|
|
}
|
|
if to != "" {
|
|
where = append(where, "s.date <= "+args.add(to))
|
|
}
|
|
|
|
clause := "1=1"
|
|
if len(where) > 0 {
|
|
clause = strings.Join(where, " AND ")
|
|
}
|
|
|
|
rows, err := db.QueryContext(ctx, `
|
|
SELECT s.id, s.user_id, u.username, s.date, s.created_at
|
|
FROM schedule_entries s
|
|
JOIN users u ON u.id = s.user_id
|
|
WHERE `+clause+`
|
|
ORDER BY s.date ASC`, args.all()...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
entries := []models.ScheduleEntry{}
|
|
for rows.Next() {
|
|
var e models.ScheduleEntry
|
|
var ts int64
|
|
if err := rows.Scan(&e.ID, &e.UserID, &e.Username, &e.Date, &ts); err != nil {
|
|
return nil, err
|
|
}
|
|
e.CreatedAt = time.Unix(ts, 0).UTC()
|
|
entries = append(entries, e)
|
|
}
|
|
return entries, rows.Err()
|
|
}
|