Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/object_import.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 7 minutes ago History
object_import.py · 31.2 KB · 781 lines
1"""Generic import/export for TSV-backed collections.
2
3Implements the CLI-scale slice of plan/vocabulary/13-import-export-spec.md
4("the import/export block"): point a JSON/CSV/TSV source at a collection,
5map its columns, dry-run every row against the target schema before
6anything is written, then write via the ordinary record API so schema
7rules and universal attribution apply exactly as a hand-typed form would.
8The HTTP wizard, saved `import_recipes`/`import_runs` collections, chunked
9execute, and the classic-mode bulk-rewrite entry point that spec also
10describes are out of scope here -- this is the stdlib CLI half.
11
12RUN CONFIG (a JSON file passed to ``run``): one file describes a whole
13import run -- the collections it touches, in dependency order, and how
14each collection's source rows map onto its schema.
15
16 {
17 "order": ["legacy_crm_orgs", "legacy_crm_contacts"],
18 "collections": {
19 "legacy_crm_orgs": {
20 "input": "orgs.json",
21 "mapping": {"OrgId": "id", "OrgName": "name"},
22 "constants": {"owner_id": "u_import"}
23 },
24 "legacy_crm_contacts": {
25 "input": "contacts.csv",
26 "mapping": {
27 "ContactId": "id",
28 "FullName": "name",
29 "OrgId": "org_id",
30 "Urgency": "urgency",
31 "LegacyNotes": "extra"
32 },
33 "extra_fields": ["InternalRefCode"],
34 "ignore_fields": ["RowNumber"],
35 "value_maps": [{"field": "urgency", "map": {"medium": "normal"}}],
36 "constants": {"owner_id": "u_import"}
37 }
38 }
39 }
40
41Per collection:
42
43- ``input`` -- path to the source file (relative paths resolve against the
44 run config's own directory). Format is inferred from the extension
45 (``.json``/``.csv``/``.tsv``); a JSON source is a list of flat objects.
46- ``mapping`` -- ``{source_column: dest_field}``. Every source column must
47 be accounted for by ``mapping``, ``extra_fields``, or ``ignore_fields``;
48 an unmapped column is a dry-run error ("unknown fields not covered by
49 mapping" -- see the module-level note under Spec Conflicts below), not a
50 silent drop. Map a column to ``"id"`` to supply the record id (source
51 ids are kept exactly -- see ID Preservation below); map one to
52 ``"extra"`` to route it into the record's JSON overflow field under its
53 own source-column name.
54- ``extra_fields`` -- source columns routed into ``extra`` the same way,
55 spelled as a plain list instead of repeating ``"extra"`` in ``mapping``
56 for every one.
57- ``ignore_fields`` -- source columns intentionally dropped (e.g. a
58 spreadsheet's own row-number column).
59- ``value_maps`` -- ``[{"field": dest_field, "map": {source_value:
60 dest_value}}]``, applied to the mapped/renamed value.
61- ``constants`` -- ``{dest_field: value}`` stamped onto every row,
62 overriding whatever the row itself supplied (e.g. attributing every
63 imported record to one operator-chosen owner).
64
65ID PRESERVATION: whatever a row resolves as ``id`` (via ``mapping`` or a
66constant) is written exactly as given -- object_import never generates a
67fresh id, because other collections in the same run (and existing data)
68may already reference it.
69
70CREATED_AT PRESERVATION: a schema's ``created_at`` is ordinarily
71``read_only`` -- object_records.create_collection_record rejects a
72client-submitted value for it, same as any other read-only field, so a
73hand-typed form can never spoof "created two years ago". An import
74replaying another system's history needs the opposite: the source row's
75own timestamp, not "now". Real-run creates in this module always pass
76``create_collection_record(..., preserve_read_only=True)`` -- a new,
77narrowly-scoped kwarg added to object_records.py alongside this module
78(see its docstring) that allows a *plain* read-only field's submitted
79value through while still rejecting a genuinely ``computed`` field. Map a
80source column to ``created_at`` (or any other read-only-but-not-computed
81field) in the mapping and its value is preserved verbatim; leave it
82unmapped and the server stamps "now", exactly as an ordinary create would.
83Updates (the ``--update-existing`` duplicate path) never touch read-only
84fields, preserved or not -- an existing record's own history shouldn't
85shift just because a repeat import touched other fields on it.
86
87COMPUTED FIELDS AND ROUND-TRIPS: ``export`` emits every field the read API
88returns, computed ones (rollups, formulas) included. A computed value is
89derived by the target, so importing one is meaningless; rather than refuse
90the row (which, in a run with linked collections, cascades into every row
91whose relation points at it), ``run`` drops computed fields and says so in
92the report (``notes``, per collection and per row). A collection config
93with ``"identity": true`` maps each source column that is a schema field to
94the same-named field, so an export is a valid input with no mapping written;
95a column that is not a field stays an unmapped-column error.
96
97SPEC CONFLICTS (13-import-export-spec.md vs. this module, per the task
98that produced it -- the task wins, noted here for the record):
99
100- The spec's ``import_recipes.mapping`` auto-routes any source column
101 *absent* from the map into ``extra`` by default. This module instead
102 requires every source column to be explicitly accounted for (mapping /
103 extra_fields / ignore_fields) and reports an unmapped column as a
104 dry-run error, per this task's explicit "unknown fields not covered by
105 mapping" validation requirement.
106- No ``import_recipes``/``import_runs`` collections, no chunked/resumable
107 execute, no classic-mode bulk-rewrite entry point, no delimiter/encoding
108 sniffing, no ``partial_import_policy`` toggle (a row that fails
109 validation is always skipped-and-reported; valid rows in the same file
110 are always still written -- there is no "block the whole run" mode
111 here). All namable "implementation-session decisions" the spec's Open
112 Questions section explicitly deferred; this module is the narrower CLI
113 slice the task asked for, not the full block.
114"""
115
116from __future__ import annotations
117
118import argparse
119import csv
120import json
121import os
122import sys
123from dataclasses import dataclass, field as dataclass_field
124from pathlib import Path
125from typing import Any, Iterable
126
127import object_collections
128import object_record_changes
129import object_records
130import object_schemas
131from object_versions import DEFAULT_DATA_DIR
132
133DATA_DIR_ENV = "DBBASIC_DATA_DIR"
134EXTRA_ROUTE = "extra"
135SOURCE_FORMATS = {"json", "csv", "tsv"}
136
137
138class ImportConfigError(ValueError):
139 """Raised when a run config or a collection's mapping is malformed."""
140
141
142class ImportRunError(ValueError):
143 """Raised when a run itself can't proceed (e.g. no --actor for a real run)."""
144
145
146# --------------------------------------------------------------------------
147# Run config
148# --------------------------------------------------------------------------
149
150def load_plan(config_path: Path) -> dict[str, Any]:
151 """Load and normalize a run config: ``{"order": [...], "collections": {...}}``."""
152 config_path = Path(config_path)
153 try:
154 payload = json.loads(config_path.read_text(encoding="utf-8"))
155 except FileNotFoundError as exc:
156 raise ImportConfigError(f"Run config not found: {config_path}") from exc
157 except json.JSONDecodeError as exc:
158 raise ImportConfigError(f"Run config is not valid JSON: {config_path} ({exc})") from exc
159
160 if not isinstance(payload, dict):
161 raise ImportConfigError("Run config must be a JSON object")
162
163 order = payload.get("order")
164 if not isinstance(order, list) or not order or not all(isinstance(item, str) and item for item in order):
165 raise ImportConfigError("Run config 'order' must be a non-empty list of collection names")
166
167 collections = payload.get("collections")
168 if not isinstance(collections, dict):
169 raise ImportConfigError("Run config 'collections' must be an object")
170
171 missing = [name for name in order if name not in collections]
172 if missing:
173 raise ImportConfigError(f"Run config 'order' names collections with no config: {missing}")
174
175 base = config_path.resolve().parent
176 normalized = {
177 name: _normalize_collection_config(name, collections[name], base=base) for name in order
178 }
179 return {"order": list(order), "collections": normalized}
180
181
182def _normalize_collection_config(name: str, raw: Any, *, base: Path) -> dict[str, Any]:
183 if not isinstance(raw, dict):
184 raise ImportConfigError(f"Collection config for {name!r} must be an object")
185
186 input_value = raw.get("input")
187 if not isinstance(input_value, str) or not input_value:
188 raise ImportConfigError(f"Collection config for {name!r} is missing 'input'")
189 input_path = Path(input_value)
190 if not input_path.is_absolute():
191 input_path = base / input_path
192
193 fmt = raw.get("format")
194 if fmt is not None and fmt not in SOURCE_FORMATS:
195 raise ImportConfigError(f"Collection config for {name!r} has an unknown 'format': {fmt!r}")
196
197 mapping = raw.get("mapping") or {}
198 if not isinstance(mapping, dict) or not all(isinstance(v, str) for v in mapping.values()):
199 raise ImportConfigError(f"Collection config for {name!r}: 'mapping' must be an object of strings")
200
201 extra_fields = raw.get("extra_fields") or []
202 ignore_fields = raw.get("ignore_fields") or []
203 value_maps = raw.get("value_maps") or []
204 constants = raw.get("constants") or {}
205 if not isinstance(value_maps, list):
206 raise ImportConfigError(f"Collection config for {name!r}: 'value_maps' must be a list")
207 if not isinstance(constants, dict):
208 raise ImportConfigError(f"Collection config for {name!r}: 'constants' must be an object")
209
210 return {
211 "collection": name,
212 "input": input_path,
213 "format": fmt,
214 "mapping": dict(mapping),
215 "extra_fields": list(extra_fields),
216 "ignore_fields": list(ignore_fields),
217 "value_maps": list(value_maps),
218 "constants": dict(constants),
219 # An export is its own input: every source column that is a field of
220 # the schema maps to the same-named field, with no per-column
221 # mapping to write. Columns that are NOT fields stay unmapped (and
222 # are reported as such), so a typo still fails loudly.
223 "identity": bool(raw.get("identity")),
224 }
225
226
227# --------------------------------------------------------------------------
228# Source loading
229# --------------------------------------------------------------------------
230
231def load_source_rows(path: Path, fmt: str | None = None) -> list[dict[str, Any]]:
232 """Return a source file's rows as plain dicts. JSON: a list of objects. CSV/TSV: DictReader rows."""
233 path = Path(path)
234 fmt = fmt or _infer_format(path)
235 if fmt == "json":
236 try:
237 payload = json.loads(path.read_text(encoding="utf-8"))
238 except FileNotFoundError as exc:
239 raise ImportConfigError(f"Import source not found: {path}") from exc
240 except json.JSONDecodeError as exc:
241 raise ImportConfigError(f"Import source is not valid JSON: {path} ({exc})") from exc
242 if not isinstance(payload, list):
243 raise ImportConfigError(f"JSON import source must be a list of records: {path}")
244 rows = []
245 for index, row in enumerate(payload, start=1):
246 if not isinstance(row, dict):
247 raise ImportConfigError(f"JSON import source row {index} is not an object: {path}")
248 rows.append(row)
249 return rows
250
251 delimiter = "\t" if fmt == "tsv" else ","
252 try:
253 with path.open(newline="", encoding="utf-8") as handle:
254 reader = csv.DictReader(handle, delimiter=delimiter)
255 return [dict(row) for row in reader]
256 except FileNotFoundError as exc:
257 raise ImportConfigError(f"Import source not found: {path}") from exc
258
259
260def _infer_format(path: Path) -> str:
261 suffix = path.suffix.lower().lstrip(".")
262 if suffix not in SOURCE_FORMATS:
263 raise ImportConfigError(
264 f"Cannot infer source format from extension (expected .json/.csv/.tsv): {path}"
265 )
266 return suffix
267
268
269# --------------------------------------------------------------------------
270# Row mapping
271# --------------------------------------------------------------------------
272
273def map_row(source_row: dict[str, Any], cfg: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
274 """Apply one collection's rename/extra/value-map/constant rules to a source row.
275
276 Returns ``(dest_record, errors)``. ``dest_record`` is the payload
277 object_records would receive; ``errors`` covers mapping-time problems
278 (an unmapped column, no resolvable id) -- schema-level checks
279 (required/enum/relation) happen later in ``validate_row``, once the
280 target schema is known.
281 """
282 errors: list[str] = []
283 mapping: dict[str, str] = cfg["mapping"]
284 extra_fields = set(cfg["extra_fields"])
285 ignore_fields = set(cfg["ignore_fields"])
286
287 dest: dict[str, Any] = {}
288 extra_blob: dict[str, Any] = {}
289
290 for source_col, value in source_row.items():
291 if source_col in mapping:
292 dest_name = mapping[source_col]
293 if dest_name == EXTRA_ROUTE:
294 extra_blob[source_col] = value
295 else:
296 dest[dest_name] = value
297 elif source_col in extra_fields:
298 extra_blob[source_col] = value
299 elif source_col in ignore_fields:
300 continue
301 else:
302 errors.append(
303 f"unmapped source column {source_col!r} (add it to mapping, "
304 "extra_fields, or ignore_fields)"
305 )
306
307 for rule in cfg["value_maps"]:
308 if not isinstance(rule, dict):
309 continue
310 target_field = rule.get("field")
311 value_map = rule.get("map") or {}
312 if target_field in dest:
313 raw = dest[target_field]
314 raw_str = "" if raw is None else str(raw)
315 if raw_str in value_map:
316 dest[target_field] = value_map[raw_str]
317
318 for const_name, const_value in cfg["constants"].items():
319 dest[const_name] = const_value
320
321 if dest.get("id") in (None, ""):
322 errors.append('row has no resolvable "id" (map a source column to "id" in the mapping)')
323 else:
324 dest["id"] = str(dest["id"])
325
326 if extra_blob:
327 dest["extra"] = extra_blob
328
329 return dest, errors
330
331
332# --------------------------------------------------------------------------
333# Row validation (dry-run and real-run share this)
334# --------------------------------------------------------------------------
335
336def _is_computed_field(field: dict[str, Any]) -> bool:
337 field_type = str(field.get("type", "")).lower()
338 return bool(field_type == "computed" or field.get("computed"))
339
340
341def _is_empty(value: str) -> bool:
342 return value is None or value == ""
343
344
345def validate_row(
346 collection: str,
347 dest: dict[str, Any],
348 *,
349 base_dir: Path,
350 roots: Iterable[Path] | None,
351 known_ids: dict[str, set[str]],
352) -> list[str]:
353 """Validate one mapped row against the target schema's field rules.
354
355 Reuses object_records' own private per-field checks (type/enum/
356 validation-rule/relation) directly, rather than re-deriving them --
357 there is no public dry-run validator yet (13-import-export-spec.md's
358 own Open Questions section names this exact gap: "Dry-run validation
359 needs a new public entry point"). Reusing the private functions means
360 a validation error here is worded identically to what a real write
361 would raise, same as the spec wants; a future public
362 ``validate_record_payload`` can replace this call site without
363 changing behavior.
364
365 Relation checks are widened for "target existence within the run": a
366 relation to a row from an earlier (or the same) collection in this run
367 that has already validated is accepted even though nothing has been
368 written yet -- ``known_ids`` accumulates as the run proceeds, seeded
369 per collection with whatever already exists on disk.
370 """
371 errors: list[str] = []
372 record_id = str(dest.get("id", ""))
373 if not object_records.validate_record_id(record_id):
374 errors.append(f"invalid record id: {record_id!r}")
375
376 fields = object_records._schema_fields(collection, base_dir=base_dir, roots=roots)
377 submitted = frozenset(dest)
378
379 for schema_field in fields:
380 name = schema_field["name"]
381 if name == "id":
382 continue
383 raw_value = dest.get(name, "")
384 value = "" if raw_value is None else str(raw_value)
385 read_only = object_records._is_computed_or_read_only(schema_field)
386 computed = _is_computed_field(schema_field)
387
388 if name in submitted and read_only:
389 if computed:
390 errors.append(f"field '{name}' is computed and cannot be imported")
391 continue
392 # Plain read-only (not computed): allowed here. A real run
393 # carries it through via create_collection_record(...,
394 # preserve_read_only=True) -- see the module docstring.
395
396 if object_records._field_is_required(schema_field) and not read_only and _is_empty(value):
397 errors.append(f"field '{name}' is required")
398 continue
399 if _is_empty(value):
400 continue
401
402 try:
403 object_records._validate_field_type(schema_field, value)
404 object_records._validate_field_enum(schema_field, value)
405 object_records._validate_field_rules(schema_field, value)
406 except object_records.InvalidRecordPayloadError as exc:
407 errors.append(str(exc))
408 continue
409
410 relation_error = _check_relation(schema_field, value, known_ids=known_ids, base_dir=base_dir)
411 if relation_error:
412 errors.append(relation_error)
413
414 return errors
415
416
417def _check_relation(
418 schema_field: dict[str, Any],
419 value: str,
420 *,
421 known_ids: dict[str, set[str]],
422 base_dir: Path,
423) -> str | None:
424 relation = schema_field.get("relation")
425 if relation is None:
426 return None
427 target = relation.get("collection") if isinstance(relation, dict) else relation
428 if isinstance(target, str) and value in known_ids.get(target, ()):
429 return None
430 try:
431 object_records._validate_field_relation(schema_field, value, base_dir=base_dir)
432 except object_records.InvalidRecordPayloadError as exc:
433 return str(exc)
434 return None
435
436
437# --------------------------------------------------------------------------
438# Reporting
439# --------------------------------------------------------------------------
440
441@dataclass
442class RowOutcome:
443 row_number: int
444 id: str
445 status: str # "ok" | "exists" | "error" -- validation-time classification, never mutated
446 reasons: list[str]
447 action: str | None = None # "created" | "updated" | "skipped" -- set only on a real run
448 notes: list[str] = dataclass_field(default_factory=list) # non-fatal: e.g. computed fields skipped
449
450
451@dataclass
452class CollectionReport:
453 collection: str
454 total: int = 0
455 ok: int = 0
456 exists: int = 0
457 errors: int = 0
458 created: int = 0
459 updated: int = 0
460 skipped: int = 0
461 rows: list[RowOutcome] = dataclass_field(default_factory=list)
462 # Collection-level, non-fatal notes (a computed field was skipped on N rows).
463 notes: list[str] = dataclass_field(default_factory=list)
464
465 def to_dict(self) -> dict[str, Any]:
466 return {
467 "collection": self.collection,
468 "total": self.total,
469 "ok": self.ok,
470 "exists": self.exists,
471 "errors": self.errors,
472 "created": self.created,
473 "updated": self.updated,
474 "skipped": self.skipped,
475 "notes": self.notes,
476 "rows": [
477 {
478 "row": row.row_number,
479 "id": row.id,
480 "status": row.status,
481 "reasons": row.reasons,
482 "action": row.action,
483 "notes": row.notes,
484 }
485 for row in self.rows
486 ],
487 }
488
489
490# --------------------------------------------------------------------------
491# Run orchestration
492# --------------------------------------------------------------------------
493
494def run_import(
495 plan: dict[str, Any],
496 *,
497 base_dir: Path,
498 roots: Iterable[Path] | None = None,
499 dry_run: bool,
500 actor: str | None = None,
501 update_existing: bool = False,
502) -> list[CollectionReport]:
503 """Validate (and, unless ``dry_run``, write) every collection in a run's order.
504
505 Nothing is written for a collection until every row in it has been
506 mapped and validated; only rows without errors are ever passed to
507 create/update. Duplicate ids are checked twice, at different scopes:
508 within the source file itself (two rows claiming the same id is
509 always an error) and against the target collection's existing ids
510 (idempotency -- ``exists``, resolved to skip or update below).
511 """
512 if not dry_run and not actor:
513 raise ImportRunError("actor is required for a real run (pass --actor, or use --dry-run)")
514
515 known_ids: dict[str, set[str]] = {}
516 reports: list[CollectionReport] = []
517
518 for collection in plan["order"]:
519 cfg = plan["collections"][collection]
520 source_rows = load_source_rows(cfg["input"], cfg["format"])
521
522 existing_ids = _existing_ids(collection, base_dir=base_dir, roots=roots)
523 known_ids.setdefault(collection, set()).update(existing_ids)
524
525 report = CollectionReport(collection=collection, total=len(source_rows))
526 seen_in_file: set[str] = set()
527 valid_rows: dict[int, dict[str, Any]] = {}
528 schema_fields = _schema_fields_or_empty(collection, base_dir=base_dir, roots=roots)
529 computed_names = {f["name"] for f in schema_fields if _is_computed_field(f)}
530 if cfg.get("identity"):
531 cfg = _with_identity_mapping(cfg, source_rows, {f["name"] for f in schema_fields})
532 skipped_computed: dict[str, int] = {}
533
534 for row_number, source_row in enumerate(source_rows, start=1):
535 dest, reasons = map_row(source_row, cfg)
536 # A computed field is derived by the target (a rollup, a
537 # formula): an export carries its value, and importing it would
538 # be refused. It is dropped, and said so -- not an error.
539 dropped = [name for name in dest if name in computed_names]
540 for name in dropped:
541 del dest[name]
542 skipped_computed[name] = skipped_computed.get(name, 0) + 1
543 record_id = str(dest.get("id", ""))
544
545 if reasons:
546 report.rows.append(RowOutcome(row_number, record_id, "error", reasons))
547 report.errors += 1
548 continue
549
550 if record_id in seen_in_file:
551 report.rows.append(
552 RowOutcome(
553 row_number, record_id, "error",
554 [f"duplicate id within import file: {record_id}"],
555 )
556 )
557 report.errors += 1
558 continue
559
560 row_errors = validate_row(
561 collection, dest, base_dir=base_dir, roots=roots, known_ids=known_ids
562 )
563 if row_errors:
564 report.rows.append(RowOutcome(row_number, record_id, "error", row_errors))
565 report.errors += 1
566 continue
567
568 seen_in_file.add(record_id)
569 known_ids[collection].add(record_id)
570 status = "exists" if record_id in existing_ids else "ok"
571 report.rows.append(RowOutcome(
572 row_number, record_id, status, [],
573 notes=[f"computed field '{name}' skipped (derived by the target)"
574 for name in dropped]))
575 if status == "exists":
576 report.exists += 1
577 else:
578 report.ok += 1
579 valid_rows[row_number] = dest
580
581 report.notes = [
582 f"computed field '{name}' skipped on {count} row(s): the target derives it"
583 for name, count in sorted(skipped_computed.items())]
584
585 if not dry_run:
586 _execute_collection(
587 collection,
588 report,
589 valid_rows,
590 existing_ids=existing_ids,
591 base_dir=base_dir,
592 roots=roots,
593 actor=actor,
594 update_existing=update_existing,
595 )
596
597 reports.append(report)
598
599 return reports
600
601
602def _schema_fields_or_empty(collection: str, *, base_dir: Path,
603 roots: Iterable[Path] | None) -> list[dict[str, Any]]:
604 try:
605 return list(object_records._schema_fields(collection, base_dir=base_dir, roots=roots))
606 except Exception: # noqa: BLE001 -- validate_row reports a missing schema itself
607 return []
608
609
610def _with_identity_mapping(cfg: dict[str, Any], source_rows: list[dict[str, Any]],
611 field_names: set[str]) -> dict[str, Any]:
612 """The config with each source column that names a schema field mapped
613 to itself, unless the config already says what to do with that column."""
614 handled = set(cfg["mapping"]) | set(cfg["extra_fields"]) | set(cfg["ignore_fields"])
615 mapping = dict(cfg["mapping"])
616 for row in source_rows:
617 for column in row:
618 if column not in handled and (column in field_names or column == "id"):
619 mapping[column] = column
620 return {**cfg, "mapping": mapping}
621
622
623def _existing_ids(collection: str, *, base_dir: Path, roots: Iterable[Path] | None) -> set[str]:
624 try:
625 rows = object_records.read_collection_records(collection, base_dir=base_dir, roots=roots)
626 except (object_collections.CollectionNotFoundError, object_collections.InvalidCollectionNameError):
627 return set()
628 return {row["id"] for row in rows}
629
630
631def _execute_collection(
632 collection: str,
633 report: CollectionReport,
634 valid_rows: dict[int, dict[str, Any]],
635 *,
636 existing_ids: set[str],
637 base_dir: Path,
638 roots: Iterable[Path] | None,
639 actor: str,
640 update_existing: bool,
641) -> None:
642 for outcome in report.rows:
643 if outcome.status == "error":
644 continue
645 dest = valid_rows[outcome.row_number]
646 record_id = dest["id"]
647
648 if outcome.status == "exists":
649 if update_existing:
650 changes = {k: v for k, v in dest.items() if k != "id"}
651 changes = _strip_read_only(collection, changes, base_dir=base_dir, roots=roots)
652 object_records.update_collection_record(
653 collection, record_id, changes, base_dir=base_dir, roots=roots, actor=actor
654 )
655 outcome.action = "updated"
656 report.updated += 1
657 else:
658 outcome.action = "skipped"
659 report.skipped += 1
660 continue
661
662 object_records.create_collection_record(
663 collection, dest, base_dir=base_dir, roots=roots, actor=actor, preserve_read_only=True
664 )
665 outcome.action = "created"
666 report.created += 1
667
668
669def _strip_read_only(
670 collection: str, changes: dict[str, Any], *, base_dir: Path, roots: Iterable[Path] | None
671) -> dict[str, Any]:
672 fields = object_records._schema_fields(collection, base_dir=base_dir, roots=roots)
673 read_only_names = {f["name"] for f in fields if object_records._is_computed_or_read_only(f)}
674 return {name: value for name, value in changes.items() if name not in read_only_names}
675
676
677# --------------------------------------------------------------------------
678# Export
679# --------------------------------------------------------------------------
680
681def export_collection(
682 collection: str, *, base_dir: Path, roots: Iterable[Path] | None = None
683) -> list[dict[str, str]]:
684 """Return every record in a collection exactly as the read API returns it."""
685 return object_records.read_collection_records(collection, base_dir=base_dir, roots=roots)
686
687
688# --------------------------------------------------------------------------
689# CLI
690# --------------------------------------------------------------------------
691
692def main(argv: list[str] | None = None) -> int:
693 parser = argparse.ArgumentParser(
694 description="Import records into, or export them out of, TSV-backed collections."
695 )
696 parser.add_argument(
697 "--data-dir",
698 type=Path,
699 default=None,
700 help=f"runtime data directory (default: ${DATA_DIR_ENV} or ./data)",
701 )
702 subcommands = parser.add_subparsers(dest="command", required=True)
703
704 run = subcommands.add_parser("run", help="import records per a run config")
705 run.add_argument("config", type=Path, help="path to the run config JSON file")
706 run.add_argument("--dry-run", action="store_true", help="validate only; write nothing")
707 run.add_argument("--actor", help="required for a real run; attributed on every write")
708 run.add_argument(
709 "--update-existing",
710 action="store_true",
711 help="upsert rows whose id already exists in the target collection (default: skip them)",
712 )
713 run.add_argument("--json", action="store_true", help="print the report as JSON")
714
715 export = subcommands.add_parser("export", help="dump one collection to JSON")
716 export.add_argument("collection")
717 export.add_argument(
718 "--output", type=Path, default=None, help="write to this file instead of stdout"
719 )
720
721 args = parser.parse_args(argv)
722 base_dir = _base_dir(args.data_dir)
723
724 try:
725 if args.command == "run":
726 plan = load_plan(args.config)
727 reports = run_import(
728 plan,
729 base_dir=base_dir,
730 dry_run=args.dry_run,
731 actor=args.actor,
732 update_existing=args.update_existing,
733 )
734 _print_run_report(reports, json_output=args.json, dry_run=args.dry_run)
735 return 1 if any(report.errors for report in reports) else 0
736
737 if args.command == "export":
738 records = export_collection(args.collection, base_dir=base_dir)
739 payload = json.dumps(records, indent=2)
740 if args.output:
741 args.output.write_text(payload + "\n", encoding="utf-8")
742 print(f"Exported {len(records)} record(s) from {args.collection} to {args.output}")
743 else:
744 print(payload)
745 return 0
746 except (ImportConfigError, ImportRunError) as exc:
747 print(f"Error: {exc}", file=sys.stderr)
748 return 1
749 except (object_collections.CollectionNotFoundError, object_collections.InvalidCollectionNameError) as exc:
750 print(f"Error: {exc}", file=sys.stderr)
751 return 1
752
753 parser.error(f"Unknown command: {args.command}")
754 return 2
755
756
757def _base_dir(data_dir: Path | None) -> Path:
758 if data_dir is not None:
759 return data_dir
760 return Path(os.environ.get(DATA_DIR_ENV, "data"))
761
762
763def _print_run_report(reports: list[CollectionReport], *, json_output: bool, dry_run: bool) -> None:
764 if json_output:
765 print(json.dumps([report.to_dict() for report in reports], indent=2))
766 return
767
768 for report in reports:
769 summary = f"{report.collection}: {report.ok} ok, {report.exists} exists, {report.errors} errors"
770 if not dry_run:
771 summary += f" -- {report.created} created, {report.updated} updated, {report.skipped} skipped"
772 print(summary)
773 for note in report.notes:
774 print(f" note: {note}")
775 for row in report.rows:
776 if row.status == "error":
777 print(f" row {row.row_number} (id={row.id or '?'}): " + "; ".join(row.reasons))
778
779
780if __name__ == "__main__":
781 raise SystemExit(main())