Ports the leaf data-layer modules and validates them: - mschema/ (models, eligibility, merge, render), db/ (connection, sampling, introspect, fetch_ca), rest/client.py -- renamed psdwp3->nsp, verbatim. - L0 (testcontainers, real Postgres): db connection read-only enforcement (psd_ro cannot CREATE/INSERT), introspect against a known schema (tables, columns, types, comments, FKs, enum, composite PK), sampling most-frequent values + truncation reporting. 15 tests, ~4s. - L1 (fake data): rest/client RPC contract (mocked transport -- X-API-Key header, payloads, base_url slash handling, HTTP/network error surfacing), mschema/render 3 formats (markdown, mschema-text, schema-dict) + eligibility rules (wide_text excluded, short_text/numeric/enum/temporal/ boolean eligible, annotation override wins). 25 tests. pyproject registers l0/l2 markers + addopts '-m not l2' (L2 opt-in). Deferred to their dependency-porting tasks: test_rrf.py (search needs vectorstore, B3) and the 11 CLI contract tests (need _guards/session, wired when each command lands). 'Not assumed reliable' now has real teeth for the data layer; CLI/search contracts follow.
38 lines
1.2 KiB
Python
38 lines
1.2 KiB
Python
from sqlalchemy import Engine, create_engine, text
|
|
|
|
from nsp.config import DatabaseConfig
|
|
|
|
|
|
def make_engine(cfg: DatabaseConfig) -> Engine:
|
|
url = (
|
|
f"postgresql+psycopg2://{cfg.user}:{cfg.password}"
|
|
f"@{cfg.host}:{cfg.port}/{cfg.database}"
|
|
)
|
|
return create_engine(url, echo=False)
|
|
|
|
|
|
def ping(engine: Engine) -> None:
|
|
with engine.connect() as conn:
|
|
conn.execute(text("SELECT 1"))
|
|
|
|
|
|
def writable_tables(engine: Engine, schema: str) -> list[str]:
|
|
"""Tabelle dello schema su cui l'utente corrente ha privilegi di scrittura."""
|
|
q = text("""
|
|
SELECT c.relname
|
|
FROM pg_class c
|
|
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
WHERE n.nspname = :schema
|
|
AND c.relkind IN ('r', 'p')
|
|
AND has_table_privilege(current_user, c.oid, 'INSERT, UPDATE, DELETE')
|
|
ORDER BY c.relname
|
|
""")
|
|
with engine.connect() as conn:
|
|
return [row[0] for row in conn.execute(q, {"schema": schema})]
|
|
|
|
|
|
def can_create_in_schema(engine: Engine, schema: str) -> bool:
|
|
q = text("SELECT has_schema_privilege(current_user, :schema, 'CREATE')")
|
|
with engine.connect() as conn:
|
|
return bool(conn.execute(q, {"schema": schema}).scalar())
|