"""CSV import and export. NULL is an empty field; booleans are written as ``true`` and ``false``. """ from __future__ import annotations import csv from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, TextIO from .errors import SchemaError from .schema import Schema, parse_text from .table import Predicate, Table def format_value(value: Any) -> str: if value is None: return "" if isinstance(value, bool): return "true" if value else "false" return str(value) def write_csv(rows: Iterable[Mapping[str, Any]], columns: Sequence[str], handle: TextIO) -> None: """Write a header line and one line per row, using ``\\n`` line endings.""" writer = csv.writer(handle, lineterminator="\n") writer.writerow(columns) for row in rows: writer.writerow([format_value(row[name]) for name in columns]) def read_csv(handle: TextIO, schema: Schema) -> List[Dict[str, Any]]: """Read rows written by :func:`write_csv`. An ``id`` column in the file is ignored.""" reader = csv.DictReader(handle) header = reader.fieldnames or [] for name in header: if not schema.has(name): raise SchemaError("unknown column in CSV header: %s" % name) rows = [] for record in reader: rows.append({ name: parse_text(schema.column(name), text) for name, text in record.items() if name != "id" and text is not None }) return rows def export_csv(table: Table, path: str, where: Optional[Predicate] = None, columns: Optional[Sequence[str]] = None) -> int: """Write the matching rows to ``path`` and return how many were written.""" names = list(columns) if columns else table.schema.names() rows = table.select(where=where, columns=names) with open(path, "w", encoding="utf-8", newline="") as handle: write_csv(rows, names, handle) return len(rows) def import_csv(table: Table, path: str) -> int: """Insert every row of the CSV file at ``path`` and return how many were added.""" with open(path, "r", encoding="utf-8", newline="") as handle: rows = read_csv(handle, table.schema) table.insert_many(rows) return len(rows)