Registry stack documentation: machine-readable Markdown.
Index of all pages: https://docs.registrystack.org/llms.txt
Full corpus: https://docs.registrystack.org/llms-full.txt

# Declare native field patterns

> Constrain string and text fields and Action inputs with a PostgreSQL regular expression, verify it before activation, and evolve it through package changes.

A persisted `string` or `text` field in a Base Registry Engine (BReg) project can declare `pattern` using PostgreSQL's native advanced regular-expression syntax.
PostgreSQL 17 or newer remains the minimum version.

Phase 1 field encryption cannot preserve that database-enforced contract without disclosing plaintext to PostgreSQL.
The compiler therefore refuses a field that combines `pattern` with `encrypted: true` at the authored `pattern` path, using `breg.field.encrypted-pattern-refused`.
Remove `pattern`, or keep the field in plaintext storage when the native pattern is required.

```yaml
fields:
  - id: identifier
    type: string
    maximumLength: 13
    required: true
    classification: restricted
    pattern: '^[0-9]{13}$'
```

This example accepts exactly 13 ASCII digits, preserves a leading zero, and rejects whitespace, Unicode digits, and embedded or trailing newlines.
A string is a suitable representation when leading zeros belong to the value.
The rule does not implement a checksum or identify a national identifier system.

The native `~` operator uses the authored expression unchanged.
There is no implicit anchoring, case conversion, or flag rewriting.
An unanchored expression matches a substring.
Native options embedded in the expression retain their PostgreSQL meanings.
Requiredness remains separate: SQL null passes the pattern check wherever the field or governed request-detail retention permits null.
An empty string is matched normally, and an empty pattern is valid PostgreSQL syntax.
Derived fields and other field types cannot declare `pattern`.
An Action input may declare one too; see [Add a pattern to an Action input](#add-a-pattern-to-an-action-input).

An expression is limited to 4096 UTF-8 bytes and cannot contain NUL.
Values keep the existing field bounds: `string.maximumLength` is at most 1,000,000 characters, and `text.maximumLength` is at most 10,000,000 characters.
The HTTP request, transaction, and database statement deadlines continue to bound execution, including native regex evaluation.
A pathological expression can exhaust those limits.
Review and schema-test expressions against representative values before activation.
Runtime callers supply values, never expressions.

{/* Evidence: crates/registry-breg/tests/native_patterns.rs native_pattern_is_persisted_bounded_and_not_a_portable_schema_pattern;
    crates/registry-breg/tests/native_patterns.rs patterns_are_rejected_on_derived_and_non_string_fields_and_safely_quoted;
    crates/registry-breg/src/compiler.rs breg.field.encrypted-pattern-refused. */}

## Add a pattern to an Action input

A `string` or `text` Action input can declare `pattern` in the same dialect and within the same bounds as a Record field: at most 4096 UTF-8 bytes, no NUL.
The Action refuses a submitted value that does not match before it writes anything, and a Proposal Action applies the same check when a draft is started and when it is edited, revised, or rebased.

```yaml
inputs:
  - id: postal-code
    apiName: postalCode
    typeRef: postal-code
    pattern: '^[0-9]{5}$'
    required: true
    classification: internal
```

The expression sits beside `typeRef` on the input, as it does on a Record field.
A reusable `valueTypes` entry cannot carry `pattern`, so a shared type cannot add one to every Action that uses it.
An input of any other type is refused with `breg.action.input-pattern-type-unsupported`, and an expression over the bounds with `breg.action.input-pattern-bounds-invalid`.

PostgreSQL evaluates the expression with the same `~` operator and no rewriting as for a Record field, using the connection that runs the Action, so BReg has no second regular-expression engine.
A mismatch returns HTTP 400 `request.invalid` with `fieldPath` naming the input (`/input/postalCode`); neither the expression nor the submitted value is returned.
Absent and null values are not tested; `required` decides those.
Each patterned string input costs one extra round trip on the Action's connection.

The expression is not published in generated JSON Schema or OpenAPI, for the same reason as for a Record field.
Its syntax cannot be checked offline.
`bregctl check` reports `breg.action.input-pattern-unverified-offline` at the authored input.
Unlike a Record field pattern, no installer step evaluates an input pattern, so PostgreSQL rejects invalid syntax only when an Action first receives a value for that input.
The Action then refuses with HTTP 503 and logs the Action and input identifiers without the expression.
Exercise every patterned Action input in a fixture journey (`bregctl test`) before activation.

A value that passes the input pattern still meets the Record field's own pattern and CHECK at write time, which stays authoritative for storage integrity.

{/* Evidence: crates/registry-breg/tests/action_input_patterns.rs a_pattern_beside_a_type_reference_is_kept_on_the_compiled_input;
    crates/registry-breg/tests/action_input_patterns.rs an_inline_string_input_may_declare_a_pattern;
    crates/registry-breg/tests/action_input_patterns.rs the_native_expression_does_not_become_a_portable_schema_pattern;
    crates/registry-breg/tests/action_input_patterns.rs a_pattern_on_a_non_string_input_is_refused;
    crates/registry-breg/tests/action_input_patterns.rs an_oversized_pattern_is_refused_without_echoing_it;
    crates/registry-breg/tests/action_input_patterns.rs syntax_is_left_to_postgresql_as_it_is_for_a_record_pattern;
    crates/registry-breg/tests/action_input_patterns.rs a_reusable_value_type_cannot_carry_a_pattern. */}

{/* TODO[evidence]: the HTTP 400 request.invalid mismatch response and the HTTP 503 refusal on invalid input-pattern syntax have no located test. */}

## Verify before activation

`bregctl check <project>` performs offline structural checks and generates safely quoted PostgreSQL SQL.
It cannot establish PostgreSQL expression syntax or existing-data conformance.
It reports `breg.field.pattern-unverified-offline` for each pattern at its authored field path.
These are advisory findings unless `--deny-warnings` is selected.

Use the normal PostgreSQL-backed `bregctl test <project> --runtime-config <config> --credentials <credentials> --output <receipt.json>` and the package workflow before activation.
The compiled installer explicitly evaluates each native expression even when all fixture tables are empty.
An invalid expression refuses schema-test and installation.
Schema-test and activation report `breg.field.pattern-syntax-invalid` at the authored path of the field `pattern`, using authored identifiers and a repair hint without including the expression or raw database diagnostic.
A failed activation keeps its exact target pinned in maintenance.
Invalid syntax cannot be repaired by changing that target's bytes: restore the operator's pre-activation backup, correct the expression, and repeat schema-test, packaging, and activation.
No command clears failed maintenance to bypass this recovery.

The compiled effective model preserves the expression.
Caller-filtered operation metadata exposes it under `storageValidation` with `kind: postgresql-are`; see the [Base Registry Engine API reference](../../reference/breg-api/).
Generated JSON Schema and OpenAPI value schemas do not publish a standard `pattern`, because their regex semantics are different.

{/* Evidence: crates/registry-breg/tests/native_patterns.rs native_pattern_is_persisted_bounded_and_not_a_portable_schema_pattern;
    crates/registry-bregctl/src/check.rs breg.field.pattern-unverified-offline;
    crates/registry-bregctl/src/lib.rs breg.field.pattern-syntax-invalid. */}

## Know how a violation is refused

A named database CHECK enforces the rule for every current-row writer, including direct CRUD, atomic batches, Actions, reviewed application, and authorised SQL.
Ordinary CRUD does not invoke an Action handler.
A rejected SQL mutation rolls back with its transaction.
Direct writes and immediate Actions return HTTP 409 with `code: mutation.conflict` and the authored Record type and field admitted by their write contract.
Repair the submitted value before trying again; retrying the unchanged request cannot make the value conform.
HTTP 409 does not promise that a conflict is transient.
Proposal application returns the existing generic conflict because application authority does not grant target-field disclosure.
No response includes stored values, physical table names, constraint names, or raw PostgreSQL diagnostics.

Fixture journeys for a direct-write or immediate-Action pattern rejection declare the exact authored identifiers in the expectation:

```yaml
expect:
  outcome: refusal
  status: 409
  problemCode: mutation.conflict
  recordType: person
  fieldId: identifier
```

`recordType` and `fieldId` are optional together and allowed only for this conflict expectation.
Preflight checks that the pair names a patterned field on a target of the step; execution requires that exact pair in the response.
Preflight does not evaluate PostgreSQL expressions or infer the failed field from input values.
Omit both identifiers when expecting a generic conflict, such as a duplicate unique value or a concealed Proposal application failure.
That expectation accepts a response without field metadata.
On a direct create, patch or batch it also accepts the members a row-local constraint refusal adds (`recordType`, `constraintId`, `constraintKind`, and `left` and `right` or `field`) when they exactly match a compare, int-range or vocabulary constraint declared on the step's Record type whose fields the step's access profile reads.
Any other member, such as `fieldId`, and unknown, partial or mismatched constraint members are refused.

{/* TODO[evidence]: no test located for the 409 mutation.conflict response members on a pattern violation or the fixture expectation pairing of recordType and fieldId; the closest anchor is crates/registry-breg/tests/native_patterns.rs native_pattern_is_persisted_bounded_and_not_a_portable_schema_pattern. */}

## Evolve a pattern through package changes

Every pattern check has a stable identity derived from its Record type and field, independent of the expression.
Its physical-name inventory member is `pattern:<field-id>`.
The generated schema fingerprint covers the native CHECK.

Adding a rule emits `field-pattern-added`, classified `compatible-additive` like existing added CHECK constraints.
This classification permits the compiler-owned DDL path; it does not promise that existing rows or future writes satisfy the new rule.
PostgreSQL validates every existing row before the addition commits.
A failure leaves the old package active and the target pinned in maintenance.
Activation reports `breg.field.pattern-existing-rows-invalid` at the authored field.
Correct the violating data using the documented operator recovery procedure, then retry the exact target.
A successful future write alone does not validate the preexisting rows.

Adding or replacing the validated CHECK takes an `ACCESS EXCLUSIVE` table lock and scans existing rows.
Plan a maintenance window around the table size and expression cost, including readers and writers that may already hold locks.
The lock is held until the migration transaction ends.
Rehearse with representative data, and size `operationalTimeouts.migrationStatementMilliseconds` for lock acquisition and the full validation scan.
`migrationLockMilliseconds` bounds each lock wait; keep it shorter than the statement timeout when a separate lock-wait limit is useful.
Reviewed steps use their packaged `lockTimeoutMilliseconds` and `statementTimeoutMilliseconds` bounds.
A timeout leaves the same maintenance and recovery interlock.
See PostgreSQL's [ALTER TABLE locking and validation](https://www.postgresql.org/docs/18/sql-altertable.html) and [statement and lock timeouts](https://www.postgresql.org/docs/18/runtime-config-client.html).

Changing or removing a rule emits `field-pattern-changed` or `field-pattern-removed`, classified `destructive-or-irreversible` under the existing reviewed migration contract.
This includes loosening: the compiler does not attempt to prove containment between two regex languages.
A reviewed change covers the authored field and its implicit `pattern:<field-id>` constraint; reviewed SQL drops the existing check and installs the candidate check when one remains.
Use one transactional `ALTER TABLE` statement with `DROP CONSTRAINT` and `ADD CONSTRAINT` clauses and a validated CHECK, not `NOT VALID`.
The existing rehearsal, backup binding, exact catalog fingerprint, and recovery requirements still apply.
No orphan constraint remains after removal.

Record field patterns also bind Action and Proposal fingerprints.
Unchanged patterns preserve their existing contracts.
A relevant changed pattern makes a pending frozen Proposal incompatible.
Use the existing authorised rebase, resubmission, and configured review process; activation does not silently rewrite Proposal values or rerun their computation.

Governed request-detail clearing can null eligible retained intake fields even when their normal create contract requires a value and declares a pattern.
This remains separate from retained-history erasure, which does not rewrite the current row.

{/* Evidence: crates/registry-breg/tests/native_patterns.rs native_pattern_evolution_has_stable_identity_and_explicit_reviewed_changes. */}

## Keep an identity fixed

To keep an identity field from being retargeted, list it in `writableFields` only on a profile that creates the Record and has no patch operation.
Give the profile that patches the Record `writableFields` that omit the field.
No access profile then holds both the patch operation and that field, so a request that tries to replace it is refused before the write.
This is an HTTP authority boundary for the configured profiles only.
It does not make the field physically immutable to package evolution or to an operator holding migration authority, so review those powers separately.
If the identity itself must change, model that as a new Record, a normalised dated observation, a separate Record type, or a narrow typed Action with the required review semantics.

{/* Evidence: crates/registry-breg/tests/postgres_client_capabilities.rs (writableFields bound the accepted fields);
    crates/registry-breg/tests/access_configuration.rs */}

## Next

- [Control access and reads](../breg-access/)
- [Actions and Proposals](../breg-actions/)
- [Configure Proposals](../breg-proposals/)
- [Base Registry Engine API reference](../../reference/breg-api/)