@typed-sql/postgres 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 (46) hide show
  1. package/CHANGELOG.md +130 -0
  2. package/README.md +57 -65
  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 +68 -4
  12. package/dist/packages/postgres/src/pg.d.ts.map +1 -1
  13. package/dist/packages/postgres/src/pg.js +458 -14
  14. package/dist/packages/postgres/src/pg.js.map +1 -1
  15. package/dist/packages/postgres/src/prepared.d.ts +20 -0
  16. package/dist/packages/postgres/src/prepared.d.ts.map +1 -0
  17. package/dist/packages/postgres/src/prepared.js +47 -0
  18. package/dist/packages/postgres/src/prepared.js.map +1 -0
  19. package/dist/packages/postgres/src/provider.d.ts +2 -1
  20. package/dist/packages/postgres/src/provider.d.ts.map +1 -1
  21. package/dist/packages/postgres/src/provider.js +3 -1
  22. package/dist/packages/postgres/src/provider.js.map +1 -1
  23. package/dist/packages/postgres/src/resolver.d.ts.map +1 -1
  24. package/dist/packages/postgres/src/resolver.js +11 -1
  25. package/dist/packages/postgres/src/resolver.js.map +1 -1
  26. package/dist/packages/postgres/src/routing.d.ts +22 -0
  27. package/dist/packages/postgres/src/routing.d.ts.map +1 -0
  28. package/dist/packages/postgres/src/routing.js +70 -0
  29. package/dist/packages/postgres/src/routing.js.map +1 -0
  30. package/dist/packages/postgres/src/runtime.d.ts +34 -3
  31. package/dist/packages/postgres/src/runtime.d.ts.map +1 -1
  32. package/dist/packages/postgres/src/runtime.js +923 -22
  33. package/dist/packages/postgres/src/runtime.js.map +1 -1
  34. package/dist/packages/postgres/src/semantics.d.ts +5 -0
  35. package/dist/packages/postgres/src/semantics.d.ts.map +1 -0
  36. package/dist/packages/postgres/src/semantics.js +211 -0
  37. package/dist/packages/postgres/src/semantics.js.map +1 -0
  38. package/dist/packages/postgres/src/stream.d.ts +34 -0
  39. package/dist/packages/postgres/src/stream.d.ts.map +1 -0
  40. package/dist/packages/postgres/src/stream.js +124 -0
  41. package/dist/packages/postgres/src/stream.js.map +1 -0
  42. package/dist/packages/postgres/src/version.d.ts +2 -0
  43. package/dist/packages/postgres/src/version.d.ts.map +1 -0
  44. package/dist/packages/postgres/src/version.js +2 -0
  45. package/dist/packages/postgres/src/version.js.map +1 -0
  46. package/package.json +4 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,135 @@
1
1
  # @typed-sql/postgres
2
2
 
3
+ ## 2.0.0-rc.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Publish the coherent 2.0.0-rc.1 release-candidate train.
8
+
9
+ ## 2.0.0-rc.0
10
+
11
+ ### Major Changes
12
+
13
+ - 29afc3d: Add conservative semantic primary/replica routing over application-owned databases, scoped
14
+ read-after-write pinning, explicit role requirements, stable unsafe-route errors, dialect runtime
15
+ semantic resolvers, and bounded abortable transaction retry policies with native PostgreSQL and
16
+ MySQL error classifiers. Parse and classify dialect locking reads so uncertain or affine work
17
+ always fails closed to primary.
18
+ - 6a7ae58: Add opt-in live query verification through grammar-owned PostgreSQL PREPARE and MySQL
19
+ COM_STMT_PREPARE adapters, bounded neutral comparison, deterministic secret-free proof artifacts,
20
+ offline cache validation, explicit unsupported classifications, CLI workflows, real database E2E,
21
+ and performance budgets.
22
+ - b06fd0a: Add grammar-neutral optional adapter capability discovery, typed PostgreSQL COPY import and export
23
+ through application-owned `pg-copy-streams`, and typed MySQL LOAD DATA import through mysql2's
24
+ application-owned infile stream. Bulk transfers preserve ordinary `INSERT` parameter evidence,
25
+ enforce structural row stability, apply bounded backpressure, support cancellation and progress,
26
+ and integrate with transaction ownership and conservative connection cleanup.
27
+ - 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.
28
+ - 1b054b6: Add an adapter-neutral, redacted database observation lifecycle for queries, cardinality contracts,
29
+ batches, PostgreSQL pipelines, streams, cancellation, and nested transactions. Runtime fingerprints
30
+ correlate with compiler structural variants while SQL, parameter values, connection configuration,
31
+ and driver causes remain excluded by default. Publish the optional OpenTelemetry bridge with current
32
+ database semantic conventions and explicit high-cardinality or exception-capture opt-ins.
33
+ - 87189c3: Add grammar-neutral `all`, `one`, and `maybeOne` execution with exact row types, stable cardinality
34
+ and cancellation errors, explicit adapter capabilities, AbortSignal support, and absolute deadlines.
35
+ The pg and mysql2 adapters conservatively discard interrupted connections, including transaction
36
+ leases, while the existing uncontrolled `execute` path remains unchanged.
37
+ - e654fae: Add opt-in Standard Schema V1 result validation with compile-time output compatibility, immutable
38
+ query attachment, sync and async validators, redacted fingerprinted errors, and consistent decoded-row
39
+ handling across buffered cardinality methods, batches, PostgreSQL pipelines, streams, and transactions.
40
+ - b2ec119: Add opt-in, grammar-neutral query-plan governance with PostgreSQL and MySQL structured EXPLAIN
41
+ adapters, transient application-owned samples, redacted fingerprint-keyed artifacts, absolute and
42
+ comparable regression budgets, explicit uncertainty, CLI capture and review, documentation, and
43
+ performance coverage.
44
+
45
+ ### Patch Changes
46
+
47
+ - Updated dependencies [29afc3d]
48
+ - Updated dependencies [3f063f6]
49
+ - Updated dependencies [6a7ae58]
50
+ - Updated dependencies [af27a0e]
51
+ - Updated dependencies [b06fd0a]
52
+ - Updated dependencies [3050209]
53
+ - Updated dependencies [1b054b6]
54
+ - Updated dependencies [b4f1b6e]
55
+ - Updated dependencies [87189c3]
56
+ - Updated dependencies [e654fae]
57
+ - Updated dependencies [b2ec119]
58
+ - @typed-sql/ast@2.0.0-rc.0
59
+ - @typed-sql/core@2.0.0-rc.0
60
+ - @typed-sql/schema@2.0.0-rc.0
61
+
62
+ ## 1.0.0
63
+
64
+ ### Major Changes
65
+
66
+ - 7ca256b: Release the first public typed-sql beta: exact TypeScript 7 row inference from static PostgreSQL and
67
+ MySQL, versioned schema introspection, application-owned drivers, config-driven grammar plugins,
68
+ CLI verification, editor language-server integration, versioned diagnostics, bounded parsing, and
69
+ real-database plus packed-tarball verification.
70
+
71
+ ### Minor Changes
72
+
73
+ - 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.
74
+ - eb16de7: Add lazy, exactly typed query streams to the PostgreSQL and MySQL runtime adapters. PostgreSQL
75
+ uses an application-owned optional `pg-cursor` installation for bounded cursor reads. MySQL uses
76
+ mysql2's execute-protocol stream and shared decoder plan. Both adapters enforce deterministic
77
+ cleanup, transaction ownership, and positive safe-integer batch sizes.
78
+ - eb16de7: Add a grammar-neutral validated query-batch type and ordered, exactly typed query batches to the
79
+ PostgreSQL and MySQL runtime adapters. Non-empty root batches execute sequentially on one leased
80
+ connection, transaction batches reuse their transaction connection, and empty batches avoid
81
+ connection acquisition. Batch execution preserves prepared metadata and adapter codecs, stops at
82
+ the first failure, and rejects transaction work that escapes its callback.
83
+ - b6389e4: Add an exactly typed PostgreSQL `pipeline()` capability backed by node-postgres's documented opt-in pipeline mode. Pipelines lease one client, dispatch independent queries before awaiting their results, preserve tuple order and prepared metadata, settle every in-flight query before cleanup, and integrate with transaction rollback and non-escape guarantees without changing sequential `batch()` semantics.
84
+
85
+ ### Patch Changes
86
+
87
+ - 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.
88
+ - eb16de7: Own in-flight transaction executions through settlement so unawaited work can never race commit, savepoint release, rollback, or connection release.
89
+
90
+ 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.
91
+ - eb16de7: Allow adapters to retain enriched capabilities in transaction callbacks and nested transactions
92
+ through a self-typed core database contract. Transaction cleanup now also preserves the original
93
+ operation error when rollback or connection-release cleanup fails.
94
+ - 1563a7a: Declare and enforce the 1.0 package stability boundary. Core SQL, compiler, schema, config, AST,
95
+ PostgreSQL, MySQL, and CLI packages form the stable train; the TypeScript preview bridge and
96
+ language server remain explicitly experimental. Freeze public entrypoints and query type contracts,
97
+ and remove internal compiler/type helpers from stable package-root exports before 1.0.
98
+ - 9dd6bc4: Finalize dialect contract version 3 with explicit identifier quoting and grammar-owned capability
99
+ declarations. Accept third-party snapshot dialects, validate grammar versions, and document the
100
+ public grammar-authoring and conformance workflow.
101
+ - 16e2475: Prove npm trusted publishing and provenance after the initial registry bootstrap.
102
+ - 642cebd: Prove and document runtime codec fidelity against live PostgreSQL and MySQL values. PostgreSQL now
103
+ delegates non-policy OIDs to the installed pg parser table, MySQL maps BIT to Uint8Array, and the
104
+ mysql2 adapter rejects pool settings that would contradict its type policy.
105
+ - 3e2c75c: Infer ordered query parameter tuples and let TypeScript reject interpolation values that do not
106
+ match their SQL context. Dialect contract version 2 adds explicit parameter analysis; unresolved
107
+ positions remain `unknown`. Add typed nullable predicate composition through `sql.fragment()`,
108
+ `sql.and()`, `sql.or()`, `sql.where()`, and `sql.append()` while preserving row and parameter tuples.
109
+ Direct append fragments are grammar-analyzed cumulatively against their static base, so TypeScript
110
+ rejects fragment interpolation values that disagree with the referenced database columns.
111
+ Add `sql.empty` and SQL-template-native conditional structural fragments. The compiler analyzes
112
+ complete branch variants, preserves literal boolean-dependent result rows, and type-checks nested
113
+ fragment parameters without adding a query-builder DSL. Bound independent structural expansion at
114
+ 64 variants by default, correlate repeated conditions, merge diagnostics and fragment expectations
115
+ across variants, and fail closed on incompatible contexts. Share indexed catalog and conservative
116
+ parameter-resolution primitives across grammars, harden cooked-template scanning, and add runtime,
117
+ resolver, scanner, and structural performance gates.
118
+ - Updated dependencies [eb16de7]
119
+ - Updated dependencies [b6389e4]
120
+ - Updated dependencies [eb16de7]
121
+ - Updated dependencies [b6389e4]
122
+ - Updated dependencies [eb16de7]
123
+ - Updated dependencies [1563a7a]
124
+ - Updated dependencies [9dd6bc4]
125
+ - Updated dependencies [7ca256b]
126
+ - Updated dependencies [16e2475]
127
+ - Updated dependencies [69c7d87]
128
+ - Updated dependencies [3e2c75c]
129
+ - @typed-sql/core@1.0.0
130
+ - @typed-sql/ast@1.0.0
131
+ - @typed-sql/schema@1.0.0
132
+
3
133
  ## 1.0.0-rc.0
4
134
 
5
135
  ### Patch Changes
package/README.md CHANGED
@@ -1,95 +1,87 @@
1
1
  # @typed-sql/postgres
2
2
 
3
- PostgreSQL grammar, catalog introspection, exact result inference, type policy, runtime codecs, and
4
- an optional application-owned `pg` adapter for [typed-sql](https://github.com/Lojhan/typed-sql).
3
+ The stable PostgreSQL grammar for [typed-sql](https://github.com/Lojhan/typed-sql), including
4
+ catalog introspection, row and parameter inference, type policy, runtime codecs, and an optional
5
+ application-owned `pg` adapter, native live verifier, and structured-plan inspector.
5
6
 
6
7
  ```sh
7
- pnpm add @typed-sql/core@next @typed-sql/postgres@next pg
8
- pnpm add -D @typed-sql/cli@next typescript@7.0.2
8
+ pnpm add @typed-sql/core @typed-sql/postgres pg
9
+ pnpm add -D @typed-sql/cli typescript@7.0.2
9
10
  ```
10
11
 
11
- `pg` is intentionally not a dependency or peer dependency of this package. Your application chooses
12
- its driver version, pool configuration, and lifecycle; the adapter loads it only when you import
13
- `@typed-sql/postgres/pg`.
12
+ `pg` is loaded only through `@typed-sql/postgres/pg`; it is not a dependency or peer dependency of
13
+ the grammar. Applications that stream rows also install the optional application-owned cursor:
14
14
 
15
- ## Configure and generate
16
-
17
- ```ts
18
- import { defineConfig } from "@typed-sql/core";
19
- import { postgres, typePolicy } from "@typed-sql/postgres";
20
- import { pg } from "@typed-sql/postgres/pg";
21
-
22
- export default defineConfig({
23
- dialect: postgres({ typePolicy }),
24
- schema: {
25
- file: "generated/db/schema.json",
26
- provider: pg({
27
- connectionString: () => process.env.DATABASE_URL!,
28
- schemas: ["public"],
29
- typePolicy,
30
- }),
31
- },
32
- outDir: "generated/db",
33
- projects: ["tsconfig.json"],
34
- typePolicy,
35
- });
15
+ ```sh
16
+ pnpm add pg-cursor
36
17
  ```
37
18
 
19
+ Applications that use PostgreSQL COPY also install its optional application-owned stream:
20
+
38
21
  ```sh
39
- pnpm exec typed-sql generate
22
+ pnpm add pg-copy-streams
40
23
  ```
41
24
 
42
- ## Query and execute
43
-
44
25
  ```ts
45
- import { sql, typePolicy } from "@typed-sql/postgres";
26
+ import { requireAdapterCapability } from "@typed-sql/core";
27
+ import { postgresCopy, sql, typePolicy } from "@typed-sql/postgres";
46
28
  import { createPgDatabase } from "@typed-sql/postgres/pg";
47
29
 
48
30
  const query = sql`
49
- SELECT account.id, account.email, account.status, project.budget
31
+ SELECT account.id, account.email, project.budget
50
32
  FROM users AS account
51
33
  LEFT JOIN projects AS project ON project.owner_id = account.id
52
- ORDER BY account.id
53
34
  `;
54
35
 
55
36
  const database = await createPgDatabase({
56
37
  connectionString: process.env.DATABASE_URL!,
38
+ poolConfig: { pipeline: true },
57
39
  typePolicy,
40
+ copyStreamsImporter: () => import("pg-copy-streams"),
41
+ // observer: createOpenTelemetryObserver(),
58
42
  });
59
43
 
44
+ // pipeline() requires the application-owned pg 8.23.0 or newer.
45
+
60
46
  const rows = await database.execute(query);
61
- // readonly {
62
- // id: bigint;
63
- // email: string;
64
- // status: "active" | "suspended";
65
- // budget: string | null;
66
- // }[]
47
+
48
+ const accountById = database.prepare("account-by-id", (id: bigint) => sql`
49
+ SELECT account.id, account.email
50
+ FROM users AS account
51
+ WHERE account.id = ${id}
52
+ `);
53
+
54
+ const [selectedAccounts, allAccounts] = await database.batch([accountById(42n), query]);
55
+ const [pipelinedAccount, pipelinedAll] = await database.pipeline([accountById(42n), query]);
56
+
57
+ for await (const account of database.stream(accountById(42n), { batchSize: 500 })) {
58
+ // account retains the query's inferred row type
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
+ );
67
67
  ```
68
68
 
69
- The default lossless policy maps PostgreSQL `bigint` to `bigint`, `numeric` to `string`, temporal
70
- types to `Date`, JSON to `unknown`, enums to literal unions, arrays recursively, and `bytea` to
71
- `Uint8Array`. Per-query parsers do not mutate `pg` globals and delegate non-policy OIDs to the
72
- installed driver's native parser table. See the tested
73
- [runtime codec matrix](https://github.com/Lojhan/typed-sql/blob/main/docs/CODEC_FIDELITY.md#postgresql-and-pg).
74
-
75
- ## Supported SQL
76
-
77
- | Surface | Status | Notes |
78
- | --- | --- | --- |
79
- | Static tagged templates | Supported | Imports and aliases from `@typed-sql/postgres` are recognized. |
80
- | `SELECT`, `DISTINCT`, `DISTINCT ON` | Supported | Static row-shape inference. |
81
- | Tables, schemas, aliases and stars | Supported | Catalog lookup, ambiguity checks and `USING` column merging. |
82
- | Inner and outer joins | Supported | Outer-join nullability propagates into result columns. |
83
- | CTEs and derived/correlated/scalar subqueries | Supported | Recursive CTEs and unsafe scalar/IN arity diagnose. |
84
- | Grouping, aggregates and windows | Supported | Includes common aggregates, `FILTER`, named and inline windows. |
85
- | Expressions, `CASE`, casts and `$n` parameters | Supported | Parameters infer from columns, casts, DML targets, ranges, limits, and catalog functions; ambiguous positions remain `unknown`. |
86
- | Arrays, enums, domains, JSON and catalog functions | Supported | Known types and function name/arity are validated. |
87
- | `INSERT`, `UPDATE`, `DELETE`, `RETURNING` | Supported | Commands without `RETURNING` infer `Query<never, Parameters>`. |
88
- | Set operations and `WITHIN GROUP` | Not supported | Fail safely during parsing. |
89
- | Dynamic SQL or identifiers | No static inference | Use runtime values and `sql.ident()` explicitly. |
90
-
91
- A feature not marked supported produces a diagnostic or `Query<unknown>`; it never receives an
92
- optimistic row type. Introspection covers tables, views, columns, defaults, server version, arrays,
93
- enums, domains and user functions.
69
+ The package root exports `sql`, `postgres`, and the PostgreSQL type policy. The `/pg` entrypoint
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.
76
+
77
+ Read the [PostgreSQL grammar guide](https://github.com/Lojhan/typed-sql/blob/main/docs/dialects/postgresql.md),
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),
84
+ [configuration](https://github.com/Lojhan/typed-sql/blob/main/docs/getting-started/configuration.md), and
85
+ [database type mappings](https://github.com/Lojhan/typed-sql/blob/main/docs/reference/type-mappings.md).
94
86
 
95
87
  MIT © typed-sql contributors
@@ -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: PostgresCopyTransport): PostgresCopyCapability;
30
+ //# 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,EAEV,KAAK,WAAW,EAEjB,MAAM,iBAAiB,CAAC;AAOzB,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,kBAAmB,SAAQ,oBAAoB;CAAG;AAEnE,MAAM,WAAW,uBAAwB,SAAQ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, } 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,i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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,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,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EACL,yBAAyB,EACzB,yBAAyB,IAAI,UAAU,EACvC,mBAAmB,EACnB,eAAe,GAChB,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAA4B,KAAK,aAAa,EAAyB,MAAM,iBAAiB,CAAC;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