package db import ( "context" "database/sql" "fmt" ) // ListSites returns all configured prober sites, ordered by slot index. func (d *DB) ListSites(ctx context.Context) ([]Site, error) { rows, err := d.QueryContext(ctx, ` SELECT idx, site_id, created_at, updated_at FROM sites ORDER BY idx `) if err != nil { return nil, err } defer rows.Close() var out []Site for rows.Next() { var s Site var createdAt, updatedAt string if err := rows.Scan(&s.Index, &s.SiteID, &createdAt, &updatedAt); err != nil { return nil, err } var err error if s.CreatedAt, err = dbToTime(createdAt); err != nil { return nil, err } if s.UpdatedAt, err = dbToTime(updatedAt); err != nil { return nil, err } out = append(out, s) } return out, rows.Err() } // GetSiteIndex resolves a configured site_id to its 1/2/3 slot index. It // returns (0, nil) — not an error — if no site with that ID is configured, // matching the "0 means unconfigured" convention used throughout the // prober-facing handlers. func (d *DB) GetSiteIndex(ctx context.Context, siteID string) (int, error) { var idx int err := d.QueryRowContext(ctx, `SELECT idx FROM sites WHERE site_id=?`, siteID).Scan(&idx) if err == sql.ErrNoRows { return 0, nil } if err != nil { return 0, err } return idx, nil } // UpsertSite assigns (or renames) the site occupying the given slot. idx // must be 1, 2, or 3 — the schema hard-caps the number of prober slots at // three (see ip_queue.site{1,2,3}_complete). site_id must be unique across // slots. func (d *DB) UpsertSite(ctx context.Context, idx int, siteID string) error { if idx < 1 || idx > 3 { return fmt.Errorf("site index must be 1, 2, or 3, got %d: %w", idx, ErrValidation) } if siteID == "" { return fmt.Errorf("site_id must not be empty: %w", ErrValidation) } var existingIdx int err := d.QueryRowContext(ctx, `SELECT idx FROM sites WHERE site_id=? AND idx!=?`, siteID, idx).Scan(&existingIdx) if err != nil && err != sql.ErrNoRows { return err } if err == nil { return fmt.Errorf("site_id %q already assigned to slot %d: %w", siteID, existingIdx, ErrConflict) } now := timeToDB(Now()) _, err = d.ExecContext(ctx, ` INSERT INTO sites (idx, site_id, created_at, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(idx) DO UPDATE SET site_id=excluded.site_id, updated_at=excluded.updated_at `, idx, siteID, now, now) if err != nil { return fmt.Errorf("upsert site: %w", err) } return nil } // DeleteSite frees the given slot. func (d *DB) DeleteSite(ctx context.Context, idx int) error { res, err := d.ExecContext(ctx, `DELETE FROM sites WHERE idx=?`, idx) if err != nil { return err } if n, _ := res.RowsAffected(); n == 0 { return fmt.Errorf("site slot %d: %w", idx, ErrNotFound) } return nil }