history.v

7.1 KB · raw

1//! History: one line of saves, and the queries every command needs.23module history45import src.storage6import src.snapshot78// A save is a full snapshot of the tree plus what made it.9pub struct Save {10pub mut:11	id            string12	parent        string13	message       string14	created_at    i6415	machine       string16	is_checkpoint bool17	size_bytes    i6418	agent         string19	session       string20	restores      string21	replayed_from string22}2324const select_save = 'SELECT id, parent, message, created_at, machine, is_checkpoint, size_bytes,25	agent, session, restores, replayed_from FROM saves'2627fn read_save(stmt &storage.Stmt) Save {28	return Save{29		id:            stmt.text(0)30		parent:        stmt.text_or_none(1) or { '' }31		message:       stmt.text(2)32		created_at:    stmt.int(3)33		machine:       stmt.text(4)34		is_checkpoint: stmt.int(5) != 035		size_bytes:    stmt.int(6)36		agent:         stmt.text_or_none(7) or { '' }37		session:       stmt.text_or_none(8) or { '' }38		restores:      stmt.text_or_none(9) or { '' }39		replayed_from: stmt.text_or_none(10) or { '' }40	}41}4243// head is the newest save on the line.44pub fn head(store &storage.Store) ?Save {45	id := store.state(storage.head_key) or { return none }46	return by_id(store, id) or { none }47}4849// head_id is the head save's ID, or '' before the first save.50pub fn head_id(store &storage.Store) string {51	return store.state(storage.head_key) or { '' }52}5354// save_row is the strict lookup: a database error comes back unchanged, and55// only a statement that returns no row means the save is missing. Callers that56// walk a parent chain use this so a bad read cannot pass for the end of it.57fn save_row(store &storage.Store, id string) !Save {58	mut stmt := store.db.prepare('${select_save} WHERE id = ?')!59	defer {60		stmt.finalize()61	}62	stmt.bind_text(1, id)!63	if stmt.step()! {64		return read_save(stmt)65	}66	return error('save ${id} is missing')67}6869// by_id answers "does this save exist" for callers that only branch on it.70pub fn by_id(store &storage.Store, id string) ?Save {71	return save_row(store, id) or { none }72}7374// resolve accepts any unique prefix of six characters or more, the way Koh 275// did, so an agent can name a save without quoting the whole ID.76pub fn resolve(store &storage.Store, prefix string) !Save {77	if prefix.len < 6 {78		return error('"${prefix}" is too short — give at least 6 characters of a save ID')79	}80	// Save IDs are hexadecimal. Anything else here would be read as a LIKE81	// wildcard and scan the table, so reject it before the query.82	for c in prefix {83		if !(c >= `0` && c <= `9`) && !(c >= `a` && c <= `f`) && !(c >= `A` && c <= `F`) {84			return error('"${prefix}" is not a save ID prefix — save IDs are hexadecimal')85		}86	}87	mut stmt := store.db.prepare('${select_save} WHERE id LIKE ? ORDER BY id')!88	defer {89		stmt.finalize()90	}91	stmt.bind_text(1, '${prefix}%')!92	mut found := []Save{}93	for stmt.step()! {94		found << read_save(stmt)95	}96	match found.len {97		0 { return error('no save starts with "${prefix}"') }98		1 { return found[0] }99		else { return error('"${prefix}" matches ${found.len} saves — give more characters') }100	}101}102103// all_saves returns every save Koh knows, newest first. This is the "all" tab:104// it includes saves that were replayed away and are no longer on the line.105pub fn all_saves(store &storage.Store) ![]Save {106	// Saves made within one second share a time; the order they were written107	// in breaks the tie, as in Koh 2. An ID is a hash and would shuffle them.108	mut stmt := store.db.prepare('${select_save} ORDER BY created_at DESC, rowid DESC')!109	defer {110		stmt.finalize()111	}112	mut saves := []Save{}113	for stmt.step()! {114		saves << read_save(stmt)115	}116	return saves117}118119// line returns the saves that are on the line, newest first.120pub fn line(store &storage.Store) ![]Save {121	mut saves := []Save{}122	mut cursor := head_id(store)123	for cursor != '' {124		save := save_row(store, cursor)!125		saves << save126		cursor = save.parent127	}128	return saves129}130131// effective is where the line actually sits: `head.restores` when the newest132// save was a going-back, else `head`. Going back repeatedly therefore keeps133// stepping further back instead of undoing the undo.134pub fn effective(store &storage.Store) !Save {135	current := head(store) or { return error('this repo has no saves yet') }136	if current.restores != '' {137		return by_id(store, current.restores) or {138			return error('save ${current.restores} is missing')139		}140	}141	return current142}143144// step_back walks `n` parents back from `id`.145pub fn step_back(store &storage.Store, id string, n int) !Save {146	mut current := by_id(store, id) or { return error('save ${id} is missing') }147	for _ in 0 .. n {148		if current.parent == '' {149			return error('there is nothing before ${current.id} — it is the first save')150		}151		current = by_id(store, current.parent) or {152			return error('save ${current.parent} is missing')153		}154	}155	return current156}157158// session_start returns the oldest save of the session `id` belongs to.159pub fn session_start(store &storage.Store, id string) !Save {160	current := by_id(store, id) or { return error('save ${id} is missing') }161	if current.session == '' {162		return error('save ${current.id} is not part of a session')163	}164	mut oldest := current165	mut cursor := current.parent166	for cursor != '' {167		previous := save_row(store, cursor)!168		if previous.session != current.session {169			break170		}171		oldest = previous172		cursor = previous.parent173	}174	return oldest175}176177// last_session finds the most recent session name on the line.178pub fn last_session(store &storage.Store) !string {179	for save in line(store)! {180		if save.session != '' {181			return save.session182		}183	}184	return error('no save on the line belongs to a session')185}186187// session_saves returns the line's saves in a session, oldest first. A save188// replayed away by a combine is off the line, and its copy stands for it.189pub fn session_saves(store &storage.Store, name string) ![]Save {190	mut saves := line(store)!.filter(it.session == name)191	saves.reverse_in_place()192	return saves193}194195// latest_checkpoint is the newest checkpoint on the line.196pub fn latest_checkpoint(store &storage.Store) ?Save {197	for save in line(store) or { return none } {198		if save.is_checkpoint {199			return save200		}201	}202	return none203}204205// files_of lists a save's files sorted by path, each with its object's size.206pub fn files_of(store &storage.Store, save_id string) ![]snapshot.FileEntry {207	mut stmt :=208		store.db.prepare('SELECT path, hash, executable FROM save_files WHERE save_id = ? ORDER BY path')!209	defer {210		stmt.finalize()211	}212	stmt.bind_text(1, save_id)!213	mut files := []snapshot.FileEntry{}214	for stmt.step()! {215		hash := stmt.text(1)216		files << snapshot.FileEntry{217			path:       stmt.text(0)218			hash:       hash219			size:       store.object_size(hash) or { 0 }220			executable: stmt.int(2) != 0221		}222	}223	return files224}225226// save_count counts every save Koh holds, replayed-away ones included, unlike `line`.227pub fn save_count(store &storage.Store) !i64 {228	return count(store, 'saves')229}230231pub fn checkpoint_count(store &storage.Store) !i64 {232	return count(store, 'saves WHERE is_checkpoint = 1')233}234235fn count(store &storage.Store, what string) !i64 {236	mut stmt := store.db.prepare('SELECT COUNT(*) FROM ${what}')!237	defer {238		stmt.finalize()239	}240	if !stmt.step()! {241		return 0242	}243	return stmt.int(0)244}