@typed-sql/mysql 1.0.0-rc.0 → 2.0.0-rc.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/README.md +45 -56
  3. package/dist/packages/mysql/src/bulk.d.ts +22 -0
  4. package/dist/packages/mysql/src/bulk.d.ts.map +1 -0
  5. package/dist/packages/mysql/src/bulk.js +205 -0
  6. package/dist/packages/mysql/src/bulk.js.map +1 -0
  7. package/dist/packages/mysql/src/decoding.d.ts +26 -0
  8. package/dist/packages/mysql/src/decoding.d.ts.map +1 -0
  9. package/dist/packages/mysql/src/decoding.js +172 -0
  10. package/dist/packages/mysql/src/decoding.js.map +1 -0
  11. package/dist/packages/mysql/src/index.d.ts +5 -1
  12. package/dist/packages/mysql/src/index.d.ts.map +1 -1
  13. package/dist/packages/mysql/src/index.js +16 -3
  14. package/dist/packages/mysql/src/index.js.map +1 -1
  15. package/dist/packages/mysql/src/mysql2.d.ts +60 -1
  16. package/dist/packages/mysql/src/mysql2.d.ts.map +1 -1
  17. package/dist/packages/mysql/src/mysql2.js +402 -1
  18. package/dist/packages/mysql/src/mysql2.js.map +1 -1
  19. package/dist/packages/mysql/src/prepared.d.ts +20 -0
  20. package/dist/packages/mysql/src/prepared.d.ts.map +1 -0
  21. package/dist/packages/mysql/src/prepared.js +47 -0
  22. package/dist/packages/mysql/src/prepared.js.map +1 -0
  23. package/dist/packages/mysql/src/provider.d.ts.map +1 -1
  24. package/dist/packages/mysql/src/provider.js +8 -1
  25. package/dist/packages/mysql/src/provider.js.map +1 -1
  26. package/dist/packages/mysql/src/resolver.d.ts.map +1 -1
  27. package/dist/packages/mysql/src/resolver.js +20 -1
  28. package/dist/packages/mysql/src/resolver.js.map +1 -1
  29. package/dist/packages/mysql/src/routing.d.ts +22 -0
  30. package/dist/packages/mysql/src/routing.d.ts.map +1 -0
  31. package/dist/packages/mysql/src/routing.js +72 -0
  32. package/dist/packages/mysql/src/routing.js.map +1 -0
  33. package/dist/packages/mysql/src/runtime.d.ts +22 -8
  34. package/dist/packages/mysql/src/runtime.d.ts.map +1 -1
  35. package/dist/packages/mysql/src/runtime.js +530 -70
  36. package/dist/packages/mysql/src/runtime.js.map +1 -1
  37. package/dist/packages/mysql/src/semantics.d.ts +5 -0
  38. package/dist/packages/mysql/src/semantics.d.ts.map +1 -0
  39. package/dist/packages/mysql/src/semantics.js +203 -0
  40. package/dist/packages/mysql/src/semantics.js.map +1 -0
  41. package/dist/packages/mysql/src/stream.d.ts +32 -0
  42. package/dist/packages/mysql/src/stream.d.ts.map +1 -0
  43. package/dist/packages/mysql/src/stream.js +175 -0
  44. package/dist/packages/mysql/src/stream.js.map +1 -0
  45. package/dist/packages/mysql/src/version.d.ts +2 -0
  46. package/dist/packages/mysql/src/version.d.ts.map +1 -0
  47. package/dist/packages/mysql/src/version.js +2 -0
  48. package/dist/packages/mysql/src/version.js.map +1 -0
  49. package/package.json +4 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,141 @@
1
1
  # @typed-sql/mysql
2
2
 
3
+ ## 2.0.0-rc.1
4
+
5
+ ### Minor Changes
6
+
7
+ - 9c72dab: Use live MySQL catalog origins to preserve enum result evidence, and compare parameter metadata in
8
+ the safe input direction so compiler-enforced literal subsets do not become false mismatches.
9
+
10
+ ## 2.0.0-rc.0
11
+
12
+ ### Major Changes
13
+
14
+ - 29afc3d: Add conservative semantic primary/replica routing over application-owned databases, scoped
15
+ read-after-write pinning, explicit role requirements, stable unsafe-route errors, dialect runtime
16
+ semantic resolvers, and bounded abortable transaction retry policies with native PostgreSQL and
17
+ MySQL error classifiers. Parse and classify dialect locking reads so uncertain or affine work
18
+ always fails closed to primary.
19
+ - 6a7ae58: Add opt-in live query verification through grammar-owned PostgreSQL PREPARE and MySQL
20
+ COM_STMT_PREPARE adapters, bounded neutral comparison, deterministic secret-free proof artifacts,
21
+ offline cache validation, explicit unsupported classifications, CLI workflows, real database E2E,
22
+ and performance budgets.
23
+ - b06fd0a: Add grammar-neutral optional adapter capability discovery, typed PostgreSQL COPY import and export
24
+ through application-owned `pg-copy-streams`, and typed MySQL LOAD DATA import through mysql2's
25
+ application-owned infile stream. Bulk transfers preserve ordinary `INSERT` parameter evidence,
26
+ enforce structural row stability, apply bounded backpressure, support cancellation and progress,
27
+ and integrate with transaction ownership and conservative connection cleanup.
28
+ - 3050209: Add the dialect contract v4 semantic query evidence foundation. PostgreSQL and MySQL now report operation, dependencies, cardinality, volatility, locking, connection affinity, and required capabilities; compiler results add deterministic query and structural-variant fingerprints and conservatively merged source-mapped semantics. Schema snapshots can record function volatility, and the AST package exposes a neutral statement walker for grammar implementations.
29
+ - 1b054b6: Add an adapter-neutral, redacted database observation lifecycle for queries, cardinality contracts,
30
+ batches, PostgreSQL pipelines, streams, cancellation, and nested transactions. Runtime fingerprints
31
+ correlate with compiler structural variants while SQL, parameter values, connection configuration,
32
+ and driver causes remain excluded by default. Publish the optional OpenTelemetry bridge with current
33
+ database semantic conventions and explicit high-cardinality or exception-capture opt-ins.
34
+ - 87189c3: Add grammar-neutral `all`, `one`, and `maybeOne` execution with exact row types, stable cardinality
35
+ and cancellation errors, explicit adapter capabilities, AbortSignal support, and absolute deadlines.
36
+ The pg and mysql2 adapters conservatively discard interrupted connections, including transaction
37
+ leases, while the existing uncontrolled `execute` path remains unchanged.
38
+ - e654fae: Add opt-in Standard Schema V1 result validation with compile-time output compatibility, immutable
39
+ query attachment, sync and async validators, redacted fingerprinted errors, and consistent decoded-row
40
+ handling across buffered cardinality methods, batches, PostgreSQL pipelines, streams, and transactions.
41
+ - b2ec119: Add opt-in, grammar-neutral query-plan governance with PostgreSQL and MySQL structured EXPLAIN
42
+ adapters, transient application-owned samples, redacted fingerprint-keyed artifacts, absolute and
43
+ comparable regression budgets, explicit uncertainty, CLI capture and review, documentation, and
44
+ performance coverage.
45
+
46
+ ### Patch Changes
47
+
48
+ - Updated dependencies [29afc3d]
49
+ - Updated dependencies [3f063f6]
50
+ - Updated dependencies [6a7ae58]
51
+ - Updated dependencies [af27a0e]
52
+ - Updated dependencies [b06fd0a]
53
+ - Updated dependencies [3050209]
54
+ - Updated dependencies [1b054b6]
55
+ - Updated dependencies [b4f1b6e]
56
+ - Updated dependencies [87189c3]
57
+ - Updated dependencies [e654fae]
58
+ - Updated dependencies [b2ec119]
59
+ - @typed-sql/ast@2.0.0-rc.0
60
+ - @typed-sql/core@2.0.0-rc.0
61
+ - @typed-sql/schema@2.0.0-rc.0
62
+
63
+ ## 1.0.0
64
+
65
+ ### Major Changes
66
+
67
+ - 7ca256b: Release the first public typed-sql beta: exact TypeScript 7 row inference from static PostgreSQL and
68
+ MySQL, versioned schema introspection, application-owned drivers, config-driven grammar plugins,
69
+ CLI verification, editor language-server integration, versioned diagnostics, bounded parsing, and
70
+ real-database plus packed-tarball verification.
71
+
72
+ ### Minor Changes
73
+
74
+ - eb16de7: Add grammar-neutral stream and ordered-result type contracts, and add lazy prepared-query factories to the PostgreSQL and MySQL runtime adapters. Prepared factories retain exact query types, validate stable SQL shapes, and remain available inside nested transactions.
75
+ - eb16de7: Add lazy, exactly typed query streams to the PostgreSQL and MySQL runtime adapters. PostgreSQL
76
+ uses an application-owned optional `pg-cursor` installation for bounded cursor reads. MySQL uses
77
+ mysql2's execute-protocol stream and shared decoder plan. Both adapters enforce deterministic
78
+ cleanup, transaction ownership, and positive safe-integer batch sizes.
79
+ - eb16de7: Add a grammar-neutral validated query-batch type and ordered, exactly typed query batches to the
80
+ PostgreSQL and MySQL runtime adapters. Non-empty root batches execute sequentially on one leased
81
+ connection, transaction batches reuse their transaction connection, and empty batches avoid
82
+ connection acquisition. Batch execution preserves prepared metadata and adapter codecs, stops at
83
+ the first failure, and rejects transaction work that escapes its callback.
84
+
85
+ ### Patch Changes
86
+
87
+ - b6389e4: Cache bounded, database-local MySQL row-decoder plans for repeated result metadata across buffered, prepared, transactional, and streaming execution.
88
+ - b6389e4: Cache immutable SQL rendering skeletons for prepared query factories so repeated calls only bind changing values while still rejecting structural drift before driver dispatch.
89
+ - eb16de7: Compile MySQL result-field decoders once per result and avoid copying rows when runtime type-policy
90
+ decoding does not change their values. This removes repeated field scans and makes buffered decoding
91
+ scale linearly with result width.
92
+ - eb16de7: Own in-flight transaction executions through settlement so unawaited work can never race commit, savepoint release, rollback, or connection release.
93
+
94
+ The PostgreSQL adapter now also rejects pg's client-side `query_timeout` option because it can settle before the connection is safe to reuse. Root batches discard checked-out clients after query rejection, while caught transaction query, batch, and stream failures force rollback and discard the lease. Use PostgreSQL's server-enforced `statement_timeout` for statement deadlines.
95
+ - eb16de7: Allow adapters to retain enriched capabilities in transaction callbacks and nested transactions
96
+ through a self-typed core database contract. Transaction cleanup now also preserves the original
97
+ operation error when rollback or connection-release cleanup fails.
98
+ - 1563a7a: Declare and enforce the 1.0 package stability boundary. Core SQL, compiler, schema, config, AST,
99
+ PostgreSQL, MySQL, and CLI packages form the stable train; the TypeScript preview bridge and
100
+ language server remain explicitly experimental. Freeze public entrypoints and query type contracts,
101
+ and remove internal compiler/type helpers from stable package-root exports before 1.0.
102
+ - 9dd6bc4: Finalize dialect contract version 3 with explicit identifier quoting and grammar-owned capability
103
+ declarations. Accept third-party snapshot dialects, validate grammar versions, and document the
104
+ public grammar-authoring and conformance workflow.
105
+ - 16e2475: Prove npm trusted publishing and provenance after the initial registry bootstrap.
106
+ - 642cebd: Prove and document runtime codec fidelity against live PostgreSQL and MySQL values. PostgreSQL now
107
+ delegates non-policy OIDs to the installed pg parser table, MySQL maps BIT to Uint8Array, and the
108
+ mysql2 adapter rejects pool settings that would contradict its type policy.
109
+ - bd26d6e: Replace potentially expensive parser regular expressions with bounded scanners, tighten editor
110
+ completion matching, and prevent releases while high-severity CodeQL alerts remain open.
111
+ - 3e2c75c: Infer ordered query parameter tuples and let TypeScript reject interpolation values that do not
112
+ match their SQL context. Dialect contract version 2 adds explicit parameter analysis; unresolved
113
+ positions remain `unknown`. Add typed nullable predicate composition through `sql.fragment()`,
114
+ `sql.and()`, `sql.or()`, `sql.where()`, and `sql.append()` while preserving row and parameter tuples.
115
+ Direct append fragments are grammar-analyzed cumulatively against their static base, so TypeScript
116
+ rejects fragment interpolation values that disagree with the referenced database columns.
117
+ Add `sql.empty` and SQL-template-native conditional structural fragments. The compiler analyzes
118
+ complete branch variants, preserves literal boolean-dependent result rows, and type-checks nested
119
+ fragment parameters without adding a query-builder DSL. Bound independent structural expansion at
120
+ 64 variants by default, correlate repeated conditions, merge diagnostics and fragment expectations
121
+ across variants, and fail closed on incompatible contexts. Share indexed catalog and conservative
122
+ parameter-resolution primitives across grammars, harden cooked-template scanning, and add runtime,
123
+ resolver, scanner, and structural performance gates.
124
+ - Updated dependencies [eb16de7]
125
+ - Updated dependencies [b6389e4]
126
+ - Updated dependencies [eb16de7]
127
+ - Updated dependencies [b6389e4]
128
+ - Updated dependencies [eb16de7]
129
+ - Updated dependencies [1563a7a]
130
+ - Updated dependencies [9dd6bc4]
131
+ - Updated dependencies [7ca256b]
132
+ - Updated dependencies [16e2475]
133
+ - Updated dependencies [69c7d87]
134
+ - Updated dependencies [3e2c75c]
135
+ - @typed-sql/core@1.0.0
136
+ - @typed-sql/ast@1.0.0
137
+ - @typed-sql/schema@1.0.0
138
+
3
139
  ## 1.0.0-rc.0
4
140
 
5
141
  ### Patch Changes
package/README.md CHANGED
@@ -1,83 +1,72 @@
1
1
  # @typed-sql/mysql
2
2
 
3
- MySQL grammar, catalog introspection, exact result inference, type policy, runtime codecs, and an
4
- optional application-owned `mysql2` adapter for [typed-sql](https://github.com/Lojhan/typed-sql).
3
+ The stable MySQL grammar for [typed-sql](https://github.com/Lojhan/typed-sql), including catalog
4
+ introspection, row and parameter inference, type policy, runtime codecs, and an optional
5
+ application-owned `mysql2` adapter, native live verifier, and structured-plan inspector.
5
6
 
6
7
  ```sh
7
- pnpm add @typed-sql/core@next @typed-sql/mysql@next mysql2
8
- pnpm add -D @typed-sql/cli@next typescript@7.0.2
8
+ pnpm add @typed-sql/core @typed-sql/mysql mysql2
9
+ pnpm add -D @typed-sql/cli typescript@7.0.2
9
10
  ```
10
11
 
11
- `mysql2` is intentionally not a dependency or peer dependency of this package. It is loaded only
12
- when an application imports `@typed-sql/mysql/mysql2`.
13
-
14
- ## Configure and generate
15
-
16
- ```ts
17
- import { defineConfig } from "@typed-sql/core";
18
- import { mysql, typePolicy } from "@typed-sql/mysql";
19
- import { mysql2 } from "@typed-sql/mysql/mysql2";
20
-
21
- export default defineConfig({
22
- dialect: mysql({ typePolicy }),
23
- schema: {
24
- file: "generated/db/schema.json",
25
- provider: mysql2({
26
- connectionUri: () => process.env.DATABASE_URL!,
27
- schemas: ["app"],
28
- typePolicy,
29
- }),
30
- },
31
- outDir: "generated/db",
32
- projects: ["tsconfig.json"],
33
- typePolicy,
34
- });
35
- ```
36
-
37
- ## Query and execute
12
+ `mysql2` is loaded only through `@typed-sql/mysql/mysql2`; it is not a dependency or peer dependency
13
+ of the grammar.
38
14
 
39
15
  ```ts
40
- import { sql, typePolicy } from "@typed-sql/mysql";
16
+ import { requireAdapterCapability } from "@typed-sql/core";
17
+ import { mysqlBulk, sql, typePolicy } from "@typed-sql/mysql";
41
18
  import { createMySql2Database } from "@typed-sql/mysql/mysql2";
42
19
 
43
20
  const query = sql`
44
- SELECT account.id, account.email, account.status, project.budget
21
+ SELECT account.id, account.email, project.budget
45
22
  FROM users AS account
46
23
  LEFT JOIN projects AS project ON project.owner_id = account.id
47
- ORDER BY account.id
48
24
  `;
49
25
 
50
26
  const database = await createMySql2Database({
51
27
  connectionUri: process.env.DATABASE_URL!,
52
28
  typePolicy,
29
+ // observer: createOpenTelemetryObserver(),
53
30
  });
54
31
 
55
32
  const rows = await database.execute(query);
56
- // readonly {
57
- // id: bigint;
58
- // email: string;
59
- // status: "active" | "suspended";
60
- // budget: string | null;
61
- // }[]
62
- ```
63
33
 
64
- The adapter enables lossless bigint/decimal defaults, explicit alternative codecs, catalog
65
- introspection, and nested savepoints without changing global `mysql2` behavior. It rejects
66
- `poolConfig` options that would contradict the selected type policy. See the tested
67
- [runtime codec matrix](https://github.com/Lojhan/typed-sql/blob/main/docs/CODEC_FIDELITY.md#mysql-and-mysql2).
34
+ const accountById = database.prepare("account-by-id", (id: bigint) => sql`
35
+ SELECT account.id, account.email
36
+ FROM users AS account
37
+ WHERE account.id = ${id}
38
+ `);
39
+
40
+ const [selectedAccounts, allAccounts] = await database.batch([accountById(42n), query]);
68
41
 
69
- ## Supported SQL
42
+ for await (const account of database.stream(accountById(42n), { batchSize: 500 })) {
43
+ // account retains the query's inferred row type
44
+ }
70
45
 
71
- The grammar targets MySQL 8.4 LTS and supports aliases and stars, inner/outer/cross joins, CTEs,
72
- derived and correlated subqueries, grouping, aggregates, windows, `CASE`, scalar/EXISTS/IN/BETWEEN
73
- expressions, common JSON functions/operators, and `INSERT`/`UPDATE`/`DELETE` command typing. Catalog
74
- inference covers enums, unsigned integers, decimals, JSON, dates, binary values and `tinyint(1)`
75
- policy mapping. Ordered parameters infer from column comparisons, DML targets, casts, ranges,
76
- limits, and cataloged function arguments; positions without enough evidence remain `unknown`.
46
+ const bulk = requireAdapterCapability(database, mysqlBulk);
47
+ await bulk.loadData(
48
+ (account: { readonly id: bigint; readonly email: string }) =>
49
+ sql`INSERT INTO users (id, email) VALUES (${account.id}, ${account.email})`,
50
+ accounts,
51
+ );
52
+ ```
77
53
 
78
- Recursive CTE inference, `FULL JOIN`, array constructors, aggregate `FILTER` and incompatible
79
- `RETURNING` clauses produce `TSQ401`. Commands without a result surface infer
80
- `Query<never, Parameters>`.
81
- Unknown functions warn and infer `unknown`; ambiguous or structurally unsafe queries are errors.
54
+ The package root exports `sql`, `mysql`, and the MySQL type policy. The `/mysql2` entrypoint exports
55
+ the schema provider, execution adapter, `createMySql2LiveVerifier`, and `createMySql2PlanInspector`;
56
+ `/runtime` exposes driver-neutral MySQL rendering and codecs.
57
+
58
+ The root also exports `createMySqlRoutedDatabase`, the runtime semantic resolver, and the native
59
+ transaction retry classifier. These compose application-owned adapters without installing or
60
+ creating `mysql2` pools.
61
+
62
+ Read the [MySQL grammar guide](https://github.com/Lojhan/typed-sql/blob/main/docs/dialects/mysql.md),
63
+ [execution guide](https://github.com/Lojhan/typed-sql/blob/main/docs/guides/execution.md),
64
+ [bulk data guide](https://github.com/Lojhan/typed-sql/blob/main/docs/guides/bulk-data.md),
65
+ [observability guide](https://github.com/Lojhan/typed-sql/blob/main/docs/guides/observability.md),
66
+ [live verification guide](https://github.com/Lojhan/typed-sql/blob/main/docs/guides/live-verification.md),
67
+ [query plan governance guide](https://github.com/Lojhan/typed-sql/blob/main/docs/guides/query-plan-governance.md),
68
+ [routing and retry guide](https://github.com/Lojhan/typed-sql/blob/main/docs/guides/routing-and-retries.md),
69
+ [configuration](https://github.com/Lojhan/typed-sql/blob/main/docs/getting-started/configuration.md), and
70
+ [database type mappings](https://github.com/Lojhan/typed-sql/blob/main/docs/reference/type-mappings.md).
82
71
 
83
72
  MIT © typed-sql contributors
@@ -0,0 +1,22 @@
1
+ import { type ExecutionOptions, type Query } from "@typed-sql/core";
2
+ export interface MySqlBulkProgress {
3
+ readonly rows: number;
4
+ readonly bytes: number;
5
+ }
6
+ export interface MySqlBulkResult extends MySqlBulkProgress {
7
+ }
8
+ export interface MySqlLoadDataOptions extends ExecutionOptions {
9
+ /** Preferred encoded chunk size. One unusually wide row may exceed it. */
10
+ readonly chunkBytes?: number;
11
+ readonly onProgress?: (progress: MySqlBulkProgress) => void;
12
+ }
13
+ export interface MySqlBulkTransport {
14
+ loadData(statement: string, chunks: AsyncIterable<Uint8Array>, options: ExecutionOptions): Promise<void>;
15
+ }
16
+ export interface MySqlBulkCapability {
17
+ /** Compiles one typed INSERT factory into a client-streamed LOAD DATA LOCAL INFILE operation. */
18
+ loadData<Input, Row, Params extends readonly unknown[]>(rowQuery: (input: Input) => Query<Row, Params>, rows: Iterable<Input> | AsyncIterable<Input>, options?: MySqlLoadDataOptions): Promise<MySqlBulkResult>;
19
+ }
20
+ export declare const mysqlBulk: import("@typed-sql/core").AdapterCapability<MySqlBulkCapability>;
21
+ export declare function createMySqlBulkCapability(transport: MySqlBulkTransport): MySqlBulkCapability;
22
+ //# sourceMappingURL=bulk.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bulk.d.ts","sourceRoot":"","sources":["../../../../src/bulk.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,KAAK,gBAAgB,EACrB,KAAK,KAAK,EAGX,MAAM,iBAAiB,CAAC;AAOzB,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,eAAgB,SAAQ,iBAAiB;CAAG;AAE7D,MAAM,WAAW,oBAAqB,SAAQ,gBAAgB;IAC5D,0EAA0E;IAC1E,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,iBAAiB,KAAK,IAAI,CAAC;CAC7D;AAED,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,CAAC,UAAU,CAAC,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1G;AAED,MAAM,WAAW,mBAAmB;IAClC,iGAAiG;IACjG,QAAQ,CAAC,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,SAAS,OAAO,EAAE,EACpD,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EAC9C,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,GAAG,aAAa,CAAC,KAAK,CAAC,EAC5C,OAAO,CAAC,EAAE,oBAAoB,GAC7B,OAAO,CAAC,eAAe,CAAC,CAAC;CAC7B;AAED,eAAO,MAAM,SAAS,kEAAkE,CAAC;AAwGzF,wBAAgB,yBAAyB,CAAC,SAAS,EAAE,kBAAkB,GAAG,mBAAmB,CAqG5F"}
@@ -0,0 +1,205 @@
1
+ import { parseStatement } from "@typed-sql/ast";
2
+ import { bindQueryRenderSkeleton, compileQueryRenderSkeleton, defineAdapterCapability, QueryCancelledError, } from "@typed-sql/core";
3
+ const mysqlRenderer = Object.freeze({
4
+ placeholder: () => "?",
5
+ quoteIdentifier: (name) => `\`${name.replaceAll("`", "``")}\``,
6
+ });
7
+ export const mysqlBulk = defineAdapterCapability("mysql.load-data");
8
+ const encoder = new TextEncoder();
9
+ const DEFAULT_CHUNK_BYTES = 64 * 1_024;
10
+ function mysqlTextValue(value) {
11
+ if (typeof value === "string")
12
+ return value;
13
+ if (typeof value === "bigint")
14
+ return value.toString();
15
+ if (typeof value === "boolean")
16
+ return value ? "1" : "0";
17
+ if (typeof value === "number") {
18
+ if (!Number.isFinite(value))
19
+ throw new RangeError("MySQL LOAD DATA cannot encode non-finite numbers");
20
+ return String(value);
21
+ }
22
+ if (value instanceof Date) {
23
+ throw new TypeError("MySQL LOAD DATA text mode does not accept Date values because mysql2 timezone encoding is connection-specific; use ordinary execution");
24
+ }
25
+ if (value instanceof Uint8Array) {
26
+ throw new TypeError("MySQL LOAD DATA text mode does not accept binary values; use ordinary execution");
27
+ }
28
+ if (typeof value === "object" && value !== null) {
29
+ throw new TypeError("MySQL LOAD DATA text mode does not accept structured values because mysql2 parameter encoding is type-specific; use ordinary execution");
30
+ }
31
+ throw new TypeError(`MySQL LOAD DATA cannot encode ${typeof value} values`);
32
+ }
33
+ function escapedField(value) {
34
+ if (value === null || value === undefined)
35
+ return "\\N";
36
+ return mysqlTextValue(value)
37
+ .replaceAll("\\", "\\\\")
38
+ .replaceAll("\0", "\\0")
39
+ .replaceAll("\t", "\\t")
40
+ .replaceAll("\n", "\\n")
41
+ .replaceAll("\r", "\\r");
42
+ }
43
+ function encodedRow(values) {
44
+ return encoder.encode(`${values.map(escapedField).join("\t")}\n`);
45
+ }
46
+ function chunkSize(value) {
47
+ const resolved = value ?? DEFAULT_CHUNK_BYTES;
48
+ if (!Number.isSafeInteger(resolved) || resolved <= 0) {
49
+ throw new RangeError("MySQL LOAD DATA chunkBytes must be a positive safe integer");
50
+ }
51
+ return resolved;
52
+ }
53
+ function loadDataStatement(text, parameterCount) {
54
+ const statement = parseStatement(text, { syntax: "mysql" });
55
+ if (statement.kind !== "insert" ||
56
+ statement.with !== undefined ||
57
+ statement.table.alias !== undefined ||
58
+ statement.source.kind !== "values" ||
59
+ statement.source.rows.length !== 1 ||
60
+ statement.returning.length !== 0 ||
61
+ statement.columns.length === 0) {
62
+ throw new TypeError("MySQL LOAD DATA requires a plain single-row INSERT with an explicit column list and one VALUES row");
63
+ }
64
+ const values = statement.source.rows[0];
65
+ if (values.length !== statement.columns.length ||
66
+ values.length !== parameterCount ||
67
+ values.some((expression, index) => expression.kind !== "parameter" || expression.index !== index + 1)) {
68
+ throw new TypeError("MySQL LOAD DATA INSERT values must be one ordered parameter per target column");
69
+ }
70
+ const quote = mysqlRenderer.quoteIdentifier;
71
+ const table = `${statement.table.schema === undefined ? "" : `${quote(statement.table.schema.name)}.`}${quote(statement.table.name.name)}`;
72
+ const columns = statement.columns.map(({ name }) => quote(name)).join(", ");
73
+ return `LOAD DATA LOCAL INFILE 'typed-sql-stream' INTO TABLE ${table} CHARACTER SET utf8mb4 FIELDS TERMINATED BY '\\t' ESCAPED BY '\\\\' LINES TERMINATED BY '\\n' (${columns})`;
74
+ }
75
+ function cancelled(signal) {
76
+ if (signal?.aborted === true)
77
+ throw new QueryCancelledError("signal", { cause: signal.reason });
78
+ }
79
+ function asyncIterator(values) {
80
+ if (Symbol.asyncIterator in Object(values))
81
+ return values[Symbol.asyncIterator]();
82
+ const iterator = values[Symbol.iterator]();
83
+ return {
84
+ next: async () => iterator.next(),
85
+ ...(iterator.return === undefined ? {} : { return: async () => iterator.return() }),
86
+ };
87
+ }
88
+ function concatenate(chunks, length) {
89
+ if (chunks.length === 1)
90
+ return chunks[0];
91
+ const result = new Uint8Array(length);
92
+ let offset = 0;
93
+ for (const chunk of chunks) {
94
+ result.set(chunk, offset);
95
+ offset += chunk.byteLength;
96
+ }
97
+ return result;
98
+ }
99
+ export function createMySqlBulkCapability(transport) {
100
+ return Object.freeze({
101
+ async loadData(rowQuery, rows, options = {}) {
102
+ const preferredChunkBytes = chunkSize(options.chunkBytes);
103
+ cancelled(options.signal);
104
+ const iterator = asyncIterator(rows);
105
+ let iteratorClosed = false;
106
+ const closeIterator = async () => {
107
+ if (iteratorClosed || iterator.return === undefined)
108
+ return;
109
+ iteratorClosed = true;
110
+ await iterator.return();
111
+ };
112
+ let first;
113
+ try {
114
+ first = await iterator.next();
115
+ }
116
+ catch (error) {
117
+ try {
118
+ await closeIterator();
119
+ }
120
+ catch {
121
+ /* Preserve the producer failure. */
122
+ }
123
+ throw error;
124
+ }
125
+ if (first.done === true)
126
+ return Object.freeze({ rows: 0, bytes: 0 });
127
+ let firstQuery;
128
+ let compiled;
129
+ let statement;
130
+ try {
131
+ firstQuery = rowQuery(first.value);
132
+ compiled = compileQueryRenderSkeleton(firstQuery, mysqlRenderer);
133
+ statement = loadDataStatement(compiled.rendered.text, compiled.rendered.values.length);
134
+ }
135
+ catch (error) {
136
+ try {
137
+ await closeIterator();
138
+ }
139
+ catch {
140
+ /* Preserve the query compilation failure. */
141
+ }
142
+ throw error;
143
+ }
144
+ let rowCount = 0;
145
+ let byteCount = 0;
146
+ let inputComplete = false;
147
+ const chunks = (async function* () {
148
+ let pending = [];
149
+ let pendingBytes = 0;
150
+ let current = first;
151
+ try {
152
+ while (current.done !== true) {
153
+ cancelled(options.signal);
154
+ const query = rowCount === 0 ? firstQuery : rowQuery(current.value);
155
+ const rendered = rowCount === 0 ? compiled.rendered : bindQueryRenderSkeleton(query, compiled.skeleton);
156
+ if (rendered === undefined)
157
+ throw new TypeError("MySQL LOAD DATA row query changed its structural SQL shape");
158
+ const encoded = encodedRow(rendered.values);
159
+ if (pendingBytes > 0 && pendingBytes + encoded.byteLength > preferredChunkBytes) {
160
+ const chunk = concatenate(pending, pendingBytes);
161
+ byteCount += chunk.byteLength;
162
+ options.onProgress?.(Object.freeze({ rows: rowCount, bytes: byteCount }));
163
+ yield chunk;
164
+ pending = [];
165
+ pendingBytes = 0;
166
+ }
167
+ pending.push(encoded);
168
+ pendingBytes += encoded.byteLength;
169
+ rowCount += 1;
170
+ current = await iterator.next();
171
+ }
172
+ inputComplete = true;
173
+ if (pendingBytes > 0) {
174
+ const chunk = concatenate(pending, pendingBytes);
175
+ byteCount += chunk.byteLength;
176
+ options.onProgress?.(Object.freeze({ rows: rowCount, bytes: byteCount }));
177
+ yield chunk;
178
+ }
179
+ }
180
+ finally {
181
+ if (current.done !== true)
182
+ await closeIterator();
183
+ }
184
+ })();
185
+ try {
186
+ await transport.loadData(statement, chunks, options);
187
+ }
188
+ catch (error) {
189
+ if (!inputComplete) {
190
+ try {
191
+ await closeIterator();
192
+ }
193
+ catch {
194
+ /* Preserve the transport, producer, or database failure. */
195
+ }
196
+ }
197
+ throw error;
198
+ }
199
+ if (!inputComplete)
200
+ await closeIterator();
201
+ return Object.freeze({ rows: rowCount, bytes: byteCount });
202
+ },
203
+ });
204
+ }
205
+ //# sourceMappingURL=bulk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bulk.js","sourceRoot":"","sources":["../../../../src/bulk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EACL,uBAAuB,EACvB,0BAA0B,EAC1B,uBAAuB,EAGvB,mBAAmB,GAEpB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,aAAa,GAAgB,MAAM,CAAC,MAAM,CAAC;IAC/C,WAAW,EAAE,GAAG,EAAE,CAAC,GAAG;IACtB,eAAe,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE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 +1,26 @@
1
+ import type { MySqlTypePolicy } from "./type-policy.js";
2
+ export interface MySqlFieldLike {
3
+ readonly name: string;
4
+ readonly columnType: number;
5
+ readonly columnLength?: number;
6
+ }
7
+ export type MySqlRuntimeTypePolicy = Pick<MySqlTypePolicy, "bigint" | "decimal" | "date" | "json" | "tinyint1">;
8
+ type ValueDecoder = (value: unknown) => unknown;
9
+ export interface MySqlColumnDecoder {
10
+ readonly name: string;
11
+ readonly decode: ValueDecoder;
12
+ }
13
+ export declare function encodeMySqlValue(value: unknown): unknown;
14
+ /** Compiles immutable field metadata into a decoder plan shared by buffered and streamed rows. */
15
+ export declare function compileMySqlRowDecoders(fields: readonly MySqlFieldLike[], typePolicy: MySqlRuntimeTypePolicy, decimal?: (value: string) => unknown): readonly MySqlColumnDecoder[];
16
+ /** Database-local bounded cache for immutable decoder plans derived from native result metadata. */
17
+ export declare class MySqlDecoderPlanCache {
18
+ #private;
19
+ constructor(typePolicy: MySqlRuntimeTypePolicy, decimal?: (value: string) => unknown, capacity?: number);
20
+ get(fields: readonly MySqlFieldLike[]): readonly MySqlColumnDecoder[];
21
+ }
22
+ export declare function decodeMySqlRows(rows: readonly Record<string, unknown>[], decoders: readonly MySqlColumnDecoder[]): readonly Record<string, unknown>[];
23
+ /** Decodes one streamed row without allocating an intermediate one-element array. */
24
+ export declare function decodeMySqlRow(row: Record<string, unknown>, decoders: readonly MySqlColumnDecoder[]): Record<string, unknown>;
25
+ export {};
26
+ //# sourceMappingURL=decoding.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decoding.d.ts","sourceRoot":"","sources":["../../../../src/decoding.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,YAAY,CAAC,EAAE,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