package index
import (
"database/sql"
"errors"
"time"
)
// A check-in is named by a small integer wherever the index refers to one
// in volume; its hash lives in checkin alone. This file is the one place
// a hash becomes an id.
// rowQueryer is what a *sql.DB and a *sql.Tx share.
type rowQueryer interface {
Exec(query string, args ...any) (sql.Result, error)
QueryRow(query string, args ...any) *sql.Row
}
// checkinID is the id of the check-in named hash, allocating a ghost for
// a hash no checkin row holds yet: an edge may name a parent that has not
// arrived, and it needs an id all the same. A ghost's id is negative and
// the check-in that arrives takes it over (upsertCheckin), so nothing
// that names the id changes.
func checkinID(q rowQueryer, hash string) (int64, error) {
var id int64
err := q.QueryRow(`SELECT id FROM checkin WHERE hash = ?`, hash).Scan(&id)
if err == nil {
return id, nil
}
if !errors.Is(err, sql.ErrNoRows) {
return 0, err
}
err = q.QueryRow(`SELECT id FROM checkin_ghost WHERE hash = ?`, hash).Scan(&id)
if err == nil {
return id, nil
}
if !errors.Is(err, sql.ErrNoRows) {
return 0, err
}
// Below every id in use: an adopted ghost is a negative checkin id
// that checkin_ghost no longer lists, so both tables are asked.
if err := q.QueryRow(`SELECT min(
COALESCE((SELECT min(id) FROM checkin), 0),
COALESCE((SELECT min(id) FROM checkin_ghost), 0), 0) - 1`).Scan(&id); err != nil {
return 0, err
}
if _, err := q.Exec(`INSERT INTO checkin_ghost (id, hash) VALUES (?, ?)`, id, hash); err != nil {
return 0, err
}
return id, nil
}
// knownCheckinID is the id of a check-in the index holds, ghost or not,
// with ok false when it has never heard of the hash. Reads use it: they
// must not allocate.
func knownCheckinID(q rowQueryer, hash string) (id int64, ok bool, err error) {
for _, table := range []string{"checkin", "checkin_ghost"} {
err = q.QueryRow(`SELECT id FROM `+table+` WHERE hash = ?`, hash).Scan(&id)
if err == nil {
return id, true, nil
}
if !errors.Is(err, sql.ErrNoRows) {
return 0, false, err
}
}
return 0, false, nil
}
// upsertCheckin writes the artifact-borne fields of a check-in and
// returns its id and the date it is stored under. INSERT OR REPLACE
// would clobber the computed branch column on redelivery, and would give
// the row a new id.
//
// The stored date is the one filechange rows carry too. A rebuild writes
// it in the millisecond form and a live fold as the D card spells it; a
// row already held keeps its spelling when the new one names the same
// instant, so a redelivery after a rebuild changes nothing. A date that
// really differs moves the check-in's filechange rows with it.
func upsertCheckin(q rowQueryer, hash, date, user, comment string) (int64, string, error) {
var oldID sql.NullInt64
var oldDate string
err := q.QueryRow(`SELECT id, date FROM checkin WHERE hash = ?`, hash).Scan(&oldID, &oldDate)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return 0, "", err
}
if oldID.Valid {
if sameInstant(oldDate, date) {
date = oldDate
} else if err := moveFileDates(q, oldID.Int64, oldDate, date); err != nil {
return 0, "", err
}
}
var ghost sql.NullInt64
if err := q.QueryRow(`SELECT id FROM checkin_ghost WHERE hash = ?`, hash).Scan(&ghost); err != nil &&
!errors.Is(err, sql.ErrNoRows) {
return 0, "", err
}
if _, err := q.Exec(`INSERT INTO checkin (id, hash, date, user, comment)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT (hash) DO UPDATE SET date=excluded.date,
user=excluded.user, comment=excluded.comment`,
ghost, hash, date, user, comment); err != nil {
return 0, "", err
}
if ghost.Valid {
if _, err := q.Exec(`DELETE FROM checkin_ghost WHERE id = ?`, ghost.Int64); err != nil {
return 0, "", err
}
}
var id int64
err = q.QueryRow(`SELECT id FROM checkin WHERE hash = ?`, hash).Scan(&id)
return id, date, err
}
// sameInstant reports whether two D-card spellings name one moment.
func sameInstant(a, b string) bool {
if a == b {
return true
}
const layout = "2006-01-02T15:04:05"
ta, err := time.Parse(layout, a)
if err != nil {
return false
}
tb, err := time.Parse(layout, b)
return err == nil && ta.Equal(tb)
}
// moveFileDates rewrites the date of every filechange row of a check-in:
// the file rows are found by the check-in's index, and each one's
// ancestor directories are the other rows it wrote.
func moveFileDates(q rowQueryer, id int64, from, to string) error {
rows, err := q.(interface {
Query(string, ...any) (*sql.Rows, error)
}).Query(`SELECT path FROM filechange WHERE ci = ? AND dir = 0`, id)
if err != nil {
return err
}
var files []string
for rows.Next() {
var p string
if err := rows.Scan(&p); err != nil {
rows.Close()
return err
}
files = append(files, p)
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
for _, e := range ancestorPaths(files) {
if _, err := q.Exec(`UPDATE OR REPLACE filechange SET date = ? WHERE path = ? AND date = ? AND ci = ?`,
to, e.Path, from, id); err != nil {
return err
}
}
return nil
}
// putParents rewrites a check-in's parent edges.
func putParents(q rowQueryer, child int64, parents []string) error {
for i, parent := range parents {
pid, err := checkinID(q, parent)
if err != nil {
return err
}
if _, err := q.Exec(`INSERT OR REPLACE INTO checkin_parent (child, parent, ord)
VALUES (?, ?, ?)`, child, pid, i); err != nil {
return err
}
}
return nil
}
// hashOf is the SQL expression for the hash of the check-in whose id is
// the column col, a parent that has not arrived included.
func hashOf(col string) string {
return `COALESCE((SELECT hash FROM checkin WHERE id = ` + col +
`), (SELECT hash FROM checkin_ghost WHERE id = ` + col + `))`
}
// idsOf is the SQL subquery for the id of the check-in whose hash is the
// parameter param, a ghost included, for use after IN or as a recursive
// seed. It is empty for a hash the index has never heard of.
func idsOf(param string) string {
return `SELECT id FROM checkin WHERE hash = ` + param +
` UNION ALL SELECT id FROM checkin_ghost WHERE hash = ` + param
}