@typed-sql/postgres 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/README.md +29 -4
  3. package/dist/packages/postgres/src/bulk.d.ts +30 -0
  4. package/dist/packages/postgres/src/bulk.d.ts.map +1 -0
  5. package/dist/packages/postgres/src/bulk.js +228 -0
  6. package/dist/packages/postgres/src/bulk.js.map +1 -0
  7. package/dist/packages/postgres/src/index.d.ts +5 -1
  8. package/dist/packages/postgres/src/index.d.ts.map +1 -1
  9. package/dist/packages/postgres/src/index.js +17 -4
  10. package/dist/packages/postgres/src/index.js.map +1 -1
  11. package/dist/packages/postgres/src/pg.d.ts +57 -2
  12. package/dist/packages/postgres/src/pg.d.ts.map +1 -1
  13. package/dist/packages/postgres/src/pg.js +346 -2
  14. package/dist/packages/postgres/src/pg.js.map +1 -1
  15. package/dist/packages/postgres/src/provider.d.ts +2 -1
  16. package/dist/packages/postgres/src/provider.d.ts.map +1 -1
  17. package/dist/packages/postgres/src/provider.js +3 -1
  18. package/dist/packages/postgres/src/provider.js.map +1 -1
  19. package/dist/packages/postgres/src/resolver.d.ts.map +1 -1
  20. package/dist/packages/postgres/src/resolver.js +11 -1
  21. package/dist/packages/postgres/src/resolver.js.map +1 -1
  22. package/dist/packages/postgres/src/routing.d.ts +22 -0
  23. package/dist/packages/postgres/src/routing.d.ts.map +1 -0
  24. package/dist/packages/postgres/src/routing.js +70 -0
  25. package/dist/packages/postgres/src/routing.js.map +1 -0
  26. package/dist/packages/postgres/src/runtime.d.ts +14 -1
  27. package/dist/packages/postgres/src/runtime.d.ts.map +1 -1
  28. package/dist/packages/postgres/src/runtime.js +440 -28
  29. package/dist/packages/postgres/src/runtime.js.map +1 -1
  30. package/dist/packages/postgres/src/semantics.d.ts +5 -0
  31. package/dist/packages/postgres/src/semantics.d.ts.map +1 -0
  32. package/dist/packages/postgres/src/semantics.js +211 -0
  33. package/dist/packages/postgres/src/semantics.js.map +1 -0
  34. package/dist/packages/postgres/src/stream.d.ts +7 -7
  35. package/dist/packages/postgres/src/stream.d.ts.map +1 -1
  36. package/dist/packages/postgres/src/stream.js.map +1 -1
  37. package/dist/packages/postgres/src/version.d.ts +2 -0
  38. package/dist/packages/postgres/src/version.d.ts.map +1 -0
  39. package/dist/packages/postgres/src/version.js +2 -0
  40. package/dist/packages/postgres/src/version.js.map +1 -0
  41. package/package.json +4 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,118 @@
1
1
  # @typed-sql/postgres
2
2
 
3
+ ## 2.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 29afc3d: Add conservative semantic primary/replica routing over application-owned databases, scoped
8
+ read-after-write pinning, explicit role requirements, stable unsafe-route errors, dialect runtime
9
+ semantic resolvers, and bounded abortable transaction retry policies with native PostgreSQL and
10
+ MySQL error classifiers. Parse and classify dialect locking reads so uncertain or affine work
11
+ always fails closed to primary.
12
+ - 6a7ae58: Add opt-in live query verification through grammar-owned PostgreSQL PREPARE and MySQL
13
+ COM_STMT_PREPARE adapters, bounded neutral comparison, deterministic secret-free proof artifacts,
14
+ offline cache validation, explicit unsupported classifications, CLI workflows, real database E2E,
15
+ and performance budgets.
16
+ - b06fd0a: Add grammar-neutral optional adapter capability discovery, typed PostgreSQL COPY import and export
17
+ through application-owned `pg-copy-streams`, and typed MySQL LOAD DATA import through mysql2's
18
+ application-owned infile stream. Bulk transfers preserve ordinary `INSERT` parameter evidence,
19
+ enforce structural row stability, apply bounded backpressure, support cancellation and progress,
20
+ and integrate with transaction ownership and conservative connection cleanup.
21
+ - 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.
22
+ - 1b054b6: Add an adapter-neutral, redacted database observation lifecycle for queries, cardinality contracts,
23
+ batches, PostgreSQL pipelines, streams, cancellation, and nested transactions. Runtime fingerprints
24
+ correlate with compiler structural variants while SQL, parameter values, connection configuration,
25
+ and driver causes remain excluded by default. Publish the optional OpenTelemetry bridge with current
26
+ database semantic conventions and explicit high-cardinality or exception-capture opt-ins.
27
+ - 87189c3: Add grammar-neutral `all`, `one`, and `maybeOne` execution with exact row types, stable cardinality
28
+ and cancellation errors, explicit adapter capabilities, AbortSignal support, and absolute deadlines.
29
+ The pg and mysql2 adapters conservatively discard interrupted connections, including transaction
30
+ leases, while the existing uncontrolled `execute` path remains unchanged.
31
+ - e654fae: Add opt-in Standard Schema V1 result validation with compile-time output compatibility, immutable
32
+ query attachment, sync and async validators, redacted fingerprinted errors, and consistent decoded-row
33
+ handling across buffered cardinality methods, batches, PostgreSQL pipelines, streams, and transactions.
34
+ - b2ec119: Add opt-in, grammar-neutral query-plan governance with PostgreSQL and MySQL structured EXPLAIN
35
+ adapters, transient application-owned samples, redacted fingerprint-keyed artifacts, absolute and
36
+ comparable regression budgets, explicit uncertainty, CLI capture and review, documentation, and
37
+ performance coverage.
38
+
39
+ ### Patch Changes
40
+
41
+ - Updated dependencies [7ea5d2f]
42
+ - Updated dependencies [29afc3d]
43
+ - Updated dependencies [3f063f6]
44
+ - Updated dependencies [6a7ae58]
45
+ - Updated dependencies [af27a0e]
46
+ - Updated dependencies [b06fd0a]
47
+ - Updated dependencies [3050209]
48
+ - Updated dependencies [1b054b6]
49
+ - Updated dependencies [b4f1b6e]
50
+ - Updated dependencies [87189c3]
51
+ - Updated dependencies [e654fae]
52
+ - Updated dependencies [b2ec119]
53
+ - @typed-sql/core@2.0.0
54
+ - @typed-sql/ast@2.0.0
55
+ - @typed-sql/schema@2.0.0
56
+
57
+ ## 2.0.0-rc.1
58
+
59
+ ### Patch Changes
60
+
61
+ - Publish the coherent 2.0.0-rc.1 release-candidate train.
62
+
63
+ ## 2.0.0-rc.0
64
+
65
+ ### Major Changes
66
+
67
+ - 29afc3d: Add conservative semantic primary/replica routing over application-owned databases, scoped
68
+ read-after-write pinning, explicit role requirements, stable unsafe-route errors, dialect runtime
69
+ semantic resolvers, and bounded abortable transaction retry policies with native PostgreSQL and
70
+ MySQL error classifiers. Parse and classify dialect locking reads so uncertain or affine work
71
+ always fails closed to primary.
72
+ - 6a7ae58: Add opt-in live query verification through grammar-owned PostgreSQL PREPARE and MySQL
73
+ COM_STMT_PREPARE adapters, bounded neutral comparison, deterministic secret-free proof artifacts,
74
+ offline cache validation, explicit unsupported classifications, CLI workflows, real database E2E,
75
+ and performance budgets.
76
+ - b06fd0a: Add grammar-neutral optional adapter capability discovery, typed PostgreSQL COPY import and export
77
+ through application-owned `pg-copy-streams`, and typed MySQL LOAD DATA import through mysql2's
78
+ application-owned infile stream. Bulk transfers preserve ordinary `INSERT` parameter evidence,
79
+ enforce structural row stability, apply bounded backpressure, support cancellation and progress,
80
+ and integrate with transaction ownership and conservative connection cleanup.
81
+ - 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.
82
+ - 1b054b6: Add an adapter-neutral, redacted database observation lifecycle for queries, cardinality contracts,
83
+ batches, PostgreSQL pipelines, streams, cancellation, and nested transactions. Runtime fingerprints
84
+ correlate with compiler structural variants while SQL, parameter values, connection configuration,
85
+ and driver causes remain excluded by default. Publish the optional OpenTelemetry bridge with current
86
+ database semantic conventions and explicit high-cardinality or exception-capture opt-ins.
87
+ - 87189c3: Add grammar-neutral `all`, `one`, and `maybeOne` execution with exact row types, stable cardinality
88
+ and cancellation errors, explicit adapter capabilities, AbortSignal support, and absolute deadlines.
89
+ The pg and mysql2 adapters conservatively discard interrupted connections, including transaction
90
+ leases, while the existing uncontrolled `execute` path remains unchanged.
91
+ - e654fae: Add opt-in Standard Schema V1 result validation with compile-time output compatibility, immutable
92
+ query attachment, sync and async validators, redacted fingerprinted errors, and consistent decoded-row
93
+ handling across buffered cardinality methods, batches, PostgreSQL pipelines, streams, and transactions.
94
+ - b2ec119: Add opt-in, grammar-neutral query-plan governance with PostgreSQL and MySQL structured EXPLAIN
95
+ adapters, transient application-owned samples, redacted fingerprint-keyed artifacts, absolute and
96
+ comparable regression budgets, explicit uncertainty, CLI capture and review, documentation, and
97
+ performance coverage.
98
+
99
+ ### Patch Changes
100
+
101
+ - Updated dependencies [29afc3d]
102
+ - Updated dependencies [3f063f6]
103
+ - Updated dependencies [6a7ae58]
104
+ - Updated dependencies [af27a0e]
105
+ - Updated dependencies [b06fd0a]
106
+ - Updated dependencies [3050209]
107
+ - Updated dependencies [1b054b6]
108
+ - Updated dependencies [b4f1b6e]
109
+ - Updated dependencies [87189c3]
110
+ - Updated dependencies [e654fae]
111
+ - Updated dependencies [b2ec119]
112
+ - @typed-sql/ast@2.0.0-rc.0
113
+ - @typed-sql/core@2.0.0-rc.0
114
+ - @typed-sql/schema@2.0.0-rc.0
115
+
3
116
  ## 1.0.0
4
117
 
5
118
  ### Major Changes
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  The stable PostgreSQL grammar for [typed-sql](https://github.com/Lojhan/typed-sql), including
4
4
  catalog introspection, row and parameter inference, type policy, runtime codecs, and an optional
5
- application-owned `pg` adapter.
5
+ application-owned `pg` adapter, native live verifier, and structured-plan inspector.
6
6
 
7
7
  ```sh
8
8
  pnpm add @typed-sql/core @typed-sql/postgres pg
@@ -16,8 +16,15 @@ the grammar. Applications that stream rows also install the optional application
16
16
  pnpm add pg-cursor
17
17
  ```
18
18
 
19
+ Applications that use PostgreSQL COPY also install its optional application-owned stream:
20
+
21
+ ```sh
22
+ pnpm add pg-copy-streams
23
+ ```
24
+
19
25
  ```ts
20
- import { sql, typePolicy } from "@typed-sql/postgres";
26
+ import { requireAdapterCapability } from "@typed-sql/core";
27
+ import { postgresCopy, sql, typePolicy } from "@typed-sql/postgres";
21
28
  import { createPgDatabase } from "@typed-sql/postgres/pg";
22
29
 
23
30
  const query = sql`
@@ -30,6 +37,8 @@ const database = await createPgDatabase({
30
37
  connectionString: process.env.DATABASE_URL!,
31
38
  poolConfig: { pipeline: true },
32
39
  typePolicy,
40
+ copyStreamsImporter: () => import("pg-copy-streams"),
41
+ // observer: createOpenTelemetryObserver(),
33
42
  });
34
43
 
35
44
  // pipeline() requires the application-owned pg 8.23.0 or newer.
@@ -48,14 +57,30 @@ const [pipelinedAccount, pipelinedAll] = await database.pipeline([accountById(42
48
57
  for await (const account of database.stream(accountById(42n), { batchSize: 500 })) {
49
58
  // account retains the query's inferred row type
50
59
  }
60
+
61
+ const copy = requireAdapterCapability(database, postgresCopy);
62
+ await copy.copyFrom(
63
+ (account: { readonly id: bigint; readonly email: string }) =>
64
+ sql`INSERT INTO users (id, email) VALUES (${account.id}, ${account.email})`,
65
+ accounts,
66
+ );
51
67
  ```
52
68
 
53
69
  The package root exports `sql`, `postgres`, and the PostgreSQL type policy. The `/pg` entrypoint
54
- exports the schema provider and execution adapter; `/runtime` exposes driver-neutral PostgreSQL
55
- rendering and codecs.
70
+ exports the schema provider, execution adapter, `createPgLiveVerifier`, and `createPgPlanInspector`;
71
+ `/runtime` exposes driver-neutral PostgreSQL rendering and codecs.
72
+
73
+ The root also exports `createPostgresRoutedDatabase`, the runtime semantic resolver, and the native
74
+ transaction retry classifier. These compose application-owned adapters without installing or
75
+ creating `pg` pools.
56
76
 
57
77
  Read the [PostgreSQL grammar guide](https://github.com/Lojhan/typed-sql/blob/main/docs/dialects/postgresql.md),
58
78
  [execution guide](https://github.com/Lojhan/typed-sql/blob/main/docs/guides/execution.md),
79
+ [bulk data guide](https://github.com/Lojhan/typed-sql/blob/main/docs/guides/bulk-data.md),
80
+ [observability guide](https://github.com/Lojhan/typed-sql/blob/main/docs/guides/observability.md),
81
+ [live verification guide](https://github.com/Lojhan/typed-sql/blob/main/docs/guides/live-verification.md),
82
+ [query plan governance guide](https://github.com/Lojhan/typed-sql/blob/main/docs/guides/query-plan-governance.md),
83
+ [routing and retry guide](https://github.com/Lojhan/typed-sql/blob/main/docs/guides/routing-and-retries.md),
59
84
  [configuration](https://github.com/Lojhan/typed-sql/blob/main/docs/getting-started/configuration.md), and
60
85
  [database type mappings](https://github.com/Lojhan/typed-sql/blob/main/docs/reference/type-mappings.md).
61
86
 
@@ -0,0 +1,30 @@
1
+ import { type ExecutionOptions, type Query, type QueryStream } from "@typed-sql/core";
2
+ export interface PostgresCopyProgress {
3
+ readonly rows: number;
4
+ readonly bytes: number;
5
+ }
6
+ export interface PostgresCopyResult extends PostgresCopyProgress {
7
+ }
8
+ export interface PostgresCopyFromOptions extends ExecutionOptions {
9
+ /** Preferred encoded chunk size. One unusually wide row may exceed it. */
10
+ readonly chunkBytes?: number;
11
+ readonly onProgress?: (progress: PostgresCopyProgress) => void;
12
+ }
13
+ export interface PostgresCopyToOptions extends ExecutionOptions {
14
+ }
15
+ export interface PostgresCopyTransport {
16
+ copyFrom(statement: string, chunks: AsyncIterable<Uint8Array>, options: ExecutionOptions): Promise<void>;
17
+ copyTo(statement: string, options: ExecutionOptions): QueryStream<Uint8Array>;
18
+ }
19
+ export interface PostgresCopyCapability {
20
+ /**
21
+ * Compiles one ordinary typed single-row INSERT factory into COPY FROM STDIN.
22
+ * Every later row must preserve the first query's exact structural shape.
23
+ */
24
+ copyFrom<Input, Row, Params extends readonly unknown[]>(rowQuery: (input: Input) => Query<Row, Params>, rows: Iterable<Input> | AsyncIterable<Input>, options?: PostgresCopyFromOptions): Promise<PostgresCopyResult>;
25
+ /** Streams raw PostgreSQL CSV bytes for a static typed SELECT query. */
26
+ copyTo<Row>(query: Query<Row, readonly []>, options?: PostgresCopyToOptions): QueryStream<Uint8Array>;
27
+ }
28
+ export declare const postgresCopy: import("@typed-sql/core").AdapterCapability<PostgresCopyCapability>;
29
+ export declare function createPostgresCopyCapability(transport: Postg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B,GAChC,OAAO,CAAC,kBAAkB,CAAC,CAAC;IAE/B,wEAAwE;IACxE,MAAM,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,EAAE,SAAS,EAAE,CAAC,EAAE,OAAO,CAAC,EAAE,qBAAqB,GAAG,WAAW,CAAC,UAAU,CAAC,CAAC;CACvG;AAED,eAAO,MAAM,YAAY,qEAAmE,CAAC;AAqH7F,wBAAgB,4BAA4B,CAAC,SAAS,EAAE,qBAAqB,GAAG,sBAAsB,CA2GrG"}
@@ -0,0 +1,228 @@
1
+ import { parseStatement } from "@typed-sql/ast";
2
+ import { bindQueryRenderSkeleton, compileQueryRenderSkeleton, defineAdapterCapability, QueryCancelledError, } from "@typed-sql/core";
3
+ const postgresRenderer = Object.freeze({
4
+ placeholder: (index) => `$${index}`,
5
+ quoteIdentifier: (name) => `"${name.replaceAll('"', '""')}"`,
6
+ });
7
+ export const postgresCopy = defineAdapterCapability("postgres.copy");
8
+ const encoder = new TextEncoder();
9
+ const DEFAULT_CHUNK_BYTES = 64 * 1_024;
10
+ function quoteIdentifier(value) {
11
+ return postgresRenderer.quoteIdentifier(value);
12
+ }
13
+ function postgresArrayElement(value) {
14
+ if (value === null || value === undefined)
15
+ return "NULL";
16
+ if (Array.isArray(value))
17
+ return postgresArray(value);
18
+ const encoded = postgresTextValue(value);
19
+ return `"${encoded.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
20
+ }
21
+ function postgresArray(value) {
22
+ return `{${value.map(postgresArrayElement).join(",")}}`;
23
+ }
24
+ function postgresTextValue(value) {
25
+ if (typeof value === "string")
26
+ return value;
27
+ if (typeof value === "bigint" || typeof value === "boolean")
28
+ return String(value);
29
+ if (typeof value === "number") {
30
+ if (!Number.isFinite(value))
31
+ throw new RangeError("PostgreSQL COPY cannot encode non-finite numbers");
32
+ return String(value);
33
+ }
34
+ if (value instanceof Date) {
35
+ if (Number.isNaN(value.getTime()))
36
+ throw new RangeError("PostgreSQL COPY cannot encode an invalid Date");
37
+ return value.toISOString();
38
+ }
39
+ if (value instanceof Uint8Array)
40
+ return `\\x${Buffer.from(value).toString("hex")}`;
41
+ if (Array.isArray(value))
42
+ return postgresArray(value);
43
+ if (typeof value === "object" && value !== null)
44
+ return JSON.stringify(value);
45
+ throw new TypeError(`PostgreSQL COPY cannot encode ${typeof value} values`);
46
+ }
47
+ function csvField(value) {
48
+ if (value === null || value === undefined)
49
+ return "";
50
+ return `"${postgresTextValue(value).replaceAll('"', '""')}"`;
51
+ }
52
+ function csvRow(values) {
53
+ return encoder.encode(`${values.map(csvField).join(",")}\n`);
54
+ }
55
+ function chunkSize(value) {
56
+ const resolved = value ?? DEFAULT_CHUNK_BYTES;
57
+ if (!Number.isSafeInteger(resolved) || resolved <= 0) {
58
+ throw new RangeError("PostgreSQL COPY chunkBytes must be a positive safe integer");
59
+ }
60
+ return resolved;
61
+ }
62
+ function copyFromStatement(text, parameterCount) {
63
+ const statement = parseStatement(text);
64
+ if (statement.kind !== "insert" ||
65
+ statement.with !== undefined ||
66
+ statement.table.alias !== undefined ||
67
+ statement.source.kind !== "values" ||
68
+ statement.source.rows.length !== 1 ||
69
+ statement.returning.length !== 0 ||
70
+ statement.columns.length === 0) {
71
+ throw new TypeError("PostgreSQL COPY requires a plain single-row INSERT with an explicit column list, one VALUES row, and no RETURNING clause");
72
+ }
73
+ const values = statement.source.rows[0];
74
+ if (values.length !== statement.columns.length ||
75
+ values.length !== parameterCount ||
76
+ values.some((expression, index) => expression.kind !== "parameter" || expression.index !== index + 1)) {
77
+ throw new TypeError("PostgreSQL COPY INSERT values must be one ordered parameter per target column");
78
+ }
79
+ const table = `${statement.table.schema === undefined ? "" : `${quoteIdentifier(statement.table.schema.name)}.`}${quoteIdentifier(statement.table.name.name)}`;
80
+ const columns = statement.columns.map(({ name }) => quoteIdentifier(name)).join(", ");
81
+ return `COPY ${table} (${columns}) FROM STDIN WITH (FORMAT csv)`;
82
+ }
83
+ function copyToStatement(query) {
84
+ const { rendered } = compileQueryRenderSkeleton(query, postgresRenderer);
85
+ if (rendered.values.length !== 0)
86
+ throw new TypeError("PostgreSQL COPY TO accepts only static queries without parameters");
87
+ const text = rendered.text.trim().replace(/;\s*$/u, "");
88
+ if (parseStatement(text).kind !== "select") {
89
+ throw new TypeError("PostgreSQL COPY TO requires a SELECT query");
90
+ }
91
+ return `COPY (${text}) TO STDOUT WITH (FORMAT csv)`;
92
+ }
93
+ function cancelled(signal) {
94
+ if (signal?.aborted === true)
95
+ throw new QueryCancelledError("signal", { cause: signal.reason });
96
+ }
97
+ function asyncIterator(values) {
98
+ if (Symbol.asyncIterator in Object(values))
99
+ return values[Symbol.asyncIterator]();
100
+ const iterator = values[Symbol.iterator]();
101
+ return {
102
+ next: async () => iterator.next(),
103
+ ...(iterator.return === undefined ? {} : { return: async () => iterator.return() }),
104
+ };
105
+ }
106
+ function concatenate(chunks, length) {
107
+ if (chunks.length === 1)
108
+ return chunks[0];
109
+ const result = new Uint8Array(length);
110
+ let offset = 0;
111
+ for (const chunk of chunks) {
112
+ result.set(chunk, offset);
113
+ offset += chunk.byteLength;
114
+ }
115
+ return result;
116
+ }
117
+ export function createPostgresCopyCapability(transport) {
118
+ return Object.freeze({
119
+ async copyFrom(rowQuery, rows, options = {}) {
120
+ const preferredChunkBytes = chunkSize(options.chunkBytes);
121
+ cancelled(options.signal);
122
+ const iterator = asyncIterator(rows);
123
+ let iteratorClosed = false;
124
+ const closeIterator = async () => {
125
+ if (iteratorClosed || iterator.return === undefined)
126
+ return;
127
+ iteratorClosed = true;
128
+ await iterator.return();
129
+ };
130
+ let first;
131
+ try {
132
+ first = await iterator.next();
133
+ }
134
+ catch (error) {
135
+ try {
136
+ await closeIterator();
137
+ }
138
+ catch {
139
+ /* Preserve the producer failure. */
140
+ }
141
+ throw error;
142
+ }
143
+ if (first.done === true)
144
+ return Object.freeze({ rows: 0, bytes: 0 });
145
+ let firstQuery;
146
+ let compiled;
147
+ let statement;
148
+ try {
149
+ firstQuery = rowQuery(first.value);
150
+ compiled = compileQueryRenderSkeleton(firstQuery, postgresRenderer);
151
+ statement = copyFromStatement(compiled.rendered.text, compiled.rendered.values.length);
152
+ }
153
+ catch (error) {
154
+ try {
155
+ await closeIterator();
156
+ }
157
+ catch {
158
+ /* Preserve the query compilation failure. */
159
+ }
160
+ throw error;
161
+ }
162
+ let rowCount = 0;
163
+ let byteCount = 0;
164
+ let inputComplete = false;
165
+ const chunks = (async function* () {
166
+ let pending = [];
167
+ let pendingBytes = 0;
168
+ let current = first;
169
+ try {
170
+ while (current.done !== true) {
171
+ cancelled(options.signal);
172
+ const query = rowCount === 0 ? firstQuery : rowQuery(current.value);
173
+ const rendered = rowCount === 0 ? compiled.rendered : bindQueryRenderSkeleton(query, compiled.skeleton);
174
+ if (rendered === undefined) {
175
+ throw new TypeError("PostgreSQL COPY row query changed its structural SQL shape");
176
+ }
177
+ const encoded = csvRow(rendered.values);
178
+ if (pendingBytes > 0 && pendingBytes + encoded.byteLength > preferredChunkBytes) {
179
+ const chunk = concatenate(pending, pendingBytes);
180
+ byteCount += chunk.byteLength;
181
+ options.onProgress?.(Object.freeze({ rows: rowCount, bytes: byteCount }));
182
+ yield chunk;
183
+ pending = [];
184
+ pendingBytes = 0;
185
+ }
186
+ pending.push(encoded);
187
+ pendingBytes += encoded.byteLength;
188
+ rowCount += 1;
189
+ current = await iterator.next();
190
+ }
191
+ inputComplete = true;
192
+ if (pendingBytes > 0) {
193
+ const chunk = concatenate(pending, pendingBytes);
194
+ byteCount += chunk.byteLength;
195
+ options.onProgress?.(Object.freeze({ rows: rowCount, bytes: byteCount }));
196
+ yield chunk;
197
+ }
198
+ }
199
+ finally {
200
+ if (current.done !== true)
201
+ await closeIterator();
202
+ }
203
+ })();
204
+ try {
205
+ await transport.copyFrom(statement, chunks, options);
206
+ }
207
+ catch (error) {
208
+ if (!inputComplete) {
209
+ try {
210
+ await closeIterator();
211
+ }
212
+ catch {
213
+ /* Preserve the transport, producer, or database failure. */
214
+ }
215
+ }
216
+ throw error;
217
+ }
218
+ if (!inputComplete)
219
+ await closeIterator();
220
+ return Object.freeze({ rows: rowCount, bytes: byteCount });
221
+ },
222
+ copyTo(query, options = {}) {
223
+ cancelled(options.signal);
224
+ return transport.copyTo(copyToStatement(query), options);
225
+ },
226
+ });
227
+ }
228
+ //# 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,GAGpB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,gBAAgB,GAAgB,MAAM,CAAC,MAAM,CAAC;IAClD,WAAW,EAAE,CAAC,KAAa,EAAE,EAAE,CAAC,IAAI,KAAK,EAAE;IAC3C,eAAe,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG;CACrE,CAAC,CAAC;AAqCH,MAAM,CAAC,MAAM,YAAY,GAAG,uBAAuB,CAAyB,eAAe,CAAC,CAAC;AAE7F,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,MAAM,mBAAmB,GAAG,EAAE,GAAG,KAAK,CAAC;AAEvC,SAAS,eAAe,CAAC,KAAa;IACpC,OAAO,gBAAgB,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;AACjD,CAAC;AAED,SAAS,oBAAoB,CAAC,KAAc;IAC1C,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,MAAM,CAAC;IACzD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,aAAa,CAAC,KAAK,CAAC,CAAC;IACtD,MAAM,OAAO,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAC;IAC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AQ,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;YACvD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,CAAC,aAAa,EAAE,CAAC;oBACnB,IAAI,CAAC;wBACH,MAAM,aAAa,EAAE,CAAC;oBACxB,CAAC;oBAAC,MAAM,CAAC;wBACP,4DAA4D;oBAC9D,CAAC;gBACH,CAAC;gBACD,MAAM,KAAK,CAAC;YACd,CAAC;YACD,IAAI,CAAC,aAAa;gBAAE,MAAM,aAAa,EAAE,CAAC;YAC1C,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;QAC7D,CAAC;QAED,MAAM,CAAM,KAA8B,EAAE,OAAO,GAA0B,EAAE;YAC7E,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YAC1B,OAAO,SAAS,CAAC,MAAM,CAAC,eAAe,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;QAC3D,CAAC;KACF,CAAC,CAAC;AACL,CAAC"}
@@ -1,7 +1,9 @@
1
1
  import { type DialectPlugin } from "@typed-sql/core";
2
2
  import { type SchemaSnapshot } from "@typed-sql/schema";
3
3
  import { type PostgresTypePolicy } from "./type-policy.js";
4
- export declare const POSTGRES_DIALECT_VERSION = "1.0.0";
4
+ export type { PostgresCopyCapability, PostgresCopyFromOptions, PostgresCopyProgress, PostgresCopyResult, PostgresCopyToOptions, } from "./bulk.js";
5
+ export { postgresCopy } from "./bulk.js";
6
+ export { POSTGRES_DIALECT_VERSION } from "./version.js";
5
7
  export type PostgresSchemaSnapshot = SchemaSnapshot & {
6
8
  readonly dialect: "postgres";
7
9
  };
@@ -14,6 +16,8 @@ export type { SchemaSnapshot } from "@typed-sql/schema";
14
16
  export { parseSchemaSnapshot } from "@typed-sql/schema";
15
17
  export type { PostgresDriverImporter, PostgresDriverModule, PostgresIntrospectionClient, PostgresIntrospectionPool, PostgresQueryable, PostgresQueryResult, PostgresSchemaProviderOptions, } from "./provider.js";
16
18
  export { introspectPostgres, loadPostgresDriver, PostgresSchemaProvider, postgresCatalogQueries } from "./provider.js";
19
+ export type { PostgresQuerySemanticResolverOptions, PostgresRoutedDatabaseOptions } from "./routing.js";
20
+ export { createPostgresQuerySemanticResolver, createPostgresRoutedDatabase, isPostgresRetryableTransactionError, } from "./routing.js";
17
21
  export type { PostgresTypePolicy } from "./type-policy.js";
18
22
  export { defaultPostgresTypePolicy, defaultPostgresTypePolicy as typePolicy, isKnownPostgresType, mapPostgresType, } from "./type-policy.js";
19
23
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAA4B,KAAK,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAuB,KAAK,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAE7E,OAAO,EAA6B,KAAK,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAEtF,eAAO,MAAM,wBAAwB,UAAU,CAAC;AAEhD,MAAM,MAAM,sBAAsB,GAAG,cAAc,GAAG;IAAE,QAAQ,CAAC,OAAO,EAAE,UAAU,CAAA;CAAE,CAAC;AACvF,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,UAAU,CAAC,EAAE,kBAAkB,CAAC;CAC1C;AAyBD,wBAAgB,QAAQ,CACtB,OAAO,GAAE,sBAA2B,GACnC,aAAa,CAAC,sBAAsB,EAAE,kBAAkB,CAAC,CA8B3D;AAED,OAAO,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AACtC,YAAY,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,YAAY,EACV,sBAAsB,EACtB,oBAAoB,EACpB,2BAA2B,EAC3B,yBAAyB,EACzB,iB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sB,EACtB,oBAAoB,EACpB,2BAA2B,EAC3B,yBAAyB,EACzB,iBAAiB,EACjB,mBAAmB,EACnB,6BAA6B,GAC9B,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvH,YAAY,EAAE,oCAAoC,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAC;AACxG,OAAO,EACL,mCAAmC,EACnC,4BAA4B,EAC5B,mCAAmC,GACpC,MAAM,cAAc,CAAC;AACtB,YAAY,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EACL,yBAAyB,EACzB,yBAAyB,IAAI,UAAU,EACvC,mBAAmB,EACnB,eAAe,GAChB,MAAM,kBAAkB,CAAC"}
@@ -1,15 +1,19 @@
1
1
  import { parseStatement, SqlParseError } from "@typed-sql/ast";
2
- import { DIALECT_CONTRACT_VERSION } from "@typed-sql/core";
2
+ import { DIALECT_CONTRACT_VERSION, unknownQuerySemantics } from "@typed-sql/core";
3
3
  import { parseSchemaSnapshot } from "@typed-sql/schema";
4
4
  import { resolveStatement } from "./resolver.js";
5
+ import { analyzePostgresSemantics } from "./semantics.js";
5
6
  import { defaultPostgresTypePolicy } from "./type-policy.js";
6
- export const POSTGRES_DIALECT_VERSION = "1.0.0";
7
+ import { POSTGRES_DIALECT_VERSION } from "./version.js";
8
+ export { postgresCopy } from "./bulk.js";
9
+ export { POSTGRES_DIALECT_VERSION } from "./version.js";
7
10
  const capabilities = Object.freeze({
8
11
  aggregateFilter: true,
9
12
  arrays: true,
10
13
  distinctOn: true,
11
14
  fullJoins: true,
12
- recursiveCtes: true,
15
+ lockingReads: true,
16
+ recursiveCtes: false,
13
17
  returning: true,
14
18
  setOperations: false,
15
19
  });
@@ -42,7 +46,14 @@ export function postgres(options = {}) {
42
46
  },
43
47
  analyze(sql, snapshot, policy = defaultTypePolicy) {
44
48
  try {
45
- return resolveStatement(parseStatement(sql), snapshot, { typePolicy: policy });
49
+ const statement = parseStatement(sql);
50
+ const resolved = resolveStatement(statement, snapshot, { typePolicy: policy });
51
+ return {
52
+ ...resolved,
53
+ semantics: resolved.diagnostics.some(({ severity }) => severity === "error")
54
+ ? unknownQuerySemantics(statement.range, "PostgreSQL semantic analysis reported an error.")
55
+ : analyzePostgresSemantics(statement, snapshot),
56
+ };
46
57
  }
47
58
  catch (error) {
48
59
  if (!(error instanceof SqlParseError))
@@ -51,6 +62,7 @@ export function postgres(options = {}) {
51
62
  columns: [],
52
63
  parameters: [],
53
64
  diagnostics: [{ code: error.code, message: error.message, severity: "error", range: error.range }],
65
+ semantics: unknownQuerySemantics(error.range, "The SQL could not be parsed by the PostgreSQL grammar."),
54
66
  };
55
67
  }
56
68
  },
@@ -60,5 +72,6 @@ export function postgres(options = {}) {
60
72
  export { sql } from "@typed-sql/core";
61
73
  export { parseSchemaSnapshot } from "@typed-sql/schema";
62
74
  export { introspectPostgres, loadPostgresDriver, PostgresSchemaProvider, postgresCatalogQueries } from "./provider.js";
75
+ export { createPostgresQuerySemanticResolver, createPostgresRoutedDatabase, isPostgresRetryableTransactionError, } from "./routing.js";
63
76
  export { defaultPostgresTypePolicy, defaultPostgresTypePolicy as typePolicy, isKnownPostgresType, mapPostgresType, } from "./type-policy.js";
64
77
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAE,wBAAwB,EAAsB,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,mBAAmB,EAAuB,MAAM,mBAAmB,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,yBAAyB,EAA2B,MAAM,kBAAkB,CAAC;AAEtF,MAAM,CAAC,MAAM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