seed-dev-db 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,237 @@
1
+ """Insert generated batches inside one guarded PostgreSQL transaction."""
2
+
3
+ from collections.abc import Callable, Iterator
4
+ from dataclasses import dataclass
5
+ from typing import Literal, cast
6
+
7
+ from sqlalchemy import URL, Connection, MetaData, Table, insert, literal_column, select
8
+ from sqlalchemy.exc import DBAPIError, SQLAlchemyError
9
+
10
+ from seed.config import SeedConfig
11
+ from seed.generation.engine import LiveInputs, generate_live_batches
12
+ from seed.generation.relationships import MAX_EXISTING_KEYS, KeyTuple
13
+ from seed.generation.streaming import GeneratedRecord, GenerationError, RecordBatch, Value
14
+ from seed.metadata import Metadata, TableId, TableSchema
15
+ from seed.planning.plan import PlanIssue, PlannedDependency, PlanRequest
16
+ from seed.postgres.apply_guard import ApprovedPlan, begin_guarded_write, rollback
17
+
18
+ type Outcome = Literal["not_started", "rolled_back", "committed", "unknown"]
19
+
20
+
21
+ class InsertedCount(Metadata):
22
+ table: TableId
23
+ rows: int
24
+
25
+
26
+ class InsertionResult(Metadata):
27
+ outcome: Outcome
28
+ counts: tuple[InsertedCount, ...] | None = None
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class WriteResult:
33
+ status: int
34
+ insertion: InsertionResult
35
+ issue: PlanIssue | None = None
36
+
37
+
38
+ class PostgreSQLWriter:
39
+ """Bind values into the reflected SQL type and correlate returned identities."""
40
+
41
+ def __init__(self, connection: Connection) -> None:
42
+ self.connection = connection
43
+ self._metadata = MetaData()
44
+ self._tables: dict[TableId, Table] = {}
45
+
46
+ def table(self, identifier: TableId) -> Table:
47
+ table = self._tables.get(identifier)
48
+ if table is None:
49
+ table = Table(
50
+ identifier.table,
51
+ self._metadata,
52
+ schema=identifier.schema_name,
53
+ autoload_with=self.connection,
54
+ postgresql_ignore_search_path=True,
55
+ resolve_fks=False,
56
+ quote=True,
57
+ quote_schema=True,
58
+ )
59
+ self._tables[identifier] = table
60
+ return table
61
+
62
+ def write(
63
+ self,
64
+ model: TableSchema,
65
+ batch: RecordBatch,
66
+ identities: tuple[str, ...],
67
+ ) -> RecordBatch:
68
+ """Return records in input order with any assigned server keys."""
69
+ table = self.table(model.id)
70
+ returned = [table.c[name] for name in identities]
71
+ base = insert(table)
72
+ statement = (
73
+ base.returning(*returned, sort_by_parameter_order=True)
74
+ if returned
75
+ else base.returning(literal_column("1"))
76
+ )
77
+ parameters = [record.values for record in batch]
78
+ ordered_batches = getattr(
79
+ self.connection.dialect, "insert_executemany_returning_sort_by_parameter_order", False
80
+ )
81
+ if not parameters[0]:
82
+ rows = [self.connection.execute(statement.values()).one() for _ in batch]
83
+ elif len(batch) == 1:
84
+ rows = [self.connection.execute(statement, parameters[0]).one()]
85
+ elif identities and not ordered_batches:
86
+ rows = [self.connection.execute(statement, row).one() for row in parameters]
87
+ else:
88
+ rows = list(self.connection.execute(statement, parameters))
89
+ if len(rows) != len(batch):
90
+ raise GenerationError(
91
+ PlanIssue(
92
+ code="INSERT_COUNT_MISMATCH",
93
+ message="PostgreSQL returned an unexpected row count.",
94
+ table=model.id,
95
+ )
96
+ )
97
+ return tuple(
98
+ GeneratedRecord(
99
+ record.table,
100
+ record.ordinal,
101
+ {
102
+ **record.values,
103
+ **dict(
104
+ zip(
105
+ identities,
106
+ cast(tuple[Value, ...], tuple(row)[: len(identities)]),
107
+ strict=True,
108
+ )
109
+ ),
110
+ },
111
+ )
112
+ for record, row in zip(batch, rows, strict=True)
113
+ )
114
+
115
+ def load_existing(self, edge: PlannedDependency) -> Iterator[KeyTuple]:
116
+ """Read one bounded, stable set of whole non-null referenced keys."""
117
+ foreign = edge.foreign_key
118
+ table = self.table(foreign.parent)
119
+ columns = [table.c[name] for name in foreign.parent_columns]
120
+ statement = (
121
+ select(*columns)
122
+ .where(*(column.is_not(None) for column in columns))
123
+ .order_by(*columns)
124
+ .limit(MAX_EXISTING_KEYS)
125
+ )
126
+ for row in self.connection.execute(statement):
127
+ yield cast(KeyTuple, tuple(row))
128
+
129
+ def conflicts(self, model: TableSchema, values: dict[str, Value]) -> bool:
130
+ """Probe only existing database-backed keys with typed indexed predicates."""
131
+ specs: list[tuple[tuple[str, ...], bool]] = []
132
+ if model.primary_key:
133
+ specs.append((model.primary_key.columns, False))
134
+ specs.extend(
135
+ (key.columns, bool(key.nulls_distinct)) for key in model.unique_keys if key.supported
136
+ )
137
+ table = self.table(model.id)
138
+ for columns, nulls_distinct in specs:
139
+ if any(name not in values for name in columns):
140
+ continue
141
+ if nulls_distinct and any(values[name] is None for name in columns):
142
+ continue
143
+ predicates = [
144
+ table.c[name].is_(None) if values[name] is None else table.c[name] == values[name]
145
+ for name in columns
146
+ ]
147
+ if self.connection.scalar(
148
+ select(select(literal_column("1")).select_from(table).where(*predicates).exists())
149
+ ):
150
+ return True
151
+ return False
152
+
153
+
154
+ def execute_apply(
155
+ connection: Connection,
156
+ url: URL,
157
+ config: SeedConfig,
158
+ request: PlanRequest,
159
+ approved: ApprovedPlan,
160
+ ) -> WriteResult:
161
+ """Hold all locks through one commit and expose counts only after acknowledgement."""
162
+ try:
163
+ transaction = begin_guarded_write(connection, url, config, request, approved)
164
+ except KeyboardInterrupt:
165
+ return _write_error(
166
+ "not_started", "INTERRUPTED", "Apply was interrupted before writing.", 130
167
+ )
168
+ writer = PostgreSQLWriter(connection)
169
+ counts: dict[TableId, int] = {}
170
+ inputs = LiveInputs(
171
+ insert=writer.write,
172
+ existing=writer.load_existing,
173
+ conflicts=writer.conflicts if config.safety.allow_existing_data else None,
174
+ )
175
+ try:
176
+ for batch in generate_live_batches(
177
+ approved.plan, approved.inspection.schema, config, inputs
178
+ ):
179
+ identifier = batch[0].table
180
+ counts[identifier] = counts.get(identifier, 0) + len(batch)
181
+ except GenerationError as error:
182
+ rollback(transaction)
183
+ return WriteResult(4, InsertionResult(outcome="rolled_back"), error.issue)
184
+ except SQLAlchemyError:
185
+ rollback(transaction)
186
+ return _write_error("rolled_back", "INSERT_FAILED", "Could not insert the planned rows.")
187
+ except KeyboardInterrupt:
188
+ rollback(transaction)
189
+ return _write_error(
190
+ "rolled_back", "INTERRUPTED", "Apply was interrupted before commit.", 130
191
+ )
192
+ except Exception:
193
+ rollback(transaction)
194
+ raise
195
+ issue = commit_outcome(transaction.commit)
196
+ if issue is not None:
197
+ rollback(transaction)
198
+ return issue
199
+ return WriteResult(
200
+ 0,
201
+ InsertionResult(
202
+ outcome="committed",
203
+ counts=tuple(InsertedCount(table=table, rows=rows) for table, rows in counts.items()),
204
+ ),
205
+ )
206
+
207
+
208
+ def commit_outcome(commit: Callable[[], None]) -> WriteResult | None:
209
+ """Differentiate an acknowledged server rejection from an ambiguous commit."""
210
+ try:
211
+ commit()
212
+ except DBAPIError as error:
213
+ sqlstate = getattr(error.orig, "sqlstate", "") or ""
214
+ if not error.connection_invalidated and (
215
+ sqlstate.startswith("23") or sqlstate in {"40001", "40P01"}
216
+ ):
217
+ return _write_error(
218
+ "rolled_back", "COMMIT_REJECTED", "PostgreSQL rejected the transaction."
219
+ )
220
+ return _unknown_commit()
221
+ except (SQLAlchemyError, KeyboardInterrupt, OSError):
222
+ return _unknown_commit()
223
+ return None
224
+
225
+
226
+ def _unknown_commit() -> WriteResult:
227
+ return _write_error(
228
+ "unknown",
229
+ "COMMIT_OUTCOME_UNKNOWN",
230
+ "Commit was not acknowledged. Verify the database outcome before retrying.",
231
+ )
232
+
233
+
234
+ def _write_error(outcome: Outcome, code: str, message: str, status: int = 6) -> WriteResult:
235
+ return WriteResult(
236
+ status, InsertionResult(outcome=outcome), PlanIssue(code=code, message=message)
237
+ )
@@ -0,0 +1,76 @@
1
+ """Application service for read-only schema inspection."""
2
+
3
+ import re
4
+ import warnings
5
+ from pathlib import Path
6
+
7
+ from sqlalchemy import URL
8
+ from sqlalchemy.exc import SAWarning
9
+
10
+ from seed.config import SeedConfig, load_config, resolve_database_url
11
+ from seed.metadata import DatabaseSchema
12
+ from seed.postgres.connection import DatabaseError, parse_database_url, read_session
13
+ from seed.postgres.schema import reflect_schema
14
+
15
+ _IDENTIFIER = r'(?:"(?:[^"]|"")*"|[^".]+)'
16
+ _TABLE_NAME = re.compile(rf"({_IDENTIFIER})(?:\.({_IDENTIFIER}))?")
17
+
18
+
19
+ def _identifier(token: str) -> str:
20
+ return token[1:-1].replace('""', '"') if token.startswith('"') else token
21
+
22
+
23
+ def requested_tables(schema: str, filters: list[str]) -> set[str]:
24
+ """Parse exact, optionally qualified table filters for a single schema."""
25
+ names: set[str] = set()
26
+ for expression in filters:
27
+ match = _TABLE_NAME.fullmatch(expression)
28
+ if not match or "\x00" in expression:
29
+ raise DatabaseError("INVALID_TABLE_FILTER", "Use a valid table filter.", 4)
30
+ first = _identifier(match[1])
31
+ if match[2] is None:
32
+ name = first
33
+ else:
34
+ if first != schema:
35
+ raise DatabaseError(
36
+ "SCHEMA_MISMATCH", "A table filter belongs to a different schema.", 4
37
+ )
38
+ name = _identifier(match[2])
39
+ if not name:
40
+ raise DatabaseError("INVALID_TABLE_FILTER", "Use a valid table filter.", 4)
41
+ names.add(name)
42
+ return names
43
+
44
+
45
+ def inspect_database(
46
+ config_path: Path, schema_override: str | None, filters: list[str]
47
+ ) -> DatabaseSchema:
48
+ """Return inspected metadata with optional display filtering."""
49
+ config = load_config(config_path)
50
+ if schema_override is not None and (not schema_override or "\x00" in schema_override):
51
+ raise DatabaseError("INVALID_SCHEMA", "Use a valid PostgreSQL schema name.", 4)
52
+ schema_name = config.database.schema_name if schema_override is None else schema_override
53
+ names = requested_tables(schema_name, filters)
54
+ report = read_schema(config, schema_name)
55
+ if not names:
56
+ return report
57
+ tables = tuple(table for table in report.tables if table.id.table in names)
58
+ if len(tables) != len(names):
59
+ raise DatabaseError(
60
+ "TABLE_UNAVAILABLE", "A requested table was not found in the selected schema.", 4
61
+ )
62
+ return report.model_copy(update={"tables": tables})
63
+
64
+
65
+ def read_schema(config: SeedConfig, schema_name: str, *, url: URL | None = None) -> DatabaseSchema:
66
+ """Read a complete schema through the shared redaction boundary."""
67
+ if url is None:
68
+ url = parse_database_url(resolve_database_url(config))
69
+ with read_session(url, config.database) as connection, warnings.catch_warnings():
70
+ warnings.simplefilter("ignore", SAWarning)
71
+ try:
72
+ return reflect_schema(connection, url, schema_name).schema
73
+ except (ValueError, LookupError, NotImplementedError):
74
+ raise DatabaseError(
75
+ "SCHEMA_INSPECTION_FAILED", "PostgreSQL metadata could not be normalized.", 4
76
+ ) from None
@@ -0,0 +1,234 @@
1
+ """Normalize PostgreSQL reflection into stable, driver-independent metadata."""
2
+
3
+ from sqlalchemy import URL, Connection, inspect, text
4
+ from sqlalchemy.dialects.postgresql import DOMAIN, ENUM
5
+ from sqlalchemy.dialects.postgresql.base import PGInspector
6
+ from sqlalchemy.engine.interfaces import ReflectedColumn
7
+ from sqlalchemy.types import (
8
+ TIMESTAMP,
9
+ UUID,
10
+ VARCHAR,
11
+ BigInteger,
12
+ Boolean,
13
+ Date,
14
+ Float,
15
+ Integer,
16
+ Numeric,
17
+ SmallInteger,
18
+ Text,
19
+ )
20
+
21
+ from seed.metadata import (
22
+ Check,
23
+ ColumnSchema,
24
+ ColumnType,
25
+ DatabaseSchema,
26
+ ForeignKey,
27
+ Inspection,
28
+ Key,
29
+ TableId,
30
+ TableSchema,
31
+ Target,
32
+ UniqueKey,
33
+ digest,
34
+ )
35
+ from seed.postgres.catalog import enrich_table
36
+ from seed.postgres.connection import DatabaseError
37
+
38
+
39
+ def reflect_schema(
40
+ connection: Connection,
41
+ url: URL,
42
+ schema_name: str,
43
+ *,
44
+ require_read_only: bool = True,
45
+ ) -> Inspection:
46
+ """Reflect a schema from a read-only snapshot or a guarded write transaction."""
47
+ if require_read_only and connection.scalar(text("SHOW transaction_read_only")) != "on":
48
+ raise DatabaseError(
49
+ "SCHEMA_INSPECTION_FAILED", "Inspection requires a read-only session.", 4
50
+ )
51
+ major = int(connection.scalar(text("SHOW server_version_num"))) // 10000
52
+ if major not in range(15, 20):
53
+ raise DatabaseError("UNSUPPORTED_SERVER", "Seed supports PostgreSQL majors 15–19.", 4)
54
+ inspector = inspect(connection)
55
+ if not isinstance(inspector, PGInspector):
56
+ raise DatabaseError("UNSUPPORTED_SERVER", "A PostgreSQL connection is required.", 4)
57
+ schemas = tuple(
58
+ sorted(
59
+ name
60
+ for name in inspector.get_schema_names()
61
+ if name != "information_schema" and not name.startswith("pg_")
62
+ )
63
+ )
64
+ if schema_name not in schemas or not connection.scalar(
65
+ text("SELECT has_schema_privilege(:schema, 'USAGE')"), {"schema": schema_name}
66
+ ):
67
+ raise DatabaseError("SCHEMA_UNAVAILABLE", "The selected schema is unavailable.", 4)
68
+
69
+ relations = connection.execute(
70
+ text(
71
+ "SELECT c.relname, c.relkind, c.oid FROM pg_catalog.pg_class AS c "
72
+ "JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace "
73
+ "WHERE n.nspname = :schema AND c.relkind IN ('r', 'p', 'v', 'm', 'f')"
74
+ ),
75
+ {"schema": schema_name},
76
+ ).mappings()
77
+ tables, identities, definitions = [], [], []
78
+ for row in sorted(relations, key=lambda item: item["relname"]):
79
+ table = row["relname"]
80
+ identity = TableId(schema=schema_name, table=table)
81
+ record, raw = _reflect_table(inspector, identity, row["relkind"])
82
+ record, supplemental = enrich_table(connection, int(row["oid"]), record)
83
+ tables.append(record)
84
+ identities.append((table, int(row["oid"])))
85
+ definitions.append([raw, supplemental])
86
+
87
+ target = Target(
88
+ host=url.host or "",
89
+ port=url.port or 5432,
90
+ database=str(connection.scalar(text("SELECT current_database()"))),
91
+ schema=schema_name,
92
+ )
93
+ fingerprint = digest(
94
+ [schema_name, [item.model_dump(mode="json", by_alias=True) for item in tables]]
95
+ )
96
+ return Inspection(
97
+ DatabaseSchema(
98
+ target=target,
99
+ server_major=major,
100
+ schemas=schemas,
101
+ tables=tuple(tables),
102
+ fingerprint=fingerprint,
103
+ ),
104
+ tuple(identities),
105
+ digest(definitions),
106
+ )
107
+
108
+
109
+ def _reflect_table(
110
+ inspector: PGInspector,
111
+ identifier: TableId,
112
+ kind: str,
113
+ ) -> tuple[TableSchema, object]:
114
+ name, schema = identifier.table, identifier.schema_name
115
+ reflected = inspector.get_columns(name, schema=schema)
116
+ columns = tuple(_column(item, index) for index, item in enumerate(reflected, start=1))
117
+ if kind not in {"r", "p", "f"}:
118
+ return TableSchema(id=identifier, kind=kind, columns=columns), [
119
+ item.get("default") for item in reflected
120
+ ]
121
+ pk = inspector.get_pk_constraint(name, schema=schema)
122
+ pk_columns = tuple(pk.get("constrained_columns") or ())
123
+ primary = Key(name=pk.get("name") or "", columns=pk_columns) if pk_columns else None
124
+ fks = inspector.get_foreign_keys(name, schema=schema, postgresql_ignore_search_path=True)
125
+ foreign = tuple(
126
+ sorted(
127
+ (
128
+ ForeignKey(
129
+ name=item.get("name") or "",
130
+ columns=tuple(item["constrained_columns"]),
131
+ parent=TableId(
132
+ schema=item.get("referred_schema") or schema, table=item["referred_table"]
133
+ ),
134
+ parent_columns=tuple(item["referred_columns"]),
135
+ match=item.get("options", {}).get("match", "SIMPLE"),
136
+ deferrable=item.get("options", {}).get("deferrable", False),
137
+ on_update=item.get("options", {}).get("onupdate", "NO ACTION"),
138
+ on_delete=item.get("options", {}).get("ondelete", "NO ACTION"),
139
+ )
140
+ for item in fks
141
+ ),
142
+ key=lambda item: item.name,
143
+ )
144
+ )
145
+ unique = tuple(
146
+ sorted(
147
+ (
148
+ UniqueKey(name=item.get("name") or "", columns=tuple(item["column_names"]))
149
+ for item in inspector.get_unique_constraints(name, schema=schema)
150
+ ),
151
+ key=lambda item: item.name,
152
+ )
153
+ )
154
+ reflected_checks = inspector.get_check_constraints(name, schema=schema)
155
+ checks = tuple(
156
+ sorted(
157
+ (Check(name=item.get("name") or "", columns=()) for item in reflected_checks),
158
+ key=lambda item: item.name,
159
+ )
160
+ )
161
+ raw = [
162
+ [item["name"], item.get("default"), item.get("computed"), item.get("identity")]
163
+ for item in reflected
164
+ ]
165
+ return TableSchema(
166
+ id=identifier,
167
+ kind=kind,
168
+ columns=columns,
169
+ primary_key=primary,
170
+ foreign_keys=foreign,
171
+ unique_keys=unique,
172
+ checks=checks,
173
+ ), [raw, sorted((item.get("name") or "", item.get("sqltext", "")) for item in reflected_checks)]
174
+
175
+
176
+ def _column(value: ReflectedColumn, ordinal: int) -> ColumnSchema:
177
+ kind = value["type"]
178
+ name = kind.__visit_name__.lower()
179
+ if isinstance(kind, ENUM):
180
+ normalized = ColumnType(
181
+ name="enum",
182
+ supported=True,
183
+ enum_labels=tuple(kind.enums),
184
+ type_schema=kind.schema,
185
+ type_name=kind.name,
186
+ )
187
+ elif isinstance(kind, TIMESTAMP):
188
+ normalized = ColumnType(
189
+ name=name,
190
+ supported=True,
191
+ timezone=kind.timezone,
192
+ precision=getattr(kind, "precision", None),
193
+ )
194
+ elif isinstance(kind, Numeric) and not isinstance(kind, Float):
195
+ normalized = ColumnType(
196
+ name=name,
197
+ precision=kind.precision,
198
+ scale=kind.scale,
199
+ supported=kind.scale is None
200
+ or (kind.precision is not None and 0 <= kind.scale <= kind.precision),
201
+ )
202
+ elif isinstance(kind, (Text, VARCHAR)) and name in {"text", "varchar"}:
203
+ normalized = ColumnType(
204
+ name=name,
205
+ supported=True,
206
+ length=kind.length,
207
+ collation=kind.collation,
208
+ )
209
+ elif isinstance(kind, SmallInteger):
210
+ normalized = ColumnType(name="smallint", supported=True)
211
+ elif isinstance(kind, BigInteger):
212
+ normalized = ColumnType(name="bigint", supported=True)
213
+ elif isinstance(kind, (Integer, Boolean, Date, UUID)):
214
+ normalized = ColumnType(name=name, supported=True)
215
+ elif isinstance(kind, DOMAIN):
216
+ normalized = ColumnType(
217
+ name="domain",
218
+ supported=False,
219
+ type_schema=kind.schema,
220
+ type_name=kind.name,
221
+ )
222
+ else:
223
+ normalized = ColumnType(name=name, supported=False)
224
+ identity = value.get("identity")
225
+ generated = value.get("computed")
226
+ return ColumnSchema(
227
+ name=value["name"],
228
+ ordinal=ordinal,
229
+ type=normalized,
230
+ nullable=value["nullable"],
231
+ default_kind="expression" if value.get("default") is not None else "none",
232
+ identity=("always" if identity.get("always") else "by_default") if identity else None,
233
+ generated=("stored" if generated.get("persisted") else "virtual") if generated else None,
234
+ )
@@ -0,0 +1 @@
1
+ """Shared dataset and command result projections."""
@@ -0,0 +1,72 @@
1
+ """Shared JSON projection of typed generated values."""
2
+
3
+ from dataclasses import dataclass
4
+ from datetime import UTC, date, datetime
5
+ from decimal import Decimal
6
+ from uuid import UUID
7
+
8
+ from seed.generation.streaming import GeneratedRecord, Value
9
+ from seed.metadata import TableId, TableSchema
10
+
11
+ type JsonValue = None | bool | int | str
12
+ type JsonRow = tuple[JsonValue, ...]
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class DatasetColumn:
17
+ name: str
18
+ type: str
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class TableSample:
23
+ table: TableId
24
+ columns: tuple[DatasetColumn, ...]
25
+ rows: tuple[JsonRow, ...]
26
+
27
+ def payload(self) -> dict[str, object]:
28
+ """Return the version-1 tabular representation."""
29
+ return {**dataset_header(self.table, self.columns), "rows": self.rows}
30
+
31
+
32
+ def dataset_header(table: TableId, columns: tuple[DatasetColumn, ...]) -> dict[str, object]:
33
+ """Describe a table and the ordered positions of its dataset columns."""
34
+ return {
35
+ "table": table.model_dump(by_alias=True),
36
+ "columns": [{"name": column.name, "type": column.type} for column in columns],
37
+ }
38
+
39
+
40
+ def dataset_columns(table: TableSchema) -> tuple[DatasetColumn, ...]:
41
+ """Return writable columns in schema order, with their output type names."""
42
+ return tuple(
43
+ DatasetColumn(
44
+ column.name,
45
+ "timestamptz"
46
+ if column.type.name == "timestamp" and column.type.timezone
47
+ else column.type.name,
48
+ )
49
+ for column in table.columns
50
+ if column.generated is None
51
+ )
52
+
53
+
54
+ def dataset_row(record: GeneratedRecord, columns: tuple[DatasetColumn, ...]) -> JsonRow:
55
+ """Return a positional row in the descriptor order."""
56
+ return tuple(json_value(record.values[column.name], column.type) for column in columns)
57
+
58
+
59
+ def json_value(value: Value, column_type: str) -> JsonValue:
60
+ """Render lossless JSON scalars for the supported PostgreSQL types."""
61
+ if isinstance(value, Decimal):
62
+ return format(value, "f")
63
+ if isinstance(value, datetime):
64
+ stamp = value.astimezone(UTC) if value.utcoffset() is not None else value
65
+ return stamp.isoformat()
66
+ if isinstance(value, date):
67
+ return value.isoformat()
68
+ if isinstance(value, UUID):
69
+ return str(value)
70
+ if type(value) is int and column_type == "bigint":
71
+ return str(value)
72
+ return value
@@ -0,0 +1,65 @@
1
+ """Render schema inspection metadata without executing terminal control sequences."""
2
+
3
+ from seed.metadata import DatabaseSchema
4
+
5
+
6
+ def _safe(text: str) -> str:
7
+ return "".join(char if char.isprintable() else f"\\u{ord(char):04x}" for char in text)
8
+
9
+
10
+ def _sequence(names: tuple[str, ...]) -> str:
11
+ return ", ".join(map(_safe, names))
12
+
13
+
14
+ def inspection_lines(report: DatabaseSchema) -> list[str]:
15
+ """Build readable lines for the terminal schema report."""
16
+ lines = [
17
+ f"PostgreSQL {report.server_major} · {_safe(report.target.database)} "
18
+ f"· schema {_safe(report.target.schema_name)}",
19
+ f"{len(report.tables)} relations · fingerprint {report.fingerprint}",
20
+ ]
21
+ for table in report.tables:
22
+ lines.append(f"{_safe(table.id.schema_name)}.{_safe(table.id.table)} ({table.kind})")
23
+ for column in table.columns:
24
+ kind = column.type
25
+ modifiers: list[str] = []
26
+ if kind.length is not None:
27
+ modifiers.append(f"length {kind.length}")
28
+ if kind.precision is not None:
29
+ modifiers.append(f"precision {kind.precision}")
30
+ if kind.scale is not None:
31
+ modifiers.append(f"scale {kind.scale}")
32
+ if kind.enum_labels:
33
+ modifiers.append(f"labels {_sequence(kind.enum_labels)}")
34
+ if kind.timezone is not None:
35
+ modifiers.append("with time zone" if kind.timezone else "without time zone")
36
+ details = [
37
+ "nullable" if column.nullable else "required",
38
+ f"default {column.default_kind}",
39
+ *modifiers,
40
+ ]
41
+ if column.identity:
42
+ details.append(f"identity {column.identity}")
43
+ if column.generated:
44
+ details.append(f"generated {column.generated}")
45
+ if not kind.supported:
46
+ details.append("detected only")
47
+ lines.append(f" {_safe(column.name)} · {_safe(kind.name)} · {', '.join(details)}")
48
+ if table.primary_key:
49
+ key = table.primary_key
50
+ lines.append(f" Primary key {_safe(key.name)} ({_sequence(key.columns)})")
51
+ for foreign in table.foreign_keys:
52
+ parent = f"{_safe(foreign.parent.schema_name)}.{_safe(foreign.parent.table)}"
53
+ lines.append(
54
+ f" Foreign key {_safe(foreign.name)} ({_sequence(foreign.columns)}) "
55
+ f"→ {parent} ({_sequence(foreign.parent_columns)})"
56
+ )
57
+ for unique in table.unique_keys:
58
+ status = "MVP" if unique.supported else "Detected only"
59
+ lines.append(f" Unique {_safe(unique.name)} ({_sequence(unique.columns)}) · {status}")
60
+ for check in table.checks:
61
+ lines.append(f" Check {_safe(check.name)} · {check.status}")
62
+ for feature in table.features:
63
+ if feature.reason:
64
+ lines.append(f" {_safe(feature.name)} · {feature.status} · {feature.reason}")
65
+ return lines