Files
leleka/scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/cli.py
T

131 lines
5.5 KiB
Python

"""Command line interface: ``python3 -m minidb.cli --db FILE COMMAND ...``."""
from __future__ import annotations
import argparse
import sys
from typing import Any, Dict, List, Optional, Sequence, TextIO
from .csvio import export_csv, import_csv, write_csv
from .errors import MiniDBError, SchemaError
from .schema import Column, Schema, parse_text
from .storage import JsonFileStorage
from .table import Database, Table
def parse_column_spec(spec: str) -> Column:
"""``name:type`` or ``name:type:required`` (required columns may not be NULL)."""
parts = spec.split(":")
if len(parts) not in (2, 3) or (len(parts) == 3 and parts[2] != "required"):
raise SchemaError("bad column spec %r, expected name:type[:required]" % spec)
return Column(parts[0], parts[1], nullable=len(parts) == 2)
def parse_assignments(schema: Schema, items: Sequence[str]) -> Dict[str, Any]:
"""Turn ``['name=Ann', 'age=31']`` into typed values; ``age=`` sets NULL."""
values: Dict[str, Any] = {}
for item in items:
name, separator, text = item.partition("=")
if not separator:
raise SchemaError("expected column=value, got %r" % item)
values[name] = parse_text(schema.column(name), text)
return values
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="minidb", description="Work with a minidb JSON database file.")
parser.add_argument("--db", required=True, help="path of the database file (created on first write)")
commands = parser.add_subparsers(dest="command", required=True)
create = commands.add_parser("create", help="create a table")
create.add_argument("table")
create.add_argument("columns", nargs="+", metavar="name:type[:required]")
insert = commands.add_parser("insert", help="insert one row and print its id")
insert.add_argument("table")
insert.add_argument("assignments", nargs="+", metavar="column=value")
select = commands.add_parser("select", help="print rows as CSV")
select.add_argument("table")
select.add_argument("--columns", help="comma separated column names (default: all)")
select.add_argument("--order-by", dest="order_by", help="column to sort by")
select.add_argument("--desc", action="store_true", help="sort descending")
select.add_argument("--limit", type=int)
select.add_argument("--where", help="only rows for which this expression is true (see SPEC.md)")
update = commands.add_parser("update", help="change the row with the given id")
update.add_argument("table")
update_filter = update.add_mutually_exclusive_group(required=True)
update_filter.add_argument("--id", type=int, dest="row_id")
update_filter.add_argument("--where", help="update the rows for which this expression is true")
update.add_argument("assignments", nargs="+", metavar="column=value")
delete = commands.add_parser("delete", help="delete the row with the given id")
delete.add_argument("table")
delete_filter = delete.add_mutually_exclusive_group(required=True)
delete_filter.add_argument("--id", type=int, dest="row_id")
delete_filter.add_argument("--where", help="delete the rows for which this expression is true")
load = commands.add_parser("import-csv", help="append the rows of a CSV file")
load.add_argument("table")
load.add_argument("file")
dump = commands.add_parser("export-csv", help="write a table to a CSV file")
dump.add_argument("table")
dump.add_argument("file")
return parser
def _row_filter(args: argparse.Namespace):
"""The ``where`` argument for the table methods: the query text, or a test for one id."""
if args.where is not None:
return args.where
row_id = args.row_id
return lambda row: row["id"] == row_id
def run(args: argparse.Namespace, db: Database, out: TextIO) -> bool:
"""Execute one command; returns True when the database must be saved."""
if args.command == "create":
db.create_table(args.table, [parse_column_spec(spec) for spec in args.columns])
return True
table: Table = db.table(args.table)
if args.command == "insert":
print(table.insert(**parse_assignments(table.schema, args.assignments)), file=out)
return True
if args.command == "select":
names: Optional[List[str]] = args.columns.split(",") if args.columns else None
rows = table.select(where=args.where, columns=names, order_by=args.order_by, descending=args.desc, limit=args.limit)
write_csv(rows, names or table.schema.names(), out)
return False
if args.command == "update":
changed = table.update(parse_assignments(table.schema, args.assignments), where=_row_filter(args))
print("updated %d" % changed, file=out)
return True
if args.command == "delete":
removed = table.delete(where=_row_filter(args))
print("deleted %d" % removed, file=out)
return True
if args.command == "import-csv":
print("imported %d" % import_csv(table, args.file), file=out)
return True
print("exported %d" % export_csv(table, args.file), file=out)
return False
def main(argv: Optional[Sequence[str]] = None, out: Optional[TextIO] = None) -> int:
out = out if out is not None else sys.stdout
args = build_parser().parse_args(argv)
try:
db = Database(JsonFileStorage(args.db))
if run(args, db, out):
db.save()
except (MiniDBError, OSError) as exc:
print("error: %s" % exc, file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
sys.exit(main())