use std::path::{Path, PathBuf};
use anyhow::{bail, ensure, Context, Result};
use link_cli::{make_transitions_log_filename, FileTransitionLog, QueryProcessor, RowUndoPolicy};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use super::{cli_transaction::CliTransaction, Cli};
mod rollback;
use rollback::{capture, changes, reverse, Change};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Definition {
id: String,
checksum: Option<String>,
up: String,
down: Option<String>,
}
#[derive(Deserialize, Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
struct Identity {
id: String,
checksum: String,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct Applied {
down: Option<String>,
changes: Vec<Change>,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct State {
version: u32,
known: Vec<Identity>,
applied: Vec<Applied>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Action {
List,
Plan,
Up,
Down,
Manual,
}
pub(super) struct Migrations {
definitions: Vec<Definition>,
manifest: Vec<Identity>,
action: Action,
target: Option<String>,
terminal: bool,
}
fn marker(cli: &Cli) -> PathBuf {
PathBuf::from(format!("{}.migrations.active", cli.db))
}
fn manifest_path(cli: &Cli) -> PathBuf {
PathBuf::from(
cli.migrations
.clone()
.unwrap_or_else(|| format!("{}.migrations.json", cli.db)),
)
}
pub(super) fn requested(cli: &Cli) -> bool {
cli.migrate.is_some()
|| cli.migrations.is_some()
|| cli.migration_mode.is_some()
|| cli.migration_target.is_some()
}
pub(super) fn enabled(cli: &Cli) -> bool {
requested(cli) || marker(cli).exists() || manifest_path(cli).exists()
}
impl Migrations {
pub(super) fn load(cli: &Cli) -> Result<Option<Self>> {
if !enabled(cli) {
return Ok(None);
}
ensure!(
cli.transactions_file.is_none(),
"Migrations require the default transitions journal."
);
ensure!(
cli.checkout.is_none() && cli.branch.is_none() && cli.branch_from.is_none(),
"Checkout and branch switching are unavailable on a store with migrations."
);
ensure!(
cli.migrate.is_none() || cli.migration_mode.is_none(),
"Use either --migrate or --migration-mode."
);
ensure!(
!marker(cli).exists() || make_transitions_log_filename(Path::new(&cli.db)).is_file(),
"The managed store is missing its transitions journal."
);
let terminal = cli.migrate.is_some();
let action = match (cli.migrate.as_deref(), cli.migration_mode.as_deref()) {
(Some("list"), None) => Action::List,
(Some("plan"), None) => Action::Plan,
(Some("up"), None) | (None, Some("auto-up")) => Action::Up,
(Some("down"), None) | (None, Some("auto-down")) => Action::Down,
(None, None | Some("manual")) => Action::Manual,
(Some(_), _) => bail!("Use --migrate list, plan, up, or down."),
_ => bail!("Use --migration-mode manual, auto-up, or auto-down."),
};
ensure!(
action != Action::List || cli.migration_target.is_none(),
"--migration-target is unavailable with --migrate list."
);
let path = manifest_path(cli);
let definitions: Vec<Definition> = serde_json::from_slice(
&std::fs::read(&path)
.with_context(|| format!("Cannot read migration manifest '{}'", path.display()))?,
)
.context("Invalid migration manifest")?;
let mut manifest = Vec::new();
for definition in &definitions {
let id = &definition.id;
ensure!(
valid_id(id) && !manifest.iter().any(|entry: &Identity| entry.id == *id),
"Invalid or duplicate migration ID '{id}'."
);
ensure!(
valid_query(&definition.up) && definition.down.as_deref().is_none_or(valid_query),
"Empty or invalid query in migration '{id}'."
);
let mut hasher = Sha256::new();
hasher.update(definition.up.as_bytes());
hasher.update([0]);
hasher.update(definition.down.as_deref().unwrap_or("").as_bytes());
let checksum = hasher
.finalize()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
ensure!(
definition
.checksum
.as_ref()
.is_none_or(|expected| *expected == checksum),
"Checksum mismatch for migration '{id}'."
);
manifest.push(Identity {
id: id.clone(),
checksum,
});
}
Ok(Some(Self {
definitions,
manifest,
action,
target: cli.migration_target.clone(),
terminal,
}))
}
pub(super) fn run(&self, cli: &Cli, storage: &mut impl CliTransaction) -> Result<bool> {
let mut state = match storage.transactions().migration_state()? {
Some(payload) => {
serde_json::from_str::<State>(&payload).context("Invalid migration history")?
}
None => State {
version: 1,
known: Vec::new(),
applied: Vec::new(),
},
};
ensure!(
state.version == 1 && state.applied.len() <= state.known.len(),
"Invalid migration history."
);
for (previous, supplied) in state.known.iter().zip(&self.manifest) {
ensure!(
previous == supplied,
"Migration manifest diverges at '{}'. IDs, order and checksums are immutable.",
previous.id
);
}
let current = state.applied.len();
let known = state.known.len();
state
.known
.extend(self.manifest.iter().skip(known).map(|entry| Identity {
id: entry.id.clone(),
checksum: entry.checksum.clone(),
}));
if self.action == Action::List {
for (index, entry) in state.known.iter().enumerate() {
println!(
"{}\t{}\t{}",
if index < current {
"applied"
} else {
"pending"
},
entry.id,
entry.checksum
);
}
return Ok(true);
}
let target = match self.target.as_deref() {
Some("base") => 0,
Some("latest") => self.manifest.len(),
Some(id) => state
.known
.iter()
.position(|entry| entry.id == id)
.map(|index| index + 1)
.with_context(|| format!("Unknown migration target '{id}'."))?,
None if self.action == Action::Down && self.terminal => current.saturating_sub(1),
None => self.manifest.len(),
};
if self.action == Action::Plan {
if current < target {
ensure!(
target <= self.definitions.len(),
"The manifest is missing forward migrations for the target."
);
for entry in &state.known[current..target] {
println!("up\t{}\t{}", entry.id, entry.checksum);
}
} else {
for entry in state.known[target..current].iter().rev() {
println!("down\t{}\t{}", entry.id, entry.checksum);
}
}
return Ok(true);
}
if current == target {
return Ok(self.terminal);
}
ensure!(self.action != Action::Manual,
"Migration required. Run --migrate plan, then --migrate up or down to the configured target.");
ensure!(
(target > current) == (self.action == Action::Up),
"The migration target is in the opposite direction."
);
ensure!(
target < current || target <= self.definitions.len(),
"The manifest is missing forward migrations for the target."
);
FileTransitionLog::open(marker(cli))?;
storage
.transactions()
.set_row_undo_policy(RowUndoPolicy::WriteAheadImage)?;
storage.begin()?;
let operation = (|| {
let processor = QueryProcessor::new(cli.trace);
for definition in self.definitions.iter().take(target).skip(current) {
let before = capture(storage)?;
processor
.process_query(storage, &definition.up)
.with_context(|| format!("Applying migration '{}'", definition.id))?;
let changes = changes(&before, &capture(storage)?);
ensure!(
definition.down.is_some() || !changes.iter().any(Change::loses_identity),
"Migration '{}' removes existing links and requires an explicit down query.",
definition.id
);
state.applied.push(Applied {
down: definition.down.clone(),
changes,
});
}
for index in (target..current).rev() {
reverse(storage, &processor, &state.applied[index])
.with_context(|| format!("Reversing migration '{}'", state.known[index].id))?;
state.applied.pop();
}
state.known.truncate(known.max(target));
storage
.transactions()
.stage_migration_state(&serde_json::to_string(&state)?)?;
Ok(())
})();
if let Err(error) = operation {
storage
.rollback()
.with_context(|| format!("Failed to roll back migration after: {error:#}"))?;
return Err(error);
}
storage.commit()?;
Ok(self.terminal)
}
}
fn valid_id(id: &str) -> bool {
!matches!(id, "base" | "latest")
&& id.as_bytes().first().is_some_and(u8::is_ascii_alphanumeric)
&& id
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
}
fn valid_query(query: &str) -> bool {
!query.trim().is_empty() && !query.contains('\0')
}