@lunora/hyperdrive 1.0.0-alpha.18 → 1.0.0-alpha.180

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/LICENSE.md CHANGED
@@ -103,3 +103,9 @@ Unless required by applicable law or agreed to in writing, software distributed
103
103
  under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
104
  CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
105
  specific language governing permissions and limitations under the License.
106
+
107
+ <!-- DEPENDENCIES -->
108
+ <!-- /DEPENDENCIES -->
109
+
110
+ <!-- TYPE_DEPENDENCIES -->
111
+ <!-- /TYPE_DEPENDENCIES -->
package/README.md CHANGED
@@ -42,7 +42,7 @@ Part of the [Lunora](https://github.com/anolilab/lunora) framework — a type-sa
42
42
  >
43
43
  > Hyperdrive talks to a database **Lunora does not own**. That breaks two invariants the rest of Lunora relies on:
44
44
  >
45
- > 1. **Non-deterministic (action-only).** A SQL query over Hyperdrive is a network call with an external, mutable result — exactly like `fetch`. It is **forbidden in `query`/`mutation`** (which must be deterministic so the coordinator can re-run them on OCC retry / subscription re-evaluation) and allowed **only in `action`s**. The `hyperdrive_outside_action` advisor lint flags `ctx.sql` used in a query/mutation.
45
+ > 1. **Non-deterministic (action-only).** A SQL query over Hyperdrive is a network call with an external, mutable result — exactly like `fetch`. It is **forbidden in `query`/`mutation`** (which must be deterministic so the coordinator can re-run them on subscription re-evaluation; an OCC conflict surfaces as a `409` to the caller, not an internal retry) and allowed **only in `action`s**. The `hyperdrive_outside_action` advisor lint flags `ctx.sql` used in a query/mutation.
46
46
  > 2. **Non-reactive.** External writes do **not** flow through the Durable-Object / SQLite change-feed, so **Lunora live queries and subscriptions will NOT re-run** when an external Postgres/MySQL row changes. There is no honest way to make external writes reactive here.
47
47
  >
48
48
  > Use Hyperdrive to _read/write your existing DB from an action_. It is the **wrong** tool for "make my Postgres reactive". If you want external data to be reactive, write a **projection** of it into a `defineSchema` DO/D1 table from the action — that write _is_ tracked.
@@ -83,19 +83,33 @@ pnpm add mysql2 # mysql2 → fromMysql2
83
83
 
84
84
  ## Usage
85
85
 
86
- `ctx.sql` is wired by codegen onto `ActionCtx` only — never `QueryCtx`/`MutationCtx`. The procedure builders (`action`, `v`) and `api` come from your app-local generated modules:
86
+ `ctx.sql` is wired by codegen onto `ActionCtx` only — never `QueryCtx`/`MutationCtx`, and it is `readonly`, so it is built once at the app level rather than assigned in a handler. Codegen emits a `sql` config thunk for it (`createHyperdrive` returns connection info; only you know which driver wraps it):
87
87
 
88
88
  ```ts
89
+ // src/server/index.ts
90
+ import type { HyperdriveLike } from "@lunora/hyperdrive";
89
91
  import { createHyperdrive, fromPostgresJs } from "@lunora/hyperdrive";
90
92
  import postgres from "postgres";
91
93
 
94
+ import { defineApp } from "../../lunora/_generated/app";
95
+
96
+ const app = defineApp<Env>()
97
+ .shard((env) => env.SHARD)
98
+ .hyperdrive((env) => fromPostgresJs(postgres(createHyperdrive(env.HYPERDRIVE as HyperdriveLike).connectionString)))
99
+ .build();
100
+
101
+ export const ShardDO = app.ShardDO;
102
+ ```
103
+
104
+ Hand-composing the worker instead? The same thunk is `createShardDO({ sql: (env) => … })`. Without it, every `ctx.sql` method throws a message pointing back at this wiring.
105
+
106
+ Handlers then just read it. The procedure builders (`action`, `v`) and `api` come from your app-local generated modules:
107
+
108
+ ```ts
92
109
  import { api } from "@/lunora/_generated/api";
93
110
  import { action, v } from "@/lunora/_generated/server";
94
111
 
95
112
  export const syncCustomer = action.input({ orgId: v.string() }).action(async ({ args: { orgId }, ctx }) => {
96
- const { connectionString } = createHyperdrive(ctx.env.HYPERDRIVE);
97
- ctx.sql = fromPostgresJs(postgres(connectionString));
98
-
99
113
  const rows = await ctx.sql.query<{ id: string; name: string }>("select id, name from customers where org = $1", [orgId]);
100
114
 
101
115
  // Want it reactive? Project it into a Lunora table — THIS write is tracked.
@@ -113,6 +127,44 @@ export const syncCustomer = action.input({ orgId: v.string() }).action(async ({
113
127
  | `pg` (node-postgres) | `fromNodePg` | `$1, $2, …` |
114
128
  | `mysql2/promise` | `fromMysql2` | `?` |
115
129
 
130
+ ## Reactive reads over your schema: the `.source()` modifier
131
+
132
+ The projection above is the escape hatch. For the common case — an existing Postgres you are not going to move, and a read path that should feel live — declare the source on the table and Lunora runs the whole loop on the shard's alarm: pull, diff, materialize, poke subscribers. No action, no mutation, no cron to write:
133
+
134
+ ```ts
135
+ // lunora/schema.ts
136
+ export default defineSchema({
137
+ messages: defineTable({ body: v.string(), channelId: v.string() })
138
+ .shardBy("channelId")
139
+ .source({
140
+ binding: "HYPERDRIVE_MESSAGES",
141
+ query: 'select id, body, channel_id as "channelId" from messages where channel_id = $1',
142
+ tenantBy: (shardKey) => [shardKey], // mandatory under .shardBy() — the tenant boundary
143
+ }),
144
+ });
145
+
146
+ export const channelMessages = defineShape({ table: "messages", where: () => ({}) });
147
+ ```
148
+
149
+ Supply the driver once, on the app builder — required, or every tick records `no sourceClient resolved for binding "…"` and the table stays empty. Lunora memoizes it per binding:
150
+
151
+ ```ts
152
+ export default defineApp<Env>()
153
+ .shard((env) => env.SHARD)
154
+ .sourceClient((env, binding) => fromPostgresJs(postgres((env[binding] as { connectionString: string }).connectionString)))
155
+ .build();
156
+ ```
157
+
158
+ Clients subscribe with the shape they would use over any table — external data stops being external once it is materialized.
159
+
160
+ Three things to know before you build on it:
161
+
162
+ - **It polls; it is not logical replication.** Freshness is the refresh cadence: every alarm tick by default, `refresh: { everyMs }` to throttle, `refresh: "manual"` to drive it yourself. Writes from other systems land on the next pull.
163
+ - **`tenantBy` is the isolation boundary.** `defineSchema` throws at load if a sourced `.shardBy()` table omits it, and the `external_source_unscoped` advisor lint catches it at build time. Without it, one tenant's DO pulls every tenant's rows.
164
+ - **`mode: "full-pull"` (the default) diffs the whole slice each tick**, so upstream deletes are detected for free, at a bench ceiling around 10k rows. Past that, `mode: "incremental"` pulls only rows past a durable watermark via a cursor column. An incremental slice cannot see a delete on its own — an absent row means "unchanged", not "deleted" — so it **requires** a delete-visibility path: either `reconcileEveryMs` (a periodic full-pull sweep) or `softDeleteColumn` (an upstream tombstone column the cursor query returns, so do not filter it out). `defineSchema` throws and the `external_source_incremental_no_delete_path` lint fails the build if an incremental source declares neither.
165
+
166
+ `.source()` cannot be combined with `.global()` — they are contradictory tiers, and `defineSchema` rejects it.
167
+
116
168
  ## Reactive `.global()` over Hyperdrive
117
169
 
118
170
  The `@lunora/hyperdrive/global` subpath is the opposite trade-off: Lunora **owns** the schema and a `.global()` table gets a real column-per-field layout on your Postgres/MySQL, with every write routed through the shared store core. Live queries stay reactive — identical to D1 — because the writer drives the same broadcast hook. Build the writer inside the Durable Object that hosts the `.global()` store and inject it as `globalDb`:
@@ -127,7 +179,7 @@ const globalDb = createPostgresGlobalCtxDb({ query: (text, params) => sql.unsafe
127
179
 
128
180
  For MySQL use `createMysqlGlobalCtxDb` with a `mysql2/promise` pool created with `flags: ["FOUND_ROWS"]` — without `CLIENT_FOUND_ROWS` the affected-rows OCC guard sees changed (not matched) rows and raises spurious conflicts. Lower-level building blocks (`buildPgExec`, `buildMysqlExec`, `postgresDialect`, `mysqlDialect`, `createHyperdriveGlobalCtxDb`) are exported for custom wiring.
129
181
 
130
- > This README covers the basics. For the full API and the determinism/realtime rationale, see the **[documentation](https://lunora.sh/docs/addons/hyperdrive)**.
182
+ > This README covers the basics. For the full API and the determinism/realtime rationale, see the **[documentation](https://lunora.sh/docs/packages/hyperdrive)**.
131
183
 
132
184
  ## Non-goals
133
185
 
package/dist/global.d.mts CHANGED
@@ -1,47 +1,136 @@
1
- import { DatabaseWriterLike } from '@lunora/do';
1
+ import { DatabaseWriterLike } from '@lunora/shard-engine';
2
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
- }
3
+ import { M as Mysql2Like, S as SqlClient } from "./packem_shared/types.d-B2JdXSms.mjs";
4
+ import { VectorMetric, VectorizeIndexLike } from '@lunora/platform';
5
+ /**
6
+ * Minimal row-returning client (e.g. `@lunora/hyperdrive`'s `fromPostgresJs`/`fromNodePg`
7
+ * result). Aliases {@link SqlClient} — the exec-facing name is kept so call sites read
8
+ * intent, but the shape is the single source of truth in `./types` (no drift).
9
+ */
10
+ type RowClient = SqlClient;
11
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
- */
12
+ * Minimal `mysql2/promise` connection/pool surface — `execute` resolves to
13
+ * `[rows | ResultSetHeader, fields]`. Aliases {@link Mysql2Like} so the /global
14
+ * entry's driver surface can never drift from the main entry's, widened with the
15
+ * (optional, structural) shape {@link assertFoundRows}'s `CLIENT_FOUND_ROWS`
16
+ * probe reads.
17
+ *
18
+ * A real `mysql2/promise` connection/pool exposes the merged client-flags
19
+ * bitmask synchronously, but at two different depths depending on which one it
20
+ * is, and NEITHER is in `mysql2`'s own `.d.ts` — its `Pool extends Connection`
21
+ * signature claims a top-level `config`, but at runtime a `mysql2/promise`
22
+ * `Pool` has none; the real value lives one level down, on the core pool it
23
+ * wraps:
24
+ *
25
+ * - a single `Connection`/`PoolConnection` → `connection.config.clientFlags`
26
+ * - a `Pool` (the `createPool({ flags: ["FOUND_ROWS"] })` example above) →
27
+ * `pool.pool.config.connectionConfig.clientFlags`
28
+ *
29
+ * Because those paths are undocumented driver internals, `global-dialect.test.ts`
30
+ * pins them against a REAL `mysql2` pool (built without connecting) rather than
31
+ * only against hand-written doubles — if a `mysql2` release relocates them, the
32
+ * probe would otherwise degrade silently to the warn branch and the OCC guard
33
+ * would go unchecked.
34
+ *
35
+ * The probe fields are typed `unknown` publicly: the paths are not in `mysql2`'s
36
+ * typings, so spelling them out made a real `createPool(...)` fail to type-check
37
+ * (TS2345, weak-type mismatch on `config`). {@link readMysqlClientFlags} reads
38
+ * them through the internal `FlagProbeShape` instead, and a minimal test double
39
+ * (only `execute`) resolves to "undeterminable" rather than a `TypeError`.
40
+ */
41
+ type Mysql2Execute = Mysql2Like & {
42
+ config?: unknown;
43
+ pool?: unknown;
44
+ };
45
+ /**
46
+ * Wrap a Postgres row-client (from `@lunora/hyperdrive`'s `fromPostgresJs` /
47
+ * `fromNodePg`) as a {@link SqlExec}. The core already renders `$N` placeholders
48
+ * for Postgres, so `all`/`run` forward verbatim. Postgres uses `RETURNING` for
49
+ * OCC (read via `all`), so `run` reports no affected-row count.
50
+ *
51
+ * `batch` dispatches every statement concurrently (`Promise.all`) over `client`
52
+ * rather than awaiting each `query` call in turn — `RowClient` only exposes a
53
+ * single-statement `query`, so there is no wire-level multi-statement command
54
+ * to reach for. When `client` is backed by a pool (the common production
55
+ * shape), this genuinely spreads the statements across multiple physical
56
+ * connections instead of serializing one full round trip at a time; against a
57
+ * single connection it still removes the sequential *await*, though the
58
+ * underlying driver may itself queue the sends. Either way it stays
59
+ * non-atomic, at-least-once, and unordered between elements, same as the
60
+ * sequential fallback minus the ordering — safe only for statements whose
61
+ * effects don't depend on each other, which is what every current caller
62
+ * batches (distinct-keyed companion rows).
63
+ */
17
64
  declare const buildPgExec: (client: RowClient) => SqlExec;
18
65
  /**
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
- */
66
+ * Wrap a `mysql2/promise` connection/pool as a {@link SqlExec}. The core already
67
+ * renders backtick identifiers and `?` placeholders for MySQL, so `all`/`run`
68
+ * forward verbatim. MySQL has no `RETURNING`, so `run` surfaces `affectedRows`
69
+ * for the store's affected-rows OCC guard.
70
+ *
71
+ * **The connection MUST be created with the `CLIENT_FOUND_ROWS` flag**
72
+ * (mysql2: `createPool({ flags: ["FOUND_ROWS"] })`). Without it, `affectedRows`
73
+ * counts *changed* rows, so an idempotent `patch`/`replace` that re-writes the
74
+ * same values reports 0 and the OCC guard raises a spurious conflict. Verified
75
+ * once here at construction — see {@link assertFoundRows} — never per statement.
76
+ *
77
+ * `batch` dispatches every statement concurrently (`Promise.all`), same
78
+ * rationale as {@link buildPgExec}'s `batch` — `Mysql2Like` only exposes a
79
+ * single-statement `execute`, so this is "spread across a pool's connections"
80
+ * rather than one wire-level multi-statement command; still non-atomic,
81
+ * at-least-once, and unordered between elements, safe only for statements
82
+ * with no cross-effect (what every current caller batches).
83
+ */
29
84
  declare const buildMysqlExec: (connection: Mysql2Execute) => SqlExec;
30
85
  /**
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
- */
86
+ * **Postgres** dialect. Differs from SQLite only in column types
87
+ * (`DOUBLE PRECISION`/`BYTEA`/`BIGSERIAL`), the `information_schema` catalog
88
+ * probe, and unique-violation detection (SQLSTATE `23505`).
89
+ */
35
90
  declare const postgresDialect: SqlDialect;
36
91
  /**
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
- */
92
+ * **MySQL** dialect. Diverges in: **no `RETURNING`** (the store's OCC falls back
93
+ * to affected-rows — which requires the connection's `CLIENT_FOUND_ROWS` flag so
94
+ * a no-op update still reports a matched row, see `buildMysqlExec`); bounded
95
+ * `VARCHAR` keys (TEXT can't be a primary key / unindexed); a TEXT/BLOB index key
96
+ * prefix; and `ER_DUP_ENTRY` (errno 1062) unique violations. (Drizzle's MySQL
97
+ * dialect supplies the backtick identifiers + `ON DUPLICATE KEY` upserts.)
98
+ */
44
99
  declare const mysqlDialect: SqlDialect;
100
+ /** Options for {@link createPgVectorIndex}. */
101
+ interface PgVectorIndexOptions {
102
+ /** Postgres client — the same `SqlClient` the Hyperdrive global store takes. */
103
+ client: SqlClient;
104
+ /**
105
+ * Vector width. Must match the embedder's output and the `dimensions` on the
106
+ * schema's `.vectorize(...)`; Postgres enforces it per row, so a mismatch
107
+ * surfaces as a write error rather than silently bad neighbours.
108
+ */
109
+ dimensions: number;
110
+ /** Distance metric. Defaults to `"cosine"`, matching the common embedding case. */
111
+ metric?: VectorMetric;
112
+ /**
113
+ * Names the backing table (`__vec_<name>`), derived rather than configurable —
114
+ * a second name for one index is a way to lose data, not a feature.
115
+ *
116
+ * This is NOT required to equal the key in the shard's `vectors` map, and often
117
+ * cannot: that key mirrors the schema's `.vectorize({ index })`, which may carry
118
+ * hyphens (`"docs-body"`), while this must be a bare SQL identifier. Keep it
119
+ * stable — changing it points the index at a different, empty table.
120
+ */
121
+ name: string;
122
+ }
123
+ /**
124
+ * Build a `pgvector`-backed vector index that satisfies {@link VectorizeIndexLike}.
125
+ *
126
+ * Requires the `vector` extension to be installable by the connecting role
127
+ * (`CREATE EXTENSION IF NOT EXISTS vector`). On a managed Postgres where the
128
+ * role cannot create extensions, install it once out-of-band; the statement is
129
+ * then a no-op.
130
+ * @param options See {@link PgVectorIndexOptions}.
131
+ * @returns An index object the shard's `vectors` map accepts as-is.
132
+ */
133
+ declare const createPgVectorIndex: (options: PgVectorIndexOptions) => VectorizeIndexLike;
45
134
  /** Which engine a Hyperdrive-backed `.global()` store targets. */
46
135
  type HyperdriveEngine = "mysql" | "postgres";
47
136
  /** Options for {@link createHyperdriveGlobalCtxDb}: the store options minus `exec`/`dialect`, plus the engine and a built `SqlExec`. */
@@ -52,18 +141,14 @@ interface CreateHyperdriveGlobalCtxDbOptions extends Omit<SqlCtxDbOptions, "dial
52
141
  exec: SqlExec;
53
142
  }
54
143
  /**
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;
144
+ * Build a reactive `.global()` writer backed by a Hyperdrive-reachable
145
+ * Postgres/MySQL database. Pass a built {@link SqlExec} (via {@link buildPgExec}/
146
+ * {@link buildMysqlExec}) and the matching `engine`; everything else mirrors the
147
+ * D1 store options.
148
+ */
149
+ declare const createHyperdriveGlobalCtxDb: ({ engine, exec, ...rest }: CreateHyperdriveGlobalCtxDbOptions) => DatabaseWriterLike;
65
150
  /** Convenience: a **Postgres** `.global()` writer from a row-client (postgres.js/pg over Hyperdrive). */
66
151
  declare const createPostgresGlobalCtxDb: (client: RowClient, options: Omit<CreateHyperdriveGlobalCtxDbOptions, "engine" | "exec">) => DatabaseWriterLike;
67
152
  /** Convenience: a **MySQL** `.global()` writer from a `mysql2/promise` connection/pool (created with `flags: ["FOUND_ROWS"]`). */
68
153
  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 };
154
+ export { CreateHyperdriveGlobalCtxDbOptions, HyperdriveEngine, type Mysql2Execute, type PgVectorIndexOptions, type RowClient, buildMysqlExec, buildPgExec, createHyperdriveGlobalCtxDb, createMysqlGlobalCtxDb, createPgVectorIndex, createPostgresGlobalCtxDb, mysqlDialect, postgresDialect };
package/dist/global.d.ts CHANGED
@@ -1,47 +1,136 @@
1
- import { DatabaseWriterLike } from '@lunora/do';
1
+ import { DatabaseWriterLike } from '@lunora/shard-engine';
2
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
- }
3
+ import { M as Mysql2Like, S as SqlClient } from "./packem_shared/types.d-B2JdXSms.js";
4
+ import { VectorMetric, VectorizeIndexLike } from '@lunora/platform';
5
+ /**
6
+ * Minimal row-returning client (e.g. `@lunora/hyperdrive`'s `fromPostgresJs`/`fromNodePg`
7
+ * result). Aliases {@link SqlClient} — the exec-facing name is kept so call sites read
8
+ * intent, but the shape is the single source of truth in `./types` (no drift).
9
+ */
10
+ type RowClient = SqlClient;
11
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
- */
12
+ * Minimal `mysql2/promise` connection/pool surface — `execute` resolves to
13
+ * `[rows | ResultSetHeader, fields]`. Aliases {@link Mysql2Like} so the /global
14
+ * entry's driver surface can never drift from the main entry's, widened with the
15
+ * (optional, structural) shape {@link assertFoundRows}'s `CLIENT_FOUND_ROWS`
16
+ * probe reads.
17
+ *
18
+ * A real `mysql2/promise` connection/pool exposes the merged client-flags
19
+ * bitmask synchronously, but at two different depths depending on which one it
20
+ * is, and NEITHER is in `mysql2`'s own `.d.ts` — its `Pool extends Connection`
21
+ * signature claims a top-level `config`, but at runtime a `mysql2/promise`
22
+ * `Pool` has none; the real value lives one level down, on the core pool it
23
+ * wraps:
24
+ *
25
+ * - a single `Connection`/`PoolConnection` → `connection.config.clientFlags`
26
+ * - a `Pool` (the `createPool({ flags: ["FOUND_ROWS"] })` example above) →
27
+ * `pool.pool.config.connectionConfig.clientFlags`
28
+ *
29
+ * Because those paths are undocumented driver internals, `global-dialect.test.ts`
30
+ * pins them against a REAL `mysql2` pool (built without connecting) rather than
31
+ * only against hand-written doubles — if a `mysql2` release relocates them, the
32
+ * probe would otherwise degrade silently to the warn branch and the OCC guard
33
+ * would go unchecked.
34
+ *
35
+ * The probe fields are typed `unknown` publicly: the paths are not in `mysql2`'s
36
+ * typings, so spelling them out made a real `createPool(...)` fail to type-check
37
+ * (TS2345, weak-type mismatch on `config`). {@link readMysqlClientFlags} reads
38
+ * them through the internal `FlagProbeShape` instead, and a minimal test double
39
+ * (only `execute`) resolves to "undeterminable" rather than a `TypeError`.
40
+ */
41
+ type Mysql2Execute = Mysql2Like & {
42
+ config?: unknown;
43
+ pool?: unknown;
44
+ };
45
+ /**
46
+ * Wrap a Postgres row-client (from `@lunora/hyperdrive`'s `fromPostgresJs` /
47
+ * `fromNodePg`) as a {@link SqlExec}. The core already renders `$N` placeholders
48
+ * for Postgres, so `all`/`run` forward verbatim. Postgres uses `RETURNING` for
49
+ * OCC (read via `all`), so `run` reports no affected-row count.
50
+ *
51
+ * `batch` dispatches every statement concurrently (`Promise.all`) over `client`
52
+ * rather than awaiting each `query` call in turn — `RowClient` only exposes a
53
+ * single-statement `query`, so there is no wire-level multi-statement command
54
+ * to reach for. When `client` is backed by a pool (the common production
55
+ * shape), this genuinely spreads the statements across multiple physical
56
+ * connections instead of serializing one full round trip at a time; against a
57
+ * single connection it still removes the sequential *await*, though the
58
+ * underlying driver may itself queue the sends. Either way it stays
59
+ * non-atomic, at-least-once, and unordered between elements, same as the
60
+ * sequential fallback minus the ordering — safe only for statements whose
61
+ * effects don't depend on each other, which is what every current caller
62
+ * batches (distinct-keyed companion rows).
63
+ */
17
64
  declare const buildPgExec: (client: RowClient) => SqlExec;
18
65
  /**
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
- */
66
+ * Wrap a `mysql2/promise` connection/pool as a {@link SqlExec}. The core already
67
+ * renders backtick identifiers and `?` placeholders for MySQL, so `all`/`run`
68
+ * forward verbatim. MySQL has no `RETURNING`, so `run` surfaces `affectedRows`
69
+ * for the store's affected-rows OCC guard.
70
+ *
71
+ * **The connection MUST be created with the `CLIENT_FOUND_ROWS` flag**
72
+ * (mysql2: `createPool({ flags: ["FOUND_ROWS"] })`). Without it, `affectedRows`
73
+ * counts *changed* rows, so an idempotent `patch`/`replace` that re-writes the
74
+ * same values reports 0 and the OCC guard raises a spurious conflict. Verified
75
+ * once here at construction — see {@link assertFoundRows} — never per statement.
76
+ *
77
+ * `batch` dispatches every statement concurrently (`Promise.all`), same
78
+ * rationale as {@link buildPgExec}'s `batch` — `Mysql2Like` only exposes a
79
+ * single-statement `execute`, so this is "spread across a pool's connections"
80
+ * rather than one wire-level multi-statement command; still non-atomic,
81
+ * at-least-once, and unordered between elements, safe only for statements
82
+ * with no cross-effect (what every current caller batches).
83
+ */
29
84
  declare const buildMysqlExec: (connection: Mysql2Execute) => SqlExec;
30
85
  /**
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
- */
86
+ * **Postgres** dialect. Differs from SQLite only in column types
87
+ * (`DOUBLE PRECISION`/`BYTEA`/`BIGSERIAL`), the `information_schema` catalog
88
+ * probe, and unique-violation detection (SQLSTATE `23505`).
89
+ */
35
90
  declare const postgresDialect: SqlDialect;
36
91
  /**
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
- */
92
+ * **MySQL** dialect. Diverges in: **no `RETURNING`** (the store's OCC falls back
93
+ * to affected-rows — which requires the connection's `CLIENT_FOUND_ROWS` flag so
94
+ * a no-op update still reports a matched row, see `buildMysqlExec`); bounded
95
+ * `VARCHAR` keys (TEXT can't be a primary key / unindexed); a TEXT/BLOB index key
96
+ * prefix; and `ER_DUP_ENTRY` (errno 1062) unique violations. (Drizzle's MySQL
97
+ * dialect supplies the backtick identifiers + `ON DUPLICATE KEY` upserts.)
98
+ */
44
99
  declare const mysqlDialect: SqlDialect;
100
+ /** Options for {@link createPgVectorIndex}. */
101
+ interface PgVectorIndexOptions {
102
+ /** Postgres client — the same `SqlClient` the Hyperdrive global store takes. */
103
+ client: SqlClient;
104
+ /**
105
+ * Vector width. Must match the embedder's output and the `dimensions` on the
106
+ * schema's `.vectorize(...)`; Postgres enforces it per row, so a mismatch
107
+ * surfaces as a write error rather than silently bad neighbours.
108
+ */
109
+ dimensions: number;
110
+ /** Distance metric. Defaults to `"cosine"`, matching the common embedding case. */
111
+ metric?: VectorMetric;
112
+ /**
113
+ * Names the backing table (`__vec_<name>`), derived rather than configurable —
114
+ * a second name for one index is a way to lose data, not a feature.
115
+ *
116
+ * This is NOT required to equal the key in the shard's `vectors` map, and often
117
+ * cannot: that key mirrors the schema's `.vectorize({ index })`, which may carry
118
+ * hyphens (`"docs-body"`), while this must be a bare SQL identifier. Keep it
119
+ * stable — changing it points the index at a different, empty table.
120
+ */
121
+ name: string;
122
+ }
123
+ /**
124
+ * Build a `pgvector`-backed vector index that satisfies {@link VectorizeIndexLike}.
125
+ *
126
+ * Requires the `vector` extension to be installable by the connecting role
127
+ * (`CREATE EXTENSION IF NOT EXISTS vector`). On a managed Postgres where the
128
+ * role cannot create extensions, install it once out-of-band; the statement is
129
+ * then a no-op.
130
+ * @param options See {@link PgVectorIndexOptions}.
131
+ * @returns An index object the shard's `vectors` map accepts as-is.
132
+ */
133
+ declare const createPgVectorIndex: (options: PgVectorIndexOptions) => VectorizeIndexLike;
45
134
  /** Which engine a Hyperdrive-backed `.global()` store targets. */
46
135
  type HyperdriveEngine = "mysql" | "postgres";
47
136
  /** Options for {@link createHyperdriveGlobalCtxDb}: the store options minus `exec`/`dialect`, plus the engine and a built `SqlExec`. */
@@ -52,18 +141,14 @@ interface CreateHyperdriveGlobalCtxDbOptions extends Omit<SqlCtxDbOptions, "dial
52
141
  exec: SqlExec;
53
142
  }
54
143
  /**
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;
144
+ * Build a reactive `.global()` writer backed by a Hyperdrive-reachable
145
+ * Postgres/MySQL database. Pass a built {@link SqlExec} (via {@link buildPgExec}/
146
+ * {@link buildMysqlExec}) and the matching `engine`; everything else mirrors the
147
+ * D1 store options.
148
+ */
149
+ declare const createHyperdriveGlobalCtxDb: ({ engine, exec, ...rest }: CreateHyperdriveGlobalCtxDbOptions) => DatabaseWriterLike;
65
150
  /** Convenience: a **Postgres** `.global()` writer from a row-client (postgres.js/pg over Hyperdrive). */
66
151
  declare const createPostgresGlobalCtxDb: (client: RowClient, options: Omit<CreateHyperdriveGlobalCtxDbOptions, "engine" | "exec">) => DatabaseWriterLike;
67
152
  /** Convenience: a **MySQL** `.global()` writer from a `mysql2/promise` connection/pool (created with `flags: ["FOUND_ROWS"]`). */
68
153
  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 };
154
+ export { CreateHyperdriveGlobalCtxDbOptions, HyperdriveEngine, type Mysql2Execute, type PgVectorIndexOptions, type RowClient, buildMysqlExec, buildPgExec, createHyperdriveGlobalCtxDb, createMysqlGlobalCtxDb, createPgVectorIndex, createPostgresGlobalCtxDb, mysqlDialect, postgresDialect };
package/dist/global.mjs CHANGED
@@ -1,9 +1 @@
1
- import { createSqlCtxDb } from '@lunora/sql-store';
2
- import { postgresDialect, mysqlDialect } from './packem_shared/mysqlDialect-oNhZ58s8.mjs';
3
- import { buildMysqlExec, buildPgExec } from './packem_shared/buildMysqlExec-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 };
1
+ import{createSqlCtxDb as c}from"@lunora/sql-store";import{postgresDialect as l,mysqlDialect as s}from"./packem_shared/mysqlDialect-BS1Sz60B.mjs";import{buildMysqlExec as a,buildPgExec as i}from"./packem_shared/buildMysqlExec-CjkrA5JG.mjs";import{createPgVectorIndex as d}from"./packem_shared/createPgVectorIndex-CSNnG065.mjs";const r=({engine:e,exec:t,...o})=>c({...o,dialect:e==="postgres"?l:s,exec:t}),p=(e,t)=>r({...t,engine:"postgres",exec:i(e)}),g=(e,t)=>r({...t,engine:"mysql",exec:a(e)});export{a as buildMysqlExec,i as buildPgExec,r as createHyperdriveGlobalCtxDb,g as createMysqlGlobalCtxDb,d as createPgVectorIndex,p as createPostgresGlobalCtxDb,s as mysqlDialect,l as postgresDialect};