Skip to content

API Reference parrot_formdesigner.services.storage

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot_formdesigner.services.storage

View source

PostgreSQL Form Storage for the forms abstraction layer.

Implements the FormStorage ABC using asyncpg for PostgreSQL persistence. Forms are stored as JSONB, supporting versioning and UPSERT operations.

Schema, table name, and tenant are configurable. The default schema is navigator (NOT public) and the default table is form_schemas. A tenant slug — when provided — overrides the schema at the SQL level so the same storage instance can serve many tenants (epson.form_schemas, pokemon.form_schemas, …).

Table columns:

  • id: UUID primary key
  • form_uid: UUID — immutable UUID identity (FEAT-389/FEAT-393). Primary uniqueness key for this table, together with version.
  • form_id: VARCHAR — mutable, human-readable slug. Kept for display/search and slug-based lookups via :meth:PostgresFormStorage.load_by_slug.
  • version: VARCHAR
  • schema_json: JSONB (serialized FormSchema)
  • style_json: JSONB (serialized StyleSchema, optional)
  • tenant: VARCHAR (nullable; physical-schema indicator captured for audit)
  • created_at, updated_at: TIMESTAMPTZ
  • created_by: VARCHAR (optional metadata)
  • UNIQUE(form_uid, version) — primary uniqueness (FEAT-389)
  • UNIQUE(tenant, form_id, version) — slug uniqueness per tenant (FEAT-389)

Usage (self-managed pool — recommended): storage = PostgresFormStorage( dsn="postgresql://user:pw@host/db", schema="navigator", table_name="form_schemas", ) await storage.initialize() # creates pool + DDL await storage.save(form_schema) await storage.close() # closes pool

Usage (externally-managed pool — backward compatible): pool = await asyncpg.create_pool(dsn="postgresql://...") storage = PostgresFormStorage( pool=pool, schema="navigator", table_name="form_schemas", ) await storage.initialize() # DDL only, pool not closed on close() await storage.save(form_schema, tenant="epson") form = await storage.load(form_schema.form_uid, tenant="epson") form = await storage.load_by_slug("my-form", tenant="epson")

Attribute DEFAULT_SCHEMA

Attribute DEFAULT_TABLE

Alias FormDialect

Re-exported from parrot_formdesigner.core.schema.FormDialect.

Alias FormSchema

Re-exported from parrot_formdesigner.core.schema.FormSchema.

Alias FormStorage

Re-exported from parrot_formdesigner.services.registry.FormStorage.

Class PostgresFormStorage

Persist FormSchema objects in a PostgreSQL table using asyncpg.

Supports two construction modes:

  1. Self-managed pool (recommended): pass dsn (or connection kwargs). initialize() creates the pool; close() closes it.

  2. External pool (backward compatible): pass an existing pool. close() will NOT close an externally-provided pool.

The target schema is assumed to exist — it is NOT auto-created. Configure per-tenant schemas at the DBA level before using a tenant override.

Parameter Type Default Description
pool Any | None None An existing asyncpg connection pool. When provided, _owns_pool is False and close() will not close it.
dsn str | None None asyncpg DSN string (e.g. "postgresql://user:pw@host/db"). Used by initialize() to create the pool when pool is None.
schema str DEFAULT_SCHEMA Postgres schema where the table lives. Default "navigator". Used when no per-call tenant overrides it.
table_name str DEFAULT_TABLE Table name within schema. Default "form_schemas".
tenant str | None None Optional default tenant slug. When set, every operation without an explicit tenant= kwarg targets <tenant>.<table_name> instead of <schema>.<table_name>.
min_size int 2 Minimum asyncpg pool size (default 2). Ignored when pool is provided externally.
max_size int 10 Maximum asyncpg pool size (default 10). Ignored when pool is provided externally.
**pool_kwargs Any {} Additional keyword arguments forwarded to asyncpg.create_pool() when creating a self-managed pool.

Method PostgresFormStorage.initialize

Create the configured table if it does not exist.

When no pool was provided at construction time, creates a new asyncpg pool using the stored DSN and pool sizing parameters. This is idempotent — safe to call on every startup.

The target schema must already exist; initialize() will NOT create it.

initialize(*, tenant: str | None = None) -> None

Parameter Type Default Description
tenant str | None None Optional tenant override; resolves the schema for this single call.

Method PostgresFormStorage.close

Close the asyncpg pool if this storage owns it.

When the pool was provided externally (pool=... kwarg at construction), this method is a no-op — the caller retains pool ownership.

Idempotent: calling close() multiple times does not raise.

close() -> None

Method PostgresFormStorage.save

Persist a FormSchema (UPSERT by form_uid + version, FEAT-389).

If form.form_id (slug) changed since this form_uid was last saved, the stored form_id column is updated to the new slug — renaming a form never breaks its form_uid-keyed storage row.

save(form: FormSchema, style: StyleSchema | None = None, *, created_by: str | None = None, tenant: str | None = None) -> str

Parameter Type Default Description
form FormSchema FormSchema to persist.
style StyleSchema | None None Optional associated StyleSchema.
created_by str | None None Optional creator identifier for audit trail.
tenant str | None None Optional per-call tenant override. If omitted, falls back to form.tenant, then the storage's default tenant, then schema.

Returns: str — The form_id of the saved form.

Method PostgresFormStorage.promote

Promote a version to published, in place (FEAT-433 Module 6).

An upsert whose update half is conditionally skipped (see :meth:_promote_sql) — this is the authoritative immutability guard for publish() (spec §8 Q5): a published row can never be silently re-promoted or overwritten, because the WHERE clause on the conflicting update excludes it. A version with no existing row (the form's very first publish) is written normally — there is nothing published yet to protect. The editor's own save path is untouched — it keeps using :meth:save's unconditional ON CONFLICT ... DO UPDATE UPSERT, which legitimately rewrites a draft in place.

promote(form_uid: uuid.UUID, version: str, schema_json: str, *, tenant: str | None = None) -> bool

Parameter Type Default Description
form_uid uuid.UUID The form's immutable UUID (FEAT-389).
version str The version tag being promoted.
schema_json str The new (already published_version-stamped) schema, serialized (FormSchema.model_dump_json()).
tenant str | None None Optional tenant override; resolves the schema for this single call.

Returns: bool — True if the row was written (promoted, or written for the first time); False if no row was affected — the version is ALREADY published (the guard).

Method PostgresFormStorage.load

Load a FormSchema from PostgreSQL by its immutable form_uid.

load(form_uid: uuid.UUID, version: str | None = None, *, tenant: str | None = None) -> FormSchema | None

Parameter Type Default Description
form_uid uuid.UUID form_uid (immutable UUID) of the form. NOT form_id — use :meth:load_by_slug for slug-based lookups.
version str | None None Specific version to load. If None, loads the latest.
tenant str | None None Optional tenant override; resolves the schema for this single call.

Returns: FormSchema | None — FormSchema if found, None otherwise.

Method PostgresFormStorage.load_by_slug

Load a form by its mutable slug (form_id) + tenant (FEAT-389).

Backward-compatible slug-based lookup for callers that only know a form's human-readable form_id (not its form_uid). Returns the latest version (by updated_at) unless version is given.

load_by_slug(form_id: str, tenant: str, version: str | None = None) -> FormSchema | None

Parameter Type Default Description
form_id str The form's human-readable slug.
tenant str Tenant to query — REQUIRED (unlike load(), this filters the tenant column directly, not just schema resolution, since slugs are only unique per tenant).
version str | None None Specific version to load. If None, loads the latest.

Returns: FormSchema | None — FormSchema if found, None otherwise.

Method PostgresFormStorage.delete

Delete all versions of a form from PostgreSQL by its form_uid.

delete(form_uid: uuid.UUID, *, tenant: str | None = None) -> bool

Parameter Type Default Description
form_uid uuid.UUID form_uid (immutable UUID) of the form to delete. NOT form_id.
tenant str | None None Optional tenant override; resolves the schema for this single call.

Returns: bool — True if at least one row was deleted, False if not found.

Method PostgresFormStorage.list_forms

List all persisted forms (latest version of each).

list_forms(*, tenant: str | None = None) -> list[dict[str, Any]]

Parameter Type Default Description
tenant str | None None Optional tenant override; resolves the schema for this single call.

Returns: list[dict[str, Any]] — List of dicts with keys form_uid, form_id, version, title, description, tenant, and created_at. description may be None when the form has no description; created_at is an ISO-8601 string or None.

Method PostgresFormStorage.list_versions

Every stored version of one form, in one ordered query (FEAT-433).

Replaces reconstructing history by probing load() per candidate version. Ordered by the parsed (major, minor) integers via a guarded CASE cast (see :meth:_list_versions_sql) — never by the raw version string or a numeric coercion of it.

list_versions(form_uid: uuid.UUID, *, tenant: str | None = None) -> list[dict[str, Any]]

Parameter Type Default Description
form_uid uuid.UUID The form's immutable UUID (FEAT-389).
tenant str | None None Optional tenant override; resolves the schema for this single call.

Returns: list[dict[str, Any]] — Rows of {"version", "created_at", "updated_at", "form_id", "published_version", "published_at"} — the projected fields, NOT the whole schema_json — oldest first.

Alias StyleSchema

Re-exported from parrot_formdesigner.core.style.StyleSchema.

Attribute logger

Alias qualified_table

Re-exported from parrot_formdesigner.services._identifiers.qualified_table.

Alias validate_identifier

Re-exported from parrot_formdesigner.services._identifiers.validate_identifier.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally