@bezoar/core 0.0.3 → 0.0.5

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/index.d.mts CHANGED
@@ -1,8 +1,15 @@
1
- import { Arguments, Bundle, Definition, Issue, Query, Returns, Row, RowQuery, Schema } from "@bezoar/schema";
1
+ import { Arguments, Bundle, Database, Definition, Issue, Query, Returns, Role, RoleQuery, Row, RowQuery, Schema } from "@bezoar/schema";
2
+ import { Compilable, Kysely } from "kysely";
2
3
  /**
3
4
  * The members of a service. A query group cannot take one of these names.
4
5
  */
5
- export declare const RESERVED: readonly ["config", "schema", "query", "first", "transaction", "migrate", "seed"];
6
+ export declare const RESERVED: readonly ["config", "schema", "query", "first", "execute", "build", "transaction", "migrate", "seed", "roles"];
7
+ /**
8
+ * The query name a report carries for a built query: one that ran through
9
+ * the builder rather than the contract. The name of the builder member of
10
+ * the service. No query of a contract has this name, as it is reserved.
11
+ */
12
+ export declare const BUILT = "build";
6
13
  /**
7
14
  * The table that records each applied migration: its version, its name, its
8
15
  * checksum, and when it was applied.
@@ -29,6 +36,34 @@ export declare const APPLIED = "SELECT version, checksum FROM bezoar_migrations
29
36
  * Records one applied migration.
30
37
  */
31
38
  export declare const RECORD = "INSERT INTO bezoar_migrations (version, name, checksum) VALUES ($1, $2, $3)";
39
+ /**
40
+ * The key of the advisory lock a roles run holds. Two runs against one
41
+ * database wait for each other, as two migration runs do.
42
+ */
43
+ export declare const ROLES_LOCK = 6451065;
44
+ /**
45
+ * Whether a role exists in the cluster.
46
+ */
47
+ export declare const EXISTS = "SELECT 1 FROM pg_roles WHERE rolname = $1";
48
+ /**
49
+ * The schemas of the database other than the system ones: where a grant
50
+ * reaches, and where a roles run revokes before it grants.
51
+ */
52
+ export declare const SCHEMAS = "SELECT nspname FROM pg_namespace\n WHERE nspname NOT LIKE 'pg\\_%' AND nspname <> 'information_schema'\n ORDER BY nspname";
53
+ /**
54
+ * Quotes an identifier for SQL text: a role or a schema name.
55
+ */
56
+ export declare const quote: (name: string) => string;
57
+ /**
58
+ * Makes a role that cannot log in. A role of bezoar is a group: a login user
59
+ * the deployment makes joins it with `IN ROLE`.
60
+ */
61
+ export declare const DECLARE: (role: string) => string;
62
+ /**
63
+ * Takes every privilege of a role on the objects of a schema, so that the
64
+ * grant file of the role states the whole of them.
65
+ */
66
+ export declare const REVOKE: (role: string, schema: string) => string;
32
67
  /**
33
68
  * Raised at construction when the SQL bundle does not match the contract: a
34
69
  * query without SQL, or SQL for a query the contract does not declare.
@@ -49,8 +84,8 @@ export declare class InvalidArgumentsError extends Error {
49
84
  }
50
85
  /**
51
86
  * Raised when a row the driver returned does not fit the columns of the
52
- * query. Carries the query name, the index of the row, and the schema's
53
- * issues.
87
+ * query, or the validator of a built query. Carries the query name, which
88
+ * is `BUILT` for a built query, the index of the row, and the issues.
54
89
  */
55
90
  export declare class InvalidRowError extends Error {
56
91
  readonly query: string;
@@ -60,7 +95,7 @@ export declare class InvalidRowError extends Error {
60
95
  }
61
96
  /**
62
97
  * Raised at construction when a query group takes the name of a member of
63
- * the service, such as `migrate`.
98
+ * the service, such as `migrate` or `build`.
64
99
  */
65
100
  export declare class ReservedQueryError extends Error {
66
101
  readonly query: string;
@@ -75,8 +110,8 @@ export declare class AmbiguousQueryError extends Error {
75
110
  constructor(query: string);
76
111
  }
77
112
  /**
78
- * Raised when the driver fails to run a query. Carries the query name and
79
- * the driver's error as `cause`.
113
+ * Raised when the driver fails to run a query. Carries the query name, which
114
+ * is `BUILT` for a built query, and the driver's error as `cause`.
80
115
  */
81
116
  export declare class QueryError extends Error {
82
117
  readonly query: string;
@@ -108,6 +143,33 @@ export declare class SeedError extends Error {
108
143
  readonly seed: string;
109
144
  constructor(seed: string, cause: unknown);
110
145
  }
146
+ /**
147
+ * Raised when a grant fails to apply: the role could not be made, a revoke
148
+ * failed, or its SQL failed. Carries the role and the driver's error as
149
+ * `cause`. The transaction rolls back.
150
+ */
151
+ export declare class RoleError extends Error {
152
+ readonly role: string;
153
+ constructor(role: string, cause: unknown);
154
+ }
155
+ /**
156
+ * Raised at construction when the service is scoped to a role the contract
157
+ * does not have.
158
+ */
159
+ export declare class UnknownRoleError extends Error {
160
+ readonly role: string;
161
+ constructor(role: string);
162
+ }
163
+ /**
164
+ * Raised when a service scoped to a role is asked for a query the role may
165
+ * not run. The service of a role offers the queries of the role and no
166
+ * other.
167
+ */
168
+ export declare class ForbiddenQueryError extends Error {
169
+ readonly query: string;
170
+ readonly role: string;
171
+ constructor(query: string, role: string);
172
+ }
111
173
  /**
112
174
  * Runs a schema check and rethrows its {@link SchemaError} as the error that
113
175
  * `frame` makes from the issues. Any other error propagates untouched.
@@ -142,23 +204,43 @@ export interface Executor {
142
204
  exec(sql: string): Promise<void>;
143
205
  transaction<T>(run: (executor: Executor) => Promise<T>): Promise<T>;
144
206
  }
207
+ /**
208
+ * The role a service is scoped to: a role of the contract, or `undefined`
209
+ * for a service over every query.
210
+ */
211
+ export type Scoping<D extends Definition> = Role<D> | undefined;
212
+ /**
213
+ * The queries a service scoped to `R` offers: the queries of the role, or
214
+ * every query of the contract when there is no role.
215
+ */
216
+ export type Scope<D extends Definition, R extends Scoping<D>> = [R] extends [Role<D>] ? RoleQuery<D, R> : Query<D>;
145
217
  /**
146
218
  * The caller-owned state a {@link Bezoar} service reads: the executor it
147
219
  * runs on and the SQL of every query. The service reads the executor on each
148
220
  * call. A caller can replace it.
149
221
  */
150
- export type Config<D extends Definition> = {
222
+ export type Config<D extends Definition, R extends Scoping<D> = undefined> = {
151
223
  /** The connection the service runs on. */
152
224
  executor: Executor;
153
225
  /** The SQL of each query, by name, as `@bezoar/kit` built it. */
154
226
  queries: Bundle<D>;
227
+ /**
228
+ * The role the service is scoped to. The service offers the queries the
229
+ * kit found the role may run and no other, and the executor is expected
230
+ * to run as the role: a driver takes the role when it connects. Without
231
+ * one, the service offers every query of the contract.
232
+ */
233
+ role?: R;
155
234
  };
156
235
  /**
157
- * What the service reports after a query runs: the name, the arguments, the
158
- * time it took in milliseconds, and the count of the outcome.
236
+ * What the service reports after a query runs: the name, the SQL, the
237
+ * arguments, the time it took in milliseconds, and the count of the
238
+ * outcome. A built query reports {@link BUILT} as its name, the compiled SQL,
239
+ * and its parameters as the arguments.
159
240
  */
160
241
  export interface Report<D extends Definition> {
161
- readonly query: Query<D>;
242
+ readonly query: Query<D> | typeof BUILT;
243
+ readonly sql: string;
162
244
  readonly arguments: unknown;
163
245
  readonly ms: number;
164
246
  readonly count: number;
@@ -194,6 +276,16 @@ export interface Seed {
194
276
  readonly name: string;
195
277
  readonly sql: string;
196
278
  }
279
+ /**
280
+ * One grant, as `@bezoar/kit` built it: the name of a role, and the SQL
281
+ * that gives the role its privileges. A grant is not tracked: the runner
282
+ * revokes what the role holds and runs the SQL again, so the SQL states the
283
+ * whole of the privileges of the role.
284
+ */
285
+ export interface Grant {
286
+ readonly role: string;
287
+ readonly sql: string;
288
+ }
197
289
  /**
198
290
  * The arguments a query is called with: its arguments when it has a required
199
291
  * slot, and optional arguments when every slot is nullable or there is none.
@@ -217,18 +309,69 @@ type Tree<D extends Definition, K extends string, P extends string = ""> = { rea
217
309
  * The queries of a contract as functions: `db.events.list({ day })`. A dot
218
310
  * in a name is a level of the object. The query `events.list` is
219
311
  * `db.events.list()`, and its first row is `db.events.list.first()`. The
220
- * directory of a query file is its group and the file is its name.
312
+ * directory of a query file is its group and the file is its name. `Q` is
313
+ * the queries to offer: every query of the contract, or those of a role.
314
+ */
315
+ export type Groups<D extends Definition, Q extends Query<D> = Query<D>> = Tree<D, Q>;
316
+ /**
317
+ * A validator of a row, in the shape of a zod schema: `safeParse` answers
318
+ * with the value as `R` on success and with the issues on failure. Any zod
319
+ * schema is one.
221
320
  */
222
- export type Groups<D extends Definition> = Tree<D, Query<D>>;
321
+ export interface Validator<R> {
322
+ safeParse(value: unknown): {
323
+ readonly success: true;
324
+ readonly data: R;
325
+ } | {
326
+ readonly success: false;
327
+ readonly error: {
328
+ readonly issues: Issue[];
329
+ };
330
+ };
331
+ }
332
+ /**
333
+ * Runs a built query: one made with `build` of the service, or any query of
334
+ * the builder that compiles. Without a validator, the rows come
335
+ * back as the builder infers them, unproven. With one, each row is proven
336
+ * against it and comes back as its output, and a row that does not fit is
337
+ * an `InvalidRowError`. The output of the validator must fit the row the
338
+ * builder infers, so a validator that disagrees with the query fails to
339
+ * compile. `first` runs the query and takes its first row, or `null`.
340
+ */
341
+ export interface Execute {
342
+ <O>(query: Compilable<O>): Promise<O[]>;
343
+ <O, R extends O>(query: Compilable<O>, row: Validator<R>): Promise<R[]>;
344
+ readonly first: {
345
+ <O>(query: Compilable<O>): Promise<O | null>;
346
+ <O, R extends O>(query: Compilable<O>, row: Validator<R>): Promise<R | null>;
347
+ };
348
+ }
349
+ /**
350
+ * Applies the grants of a build, and `declare` makes their roles alone.
351
+ */
352
+ export interface Roles {
353
+ /**
354
+ * Makes the roles the cluster lacks, and applies the grants: for each
355
+ * role, revokes what it holds and runs its SQL, inside one transaction
356
+ * under an advisory lock. Throws `RoleError` when one fails.
357
+ */
358
+ (grants: readonly Grant[]): Promise<void>;
359
+ /**
360
+ * Makes the roles the cluster lacks and grants nothing. What a migration
361
+ * that names a role needs before it runs.
362
+ */
363
+ readonly declare: (grants: readonly Grant[]) => Promise<void>;
364
+ }
223
365
  /**
224
366
  * The members of a service other than its queries. A query group cannot
225
- * take one of these names.
367
+ * take one of these names. `R` is the role the service is scoped to, or
368
+ * `undefined` for a service over every query.
226
369
  */
227
- export interface Service<D extends Definition> {
370
+ export interface Service<D extends Definition, R extends Scoping<D> = undefined> {
228
371
  /**
229
- * The caller-owned state: the executor and the SQL bundle.
372
+ * The caller-owned state: the executor, the SQL bundle, and the role.
230
373
  */
231
- config: Config<D>;
374
+ config: Config<D, R>;
232
375
  /**
233
376
  * The validation bundle for the contract.
234
377
  */
@@ -240,19 +383,36 @@ export interface Service<D extends Definition> {
240
383
  * when the arguments do not fit the slots, `QueryError` when the driver
241
384
  * fails, and `InvalidRowError` when a row does not fit the columns.
242
385
  */
243
- query: <Q extends Query<D>>(query: Q, ...args: Args<D, Q>) => Promise<Returns<D, Q>>;
386
+ query: <Q extends Scope<D, R>>(query: Q, ...args: Args<D, Q>) => Promise<Returns<D, Q>>;
244
387
  /**
245
388
  * Runs a query with a column by name and returns its first row, or `null`
246
389
  * when it has none. The same call as `first` on the function under its
247
390
  * group. Proves the row it returns and no other. Throws as `query` does.
248
391
  */
249
- first: <Q extends RowQuery<D>>(query: Q, ...args: Args<D, Q>) => Promise<Row<D, Q> | null>;
392
+ first: <Q extends Scope<D, R> & RowQuery<D>>(query: Q, ...args: Args<D, Q>) => Promise<Row<D, Q> | null>;
393
+ /**
394
+ * Runs a built query and returns its rows, proven against a validator
395
+ * when one is given. `execute.first` returns the first row or `null`. See
396
+ * {@link Execute}. Throws `QueryError` when the driver fails and
397
+ * `InvalidRowError` when a row does not fit the validator.
398
+ */
399
+ execute: Execute;
400
+ /**
401
+ * The query builder of the service: a [kysely](https://kysely.dev) over
402
+ * the executor of the container, typed by the {@link Database} of the
403
+ * contract. A query built here runs on the executor of the service when
404
+ * it executes. Its own `transaction` is refused: a transaction belongs
405
+ * to `transaction` of the service, and the service of a transaction has
406
+ * a builder of its own.
407
+ */
408
+ build: Kysely<Database<D>>;
250
409
  /**
251
410
  * Runs a function inside one transaction. The function receives a service
252
- * over the transaction, with the same queries and options. The transaction
253
- * commits when the function returns and rolls back when it throws.
411
+ * over the transaction, with the same queries, builder, and options. The
412
+ * transaction commits when the function returns and rolls back when it
413
+ * throws.
254
414
  */
255
- transaction: <T>(run: (tx: Bezoar<D>) => Promise<T>) => Promise<T>;
415
+ transaction: <T>(run: (tx: Bezoar<D, R>) => Promise<T>) => Promise<T>;
256
416
  /**
257
417
  * Applies the migrations the database lacks, in the order given, inside
258
418
  * one transaction under an advisory lock. Returns the versions it applied.
@@ -265,13 +425,18 @@ export interface Service<D extends Definition> {
265
425
  * `SeedError` when one fails.
266
426
  */
267
427
  seed: (seeds: readonly Seed[]) => Promise<void>;
428
+ /**
429
+ * Applies the grants of a build. See {@link Roles}.
430
+ */
431
+ roles: Roles;
268
432
  }
269
433
  /**
270
434
  * A runtime database service over a contract. The service has its members
271
435
  * and, beside them, a function for every query under its group. It never
272
- * connects: the caller brings an executor from a driver package.
436
+ * connects: the caller brings an executor from a driver package. A service
437
+ * scoped to a role `R` has a function for the queries of the role alone.
273
438
  */
274
- export type Bezoar<D extends Definition> = Service<D> & Groups<D>;
439
+ export type Bezoar<D extends Definition, R extends Scoping<D> = undefined> = Service<D, R> & Groups<D, Scope<D, R>>;
275
440
  /**
276
441
  * Builds the runtime {@link Bezoar} service over a contract.
277
442
  *
@@ -282,15 +447,40 @@ export type Bezoar<D extends Definition> = Service<D> & Groups<D>;
282
447
  * has no column. `first` returns the first row instead. The service never
283
448
  * connects: the caller brings an executor from a driver
284
449
  * package, and a transaction is the same service over the executor of the
285
- * transaction.
450
+ * transaction. A container with a role makes a service over the queries of
451
+ * the role alone, typed so, over an executor the driver runs as the role.
286
452
  *
287
453
  * @param definition - The contract: the kit's `contract` export.
288
- * @param config - The caller-owned container: the executor and the bundle.
454
+ * @param config - The caller-owned container: the executor, the bundle, and
455
+ * the role, if any.
289
456
  * @param options - The runtime features: a report after each query.
290
457
  * @returns A {@link Bezoar} service bound to the container.
291
458
  * @throws InvalidBundleError when the bundle does not match the contract.
459
+ * @throws UnknownRoleError when the contract has no such role.
292
460
  * @throws ReservedQueryError when a query group takes a member's name.
293
461
  * @throws AmbiguousQueryError when a name is both a query and a group.
294
462
  */
295
- export declare const makeBezoar: <const D extends Definition>(definition: D, config: Config<D>, options?: Options<D>) => Bezoar<D>;
463
+ export declare const makeBezoar: <const D extends Definition, const R extends Scoping<D> = undefined>(definition: D, config: Config<D, R>, options?: Options<D>) => Bezoar<D, R>;
464
+ /**
465
+ * Makes the roles the cluster lacks, inside one transaction. What a
466
+ * migration needs before it can name a role, in a policy or a grant of its
467
+ * own. Nothing is granted.
468
+ *
469
+ * @param executor - The connection to run on.
470
+ * @param grants - The grants, for the names of their roles.
471
+ */
472
+ export declare const declareRoles: (executor: Executor, grants: readonly Grant[]) => Promise<void>;
473
+ /**
474
+ * Applies the grants: makes the roles the cluster lacks, and for each role
475
+ * revokes every privilege it holds on the objects of each schema and then
476
+ * runs its SQL. The run is one transaction under an advisory lock, so two
477
+ * runs wait for each other and a run is all or nothing. A grant file states
478
+ * the whole of the privileges of its role: a grant removed from the file is
479
+ * gone after the next run. A membership of a role in another, and a default
480
+ * privilege, are not revoked.
481
+ *
482
+ * @param executor - The connection to run on.
483
+ * @param grants - The grants, in the order to apply them.
484
+ */
485
+ export declare const roles: (executor: Executor, grants: readonly Grant[]) => Promise<void>;
296
486
  export {};
package/.dist/index.mjs CHANGED
@@ -1,14 +1,19 @@
1
1
  import { SchemaError, defineSchema } from "@bezoar/schema";
2
+ import { Kysely, PostgresAdapter, PostgresIntrospector, PostgresQueryCompiler } from "kysely";
2
3
  import { keys, record, rekey } from "objectively";
3
4
  const RESERVED = [
4
5
  "config",
5
6
  "schema",
6
7
  "query",
7
8
  "first",
9
+ "execute",
10
+ "build",
8
11
  "transaction",
9
12
  "migrate",
10
- "seed"
13
+ "seed",
14
+ "roles"
11
15
  ];
16
+ const BUILT = "build";
12
17
  const TABLE = "bezoar_migrations";
13
18
  const LOCK = 6451064;
14
19
  const ACQUIRE = "SELECT pg_advisory_xact_lock($1)";
@@ -20,6 +25,19 @@ const CREATE = `CREATE TABLE IF NOT EXISTS ${TABLE} (
20
25
  )`;
21
26
  const APPLIED = `SELECT version, checksum FROM ${TABLE} ORDER BY version`;
22
27
  const RECORD = `INSERT INTO ${TABLE} (version, name, checksum) VALUES ($1, $2, $3)`;
28
+ const ROLES_LOCK = 6451065;
29
+ const EXISTS = "SELECT 1 FROM pg_roles WHERE rolname = $1";
30
+ const SCHEMAS = `SELECT nspname FROM pg_namespace
31
+ WHERE nspname NOT LIKE 'pg\\_%' AND nspname <> 'information_schema'
32
+ ORDER BY nspname`;
33
+ const quote = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
34
+ const DECLARE = (role) => `CREATE ROLE ${quote(role)} NOLOGIN`;
35
+ const REVOKE = (role, schema) => [
36
+ `REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA ${quote(schema)} FROM ${quote(role)}`,
37
+ `REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA ${quote(schema)} FROM ${quote(role)}`,
38
+ `REVOKE ALL PRIVILEGES ON ALL ROUTINES IN SCHEMA ${quote(schema)} FROM ${quote(role)}`,
39
+ `REVOKE ALL PRIVILEGES ON SCHEMA ${quote(schema)} FROM ${quote(role)}`
40
+ ].join(";\n");
23
41
  const summarize = (issues) => issues.map((issue) => issue.path.length ? `${issue.path.map(String).join(".")}: ${issue.message}` : issue.message).join("\n");
24
42
  var InvalidBundleError = class extends Error {
25
43
  issues;
@@ -99,6 +117,32 @@ var SeedError = class extends Error {
99
117
  this.seed = seed;
100
118
  }
101
119
  };
120
+ var RoleError = class extends Error {
121
+ role;
122
+ constructor(role, cause) {
123
+ super(`@bezoar/core: the grant of ${JSON.stringify(role)} failed`, { cause });
124
+ this.name = "RoleError";
125
+ this.role = role;
126
+ }
127
+ };
128
+ var UnknownRoleError = class extends Error {
129
+ role;
130
+ constructor(role) {
131
+ super(`@bezoar/core: the contract has no role ${JSON.stringify(role)}`);
132
+ this.name = "UnknownRoleError";
133
+ this.role = role;
134
+ }
135
+ };
136
+ var ForbiddenQueryError = class extends Error {
137
+ query;
138
+ role;
139
+ constructor(query, role) {
140
+ super(`@bezoar/core: ${JSON.stringify(query)} is not a query of the role ${JSON.stringify(role)}`);
141
+ this.name = "ForbiddenQueryError";
142
+ this.query = query;
143
+ this.role = role;
144
+ }
145
+ };
102
146
  const reframe = (frame, run) => {
103
147
  try {
104
148
  return run();
@@ -107,6 +151,40 @@ const reframe = (frame, run) => {
107
151
  throw error;
108
152
  }
109
153
  };
154
+ const unsupported = (what, instead) => /* @__PURE__ */ new Error(`@bezoar/core: ${what} is not supported by the service; ${instead}`);
155
+ const defineConnection = (executor) => ({
156
+ executeQuery: async (compiled) => {
157
+ const outcome = await executor().query(compiled.sql, compiled.parameters);
158
+ return {
159
+ rows: outcome.rows,
160
+ numAffectedRows: BigInt(outcome.count)
161
+ };
162
+ },
163
+ streamQuery: () => {
164
+ throw unsupported("streaming", "run the query and take its rows");
165
+ }
166
+ });
167
+ const defineDriver = (executor) => {
168
+ const connection = defineConnection(executor);
169
+ const refuse = async () => {
170
+ throw unsupported("a transaction of the builder", "run `db.transaction((tx) => ...)` and build the query on `tx`");
171
+ };
172
+ return {
173
+ init: async () => {},
174
+ acquireConnection: async () => connection,
175
+ releaseConnection: async () => {},
176
+ beginTransaction: refuse,
177
+ commitTransaction: refuse,
178
+ rollbackTransaction: refuse,
179
+ destroy: async () => {}
180
+ };
181
+ };
182
+ const defineDialect = (executor) => ({
183
+ createDriver: () => defineDriver(executor),
184
+ createQueryCompiler: () => new PostgresQueryCompiler(),
185
+ createAdapter: () => new PostgresAdapter(),
186
+ createIntrospector: (db) => new PostgresIntrospector(db)
187
+ });
110
188
  const descend = (level, segment, name) => {
111
189
  const next = level[segment] ?? {};
112
190
  if (!record(next)) throw new AmbiguousQueryError(name);
@@ -167,6 +245,28 @@ const migrate = (executor, migrations) => executor.transaction(async (tx) => {
167
245
  }
168
246
  return done;
169
247
  });
248
+ const ensure = async (tx, grants) => {
249
+ for (const grant of grants) {
250
+ const { rows } = await tx.query(EXISTS, [grant.role]);
251
+ if (rows.length === 0) try {
252
+ await tx.exec(DECLARE(grant.role));
253
+ } catch (cause) {
254
+ throw new RoleError(grant.role, cause);
255
+ }
256
+ }
257
+ };
258
+ const declareRoles = (executor, grants) => executor.transaction((tx) => ensure(tx, grants));
259
+ const roles = (executor, grants) => executor.transaction(async (tx) => {
260
+ await tx.query(ACQUIRE, [ROLES_LOCK]);
261
+ await ensure(tx, grants);
262
+ const schemas = (await tx.query(SCHEMAS, [])).rows.map((row) => String(row.nspname));
263
+ for (const grant of grants) try {
264
+ for (const schema of schemas) await tx.exec(REVOKE(grant.role, schema));
265
+ await tx.exec(grant.sql);
266
+ } catch (cause) {
267
+ throw new RoleError(grant.role, cause);
268
+ }
269
+ });
170
270
  const seed = (executor, seeds) => executor.transaction(async (tx) => {
171
271
  for (const entry of seeds) try {
172
272
  await tx.exec(entry.sql);
@@ -175,7 +275,18 @@ const seed = (executor, seeds) => executor.transaction(async (tx) => {
175
275
  }
176
276
  });
177
277
  const bind = (slots, given) => slots.map((slot) => given[slot.name] ?? null);
278
+ const scopeOf = (definition, role) => {
279
+ if (role === void 0) return keys(definition.queries);
280
+ const queries = definition.roles?.[role];
281
+ if (queries === void 0) throw new UnknownRoleError(role);
282
+ return queries;
283
+ };
178
284
  const defineService = (definition, schema, config, options) => {
285
+ const names = scopeOf(definition, config.role);
286
+ const offered = new Set(names);
287
+ const admit = (query) => {
288
+ if (config.role !== void 0 && !offered.has(query)) throw new ForbiddenQueryError(query, config.role);
289
+ };
179
290
  const execute = async (query, params) => {
180
291
  try {
181
292
  return await config.executor.query(config.queries[query], params);
@@ -185,12 +296,14 @@ const defineService = (definition, schema, config, options) => {
185
296
  };
186
297
  const prove = (query, index, row) => reframe((issues) => new InvalidRowError(query, index, issues), () => schema.assert.row(query, row));
187
298
  const perform = async (query, args) => {
299
+ admit(query);
188
300
  const statement = definition.queries[query];
189
301
  const given = reframe((issues) => new InvalidArgumentsError(query, issues), () => schema.parse.arguments(query, args));
190
302
  const started = performance.now();
191
303
  const outcome = await execute(query, bind(statement.slots, given));
192
304
  options.onQuery?.({
193
305
  query,
306
+ sql: config.queries[query],
194
307
  arguments: args,
195
308
  ms: performance.now() - started,
196
309
  count: outcome.count
@@ -210,6 +323,40 @@ const defineService = (definition, schema, config, options) => {
210
323
  prove(query, 0, row);
211
324
  return row;
212
325
  }
326
+ const builder = new Kysely({ dialect: defineDialect(() => config.executor) });
327
+ const built = async (query) => {
328
+ const compiled = query.compile();
329
+ const started = performance.now();
330
+ let result;
331
+ try {
332
+ result = await builder.executeQuery(compiled);
333
+ } catch (cause) {
334
+ throw new QueryError(BUILT, cause);
335
+ }
336
+ options.onQuery?.({
337
+ query: BUILT,
338
+ sql: compiled.sql,
339
+ arguments: compiled.parameters,
340
+ ms: performance.now() - started,
341
+ count: Number(result.numAffectedRows ?? result.rows.length)
342
+ });
343
+ return result;
344
+ };
345
+ const proveWith = (validator, index, row) => {
346
+ const result = validator.safeParse(row);
347
+ if (!result.success) throw new InvalidRowError(BUILT, index, result.error.issues);
348
+ return result.data;
349
+ };
350
+ async function executeAll(query, validator) {
351
+ const { rows } = await built(query);
352
+ return validator === void 0 ? rows : rows.map((row, index) => proveWith(validator, index, row));
353
+ }
354
+ async function executeFirst(query, validator) {
355
+ const { rows } = await built(query);
356
+ const row = rows[0];
357
+ if (row === void 0) return null;
358
+ return validator === void 0 ? row : proveWith(validator, 0, row);
359
+ }
213
360
  const transaction = (fn) => config.executor.transaction((executor) => fn(defineService(definition, schema, {
214
361
  ...config,
215
362
  executor
@@ -219,11 +366,14 @@ const defineService = (definition, schema, config, options) => {
219
366
  schema,
220
367
  query: run,
221
368
  first: take,
369
+ execute: Object.assign(executeAll, { first: executeFirst }),
370
+ build: builder,
222
371
  transaction,
223
372
  migrate: (migrations) => migrate(config.executor, migrations),
224
- seed: (seeds) => seed(config.executor, seeds)
373
+ seed: (seeds) => seed(config.executor, seeds),
374
+ roles: Object.assign((grants) => roles(config.executor, grants), { declare: (grants) => declareRoles(config.executor, grants) })
225
375
  };
226
- const groups = defineGroups(keys(definition.queries), new Set(RESERVED), (query) => {
376
+ const groups = defineGroups(names, new Set(RESERVED), (query) => {
227
377
  const method = (args) => run(query, args);
228
378
  return returnsRows(query) ? Object.assign(method, { first: (args) => take(query, args) }) : method;
229
379
  });
@@ -234,4 +384,4 @@ const makeBezoar = (definition, config, options = {}) => {
234
384
  reframe((issues) => new InvalidBundleError(issues), () => schema.assert.bundle(config.queries));
235
385
  return defineService(definition, schema, config, options);
236
386
  };
237
- export { ACQUIRE, APPLIED, AmbiguousQueryError, CREATE, InvalidArgumentsError, InvalidBundleError, InvalidRowError, LOCK, MigrationDriftError, MigrationError, QueryError, RECORD, RESERVED, ReservedQueryError, SeedError, TABLE, makeBezoar, reframe };
387
+ export { ACQUIRE, APPLIED, AmbiguousQueryError, BUILT, CREATE, DECLARE, EXISTS, ForbiddenQueryError, InvalidArgumentsError, InvalidBundleError, InvalidRowError, LOCK, MigrationDriftError, MigrationError, QueryError, RECORD, RESERVED, REVOKE, ROLES_LOCK, ReservedQueryError, RoleError, SCHEMAS, SeedError, TABLE, UnknownRoleError, declareRoles, makeBezoar, quote, reframe, roles };
package/README.md CHANGED
@@ -1,8 +1,9 @@
1
1
  # @bezoar/core
2
2
 
3
3
  The runtime service of bezoar. The service runs the queries of a contract
4
- by name, proves the arguments and the rows against the contract, and applies
5
- migrations and seeds.
4
+ by name, proves the arguments and the rows against the contract, builds
5
+ dynamic queries with [kysely](https://kysely.dev) over the tables of the
6
+ contract, and applies migrations and seeds.
6
7
 
7
8
  [`@bezoar/schema`](../schema) has the contract types and the validation.
8
9
  A driver package provides the connection.
@@ -75,7 +76,7 @@ error as `cause`. For `one` and `many`, each row is proven against the
75
76
  columns, and a row that does not fit is an `InvalidRowError` with its index.
76
77
 
77
78
  The `onQuery` option receives a report after each call: the query name, the
78
- arguments, the time in milliseconds, and the count of the outcome.
79
+ SQL, the arguments, the time in milliseconds, and the count of the outcome.
79
80
 
80
81
  ```ts
81
82
  const db = makeBezoar(contract, config, {
@@ -83,15 +84,69 @@ const db = makeBezoar(contract, config, {
83
84
  });
84
85
  ```
85
86
 
87
+ ## The query builder
88
+
89
+ A contract carries the tables and the views of the database, and the service
90
+ carries a query builder typed by them: `build`, a
91
+ [kysely](https://kysely.dev) over the executor of the service. A query built
92
+ on it runs on that executor when it executes.
93
+
94
+ ```ts
95
+ const upcoming = await db.build
96
+ .selectFrom("events")
97
+ .select(["id", "slug", "title"])
98
+ .where("day", "=", "sunday")
99
+ .orderBy("start_time")
100
+ .execute();
101
+
102
+ await db.build
103
+ .insertInto("events")
104
+ .values({ slug: "prayer", title: "Prayer" })
105
+ .execute();
106
+ ```
107
+
108
+ The tables type the builder. A column with a default or an identity is
109
+ optional in an insert. A column that takes null also takes `null`. A view is
110
+ read only. A column of a type the type table does not have is `unknown`.
111
+
112
+ A query that runs through the builder returns its rows as the builder infers
113
+ them, and no row is proven. `execute` runs a built query through the service
114
+ instead: it reports the query through `onQuery`, and with a validator it
115
+ proves each row and returns the output of the validator. Any zod schema is a
116
+ validator. A validator whose output does not fit the row the builder infers
117
+ fails to compile. `execute.first` takes the first row, or `null`.
118
+
119
+ ```ts
120
+ const rows = await db.execute(
121
+ db.build.selectFrom("events").select(["id", "slug"]),
122
+ z.object({ id: z.int(), slug: z.string() }),
123
+ );
124
+ const one = await db.execute.first(query, schema);
125
+ ```
126
+
127
+ A row that does not fit the validator is an `InvalidRowError`, and a driver
128
+ failure is a `QueryError`, each with the query name `"build"`. The report
129
+ of a built query carries the same name, the compiled SQL, and the parameters
130
+ as the arguments.
131
+
132
+ The own `transaction` of the builder is refused: a transaction belongs to
133
+ `transaction` of the service, and the service of a transaction has a builder
134
+ of its own.
135
+
86
136
  ## Transactions
87
137
 
88
138
  `transaction` runs a function with a service over one transaction. The
89
- service has the same queries and options.
139
+ service has the same queries, a builder over the transaction, and the same
140
+ options.
90
141
 
91
142
  ```ts
92
143
  await db.transaction(async (tx) => {
93
144
  await tx.events.insert({ slug: "prayer", title: "Prayer Meeting" });
94
- await tx.events.archive({ ids: [3, 4] });
145
+ await tx
146
+ .updateTable("events")
147
+ .set({ archived: true })
148
+ .where("id", "in", [3, 4])
149
+ .execute();
95
150
  });
96
151
  ```
97
152
 
@@ -99,6 +154,57 @@ The transaction commits when the function returns and rolls back when it
99
154
  throws. Whether a transaction inside a transaction opens a savepoint is up
100
155
  to the driver.
101
156
 
157
+ ## Roles
158
+
159
+ A contract built from a package with roles carries, for each role, the
160
+ queries the kit found it may run. A container with a `role` makes a service
161
+ over those queries alone, typed so: `db.admin.events.update` is not a member
162
+ of the service of `web`, and `db.query("admin.events.update")` is a type
163
+ error, and a `ForbiddenQueryError` by name at runtime. A role the contract
164
+ does not have is an `UnknownRoleError` at construction.
165
+
166
+ ```ts
167
+ const web = makeBezoar(contract, {
168
+ executor: pg(process.env.DATABASE_URL, { role: "web" }),
169
+ queries,
170
+ role: "web",
171
+ });
172
+ ```
173
+
174
+ The service does not take the role itself: the executor does. Each driver
175
+ package takes a `role` and runs every statement as it. The database then
176
+ enforces what the role may do, under its grants and its policies, for the
177
+ queries of the contract and for the builder alike.
178
+
179
+ `roles` applies the grants of a build. The kit builds the list: each entry
180
+ has a role and its SQL.
181
+
182
+ ```ts
183
+ import { roles } from "@bbf/database/roles";
184
+
185
+ await db.roles.declare(roles); // the roles alone, before the migrations
186
+ await db.migrate(migrations);
187
+ await db.roles(roles); // the grants, after the tables exist
188
+ await db.seed(seeds);
189
+ ```
190
+
191
+ `roles.declare` makes each role the cluster lacks, as a role that cannot
192
+ log in, and grants nothing. A migration that names a role, in a policy or a
193
+ grant of its own, needs this first. `roles` makes the roles the cluster
194
+ lacks, and then for each role revokes every privilege it holds on the
195
+ tables, sequences, routines, and schemas of the database and runs its SQL,
196
+ inside one transaction under an advisory lock. A grant file states the
197
+ whole of the privileges of its role: a grant removed from the file is gone
198
+ after the next run. A membership of a role in another, and a default
199
+ privilege, are not revoked. A grant that fails is a `RoleError` with its
200
+ role, and the run rolls back.
201
+
202
+ The login users are the deployment's: a role of bezoar is a group, and a
203
+ user joins it with `CREATE ROLE bbf_web LOGIN PASSWORD '…' IN ROLE web`.
204
+ The package says what `web` may do and never who `web` is. A login user
205
+ that is a member of its role alone cannot migrate or grant, so an app over
206
+ one applies neither; the owner does.
207
+
102
208
  ## Migrations and seeds
103
209
 
104
210
  `migrate` applies the migrations the database lacks. The kit builds the
@@ -129,17 +235,24 @@ tracked. Write a seed so that it can run again. A seed that fails is a
129
235
 
130
236
  ## Names
131
237
 
132
- The members of the service are `config`, `schema`, `query`, `transaction`,
133
- `migrate`, and `seed`. A query group cannot take one of these names, and a
134
- name cannot be both a query and a group. Either is an error at
135
- construction: `ReservedQueryError` or `AmbiguousQueryError`.
238
+ The members of the service are `config`, `schema`, `query`, `first`,
239
+ `execute`, `build`, `transaction`, `migrate`, `seed`, and `roles`. A query
240
+ group cannot take one of these names,
241
+ and a name cannot be both a query and a group. Either is an error at
242
+ construction: `ReservedQueryError` or `AmbiguousQueryError`. `RESERVED`
243
+ exports the list.
136
244
 
137
245
  ## Errors
138
246
 
139
247
  - `InvalidBundleError`: the SQL bundle does not match the contract.
140
248
  - `InvalidArgumentsError`: the arguments of a call do not fit the slots.
141
- - `InvalidRowError`: a row does not fit the columns.
249
+ - `InvalidRowError`: a row does not fit the columns, or the validator of a
250
+ built query.
142
251
  - `QueryError`: the driver failed. `cause` is the driver's error.
252
+ - `UnknownRoleError`: the container names a role the contract lacks.
253
+ - `ForbiddenQueryError`: a service scoped to a role was asked, by name, for
254
+ a query the role may not run.
255
+ - `RoleError`: a grant failed to apply. `cause` is the driver's error.
143
256
  - `MigrationDriftError`: the database holds a migration the list does not
144
257
  match.
145
258
  - `MigrationError`, `SeedError`: a migration or a seed failed. `cause` is
@@ -149,11 +262,14 @@ construction: `ReservedQueryError` or `AmbiguousQueryError`.
149
262
 
150
263
  ## Types
151
264
 
152
- - `Bezoar<D>` is the service: `Service<D>` and the `Groups<D>`.
265
+ - `Bezoar<D>` is the service: `Service<D>`, the `Builder<D>`, and the
266
+ `Groups<D>`.
153
267
  - `Config<D>` is the container. `Options<D>` has `onQuery`.
154
268
  - `Executor` and `Outcome` are what a driver provides.
155
269
  - `Method<D, Q>` is the function of one query. `Report<D>` is what `onQuery`
156
270
  receives.
271
+ - `Execute` is the signature of `execute`. `Validator<R>` is what it proves
272
+ a row with. `Delegated` is the name of a builder member.
157
273
  - `Migration` and `Seed` are what the kit builds for the runner.
158
274
 
159
275
  ## Related
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bezoar/core",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "description": "The bezoar runtime service: run queries by name, migrate, seed",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -21,8 +21,12 @@
21
21
  ".dist"
22
22
  ],
23
23
  "dependencies": {
24
+ "kysely": "^0.29.7",
24
25
  "objectively": "^0.3.0",
25
- "@bezoar/schema": "0.0.3"
26
+ "@bezoar/schema": "0.0.5"
27
+ },
28
+ "devDependencies": {
29
+ "zod": "^4.6.5"
26
30
  },
27
31
  "scripts": {
28
32
  "build": "obuild",