@bezoar/core 0.0.3 → 0.0.4

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, 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"];
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.
@@ -49,8 +56,8 @@ export declare class InvalidArgumentsError extends Error {
49
56
  }
50
57
  /**
51
58
  * 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.
59
+ * query, or the validator of a built query. Carries the query name, which
60
+ * is `BUILT` for a built query, the index of the row, and the issues.
54
61
  */
55
62
  export declare class InvalidRowError extends Error {
56
63
  readonly query: string;
@@ -60,7 +67,7 @@ export declare class InvalidRowError extends Error {
60
67
  }
61
68
  /**
62
69
  * Raised at construction when a query group takes the name of a member of
63
- * the service, such as `migrate`.
70
+ * the service, such as `migrate` or `build`.
64
71
  */
65
72
  export declare class ReservedQueryError extends Error {
66
73
  readonly query: string;
@@ -75,8 +82,8 @@ export declare class AmbiguousQueryError extends Error {
75
82
  constructor(query: string);
76
83
  }
77
84
  /**
78
- * Raised when the driver fails to run a query. Carries the query name and
79
- * the driver's error as `cause`.
85
+ * Raised when the driver fails to run a query. Carries the query name, which
86
+ * is `BUILT` for a built query, and the driver's error as `cause`.
80
87
  */
81
88
  export declare class QueryError extends Error {
82
89
  readonly query: string;
@@ -154,11 +161,14 @@ export type Config<D extends Definition> = {
154
161
  queries: Bundle<D>;
155
162
  };
156
163
  /**
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.
164
+ * What the service reports after a query runs: the name, the SQL, the
165
+ * arguments, the time it took in milliseconds, and the count of the
166
+ * outcome. A built query reports {@link BUILT} as its name, the compiled SQL,
167
+ * and its parameters as the arguments.
159
168
  */
160
169
  export interface Report<D extends Definition> {
161
- readonly query: Query<D>;
170
+ readonly query: Query<D> | typeof BUILT;
171
+ readonly sql: string;
162
172
  readonly arguments: unknown;
163
173
  readonly ms: number;
164
174
  readonly count: number;
@@ -220,6 +230,39 @@ type Tree<D extends Definition, K extends string, P extends string = ""> = { rea
220
230
  * directory of a query file is its group and the file is its name.
221
231
  */
222
232
  export type Groups<D extends Definition> = Tree<D, Query<D>>;
233
+ /**
234
+ * A validator of a row, in the shape of a zod schema: `safeParse` answers
235
+ * with the value as `R` on success and with the issues on failure. Any zod
236
+ * schema is one.
237
+ */
238
+ export interface Validator<R> {
239
+ safeParse(value: unknown): {
240
+ readonly success: true;
241
+ readonly data: R;
242
+ } | {
243
+ readonly success: false;
244
+ readonly error: {
245
+ readonly issues: Issue[];
246
+ };
247
+ };
248
+ }
249
+ /**
250
+ * Runs a built query: one made with `build` of the service, or any query of
251
+ * the builder that compiles. Without a validator, the rows come
252
+ * back as the builder infers them, unproven. With one, each row is proven
253
+ * against it and comes back as its output, and a row that does not fit is
254
+ * an `InvalidRowError`. The output of the validator must fit the row the
255
+ * builder infers, so a validator that disagrees with the query fails to
256
+ * compile. `first` runs the query and takes its first row, or `null`.
257
+ */
258
+ export interface Execute {
259
+ <O>(query: Compilable<O>): Promise<O[]>;
260
+ <O, R extends O>(query: Compilable<O>, row: Validator<R>): Promise<R[]>;
261
+ readonly first: {
262
+ <O>(query: Compilable<O>): Promise<O | null>;
263
+ <O, R extends O>(query: Compilable<O>, row: Validator<R>): Promise<R | null>;
264
+ };
265
+ }
223
266
  /**
224
267
  * The members of a service other than its queries. A query group cannot
225
268
  * take one of these names.
@@ -247,10 +290,27 @@ export interface Service<D extends Definition> {
247
290
  * group. Proves the row it returns and no other. Throws as `query` does.
248
291
  */
249
292
  first: <Q extends RowQuery<D>>(query: Q, ...args: Args<D, Q>) => Promise<Row<D, Q> | null>;
293
+ /**
294
+ * Runs a built query and returns its rows, proven against a validator
295
+ * when one is given. `execute.first` returns the first row or `null`. See
296
+ * {@link Execute}. Throws `QueryError` when the driver fails and
297
+ * `InvalidRowError` when a row does not fit the validator.
298
+ */
299
+ execute: Execute;
300
+ /**
301
+ * The query builder of the service: a [kysely](https://kysely.dev) over
302
+ * the executor of the container, typed by the {@link Database} of the
303
+ * contract. A query built here runs on the executor of the service when
304
+ * it executes. Its own `transaction` is refused: a transaction belongs
305
+ * to `transaction` of the service, and the service of a transaction has
306
+ * a builder of its own.
307
+ */
308
+ build: Kysely<Database<D>>;
250
309
  /**
251
310
  * 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.
311
+ * over the transaction, with the same queries, builder, and options. The
312
+ * transaction commits when the function returns and rolls back when it
313
+ * throws.
254
314
  */
255
315
  transaction: <T>(run: (tx: Bezoar<D>) => Promise<T>) => Promise<T>;
256
316
  /**
package/.dist/index.mjs CHANGED
@@ -1,14 +1,18 @@
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
13
  "seed"
11
14
  ];
15
+ const BUILT = "build";
12
16
  const TABLE = "bezoar_migrations";
13
17
  const LOCK = 6451064;
14
18
  const ACQUIRE = "SELECT pg_advisory_xact_lock($1)";
@@ -107,6 +111,40 @@ const reframe = (frame, run) => {
107
111
  throw error;
108
112
  }
109
113
  };
114
+ const unsupported = (what, instead) => /* @__PURE__ */ new Error(`@bezoar/core: ${what} is not supported by the service; ${instead}`);
115
+ const defineConnection = (executor) => ({
116
+ executeQuery: async (compiled) => {
117
+ const outcome = await executor().query(compiled.sql, compiled.parameters);
118
+ return {
119
+ rows: outcome.rows,
120
+ numAffectedRows: BigInt(outcome.count)
121
+ };
122
+ },
123
+ streamQuery: () => {
124
+ throw unsupported("streaming", "run the query and take its rows");
125
+ }
126
+ });
127
+ const defineDriver = (executor) => {
128
+ const connection = defineConnection(executor);
129
+ const refuse = async () => {
130
+ throw unsupported("a transaction of the builder", "run `db.transaction((tx) => ...)` and build the query on `tx`");
131
+ };
132
+ return {
133
+ init: async () => {},
134
+ acquireConnection: async () => connection,
135
+ releaseConnection: async () => {},
136
+ beginTransaction: refuse,
137
+ commitTransaction: refuse,
138
+ rollbackTransaction: refuse,
139
+ destroy: async () => {}
140
+ };
141
+ };
142
+ const defineDialect = (executor) => ({
143
+ createDriver: () => defineDriver(executor),
144
+ createQueryCompiler: () => new PostgresQueryCompiler(),
145
+ createAdapter: () => new PostgresAdapter(),
146
+ createIntrospector: (db) => new PostgresIntrospector(db)
147
+ });
110
148
  const descend = (level, segment, name) => {
111
149
  const next = level[segment] ?? {};
112
150
  if (!record(next)) throw new AmbiguousQueryError(name);
@@ -191,6 +229,7 @@ const defineService = (definition, schema, config, options) => {
191
229
  const outcome = await execute(query, bind(statement.slots, given));
192
230
  options.onQuery?.({
193
231
  query,
232
+ sql: config.queries[query],
194
233
  arguments: args,
195
234
  ms: performance.now() - started,
196
235
  count: outcome.count
@@ -210,6 +249,40 @@ const defineService = (definition, schema, config, options) => {
210
249
  prove(query, 0, row);
211
250
  return row;
212
251
  }
252
+ const builder = new Kysely({ dialect: defineDialect(() => config.executor) });
253
+ const built = async (query) => {
254
+ const compiled = query.compile();
255
+ const started = performance.now();
256
+ let result;
257
+ try {
258
+ result = await builder.executeQuery(compiled);
259
+ } catch (cause) {
260
+ throw new QueryError(BUILT, cause);
261
+ }
262
+ options.onQuery?.({
263
+ query: BUILT,
264
+ sql: compiled.sql,
265
+ arguments: compiled.parameters,
266
+ ms: performance.now() - started,
267
+ count: Number(result.numAffectedRows ?? result.rows.length)
268
+ });
269
+ return result;
270
+ };
271
+ const proveWith = (validator, index, row) => {
272
+ const result = validator.safeParse(row);
273
+ if (!result.success) throw new InvalidRowError(BUILT, index, result.error.issues);
274
+ return result.data;
275
+ };
276
+ async function executeAll(query, validator) {
277
+ const { rows } = await built(query);
278
+ return validator === void 0 ? rows : rows.map((row, index) => proveWith(validator, index, row));
279
+ }
280
+ async function executeFirst(query, validator) {
281
+ const { rows } = await built(query);
282
+ const row = rows[0];
283
+ if (row === void 0) return null;
284
+ return validator === void 0 ? row : proveWith(validator, 0, row);
285
+ }
213
286
  const transaction = (fn) => config.executor.transaction((executor) => fn(defineService(definition, schema, {
214
287
  ...config,
215
288
  executor
@@ -219,6 +292,8 @@ const defineService = (definition, schema, config, options) => {
219
292
  schema,
220
293
  query: run,
221
294
  first: take,
295
+ execute: Object.assign(executeAll, { first: executeFirst }),
296
+ build: builder,
222
297
  transaction,
223
298
  migrate: (migrations) => migrate(config.executor, migrations),
224
299
  seed: (seeds) => seed(config.executor, seeds)
@@ -234,4 +309,4 @@ const makeBezoar = (definition, config, options = {}) => {
234
309
  reframe((issues) => new InvalidBundleError(issues), () => schema.assert.bundle(config.queries));
235
310
  return defineService(definition, schema, config, options);
236
311
  };
237
- export { ACQUIRE, APPLIED, AmbiguousQueryError, CREATE, InvalidArgumentsError, InvalidBundleError, InvalidRowError, LOCK, MigrationDriftError, MigrationError, QueryError, RECORD, RESERVED, ReservedQueryError, SeedError, TABLE, makeBezoar, reframe };
312
+ export { ACQUIRE, APPLIED, AmbiguousQueryError, BUILT, CREATE, InvalidArgumentsError, InvalidBundleError, InvalidRowError, LOCK, MigrationDriftError, MigrationError, QueryError, RECORD, RESERVED, ReservedQueryError, SeedError, TABLE, makeBezoar, reframe };
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
 
@@ -129,16 +184,19 @@ tracked. Write a seed so that it can run again. A seed that fails is a
129
184
 
130
185
  ## Names
131
186
 
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`.
187
+ The members of the service are `config`, `schema`, `query`, `first`,
188
+ `execute`, `build`, `transaction`, `migrate`, and `seed`. A query group
189
+ cannot take one of these names,
190
+ and a name cannot be both a query and a group. Either is an error at
191
+ construction: `ReservedQueryError` or `AmbiguousQueryError`. `RESERVED`
192
+ exports the list.
136
193
 
137
194
  ## Errors
138
195
 
139
196
  - `InvalidBundleError`: the SQL bundle does not match the contract.
140
197
  - `InvalidArgumentsError`: the arguments of a call do not fit the slots.
141
- - `InvalidRowError`: a row does not fit the columns.
198
+ - `InvalidRowError`: a row does not fit the columns, or the validator of a
199
+ built query.
142
200
  - `QueryError`: the driver failed. `cause` is the driver's error.
143
201
  - `MigrationDriftError`: the database holds a migration the list does not
144
202
  match.
@@ -149,11 +207,14 @@ construction: `ReservedQueryError` or `AmbiguousQueryError`.
149
207
 
150
208
  ## Types
151
209
 
152
- - `Bezoar<D>` is the service: `Service<D>` and the `Groups<D>`.
210
+ - `Bezoar<D>` is the service: `Service<D>`, the `Builder<D>`, and the
211
+ `Groups<D>`.
153
212
  - `Config<D>` is the container. `Options<D>` has `onQuery`.
154
213
  - `Executor` and `Outcome` are what a driver provides.
155
214
  - `Method<D, Q>` is the function of one query. `Report<D>` is what `onQuery`
156
215
  receives.
216
+ - `Execute` is the signature of `execute`. `Validator<R>` is what it proves
217
+ a row with. `Delegated` is the name of a builder member.
157
218
  - `Migration` and `Seed` are what the kit builds for the runner.
158
219
 
159
220
  ## 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.4",
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.4"
27
+ },
28
+ "devDependencies": {
29
+ "zod": "^4.6.5"
26
30
  },
27
31
  "scripts": {
28
32
  "build": "obuild",