midas_cli/commands/
faker.rs1use std::path::PathBuf;
4
5use anyhow::{
6 bail,
7 Context as _,
8 Result,
9};
10use clap::{
11 Arg,
12 ArgAction,
13 ArgMatches,
14 Command,
15};
16use midas::config::ProcessEnv;
17use midas::seed::{
18 check_production,
19 run,
20 RunOptions,
21 SeedFile,
22};
23
24use crate::commands::{
25 seed_meta,
26 Context,
27};
28
29pub fn command() -> Command {
31 Command::new("faker")
32 .visible_alias("seed")
33 .about("Apply deterministic seed data to the configured database")
34 .arg(
35 Arg::new("seed-file")
36 .long("seed-file")
37 .value_name("path")
38 .help("Seed file (defaults to [seed].file or seed.toml)")
39 .num_args(1),
40 )
41 .arg(
42 Arg::new("table")
43 .long("table")
44 .value_name("name")
45 .help("Seed only this table (repeatable)")
46 .num_args(1)
47 .action(ArgAction::Append),
48 )
49 .arg(
50 Arg::new("rows")
51 .long("rows")
52 .value_name("n")
53 .help("Override generated row counts and row limits")
54 .num_args(1)
55 .value_parser(clap::value_parser!(u64)),
56 )
57 .arg(
58 Arg::new("seed")
59 .long("seed")
60 .value_name("n")
61 .help("Master seed")
62 .num_args(1)
63 .value_parser(clap::value_parser!(u64)),
64 )
65 .arg(
66 Arg::new("reset")
67 .long("reset")
68 .help("Clear selected tables before inserting")
69 .action(ArgAction::SetTrue),
70 )
71 .arg(
72 Arg::new("json")
73 .long("json")
74 .help("Emit a machine-readable summary")
75 .action(ArgAction::SetTrue),
76 )
77 .arg(
78 Arg::new("yes")
79 .long("yes")
80 .help("Confirm destructive operations")
81 .action(ArgAction::SetTrue),
82 )
83 .arg(
84 Arg::new("allow-production")
85 .long("allow-production")
86 .help("Allow running against production-like environments")
87 .action(ArgAction::SetTrue),
88 )
89}
90
91pub fn register(app: Command) -> Command {
93 app.subcommand(command())
94}
95
96pub fn owns(name: &str) -> bool {
98 matches!(name, "faker" | "seed")
99}
100
101pub fn dispatch(_name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
103 let json = matches.get_flag("json");
104 match execute(matches, context) {
105 Ok(()) => Ok(()),
106 Err(error) => {
107 if json {
108 println!("{}", serde_json::json!({ "error": error.to_string() }));
109 }
110 Err(error)
111 },
112 }
113}
114
115fn execute(matches: &ArgMatches, context: &Context) -> Result<()> {
116 let allow_production = matches.get_flag("allow-production");
117 check_production(&ProcessEnv, allow_production, context.dry_run)?;
118
119 let reset = matches.get_flag("reset");
120 if reset && !matches.get_flag("yes") {
121 bail!("--reset requires --yes");
122 }
123
124 let seed_path = seed_path(matches, context);
125 let seed = SeedFile::load(&seed_path, &context.config.seed)
126 .with_context(|| format!("failed to load seed file `{}`", seed_path.to_string_lossy()))?;
127
128 let resolved = seed_meta::live(&context.config)?;
129 let dialect = seed_meta::dialect(&context.config)?;
130
131 let tables: Vec<String> = matches
132 .get_many::<String>("table")
133 .map(|values| values.cloned().collect())
134 .unwrap_or_default();
135 let rows = matches.get_one::<u64>("rows").copied();
136 let master_seed = matches.get_one::<u64>("seed").copied();
137
138 let mut backend = midas::seed::connect(&context.config)?;
139 let summary = run(
140 Some(backend.as_mut()),
141 &RunOptions {
142 command: "faker",
143 file: &seed,
144 schema: &resolved.schema,
145 settings: &context.config.seed,
146 managed_schemas: &context.config.managed.schemas,
147 default_schema: context.config.search_path.as_deref(),
148 table_filters: &tables,
149 rows_override: rows,
150 reset,
151 skip_existing: false,
152 dry_run: context.dry_run,
153 no_lock: context.no_lock,
154 master_seed,
155 dialect,
156 warnings: &resolved.warnings,
157 },
158 )?;
159
160 if matches.get_flag("json") {
161 println!("{}", summary.to_json()?);
162 } else {
163 print_summary(&summary);
164 }
165 Ok(())
166}
167
168fn seed_path(matches: &ArgMatches, context: &Context) -> PathBuf {
169 matches
170 .get_one::<String>("seed-file")
171 .map(PathBuf::from)
172 .unwrap_or_else(|| context.config.seed.file.clone())
173}
174
175fn print_summary(summary: &midas::seed::Summary) {
176 println!("Seed: {}", summary.seed);
177 println!("Reference time: {}", summary.reference_time);
178 for table in &summary.tables {
179 println!(" {}: {} {} row(s)", table.table, table.rows, table.mode);
180 }
181 for table in &summary.reset {
182 println!("reset {table}");
183 }
184 for table in &summary.skipped {
185 println!("skipped {table}");
186 }
187 for warning in &summary.warnings {
188 eprintln!("warning: {warning}");
189 }
190 if summary.dry_run {
191 if let Some(sql) = &summary.sql {
192 print!("{sql}");
193 }
194 println!("Dry run: wrote nothing.");
195 } else {
196 println!("Seeded {} row(s).", summary.rows);
197 }
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203
204 #[test]
205 fn owns_faker_and_seed_alias() {
206 assert!(owns("faker"));
207 assert!(owns("seed"));
208 assert!(!owns("setup"));
209 }
210
211 #[test]
212 fn command_registers_expected_flags() {
213 let command = command();
214 let names: Vec<&str> = command
215 .get_arguments()
216 .map(|argument| argument.get_id().as_str())
217 .collect();
218 for expected in [
219 "seed-file",
220 "table",
221 "rows",
222 "seed",
223 "reset",
224 "json",
225 "yes",
226 "allow-production",
227 ] {
228 assert!(names.contains(&expected), "missing `{expected}`");
229 }
230 }
231}