@simetrajs/designer 0.2.0 → 0.3.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -26,6 +26,8 @@ export const client = defineObjectModule<Catalogs.Client>({
26
26
  the draft `{ values?, tabularSections? }` the phase writes. It never adds
27
27
  `id` or `mark`; the runtime checks the returned draft again.
28
28
  - `onWrite` (1C `ПриЗаписи`) sees the written row in the same transaction.
29
+ The row has the shape of a card read: the tabular sections that the phase
30
+ wrote are under `row.tabularSections.<name>`.
29
31
  - Both run on the operations `create`, `update` and `markDeletion`;
30
32
  `delete` raises no module event. On `markDeletion` the draft is empty and
31
33
  the mark is `ctx.mark`.
@@ -39,8 +41,24 @@ export const client = defineObjectModule<Catalogs.Client>({
39
41
  `ctx.isNew` is `create`; `ctx.user` is the current user.
40
42
  - `ctx.additionalProperties` is shared by the hooks of one phase only.
41
43
  - `ctx.run(operation)` runs a phase of another object in the same
42
- transaction, with its own rights check and hooks; `ctx.read(query)` reads in
43
- that transaction.
44
+ transaction, with its own rights check and hooks, and returns the written
45
+ row in the same shape as `onWrite` sees it; `ctx.read(query)` reads in
46
+ that transaction. It takes the query of `data-read` and returns `{ rows }`
47
+ or `{ count, capped? }`, e.g.
48
+ `ctx.read({ object, where: { attribute: "code", op: "eq", value }, limit: 1 })`.
49
+ - A tabular section array in an `update` passed to `ctx.run` replaces the
50
+ section: every existing row must be in the array or in `deleteIds`,
51
+ otherwise the command fails with `command.invalid`
52
+ `reason: "tabular-rows-missing"` — the same rule as `data-command`.
53
+ `ctx.run` always checks this. Build the array from a `ctx.read` of the
54
+ owner's lines.
55
+ - One command transaction may start at most `BATCH_MAX` phases through
56
+ `ctx.run`; past it the command fails with `command.depth`
57
+ `reason: "phases"`. Nesting deeper than the runtime's depth limit is
58
+ `command.depth` too.
59
+ - Hook time counts toward the command's time budget: a command past it
60
+ fails with `command.timeout`, and a lock wait past the lock timeout with
61
+ `command.busy`. Keep hooks short.
44
62
  - `ctx.reject(code, path?)` fails the command with `command.rejected`.
45
63
  - A `ctx` method works only while its hook runs. Never keep `ctx` for later:
46
64
  a late call fails the command (`command.internal`).
@@ -115,7 +115,9 @@ with a trigger on the target table, see "Carrier copies").
115
115
  `rights.dimension-name-reserved`.
116
116
  The function is verbatim SQL of a closed form: no arguments,
117
117
  `RETURNS SETOF uuid LANGUAGE sql STABLE SECURITY DEFINER SET search_path = ''`
118
- with an `AS $$ … $$` body,
118
+ plus the pinned session settings of a head (the exact `SET` options are in
119
+ the hint of `sql.head-settings`; without them that error, the same for a
120
+ verbatim scope set function) with an `AS $$ … $$` body,
119
121
  every name schema-qualified (also in the views it reads and the `sql`
120
122
  functions it calls; a `plpgsql` function in that chain is refused), and no
121
123
  `simetra.*` object except `simetra.current_user_id()`
@@ -360,7 +362,8 @@ catalogs through `runtime.run` (`simetra/server`). Every operation on them
360
362
  runs under `administerRights`:
361
363
 
362
364
  - custom role: `create`, `update` with `expectedVersion` (the `delta`
363
- tabular section is replaced whole), `markDeletion` on the roles catalog;
365
+ tabular section is replaced whole: name every existing line in the array
366
+ or in `deleteIds`), `markDeletion` on the roles catalog;
364
367
  - assignment: `create`, and `delete` with `expectedVersion`, on the role
365
368
  assignments catalog.
366
369
 
@@ -605,8 +608,15 @@ whose user id is the `sub` claim):
605
608
  - A table of a kind is read only through a role's `read` right on its object,
606
609
  at the extent of the grant (`any`, `own`, a dimension, in a container); its
607
610
  tabular sections and a register's movements and totals follow the object.
608
- `publicRead` opens every row instead and needs no right. It is an error
609
- (`rights.public-read-forbidden`) on the users catalog, a membership catalog
611
+ `publicRead` as a string opens every row instead and needs no right. The
612
+ conditional form `{ "role": "anon" | "authenticated", "published": true }`
613
+ opens only rows that are published and not marked for deletion (the header
614
+ and its tabular sections): it needs a catalog with commands, rights
615
+ functions and a rights contract with `read`, keeps the read policies and the
616
+ tenant boundary for everyone else, and adds the actions `publish` and
617
+ `unpublish`; marking a row for deletion unpublishes it. Example:
618
+ `"publicRead": { "role": "anon", "published": true }`. Any
619
+ `publicRead` is an error (`rights.public-read-forbidden`) on the users catalog, a membership catalog
610
620
  and the rights system catalogs: for public profiles declare a separate
611
621
  catalog with the public fields and a reference to the users catalog.
612
622
  - A scoped object is read only inside the reader's scopes, and only through a
@@ -676,40 +686,142 @@ on another overload of the same name is not affected.
676
686
  `simetra_command` (`NOLOGIN NOINHERIT`, on the target and the shadow server)
677
687
  and, when a project file is present, the runtime login role `simetra_runtime`
678
688
  on the target only (`LOGIN NOINHERIT`, a member of `simetra_command` and, for
679
- `supabase`, of `authenticated`, each `WITH INHERIT FALSE, SET TRUE`). It reads
689
+ `supabase`, of `authenticated` and `anon`, each `WITH INHERIT FALSE, SET TRUE`). It reads
680
690
  `database.provider` from the project file; without a project file it skips the
681
691
  login role, and the output says why. The operator sets the login role's
682
- password; the platform keeps no secrets.
692
+ password; the platform keeps no secrets (the one exception, a database on your
693
+ machine, is `--dev-passwords` below).
683
694
 
684
695
  The login role needs `ADMIN OPTION` on each of its parent roles in the role
685
696
  that runs `roles`. Without it `roles` still creates the grant roles, but
686
697
  refuses the login role with `roles.admin-option-missing` and does not create
687
- it. An existing role is only checked, never changed.
698
+ it. An existing role is only checked, with one change: after upgrading
699
+ Simetra, run `roles` again on an existing database; it adds a missing
700
+ membership of the login role in a parent of its profile, or refuses with
701
+ `roles.membership-grant-denied`, which names the `GRANT` to run.
702
+
703
+ ### The `postgres` provider
704
+
705
+ On `database.provider: "postgres"` the same command prepares the cluster and
706
+ needs a superuser that logs in as itself. Give it through
707
+ `--database-url-env <VAR>` (a variable other than the owner's, so the
708
+ superuser DSN is not the one `plan` and `apply` use). It creates the roles of
709
+ the profile, the application database owned by `simetra_owner`,
710
+ `plpgsql_check` in that database, and the sealed template database
711
+ `simetra_template` that shadows and proof copies are built from. Running it
712
+ again converges the declared state and creates nothing.
713
+
714
+ For a database on your machine, `simetra roles --dev-passwords` (MCP input
715
+ `devPasswords: true`) also sets the password of each login role this run
716
+ creates (`simetra_owner`, `simetra_auth`, `simetra_runtime`,
717
+ `simetra_signals`) from `SIMETRA_OWNER_DEV_PASSWORD`,
718
+ `SIMETRA_AUTH_DEV_PASSWORD`, `SIMETRA_RUNTIME_DEV_PASSWORD` and
719
+ `SIMETRA_SIGNALS_DEV_PASSWORD` in the environment. A role that already exists
720
+ keeps its password. It refuses before anything is written when a variable is
721
+ missing or empty (`roles.dev-password-missing`), when the database host is not
722
+ this machine — `localhost`, `127.0.0.0/8`, `::1` or a unix socket
723
+ (`roles.dev-passwords-remote`), or when the provider is not `postgres`
724
+ (`roles.dev-passwords-unsupported`). On any other server set the passwords
725
+ yourself.
726
+
727
+ The identity provider's own roles get their grants here too: the role of the
728
+ platform owner receives `USAGE` on the `better_auth` schema and `TRIGGER` and
729
+ `REFERENCES` on `better_auth."user"`, so the provision triggers and the foreign
730
+ keys of the model can sit on the account table. Before the identity provider's
731
+ migration has created that table, the table grants are skipped and the output
732
+ says so; run `roles` again after the migration. The spec of the
733
+ profile has the role set and the reasons:
734
+ `docs/superpowers/specs/2026-11-08-postgres-profile-design.md` §3.
735
+
736
+ Refusals, all raised before anything is written unless the hint says
737
+ otherwise:
738
+
739
+ - `roles.superuser-required` — the role is not a superuser, or its current
740
+ role differs from the login role; connect as the superuser.
741
+ - `roles.unsafe-schema` — a schema in the database (`extensions`,
742
+ `better_auth`) has an owner or content a superuser session must not trust;
743
+ the hint lists what to fix by hand.
744
+ - `roles.unsafe-template` — `simetra_template` is owned by a non-superuser,
745
+ accepts connections, or is closed without being marked as a template; drop
746
+ it as a superuser and run `roles` again.
747
+ - `roles.database-owner` — the database belongs to another role than
748
+ `simetra_owner`; fix the owner by hand or use a database `roles` creates.
749
+ - `roles.database-locale` — the database or `simetra_template` has another
750
+ collation than ICU `en-US`; `roles` never drops a database: dump, drop and
751
+ restore it by hand around a new `roles` run (the template is only dropped).
752
+ - `roles.shared-cluster` — a Simetra login role has an explicit `CONNECT` on
753
+ other databases; one cluster serves one application.
754
+ - `roles.extension-unavailable` — the server does not offer `plpgsql_check`
755
+ in `pg_available_extensions`; install the extension's package on the
756
+ database server (`postgresql-<major>-plpgsql-check` from PGDG) and run
757
+ `roles` again. `apply` refuses the same way with
758
+ `apply.extension-unavailable` before it locks any table when its plan checks
759
+ function bodies with the extension and the server no longer offers it.
760
+ - `plan.owner-not-bypassrls` — the role of `plan`, `apply` or `rehearse` has
761
+ neither `BYPASSRLS` nor superuser; run `ALTER ROLE <role> BYPASSRLS` as a
762
+ superuser.
763
+ - `plan.shadow-base-unsupported` — a separate shadow server is not supported
764
+ on `postgres`; drop `--shadow-url-env`.
765
+
766
+ - `plan.identity-table-missing` — the model needs provision triggers on the
767
+ account table of the identity provider and the connected role cannot place
768
+ them: reason `table` means the table does not exist yet (run the provider's
769
+ migration first), reason `privilege` means the role lacks `USAGE` on its
770
+ schema or `TRIGGER` on the table (run `roles` again as the superuser).
771
+ - `plan.identity-trigger-locked` — on `postgres` only the owner of the account
772
+ table can remove or enable a provision trigger on it, and `plan` does not run
773
+ as that owner: reason `removed` means the plan drops a trigger, reason
774
+ `disabled` means it would enable a trigger that is disabled. Do the change by
775
+ hand as the table owner.
688
776
 
689
777
  `plan.platform-role-shape` with the violation `request-role:<role>` means an
690
778
  API request role (such as `authenticated`) and a platform role are members of
691
779
  each other in some form, even `ADMIN` alone; revoke that membership.
692
780
 
781
+ ### Runtime login and anonymous sessions
782
+
783
+ The runtime refuses to start with `command.privileged-login` when its login
784
+ role reaches a power it must not hold, itself or through a membership; the
785
+ `reason` names the first fact found: `owner`, `superuser`, `bypassrls`,
786
+ `createrole`, `server-files`, `read-all-data`, `write-all-data`,
787
+ `database-owner` (the login owns the current database), `provider-login` or
788
+ `service`. Use the
789
+ dedicated runtime login role `simetra_runtime`, not an owner, a superuser or a
790
+ provider login.
791
+
792
+ An anonymous session is a guest and reads as one. On a provider whose
793
+ identity data marks anonymous sessions with a claim, a session that has a
794
+ subject but no anonymous claim is refused with `command.unauthenticated`
795
+ before any database work: the claim must be present, `true` or `false`.
796
+
693
797
  ## Reading past row-level security
694
798
 
695
- `sql.definer-reads-rls` (a warning) marks a unit that reads a table under
799
+ A `SECURITY DEFINER` function runs as its owner, the applying role, which
800
+ bypasses row-level security (`FORCE ROW LEVEL SECURITY` does not stop it).
801
+ One that a role of the API (or `PUBLIC`) may `EXECUTE` fails `compile` with
802
+ `sql.definer-caller-unchecked` in any `.sql` file, SQL debt included, whatever
803
+ it reads, until it names the check of its caller. Two ways out: link it to a
804
+ scope kind as its set function (or to an access dimension as its values
805
+ function), or declare its signature with the named check. After `introspect`
806
+ from scratch, set functions come back unlinked and fail this way until you
807
+ link them.
808
+
809
+ `sql.definer-reads-rls` (a warning) marks a view that reads a table under
696
810
  row-level security as its owner, so the caller's policies do not apply, while
697
- a role of the API (or `PUBLIC`) can run or read it:
811
+ a role of the API (or `PUBLIC`) can read it:
698
812
 
699
- - a `SECURITY DEFINER` function that someone may `EXECUTE`;
700
813
  - a view without `security_invoker` that someone may `SELECT`;
701
814
  - a materialized view, which stores the rows its owner read at `REFRESH`.
702
815
 
703
- The diagnostic lists the tables it found. The compiler does not see the owner of a function,
704
- so one whose owner is itself subject to row-level security is flagged too.
705
- Convert in this order of preference:
816
+ The diagnostic lists the tables it found. Convert in this order of
817
+ preference:
706
818
 
707
819
  1. Read through a right and a policy: let the caller read the kind's table
708
820
  itself, so the platform's policies decide, and make the unit
709
821
  `SECURITY INVOKER` (a view: `WITH (security_invoker = true)` in
710
822
  `CREATE VIEW`; a separate `ALTER VIEW` is not accepted in `.sql` files).
711
- 2. If the unit must run as its owner, check the caller's membership or rights
712
- inside it, or filter the rows with the rights functions in a view.
823
+ 2. Write the operation as a command of the object or a TypeScript hook; a
824
+ view may filter the rows with the rights functions.
713
825
  3. If no API caller needs it, `REVOKE EXECUTE` (function) or `REVOKE SELECT`
714
826
  (view, materialized view) from `PUBLIC` and from each API role. A
715
827
  materialized view that serves callers is replaced by a view with
@@ -0,0 +1,81 @@
1
+ # The database: plan and apply
2
+
3
+ `plan` compares the live database with the metadata and writes
4
+ `plans/<from>-<to>.plan.json` next to the metadata directory (the directory
5
+ that holds `metadata/`); the database is only read. Its output shows drift
6
+ first, then each step with its class and lock level, then the `planHash`.
7
+ Show the plan to the owner before applying it.
8
+
9
+ The generated SQL grants to platform roles (`simetra_command`) that live in the
10
+ cluster, not in the database, so `plan` does not create them. Without one on
11
+ the target or the shadow server, `plan`, `diff` and `rehearse` refuse with
12
+ `plan.platform-role-missing`: run `simetra roles` once with a role that has
13
+ `CREATEROLE` ("Platform roles" in the people-and-rights reference; `postgres`
14
+ needs a superuser and no separate shadow server). It only checks an existing role; an unsafe
15
+ shape (`plan.platform-role-shape`) is fixed by hand, not by `roles`.
16
+
17
+ `apply` applies exactly that file in one transaction. It needs the `planHash`
18
+ of the reviewed plan, confirmation (`--yes`, MCP `confirm: true`), and in
19
+ `allow` the id of every step that drops data or relaxes a guarantee and
20
+ `drift` when the plan carries drift; the plan output says which items need
21
+ it. `rehearse` runs the plan and rolls it back, but still takes the same
22
+ locks as `apply`. It also builds the desired shadow database and proves on the
23
+ same connection that the catalog equals the desired state, so it holds the
24
+ plan's locks a little longer. A successful `rehearse` writes its report to
25
+ `plans/<from>-<to>.rehearsal.json` next to the plan.
26
+
27
+ Before the end of the transaction, `apply` and `rehearse` re-validate function
28
+ bodies and fire deferred constraints; an invalid constraint or index that the
29
+ desired state does not have is refused. An `apply.function-check-blind` warning lists
30
+ functions the check cannot see (another language, no `EXECUTE` for the role, a
31
+ trigger function without a trigger): nothing proved their bodies, so review
32
+ them by hand.
33
+
34
+ When the role has global default privileges, a plan also ends with environment
35
+ steps: explicit GRANT/REVOKE that cancel them on the objects the plan creates.
36
+ The output shows them as their own group, `environment rights: the global
37
+ default privileges of role <role>`; review them with the rest of the plan.
38
+ If the environment changes before the apply, it is refused
39
+ (`apply.target-changed`); plan again. A plan file from an older tool version is
40
+ refused too: rebuild it with `plan`. After a data-only restore or a
41
+ logical-replication move, reset the row version epoch (the row-version-epoch reference).
42
+
43
+ A promotion plan's `allow` also takes its listed `access:<table>`, `remove:<t>`,
44
+ `repair:<t>`, `delete:<t>.<constraint>` and `update:<t>.<constraint>` items; a
45
+ repair rewrites existing values with the fill expression shown.
46
+ A promotion is applied only with a valid rehearsal report: rehearse the plan on
47
+ a copy of the target with data first. Point the rehearsal at the copy through
48
+ the connection variable: `simetra apply --rehearse --database-url-env <VAR>`
49
+ on the command line, or an MCP server launched with
50
+ `simetra mcp --database-url-env <VAR>` (an MCP server's database is fixed at
51
+ launch). Make the copy from the target after the plan, restore it as the plan's
52
+ role with `pg_restore --no-owner`, on a server with the same PostgreSQL major
53
+ version, encoding and collation; otherwise the rehearsal is refused as not a
54
+ copy of the plan's target (`apply.target-changed`). Rehearsing on the target
55
+ itself is allowed, but it holds the target's locks for the whole run: make it
56
+ a deliberate choice of the owner, not a default. `apply` refuses without a
57
+ report (`apply.rehearsal-required`), with a stale one (`apply.rehearsal-stale`:
58
+ another plan, report format, server, ledger head, or not one row count per
59
+ promoted table), and when a table has rows on the target but none on the copy
60
+ (`apply.rehearsal-copy-empty`); it warns when the copy has fewer rows
61
+ (`apply.rehearsal-fewer-rows`) or when the statement timeout computed from the
62
+ report exceeds what Postgres accepts (`apply.rehearsal-timeout-unbounded`).
63
+
64
+ Which connection to use:
65
+
66
+ - Reads of the target (`introspect`, `diff`, `plan`) run in short read-only
67
+ transactions and work through a transaction-mode pooler.
68
+ - The shadow database of `diff` and `plan` needs a direct or session-mode
69
+ connection: it is created, reached by name and loaded with session settings
70
+ that a transaction-mode pooler is not guaranteed to keep. With a pooled target
71
+ connection, point `--shadow-url-env` at a direct one.
72
+ - A long `apply` wants a direct or session-mode connection too: a pooler may
73
+ cut the transaction with its own timeouts.
74
+
75
+ A changed plan file, changed metadata or a changed database refuses the
76
+ apply; plan again.
77
+
78
+ If `apply` reports `outcome unknown`, the connection was lost and the apply may
79
+ or may not have been committed. Never apply again blindly: look up the printed
80
+ apply id in the `apply_id` column of `simetra.ledger` first — a row means it was
81
+ committed.
@@ -0,0 +1,39 @@
1
+ # Row version epoch
2
+
3
+ Every row of a table with the mechanics trigger carries a `version` from one
4
+ database-wide sequence, `simetra.row_version`. A client keeps a row by its
5
+ version, so a version must never repeat for a key. The database gives the
6
+ client an epoch, `simetra.row_version_epoch()`; when it changes, the client drops
7
+ the versions it holds.
8
+
9
+ The epoch changes on its own when the server restarts, a volume snapshot or a
10
+ point in the past is restored, a failover moves the timeline, or the database
11
+ moves to a new cluster or a new database. It is `NULL` on a replica.
12
+
13
+ Two cases the database cannot see:
14
+
15
+ - **A data-only restore into the same database** (`pg_restore --data-only`,
16
+ `psql` from a dump). The dump brings back old sequence values and the old
17
+ epoch row.
18
+ - **A move by logical replication.** Sequences do not travel, so the new
19
+ sequence may sit below the versions in the rows.
20
+
21
+ After either, the schema owner runs the call below with the application stopped
22
+ and before its first read:
23
+
24
+ ```sql
25
+ SELECT simetra.reset_row_version_epoch();
26
+ ```
27
+
28
+ It seeds the sequence above every version in the mechanics tables and issues a
29
+ new epoch. Versions issued between the restore and the call may repeat: the
30
+ database does not guard that window.
31
+
32
+ Rules for your own SQL:
33
+
34
+ - Never set `synchronous_commit = off` after a row write in a debt unit. The
35
+ mechanics trigger raises the commit to synchronous; `off` makes it
36
+ asynchronous again, and a crash then loses issued versions without an epoch
37
+ change.
38
+ - Never write the `simetra.row_version_*` settings (`sql.debt-session-write`
39
+ warns).
@@ -0,0 +1,28 @@
1
+ # Search fields and mode
2
+
3
+ The object property `search` on a Catalog, a Document or a `CustomTable`
4
+ names what a search of the object looks at (a reference picker, a `contains`
5
+ or `startsWith` filter of a list read).
6
+
7
+ ```json
8
+ { "search": { "fields": ["description", "code"], "mode": "startsWith" } }
9
+ ```
10
+
11
+ - `fields`: logical names of header attributes, standard or custom. Omitted:
12
+ the default fields of the kind — a Catalog's presentation field
13
+ (`description`, or `code` with `mainPresentation: "Code"`; none when its
14
+ length is 0), a Document's `number`, a `CustomTable` none. An object with no
15
+ fields has no search.
16
+ - `mode`: `startsWith` or `contains`; `contains` when omitted.
17
+ - A field of type `String` or `Text` gets a stored derived column and an index
18
+ built by the platform (`<column>_search`); it is not an attribute, so leave
19
+ it out of metadata files and out of `fields`.
20
+ - `startsWith` is read through an index on a bounded prefix of the lowercased
21
+ value, with the exact condition on the full value beside it, so the result
22
+ is the same with or without the index. It is the mode to choose for a large
23
+ table.
24
+ - `contains` has no index: it scans the rows of the scope, so it stays fast
25
+ only for a scope up to about a hundred thousand rows, and a request needs a
26
+ scope equality. Without one the scan covers the whole table.
27
+ - Adding `search` to an adopted `CustomTable` adds the derived column in the
28
+ apply plan; it rewrites the table, so the plan marks it as a heavy step.
@@ -37,8 +37,9 @@ Only commands write a table of a kind: write a change of its rows as a
37
37
  command of the object or its TypeScript hook. No application SQL, in any
38
38
  file and in debt too, writes one: an `INSERT`, `UPDATE`, `DELETE` or `MERGE`
39
39
  in a function or procedure body whose target is a table of a kind, a tabular
40
- section, a view of the model over one, or the provider's account table
41
- (`auth.users`) is `sql.kind-table-verbatim` with the form `functionBody`, also
40
+ section, a view of the model over one, the provider's account table
41
+ (`auth.users`) or any relation of the platform schema `simetra` is
42
+ `sql.kind-table-verbatim` with the form `functionBody`, also
42
43
  inside a literal `EXECUTE`, a `DO` block or a function the body creates.
43
44
  Reading the table (`SELECT`, `FOR UPDATE`, `UPDATE … FROM`, `MERGE … USING`)
44
45
  and `LOCK` are fine. An unqualified table name counts in every schema,
@@ -52,8 +53,11 @@ the statements the hint of `sql.function-body-statement` lists; the field
52
53
  `statement` names the one refused. A body never changes the schema: move DDL
53
54
  into metadata or a migration.
54
55
 
55
- - `nonLiteralExecute`, `dynamicText` (a call of a builtin or provider
56
- function that executes SQL text, such as `query_to_xml` or `dblink`) and
56
+ - `nonLiteralExecute`, `dynamicText` (a call of a builtin that executes SQL
57
+ text, such as `query_to_xml`, or of any function of a provider schema that
58
+ is not on the provider's reviewed list, such as `dblink` or `cron.schedule`;
59
+ in a body without an empty `search_path`, also an unqualified call that is
60
+ neither a builtin nor a function of the model) and
57
61
  `language` (a language other than `sql` and `plpgsql`) cannot be judged:
58
62
  rewrite the function with static SQL or remove it. Partition maintenance or
59
63
  statistics through `EXECUTE format(…)` is refused on adoption for the same
@@ -62,6 +66,16 @@ into metadata or a migration.
62
66
  - A temporary table of the body is `CREATE TEMP TABLE … ON COMMIT DROP`, and
63
67
  every later reference to it (`DROP`, DML, a read) is `pg_temp.<name>`: an
64
68
  unqualified name could hit a table of the same name in your schema.
69
+ - A body leaves no session state behind its transaction: a pooled connection
70
+ serves the next command of another user. A setting is `SET LOCAL` or
71
+ `set_config(…, true)` with the literal `true`; `SET` without `LOCAL`,
72
+ `RESET` and any other `set_config` are `sql.function-body-session-setting`.
73
+ A temporary table named after a type of `pg_catalog` (`name`, `uuid`,
74
+ `text`…) is `sql.function-body-temp-type`: rename it. A session-level
75
+ advisory lock, `setseed`, `currval` or `lastval` is
76
+ `sql.function-body-session-builtin`: take `pg_advisory_xact_lock` instead of
77
+ the lock, and read the generated value from `INSERT … RETURNING` instead of
78
+ `currval` or `lastval`, which depend on the state of the session.
65
79
 
66
80
  Application SQL anywhere (a body, a view, a policy, a domain `CHECK`, a
67
81
  default) calls only the platform and generated functions that read, such as
@@ -91,17 +105,33 @@ model they call, by an allowlist (`sql.head-not-allowed`):
91
105
 
92
106
  - **A handler only checks.** It reads with `SELECT … INTO`, assigns fields of
93
107
  `NEW`, raises errors and returns `NEW` or `NULL`. It writes no table and runs
94
- no `EXECUTE`, `CALL`, `SET` or cursor. A `beforeWrite` handler on a provider
108
+ no `EXECUTE`, `CALL`, `SET`, cursor or `ASSERT` (a session setting can
109
+ switch `ASSERT` off: check with `IF … THEN RAISE`). A `beforeWrite` handler on a provider
95
110
  table (`auth.users`) does not assign `NEW` either. A write the handler did
96
111
  belongs to a command or a TypeScript hook.
97
112
  - **Everything else is a query function.** `LANGUAGE sql`, a string body of
98
113
  exactly one `SELECT` (no `INTO`, no `FOR UPDATE`, no data-modifying `WITH`),
99
- `SET search_path = ''` and no other `SET` option. It reads only qualified
114
+ `SET search_path = ''` and no other `SET` option except the pinned session
115
+ settings below. It reads only qualified
100
116
  tables of kinds, adopted tables and views of the model, and calls only query
101
117
  functions of the model, generated functions that read,
102
118
  `simetra.current_user_id()`, the listed provider functions and allowlisted
103
119
  builtins. A function of a kind module that is not of this form belongs in
104
120
  a shared `sql/` file, called by nothing inside a command.
121
+ - **A scope set function, an access dimension values function and a policy
122
+ function pin the session settings** the client could choose (time zone,
123
+ date, interval, number, money, `bytea` and XML styles, text search
124
+ configuration) with `SET` options of their `CREATE FUNCTION`; the hint of
125
+ `sql.head-settings` lists the exact options (`fix` does not add them). A
126
+ function they call sets none of these to another value.
127
+ - **A verbatim policy expression runs in the client's settings**, and so does
128
+ what it reads: a view and a function that does not pin the settings itself.
129
+ There `current_date`, `localtime` and a conversion to `date`, `time`,
130
+ `timetz` or `timestamp` without `now() AT TIME ZONE '<zone>'`, or to
131
+ `timestamptz` from a value without a zone, is `sql.head-not-allowed`
132
+ (`setting`, `TimeZone`).
133
+ - **A cast to a `reg*` type** names an object by text; only a string literal
134
+ cast to `regclass` (read as that relation) is allowed in a head.
105
135
 
106
136
  ## Reading `sql.head-not-allowed`
107
137
 
@@ -173,10 +203,11 @@ is closed by its own rule:
173
203
  your SQL, and its cascade would write tables of kinds. Promote the root, or
174
204
  delete tenants through a command.
175
205
  - **Extensions** — `CREATE EXTENSION … SCHEMA extensions` (a schema of the
176
- provider); without `SCHEMA` or with another schema it is the warning
177
- `sql.debt-extension-schema`. Until you fix it, code inside a command calls
178
- no function of the model in that schema, and none at all while an
179
- extension has no `SCHEMA`.
206
+ provider); without `SCHEMA` or with another schema it is the error
207
+ `sql.debt-extension-schema`. Fix it with `ALTER EXTENSION … SET SCHEMA
208
+ extensions` in the database and `SCHEMA extensions` in the statement:
209
+ Postgres picks an overload by argument types, so a name match with a model
210
+ function would not make a call safe.
180
211
 
181
212
  ## Before a promotion
182
213
 
@@ -1,35 +0,0 @@
1
- #!/usr/bin/env node
2
- // src/schema-engine/errors.ts
3
- /**
4
- * Помилки адаптера, які межа підключення (`io/database.ts`) розпізнає за
5
- * класом. Окремий модуль без `pg` і pg-delta: межу імпортує кожен виклик
6
- * CLI, а двигун вантажиться лише інструментом бази.
7
- */
8
- /** Тінь на сервері іншої мажорної версії: каталоги двох версій не порівнюються. */
9
- var ShadowServerMismatchError = class extends Error {
10
- name = "ShadowServerMismatchError";
11
- };
12
- /** Роль підключення не має `CREATEDB` на сервері, де мала б з'явитися тінь. */
13
- var ShadowCreateRefusedError = class extends Error {
14
- onShadowBase;
15
- name = "ShadowCreateRefusedError";
16
- constructor(onShadowBase) {
17
- super("the connecting role lacks CREATEDB");
18
- this.onShadowBase = onShadowBase;
19
- }
20
- };
21
- /**
22
- * Збій створення тіні чи підключення до неї з причиною, якої адаптер не
23
- * розпізнав: причина — у `cause`. Межа описує її адресою сервера, де мала
24
- * з'явитися тінь, і називає вимогу тіні до режиму з'єднання (спека designer
25
- * §3.2).
26
- */
27
- var ShadowServerError = class extends Error {
28
- onShadowBase;
29
- name = "ShadowServerError";
30
- constructor(cause, onShadowBase) {
31
- super("the shadow could not be created or reached", { cause });
32
- this.onShadowBase = onShadowBase;
33
- }
34
- };
35
- export { ShadowServerError as n, ShadowServerMismatchError as r, ShadowCreateRefusedError as t };