1use apiplant_core::schema::FieldType;
45use apiplant_core::{App, Resource};
46use sea_orm::sea_query::Value as SqlValue;
47use sea_orm::{ConnectionTrait, DatabaseBackend, Statement};
48use serde_json::Value as Json;
49use std::path::{Path, PathBuf};
50use uuid::Uuid;
51
52use crate::ident::quote_ident;
53use crate::{value, Error};
54
55#[derive(Debug, Clone)]
57pub struct FileReport {
58 pub resource: String,
59 pub inserted: u64,
61 pub skipped: u64,
63}
64
65#[derive(Debug, Clone, Default)]
67pub struct Report {
68 pub files: Vec<FileReport>,
69}
70
71impl Report {
72 pub fn inserted(&self) -> u64 {
73 self.files.iter().map(|f| f.inserted).sum()
74 }
75
76 pub fn skipped(&self) -> u64 {
77 self.files.iter().map(|f| f.skipped).sum()
78 }
79
80 pub fn is_empty(&self) -> bool {
82 self.files.is_empty()
83 }
84}
85
86pub async fn seed(conn: &impl ConnectionTrait, app: &App) -> Result<Report, Error> {
92 seed_dir(conn, app, &app.root.join("seed")).await
93}
94
95pub async fn seed_dir(conn: &impl ConnectionTrait, app: &App, dir: &Path) -> Result<Report, Error> {
98 if !dir.is_dir() {
99 return Ok(Report::default());
100 }
101
102 let mut files: Vec<(String, PathBuf)> = Vec::new();
104 let entries = std::fs::read_dir(dir)
105 .map_err(|e| Error::Schema(format!("cannot read {}: {e}", dir.display())))?;
106 for entry in entries {
107 let path = entry
108 .map_err(|e| Error::Schema(format!("cannot read {}: {e}", dir.display())))?
109 .path();
110 match path.extension().and_then(|e| e.to_str()) {
111 Some("toml") | Some("csv") => {}
112 _ => continue,
113 }
114 let name = path
115 .file_stem()
116 .and_then(|s| s.to_str())
117 .unwrap_or_default()
118 .to_string();
119 if !app.resources.contains_key(&name) {
120 return Err(Error::Schema(format!(
121 "{}: no resource named `{name}` — a seed file is named after the \
122 resource it fills",
123 path.display()
124 )));
125 }
126 if let Some((_, other)) = files.iter().find(|(existing, _)| existing == &name) {
127 return Err(Error::Schema(format!(
128 "{name} is seeded twice, by {} and {} — one file per resource",
129 other.display(),
130 path.display()
131 )));
132 }
133 files.push((name, path));
134 }
135
136 let mut report = Report::default();
138 for resource in app.resources_in_dependency_order() {
139 let Some((_, path)) = files.iter().find(|(name, _)| name == &resource.meta.name) else {
140 continue;
141 };
142 let file = seed_file(conn, resource, path).await?;
143 tracing::info!(
144 resource = %file.resource,
145 inserted = file.inserted,
146 skipped = file.skipped,
147 "seeded"
148 );
149 report.files.push(file);
150 }
151 Ok(report)
152}
153
154type Row = Vec<(String, Raw)>;
157
158#[derive(Debug, Clone)]
160enum Raw {
161 Text(String),
163 Typed(Json),
165}
166
167async fn seed_file(
169 conn: &impl ConnectionTrait,
170 r: &Resource,
171 path: &Path,
172) -> Result<FileReport, Error> {
173 let origin = path.display().to_string();
174 let text = std::fs::read_to_string(path)
175 .map_err(|e| Error::Schema(format!("cannot read {origin}: {e}")))?;
176 let rows = if path.extension().and_then(|e| e.to_str()) == Some("csv") {
177 csv_rows(&text)
178 } else {
179 toml_rows(&text)
180 }
181 .map_err(|e| Error::Schema(format!("{origin}: {e}")))?;
182
183 let password_field = r.auth.as_ref().map(|a| a.password_field.clone());
184 let table = quote_ident(&r.table_name())?;
185 let mut inserted = 0u64;
186 let mut skipped = 0u64;
187
188 for (index, row) in rows.into_iter().enumerate() {
189 let position = index + 1;
190 let mut columns: Vec<String> = Vec::new();
191 let mut params: Vec<SqlValue> = Vec::new();
192 let mut id = None;
193
194 for (column, raw) in row {
195 let known = column == "id"
196 || r.fields.contains_key(&column)
197 || (column == "password" && password_field.is_some());
198 if !known {
199 return Err(Error::Schema(format!(
200 "{origin}: row {position}: `{column}` is not a field of `{}`",
201 r.meta.name
202 )));
203 }
204 if column == "id" {
205 id = Some(uuid_for(&as_key(&raw).map_err(|e| {
206 Error::Schema(format!("{origin}: row {position}: `id`: {e}"))
207 })?));
208 continue;
209 }
210 if Some(column.as_str()) == password_field.as_deref() {
211 return Err(Error::Schema(format!(
212 "{origin}: row {position}: set `password` rather than `{column}` — \
213 seeding hashes it"
214 )));
215 }
216 if column == "password" {
217 let field = password_field.as_deref().expect("checked just above");
218 let plaintext = as_key(&raw)
219 .map_err(|e| Error::Schema(format!("{origin}: row {position}: {e}")))?;
220 let hash = apiplant_auth::Authenticator::hash_password_with_argon2(&plaintext)
221 .map_err(|e| Error::Schema(format!("{origin}: row {position}: {e}")))?;
222 columns.push(field.to_string());
223 params.push(SqlValue::from(hash));
224 continue;
225 }
226
227 let field = &r.fields[&column];
228 let sql = to_sql(field.ty, &raw)
229 .map_err(|e| Error::Schema(format!("{origin}: row {position}: `{column}`: {e}")))?;
230 let Some(sql) = sql else { continue };
231 columns.push(column);
232 params.push(sql);
233 }
234
235 let id = id.unwrap_or_else(|| uuid_for(&format!("{}#{position}", r.meta.name)));
239 columns.insert(0, "id".to_string());
240 params.insert(0, SqlValue::from(id));
241
242 let quoted: Vec<String> = columns
243 .iter()
244 .map(|c| quote_ident(c))
245 .collect::<Result<_, _>>()?;
246 let placeholders: Vec<String> = (1..=quoted.len()).map(|n| format!("${n}")).collect();
247 let sql = format!(
248 "INSERT INTO {table} ({}) VALUES ({}) ON CONFLICT (\"id\") DO NOTHING",
249 quoted.join(", "),
250 placeholders.join(", ")
251 );
252 let result = conn
253 .execute(Statement::from_sql_and_values(
254 DatabaseBackend::Postgres,
255 sql,
256 params,
257 ))
258 .await?;
259 if result.rows_affected() > 0 {
260 inserted += 1;
261 } else {
262 skipped += 1;
263 }
264 }
265
266 Ok(FileReport {
267 resource: r.meta.name.clone(),
268 inserted,
269 skipped,
270 })
271}
272
273fn as_key(raw: &Raw) -> Result<String, String> {
275 match raw {
276 Raw::Text(s) => Ok(s.clone()),
277 Raw::Typed(Json::String(s)) => Ok(s.clone()),
278 Raw::Typed(_) => Err("expected a string".to_string()),
279 }
280}
281
282fn to_sql(ty: FieldType, raw: &Raw) -> Result<Option<SqlValue>, String> {
285 if matches!(ty, FieldType::Reference | FieldType::Uuid) {
288 return Ok(Some(SqlValue::from(uuid_for(&as_key(raw)?))));
289 }
290 Ok(Some(match raw {
291 Raw::Text(s) if s.is_empty() => return Ok(None),
292 Raw::Text(s) if ty == FieldType::Json => {
294 SqlValue::from(serde_json::from_str::<Json>(s).map_err(|e| format!("not JSON: {e}"))?)
295 }
296 Raw::Text(s) => value::string_to_sql(ty, s)?,
297 Raw::Typed(Json::Null) => return Ok(None),
298 Raw::Typed(v)
302 if matches!(ty, FieldType::String | FieldType::Text | FieldType::File)
303 && !v.is_string() =>
304 {
305 match v {
306 Json::Object(_) | Json::Array(_) => return Err("expected a string".to_string()),
307 other => SqlValue::from(other.to_string()),
308 }
309 }
310 Raw::Typed(v) => value::json_to_sql(ty, v)?,
311 }))
312}
313
314fn toml_rows(text: &str) -> Result<Vec<Row>, String> {
320 let doc: toml::Value = toml::from_str(text).map_err(|e| e.to_string())?;
321 let table = doc
322 .as_table()
323 .ok_or("expected a table of `[[row]]` entries")?;
324 for key in table.keys() {
325 if key != "row" {
326 return Err(format!(
327 "`{key}` is not `row` — a seed file is a list of `[[row]]` tables"
328 ));
329 }
330 }
331 let Some(rows) = table.get("row") else {
332 return Ok(Vec::new());
333 };
334 let rows = rows
335 .as_array()
336 .ok_or("`row` must be written as `[[row]]` tables")?;
337
338 rows.iter()
339 .enumerate()
340 .map(|(index, row)| {
341 let row = row
342 .as_table()
343 .ok_or_else(|| format!("row {} is not a table", index + 1))?;
344 Ok(row
345 .iter()
346 .map(|(k, v)| (k.clone(), Raw::Typed(toml_to_json(v))))
347 .collect())
348 })
349 .collect()
350}
351
352fn toml_to_json(v: &toml::Value) -> Json {
354 match v {
355 toml::Value::String(s) => Json::String(s.clone()),
356 toml::Value::Integer(i) => Json::from(*i),
357 toml::Value::Float(f) => Json::from(*f),
358 toml::Value::Boolean(b) => Json::Bool(*b),
359 toml::Value::Datetime(d) => Json::String(d.to_string()),
361 toml::Value::Array(items) => Json::Array(items.iter().map(toml_to_json).collect()),
362 toml::Value::Table(t) => Json::Object(
363 t.iter()
364 .map(|(k, v)| (k.clone(), toml_to_json(v)))
365 .collect(),
366 ),
367 }
368}
369
370fn csv_rows(text: &str) -> Result<Vec<Row>, String> {
373 let records = parse_csv(text)?;
374 let mut records = records.into_iter();
375 let Some(header) = records.next() else {
376 return Ok(Vec::new());
377 };
378 let header: Vec<String> = header
379 .into_iter()
380 .map(|c| c.text.trim().to_string())
381 .collect();
382
383 records
384 .enumerate()
385 .map(|(index, record)| {
386 if record.len() > header.len() {
387 return Err(format!(
388 "row {}: {} values for {} columns",
389 index + 1,
390 record.len(),
391 header.len()
392 ));
393 }
394 Ok(header
395 .iter()
396 .cloned()
397 .zip(record)
398 .filter(|(_, cell)| !cell.text.is_empty() || cell.quoted)
403 .map(|(column, cell)| (column, Raw::Text(cell.text)))
404 .collect())
405 })
406 .collect()
407}
408
409pub fn uuid_for(key: &str) -> Uuid {
416 if let Ok(uuid) = Uuid::parse_str(key) {
417 return uuid;
418 }
419 let digest = apiplant_auth::Authenticator::hash_api_key(&format!("apiplant-seed:{key}"));
420 let mut bytes = [0u8; 16];
421 for (i, byte) in bytes.iter_mut().enumerate() {
422 *byte = u8::from_str_radix(&digest[i * 2..i * 2 + 2], 16).unwrap_or(0);
424 }
425 bytes[6] = (bytes[6] & 0x0f) | 0x80;
429 bytes[8] = (bytes[8] & 0x3f) | 0x80;
430 Uuid::from_bytes(bytes)
431}
432
433#[derive(Debug, Clone, PartialEq, Eq)]
435struct Cell {
436 text: String,
437 quoted: bool,
438}
439
440fn parse_csv(text: &str) -> Result<Vec<Vec<Cell>>, String> {
446 let mut rows: Vec<Vec<Cell>> = Vec::new();
447 let mut row: Vec<Cell> = Vec::new();
448 let mut cell = String::new();
449 let mut quoted = false;
450 let mut in_quotes = false;
451 let mut at_line_start = true;
454 let mut chars = text.chars().peekable();
455
456 while let Some(c) = chars.next() {
457 if at_line_start {
458 if c == '#' {
459 for c in chars.by_ref() {
460 if c == '\n' {
461 break;
462 }
463 }
464 continue;
465 }
466 if c == '\n' {
467 continue;
468 }
469 if c == '\r' && chars.peek() == Some(&'\n') {
470 chars.next();
471 continue;
472 }
473 at_line_start = false;
474 }
475
476 if in_quotes {
477 if c == '"' {
478 if chars.peek() == Some(&'"') {
479 chars.next();
480 cell.push('"');
481 } else {
482 in_quotes = false;
483 }
484 } else {
485 cell.push(c);
486 }
487 continue;
488 }
489
490 match c {
491 '"' if cell.is_empty() => {
492 in_quotes = true;
493 quoted = true;
494 }
495 '"' => return Err("a quote may only open a field".to_string()),
496 ',' => row.push(Cell {
497 text: std::mem::take(&mut cell),
498 quoted: std::mem::take(&mut quoted),
499 }),
500 '\r' if chars.peek() == Some(&'\n') => {}
501 '\n' => {
502 row.push(Cell {
503 text: std::mem::take(&mut cell),
504 quoted: std::mem::take(&mut quoted),
505 });
506 rows.push(std::mem::take(&mut row));
507 at_line_start = true;
508 }
509 _ => cell.push(c),
510 }
511 }
512
513 if in_quotes {
514 return Err("a quoted field was never closed".to_string());
515 }
516 if !cell.is_empty() || quoted || !row.is_empty() {
518 row.push(Cell { text: cell, quoted });
519 rows.push(row);
520 }
521 Ok(rows)
522}
523
524#[cfg(test)]
525mod tests {
526 use super::*;
527
528 fn cells(row: &[Cell]) -> Vec<&str> {
529 row.iter().map(|c| c.text.as_str()).collect()
530 }
531
532 fn column<'a>(row: &'a Row, name: &str) -> &'a Raw {
533 &row.iter().find(|(c, _)| c == name).expect("column").1
534 }
535
536 #[test]
537 fn parses_quotes_commas_and_newlines() {
538 let rows = parse_csv("a,b\n1,\"two, and\"\n\"line\nbreak\",\"say \"\"hi\"\"\"\n").unwrap();
539 assert_eq!(cells(&rows[0]), ["a", "b"]);
540 assert_eq!(cells(&rows[1]), ["1", "two, and"]);
541 assert_eq!(cells(&rows[2]), ["line\nbreak", "say \"hi\""]);
542 }
543
544 #[test]
545 fn comments_and_blank_lines_are_skipped() {
546 let rows = parse_csv("# a note\nname\n\nacme\n").unwrap();
547 assert_eq!(rows.len(), 2);
548 assert_eq!(cells(&rows[1]), ["acme"]);
549 }
550
551 #[test]
552 fn an_empty_csv_cell_is_left_out_but_an_empty_string_is_not() {
553 let rows = csv_rows("a,b\n,\"\"\n").unwrap();
554 assert!(rows[0].iter().all(|(c, _)| c != "a"));
555 assert!(matches!(column(&rows[0], "b"), Raw::Text(s) if s.is_empty()));
556 }
557
558 #[test]
559 fn a_final_row_without_a_newline_still_counts() {
560 assert_eq!(parse_csv("a\n1").unwrap().len(), 2);
561 }
562
563 #[test]
564 fn an_unterminated_quote_is_an_error() {
565 assert!(parse_csv("a\n\"oops\n").is_err());
566 }
567
568 #[test]
569 fn toml_rows_are_read_in_order_with_their_types() {
570 let rows = toml_rows(
571 r#"
572 [[row]]
573 id = "acme"
574 name = "Acme, Inc."
575 seats = 12
576 active = true
577
578 [[row]]
579 id = "globex"
580 name = "Globex"
581 "#,
582 )
583 .unwrap();
584 assert_eq!(rows.len(), 2);
585 assert!(matches!(
586 column(&rows[0], "seats"),
587 Raw::Typed(Json::Number(_))
588 ));
589 assert!(matches!(
590 column(&rows[0], "active"),
591 Raw::Typed(Json::Bool(true))
592 ));
593 assert!(matches!(column(&rows[1], "id"), Raw::Typed(Json::String(s)) if s == "globex"));
594 }
595
596 #[test]
597 fn a_toml_file_that_is_not_rows_says_so() {
598 let err = toml_rows("[[organization]]\nname = \"Acme\"\n").unwrap_err();
599 assert!(err.contains("`[[row]]`"), "{err}");
600 }
601
602 #[test]
603 fn a_toml_datetime_becomes_a_timestamp() {
604 let rows = toml_rows("[[row]]\nat = 2024-01-31T09:00:00Z\n").unwrap();
605 let sql = to_sql(FieldType::Timestamp, column(&rows[0], "at")).unwrap();
606 assert!(sql.is_some());
607 }
608
609 #[test]
610 fn a_number_is_accepted_where_a_string_column_wants_one() {
611 let rows = toml_rows("[[row]]\npostcode = 90210\n").unwrap();
612 let sql = to_sql(FieldType::String, column(&rows[0], "postcode")).unwrap();
613 assert_eq!(sql, Some(SqlValue::from("90210".to_string())));
614 }
615
616 #[test]
617 fn aliases_are_stable_and_uuids_pass_through() {
618 assert_eq!(uuid_for("acme"), uuid_for("acme"));
619 assert_ne!(uuid_for("acme"), uuid_for("globex"));
620 let explicit = "0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0";
621 assert_eq!(uuid_for(explicit).to_string(), explicit);
622 let derived = uuid_for("acme");
624 assert_eq!(derived.get_version_num(), 8);
625 assert_eq!(derived.as_bytes()[8] & 0xc0, 0x80);
626 }
627}