@palbase/backend 15.0.0 → 17.0.0
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.
- package/dist/{chunk-7LAXRLPG.js → chunk-IBIME7N2.js} +321 -2
- package/dist/chunk-IBIME7N2.js.map +1 -0
- package/dist/db/index.cjs +1 -1
- package/dist/db/index.cjs.map +1 -1
- package/dist/db/index.d.cts +1 -2
- package/dist/db/index.d.ts +1 -2
- package/dist/db/index.js +6 -8
- package/dist/{endpoint-BW8bn1y-.d.cts → index-D6mRh4yq.d.cts} +654 -1
- package/dist/{endpoint-BW8bn1y-.d.ts → index-J1tnAnFj.d.ts} +654 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -4
- package/dist/index.d.ts +2 -4
- package/dist/index.js +135 -23
- package/dist/index.js.map +1 -1
- package/dist/test/index.cjs +84 -962
- package/dist/test/index.cjs.map +1 -1
- package/dist/test/index.d.cts +64 -61
- package/dist/test/index.d.ts +64 -61
- package/dist/test/index.js +85 -465
- package/dist/test/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-7LAXRLPG.js.map +0 -1
- package/dist/chunk-I72YYSEI.js +0 -148
- package/dist/chunk-I72YYSEI.js.map +0 -1
- package/dist/chunk-LUV36KQU.js +0 -327
- package/dist/chunk-LUV36KQU.js.map +0 -1
- package/dist/index-B398u5B0.d.ts +0 -650
- package/dist/index-DmkBkvP6.d.cts +0 -650
package/dist/index-B398u5B0.d.ts
DELETED
|
@@ -1,650 +0,0 @@
|
|
|
1
|
-
import { Tables, TableTypes } from './db/env.js';
|
|
2
|
-
import { D as DBClient, b8 as TxPlanHandle, bi as TxTable, M as Materialized } from './endpoint-BW8bn1y-.js';
|
|
3
|
-
|
|
4
|
-
/** On delete action for foreign key references. */
|
|
5
|
-
type OnDeleteAction = 'cascade' | 'set null' | 'restrict' | 'no action';
|
|
6
|
-
/**
|
|
7
|
-
* The ON DELETE actions permitted on a foreign key to the built-in auth users
|
|
8
|
-
* (`auth.users`). Both let a user's rows be removed (`cascade`) or detached
|
|
9
|
-
* (`set null`) when the account is erased; `restrict` / `no action` would BLOCK
|
|
10
|
-
* erasure and are therefore excluded. This is the CLIENT-SIDE mirror of the
|
|
11
|
-
* server's auth-FK deletion policy — the server (validateAuthUserFK) is the real
|
|
12
|
-
* boundary, this narrows the type so the common mistake is caught at compile time.
|
|
13
|
-
*/
|
|
14
|
-
type AuthUserOnDelete = Extract<OnDeleteAction, 'cascade' | 'set null'>;
|
|
15
|
-
/** Column type identifiers. */
|
|
16
|
-
type ColumnType = 'uuid' | 'text' | 'integer' | 'bigint' | 'numeric' | 'boolean' | 'timestamp' | 'jsonb' | 'enum';
|
|
17
|
-
/** Base column definition shared by all column types. */
|
|
18
|
-
interface ColumnDef {
|
|
19
|
-
type: ColumnType;
|
|
20
|
-
nullable: boolean;
|
|
21
|
-
primaryKey: boolean;
|
|
22
|
-
defaultValue?: unknown;
|
|
23
|
-
defaultRandom?: boolean;
|
|
24
|
-
defaultNow?: boolean;
|
|
25
|
-
references?: {
|
|
26
|
-
table: string;
|
|
27
|
-
column: string;
|
|
28
|
-
};
|
|
29
|
-
onDeleteAction?: OnDeleteAction;
|
|
30
|
-
enumName?: string;
|
|
31
|
-
enumValues?: string[];
|
|
32
|
-
unique?: boolean;
|
|
33
|
-
}
|
|
34
|
-
declare const __colKind: unique symbol;
|
|
35
|
-
declare const __colNullable: unique symbol;
|
|
36
|
-
declare const __colHasDefault: unique symbol;
|
|
37
|
-
declare const __colEnumValues: unique symbol;
|
|
38
|
-
declare const __colPayload: unique symbol;
|
|
39
|
-
/**
|
|
40
|
-
* Fluent column builder with phantom type params:
|
|
41
|
-
* K — ColumnType literal (e.g. "text", "integer")
|
|
42
|
-
* N — boolean: true when nullable() has been called last (false = NOT NULL)
|
|
43
|
-
* D — boolean: true when a default has been set
|
|
44
|
-
* E — enum value union (never for non-enum columns)
|
|
45
|
-
* P — jsonb payload shape (unknown unless jsonb<T>() supplied one)
|
|
46
|
-
*
|
|
47
|
-
* All five params have defaults so bare `ColumnBuilder` (no args) still
|
|
48
|
-
* satisfies `Record<string, ColumnBuilder>` in schema.ts without modification.
|
|
49
|
-
*
|
|
50
|
-
* The five `declare readonly` brand fields carry the phantom types into the
|
|
51
|
-
* structural shape so that conditional types like ColValue<C> can discriminate
|
|
52
|
-
* on K without requiring runtime values on those fields.
|
|
53
|
-
*/
|
|
54
|
-
declare class ColumnBuilder<K extends ColumnType = ColumnType, N extends boolean = boolean, D extends boolean = boolean, E = unknown, P = unknown> {
|
|
55
|
-
readonly [__colKind]: K;
|
|
56
|
-
readonly [__colNullable]: N;
|
|
57
|
-
readonly [__colHasDefault]: D;
|
|
58
|
-
readonly [__colEnumValues]: E;
|
|
59
|
-
readonly [__colPayload]: P;
|
|
60
|
-
readonly _def: ColumnDef;
|
|
61
|
-
constructor(type: K, existingDef?: ColumnDef);
|
|
62
|
-
/** Mark this column as the primary key. */
|
|
63
|
-
primaryKey(): ColumnBuilder<K, N, D, E, P>;
|
|
64
|
-
/** Mark this column as NOT NULL (default). */
|
|
65
|
-
notNull(): ColumnBuilder<K, false, D, E, P>;
|
|
66
|
-
/** Allow NULL values. */
|
|
67
|
-
nullable(): ColumnBuilder<K, true, D, E, P>;
|
|
68
|
-
/** Set a default value. */
|
|
69
|
-
default(value: unknown): ColumnBuilder<K, N, true, E, P>;
|
|
70
|
-
/** UUID: generate a random default (gen_random_uuid()). */
|
|
71
|
-
defaultRandom(): ColumnBuilder<K, N, true, E, P>;
|
|
72
|
-
/** Timestamp: default to now(). */
|
|
73
|
-
defaultNow(): ColumnBuilder<K, N, true, E, P>;
|
|
74
|
-
/** Add a foreign key reference. */
|
|
75
|
-
references(table: string, column: string): ColumnBuilder<K, N, D, E, P>;
|
|
76
|
-
/**
|
|
77
|
-
* Add a real DB-level foreign key to the built-in auth users
|
|
78
|
-
* (`REFERENCES auth.users(id)`), so a column like `user_id` gets true
|
|
79
|
-
* database cascade/integrity instead of app-layer-only. Sugar for
|
|
80
|
-
* `.references("auth.users", "id")`.
|
|
81
|
-
*
|
|
82
|
-
* `auth.users` lives in the SAME tenant database (palauth-owned), so this is
|
|
83
|
-
* a genuine cross-schema integrity constraint scoped to THIS tenant's users.
|
|
84
|
-
* The referenced `auth.users.id` is `text` (palauth ids are `usr_<uuid>`), so
|
|
85
|
-
* the referencing column must be `text()` too.
|
|
86
|
-
*
|
|
87
|
-
* ON DELETE is REQUIRED here and may only be `cascade` or `set null`: an
|
|
88
|
-
* account-erasure request must never be blocked by a lingering FK, so
|
|
89
|
-
* `restrict` / `no action` are not accepted (they don't type-check). Example:
|
|
90
|
-
* `text().notNull().referencesAuthUser("cascade")`, or
|
|
91
|
-
* `text().nullable().referencesAuthUser("set null")`. The server
|
|
92
|
-
* (validateAuthUserFK) enforces this — and the remaining rules the type can't
|
|
93
|
-
* express (referencing column is text, `set null` needs a nullable column) —
|
|
94
|
-
* as the real boundary; this signature is the compile-time DX mirror.
|
|
95
|
-
*/
|
|
96
|
-
referencesAuthUser(onDelete: AuthUserOnDelete): ColumnBuilder<K, N, D, E, P>;
|
|
97
|
-
/**
|
|
98
|
-
* Add a real DB-level foreign key to the canonical, server-minted installation
|
|
99
|
-
* anchor (`REFERENCES auth.installations(id)`) — the app-scoped verified-device
|
|
100
|
-
* root (`ins_...`). Sugar for `.references("auth.installations", "id")`.
|
|
101
|
-
*
|
|
102
|
-
* An installation is an APP INSTALL, not a user: this FK is NOT user ownership.
|
|
103
|
-
* A user-owned row STILL needs its own `.referencesAuthUser(...)` FK so account
|
|
104
|
-
* erasure removes it — an installation reference alone does not tie a row to a
|
|
105
|
-
* user's deletion. Use this only for install-scoped state (device prefs, push
|
|
106
|
-
* routing, …), alongside a separate auth-user FK where the row is user-owned.
|
|
107
|
-
*
|
|
108
|
-
* `auth.installations` lives in the SAME tenant DB (palauth-owned); its `id` is
|
|
109
|
-
* `text` (`ins_<uuid>`), so the referencing column must be `text()` too. ON
|
|
110
|
-
* DELETE is REQUIRED and may only be `cascade` or `set null` (same allowed set
|
|
111
|
-
* as an auth-user FK): an installation revoke / orphan cleanup must never be
|
|
112
|
-
* blocked by a lingering FK. The server (validateAuthAnchorFK) is the real
|
|
113
|
-
* boundary; this signature is the compile-time DX mirror.
|
|
114
|
-
*/
|
|
115
|
-
referencesInstallation(onDelete: AuthUserOnDelete): ColumnBuilder<K, N, D, E, P>;
|
|
116
|
-
/** Set the ON DELETE action for a foreign key reference. */
|
|
117
|
-
onDelete(action: OnDeleteAction): ColumnBuilder<K, N, D, E, P>;
|
|
118
|
-
/** Add a single-column UNIQUE constraint. */
|
|
119
|
-
unique(): ColumnBuilder<K, N, D, E, P>;
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
|
-
* Extracts the TypeScript value type for a column, respecting nullability.
|
|
123
|
-
* - "uuid" | "text" | "timestamp" | "bigint" | "numeric" → string (or string | null when N = true)
|
|
124
|
-
* Note: bigint/numeric surface as string — JS number loses precision past 2^53,
|
|
125
|
-
* and pgx/PostgREST serialize int8/numeric as strings. App code uses
|
|
126
|
-
* BigInt(row.amount) for bigint, or a decimal lib for numeric.
|
|
127
|
-
* - "integer" → number
|
|
128
|
-
* - "boolean" → boolean
|
|
129
|
-
* - "jsonb" → P (the dev-supplied payload shape from jsonb<T>(), else unknown)
|
|
130
|
-
* - "enum" → E (the union of literal values)
|
|
131
|
-
*/
|
|
132
|
-
type ColValue<C> = C extends ColumnBuilder<'uuid' | 'text' | 'timestamp' | 'bigint' | 'numeric', infer N, infer _D, infer _E, infer _P> ? N extends true ? string | null : string : C extends ColumnBuilder<'integer', infer N, infer _D, infer _E, infer _P> ? N extends true ? number | null : number : C extends ColumnBuilder<'boolean', infer N, infer _D, infer _E, infer _P> ? N extends true ? boolean | null : boolean : C extends ColumnBuilder<'jsonb', infer N, infer _D, infer _E, infer P> ? N extends true ? P | null : P : C extends ColumnBuilder<'enum', infer N, infer _D, infer E, infer _P> ? N extends true ? E | null : E : never;
|
|
133
|
-
/**
|
|
134
|
-
* True when a column is optional on INSERT:
|
|
135
|
-
* - nullable columns (N = true) — the DB allows NULL so the field may be omitted
|
|
136
|
-
* - columns with a default (D = true) — the DB fills in the value when absent
|
|
137
|
-
*/
|
|
138
|
-
type ColIsOptionalOnInsert<C> = C extends ColumnBuilder<infer _K, true, infer _D, infer _E> ? true : C extends ColumnBuilder<infer _K, infer _N, true, infer _E> ? true : false;
|
|
139
|
-
/** Create a UUID column. */
|
|
140
|
-
declare function uuid(): ColumnBuilder<'uuid', false, false, never>;
|
|
141
|
-
/** Create a TEXT column. */
|
|
142
|
-
declare function text(): ColumnBuilder<'text', false, false, never>;
|
|
143
|
-
/** Create an INTEGER column. Emits int4 (max ~2.1B). */
|
|
144
|
-
declare function integer(): ColumnBuilder<'integer', false, false, never>;
|
|
145
|
-
/**
|
|
146
|
-
* Create a BIGINT column (Postgres int8, max ~9.2×10^18).
|
|
147
|
-
* Surfaces as `string` in row/insert types — JS number loses precision past 2^53
|
|
148
|
-
* and pgx/PostgREST serialize int8 as a JSON string. Use BigInt(row.column) in app code.
|
|
149
|
-
*/
|
|
150
|
-
declare function bigint(): ColumnBuilder<'bigint', false, false, never>;
|
|
151
|
-
/**
|
|
152
|
-
* Create a NUMERIC column (Postgres `numeric`/`decimal`, arbitrary precision).
|
|
153
|
-
* For exact fractional values (money with cents as a decimal, rates, weights)
|
|
154
|
-
* where int4/int8 don't fit. Surfaces as `string` in row/insert types — JS
|
|
155
|
-
* number can't hold arbitrary-precision decimals without rounding, and
|
|
156
|
-
* pgx/PostgREST serialize numeric as a JSON string. Parse with a decimal lib
|
|
157
|
-
* (or BigInt for scaled integers) in app code.
|
|
158
|
-
*/
|
|
159
|
-
declare function numeric(): ColumnBuilder<'numeric', false, false, never>;
|
|
160
|
-
/** Create a BOOLEAN column. */
|
|
161
|
-
declare function boolean(): ColumnBuilder<'boolean', false, false, never>;
|
|
162
|
-
/** Create a TIMESTAMP column. */
|
|
163
|
-
declare function timestamp(): ColumnBuilder<'timestamp', false, false, never>;
|
|
164
|
-
/**
|
|
165
|
-
* Create a JSONB column. Pass a payload type to make the generated row/insert
|
|
166
|
-
* type concrete instead of `unknown`:
|
|
167
|
-
*
|
|
168
|
-
* tags: jsonb<string[]>() // row.tags: string[]
|
|
169
|
-
* meta: jsonb<{ tier: string }>() // row.meta: { tier: string }
|
|
170
|
-
* raw: jsonb() // row.raw: unknown (back-compat)
|
|
171
|
-
*
|
|
172
|
-
* The runtime accepts a plain JS object/array directly (no JSON.stringify); the
|
|
173
|
-
* generic only refines the TYPE the env codegen emits.
|
|
174
|
-
*/
|
|
175
|
-
declare function jsonb<T = unknown>(): ColumnBuilder<'jsonb', false, false, never, T>;
|
|
176
|
-
/**
|
|
177
|
-
* Create an ENUM column.
|
|
178
|
-
* @param name The PostgreSQL enum type name (used in DDL).
|
|
179
|
-
* @param values A readonly tuple of valid string values — kept `const` so the
|
|
180
|
-
* union `V[number]` is as narrow as possible.
|
|
181
|
-
*/
|
|
182
|
-
declare function enumType<const V extends readonly string[]>(name: string, values: V): ColumnBuilder<'enum', false, false, V[number]>;
|
|
183
|
-
|
|
184
|
-
/**
|
|
185
|
-
* policy.ts — the RLS policy authoring DSL.
|
|
186
|
-
*
|
|
187
|
-
* `policy(name)` returns a fluent builder that mirrors the `ColumnBuilder`
|
|
188
|
-
* style in columns.ts: each chainable method mutates the underlying
|
|
189
|
-
* definition and returns the builder so calls compose. The terminal value is
|
|
190
|
-
* a plain {@link PolicyDef} — the exact JSON shape the runtime's
|
|
191
|
-
* `schema_extract.js` reads off the bundled module and the Go side parses into
|
|
192
|
-
* `PolicyJSON` (CONTRACT-POLICY).
|
|
193
|
-
*
|
|
194
|
-
* @example
|
|
195
|
-
* import { policy } from "@palbase/backend";
|
|
196
|
-
*
|
|
197
|
-
* policy("owner_select")
|
|
198
|
-
* .for("select")
|
|
199
|
-
* .to("authenticated")
|
|
200
|
-
* .using("owner = (select auth.uid())");
|
|
201
|
-
*/
|
|
202
|
-
/** The SQL command a policy applies to. `"all"` covers SELECT/INSERT/UPDATE/DELETE. */
|
|
203
|
-
type PolicyCommand = "all" | "select" | "insert" | "update" | "delete";
|
|
204
|
-
/** Whether a policy is permissive (OR-combined, the default) or restrictive
|
|
205
|
-
* (AND-combined). Mirrors Postgres `CREATE POLICY ... AS PERMISSIVE|RESTRICTIVE`. */
|
|
206
|
-
type PolicyMode = "permissive" | "restrictive";
|
|
207
|
-
/**
|
|
208
|
-
* The compiled, serializable policy definition — the EXACT shape consumed by
|
|
209
|
-
* `schema_extract.js` → Go `PolicyJSON` (CONTRACT-POLICY).
|
|
210
|
-
*
|
|
211
|
-
* - `roles`: the DB roles this policy applies to (`TO` clause). An empty array
|
|
212
|
-
* means the policy applies to PUBLIC (all roles) — the Postgres default.
|
|
213
|
-
* - `using`: the `USING (...)` row-visibility expression, or `null` when none.
|
|
214
|
-
* - `withCheck`: the `WITH CHECK (...)` write-validation expression, or `null`.
|
|
215
|
-
* - `permissive`: `true` for `AS PERMISSIVE` (default), `false` for restrictive.
|
|
216
|
-
*/
|
|
217
|
-
interface PolicyDef {
|
|
218
|
-
name: string;
|
|
219
|
-
command: PolicyCommand;
|
|
220
|
-
roles: string[];
|
|
221
|
-
using: string | null;
|
|
222
|
-
withCheck: string | null;
|
|
223
|
-
permissive: boolean;
|
|
224
|
-
}
|
|
225
|
-
/**
|
|
226
|
-
* Fluent RLS policy builder.
|
|
227
|
-
*
|
|
228
|
-
* Defaults (documented, applied at construction):
|
|
229
|
-
* - `command`: `"all"` — applies to every SQL command unless `.for(...)` narrows it.
|
|
230
|
-
* - `roles`: `["authenticated"]` — the common case is "rule applies to signed-in
|
|
231
|
-
* users". Call `.to(...)` to override; pass `.to()` with no roles (or never
|
|
232
|
-
* call it after a reset) to target PUBLIC.
|
|
233
|
-
* - `using` / `withCheck`: `null` — no row filter / write check until set.
|
|
234
|
-
* - `permissive`: `true` — `AS PERMISSIVE` (policies OR together).
|
|
235
|
-
*
|
|
236
|
-
* Each method mutates `_def` in place and returns `this`, so the chain is a
|
|
237
|
-
* single builder instance (no per-call allocation, like a tagged-template
|
|
238
|
-
* compile target). The terminal `PolicyDef` is read directly off `_def` by
|
|
239
|
-
* `schema_extract.js`.
|
|
240
|
-
*/
|
|
241
|
-
declare class PolicyBuilder {
|
|
242
|
-
readonly _def: PolicyDef;
|
|
243
|
-
constructor(name: string);
|
|
244
|
-
/** Restrict the policy to a single SQL command (default `"all"`). */
|
|
245
|
-
for(command: PolicyCommand): this;
|
|
246
|
-
/**
|
|
247
|
-
* Set the DB roles the policy applies to (the `TO` clause), replacing any
|
|
248
|
-
* previously-set roles. Call with no arguments to target PUBLIC (all roles).
|
|
249
|
-
*
|
|
250
|
-
* @example
|
|
251
|
-
* policy("p").to("authenticated")
|
|
252
|
-
* policy("p").to("authenticated", "service_role")
|
|
253
|
-
* policy("p").to() // PUBLIC
|
|
254
|
-
*/
|
|
255
|
-
to(...roles: string[]): this;
|
|
256
|
-
/** Set the `USING (...)` row-visibility expression (raw SQL). */
|
|
257
|
-
using(sqlExpr: string): this;
|
|
258
|
-
/** Set the `WITH CHECK (...)` write-validation expression (raw SQL). */
|
|
259
|
-
withCheck(sqlExpr: string): this;
|
|
260
|
-
/** Set the policy mode: `"permissive"` (default, OR-combined) or
|
|
261
|
-
* `"restrictive"` (AND-combined). */
|
|
262
|
-
as(mode: PolicyMode): this;
|
|
263
|
-
}
|
|
264
|
-
/**
|
|
265
|
-
* Start authoring an RLS policy. Returns a {@link PolicyBuilder}; the resulting
|
|
266
|
-
* `PolicyBuilder` is accepted directly in a table's `policies: [...]` array
|
|
267
|
-
* (its `_def` is read at schema-extract time).
|
|
268
|
-
*
|
|
269
|
-
* @param name The policy name. Palbase reconciliation keys policies by
|
|
270
|
-
* `(table, name)`, so names must be unique per table.
|
|
271
|
-
*/
|
|
272
|
-
declare function policy(name: string): PolicyBuilder;
|
|
273
|
-
|
|
274
|
-
/**
|
|
275
|
-
* Postgres extensions a Palbase project can enable from its schema.
|
|
276
|
-
*
|
|
277
|
-
* Extensions are config-as-code: declare them in `defineSchema({ extensions })`
|
|
278
|
-
* and the deploy installs them (CREATE EXTENSION … SCHEMA extensions) using the
|
|
279
|
-
* deploy path's privileged connection. They are NOT toggled live from Studio —
|
|
280
|
-
* CREATE EXTENSION requires a superuser role that only the deploy path holds.
|
|
281
|
-
*
|
|
282
|
-
* The list is an allowlist (a string-literal union) so editors autocomplete the
|
|
283
|
-
* supported names and a typo fails typecheck. It is intentionally extensible:
|
|
284
|
-
* add a name here (+ confirm the base image ships it) to support more.
|
|
285
|
-
*/
|
|
286
|
-
declare const PALBASE_EXTENSIONS: readonly ["vector", "pg_trgm", "unaccent", "citext", "postgis", "cube", "earthdistance", "hstore", "ltree", "btree_gist", "pg_cron", "pgcrypto", "uuid-ossp"];
|
|
287
|
-
/** A Postgres extension supported by Palbase (allowlist union). */
|
|
288
|
-
type PalbaseExtension = (typeof PALBASE_EXTENSIONS)[number];
|
|
289
|
-
/**
|
|
290
|
-
* Extensions that depend on another extension. The deploy installs
|
|
291
|
-
* dependencies first; declaring `earthdistance` without `cube` still works
|
|
292
|
-
* because the deploy resolves the order, but listing both is clearer.
|
|
293
|
-
*/
|
|
294
|
-
declare const EXTENSION_DEPENDENCIES: Partial<Record<PalbaseExtension, PalbaseExtension[]>>;
|
|
295
|
-
/** Runtime guard: is `name` a supported Palbase extension? */
|
|
296
|
-
declare function isPalbaseExtension(name: string): name is PalbaseExtension;
|
|
297
|
-
|
|
298
|
-
/**
|
|
299
|
-
* A named raw-SQL DDL object declared in db/schema.ts for anything the typed DSL
|
|
300
|
-
* cannot express (EXCLUDE, CHECK, partial/expression indexes, triggers, views).
|
|
301
|
-
* The deploy emits `up` verbatim on the privileged DDL connection — same trust
|
|
302
|
-
* posture as policy().using(). Tracked by NAME (not by diffing the body), so a
|
|
303
|
-
* changed body needs a new name or an explicit drop+add.
|
|
304
|
-
*/
|
|
305
|
-
interface RawConstraintDef {
|
|
306
|
-
name: string;
|
|
307
|
-
up: string;
|
|
308
|
-
down?: string;
|
|
309
|
-
}
|
|
310
|
-
declare function raw(name: string, up: string, opts?: {
|
|
311
|
-
down?: string;
|
|
312
|
-
}): RawConstraintDef;
|
|
313
|
-
|
|
314
|
-
/**
|
|
315
|
-
* A map of column builders keyed by column name — the value you write under
|
|
316
|
-
* the `columns` key of `defineSchema({ tables: { <name>: { columns } } })`.
|
|
317
|
-
*
|
|
318
|
-
* The default `Record<string, ColumnBuilder>` keeps bare references compiling
|
|
319
|
-
* without a type argument.
|
|
320
|
-
*/
|
|
321
|
-
type ColumnMap = Record<string, ColumnBuilder>;
|
|
322
|
-
/**
|
|
323
|
-
* The author-facing value written under each table key:
|
|
324
|
-
* `{ columns, rls?, policies? }`.
|
|
325
|
-
*
|
|
326
|
-
* - `columns`: the column map (required).
|
|
327
|
-
* - `rls`: enable + FORCE row-level security on this table. Implied when
|
|
328
|
-
* `policies` is non-empty; set it explicitly to enable RLS with no policies
|
|
329
|
-
* yet (deny-all — useful only as an intermediate step).
|
|
330
|
-
* - `policies`: the RLS policies for this table, authored with `policy(name)`.
|
|
331
|
-
* Each entry may be a {@link PolicyBuilder} (the normal `policy(...)` chain)
|
|
332
|
-
* or a raw {@link PolicyDef} object.
|
|
333
|
-
*
|
|
334
|
-
* The `C` type parameter preserves the precise per-column phantom types so the
|
|
335
|
-
* typed `Database.tables.*` surface keeps inferring insert/row shapes.
|
|
336
|
-
*/
|
|
337
|
-
interface TableInput<C extends ColumnMap = ColumnMap> {
|
|
338
|
-
columns: C;
|
|
339
|
-
rls?: boolean;
|
|
340
|
-
policies?: (PolicyBuilder | PolicyDef)[];
|
|
341
|
-
/** Composite/named primary key (ordered column names). Omit for single-column inline .primaryKey(). */
|
|
342
|
-
primaryKey?: string[];
|
|
343
|
-
/** Named multi-column UNIQUE constraints. */
|
|
344
|
-
unique?: {
|
|
345
|
-
name: string;
|
|
346
|
-
columns: string[];
|
|
347
|
-
}[];
|
|
348
|
-
/** Named raw-SQL DDL objects (EXCLUDE, triggers, views) that the typed DSL cannot express. */
|
|
349
|
-
raw?: RawConstraintDef[];
|
|
350
|
-
/**
|
|
351
|
-
* Named first-class CHECK constraints. Diffed by NAME with a BODY compare:
|
|
352
|
-
* a changed `expr` (after pg normalization) recreates the constraint
|
|
353
|
-
* (DROP + ADD). `expr` is trusted SQL emitted verbatim (like policy USING),
|
|
354
|
-
* `name` is identifier-validated.
|
|
355
|
-
*/
|
|
356
|
-
checks?: {
|
|
357
|
-
name: string;
|
|
358
|
-
expr: string;
|
|
359
|
-
}[];
|
|
360
|
-
/**
|
|
361
|
-
* Plain (non-unique) btree indexes over an ordered column list, emitted as
|
|
362
|
-
* standalone `CREATE INDEX [IF NOT EXISTS] name ON table (col1, col2)`
|
|
363
|
-
* statements (NOT a table clause — a separate migration statement category).
|
|
364
|
-
* Structural compare by NAME (no expression normalization). `name` and each
|
|
365
|
-
* column are identifier-validated by the Go differ.
|
|
366
|
-
*
|
|
367
|
-
* Scope: columns-only plain btree. Partial (`where`) and expression indexes
|
|
368
|
-
* are a deliberate follow-up — modelling them needs the same raw-SQL
|
|
369
|
-
* normalization round-trip CHECK uses (Task 10), so they are NOT in this
|
|
370
|
-
* type yet to avoid a half-working partial-index path.
|
|
371
|
-
*/
|
|
372
|
-
indexes?: {
|
|
373
|
-
name: string;
|
|
374
|
-
columns: string[];
|
|
375
|
-
}[];
|
|
376
|
-
}
|
|
377
|
-
/**
|
|
378
|
-
* A table definition — the runtime value the Go runtime's `schema_extract.js`
|
|
379
|
-
* reads. It keys tables by `tableDef.name`, reads `tableDef.columns` for the
|
|
380
|
-
* column DDL, and `tableDef.rls` + `tableDef.policies` for RLS.
|
|
381
|
-
*
|
|
382
|
-
* `defineSchema` derives `name` from the object key, so authors never repeat
|
|
383
|
-
* the table name. `rls`/`policies` are always present after normalization
|
|
384
|
-
* (defaulted to `false`/`[]`).
|
|
385
|
-
*
|
|
386
|
-
* The `C` type parameter preserves the precise per-column phantom types so that
|
|
387
|
-
* downstream mapped types (InsertShape, RowShape) can discriminate on them.
|
|
388
|
-
*/
|
|
389
|
-
interface TableDef<C extends ColumnMap = ColumnMap> {
|
|
390
|
-
name: string;
|
|
391
|
-
columns: C;
|
|
392
|
-
rls: boolean;
|
|
393
|
-
policies: PolicyDef[];
|
|
394
|
-
primaryKey?: string[];
|
|
395
|
-
unique?: {
|
|
396
|
-
name: string;
|
|
397
|
-
columns: string[];
|
|
398
|
-
}[];
|
|
399
|
-
/** Named raw-SQL DDL objects emitted verbatim on deploy. Tracked by name. */
|
|
400
|
-
raw?: RawConstraintDef[];
|
|
401
|
-
/** Named first-class CHECK constraints. Diffed by name + (normalized) body. */
|
|
402
|
-
checks?: {
|
|
403
|
-
name: string;
|
|
404
|
-
expr: string;
|
|
405
|
-
}[];
|
|
406
|
-
/** Plain btree indexes (columns-only), emitted as standalone CREATE INDEX. Diffed by name. */
|
|
407
|
-
indexes?: {
|
|
408
|
-
name: string;
|
|
409
|
-
columns: string[];
|
|
410
|
-
}[];
|
|
411
|
-
}
|
|
412
|
-
/**
|
|
413
|
-
* A schema definition containing multiple tables, keyed by table name.
|
|
414
|
-
*
|
|
415
|
-
* The `T` type parameter preserves the exact `TableDef<...>` type for each
|
|
416
|
-
* table so that `SchemaDef["tables"]["rooms"]` resolves to the precise
|
|
417
|
-
* `TableDef<{ id: ColumnBuilder<'uuid', false, true, never>; ... }>`.
|
|
418
|
-
*/
|
|
419
|
-
interface SchemaDef<T extends Record<string, TableDef> = Record<string, TableDef>> {
|
|
420
|
-
tables: T;
|
|
421
|
-
/** Postgres extensions to install on deploy. Normalized to `[]` when absent. */
|
|
422
|
-
extensions: PalbaseExtension[];
|
|
423
|
-
}
|
|
424
|
-
/** The author-facing input to `defineSchema` — a `tables` map whose keys are
|
|
425
|
-
* the table names and whose values are `{ columns, rls?, policies? }`, plus an
|
|
426
|
-
* optional `extensions` allowlist. */
|
|
427
|
-
interface SchemaInput<T extends Record<string, TableInput> = Record<string, TableInput>> {
|
|
428
|
-
tables: T;
|
|
429
|
-
/**
|
|
430
|
-
* Postgres extensions to enable for this project, e.g. `["vector"]`.
|
|
431
|
-
* Config-as-code: installed by the deploy (CREATE EXTENSION … SCHEMA
|
|
432
|
-
* extensions) with the privileged deploy connection. The type is an
|
|
433
|
-
* allowlist union, so unsupported names fail typecheck.
|
|
434
|
-
*/
|
|
435
|
-
extensions?: PalbaseExtension[];
|
|
436
|
-
}
|
|
437
|
-
/** Map the author's `{ tables: { <name>: { columns } } }` input to the
|
|
438
|
-
* `{ tables: { <name>: TableDef<columns> } }` runtime/type shape, threading the
|
|
439
|
-
* per-table column map `T[K]["columns"]` so column-level inference survives. */
|
|
440
|
-
type TablesFromInput<T extends Record<string, TableInput>> = {
|
|
441
|
-
[K in keyof T]: TableDef<T[K]["columns"]>;
|
|
442
|
-
};
|
|
443
|
-
/**
|
|
444
|
-
* Define a schema. The table NAME comes from the object key. Each table value
|
|
445
|
-
* is `{ columns, rls?, policies? }`:
|
|
446
|
-
*
|
|
447
|
-
* export default defineSchema({
|
|
448
|
-
* tables: {
|
|
449
|
-
* todos: {
|
|
450
|
-
* columns: {
|
|
451
|
-
* id: uuid().primaryKey().defaultRandom(),
|
|
452
|
-
* owner: text().notNull(),
|
|
453
|
-
* title: text().notNull(),
|
|
454
|
-
* },
|
|
455
|
-
* rls: true,
|
|
456
|
-
* policies: [
|
|
457
|
-
* policy("owner_all").for("all").to("authenticated")
|
|
458
|
-
* .using("owner = (select auth.uid())")
|
|
459
|
-
* .withCheck("owner = (select auth.uid())"),
|
|
460
|
-
* ],
|
|
461
|
-
* },
|
|
462
|
-
* },
|
|
463
|
-
* });
|
|
464
|
-
*
|
|
465
|
-
* The returned value is
|
|
466
|
-
* `{ tables: { todos: { name, columns, rls, policies } } }` — the exact shape
|
|
467
|
-
* the runtime schema extractor parses. Per-column phantom types are preserved
|
|
468
|
-
* so `Database.tables.todos.insert({...})` stays typed.
|
|
469
|
-
*
|
|
470
|
-
* RLS normalization: `rls` defaults to `false`, `policies` to `[]`. When
|
|
471
|
-
* `policies` is non-empty, `rls` is forced on (ENABLE + FORCE) regardless of
|
|
472
|
-
* the declared `rls` flag — a table with policies must have RLS enabled or the
|
|
473
|
-
* policies would be inert.
|
|
474
|
-
*/
|
|
475
|
-
declare function defineSchema<T extends Record<string, TableInput>>(input: SchemaInput<T>): SchemaDef<TablesFromInput<T>>;
|
|
476
|
-
|
|
477
|
-
/**
|
|
478
|
-
* typed-db.ts — Task 2: TypedDB schema-derived insert/row shapes.
|
|
479
|
-
*
|
|
480
|
-
* Derives INSERT and full-row TypeScript types from a `defineSchema()` result
|
|
481
|
-
* and wraps the untyped runtime `DBClient` with a typed facade.
|
|
482
|
-
*
|
|
483
|
-
* No value-any. No `as unknown as X`. The two narrow `as` casts in
|
|
484
|
-
* `makeTypedTable` are safe because:
|
|
485
|
-
* - `data as Record<string, unknown>`: InsertShape<T> maps string keys to
|
|
486
|
-
* typed values; all value types are subsets of `unknown`, so the cast is
|
|
487
|
-
* structurally sound.
|
|
488
|
-
* - `result as RowShape<T>`: The runtime DBClient returns `Record<string,
|
|
489
|
-
* unknown>` which is the erased form of the typed row; we're narrowing back
|
|
490
|
-
* to the precise shape that the schema declared.
|
|
491
|
-
* Both casts are narrowing only (not widening) and correctness is guaranteed
|
|
492
|
-
* by the schema the caller provides.
|
|
493
|
-
*/
|
|
494
|
-
|
|
495
|
-
/** Keys of C whose columns are required on INSERT (not nullable, no default). */
|
|
496
|
-
type RequiredKeys<C> = {
|
|
497
|
-
[K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? never : K;
|
|
498
|
-
}[keyof C];
|
|
499
|
-
/** Keys of C whose columns are optional on INSERT (nullable or has a default). */
|
|
500
|
-
type OptionalKeys<C> = {
|
|
501
|
-
[K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? K : never;
|
|
502
|
-
}[keyof C];
|
|
503
|
-
/**
|
|
504
|
-
* The TypeScript type for an INSERT payload for table `T`.
|
|
505
|
-
* - Required: columns that are NOT NULL and have no DB-level default.
|
|
506
|
-
* - Optional: columns that are nullable or carry a default.
|
|
507
|
-
*
|
|
508
|
-
* When all columns are optional, `RequiredKeys<C>` resolves to `never` and
|
|
509
|
-
* the first part becomes `{}`, which is a neutral element for `&`.
|
|
510
|
-
*/
|
|
511
|
-
type InsertShape<T extends TableDef> = {
|
|
512
|
-
[K in RequiredKeys<T["columns"]>]: ColValue<T["columns"][K]>;
|
|
513
|
-
} & {
|
|
514
|
-
[K in OptionalKeys<T["columns"]>]?: ColValue<T["columns"][K]>;
|
|
515
|
-
};
|
|
516
|
-
/**
|
|
517
|
-
* The TypeScript type for a full row returned by the DB for table `T`.
|
|
518
|
-
* Every column is present; nullable columns resolve to `T | null`.
|
|
519
|
-
*/
|
|
520
|
-
type RowShape<T extends TableDef> = {
|
|
521
|
-
[K in keyof T["columns"]]: ColValue<T["columns"][K]>;
|
|
522
|
-
};
|
|
523
|
-
/** A typed table accessor that mirrors the runtime DBClient surface. */
|
|
524
|
-
interface TypedTable<T extends TableDef> {
|
|
525
|
-
insert(data: InsertShape<T>): Promise<RowShape<T>>;
|
|
526
|
-
/** Update the row by id; resolves to the updated row, or `null` if no row
|
|
527
|
-
* matched (absent or RLS-hidden) — an idempotent outcome, mirroring
|
|
528
|
-
* `findById`. The runtime returns a null row rather than throwing. */
|
|
529
|
-
update(id: string, data: Partial<InsertShape<T>>): Promise<RowShape<T> | null>;
|
|
530
|
-
delete(id: string): Promise<void>;
|
|
531
|
-
findById(id: string): Promise<RowShape<T> | null>;
|
|
532
|
-
findMany(query?: Partial<RowShape<T>>): Promise<RowShape<T>[]>;
|
|
533
|
-
}
|
|
534
|
-
/** A typed DB facade covering all tables declared in schema `S`. */
|
|
535
|
-
interface TypedDB<S extends SchemaDef> {
|
|
536
|
-
tables: {
|
|
537
|
-
[K in keyof S["tables"]]: TypedTable<S["tables"][K]>;
|
|
538
|
-
};
|
|
539
|
-
/** Run a transaction plan. See {@link EnvTypedDatabase.transaction}. */
|
|
540
|
-
transaction<T>(fn: (tx: TypedTx<S>) => T extends Promise<unknown> ? never : T): Promise<Materialized<T>>;
|
|
541
|
-
}
|
|
542
|
-
/** The plan-building handle a `TypedDB<S>` transaction callback receives: the
|
|
543
|
-
* schema's tables, expressed as plan operations rather than awaited calls. */
|
|
544
|
-
type TypedTx<S extends SchemaDef> = TxPlanHandle<{
|
|
545
|
-
[K in keyof S["tables"]]: TxTable<RowShape<S["tables"][K]>, InsertShape<S["tables"][K]>>;
|
|
546
|
-
}>;
|
|
547
|
-
/**
|
|
548
|
-
* Wraps a raw `DBClient` with the type-safe `TypedDB<S>` facade derived from
|
|
549
|
-
* the provided schema. No behavior change for the direct ops — all calls
|
|
550
|
-
* delegate to `raw` with the table name as a plain string.
|
|
551
|
-
*
|
|
552
|
-
* `transaction` does NOT delegate to a per-op client: the callback describes a
|
|
553
|
-
* plan against a fresh {@link TxPlanBuilder}, and the whole plan travels in one
|
|
554
|
-
* `raw.txPlan` call. The schema is used only for its table NAMES; the values
|
|
555
|
-
* are typed by `S` at compile time and are plain strings at run time.
|
|
556
|
-
*
|
|
557
|
-
* The `as` casts are single structural narrowings from a dynamically-built
|
|
558
|
-
* object to the precise mapped type (TS cannot infer the mapped-type result
|
|
559
|
-
* through `Object.keys` iteration) — see the module-level doc comment.
|
|
560
|
-
*/
|
|
561
|
-
declare function makeTypedDB<S extends SchemaDef>(schema: S, raw: DBClient): TypedDB<S>;
|
|
562
|
-
/** A typed table accessor derived from one env `Tables` entry's flat shapes. */
|
|
563
|
-
interface EnvTypedTable<T extends TableTypes> {
|
|
564
|
-
insert(data: T["insert"]): Promise<T["row"]>;
|
|
565
|
-
/** Update the row by id; resolves to the updated row, or `null` if no row
|
|
566
|
-
* matched (absent or RLS-hidden) — an idempotent outcome, mirroring
|
|
567
|
-
* `findById`. The runtime returns a null row rather than throwing. */
|
|
568
|
-
update(id: string, data: Partial<T["insert"]>): Promise<T["row"] | null>;
|
|
569
|
-
delete(id: string): Promise<void>;
|
|
570
|
-
findById(id: string): Promise<T["row"] | null>;
|
|
571
|
-
findMany(query?: Partial<T["row"]>): Promise<T["row"][]>;
|
|
572
|
-
}
|
|
573
|
-
/** The `tables` map exposed on `Database`/`tx`, keyed by the env `Tables`
|
|
574
|
-
* interface. When no schema is declared `Tables` is empty, so `tables` is an
|
|
575
|
-
* empty object — accessing `.tables.foo` is then a compile error (no member). */
|
|
576
|
-
type EnvTables = {
|
|
577
|
-
[K in keyof Tables]: EnvTypedTable<Tables[K]>;
|
|
578
|
-
};
|
|
579
|
-
/** The project's tables as PLAN operations, keyed by the env `Tables`
|
|
580
|
-
* interface. The transaction twin of {@link EnvTables}. */
|
|
581
|
-
type TxTables = {
|
|
582
|
-
[K in keyof Tables]: TxTable<Tables[K]["row"], Tables[K]["insert"]>;
|
|
583
|
-
};
|
|
584
|
-
/**
|
|
585
|
-
* The handle a `Database.transaction(…)` callback receives.
|
|
586
|
-
*
|
|
587
|
-
* Tables only — no `query`, no `findById`, no `asService`. A read whose value
|
|
588
|
-
* the plan does not write belongs outside the transaction, where it costs one
|
|
589
|
-
* round trip and is an ordinary value you can branch on.
|
|
590
|
-
*/
|
|
591
|
-
type TxPlan = TxPlanHandle<TxTables>;
|
|
592
|
-
/**
|
|
593
|
-
* The RLS-bypass sibling returned by `Database.asService()`. Same typed surface
|
|
594
|
-
* as {@link EnvTypedDatabase} — `tables`, the raw string ops, and a typed
|
|
595
|
-
* `transaction` — but it does NOT re-expose `asService` (no double-bypass).
|
|
596
|
-
* Every op it performs runs as the `service_role` (BYPASSRLS).
|
|
597
|
-
*/
|
|
598
|
-
interface EnvServiceDatabase extends Omit<DBClient, "txPlan" | "asService"> {
|
|
599
|
-
tables: EnvTables;
|
|
600
|
-
transaction<T>(fn: (tx: TxPlan) => T extends Promise<unknown> ? never : T): Promise<Materialized<T>>;
|
|
601
|
-
}
|
|
602
|
-
/**
|
|
603
|
-
* The typed-by-default Database surface: the raw string-keyed `DBClient` ops
|
|
604
|
-
* PLUS a `tables` map typed against the project's generated `palbase-env.d.ts`,
|
|
605
|
-
* a `transaction` that runs a whole plan in one request, and `asService()` for
|
|
606
|
-
* the explicit RLS-bypass sibling.
|
|
607
|
-
*
|
|
608
|
-
* The low-level `txPlan` op is deliberately NOT re-exposed here: `transaction`
|
|
609
|
-
* is the surface, and a hand-built plan would bypass the ref/guard machinery
|
|
610
|
-
* that makes one safe to write.
|
|
611
|
-
*/
|
|
612
|
-
interface EnvTypedDatabase extends Omit<DBClient, "txPlan" | "asService"> {
|
|
613
|
-
tables: EnvTables;
|
|
614
|
-
/**
|
|
615
|
-
* Run a transaction. The callback DESCRIBES the operations; the whole
|
|
616
|
-
* description travels in one request and the broker runs it inside a single
|
|
617
|
-
* transaction — committing when it finishes, rolling back on any failure.
|
|
618
|
-
*
|
|
619
|
-
* The callback is SYNCHRONOUS: nothing has run when it returns, so there is
|
|
620
|
-
* nothing to await. `async` on it and `await` inside it are compile errors.
|
|
621
|
-
* Values a later operation needs are {@link Ref}s, written straight into the
|
|
622
|
-
* next operation; values the CALLER needs are returned and substituted before
|
|
623
|
-
* this promise resolves.
|
|
624
|
-
*
|
|
625
|
-
* @example
|
|
626
|
-
* const { statementId } = await Database.transaction((tx) => {
|
|
627
|
-
* const st = tx.tables.statements
|
|
628
|
-
* .insert({ household_id: hid, file_sha256: sha, status: "reviewing" })
|
|
629
|
-
* .expectOne(new Internal("statement insert failed"));
|
|
630
|
-
*
|
|
631
|
-
* tx.tables.statement_lines.insertMany(
|
|
632
|
-
* lines.map((l) => ({ statement_id: st.id, category: resolveCategory(l) })),
|
|
633
|
-
* );
|
|
634
|
-
*
|
|
635
|
-
* return { statementId: st.id };
|
|
636
|
-
* });
|
|
637
|
-
*/
|
|
638
|
-
transaction<T>(fn: (tx: TxPlan) => T extends Promise<unknown> ? never : T): Promise<Materialized<T>>;
|
|
639
|
-
/**
|
|
640
|
-
* Return a sibling that bypasses RLS by running as the `service_role`. Use
|
|
641
|
-
* sparingly and explicitly — the default `Database.*` path is RLS-enforced.
|
|
642
|
-
*
|
|
643
|
-
* @example
|
|
644
|
-
* const all = await Database.asService().tables.todos.findMany({});
|
|
645
|
-
* const rows = await Database.asService().query("SELECT * FROM todos");
|
|
646
|
-
*/
|
|
647
|
-
asService(): EnvServiceDatabase;
|
|
648
|
-
}
|
|
649
|
-
|
|
650
|
-
export { jsonb as A, makeTypedDB as B, ColumnBuilder as C, numeric as D, type EnvTypedDatabase as E, policy as F, raw as G, text as H, type InsertShape as I, timestamp as J, uuid as K, type OnDeleteAction as O, PALBASE_EXTENSIONS as P, type RawConstraintDef as R, type SchemaDef as S, type TableDef as T, type ColumnDef as a, type ColumnMap as b, type ColumnType as c, EXTENSION_DEPENDENCIES as d, type EnvServiceDatabase as e, type EnvTables as f, type EnvTypedTable as g, type PalbaseExtension as h, PolicyBuilder as i, type PolicyCommand as j, type PolicyDef as k, type PolicyMode as l, type RowShape as m, type SchemaInput as n, type TableInput as o, type TxPlan as p, type TxTables as q, type TypedDB as r, type TypedTable as s, type TypedTx as t, bigint as u, boolean as v, defineSchema as w, enumType as x, integer as y, isPalbaseExtension as z };
|