@di-framework/pglite-component 0.0.0-stage → 6.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE-APACHE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,23 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 @di-framework Contributors
4
+
5
+ Contact: support@di-framework.dev
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,305 @@
1
- # Temporary Holding Version
1
+ # di-framework:pglite — embedded PostgreSQL over WIT
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The provider bundles the PGlite PostgreSQL 17.5 engine into a WebAssembly
4
+ component. SQL calls cross WIT and WebAssembly memory. There is no TCP listener,
5
+ network client, native sidecar, or separate database service.
6
+
7
+ ```text
8
+ app.wasm → di-framework:pglite/database → bundled PostgreSQL engine
9
+ ↓
10
+ WASI filesystem
11
+ ↓
12
+ persistent /data mount
13
+ ```
14
+
15
+ `open("/data/orders", none)` opens a persistent database root. An empty path
16
+ selects `/data/pglite`. Missing or read-only storage fails; the provider never
17
+ silently substitutes an in-memory database. This replaces the old TCP client:
18
+ `PGHOST`, `PGPORT`, and connection-target strings are no longer used.
19
+
20
+ ## npm package
21
+
22
+ `@di-framework/pglite-component` is versioned with this repository (6.0.x) and
23
+ published by the platform release workflow. It contains:
24
+
25
+ | Import | What |
26
+ | --- | --- |
27
+ | `@di-framework/pglite-component` | The `SqlDatabase` adapter (`createWasmPgliteDatabase`, see below), ESM with types |
28
+ | `@di-framework/pglite-component/wasm` | `dist/di-framework-pglite.wasm`, the composed provider component |
29
+ | `@di-framework/pglite-component/wit` | `dist/di-framework-pglite.wit`, the WIT recovered from that component |
30
+ | `@di-framework/pglite-component/wit/*` | The source WIT (`wit/world.wit` and its `deps/`) for bindings generators |
31
+
32
+ `BUILD-INFO.txt`, `SHA256SUMS` and `THIRD-PARTY-NOTICES.txt` ship next to the
33
+ wasm. The adapter needs `@di-framework/repo` `^6.1.0` as a peer dependency.
34
+
35
+ The release job builds the wasm from source with the same `make` targets as
36
+ CI, runs `make unit smoke` against it, and refuses to publish a pack without
37
+ the wasm or the adapter. The npm copy is for application developers composing
38
+ locally. GHCR stays the digest-pinned source that the CLI composes at deploy
39
+ time (see [Publishing to GHCR](#publishing-to-ghcr)); the two are separate
40
+ builds of the same sources and are not guaranteed to be byte-identical, so pin
41
+ deployments by GHCR digest.
42
+
43
+ ## Build and verify
44
+
45
+ ```sh
46
+ make tools
47
+ make build
48
+ make smoke
49
+ bun test
50
+ ```
51
+
52
+ `bun run build` builds the adapter (`bun run build:adapter`, TypeScript only,
53
+ no engine) and then runs `make build`.
54
+
55
+ Use the pinned Rust toolchain through rustup, Python 3, and the installed
56
+ `wasm-tools`/`wac`. Preparing the engine from source also needs a Linux Docker
57
+ or Podman daemon, Git, curl, and several GB of build storage. The engine build
58
+ is cached under `target/engine`. Containers are build tools only; deployment
59
+ runs the resulting `.wasm` directly. For a remote Podman daemon, set the task's
60
+ `DOCKER_CONTEXT=podman`.
61
+
62
+ The build embeds the support filesystem, adapts the engine's WASI Preview 1
63
+ imports to Preview 2, and composes the engine with the Rust database provider.
64
+ It fails if the final artifact imports sockets or leaves the engine unresolved.
65
+ Ship `dist/di-framework-pglite.wasm` together with `THIRD-PARTY-NOTICES.txt`.
66
+ Build provenance and checksums are in `dist/BUILD-INFO.txt` and `SHA256SUMS`.
67
+
68
+ `make smoke` composes a real WIT consumer, runs it without network access, and
69
+ checks typed parameters/results, SQL errors and recovery, transactions,
70
+ rollback on close/drop, exclusive connection ownership, durability settings,
71
+ and persistence across separate runtime processes. It also exits a runtime
72
+ with an open transaction and verifies that committed rows survive and the
73
+ uncommitted row is absent after restart. No scripted database server is used.
74
+
75
+ ## Publishing to GHCR
76
+
77
+ The pglite component is published to GitHub Container Registry (GHCR) as an OCI wasm component. [The workflow](https://github.com/di-framework/platform/actions/workflows/pglite-component-publish.yml) runs by itself on each push to `main` that changes one of its input paths (`on.push.paths`). `workflow_dispatch` stays available for reruns and always builds.
78
+
79
+ The workflow has four jobs:
80
+ - `check-source` (`packages: read`) hashes the committed input files (`scripts/source-check.ts`). On a push it skips the build when `ghcr.io/di-framework/pglite-component:src-<hash>` already exists, so commits that do not change the component publish nothing.
81
+ - `build` (no write token) runs the same targets as `ci.yml`: `make tools-rust`, `make unit smoke` (which runs `make build`, composing the provider with the engine via `wac plug`), then the publisher crates' clippy and tests.
82
+ - `publish` (`packages: write`) downloads the tested `dist/` and runs `pglite-component-publisher`. It never rebuilds or modifies `dist/`. It checks `SHA256SUMS`, requires the export `di-framework:pglite/database@0.2.0` and rejects any import that is not `wasi:*`, then pushes `ghcr.io/di-framework/pglite-component:<commit sha>` once, pulls it back by the manifest digest to compare bytes, then points the version tag (`0.2.0`, the WIT package version) at that same manifest with `oras tag` and asserts both tags resolve to one digest. The `build` job passes the tested wasm sha256 to `publish`, which verifies it before pushing. It also tags the manifest `src-<hash>`.
83
+ - `pin` (`contents: write`, `pull-requests: write`) opens or updates the PR `bot/pin-pglite-component`, "chore: pin pglite-component to <digest>", which rewrites the digests in this README with `scripts/pin-artifact.ts`. GitHub does not run workflows on a PR that `GITHUB_TOKEN` opened, so a maintainer has to start its checks (close and reopen it) before merging. It also runs when a push's source is already published (a revert to an older source, or a pin PR closed unmerged), so `main`'s pin follows the current source; it opens no PR when `main` already has the digest. On that path the `realign` job (`packages: write`) points the moving version tag back at that source's digest with `scripts/retag.sh`, which leaves a tag that is already there alone. Every tag move is behind the same source guard, so a stale run never retags.
84
+
85
+ Tags are movable. `0.2.0` always points to the latest `main` publish for WIT package 0.2.0, and re-running a commit also moves its SHA tag. Only the `@sha256:...` digest is immutable, so consumers pin by digest.
86
+
87
+ ### Artifact location
88
+
89
+ The digest is in **Details** > **Record component digest** > **Step summary**, and in the `pglite-publish-report` artifact (`publish-report.json`).
90
+ Published digest: `ghcr.io/di-framework/pglite-component@sha256:8bc30505cf28b1a65f72588da692d2ba3d79a6a2025c9256341a8625967a3286`
91
+
92
+ **Note:** The GHCR package must be made public by an org admin after the first publish. Until then, only members with access to di-framework/platform can pull it.
93
+
94
+ ## Use from an application
95
+
96
+ The application imports `di-framework:pglite/database@0.2.0`. For a JavaScript
97
+ component built with the framework's component toolchain:
98
+
99
+ ```ts
100
+ import { open } from 'di-framework:pglite/database@0.2.0';
101
+
102
+ const db = open('/data/orders', undefined);
103
+ try {
104
+ db.exec('CREATE TABLE IF NOT EXISTS orders (id bigint PRIMARY KEY, title text)');
105
+ db.run('INSERT INTO orders VALUES ($1, $2)', [
106
+ { tag: 'integer', val: 1n },
107
+ { tag: 'text', val: 'First order' },
108
+ ]);
109
+ const row = db.first('SELECT title FROM orders WHERE id = $1', [
110
+ { tag: 'integer', val: 1n },
111
+ ]);
112
+ } finally {
113
+ db.close();
114
+ }
115
+ ```
116
+
117
+ Compose the application with the provider. For a local build:
118
+
119
+ ```sh
120
+ make compose APP=path/to/app.wasm OUT=path/to/app.composed.wasm
121
+ mkdir -p ./data
122
+ wasmtime run --dir ./data::/data path/to/app.composed.wasm
123
+ ```
124
+
125
+ To use the published OCI component from GHCR instead (pin by digest for reproducibility):
126
+
127
+ ```sh
128
+ export PGLITE_REF='ghcr.io/di-framework/pglite-component@sha256:8bc30505cf28b1a65f72588da692d2ba3d79a6a2025c9256341a8625967a3286'
129
+ wash oci pull "${PGLITE_REF}" pglite.wasm
130
+ wac plug --plug pglite.wasm path/to/app.wasm -o path/to/app.composed.wasm
131
+ mkdir -p ./data
132
+ wasmtime run --dir ./data::/data path/to/app.composed.wasm
133
+ ```
134
+
135
+ Consumers (like cli-extensions) pin the component by digest.
136
+
137
+ That invocation is for a command component; serve HTTP components using your
138
+ normal host while granting the same filesystem preopen. The final component
139
+ requires WASI filesystem, clocks, streams, CLI and randomness interfaces, plus
140
+ standardized WebAssembly exception handling for PostgreSQL error recovery.
141
+
142
+ The public interface retains `exec`, `run`, `query`, `first`, transactions,
143
+ savepoints, `rows-affected`, `close`, and `server-version`. PostgreSQL parameters
144
+ use `$1`, `$2`, etc. Text parameters are sent with OID 0 (unknown type), allowing
145
+ PostgreSQL to infer the type from context; comparisons against `uuid`, `timestamptz`,
146
+ and `jsonb` columns work correctly (see Typed values). `server-version()` reports the bundled engine without
147
+ opening a database. Only the `template1` database is currently supported;
148
+ other `open-options.database` values are rejected. Requests must fit the engine's
149
+ input buffer; each serialized result is limited to 64 MiB and stays in memory.
150
+ Larger results return a PostgreSQL program-limit error. Signal-based statement
151
+ timeouts are unavailable in this WASI engine: nonzero `statement-timeout-ms`
152
+ options fail explicitly. Use host execution limits for runaway queries.
153
+
154
+ ## `SqlDatabase` adapter
155
+
156
+ `createWasmPgliteDatabase` adapts the `di-framework:pglite/database@0.2.0`
157
+ import to the `SqlDatabase` contract of `@di-framework/repo`, so repositories
158
+ and migrations run on embedded PostgreSQL. Compose your component with this
159
+ provider (see above). The adapter is portable: it uses only
160
+ `node:async_hooks`, which the framework's component toolchain shims.
161
+
162
+ ```ts
163
+ import type { SqlDatabase } from '@di-framework/repo';
164
+ import { createWasmPgliteDatabase } from '@di-framework/pglite-component';
165
+
166
+ // The database root is yours to choose. An empty path selects /data/pglite.
167
+ const db: SqlDatabase = await createWasmPgliteDatabase('/data/identity');
168
+
169
+ await db.exec('CREATE TABLE IF NOT EXISTS users (id uuid PRIMARY KEY, email text UNIQUE, meta jsonb)');
170
+ await db.transaction(async (tx) => {
171
+ await tx.run('INSERT INTO users (id, email, meta) VALUES (?, ?, ?)', [id, email, { plan: 'free' }]);
172
+ });
173
+ const user = await db.first<{ email: string; meta: { plan: string } }>(
174
+ 'SELECT email, meta FROM users WHERE id = ?',
175
+ [id],
176
+ );
177
+ ```
178
+
179
+ The provider allows one open connection per component instance. Keep one
180
+ handle and share it: every call goes through one async mutex.
181
+
182
+ - **Transactions.** `transaction(fn)` runs the provider's `begin` and `commit`, and `rollback` when `fn` throws. Statements issued from inside `fn`, through the callback view or the outer handle, join the transaction; other tasks wait for it. Inside `fn`, prefer the callback view: while the transaction is open it joins from any async context, including a worker loop or `AsyncResource` created earlier, and Wasm-guest code that the `node:async_hooks` shim does not instrument (native async generators). The outer handle joins only from `fn`'s own async context. From any other context it waits for the mutex, so awaiting it from `fn` deadlocks. A nested `transaction()` opens a savepoint. When it throws, only its own work rolls back, and the outer transaction can continue. Its work commits only with the outer transaction. Sibling savepoints started concurrently run one at a time. A plain statement issued through a view while a sibling savepoint is open joins that savepoint and rolls back with it: in `Promise.all([tx.transaction(failing), (async () => { await work(); await tx.run(...); })()])`, a `run` issued while the savepoint is open lands inside it, so await the savepoint first when the statement must survive it. Statements issued concurrently inside one transaction reach the connection one at a time, also with bindings that return promises. `transaction()` on a view, called from another async context while a sibling savepoint is open, waits for that sibling to finish; if the sibling awaits that call, it waits forever. Joining lasts only while a transaction is open. A savepoint's callback view kept after the savepoint returns joins the nearest open ancestor while the root transaction is still open, and its work commits or rolls back with that ancestor. Once the root transaction has ended, a retained callback view, like a timer scheduled inside `fn`, waits for the mutex like any other caller and never runs inside another task's transaction.
183
+ - **Placeholders.** `?` placeholders become `$1`, `$2`, ... in order (`toPgPlaceholders`). The rewrite skips `'...'` and `E'...'` strings, `"..."` identifiers, `$tag$...$tag$` bodies, `--` and `/* */` comments, and the jsonb operators `?|` and `?&`. Because of that, `?||` reads as `?|` followed by `|`: put a space in the concatenation (`? || 'x'`). The bare jsonb `?` operator looks like a placeholder: use `jsonb_exists(col, ?)` in a statement with parameters. A statement run without parameters is not rewritten. You can write `$n` yourself, but do not mix `$n` with `?` in one statement.
184
+ - **Parameters.** `string` is sent as text, and PostgreSQL infers its type from context, so a UUID or timestamp string works against `uuid` and `timestamptz` columns. A safe integer is `int8`, another number is `float8`, a `boolean` is `bool`, and `Uint8Array`, `ArrayBuffer` and typed arrays are `bytea`. A `Date` is sent as an RFC 3339 timestamp. Plain objects and arrays are sent as JSON, so a JavaScript array is not a PostgreSQL array: pass a literal such as `'{a,b}'`. A `bigint` outside the safe integer range is sent as decimal text, so it is not rounded. A `number` that is an integer outside the safe range throws a `TypeError`, because it has already lost precision: pass a `bigint` or a decimal string for `int8`. NaN and Infinity are valid `float8` values and are sent as `real`.
185
+ - **Results.** Values match the `wasmcloud:postgres` codec in `@di-framework/repo`, so repositories behave the same on both backends. `json` and `jsonb` are parsed. `timestamptz` is an ISO string with milliseconds (`2024-01-15T10:30:00.123Z`, microseconds truncated); `infinity` and BC dates are returned as PostgreSQL prints them. An `int8` outside the safe integer range is a decimal string, but only when the binding lifts WIT `s64` as a `bigint`; a binding that lifts it as a JavaScript number (componentize-qjs lowers `s64` from numbers) has already lost the precision, so cast large `int8` columns to `text` in the query (`id::text`) when exact values matter (#153). `bool` is a boolean, `bytea` is a `Uint8Array`, and `timestamp` without zone, `date`, `uuid`, `numeric` and arrays are strings.
186
+ - **Errors.** Failures throw `WasmPgliteError` with the WIT `tag`. A PostgreSQL error keeps its SQLSTATE in `error.code` (`'23505'` for a unique violation), and the message starts with `PostgreSQL <code>`, so `isUniqueViolation` from `@di-framework/repo` works too.
187
+
188
+ Pass `module` or `loadModule` to supply the interface yourself (for tests), and
189
+ `database` or `statementTimeoutMs` to forward `open-options`.
190
+ `createSqlDatabaseFromWasmPgliteConnection` wraps a connection you have already
191
+ opened.
192
+
193
+ The adapter's view of the import is typed by `js/wit.d.ts`, generated from
194
+ `wit/world.wit` by `bun scripts/wit-types.ts`. After changing the WIT, rerun it;
195
+ the tests and `build:adapter` fail while the file is stale, and the typecheck
196
+ fails when the WIT no longer fits the adapter. That check covers method names,
197
+ arity and result types, not parameter variants: removing or narrowing a `value`
198
+ case is not caught (TODO #153).
199
+
200
+ ## Typed values (0.2.0+)
201
+
202
+ Every `open` pins `DateStyle=ISO` and `TimeZone=UTC` (set in the startup packet and re-applied
203
+ on each open, since `close` runs `DISCARD ALL`), so text output is deterministic. Result mapping by
204
+ PostgreSQL type:
205
+
206
+ | PostgreSQL type | `value` variant | Format |
207
+ | --- | --- | --- |
208
+ | `bool` | `boolean` | |
209
+ | `int2`, `int4`, `int8` | `integer` | `int8` is `integer` (`s64`); node-pg returns a string |
210
+ | `float4`, `float8` | `real` | |
211
+ | `bytea` | `blob` | |
212
+ | `json`, `jsonb` | `json` | JSON text; `jsonb` is re-rendered by PostgreSQL (`{"a": 1}`) |
213
+ | `timestamptz` | `timestamp` | RFC 3339 in UTC, e.g. `2024-01-15T10:30:00Z`, fractional seconds kept (`...:00.123Z`). `infinity` and `-infinity` are returned as those literals; BC dates are returned unmodified (`0044-03-15 00:00:00+00 BC`) |
214
+ | `timestamp` (no zone) | `text` | `2024-01-15 10:30:00` (ISO, space separator, no offset). Deliberately not `timestamp`, which always denotes an instant |
215
+ | `date` | `text` | `2024-01-15` |
216
+ | `uuid`, `numeric` | `text` | canonical PostgreSQL text (`12.50` keeps its scale) |
217
+ | arrays | `text` | PostgreSQL array literal, e.g. `{a,b}` |
218
+ | everything else | `text` | |
219
+
220
+ Parameters are typed as follows. `integer`, `real`, `boolean` and `blob` are
221
+ sent as `int8`, `float8`, `bool` and `bytea`. `text`, `json` and `timestamp`
222
+ are all sent with OID 0 (unknown), so PostgreSQL infers the type from context:
223
+ a `json` parameter works against `json` and `jsonb` columns and with `jsonb`
224
+ operators (`@>`, `=`), and a `timestamp` parameter against `timestamptz` and
225
+ `timestamp` columns. Send RFC 3339 for `timestamp`; any string PostgreSQL
226
+ accepts for the inferred type works.
227
+
228
+ Column type OIDs are not exposed: adding them to `row` would change its shape
229
+ and break every existing consumer, and the variants above plus Text for the
230
+ rest cover the adapters' needs. A separate additive API can be added later.
231
+
232
+ ### Migrating from 0.1.0
233
+
234
+ Bump consumers and composition pins to `di-framework:pglite/database@0.2.0`
235
+ (the `value` variant gained cases, so 0.1.0 bindings do not link). Text
236
+ parameters were previously sent as `text` (OID 25); they are now OID 0. That
237
+ fixes `uuid = $1`, `timestamptz < $1` and `jsonb @> $1`, but PostgreSQL can no
238
+ longer type a parameter that has no context: `SELECT $1 IS NULL` now fails with
239
+ `could not determine data type of parameter $1`. Add a cast, for example
240
+ `SELECT $1::text IS NULL`.
241
+
242
+ Error mapping changed: undefined table (42P01), undefined column (42703) and
243
+ every other class-42 code except 42601 (syntax error) and 42P18 (un-inferable
244
+ parameter type) moved from `invalid-sql` to `execution-failed`. Branch on
245
+ `pg-error.code` instead of the variant for those cases.
246
+
247
+ Error handling surfaces SQLSTATE codes through `error.code`, enabling
248
+ machine-readable handling of constraint violations and other conditions:
249
+ - `"23505"` = unique violation
250
+ - `"22012"` = division by zero
251
+ - `"54000"` = result too large
252
+
253
+ ## Persistence and ownership
254
+
255
+ For an `open("/data/orders", ...)` call:
256
+
257
+ - `/data/orders/data/` is PGDATA (catalogs, tables, WAL and configuration).
258
+ - `/data/orders/runtime/` contains bundled initialization/support files.
259
+ - Bootstrap and shared-memory scratch files also stay beneath `/data/orders`.
260
+
261
+ Mount the entire root on persistent storage and reuse it after restarts.
262
+ Initialization creates the cluster once; later starts reuse it. Incomplete
263
+ clusters or an incompatible PostgreSQL major version are rejected.
264
+ `fsync`, `synchronous_commit`, and `full_page_writes` are enabled before the
265
+ backend starts. The host filesystem must honor WASI sync operations; a local
266
+ restart test is not a power-loss durability certification.
267
+
268
+ **Give each database directory one component owner at a time.** The provider
269
+ rejects a second simultaneous connection within its component instance. Close
270
+ or drop rolls back uncommitted work, resets session settings, and allows the
271
+ same root to be reopened. A component instance stays bound to its first root;
272
+ use another instance for a different database.
273
+
274
+ There is no cross-instance filesystem lock in this WASI implementation. The
275
+ host must serialize access to each directory, including request instances and
276
+ rolling replacements. A single replica alone does not prevent concurrent
277
+ request instances from sharing files. Do not mount one root into overlapping
278
+ instances or replicas. Fatal engine traps require a new component instance.
279
+
280
+ For the framework's platform-managed storage, annotate the WorkloadDeployment:
281
+
282
+ ```yaml
283
+ metadata:
284
+ annotations:
285
+ di-framework.dev/persistent-storage: "true"
286
+ di-framework.dev/storage-mount: /data
287
+ ```
288
+
289
+ The platform controller mounts the workload's persistent directory and grants
290
+ its components the matching WASI preopen. Use a stable workload identity on
291
+ redeploy and configure exclusive execution for this database. These
292
+ annotations provide storage; they do not enforce database ownership.
293
+
294
+ ## Implementation
295
+
296
+ - `js/adapter.ts`: the `SqlDatabase` adapter published on npm (`bun run build:adapter`).
297
+ - `js/wit.d.ts`: generated TypeScript view of the `database` interface.
298
+ - `src/lib.rs`: public WIT resources and connection lifecycle.
299
+ - `src/pgwire.rs`: PostgreSQL message encoding and typed rows, over memory.
300
+ - `src/engine.rs`: persistent filesystem setup and exclusive engine access.
301
+ - `engine/bridge.wat`: private canonical ABI bridge to the core engine.
302
+ - `scripts/prepare-engine.ts`: pinned engine preparation and componentization (all build scripts are Bun TypeScript; see `scripts/`).
303
+ - `wit/deps/pglite-engine/engine.wit`: internal interface, composed away at build.
304
+
305
+ Engine provenance and modifications are described in `engine/NOTICE`.
@@ -0,0 +1,13 @@
1
+ component: di-framework:pglite@0.2.0
2
+ profile: release
3
+ built: 2026-10-12T04:34:54Z
4
+ rustc: rustc 1.97.1 (8bab26f4f 2026-07-14)
5
+ target: wasm32-wasip2
6
+ wasm-tools: wasm-tools 1.258.0 (5c6d31c78 2026-08-24)
7
+ wit-bindgen: 0.61.1
8
+ md5: 0.7.0
9
+ engine: PostgreSQL 17.5, persistent WASI filesystem
10
+ engine-source: https://github.com/moznion/wasipg/tree/fa290be67946c0d3c4540bd1400b11e193d874e1
11
+ adapter-sha256: e51dd61669a20daca34befe7fdadf1ac84e4795a2c84a8400818ee1de5373ccc
12
+ engine-sha256: b4d513111988a9494ff506c57164762cae91d08c9e80ffdf10f349e5c7f24d7a
13
+ size: 17990191 bytes
@@ -0,0 +1,4 @@
1
+ e8681fc6d6099b33b57e9a63ed72622fa2796fc76c86a4087b6c72c2d8453892 di-framework-pglite.wasm
2
+ 6053154ec1bc94de63ce4f4f4cce5922ef57dce794c2dde326f5845b8982d35f di-framework-pglite.wit
3
+ eac0414a2dd37c0a5ff904037d65a07aa0328fa8ccc2dcd77b7efd870b9425da BUILD-INFO.txt
4
+ 0b8bbbe8aa2898431d20371148a445c9b1ecdecb2ca81d3c98d43256f650590e THIRD-PARTY-NOTICES.txt