ps_core

Generates, from a folder of YAML spec files:

  • schema.py — a permissive SQLAlchemy storage layer. Every non-primary-key column is nullable, regardless of what the Pydantic contract requires — a row that fails a rule is still saved and flagged, never rejected by the database.
  • validation.py — a Pydantic "check" class per table. Every field is Optional[T] = None; "required" is just one rule among several, applied by that field's own generated checker function. Every rule raises a generic, parameterized message — see "Field rules" below.
  • enums.py — one plain str, Enum class per enum. Normalizing input and checking membership both happen in validation.py, not here.
  • data_dictionary.md — a readable table-by-table reference of every field's SQL type, rule set, foreign key, and required status, plus a plain-English list of each table's cross-field rules.

A separate ps_core.runtime package (not code generation) provides the functions used at data-load time: load_row, validate_row, ingest, and check_foreign_keys.

Spec directory layout

spec_dir/
    enums.yaml          # optional
    cross_rules.yaml    # optional
    tables/
        *.yaml           # required, one file per table

See spec/ in this repo for a small worked example.

Field rules

A field is optional at every layer. It activates a rule by giving it a truthy value (or, for regex/max_length, the parameter itself — the value doubles as the flag):

fields:
    pac_id_hospital:
        type: text
        required: true
        strip: true
        upper: true
    pac_codigo_postal_vigente:
        type: text
        regex: "\\d{5}"
    edad_meses:
        type: float
        range: true
        min: 16.0
        max: 36.0

Rules apply in a fixed order, regardless of the order written in YAML: strip → upper → required → max_length → regex → range → not_future. Which rules are legal depends on the field's type:

type legal rules (besides required)
text strip, upper, regex, max_length
integer, float range (needs min/max)
date not_future
datetime, bool, enum (none — required only)
uuid strip

enum fields always strip + uppercase + check membership.

Messages are generic, not per-field. There is no <rule>_message key in the spec YAML. Each rule raises a message built from the field's own name (its label), by the matching function in constraints.py — matching this shape:

def check_range(v, lo, hi, label="value"):
    if v < lo or v > hi:
        raise ValueError(f"{label} must be between {lo} and {hi}, got {v}")
    return v

To change the wording for every field that uses a given rule — across the whole project — edit that one function in constraints.py. This keeps customization in one place, in code, rather than repeated in every field's YAML.

Using a rule the field's type doesn't support raises ValueError at parse time, naming the file, field, and rule — nothing is silently ignored.

Foreign keys

owner_id:
    type: uuid
    required: true
    foreign_key: users.id

Checked at parse time (the target table and column must exist) but never turned into a database constraint — a bad link is not allowed to block an insert. Call ps_core.runtime.check_foreign_keys after your insert batch to flag orphans the same way any other rule gets flagged (validated=False, errors updated).

Cross-field rules (cross_rules.yaml)

Table name → list of rules, each a fixed, named kind — never a raw condition string. Every field a rule mentions must exist on that table, checked at parse time.

kind required keys checks
order fields: [a, b], op: le|lt|ge|gt a <op> b
equals fields: [a, b] a == b
sum_equals target, parts: [...] target == sum(parts), optional tolerance
ratio_equals target, numerator, denominator target == numerator / denominator**power, optional power (default 1), tolerance
date_offset_equals base, offset_days_field, target target == base + timedelta(days=offset_days_field), optional tolerance_days
date_diff_equals start, end, target target == (end - start).days, optional tolerance_days
comparison_equals target, left, op target == (left <op> right); exactly one of right (a field) or right_value (a literal)
piecewise_lookup source, target, breakpoints, otherwise target matches the bucket source falls into — see below
requires if_field, then_field if the if-condition holds, then_field is set (and optionally equals then_value)
forbidden_if if_field, then_fields: [...] if the if-condition holds, every field in then_fields must be None (or in then_allowed_values)
any_of_implies target, conditions: [...] target == True if any condition holds, else False
conditional_equals if_field, target, value_if_true, value_if_false target equals one of two values depending on the if-condition

All optional keys accept message to override the generated default.

The if-condition language, shared by requires, forbidden_if, and conditional_equals:

  • no if_value → if_field must be truthy
  • scalar if_value → if_field must equal it
  • list if_value → if_field must be a member
  • if_op (eq/lt/le/gt/ge) + numeric if_value → that comparison

A string if_value/then_value/then_allowed_values compared against an enum field is uppercased automatically, so if_value: severa in YAML correctly matches the stored SEVERA — write YAML values in whatever case reads naturally.

piecewise_lookup breakpoints, ascending and non-overlapping:

- kind: piecewise_lookup
  source: edad_meses
  target: ventana_madurativa
  breakpoints:
      - {max: 23.9, value: v1_16_23}
      - {max: 30.9, value: v2_24_30}
      - {max: 36.0, value: v3_31_36}
  otherwise: fuera_de_rango

If target is an enum field, every breakpoint value and otherwise must be a real member of that enum — checked at parse time.

any_of_implies conditions, each {field, op[, value]} with op one of truthy/eq/lt/le/gt/ge (truthy needs no value):

- kind: any_of_implies
  target: flag_riesgo_neonatal
  conditions:
      - {field: apgar_5min, op: lt, value: 7}
      - {field: ingreso_ucin, op: truthy}

Generating

python -m ps_core.generate_all --spec-dir spec --out-dir generated

generated/ is written as a real package (__init__.py included), so validation.py's from .enums import * resolves whether you import it in-process or load it from disk later.

Loading data at runtime

from generated.schema import Base, TestTable, ForeignTable
from generated.validation import TestTableCheck, ForeignTableCheck
from ps_core.runtime import ingest, check_foreign_keys
from ps_core.parse_spec import parse_spec
from sqlalchemy import create_engine
from sqlalchemy.orm import Session

parsed_tables, _, _ = parse_spec("spec")

engine = create_engine("sqlite://")
Base.metadata.create_all(engine)

with Session(engine) as session:
    row = ingest({"field1": "hello", "field4": "2024-01-01"}, TestTableCheck, TestTable)
    session.add(row)
    session.commit()

    check_foreign_keys(
        session, parsed_tables,
        {"test_table": TestTable, "foreign_table": ForeignTable},
    )
    session.commit()

validate_row (used inside ingest) takes and returns plain data, so it is safe to run in a separate worker process — only check_cls needs to be importable by name on both sides. load_row and check_foreign_keys must run in the process that owns the database session.

A note on cross-rule messages

Field-level rules (required, range, regex, and so on) never take a custom message — see "Field rules" above. Cross-field rules are different: each one describes a genuinely distinct relationship between fields, so a single generic template can't cover them all. Their optional message key is inserted into the generated file as a plain string literal (safely repr()'d), regardless of what characters it contains — no injection risk from quotes or braces in the text.

S
Description
No description provided
Readme 398 KiB
Release 0.2.4 Latest
2026-09-14 13:29:12 -06:00
Languages
Python 98.2%
Jinja 1.8%