@lunora/hyperdrive 0.0.0 → 1.0.0-alpha.1

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.
@@ -0,0 +1,69 @@
1
+ import { DatabaseWriterLike } from '@lunora/do';
2
+ import { SqlExec, SqlDialect, SqlCtxDbOptions } from '@lunora/sql-store';
3
+ /** Minimal row-returning client (e.g. `@lunora/hyperdrive`'s `fromPostgresJs`/`fromNodePg` result). */
4
+ interface RowClient {
5
+ query: <Row = Record<string, unknown>>(text: string, params?: ReadonlyArray<unknown>) => Promise<Row[]>;
6
+ }
7
+ /** Minimal `mysql2/promise` connection/pool surface — `execute` resolves to `[rows | ResultSetHeader, fields]`. */
8
+ interface Mysql2Execute {
9
+ execute: (text: string, params?: ReadonlyArray<unknown>) => Promise<[unknown, unknown]>;
10
+ }
11
+ /**
12
+ * Wrap a Postgres row-client (from `@lunora/hyperdrive`'s `fromPostgresJs` /
13
+ * `fromNodePg`) as a {@link SqlExec}. The core already renders `$N` placeholders
14
+ * for Postgres, so `all`/`run` forward verbatim. Postgres uses `RETURNING` for
15
+ * OCC (read via `all`), so `run` reports no affected-row count.
16
+ */
17
+ declare const buildPgExec: (client: RowClient) => SqlExec;
18
+ /**
19
+ * Wrap a `mysql2/promise` connection/pool as a {@link SqlExec}. The core already
20
+ * renders backtick identifiers and `?` placeholders for MySQL, so `all`/`run`
21
+ * forward verbatim. MySQL has no `RETURNING`, so `run` surfaces `affectedRows`
22
+ * for the store's affected-rows OCC guard.
23
+ *
24
+ * **The connection MUST be created with the `CLIENT_FOUND_ROWS` flag**
25
+ * (mysql2: `createPool({ flags: ["FOUND_ROWS"] })`). Without it, `affectedRows`
26
+ * counts *changed* rows, so an idempotent `patch`/`replace` that re-writes the
27
+ * same values reports 0 and the OCC guard raises a spurious conflict.
28
+ */
29
+ declare const buildMysqlExec: (connection: Mysql2Execute) => SqlExec;
30
+ /**
31
+ * **Postgres** dialect. Differs from SQLite only in column types
32
+ * (`DOUBLE PRECISION`/`BYTEA`/`BIGSERIAL`), the `information_schema` catalog
33
+ * probe, and unique-violation detection (SQLSTATE `23505`).
34
+ */
35
+ declare const postgresDialect: SqlDialect;
36
+ /**
37
+ * **MySQL** dialect. Diverges in: **no `RETURNING`** (the store's OCC falls back
38
+ * to affected-rows — which requires the connection's `CLIENT_FOUND_ROWS` flag so
39
+ * a no-op update still reports a matched row, see `buildMysqlExec`); bounded
40
+ * `VARCHAR` keys (TEXT can't be a primary key / unindexed); a TEXT/BLOB index key
41
+ * prefix; and `ER_DUP_ENTRY` (errno 1062) unique violations. (Drizzle's MySQL
42
+ * dialect supplies the backtick identifiers + `ON DUPLICATE KEY` upserts.)
43
+ */
44
+ declare const mysqlDialect: SqlDialect;
45
+ /** Which engine a Hyperdrive-backed `.global()` store targets. */
46
+ type HyperdriveEngine = "mysql" | "postgres";
47
+ /** Options for {@link createHyperdriveGlobalCtxDb}: the store options minus `exec`/`dialect`, plus the engine and a built `SqlExec`. */
48
+ interface CreateHyperdriveGlobalCtxDbOptions extends Omit<SqlCtxDbOptions, "dialect" | "exec"> {
49
+ /** The engine, selecting the Postgres or MySQL dialect. */
50
+ engine: HyperdriveEngine;
51
+ /** A Hyperdrive-backed exec, e.g. from {@link buildPgExec}/{@link buildMysqlExec}. */
52
+ exec: SqlExec;
53
+ }
54
+ /**
55
+ * Build a reactive `.global()` writer backed by a Hyperdrive-reachable
56
+ * Postgres/MySQL database. Pass a built {@link SqlExec} (via {@link buildPgExec}/
57
+ * {@link buildMysqlExec}) and the matching `engine`; everything else mirrors the
58
+ * D1 store options.
59
+ */
60
+ declare const createHyperdriveGlobalCtxDb: ({
61
+ engine,
62
+ exec,
63
+ ...rest
64
+ }: CreateHyperdriveGlobalCtxDbOptions) => DatabaseWriterLike;
65
+ /** Convenience: a **Postgres** `.global()` writer from a row-client (postgres.js/pg over Hyperdrive). */
66
+ declare const createPostgresGlobalCtxDb: (client: RowClient, options: Omit<CreateHyperdriveGlobalCtxDbOptions, "engine" | "exec">) => DatabaseWriterLike;
67
+ /** Convenience: a **MySQL** `.global()` writer from a `mysql2/promise` connection/pool (created with `flags: ["FOUND_ROWS"]`). */
68
+ declare const createMysqlGlobalCtxDb: (connection: Mysql2Execute, options: Omit<CreateHyperdriveGlobalCtxDbOptions, "engine" | "exec">) => DatabaseWriterLike;
69
+ export { CreateHyperdriveGlobalCtxDbOptions, HyperdriveEngine, type Mysql2Execute, type RowClient, buildMysqlExec, buildPgExec, createHyperdriveGlobalCtxDb, createMysqlGlobalCtxDb, createPostgresGlobalCtxDb, mysqlDialect, postgresDialect };
@@ -0,0 +1,69 @@
1
+ import { DatabaseWriterLike } from '@lunora/do';
2
+ import { SqlExec, SqlDialect, SqlCtxDbOptions } from '@lunora/sql-store';
3
+ /** Minimal row-returning client (e.g. `@lunora/hyperdrive`'s `fromPostgresJs`/`fromNodePg` result). */
4
+ interface RowClient {
5
+ query: <Row = Record<string, unknown>>(text: string, params?: ReadonlyArray<unknown>) => Promise<Row[]>;
6
+ }
7
+ /** Minimal `mysql2/promise` connection/pool surface — `execute` resolves to `[rows | ResultSetHeader, fields]`. */
8
+ interface Mysql2Execute {
9
+ execute: (text: string, params?: ReadonlyArray<unknown>) => Promise<[unknown, unknown]>;
10
+ }
11
+ /**
12
+ * Wrap a Postgres row-client (from `@lunora/hyperdrive`'s `fromPostgresJs` /
13
+ * `fromNodePg`) as a {@link SqlExec}. The core already renders `$N` placeholders
14
+ * for Postgres, so `all`/`run` forward verbatim. Postgres uses `RETURNING` for
15
+ * OCC (read via `all`), so `run` reports no affected-row count.
16
+ */
17
+ declare const buildPgExec: (client: RowClient) => SqlExec;
18
+ /**
19
+ * Wrap a `mysql2/promise` connection/pool as a {@link SqlExec}. The core already
20
+ * renders backtick identifiers and `?` placeholders for MySQL, so `all`/`run`
21
+ * forward verbatim. MySQL has no `RETURNING`, so `run` surfaces `affectedRows`
22
+ * for the store's affected-rows OCC guard.
23
+ *
24
+ * **The connection MUST be created with the `CLIENT_FOUND_ROWS` flag**
25
+ * (mysql2: `createPool({ flags: ["FOUND_ROWS"] })`). Without it, `affectedRows`
26
+ * counts *changed* rows, so an idempotent `patch`/`replace` that re-writes the
27
+ * same values reports 0 and the OCC guard raises a spurious conflict.
28
+ */
29
+ declare const buildMysqlExec: (connection: Mysql2Execute) => SqlExec;
30
+ /**
31
+ * **Postgres** dialect. Differs from SQLite only in column types
32
+ * (`DOUBLE PRECISION`/`BYTEA`/`BIGSERIAL`), the `information_schema` catalog
33
+ * probe, and unique-violation detection (SQLSTATE `23505`).
34
+ */
35
+ declare const postgresDialect: SqlDialect;
36
+ /**
37
+ * **MySQL** dialect. Diverges in: **no `RETURNING`** (the store's OCC falls back
38
+ * to affected-rows — which requires the connection's `CLIENT_FOUND_ROWS` flag so
39
+ * a no-op update still reports a matched row, see `buildMysqlExec`); bounded
40
+ * `VARCHAR` keys (TEXT can't be a primary key / unindexed); a TEXT/BLOB index key
41
+ * prefix; and `ER_DUP_ENTRY` (errno 1062) unique violations. (Drizzle's MySQL
42
+ * dialect supplies the backtick identifiers + `ON DUPLICATE KEY` upserts.)
43
+ */
44
+ declare const mysqlDialect: SqlDialect;
45
+ /** Which engine a Hyperdrive-backed `.global()` store targets. */
46
+ type HyperdriveEngine = "mysql" | "postgres";
47
+ /** Options for {@link createHyperdriveGlobalCtxDb}: the store options minus `exec`/`dialect`, plus the engine and a built `SqlExec`. */
48
+ interface CreateHyperdriveGlobalCtxDbOptions extends Omit<SqlCtxDbOptions, "dialect" | "exec"> {
49
+ /** The engine, selecting the Postgres or MySQL dialect. */
50
+ engine: HyperdriveEngine;
51
+ /** A Hyperdrive-backed exec, e.g. from {@link buildPgExec}/{@link buildMysqlExec}. */
52
+ exec: SqlExec;
53
+ }
54
+ /**
55
+ * Build a reactive `.global()` writer backed by a Hyperdrive-reachable
56
+ * Postgres/MySQL database. Pass a built {@link SqlExec} (via {@link buildPgExec}/
57
+ * {@link buildMysqlExec}) and the matching `engine`; everything else mirrors the
58
+ * D1 store options.
59
+ */
60
+ declare const createHyperdriveGlobalCtxDb: ({
61
+ engine,
62
+ exec,
63
+ ...rest
64
+ }: CreateHyperdriveGlobalCtxDbOptions) => DatabaseWriterLike;
65
+ /** Convenience: a **Postgres** `.global()` writer from a row-client (postgres.js/pg over Hyperdrive). */
66
+ declare const createPostgresGlobalCtxDb: (client: RowClient, options: Omit<CreateHyperdriveGlobalCtxDbOptions, "engine" | "exec">) => DatabaseWriterLike;
67
+ /** Convenience: a **MySQL** `.global()` writer from a `mysql2/promise` connection/pool (created with `flags: ["FOUND_ROWS"]`). */
68
+ declare const createMysqlGlobalCtxDb: (connection: Mysql2Execute, options: Omit<CreateHyperdriveGlobalCtxDbOptions, "engine" | "exec">) => DatabaseWriterLike;
69
+ export { CreateHyperdriveGlobalCtxDbOptions, HyperdriveEngine, type Mysql2Execute, type RowClient, buildMysqlExec, buildPgExec, createHyperdriveGlobalCtxDb, createMysqlGlobalCtxDb, createPostgresGlobalCtxDb, mysqlDialect, postgresDialect };
@@ -0,0 +1,9 @@
1
+ import { createSqlCtxDb } from '@lunora/sql-store';
2
+ import { postgresDialect, mysqlDialect } from './packem_shared/postgresDialect-oNhZ58s8.mjs';
3
+ import { buildMysqlExec, buildPgExec } from './packem_shared/buildPgExec-DBbCjyq3.mjs';
4
+
5
+ const createHyperdriveGlobalCtxDb = ({ engine, exec, ...rest }) => createSqlCtxDb({ ...rest, dialect: engine === "postgres" ? postgresDialect : mysqlDialect, exec });
6
+ const createPostgresGlobalCtxDb = (client, options) => createHyperdriveGlobalCtxDb({ ...options, engine: "postgres", exec: buildPgExec(client) });
7
+ const createMysqlGlobalCtxDb = (connection, options) => createHyperdriveGlobalCtxDb({ ...options, engine: "mysql", exec: buildMysqlExec(connection) });
8
+
9
+ export { buildMysqlExec, buildPgExec, createHyperdriveGlobalCtxDb, createMysqlGlobalCtxDb, createPostgresGlobalCtxDb, mysqlDialect, postgresDialect };
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Public types for `@lunora/hyperdrive`.
3
+ *
4
+ * Hyperdrive points at a database **Lunora does not own**. Everything here is
5
+ * deliberately structural (no hard dependency on `@cloudflare/workers-types` or
6
+ * any SQL driver) so unit tests can pass plain-object doubles, exactly like the
7
+ * `D1DatabaseLike` projection in `@lunora/d1`.
8
+ *
9
+ * The hard constraint, restated wherever this surface is used: Hyperdrive
10
+ * queries are **non-deterministic** (forbidden in `query`/`mutation`, allowed
11
+ * only in `action`s — see the `hyperdrive_outside_action` advisor lint), and
12
+ * external writes are **invisible to Lunora live queries** — a subscription will
13
+ * NOT re-run when an external Postgres/MySQL row changes.
14
+ */
15
+ /**
16
+ * Structural projection of the Cloudflare `Hyperdrive` binding (`env.HYPERDRIVE`).
17
+ *
18
+ * Mirrors the fields of the real `Hyperdrive` from `@cloudflare/workers-types`
19
+ * but stays structural so a unit test can pass a plain object. At runtime only
20
+ * `connectionString` is needed to construct a driver; the discrete connection
21
+ * parts are surfaced for drivers that prefer a config object over a DSN.
22
+ */
23
+ interface HyperdriveLike {
24
+ /** A connection string Hyperdrive routes through its pooled, cached edge connection. */
25
+ connectionString: string;
26
+ /** Database name component of the connection. */
27
+ database: string;
28
+ /** Host Hyperdrive presents to the driver (the local proxy, not your origin DB). */
29
+ host: string;
30
+ /** Password component of the connection. */
31
+ password: string;
32
+ /** Port Hyperdrive presents to the driver. */
33
+ port: number;
34
+ /** User component of the connection. */
35
+ user: string;
36
+ }
37
+ /**
38
+ * The connection config surfaced by {@link import("./create-hyperdrive").createHyperdrive | createHyperdrive}: the raw
39
+ * `connectionString` plus the discrete parts, ready to hand to a driver.
40
+ */
41
+ interface HyperdriveConnection {
42
+ /** Database name. */
43
+ database: string;
44
+ /** Host (Hyperdrive's local proxy). */
45
+ host: string;
46
+ /** Password. */
47
+ password: string;
48
+ /** Port. */
49
+ port: number;
50
+ /** User. */
51
+ user: string;
52
+ }
53
+ /**
54
+ * The driver-agnostic SQL surface bound to `ctx.sql` on **`ActionCtx` only**.
55
+ *
56
+ * This is the exact type the generated ctx imports as
57
+ * `import("@lunora/hyperdrive").SqlClient`. Keep the name and shape stable — the
58
+ * codegen ctx wiring (Phase 1) depends on it.
59
+ *
60
+ * It is intentionally minimal — a single parameterised `query` — so it maps onto
61
+ * `postgres` (postgres.js), `pg` (node-postgres) and `mysql2` alike via the
62
+ * {@link import("./create-hyperdrive").fromPostgresJs | fromPostgresJs} /
63
+ * {@link import("./create-hyperdrive").fromNodePg | fromNodePg} /
64
+ * {@link import("./create-hyperdrive").fromMysql2 | fromMysql2} adapters. Use
65
+ * positional placeholders that match your driver (`$1, $2` for Postgres, `?` for
66
+ * MySQL); the package does not rewrite SQL.
67
+ *
68
+ * Reminder (also on the emitted JSDoc): non-deterministic, action-only,
69
+ * non-reactive — writes here are not tracked by Lunora live queries.
70
+ */
71
+ interface SqlClient {
72
+ /**
73
+ * Run a parameterised SQL statement and return the result rows.
74
+ * @param text SQL text with driver-native positional placeholders.
75
+ * @param params Bound parameter values, positionally matched to `text`.
76
+ * @returns The rows the statement produced (empty for non-`SELECT`s that
77
+ * return no rows).
78
+ */
79
+ query: <Row = Record<string, unknown>>(text: string, params?: ReadonlyArray<unknown>) => Promise<Row[]>;
80
+ }
81
+ /**
82
+ * Structural projection of a `pg` (node-postgres) `Client`/`Pool`. Only the
83
+ * `query` method `fromNodePg` calls is required, kept structural for testing.
84
+ */
85
+ interface NodePgLike {
86
+ query: (text: string, params?: ReadonlyArray<unknown>) => Promise<{
87
+ rows: unknown[];
88
+ }>;
89
+ }
90
+ /**
91
+ * Structural projection of a `postgres` (postgres.js) tagged-template client.
92
+ * The adapter uses the `.unsafe(text, params)` escape hatch so callers keep
93
+ * full control of the parameter list.
94
+ */
95
+ interface PostgresJsLike {
96
+ unsafe: (text: string, params?: ReadonlyArray<unknown>) => Promise<unknown>;
97
+ }
98
+ /**
99
+ * Structural projection of a `mysql2/promise` connection/pool. `mysql2`'s
100
+ * `execute` resolves to a `[rows, fields]` tuple; the adapter takes the first
101
+ * element as the rows.
102
+ */
103
+ interface Mysql2Like {
104
+ execute: (text: string, params?: ReadonlyArray<unknown>) => Promise<[unknown, unknown]>;
105
+ }
106
+ /**
107
+ * Surface a Cloudflare Hyperdrive binding as a connection ready to feed a
108
+ * user-supplied SQL driver.
109
+ *
110
+ * `@lunora/hyperdrive` deliberately **bundles no driver** — `postgres`, `pg` and
111
+ * `mysql2` are heavy and the choice is the user's (they are `optional`
112
+ * `peerDependencies`, never `dependencies`). This factory's only job is to lift
113
+ * the binding's connection details out; the user constructs their own driver
114
+ * from `connectionString` and wraps it with one of the {@link fromPostgresJs} /
115
+ * {@link fromNodePg} / {@link fromMysql2} adapters to get a {@link SqlClient}.
116
+ * @example
117
+ * ```ts
118
+ * import { createHyperdrive, fromPostgresJs } from "@lunora/hyperdrive";
119
+ * import postgres from "postgres";
120
+ *
121
+ * // inside an action (never a query/mutation):
122
+ * const { connectionString } = createHyperdrive(env.HYPERDRIVE);
123
+ * ctx.sql = fromPostgresJs(postgres(connectionString));
124
+ * const rows = await ctx.sql.query("select id from users where org = $1", [orgId]);
125
+ * ```
126
+ * @remarks
127
+ * Hyperdrive talks to an **external** database Lunora has no visibility into.
128
+ * Queries through `ctx.sql` are non-deterministic (action-only — enforced by the
129
+ * `hyperdrive_outside_action` advisor lint) and external writes are NOT tracked
130
+ * by Lunora live queries: subscriptions will not re-run when external rows
131
+ * change. Use Hyperdrive to *integrate* an existing DB from an action; if you
132
+ * want that data to be reactive, write a projection of it into a `defineSchema`
133
+ * DO/D1 table.
134
+ * @param binding The `env.HYPERDRIVE` binding (or a structural double).
135
+ * @returns The raw `connectionString` plus the discrete connection parts.
136
+ */
137
+ declare const createHyperdrive: (binding: HyperdriveLike) => {
138
+ config: HyperdriveConnection;
139
+ connectionString: string;
140
+ };
141
+ /**
142
+ * Wrap a `postgres` (postgres.js) client as a {@link SqlClient}.
143
+ *
144
+ * Uses the driver's `.unsafe(text, params)` escape hatch so the caller supplies
145
+ * a plain SQL string with `$1, $2, …` placeholders and a positional params
146
+ * array. postgres.js's `.unsafe` resolves to a row array.
147
+ */
148
+ declare const fromPostgresJs: (client: PostgresJsLike) => SqlClient;
149
+ /**
150
+ * Wrap a `pg` (node-postgres) `Client` or `Pool` as a {@link SqlClient}.
151
+ *
152
+ * node-postgres returns a result object whose `rows` field holds the row array.
153
+ */
154
+ declare const fromNodePg: (client: NodePgLike) => SqlClient;
155
+ /**
156
+ * Wrap a `mysql2/promise` connection or pool as a {@link SqlClient}.
157
+ *
158
+ * Use `?` placeholders (MySQL positional syntax). `mysql2`'s `execute` resolves
159
+ * to a `[rows, fields]` tuple; the adapter returns the first element. For a
160
+ * non-`SELECT` (DML), `mysql2` yields a `ResultSetHeader` object rather than a
161
+ * row array, so the adapter normalises that to `[]` — matching the empty-array
162
+ * contract the postgres.js / node-postgres adapters already honour.
163
+ */
164
+ declare const fromMysql2: (connection: Mysql2Like) => SqlClient;
165
+ export { type HyperdriveConnection, type HyperdriveLike, type Mysql2Like, type NodePgLike, type PostgresJsLike, type SqlClient, createHyperdrive, fromMysql2, fromNodePg, fromPostgresJs };
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Public types for `@lunora/hyperdrive`.
3
+ *
4
+ * Hyperdrive points at a database **Lunora does not own**. Everything here is
5
+ * deliberately structural (no hard dependency on `@cloudflare/workers-types` or
6
+ * any SQL driver) so unit tests can pass plain-object doubles, exactly like the
7
+ * `D1DatabaseLike` projection in `@lunora/d1`.
8
+ *
9
+ * The hard constraint, restated wherever this surface is used: Hyperdrive
10
+ * queries are **non-deterministic** (forbidden in `query`/`mutation`, allowed
11
+ * only in `action`s — see the `hyperdrive_outside_action` advisor lint), and
12
+ * external writes are **invisible to Lunora live queries** — a subscription will
13
+ * NOT re-run when an external Postgres/MySQL row changes.
14
+ */
15
+ /**
16
+ * Structural projection of the Cloudflare `Hyperdrive` binding (`env.HYPERDRIVE`).
17
+ *
18
+ * Mirrors the fields of the real `Hyperdrive` from `@cloudflare/workers-types`
19
+ * but stays structural so a unit test can pass a plain object. At runtime only
20
+ * `connectionString` is needed to construct a driver; the discrete connection
21
+ * parts are surfaced for drivers that prefer a config object over a DSN.
22
+ */
23
+ interface HyperdriveLike {
24
+ /** A connection string Hyperdrive routes through its pooled, cached edge connection. */
25
+ connectionString: string;
26
+ /** Database name component of the connection. */
27
+ database: string;
28
+ /** Host Hyperdrive presents to the driver (the local proxy, not your origin DB). */
29
+ host: string;
30
+ /** Password component of the connection. */
31
+ password: string;
32
+ /** Port Hyperdrive presents to the driver. */
33
+ port: number;
34
+ /** User component of the connection. */
35
+ user: string;
36
+ }
37
+ /**
38
+ * The connection config surfaced by {@link import("./create-hyperdrive").createHyperdrive | createHyperdrive}: the raw
39
+ * `connectionString` plus the discrete parts, ready to hand to a driver.
40
+ */
41
+ interface HyperdriveConnection {
42
+ /** Database name. */
43
+ database: string;
44
+ /** Host (Hyperdrive's local proxy). */
45
+ host: string;
46
+ /** Password. */
47
+ password: string;
48
+ /** Port. */
49
+ port: number;
50
+ /** User. */
51
+ user: string;
52
+ }
53
+ /**
54
+ * The driver-agnostic SQL surface bound to `ctx.sql` on **`ActionCtx` only**.
55
+ *
56
+ * This is the exact type the generated ctx imports as
57
+ * `import("@lunora/hyperdrive").SqlClient`. Keep the name and shape stable — the
58
+ * codegen ctx wiring (Phase 1) depends on it.
59
+ *
60
+ * It is intentionally minimal — a single parameterised `query` — so it maps onto
61
+ * `postgres` (postgres.js), `pg` (node-postgres) and `mysql2` alike via the
62
+ * {@link import("./create-hyperdrive").fromPostgresJs | fromPostgresJs} /
63
+ * {@link import("./create-hyperdrive").fromNodePg | fromNodePg} /
64
+ * {@link import("./create-hyperdrive").fromMysql2 | fromMysql2} adapters. Use
65
+ * positional placeholders that match your driver (`$1, $2` for Postgres, `?` for
66
+ * MySQL); the package does not rewrite SQL.
67
+ *
68
+ * Reminder (also on the emitted JSDoc): non-deterministic, action-only,
69
+ * non-reactive — writes here are not tracked by Lunora live queries.
70
+ */
71
+ interface SqlClient {
72
+ /**
73
+ * Run a parameterised SQL statement and return the result rows.
74
+ * @param text SQL text with driver-native positional placeholders.
75
+ * @param params Bound parameter values, positionally matched to `text`.
76
+ * @returns The rows the statement produced (empty for non-`SELECT`s that
77
+ * return no rows).
78
+ */
79
+ query: <Row = Record<string, unknown>>(text: string, params?: ReadonlyArray<unknown>) => Promise<Row[]>;
80
+ }
81
+ /**
82
+ * Structural projection of a `pg` (node-postgres) `Client`/`Pool`. Only the
83
+ * `query` method `fromNodePg` calls is required, kept structural for testing.
84
+ */
85
+ interface NodePgLike {
86
+ query: (text: string, params?: ReadonlyArray<unknown>) => Promise<{
87
+ rows: unknown[];
88
+ }>;
89
+ }
90
+ /**
91
+ * Structural projection of a `postgres` (postgres.js) tagged-template client.
92
+ * The adapter uses the `.unsafe(text, params)` escape hatch so callers keep
93
+ * full control of the parameter list.
94
+ */
95
+ interface PostgresJsLike {
96
+ unsafe: (text: string, params?: ReadonlyArray<unknown>) => Promise<unknown>;
97
+ }
98
+ /**
99
+ * Structural projection of a `mysql2/promise` connection/pool. `mysql2`'s
100
+ * `execute` resolves to a `[rows, fields]` tuple; the adapter takes the first
101
+ * element as the rows.
102
+ */
103
+ interface Mysql2Like {
104
+ execute: (text: string, params?: ReadonlyArray<unknown>) => Promise<[unknown, unknown]>;
105
+ }
106
+ /**
107
+ * Surface a Cloudflare Hyperdrive binding as a connection ready to feed a
108
+ * user-supplied SQL driver.
109
+ *
110
+ * `@lunora/hyperdrive` deliberately **bundles no driver** — `postgres`, `pg` and
111
+ * `mysql2` are heavy and the choice is the user's (they are `optional`
112
+ * `peerDependencies`, never `dependencies`). This factory's only job is to lift
113
+ * the binding's connection details out; the user constructs their own driver
114
+ * from `connectionString` and wraps it with one of the {@link fromPostgresJs} /
115
+ * {@link fromNodePg} / {@link fromMysql2} adapters to get a {@link SqlClient}.
116
+ * @example
117
+ * ```ts
118
+ * import { createHyperdrive, fromPostgresJs } from "@lunora/hyperdrive";
119
+ * import postgres from "postgres";
120
+ *
121
+ * // inside an action (never a query/mutation):
122
+ * const { connectionString } = createHyperdrive(env.HYPERDRIVE);
123
+ * ctx.sql = fromPostgresJs(postgres(connectionString));
124
+ * const rows = await ctx.sql.query("select id from users where org = $1", [orgId]);
125
+ * ```
126
+ * @remarks
127
+ * Hyperdrive talks to an **external** database Lunora has no visibility into.
128
+ * Queries through `ctx.sql` are non-deterministic (action-only — enforced by the
129
+ * `hyperdrive_outside_action` advisor lint) and external writes are NOT tracked
130
+ * by Lunora live queries: subscriptions will not re-run when external rows
131
+ * change. Use Hyperdrive to *integrate* an existing DB from an action; if you
132
+ * want that data to be reactive, write a projection of it into a `defineSchema`
133
+ * DO/D1 table.
134
+ * @param binding The `env.HYPERDRIVE` binding (or a structural double).
135
+ * @returns The raw `connectionString` plus the discrete connection parts.
136
+ */
137
+ declare const createHyperdrive: (binding: HyperdriveLike) => {
138
+ config: HyperdriveConnection;
139
+ connectionString: string;
140
+ };
141
+ /**
142
+ * Wrap a `postgres` (postgres.js) client as a {@link SqlClient}.
143
+ *
144
+ * Uses the driver's `.unsafe(text, params)` escape hatch so the caller supplies
145
+ * a plain SQL string with `$1, $2, …` placeholders and a positional params
146
+ * array. postgres.js's `.unsafe` resolves to a row array.
147
+ */
148
+ declare const fromPostgresJs: (client: PostgresJsLike) => SqlClient;
149
+ /**
150
+ * Wrap a `pg` (node-postgres) `Client` or `Pool` as a {@link SqlClient}.
151
+ *
152
+ * node-postgres returns a result object whose `rows` field holds the row array.
153
+ */
154
+ declare const fromNodePg: (client: NodePgLike) => SqlClient;
155
+ /**
156
+ * Wrap a `mysql2/promise` connection or pool as a {@link SqlClient}.
157
+ *
158
+ * Use `?` placeholders (MySQL positional syntax). `mysql2`'s `execute` resolves
159
+ * to a `[rows, fields]` tuple; the adapter returns the first element. For a
160
+ * non-`SELECT` (DML), `mysql2` yields a `ResultSetHeader` object rather than a
161
+ * row array, so the adapter normalises that to `[]` — matching the empty-array
162
+ * contract the postgres.js / node-postgres adapters already honour.
163
+ */
164
+ declare const fromMysql2: (connection: Mysql2Like) => SqlClient;
165
+ export { type HyperdriveConnection, type HyperdriveLike, type Mysql2Like, type NodePgLike, type PostgresJsLike, type SqlClient, createHyperdrive, fromMysql2, fromNodePg, fromPostgresJs };
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ export { createHyperdrive, fromMysql2, fromNodePg, fromPostgresJs } from './packem_shared/createHyperdrive-DD8GoDZo.mjs';
@@ -0,0 +1,23 @@
1
+ const buildPgExec = (client) => {
2
+ return {
3
+ all: (sql, params) => client.query(sql, params),
4
+ run: async (sql, params) => {
5
+ await client.query(sql, params);
6
+ return { rowsAffected: 0 };
7
+ }
8
+ };
9
+ };
10
+ const buildMysqlExec = (connection) => {
11
+ return {
12
+ all: async (sql, params) => {
13
+ const [rows] = await connection.execute(sql, params);
14
+ return rows;
15
+ },
16
+ run: async (sql, params) => {
17
+ const [result] = await connection.execute(sql, params);
18
+ return { rowsAffected: result.affectedRows ?? 0 };
19
+ }
20
+ };
21
+ };
22
+
23
+ export { buildMysqlExec, buildPgExec };
@@ -0,0 +1,36 @@
1
+ const createHyperdrive = (binding) => {
2
+ const config = {
3
+ database: binding.database,
4
+ host: binding.host,
5
+ password: binding.password,
6
+ port: binding.port,
7
+ user: binding.user
8
+ };
9
+ return { config, connectionString: binding.connectionString };
10
+ };
11
+ const fromPostgresJs = (client) => {
12
+ return {
13
+ query: async (text, params = []) => {
14
+ const rows = await client.unsafe(text, params);
15
+ return rows;
16
+ }
17
+ };
18
+ };
19
+ const fromNodePg = (client) => {
20
+ return {
21
+ query: async (text, params = []) => {
22
+ const result = await client.query(text, params);
23
+ return result.rows;
24
+ }
25
+ };
26
+ };
27
+ const fromMysql2 = (connection) => {
28
+ return {
29
+ query: async (text, params = []) => {
30
+ const [rows] = await connection.execute(text, params);
31
+ return Array.isArray(rows) ? rows : [];
32
+ }
33
+ };
34
+ };
35
+
36
+ export { createHyperdrive, fromMysql2, fromNodePg, fromPostgresJs };
@@ -0,0 +1,102 @@
1
+ import { sqliteEncode, sqliteDecode } from '@lunora/sql-store';
2
+ import { sql } from 'drizzle-orm';
3
+
4
+ const PG_UNIQUE_VIOLATION_RE = /duplicate key value violates unique constraint/iu;
5
+ const mysqlColumnType = (kind) => {
6
+ switch (kind) {
7
+ case "array":
8
+ case "object":
9
+ case "record": {
10
+ return "JSON";
11
+ }
12
+ case "bigint": {
13
+ return "VARCHAR(64)";
14
+ }
15
+ case "boolean": {
16
+ return "TINYINT";
17
+ }
18
+ case "bytes": {
19
+ return "LONGBLOB";
20
+ }
21
+ case "date":
22
+ case "number":
23
+ case "timestamp": {
24
+ return "DOUBLE";
25
+ }
26
+ default: {
27
+ return "LONGTEXT";
28
+ }
29
+ }
30
+ };
31
+ const MYSQL_PREFIX_INDEX_RE = /TEXT|BLOB/u;
32
+ const postgresDialect = {
33
+ companionTypes: {
34
+ autoincrementPrimaryKey: "BIGSERIAL PRIMARY KEY",
35
+ integer: "INTEGER",
36
+ key: "TEXT",
37
+ real: "DOUBLE PRECISION",
38
+ text: "TEXT"
39
+ },
40
+ columnType: (kind) => {
41
+ switch (kind) {
42
+ case "boolean": {
43
+ return "INTEGER";
44
+ }
45
+ case "bytes": {
46
+ return "BYTEA";
47
+ }
48
+ case "date":
49
+ case "number":
50
+ case "timestamp": {
51
+ return "DOUBLE PRECISION";
52
+ }
53
+ default: {
54
+ return "TEXT";
55
+ }
56
+ }
57
+ },
58
+ decode: (value, kind) => sqliteDecode(value, kind),
59
+ encode: (value) => sqliteEncode(value),
60
+ frameworkColumns: () => [
61
+ { name: "id", type: "TEXT PRIMARY KEY" },
62
+ { name: "_creationTime", type: "DOUBLE PRECISION NOT NULL" }
63
+ ],
64
+ isUniqueViolation: (error) => {
65
+ const { code } = error;
66
+ return code === "23505" || error instanceof Error && PG_UNIQUE_VIOLATION_RE.test(error.message);
67
+ },
68
+ name: "postgres",
69
+ supportsReturning: true,
70
+ tableExists: (table) => sql`SELECT table_name FROM information_schema.tables WHERE table_name = ${table}`
71
+ };
72
+ const mysqlDialect = {
73
+ affectedRows: (result) => result.rowsAffected,
74
+ companionTypes: {
75
+ autoincrementPrimaryKey: "BIGINT AUTO_INCREMENT PRIMARY KEY",
76
+ integer: "INTEGER",
77
+ // VARCHAR so it can be a PRIMARY KEY and be fully indexed (TEXT cannot,
78
+ // without a prefix length). 768 = InnoDB utf8mb4 single-column index limit.
79
+ key: "VARCHAR(768)",
80
+ real: "DOUBLE",
81
+ // Unbounded post-image storage (CDC `doc`); never an index key, so no bound.
82
+ text: "LONGTEXT"
83
+ },
84
+ columnType: (kind) => mysqlColumnType(kind),
85
+ decode: (value, kind) => sqliteDecode(value, kind),
86
+ encode: (value) => sqliteEncode(value),
87
+ frameworkColumns: () => [
88
+ { name: "id", type: "VARCHAR(768) PRIMARY KEY" },
89
+ { name: "_creationTime", type: "DOUBLE NOT NULL" }
90
+ ],
91
+ // InnoDB can't index a TEXT/LONGTEXT/BLOB column without a key prefix; bound it to 768 chars.
92
+ indexKeyPrefix: (kind) => MYSQL_PREFIX_INDEX_RE.test(mysqlColumnType(kind)) ? 768 : void 0,
93
+ isUniqueViolation: (error) => {
94
+ const candidate = error;
95
+ return candidate.errno === 1062 || candidate.code === "ER_DUP_ENTRY";
96
+ },
97
+ name: "mysql",
98
+ supportsReturning: false,
99
+ tableExists: (table) => sql`SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ${table}`
100
+ };
101
+
102
+ export { mysqlDialect, postgresDialect };