pub mod compiler;
pub mod engine;
pub mod generators;
pub mod output;
pub mod plan;
pub mod planners;
pub mod registry;
pub mod seed;
pub mod value;
pub mod verify;
use std::collections::{BTreeMap, HashSet};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use crate::convert::ConvertWarning;
use crate::diagnostic::{codes, Diagnostic, DiagnosticBag, SourceLocation};
use crate::parser::SqlDialect;
use crate::profile::evidence::DumpProfile;
use crate::profile::{
Confidence, Decision, DumpProfiler, ModelInference, Precedence, ProfileBudget, ProfileDepth,
};
use crate::synthetic::model::{InferenceMode, InsertMode, OutputMode};
use crate::synthetic::{ConfigLoader, ModelMerger, SourceValueUse, SyntheticFile};
pub use crate::render::{RenderOptions, SqlRenderer};
pub use crate::synthetic::SyntheticModel;
pub use compiler::{CompileOptions, ModelCompiler, TableCountKind, TableCountOverride};
pub use engine::{
DenseIntegerKey, EngineReport, GeneratedRow, GenerationEngine, KeyDomain,
RandomAccessKeyGenerator, RowSink,
};
pub use generators::ConstantFactory;
pub use output::{
install_interrupt_handler, publish_in_order, AtomicOutput, CancellationToken, FamilyBudget,
FamilyBuffer, FamilyState, PartialPublication, ProtectedSpool, PublicationSet, SpillKind,
SpoolReader, SpoolWriter, SpooledRow, TempConfig,
};
pub use plan::{
ColumnOwner, CompiledOutput, CompiledRelationship, DeferredConstraints, ExecutionPhase,
FamilyPhase, GenerationPlan, PlanEstimates, PlannedColumn, PlannedTable,
RelationshipDistribution, ResolvedTableSeed,
};
pub use registry::{
ArgumentSpec, Buffering, ColumnScope, CompileContext, CompiledGenerator, CompiledModifier,
CompiledPlanner, Determinism, ExtensionRegistry, FamilySumCheck, GeneratorDescriptor,
GeneratorFactory, KeyRecipe, ModifierDescriptor, ModifierFactory, PlanContext,
PlannerDescriptor, PlannerFactory, PlannerPredicate, PredicateGuard, RowContext, RowView,
Verification,
};
pub use seed::{derive_seed, SeedRoot, StreamId};
pub use value::{GenerateError, GeneratedValue};
pub use verify::{
CheckOutcome, CheckStatus, DistributionExpectation, GenerationVerifier, VerificationReport,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RunMode {
#[default]
Generate,
Check,
DryRun,
EmitModel,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OutputTarget {
Path(PathBuf),
Discard,
}
#[derive(Debug, Clone, Default)]
pub struct SourceOptions {
pub dialect: Option<SqlDialect>,
pub depth: Option<ProfileDepth>,
pub sample: Option<usize>,
}
#[derive(Debug, Clone)]
pub struct GenerateRequest {
pub input: Option<PathBuf>,
pub config: Option<PathBuf>,
pub output: OutputTarget,
pub emit: Option<OutputTarget>,
pub compile: CompileOptions,
pub render: RenderOptions,
pub output_dialect: Option<SqlDialect>,
pub mode: RunMode,
pub explain: bool,
pub verify: bool,
pub strict: bool,
pub source: SourceOptions,
}
#[derive(Debug, Clone, Default)]
pub struct GenerateReport {
pub rows_written: u64,
pub effective_seed: Option<u64>,
pub diagnostics: DiagnosticBag,
pub source_values: Vec<SourceValueUse>,
pub explain: Vec<ExplainColumn>,
}
#[derive(Debug, Clone)]
pub struct ExplainColumn {
pub column: String,
pub reason: String,
pub confidence: String,
pub generator_kind: String,
pub source_derived: bool,
pub rejected: Vec<ExplainRejected>,
}
#[derive(Debug, Clone)]
pub struct ExplainRejected {
pub generator_kind: String,
pub reason: String,
pub precedence: String,
pub confidence: String,
}
#[derive(Debug, Clone, Copy)]
pub struct Generate;
impl Generate {
pub fn builder() -> GenerateBuilder {
GenerateBuilder::default()
}
pub fn run(request: GenerateRequest) -> Result<GenerateReport, GenerateError> {
let GenerateRequest {
input,
config,
output,
emit,
mut compile,
render,
output_dialect,
mode,
explain,
verify,
strict,
source,
} = request;
if mode == RunMode::Generate {
if let (OutputTarget::Path(sql), Some(OutputTarget::Path(model))) = (&output, &emit) {
let sql_identity = normalized_destination(sql)
.map_err(|error| output_identity_error(sql, error))?;
let model_identity = normalized_destination(model)
.map_err(|error| output_identity_error(model, error))?;
if sql_identity == model_identity {
return Err(GenerateError::diagnostic(
&codes::REQUEST_OUTPUT,
sql.display().to_string(),
"generated SQL and the resolved model require different destinations",
));
}
}
}
let had_source_dump = input.is_some();
let ResolvedModel {
model,
mut diagnostics,
decisions,
} = assemble_model(input.as_deref(), config.as_deref(), &source)?;
let explicit_seed = compile.seed.or(model.seed);
let effective_seed = explicit_seed.unwrap_or_else(rand::random);
compile.seed = Some(effective_seed);
let plan = ModelCompiler::standard()
.compile(model.clone(), compile)
.map_err(GenerateError::Diagnostics)?;
diagnostics.diagnostics.extend(plan.diagnostics.clone());
let mut render = render;
resolve_render_options(&mut render, output_dialect, &plan);
let source_values = model.source_value_uses();
if !source_values.is_empty() {
let message = if had_source_dump {
format!(
"{} rule(s) replay literal values that may have been derived from the source \
dump; review the listed rules before sharing the output",
source_values.len()
)
} else {
format!(
"{} rule(s) replay hand-authored literal values; the output is synthetic, \
not anonymized source data",
source_values.len()
)
};
let diagnostic = diagnostics.advisory(&codes::SOURCE_VALUES, "tables", message);
diagnostic.related = source_values
.iter()
.map(|used| SourceLocation {
path: used.path.clone(),
description: Some(used.rule_kind.clone()),
})
.collect();
}
let explain = if explain {
build_explain(&decisions)
} else {
Vec::new()
};
let report = GenerateReport {
rows_written: 0,
effective_seed: Some(effective_seed),
diagnostics,
source_values,
explain,
};
if strict && has_warnings(&report.diagnostics) {
return Err(GenerateError::Diagnostics(report.diagnostics));
}
if verify {
let diagnostics = report.diagnostics.clone();
let VerifiedRun {
rows_written,
diagnostics,
} = run_verified(
&model,
plan,
diagnostics,
VerifiedOptions {
explicit_seed,
output,
emit,
render,
strict,
},
)?;
let out = GenerateReport {
rows_written,
diagnostics,
..report
};
return Ok(out);
}
let model_output = stage_model(&model, &plan, explicit_seed, emit.as_ref())?;
match mode {
RunMode::Check | RunMode::EmitModel => {
publish_model(model_output)?;
Ok(report)
}
RunMode::DryRun => {
let rows_written = plan.estimates.total_rows;
publish_model(model_output)?;
Ok(GenerateReport {
rows_written,
..report
})
}
RunMode::Generate => {
let diagnostics = report.diagnostics.clone();
let (engine_report, diagnostics) = run_generate(
GenerationEngine::new(plan),
output,
model_output,
render,
diagnostics,
strict,
)?;
let out = GenerateReport {
rows_written: engine_report.rows_written,
diagnostics,
..report
};
Ok(out)
}
}
}
}
fn normalized_destination(path: &Path) -> io::Result<PathBuf> {
let absolute = if path.is_absolute() {
path.to_path_buf()
} else {
std::env::current_dir()?.join(path)
};
let filename = absolute.file_name().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("`{}` has no output filename", path.display()),
)
})?;
let mut ancestor = absolute.parent().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("`{}` has no parent destination", path.display()),
)
})?;
let mut suffix = Vec::new();
while !ancestor.try_exists()? {
let name = ancestor.file_name().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("`{}` has no existing filesystem ancestor", path.display()),
)
})?;
suffix.push(name.to_os_string());
ancestor = ancestor.parent().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("`{}` has no parent destination", path.display()),
)
})?;
}
let mut identity = ancestor.canonicalize()?;
for component in suffix.iter().rev() {
identity.push(component);
}
identity.push(filename);
Ok(identity)
}
fn output_identity_error(path: &Path, error: io::Error) -> GenerateError {
GenerateError::diagnostic(
&codes::REQUEST_OUTPUT,
path.display().to_string(),
format!(
"cannot resolve output destination `{}`: {error}",
path.display()
),
)
}
struct VerifiedRun {
rows_written: u64,
diagnostics: DiagnosticBag,
}
struct VerifiedOptions {
explicit_seed: Option<u64>,
output: OutputTarget,
emit: Option<OutputTarget>,
render: RenderOptions,
strict: bool,
}
fn run_verified(
model: &SyntheticModel,
plan: GenerationPlan,
mut diagnostics: DiagnosticBag,
options: VerifiedOptions,
) -> Result<VerifiedRun, GenerateError> {
let VerifiedOptions {
explicit_seed,
output,
emit,
render,
strict,
} = options;
let destination = match output {
OutputTarget::Path(path) => path,
OutputTarget::Discard => {
return Err(GenerateError::diagnostic(
&codes::VERIFY_NO_FILE,
"output",
"--verify requires a filesystem SQL destination, not stdout",
))
}
};
let emit_plan = match &emit {
Some(OutputTarget::Path(path)) => Some((
path.clone(),
resolved_model_yaml(model, &plan, explicit_seed)?,
)),
_ => None,
};
let verifier = verify::GenerationVerifier::new(&plan)
.dialect(render.dialect)
.output_mode(render.mode);
let mut sql_output = AtomicOutput::create(&destination).map_err(|error| {
GenerateError::diagnostic(
&codes::VERIFY_STAGE,
destination.display().to_string(),
format!(
"cannot stage output beside `{}`: {error}",
destination.display()
),
)
})?;
let temp_path = sql_output.temp_path().to_path_buf();
let (rows_written, render_warnings) = {
let mut renderer = SqlRenderer::new(sql_output.writer(), render);
let engine_report = GenerationEngine::new(plan).run(&mut renderer)?;
let warnings = renderer.warnings().to_vec();
renderer.finish()?;
(engine_report.rows_written, warnings)
};
let report = verifier.verify_path(&temp_path)?;
if !report.passed() {
let failures: Vec<String> = report
.failures()
.map(|check| format!("{} ({})", check.name, check.detail))
.collect();
let mut diagnostic = Diagnostic::error(
&codes::VERIFY_FAILED,
destination.display().to_string(),
format!(
"generated output failed verification and was not published; {} check(s) failed",
failures.len()
),
);
diagnostic.related = failures
.into_iter()
.map(|failure| SourceLocation {
path: destination.display().to_string(),
description: Some(failure),
})
.collect();
return Err(GenerateError::Diagnostic(Box::new(diagnostic)));
}
let not_checked: Vec<String> = report
.checks
.iter()
.filter(|check| check.status == verify::CheckStatus::NotChecked)
.map(|check| check.name.clone())
.collect();
merge_render_warnings(&mut diagnostics, &render_warnings);
merge_not_checked_warning(&mut diagnostics, ¬_checked);
if strict && has_warnings(&diagnostics) {
return Err(GenerateError::Diagnostics(diagnostics));
}
let mut outputs = vec![sql_output];
if let Some((path, yaml)) = emit_plan {
let mut model_output = AtomicOutput::create(&path).map_err(|error| {
GenerateError::diagnostic(
&codes::VERIFY_STAGE,
path.display().to_string(),
format!("cannot stage model beside `{}`: {error}", path.display()),
)
})?;
use std::io::Write;
model_output
.writer()
.write_all(yaml.as_bytes())
.map_err(|error| {
GenerateError::diagnostic(
&codes::EMIT_IO,
path.display().to_string(),
error.to_string(),
)
})?;
outputs.push(model_output);
}
publish_in_order(outputs).map_err(|partial| {
GenerateError::diagnostic(
&codes::VERIFY_PARTIAL_PUBLISH,
"output",
partial.to_string(),
)
})?;
Ok(VerifiedRun {
rows_written,
diagnostics,
})
}
struct ResolvedModel {
model: SyntheticModel,
diagnostics: DiagnosticBag,
decisions: Vec<Decision>,
}
fn assemble_model(
input: Option<&Path>,
config: Option<&Path>,
source: &SourceOptions,
) -> Result<ResolvedModel, GenerateError> {
match (input, config) {
(None, None) => Err(GenerateError::diagnostic(
&codes::REQUEST_SOURCE,
"request",
"at least one of `.input()` or `.config()` is required",
)),
(None, Some(config_path)) => {
match ConfigLoader::load(config_path).map_err(GenerateError::Diagnostics)? {
SyntheticFile::Model(model) => Ok(ResolvedModel {
model,
diagnostics: DiagnosticBag::default(),
decisions: Vec::new(),
}),
SyntheticFile::Overrides(_) => Err(GenerateError::diagnostic(
&codes::OVERRIDES_NO_BASE,
config_path.display().to_string(),
format!(
"`{}` is a `kind: overrides` document but no base model is available; \
supply a source dump to profile (`.input()`) so the overrides have a \
base to merge onto",
config_path.display()
),
)),
}
}
(Some(input_path), config) => {
let profile = profile_source(input_path, source)?;
let inference = ModelInference::standard()
.infer(&profile.schema, &profile)
.map_err(|error| {
GenerateError::diagnostic(
&codes::INFER_FAILED,
input_path.display().to_string(),
error.to_string(),
)
})?;
let mut diagnostics = DiagnosticBag::default();
diagnostics.diagnostics.extend(profile.warnings);
diagnostics.diagnostics.extend(
inference
.warnings
.into_iter()
.filter(|diagnostic| diagnostic.code != codes::INFER_SOURCE_DERIVED.code),
);
let base = inference.model;
let decisions = inference.decisions;
match config {
None => Ok(ResolvedModel {
model: base,
diagnostics,
decisions,
}),
Some(config_path) => {
match ConfigLoader::load(config_path).map_err(GenerateError::Diagnostics)? {
SyntheticFile::Overrides(patch) => {
let (merged, bag) = ModelMerger::merge(base, patch)
.map_err(GenerateError::Diagnostics)?;
diagnostics.diagnostics.extend(bag.diagnostics);
Ok(ResolvedModel {
model: merged,
diagnostics,
decisions,
})
}
SyntheticFile::Model(model) => {
diagnostics.warning(
crate::diagnostic::codes::CONFIG_COMPLETE_MODEL.code,
config_path.display().to_string(),
"a complete `kind: model` config was supplied with a source dump; \
using the config model and ignoring the profiled base",
);
Ok(ResolvedModel {
model,
diagnostics,
decisions: Vec::new(),
})
}
}
}
}
}
}
}
fn profile_source(path: &Path, source: &SourceOptions) -> Result<DumpProfile, GenerateError> {
let mut builder = DumpProfiler::builder();
if let Some(dialect) = source.dialect {
builder = builder.dialect(dialect);
}
if let Some(depth) = source.depth {
builder = builder.depth(depth);
}
if let Some(sample) = source.sample {
builder = builder.budget(ProfileBudget {
sample_rows: sample,
..ProfileBudget::default()
});
}
builder.build().profile_path(path).map_err(source_error)
}
fn source_error(error: impl std::fmt::Display) -> GenerateError {
GenerateError::diagnostic(&codes::SOURCE_IO, "input", error.to_string())
}
fn resolved_model_yaml(
model: &SyntheticModel,
plan: &GenerationPlan,
explicit_seed: Option<u64>,
) -> Result<String, GenerateError> {
let mut emit = model.clone();
let resolved: BTreeMap<String, u64> = plan
.tables
.iter()
.map(|t| (t.name.clone(), t.rows))
.collect();
emit.imports.clear();
emit.tables.retain(|name, _| resolved.contains_key(name));
emit.profiles.retain(|path, _| {
path.split_once('.')
.is_some_and(|(table, _)| resolved.contains_key(table))
});
for planned in &plan.tables {
let Some(table) = emit.tables.get_mut(&planned.name) else {
continue;
};
table.schema = planned.schema.clone();
table.relationships.retain(|relationship| {
planned.relationships.iter().any(|active| {
active.name == relationship.name
&& active.columns == relationship.columns
&& active.parent_table == relationship.references.table
&& active.parent_columns == relationship.references.columns
})
});
}
let family_children: HashSet<String> = plan
.tables
.iter()
.flat_map(|table| table.planners.iter())
.filter_map(|planner| planner.family_child_table().map(str::to_owned))
.collect();
emit.freeze_row_counts(&resolved, &family_children);
emit.defaults.inference = InferenceMode::Disabled;
emit.seed = explicit_seed;
serde_yaml_ng::to_string(&emit).map_err(|error| {
GenerateError::diagnostic(&codes::EMIT_SERIALIZE, "emit_config", error.to_string())
})
}
fn stage_model(
model: &SyntheticModel,
plan: &GenerationPlan,
explicit_seed: Option<u64>,
target: Option<&OutputTarget>,
) -> Result<Option<AtomicOutput>, GenerateError> {
let Some(target) = target else {
return Ok(None);
};
let yaml = resolved_model_yaml(model, plan, explicit_seed)?;
match target {
OutputTarget::Path(path) => {
let mut output = AtomicOutput::create(path).map_err(|error| {
GenerateError::diagnostic(
&codes::EMIT_IO,
path.display().to_string(),
format!("cannot stage model beside `{}`: {error}", path.display()),
)
})?;
output
.writer()
.write_all(yaml.as_bytes())
.map_err(|error| {
GenerateError::diagnostic(
&codes::EMIT_IO,
path.display().to_string(),
format!("failed to stage `{}`: {error}", path.display()),
)
})?;
Ok(Some(output))
}
OutputTarget::Discard => Ok(None),
}
}
fn publish_model(output: Option<AtomicOutput>) -> Result<(), GenerateError> {
let Some(output) = output else {
return Ok(());
};
let path = output.destination().to_path_buf();
output.commit().map_err(|error| {
GenerateError::diagnostic(
&codes::EMIT_IO,
path.display().to_string(),
format!("failed to publish `{}`: {error}", path.display()),
)
})
}
fn build_explain(decisions: &[Decision]) -> Vec<ExplainColumn> {
decisions
.iter()
.map(|decision| ExplainColumn {
column: decision.column.clone(),
reason: decision.reason.clone(),
confidence: confidence_label(decision.confidence).to_string(),
generator_kind: decision.generator_kind.clone(),
source_derived: decision.source_derived,
rejected: decision
.rejected
.iter()
.map(|rejected| ExplainRejected {
generator_kind: rejected.generator_kind.clone(),
reason: rejected.reason.clone(),
precedence: precedence_label(rejected.precedence).to_string(),
confidence: confidence_label(rejected.confidence).to_string(),
})
.collect(),
})
.collect()
}
fn confidence_label(confidence: Confidence) -> &'static str {
match confidence {
Confidence::Low => "low",
Confidence::Medium => "medium",
Confidence::High => "high",
Confidence::Certain => "certain",
}
}
fn precedence_label(precedence: Precedence) -> &'static str {
match precedence {
Precedence::TypeFallback => "type_fallback",
Precedence::ObservedDistribution => "observed_distribution",
Precedence::StrongSemantic => "strong_semantic",
Precedence::Relationship => "relationship",
Precedence::CredentialGuard => "credential_guard",
Precedence::SchemaConstraint => "schema_constraint",
Precedence::ExplicitYaml => "explicit_yaml",
}
}
fn run_generate(
engine: GenerationEngine,
output: OutputTarget,
model_output: Option<AtomicOutput>,
render: RenderOptions,
mut diagnostics: DiagnosticBag,
strict: bool,
) -> Result<(EngineReport, DiagnosticBag), GenerateError> {
match output {
OutputTarget::Path(path) => {
let mut sql_output = AtomicOutput::create(&path).map_err(|err| {
GenerateError::diagnostic(
&codes::OUTPUT_IO,
path.display().to_string(),
format!("cannot stage output beside `{}`: {err}", path.display()),
)
})?;
let (report, warnings) = {
let mut renderer = SqlRenderer::new(sql_output.writer(), render);
let report = engine.run(&mut renderer)?;
let warnings = renderer.warnings().to_vec();
renderer.finish()?;
(report, warnings)
};
merge_render_warnings(&mut diagnostics, &warnings);
if strict && has_warnings(&diagnostics) {
return Err(GenerateError::Diagnostics(diagnostics));
}
if let Some(model_output) = model_output {
publish_in_order(vec![sql_output, model_output]).map_err(|partial| {
GenerateError::diagnostic(&codes::OUTPUT_IO, "output", partial.to_string())
})?;
} else {
sql_output.commit().map_err(|error| {
GenerateError::diagnostic(
&codes::OUTPUT_IO,
path.display().to_string(),
format!("failed to publish `{}`: {error}", path.display()),
)
})?;
}
Ok((report, diagnostics))
}
OutputTarget::Discard => {
let mut sink = DiscardSink;
let report = engine.run(&mut sink)?;
publish_model(model_output)?;
Ok((report, diagnostics))
}
}
}
const DEFAULT_RENDER_BATCH_SIZE: usize = 1_000;
fn resolve_render_options(
render: &mut RenderOptions,
output_dialect: Option<SqlDialect>,
plan: &GenerationPlan,
) {
let deliberate_dialect = match (output_dialect, plan.output.dialect) {
(Some(cli), _) => {
render.dialect = cli;
true
}
(None, Some(model_dialect)) => {
render.dialect = model_dialect;
true
}
(None, None) => {
render.dialect = plan.input_dialect.unwrap_or(SqlDialect::MySql);
false
}
};
if deliberate_dialect {
render.source_dialect = render.source_dialect.or(plan.input_dialect);
}
if render.mode == OutputMode::SchemaAndData {
if let Some(mode) = plan.output.mode {
render.mode = mode;
}
}
if !render.no_copy {
render.no_copy = matches!(plan.output.inserts, Some(InsertMode::Insert));
}
if render.batch_size == DEFAULT_RENDER_BATCH_SIZE {
if let Some(batch) = plan.output.batch_size.filter(|&b| b > 0) {
render.batch_size = batch as usize;
}
}
}
fn merge_render_warnings(diagnostics: &mut DiagnosticBag, warnings: &[ConvertWarning]) {
for warning in warnings {
let code = match warning {
ConvertWarning::LossyConversion { .. } => crate::diagnostic::codes::LOSSY_TYPE.code,
_ => crate::diagnostic::codes::RENDER_WARNING.code,
};
diagnostics.warning(code, "output", warning.to_string());
}
}
fn merge_not_checked_warning(diagnostics: &mut DiagnosticBag, not_checked: &[String]) {
if not_checked.is_empty() {
return;
}
diagnostics.warning(
crate::diagnostic::codes::VERIFY_NOTCHECKED.code,
String::new(),
format!(
"verification passed but {} capability/capabilities could not be checked exactly: {}",
not_checked.len(),
not_checked.join(", ")
),
);
}
fn has_warnings(diagnostics: &DiagnosticBag) -> bool {
diagnostics
.diagnostics
.iter()
.any(|diagnostic| diagnostic.severity == crate::diagnostic::Severity::Warning)
}
struct DiscardSink;
impl RowSink for DiscardSink {
fn begin_table(&mut self, _table: &PlannedTable) -> Result<(), GenerateError> {
Ok(())
}
fn write_row(
&mut self,
_table: &PlannedTable,
_row: &GeneratedRow,
) -> Result<(), GenerateError> {
Ok(())
}
fn end_table(&mut self, _table: &PlannedTable) -> Result<(), GenerateError> {
Ok(())
}
}
#[derive(Debug, Clone, Default)]
pub struct GenerateBuilder {
input: Option<PathBuf>,
config: Option<PathBuf>,
output: Option<PathBuf>,
emit: Option<PathBuf>,
compile: CompileOptions,
render: RenderOptions,
output_dialect: Option<SqlDialect>,
mode: RunMode,
explain: bool,
verify: bool,
strict: bool,
source: SourceOptions,
}
impl GenerateBuilder {
pub fn input(mut self, path: impl Into<PathBuf>) -> Self {
self.input = Some(path.into());
self
}
pub fn config(mut self, path: impl Into<PathBuf>) -> Self {
self.config = Some(path.into());
self
}
pub fn output(mut self, path: impl Into<PathBuf>) -> Self {
self.output = Some(path.into());
self
}
pub fn emit(mut self, path: impl Into<PathBuf>) -> Self {
self.emit = Some(path.into());
self
}
pub fn explain(mut self, explain: bool) -> Self {
self.explain = explain;
self
}
pub fn input_dialect(mut self, dialect: SqlDialect) -> Self {
self.source.dialect = Some(dialect);
self
}
pub fn profile_sample(mut self, sample: usize) -> Self {
self.source.sample = Some(sample);
self
}
pub fn output_dialect(mut self, dialect: SqlDialect) -> Self {
self.render.dialect = dialect;
self.output_dialect = Some(dialect);
self
}
pub fn seed(mut self, seed: u64) -> Self {
self.compile.seed = Some(seed);
self
}
pub fn mssql_production_style(mut self, production_style: bool) -> Self {
self.render.mssql_production_style = production_style;
self
}
pub fn mssql_go(mut self, interval: u64) -> Self {
self.render.mssql_go = Some(interval);
self
}
pub fn table_scale(
mut self,
table: impl Into<String>,
factor: f64,
) -> Result<Self, GenerateError> {
if !factor.is_finite() || factor < 0.0 {
return Err(GenerateError::diagnostic(
&codes::TABLE_SCALE_INVALID,
format!("tables.{}", table.into()),
format!("table scale must be a finite, non-negative number, found {factor}"),
));
}
self.compile
.table_rows
.push(TableCountOverride::scale(table, factor));
Ok(self)
}
pub fn compile(mut self, compile: CompileOptions) -> Self {
self.compile = compile;
self
}
pub fn verify(mut self, verify: bool) -> Self {
self.verify = verify;
self
}
pub fn strict(mut self, strict: bool) -> Self {
self.strict = strict;
self
}
pub fn profile_depth(mut self, depth: ProfileDepth) -> Self {
self.source.depth = Some(depth);
self
}
pub fn mode(mut self, mode: RunMode) -> Self {
self.mode = mode;
self
}
fn build(self) -> Result<GenerateRequest, GenerateError> {
if self.verify && self.mode != RunMode::Generate {
return Err(GenerateError::diagnostic(
&codes::VERIFY_MODE,
"request.verify",
"--verify generates and publishes; it cannot be combined with \
check/dry-run/emit-only modes",
));
}
let output = match (self.mode, self.output) {
(RunMode::Generate, Some(path)) => OutputTarget::Path(path),
(RunMode::Generate, None) => {
return Err(GenerateError::diagnostic(
&codes::REQUEST_OUTPUT,
"request.output",
"`.output()` is required under `RunMode::Generate`",
))
}
(RunMode::Check | RunMode::DryRun | RunMode::EmitModel, Some(path)) => {
OutputTarget::Path(path)
}
(RunMode::Check | RunMode::DryRun | RunMode::EmitModel, None) => OutputTarget::Discard,
};
if self.verify && !matches!(output, OutputTarget::Path(_)) {
return Err(GenerateError::diagnostic(
&codes::VERIFY_NO_FILE,
"request.output",
"--verify requires a filesystem SQL destination",
));
}
Ok(GenerateRequest {
input: self.input,
config: self.config,
output,
emit: self.emit.map(OutputTarget::Path),
compile: self.compile,
render: self.render,
output_dialect: self.output_dialect,
mode: self.mode,
explain: self.explain,
verify: self.verify,
strict: self.strict,
source: self.source,
})
}
pub fn run(self) -> Result<GenerateReport, GenerateError> {
Generate::run(self.build()?)
}
}