@funcd-dev/drizzle 0.0.0-stage → 0.20.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/README.md CHANGED
@@ -1,3 +1,31 @@
1
- # Temporary Holding Version
1
+ # @funcd-dev/drizzle
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Drizzle](https://orm.drizzle.team) over funcd's `context.sql` (funcd ADR-0258): one package instead of a copied adapter
4
+ in each App.
5
+
6
+ ```ts
7
+ import { applyMigrations, funcdDrizzle } from '@funcd-dev/drizzle';
8
+ import type { FunctionContext } from '@funcd-dev/shim';
9
+
10
+ import * as schema from './db/schema.ts';
11
+
12
+ export const db = (ctx: FunctionContext) => funcdDrizzle(ctx, { schema });
13
+
14
+ // the migrate function, or an App's preApply hook: the drizzle-kit folder the bundle carries
15
+ const migrations: Record<string, string> = import.meta.glob(['../../drizzle/*.sql', '../../drizzle/meta/_journal.json'], {
16
+ query: '?raw',
17
+ import: 'default',
18
+ eager: true,
19
+ });
20
+ export const handle = async (ctx: FunctionContext) => ({ applied: await applyMigrations(ctx, migrations) });
21
+ ```
22
+
23
+ - `funcdDrizzle(ctx, { alias = 'app', schema })` is Drizzle's `sqlite-proxy` database. A `SELECT` or `WITH` goes to
24
+ `context.sql.queryValues`, any other statement to `execute`, since Drizzle sends `insert … returning()` as a read.
25
+ A `batch` is one `execute`, all or nothing, and is for writes: a select inside it gets no rows. A `WITH` that writes
26
+ (`db.with(cte).insert(…)`) takes the read path too, so write without a `WITH`.
27
+ - `applyMigrations(ctx, files, { alias = 'app', table = '_migrations' })` applies the drizzle-kit migrations the table
28
+ lacks, with their rows, in one `execute`, and returns how many it applied. It reads them from `files`, a path to
29
+ content map, and keeps the table as Drizzle's own `sqlite-proxy` migrator keeps it, so either one can take over from
30
+ the other.
31
+ - `drizzle-orm` is a peer dependency: the App picks its version (`>=0.45.0 <1.0.0`).
@@ -0,0 +1,34 @@
1
+ import { type SqliteRemoteDatabase } from 'drizzle-orm/sqlite-proxy';
2
+ /** A SQL parameter, as context.sql takes it. */
3
+ export type SQLParam = string | number | boolean | null;
4
+ /** The part of a function's context the package uses, its context.sql; a FunctionContext is one. */
5
+ export interface SQLContext {
6
+ sql: {
7
+ queryValues(alias: string, sql: string, params?: SQLParam[]): Promise<{
8
+ values: unknown[][];
9
+ }>;
10
+ execute(alias: string, sql: string, params?: SQLParam[]): Promise<{
11
+ values?: unknown[][];
12
+ }>;
13
+ execute(alias: string, statements: [string, SQLParam[]][]): Promise<{
14
+ values?: unknown[][];
15
+ }[]>;
16
+ };
17
+ }
18
+ /**
19
+ * Drizzle's sqlite-proxy database over context.sql's alias (default app). A batch is one execute, all or nothing, and is
20
+ * for writes: a select inside it gets no rows, as execute returns rows only for RETURNING.
21
+ */
22
+ export declare function funcdDrizzle<TSchema extends Record<string, unknown> = Record<string, never>>(ctx: SQLContext, options?: {
23
+ alias?: string;
24
+ schema?: TSchema;
25
+ }): SqliteRemoteDatabase<TSchema>;
26
+ /**
27
+ * Applies the drizzle-kit migrations in files that the table (default _migrations) lacks, with their rows, in one
28
+ * execute, and returns how many it applied. files maps a path to its content, as import.meta.glob with ?raw returns
29
+ * it: the folder is the prefix of the key that ends in meta/_journal.json.
30
+ */
31
+ export declare function applyMigrations(ctx: SQLContext, files: Record<string, string>, options?: {
32
+ alias?: string;
33
+ table?: string;
34
+ }): Promise<number>;
package/dist/index.js ADDED
@@ -0,0 +1,66 @@
1
+ // @funcd-dev/drizzle (funcd ADR-0258): Drizzle over context.sql. funcdDrizzle is Drizzle's sqlite-proxy database with
2
+ // funcd ADR-0233's routing; applyMigrations applies drizzle-kit's migrations from memory as Drizzle's sqlite-proxy
3
+ // migrator applies them from disk, with the same table, hashes and order, in one execute (funcd ADR-0236 Decision 5).
4
+ import { createHash } from 'node:crypto';
5
+ import { drizzle } from 'drizzle-orm/sqlite-proxy';
6
+ // Drizzle sends insert … returning() as a read method, so the statement picks the call, not the method.
7
+ const reads = /^\s*(select|with)\b/i;
8
+ async function rows(ctx, alias, query, params, method) {
9
+ const p = params;
10
+ const values = reads.test(query)
11
+ ? (await ctx.sql.queryValues(alias, query, p)).values
12
+ : ((await ctx.sql.execute(alias, query, p)).values ?? []);
13
+ return method === 'get' ? (values[0] ?? []) : values;
14
+ }
15
+ /**
16
+ * Drizzle's sqlite-proxy database over context.sql's alias (default app). A batch is one execute, all or nothing, and is
17
+ * for writes: a select inside it gets no rows, as execute returns rows only for RETURNING.
18
+ */
19
+ export function funcdDrizzle(ctx, options = {}) {
20
+ const alias = options.alias ?? 'app';
21
+ return drizzle(async (query, params, method) => ({ rows: await rows(ctx, alias, query, params, method) }), async (queries) => {
22
+ const results = await ctx.sql.execute(alias, queries.map((q) => [q.sql, q.params]));
23
+ return results.map((r, i) => ({
24
+ rows: queries[i].method === 'get' ? (r.values?.[0] ?? []) : (r.values ?? []),
25
+ }));
26
+ }, { schema: options.schema });
27
+ }
28
+ const journalPath = 'meta/_journal.json';
29
+ /**
30
+ * Applies the drizzle-kit migrations in files that the table (default _migrations) lacks, with their rows, in one
31
+ * execute, and returns how many it applied. files maps a path to its content, as import.meta.glob with ?raw returns
32
+ * it: the folder is the prefix of the key that ends in meta/_journal.json.
33
+ */
34
+ export async function applyMigrations(ctx, files, options = {}) {
35
+ const alias = options.alias ?? 'app';
36
+ const table = options.table ?? '_migrations';
37
+ const journals = Object.keys(files).filter((k) => k === journalPath || k.endsWith(`/${journalPath}`));
38
+ if (journals.length !== 1) {
39
+ throw new Error(`applyMigrations: the files hold ${journals.length === 0 ? `no ${journalPath}` : `two journals: ${journals.join(', ')}`}`);
40
+ }
41
+ const [key] = journals;
42
+ const folder = key.slice(0, -journalPath.length);
43
+ const migrations = JSON.parse(files[key]).entries.map((e) => {
44
+ const path = `${folder}${e.tag}.sql`;
45
+ const text = files[path];
46
+ if (text === undefined)
47
+ throw new Error(`applyMigrations: the files hold no ${path}, which ${key} names`);
48
+ return {
49
+ statements: text.split('--> statement-breakpoint'),
50
+ when: e.when,
51
+ hash: createHash('sha256').update(text).digest('hex'),
52
+ };
53
+ });
54
+ // drizzle-orm 0.45.3's sqlite-proxy migrator creates, reads and writes the table with these statements, so a
55
+ // database it migrated reads as migrated here, and the other way round.
56
+ await ctx.sql.execute(alias, `CREATE TABLE IF NOT EXISTS "${table}" (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at numeric)`);
57
+ const [last] = (await ctx.sql.queryValues(alias, `SELECT id, hash, created_at FROM "${table}" ORDER BY created_at DESC LIMIT 1`)).values;
58
+ const pending = migrations.filter((m) => last === undefined || Number(last[2]) < m.when);
59
+ if (pending.length === 0)
60
+ return 0;
61
+ await ctx.sql.execute(alias, pending.flatMap((m) => [
62
+ ...m.statements.map((s) => [s, []]),
63
+ [`INSERT INTO \`${table}\` ("hash", "created_at") VALUES('${m.hash}', '${m.when}')`, []],
64
+ ]));
65
+ return pending.length;
66
+ }
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@funcd-dev/drizzle",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.20.0",
4
+ "type": "module",
5
+ "description": "Drizzle over funcd's context.sql: the sqlite-proxy database and drizzle-kit migrations applied in one execute",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/pyvvo/funcd-typescript.git",
10
+ "directory": "drizzle"
11
+ },
12
+ "homepage": "https://github.com/pyvvo/funcd-typescript/tree/main/drizzle#readme",
13
+ "engines": {
14
+ "node": ">=22"
15
+ },
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "source": "./src/index.ts",
20
+ "default": "./dist/index.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "typecheck": "tsc --noEmit",
31
+ "test": "node --test --experimental-strip-types --experimental-sqlite --no-warnings test/*.test.ts",
32
+ "build": "tsc -p tsconfig.lib.json"
33
+ },
34
+ "peerDependencies": {
35
+ "drizzle-orm": ">=0.45.0 <1.0.0"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^22.10.0",
39
+ "drizzle-orm": "0.45.3",
40
+ "typescript": "^5.7.0"
41
+ }
6
42
  }