Source code for fsh_lib.identifiers
"""Create-form field helper for server-assigned identifiers.
A column whose value the database fills in -- an autogenerated
identifier like the ``100001`` in "Order #100001", produced by
pgcraft's ``PGCraftAutogeneratedIdentifierColumn`` -- must not
appear as a required input on a create form. The client never
supplies it; the ``BEFORE INSERT`` trigger does.
Generated create models declare such a field through
:func:`autogenerated_identifier_field`. It marks the field
optional and read-only and tags it with the ``x-autogenerated``
OpenAPI extension, mirroring the ``x-*`` convention in
:mod:`fsh_lib.openapi`: the FE codegen layer reads the extension and
renders the field as a server-assigned, non-editable value instead
of a form input.
"""
from __future__ import annotations
from typing import Any
from pydantic import Field
#: OpenAPI schema-extension key carrying the pgcraft identifier
#: name (the "enum" key) that produces a field's value. Present on
#: every field built by :func:`autogenerated_identifier_field`.
X_AUTOGENERATED = "x-autogenerated"
[docs]
def autogenerated_identifier_field(
*,
name: str,
description: str | None = None,
) -> Any:
"""Build a pydantic field for a server-assigned identifier.
The returned field is optional (defaults to ``None``, so a
create request may omit it) and read-only, and carries the
:data:`X_AUTOGENERATED` extension so FE codegen can label it
with the originating counter and suppress the input control.
Use it as the default of a create-model field::
class OrderCreate(BaseModel):
customer: str
order_no: str | None = autogenerated_identifier_field(
name="order",
)
Args:
name: The pgcraft identifier-counter name (the "enum" key)
that produces this value. Surfaced under
:data:`X_AUTOGENERATED` so the FE can label the field.
description: Optional human-readable description for the
generated JSON schema.
Returns:
A pydantic ``FieldInfo`` -- typed ``Any`` so it can sit
directly as a model-field default -- declaring the field
optional, read-only, and tagged ``x-autogenerated``.
"""
return Field(
default=None,
description=description,
json_schema_extra={
"readOnly": True,
X_AUTOGENERATED: name,
},
)
__all__ = ["X_AUTOGENERATED", "autogenerated_identifier_field"]