Skip to content
ERPForAll DocsDevelopment

    Generated columns

    Status: the declaration surfaces and the schema contract below are delivered; runtime read/search/write behavior is described per section. Check each section for implemented and tested scope before relying on a candidate. A generated field is a scalar column whose value PostgreSQL computes from other columns of the same row. ADR 0062 and docs/specs/orm/generated-columns.md define its contract. The code blocks below are not compiled as doctests.

    Rust macro, native builder and models/*.toml carry the same two attributes.

    #[field(integer, generated = "price * qty")] // VIRTUAL (the default)
    pub total: i32,
    #[field(char, generated = "lower(name)", generated_storage = "stored")] // STORED
    pub name_key: String,
    [[model.field]]
    name = "total"
    type = "integer"
    generated = "price * qty"
    generated_storage = "stored" # "virtual" (default when omitted) or "stored"

    An _inherit extension may replace the expression (generated = "...") and keeps the inherited storage kind unless it names one. Removing generation is refused. generated_storage without generated is refused.

    Local ordinary columns of the same model; integer, boolean, text and None literals; parentheses; unary + - not; binary + - *; comparisons == != < <= > >=; and/or; a if test else b; and the closed calls abs, lower, upper (one argument) and least, greatest, coalesce (2 to 16 arguments). Semantics are PostgreSQL’s (three-valued logic, no Python truthiness). Ceilings: 16 KiB source, depth 32, 1,024 nodes, 64 KiB emitted SQL; empty or NUL input is refused.

    Refused with a Programming error naming the field: unknown sources, the field itself, other generated fields (so cycles cannot exist), computed or related fields, delegated (_inherits) fields, cross-row access (partner_id.name, subscripts), division, floats, casts, other functions, containers, keywords.

    Both kinds are stored (queryable) and readonly, never copied, and cannot be assigned. required, default, compute, related, inverse, precompute, compute_sudo, depends, depends_context, readonly = false, copy = true and store = false are refused, also when the base declaration carries one and an extension adds the expression. A VIRTUAL field cannot appear in an index, key, exclusion or temporal key (PostgreSQL 18 does not index virtual columns); no generated field can be a partition key.

    The schema-sync contract emits an explicit GENERATED ALWAYS AS (...) VIRTUAL or STORED clause for a generated declaration. It does not backfill the output through an ORM default or compute callback. For an installed generated column, sync compares the actual PostgreSQL definition with transactional provenance in erp_schema_generated before considering a declaration change. That provenance records the compiler format, declaration signature and installed server-normalized catalog identity. Do not edit the table or fabricate a provenance row to adopt an existing ordinary column.

    An unchanged declaration and matching catalog require no generated-column mutation. A compatible expression change may use SET EXPRESSION only while output type (including typmod) and storage kind are unchanged. Out-of-band catalog drift or missing/incompatible provenance requires explicit migration or adoption. Automatic sync refuses ordinary-to-generated and generated-to-ordinary conversion, VIRTUAL-to-STORED changes, output-type changes and removal; it does not drop/recreate a column or use CASCADE as a repair. Plan those changes as explicit addon migrations with their dependencies reviewed.

    Adding a STORED output to an existing table or replacing its expression can rewrite stored rows. Normal sync applies its configured large_table_rows gate. A refused rewrite returns a Programming error naming the field:

    Generated field '<model>.<field>': rewrite requires a maintenance window

    The operator must arrange a controlled window, drain old snapshots, and explicitly choose SchemaSyncOptions::inline() to run the work in the schema transaction. Inline mode treats no table as large; it is blocking maintenance and can hold locks for the rewrite. It is not an online migration or a reason to remove lock/statement deadlines. VIRTUAL changes also acquire locks and use deadlines. A STORED change requires statistics maintenance (ANALYZE); an unfinished or failed maintenance step must be returned to the operator, never treated as a ready field with an old expression.

    The database owner manages provenance; runtime roles need SELECT access and must have no write access, including access inherited through PUBLIC or another role. A failed privilege publication requires operator recovery before activation. Runtime parity and performance remain unverified.

    The ORM candidate treats VIRTUAL and STORED as database-readable columns. Supply source fields to create, write, import, model-data updates and upsert. Except for the explicit native create/write input adapter described below, output values, even NULL, are refused with Validation: Generated field '<model>.<field>' is read-only. This also applies to context defaults, ir.default, values returned by a default_get override and copy defaults. Ordinary copy/copy_data omit outputs; PostgreSQL derives the copied record’s values anew. An editable related alias cannot write through to a generated target: the same read-only error names the owning generated field before defaults, inverses or cache mutation can apply it.

    Source writes invalidate cached outputs and downstream ordinary computes. A query or direct read of an output flushes its source fields before fetching the database value. Do not give generated outputs a compute method, and do not treat VIRTUAL as a nonstored ORM compute. A downstream stored compute that reads an output runs after INSERT; explicit incompatible precompute requests are refused by the existing precompute contract. Transaction savepoints use the existing cache rollback mechanism.

    An output requires read permission on both the output and every source. This applies to predicates, ordering, grouping and aggregates as well as direct reads. Related aliases that transitively expose an output also require those permissions, including cached/stored aliases and delegated fields. Their explicit reads authorize the owning target records as the caller before returning cached values. Cross-record aliases (including delegated exposures) currently fail closed for non-full-sudo SQL filters, ordering, grouping and aggregates: the copied local value cannot authorize its target rows. The Access error is Querying generated alias '<model>.<field>' requires target-record authorization. This restriction applies even when the caller can read a particular target; it remains until SQL target authorization is implemented. Same-record aliases and direct owning-model queries retain ordinary behavior. Explicit point reads still check each target row and company. Explicit full sudo keeps its existing field-access bypass. Unrelated native compute_sudo behavior is unchanged; generation itself never introduces a sudo callback. fields_get omits inaccessible outputs; for accessible outputs it exposes database_generated = true, generated_storage = "virtual" or "stored", and readonly = true. Generation expressions are not exposed by this metadata.

    New/onchange records have no authoritative generated value, even when they have an origin. Explicit reads return Programming: Generated field '<model>.<field>' requires a persisted record. The candidate’s web-read and onchange serializers omit unavailable output keys, including ordinary derived fields whose declared inputs require a generated value. They do not return an origin value or NULL preview. Availability is per record: mixed batches preserve requested outputs on persisted rows and omit them only from new rows, retaining input order. This also applies to nested relations; unavailable derived relations are omitted before traversal or compute. Persisted siblings and expanded targets retain their ordinary access checks. Editable x2many assignment still uses the existing origin-backed new-line and originless-line cleanup rules. Raw SQL writers retain the existing explicit cache invalidation duties.

    Remote runtime evidence and remaining final-CI/review limits are recorded in docs/design/m4-sqlfields-orm-report.md. No performance improvement is measured.

    Generated expressions follow SQL NULL rules, while domains retain the ordinary field rules. For an Integer output, a comparison such as total > -1 includes NULL when the ordinary falsy value zero satisfies it (SPEC-FIELD-045). This is the domain conversion layer; the generated expression and raw database value remain NULL.

    A native addon may declare input_adapted = true on a generated field that it owns. Only that field’s declaring addon may explicitly set or clear the flag. An extension may wrap the adapter method through ordinary #[method(override)] / Super; it cannot enable another addon’s field. The registry requires an adapter declaration, and ORM construction checks the executable method and its signature before requests are served. A runtime/WASM adapter is refused in this version.

    #[field(integer, generated = "source + other", input_adapted = true)]
    pub total: i32,

    The reserved native method is:

    #[method]
    async fn _adapt_generated_input(
    this: &RecordSet<Line>,
    tx: &mut Transaction,
    input: GeneratedInput,
    ) -> Result<Vec<RawVals>> {
    // Translate each flagged input into ordinary source fields here.
    // input.is_create() distinguishes creation from a persisted write.
    // Read stored sources through this/tx when a write omits a needed counterpart.
    // Return one row per input.rows() position, preserving order.
    }

    GeneratedInput comes from erp_sdk; only core constructs it. Use rows() to inspect it or into_rows() to normalize its owned values. For create, rows have create-input order. For a persisted write, there is one input per target recordset position. If normalized write rows differ, normal write overrides run on ordered singleton targets; equal results retain one batch call. A later singleton error prevents committing earlier writes; roll back the failed transaction. Keep write overrides correct for both batch and singleton calls.

    Core checks the caller’s write permission on flagged input names before calling the adapter. Returned names must be original non-flagged names or stored dependencies of the flagged fields supplied in that same row. Core refuses extra/missing rows, remaining generated names, unrelated or unknown additions, and changes to rows with no flagged input. The ordinary writer still checks translated source permissions, values, constraints, relations and company consistency. An adapter never grants source access by itself.

    The callback may read in the caller’s environment. It cannot create, write, unlink, upsert, flush, change execution authority, finish the transaction or schedule effects. Catching a forbidden-operation error does not make the callback succeed. Reading a field that requires recompute or flush fails naming the model and field. Only dependencies of the read and its access rules are checked; unrelated dirty fields do not block a safe read. Pending writes to fields used by SQL access rules must be flushed before the create or write call that runs the adapter. Read stored sources rather than generated counterparts; ordinary source reads do not prefetch generated siblings during the callback. Trusted native code remains trusted code; this scope is not a process sandbox.

    Typed and dynamic create/write, nested relational commands, import and model-data loads reach the same normalization boundary. Source-only operations do not invoke the callback. Generated context/default values, unflagged outputs, direct unsaved/empty assignment, write_base, upsert and explicit generated copy defaults retain their existing refusal. Generated columns stay readonly and not assignment-eligible; the flag provides no authoritative unsaved preview.

    The generic capability does not define debit/credit arithmetic. Accounting translation and unsaved-line presentation belong to their accounting slices. Consult the implementation report for executed test coverage and the ADR’s current acceptance state.