oc_chat
Loading...
Searching...
No Matches
db.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# oc_chat/registry/cli/db.py
4
5# OCT-LINT: disable=tests_exist reason="Covered by oc_chat/tests/registry/test_operator_tools_and_guards.py"
6"""
7Database operator commands for the orchestration registry.
8
9Purpose
10-------
11Expose read-only database health commands beneath
12``python -m oc_chat.registry db``.
13
14Responsibilities
15----------------
16- Wire the ``db integrity-check`` command.
17- Reserve future database operation names with explicit v0.2.x stubs.
18- Format structured integrity reports for humans or JSON consumers.
19
20Diagnostics
21-----------
22Domain: OC_CHAT.MAIN
23Levels:
24 L2 - lifecycle events
25 L3 - semantic details
26 L4 - deep tracing
27
28Contracts
29---------
30- ``integrity-check`` does not mutate logical registry state.
31- Reserved commands exit 2 with a clear not-implemented message.
32
33Dependencies
34------------
35- oc_diagnostics (structured debug logging via _dbg)
36- oc_chat.registry.backends.sqlite (SQLite backend)
37- oc_chat.registry.discovery (registry path discovery)
38"""
39from __future__ import annotations
40
41import argparse
42import json
43import sys
44from typing import Mapping
45
46from oc_diagnostics import _dbg
47
48from oc_chat.registry.backends.sqlite import SQLiteBackend
49from oc_chat.registry.discovery import discover_registry_location
50
51
52_dbg("OC_CHAT.MAIN", "module", "loaded", 4)
53
54RESERVED_DB_COMMANDS = ("backup", "restore", "prune", "archive-log", "restore-log")
55
56
57def add_db_subcommands(db_parser: argparse.ArgumentParser) -> None:
58 """Attach the M11.1c db subcommands to ``db_parser``."""
59
60 db_parser.set_defaults(handler=_cmd_db_group, db_parser=db_parser)
61 subcommands = db_parser.add_subparsers(dest="db_command")
62
63 integrity = subcommands.add_parser(
64 "integrity-check",
65 help="Run SQLite physical, FK, and append-only integrity checks.",
66 )
67 integrity.add_argument(
68 "registry",
69 nargs="?",
70 help="Registry SQLite path. Defaults to the discovery algorithm.",
71 )
72 integrity.add_argument(
73 "--json",
74 action="store_true",
75 help="Emit the structured integrity report as JSON.",
76 )
77 integrity.set_defaults(handler=_cmd_integrity_check)
78
79 for name in RESERVED_DB_COMMANDS:
80 reserved = subcommands.add_parser(
81 name,
82 help="Reserved for a later registry phase.",
83 )
84 reserved.set_defaults(handler=_cmd_reserved_db)
85
86
87def _cmd_db_group(args: argparse.Namespace) -> int:
88 parser = args.db_parser
89 parser.print_help()
90 return 1
91
92
93def _cmd_integrity_check(args: argparse.Namespace) -> int:
94 location = discover_registry_location(registry_path=args.registry)
95 backend = SQLiteBackend(location.registry_path, check_capabilities=False)
96 report = backend.integrity_check()
97 if args.json:
98 print(json.dumps(report, indent=2, sort_keys=True))
99 else:
100 print(format_integrity_report(report))
101 return 0 if report.get("ok") is True else 1
102
103
104def _cmd_reserved_db(args: argparse.Namespace) -> int:
105 print(f"db {args.db_command} not implemented in v0.2.x", file=sys.stderr)
106 return 2
107
108
109def format_integrity_report(report: Mapping[str, object]) -> str:
110 """Return a compact human-readable integrity report."""
111
112 errors = report.get("errors", [])
113 if report.get("ok") is True:
114 return "integrity ok"
115 if not isinstance(errors, list):
116 return "integrity failed: malformed error report"
117 lines = [f"integrity failed: {len(errors)} error(s)"]
118 for error in errors:
119 if isinstance(error, Mapping):
120 kind = error.get("kind", "unknown")
121 details = error.get("details", "")
122 lines.append(f" - {kind}: {details}")
123 else:
124 lines.append(f" - {error}")
125 return "\n".join(lines)
int _cmd_db_group(argparse.Namespace args)
Definition db.py:87
None add_db_subcommands(argparse.ArgumentParser db_parser)
Definition db.py:57
int _cmd_reserved_db(argparse.Namespace args)
Definition db.py:104
int _cmd_integrity_check(argparse.Namespace args)
Definition db.py:93
str format_integrity_report(Mapping[str, object] report)
Definition db.py:109