@pgxsinkit/pgwasm 0.5.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 (209) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +111 -0
  4. package/README.md +56 -0
  5. package/dist/build/index.d.ts +8 -0
  6. package/dist/build/index.d.ts.map +1 -0
  7. package/dist/build/index.js +21 -0
  8. package/dist/build/index.js.map +9 -0
  9. package/dist/build/seam.d.ts +174 -0
  10. package/dist/build/seam.d.ts.map +1 -0
  11. package/dist/chunk-0w227vw2.js +233 -0
  12. package/dist/chunk-0w227vw2.js.map +11 -0
  13. package/dist/chunk-74gcrk47.js +563 -0
  14. package/dist/chunk-74gcrk47.js.map +14 -0
  15. package/dist/chunk-at1py5s5.js +373 -0
  16. package/dist/chunk-at1py5s5.js.map +12 -0
  17. package/dist/chunk-cpsnmzrf.js +126 -0
  18. package/dist/chunk-cpsnmzrf.js.map +10 -0
  19. package/dist/chunk-d82gg1hx.js +306 -0
  20. package/dist/chunk-d82gg1hx.js.map +10 -0
  21. package/dist/chunk-gjf102c9.js +1005 -0
  22. package/dist/chunk-gjf102c9.js.map +16 -0
  23. package/dist/chunk-kb3rsr7n.js +19 -0
  24. package/dist/chunk-kb3rsr7n.js.map +9 -0
  25. package/dist/chunk-tdvrvgt5.js +83 -0
  26. package/dist/chunk-tdvrvgt5.js.map +11 -0
  27. package/dist/chunk-z0c40tja.js +50 -0
  28. package/dist/chunk-z0c40tja.js.map +10 -0
  29. package/dist/core/data-dir-archive.d.ts +17 -0
  30. package/dist/core/data-dir-archive.d.ts.map +1 -0
  31. package/dist/core/internals.d.ts +59 -0
  32. package/dist/core/internals.d.ts.map +1 -0
  33. package/dist/core/marker.d.ts +35 -0
  34. package/dist/core/marker.d.ts.map +1 -0
  35. package/dist/core/mutex.d.ts +9 -0
  36. package/dist/core/mutex.d.ts.map +1 -0
  37. package/dist/core/names.d.ts +11 -0
  38. package/dist/core/names.d.ts.map +1 -0
  39. package/dist/core/parse.d.ts +11 -0
  40. package/dist/core/parse.d.ts.map +1 -0
  41. package/dist/core/pgwasm.d.ts +53 -0
  42. package/dist/core/pgwasm.d.ts.map +1 -0
  43. package/dist/core/storage.d.ts +14 -0
  44. package/dist/core/storage.d.ts.map +1 -0
  45. package/dist/create.d.ts +10 -0
  46. package/dist/create.d.ts.map +1 -0
  47. package/dist/drizzle/codecs.d.ts +9 -0
  48. package/dist/drizzle/codecs.d.ts.map +1 -0
  49. package/dist/drizzle/driver.d.ts +50 -0
  50. package/dist/drizzle/driver.d.ts.map +1 -0
  51. package/dist/drizzle/index.d.ts +4 -0
  52. package/dist/drizzle/index.d.ts.map +1 -0
  53. package/dist/drizzle/index.js +261 -0
  54. package/dist/drizzle/index.js.map +12 -0
  55. package/dist/drizzle/session.d.ts +39 -0
  56. package/dist/drizzle/session.d.ts.map +1 -0
  57. package/dist/errors.d.ts +115 -0
  58. package/dist/errors.d.ts.map +1 -0
  59. package/dist/fs/base-filesystem.d.ts +118 -0
  60. package/dist/fs/base-filesystem.d.ts.map +1 -0
  61. package/dist/fs/index.d.ts +2 -0
  62. package/dist/fs/index.d.ts.map +1 -0
  63. package/dist/fs/index.js +11 -0
  64. package/dist/fs/index.js.map +9 -0
  65. package/dist/index.d.ts +8 -0
  66. package/dist/index.d.ts.map +1 -0
  67. package/dist/index.js +53 -0
  68. package/dist/index.js.map +9 -0
  69. package/dist/interface.d.ts +165 -0
  70. package/dist/interface.d.ts.map +1 -0
  71. package/dist/live/debounce-mutex.d.ts +6 -0
  72. package/dist/live/debounce-mutex.d.ts.map +1 -0
  73. package/dist/live/format-query.d.ts +8 -0
  74. package/dist/live/format-query.d.ts.map +1 -0
  75. package/dist/live/index.d.ts +9 -0
  76. package/dist/live/index.d.ts.map +1 -0
  77. package/dist/live/index.js +601 -0
  78. package/dist/live/index.js.map +12 -0
  79. package/dist/live/interface.d.ts +86 -0
  80. package/dist/live/interface.d.ts.map +1 -0
  81. package/dist/opfs/broker/client.d.ts +163 -0
  82. package/dist/opfs/broker/client.d.ts.map +1 -0
  83. package/dist/opfs/broker/protocol.d.ts +326 -0
  84. package/dist/opfs/broker/protocol.d.ts.map +1 -0
  85. package/dist/opfs/broker/server.d.ts +84 -0
  86. package/dist/opfs/broker/server.d.ts.map +1 -0
  87. package/dist/opfs/core/checksum.d.ts +3 -0
  88. package/dist/opfs/core/checksum.d.ts.map +1 -0
  89. package/dist/opfs/core/codec.d.ts +73 -0
  90. package/dist/opfs/core/codec.d.ts.map +1 -0
  91. package/dist/opfs/core/errors.d.ts +80 -0
  92. package/dist/opfs/core/errors.d.ts.map +1 -0
  93. package/dist/opfs/core/limits.d.ts +35 -0
  94. package/dist/opfs/core/limits.d.ts.map +1 -0
  95. package/dist/opfs/core/memory-port.d.ts +51 -0
  96. package/dist/opfs/core/memory-port.d.ts.map +1 -0
  97. package/dist/opfs/core/metadata-store.d.ts +19 -0
  98. package/dist/opfs/core/metadata-store.d.ts.map +1 -0
  99. package/dist/opfs/core/mounted-vfs.d.ts +119 -0
  100. package/dist/opfs/core/mounted-vfs.d.ts.map +1 -0
  101. package/dist/opfs/core/path.d.ts +14 -0
  102. package/dist/opfs/core/path.d.ts.map +1 -0
  103. package/dist/opfs/core/port.d.ts +30 -0
  104. package/dist/opfs/core/port.d.ts.map +1 -0
  105. package/dist/opfs/core/repacked-vfs.d.ts +138 -0
  106. package/dist/opfs/core/repacked-vfs.d.ts.map +1 -0
  107. package/dist/opfs/core/state-machine.d.ts +296 -0
  108. package/dist/opfs/core/state-machine.d.ts.map +1 -0
  109. package/dist/opfs/create.d.ts +50 -0
  110. package/dist/opfs/create.d.ts.map +1 -0
  111. package/dist/opfs/file-port.d.ts +14 -0
  112. package/dist/opfs/file-port.d.ts.map +1 -0
  113. package/dist/opfs/index.d.ts +37 -0
  114. package/dist/opfs/index.d.ts.map +1 -0
  115. package/dist/opfs/index.js +6671 -0
  116. package/dist/opfs/index.js.map +28 -0
  117. package/dist/opfs/opfs-port.d.ts +34 -0
  118. package/dist/opfs/opfs-port.d.ts.map +1 -0
  119. package/dist/opfs/opfs-repacked-fs.d.ts +55 -0
  120. package/dist/opfs/opfs-repacked-fs.d.ts.map +1 -0
  121. package/dist/opfs/wasi/preview1.d.ts +228 -0
  122. package/dist/opfs/wasi/preview1.d.ts.map +1 -0
  123. package/dist/protocol/index.d.ts +15 -0
  124. package/dist/protocol/index.d.ts.map +1 -0
  125. package/dist/protocol/index.js +23 -0
  126. package/dist/protocol/index.js.map +10 -0
  127. package/dist/protocol/wire/buffer-reader.d.ts +13 -0
  128. package/dist/protocol/wire/buffer-reader.d.ts.map +1 -0
  129. package/dist/protocol/wire/buffer-writer.d.ts +12 -0
  130. package/dist/protocol/wire/buffer-writer.d.ts.map +1 -0
  131. package/dist/protocol/wire/index.d.ts +5 -0
  132. package/dist/protocol/wire/index.d.ts.map +1 -0
  133. package/dist/protocol/wire/messages.d.ts +194 -0
  134. package/dist/protocol/wire/messages.d.ts.map +1 -0
  135. package/dist/protocol/wire/parser.d.ts +12 -0
  136. package/dist/protocol/wire/parser.d.ts.map +1 -0
  137. package/dist/protocol/wire/serializer.d.ts +61 -0
  138. package/dist/protocol/wire/serializer.d.ts.map +1 -0
  139. package/dist/protocol/wire/string-utils.d.ts +6 -0
  140. package/dist/protocol/wire/string-utils.d.ts.map +1 -0
  141. package/dist/protocol/wire/types.d.ts +7 -0
  142. package/dist/protocol/wire/types.d.ts.map +1 -0
  143. package/dist/tar/gzip.d.ts +7 -0
  144. package/dist/tar/gzip.d.ts.map +1 -0
  145. package/dist/tar/tar.d.ts +39 -0
  146. package/dist/tar/tar.d.ts.map +1 -0
  147. package/dist/templating.d.ts +42 -0
  148. package/dist/templating.d.ts.map +1 -0
  149. package/dist/types.d.ts +76 -0
  150. package/dist/types.d.ts.map +1 -0
  151. package/package.json +69 -0
  152. package/skills/opfs/SKILL.md +138 -0
  153. package/src/build/index.ts +23 -0
  154. package/src/build/seam.ts +179 -0
  155. package/src/core/data-dir-archive.ts +68 -0
  156. package/src/core/internals.ts +87 -0
  157. package/src/core/marker.ts +94 -0
  158. package/src/core/mutex.ts +16 -0
  159. package/src/core/names.ts +26 -0
  160. package/src/core/parse.ts +79 -0
  161. package/src/core/pgwasm.ts +876 -0
  162. package/src/core/storage.ts +70 -0
  163. package/src/create.ts +134 -0
  164. package/src/drizzle/codecs.ts +114 -0
  165. package/src/drizzle/driver.ts +141 -0
  166. package/src/drizzle/index.ts +15 -0
  167. package/src/drizzle/session.ts +133 -0
  168. package/src/errors.ts +201 -0
  169. package/src/fs/base-filesystem.ts +149 -0
  170. package/src/fs/index.ts +7 -0
  171. package/src/index.ts +44 -0
  172. package/src/interface.ts +186 -0
  173. package/src/live/debounce-mutex.ts +45 -0
  174. package/src/live/format-query.ts +47 -0
  175. package/src/live/index.ts +707 -0
  176. package/src/live/interface.ts +109 -0
  177. package/src/opfs/broker/client.ts +482 -0
  178. package/src/opfs/broker/protocol.ts +624 -0
  179. package/src/opfs/broker/server.ts +522 -0
  180. package/src/opfs/core/checksum.ts +85 -0
  181. package/src/opfs/core/codec.ts +1051 -0
  182. package/src/opfs/core/errors.ts +134 -0
  183. package/src/opfs/core/limits.ts +68 -0
  184. package/src/opfs/core/memory-port.ts +459 -0
  185. package/src/opfs/core/metadata-store.ts +512 -0
  186. package/src/opfs/core/mounted-vfs.ts +407 -0
  187. package/src/opfs/core/path.ts +82 -0
  188. package/src/opfs/core/port.ts +114 -0
  189. package/src/opfs/core/repacked-vfs.ts +1464 -0
  190. package/src/opfs/core/state-machine.ts +1699 -0
  191. package/src/opfs/create.ts +125 -0
  192. package/src/opfs/file-port.ts +183 -0
  193. package/src/opfs/index.ts +113 -0
  194. package/src/opfs/opfs-port.ts +90 -0
  195. package/src/opfs/opfs-repacked-fs.ts +210 -0
  196. package/src/opfs/wasi/preview1.ts +1016 -0
  197. package/src/protocol/index.ts +24 -0
  198. package/src/protocol/wire/buffer-reader.ts +60 -0
  199. package/src/protocol/wire/buffer-writer.ts +93 -0
  200. package/src/protocol/wire/index.ts +15 -0
  201. package/src/protocol/wire/messages.ts +332 -0
  202. package/src/protocol/wire/parser.ts +373 -0
  203. package/src/protocol/wire/serializer.ts +233 -0
  204. package/src/protocol/wire/string-utils.ts +18 -0
  205. package/src/protocol/wire/types.ts +12 -0
  206. package/src/tar/gzip.ts +36 -0
  207. package/src/tar/tar.ts +253 -0
  208. package/src/templating.ts +103 -0
  209. package/src/types.ts +283 -0
@@ -0,0 +1,70 @@
1
+ // Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL
2
+ // — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.
3
+
4
+ import type { StorageRequest } from "../build/seam";
5
+ import { OpfsAhpRemovedError, UnsupportedDataDirError } from "../errors";
6
+ import type { BaseFilesystem } from "../fs/base-filesystem";
7
+ import type { StorageDescription } from "../interface";
8
+
9
+ /**
10
+ * Resolve the `dataDir` / `fs` options into the storage a build mounts. A scheme is required
11
+ * (`memory://`, `idb://<name>`, `file://<path>`); a bare path, an unknown scheme and the removed
12
+ * `opfs-ahp://` are refused before anything is booted.
13
+ */
14
+ export function resolveStorage(dataDir: string | undefined, fs: BaseFilesystem | undefined): StorageRequest {
15
+ if (fs !== undefined) {
16
+ if (dataDir !== undefined) {
17
+ throw new UnsupportedDataDirError(dataDir, "`dataDir` and `fs` are exclusive; pass one of them");
18
+ }
19
+ return { kind: "vfs", vfs: fs };
20
+ }
21
+ if (dataDir === undefined || dataDir.startsWith("memory://")) {
22
+ return { kind: "memory" };
23
+ }
24
+ if (dataDir.startsWith("idb://")) {
25
+ const name = dataDir.slice("idb://".length);
26
+ if (name === "") throw new UnsupportedDataDirError(dataDir, "an IndexedDB store needs a name (idb://<name>)");
27
+ return { kind: "idb", name };
28
+ }
29
+ if (dataDir.startsWith("file://")) {
30
+ const path = dataDir.slice("file://".length);
31
+ if (path === "") throw new UnsupportedDataDirError(dataDir, "a file store needs a path (file://<path>)");
32
+ return { kind: "file", path };
33
+ }
34
+ if (dataDir.startsWith("opfs-ahp://")) {
35
+ throw new OpfsAhpRemovedError(dataDir);
36
+ }
37
+ const scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(dataDir)?.[1];
38
+ throw new UnsupportedDataDirError(
39
+ dataDir,
40
+ scheme === undefined
41
+ ? "a scheme is required: memory://, idb://<name> or file://<path>"
42
+ : `unknown scheme "${scheme}://" (supported: memory://, idb://<name>, file://<path>)`,
43
+ );
44
+ }
45
+
46
+ /** The public description of where a data directory lives. */
47
+ export function describeStorage(storage: StorageRequest): StorageDescription {
48
+ switch (storage.kind) {
49
+ case "memory":
50
+ return { kind: "memory" };
51
+ case "idb":
52
+ return { kind: "idb", name: storage.name };
53
+ case "file":
54
+ return { kind: "file", path: storage.path };
55
+ case "vfs": {
56
+ const { name, persistent } = storage.vfs.description;
57
+ return persistent === undefined ? { kind: "vfs", name } : { kind: "vfs", name, persistent };
58
+ }
59
+ }
60
+ }
61
+
62
+ /** The file name a Store backup gets: the storage's last path segment, else `pgdata`. */
63
+ export function backupBaseName(storage: StorageDescription): string {
64
+ const location = storage.kind === "idb" ? storage.name : storage.kind === "file" ? storage.path : "";
65
+ const last = location
66
+ .split("/")
67
+ .filter((segment) => segment !== "")
68
+ .pop();
69
+ return last ?? "pgdata";
70
+ }
package/src/create.ts ADDED
@@ -0,0 +1,134 @@
1
+ // Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL
2
+ // — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.
3
+
4
+ import type { DataDirEntry, PostgresBuild, ServerExtension } from "./build/seam";
5
+ import { readDataDirArchive } from "./core/data-dir-archive";
6
+ import { BUILD_MARKER_PATH, checkBuildMarker, encodeBuildMarker, findEntry, PG_VERSION_PATH } from "./core/marker";
7
+ import { PgwasmInstance } from "./core/pgwasm";
8
+ import { resolveStorage } from "./core/storage";
9
+ import {
10
+ BackupFormatError,
11
+ CrossOriginIsolationRequiredError,
12
+ ExtensionBuildMismatchError,
13
+ UnsupportedFilesystemError,
14
+ } from "./errors";
15
+ import type { Extension, Extensions, PgwasmOptions, PgwasmWithExtensions } from "./interface";
16
+
17
+ function isServerExtension(extension: Extension | ServerExtension): extension is ServerExtension {
18
+ return "kind" in extension && extension.kind === "server";
19
+ }
20
+
21
+ function assertBuild(build: unknown): asserts build is PostgresBuild {
22
+ const candidate = build as Partial<PostgresBuild> | null | undefined;
23
+ if (
24
+ typeof candidate !== "object" ||
25
+ candidate === null ||
26
+ typeof candidate.boot !== "function" ||
27
+ typeof candidate.identity?.name !== "string" ||
28
+ !Array.isArray(candidate.capabilities?.filesystems)
29
+ ) {
30
+ throw new TypeError("createPgwasm needs a Postgres build in `build`, e.g. `cBuild` from @pgxsinkit/pgwasm-c.");
31
+ }
32
+ }
33
+
34
+ /** Merge the server extensions' preload libraries into the settings. */
35
+ function mergeSettings(
36
+ settings: Readonly<Record<string, string>> | undefined,
37
+ serverExtensions: readonly ServerExtension[],
38
+ ): Record<string, string> {
39
+ const merged: Record<string, string> = { ...settings };
40
+ const preload = serverExtensions.flatMap((extension) => extension.sharedPreloadLibraries ?? []);
41
+ if (preload.length > 0) {
42
+ const existing = (merged["shared_preload_libraries"] ?? "")
43
+ .split(",")
44
+ .map((library) => library.trim())
45
+ .filter((library) => library !== "");
46
+ merged["shared_preload_libraries"] = [...new Set([...existing, ...preload])].join(",");
47
+ }
48
+ return merged;
49
+ }
50
+
51
+ /**
52
+ * A Store backup's entries, checked against the build before anything is booted, with the build
53
+ * marker added when the backup has none (it predates marking and is the C build's).
54
+ */
55
+ async function restoreEntries(build: PostgresBuild, loadDataDir: Blob | File): Promise<readonly DataDirEntry[]> {
56
+ const entries = await readDataDirArchive(loadDataDir);
57
+ if (findEntry(entries, PG_VERSION_PATH) === undefined) {
58
+ throw new BackupFormatError("The Store backup holds no data directory (it has no PG_VERSION).");
59
+ }
60
+ const marker = findEntry(entries, BUILD_MARKER_PATH);
61
+ checkBuildMarker(build.identity, marker?.data, true, "backup");
62
+ if (marker !== undefined) return entries;
63
+ return [
64
+ ...entries,
65
+ {
66
+ path: BUILD_MARKER_PATH,
67
+ type: "file",
68
+ mode: 0o600,
69
+ mtimeSeconds: Math.floor(Date.now() / 1000),
70
+ data: encodeBuildMarker(build.identity),
71
+ },
72
+ ];
73
+ }
74
+
75
+ /**
76
+ * Start a database on a Postgres build. Resolves once it is ready.
77
+ *
78
+ * Everything that can be checked before booting is: the `dataDir` scheme, the build's supported
79
+ * storage and cross-origin isolation, each server extension's build, and a Store backup's recorded
80
+ * build (ADR-0063). The booted data directory's recorded build is checked before anything is written.
81
+ */
82
+ export async function createPgwasm<E extends Extensions = Record<never, never>>(
83
+ options: PgwasmOptions<E>,
84
+ ): Promise<PgwasmWithExtensions<E>> {
85
+ const build: unknown = options.build;
86
+ assertBuild(build);
87
+ const identity = build.identity;
88
+ const capabilities = build.capabilities;
89
+
90
+ const storage = resolveStorage(options.dataDir, options.fs);
91
+ if (!capabilities.filesystems.includes(storage.kind)) {
92
+ throw new UnsupportedFilesystemError(storage.kind, identity, capabilities.filesystems);
93
+ }
94
+ if (
95
+ capabilities.requiresCrossOriginIsolation &&
96
+ (globalThis as { crossOriginIsolated?: boolean }).crossOriginIsolated === false
97
+ ) {
98
+ throw new CrossOriginIsolationRequiredError(identity);
99
+ }
100
+
101
+ const serverExtensions: ServerExtension[] = [];
102
+ const clientExtensions: [string, Extension][] = [];
103
+ for (const [key, extension] of Object.entries(options.extensions ?? {})) {
104
+ if (isServerExtension(extension)) {
105
+ if (extension.build !== identity.name) {
106
+ throw new ExtensionBuildMismatchError(extension.name, extension.build, identity);
107
+ }
108
+ serverExtensions.push(extension);
109
+ } else {
110
+ clientExtensions.push([key, extension]);
111
+ }
112
+ }
113
+
114
+ const restore = options.loadDataDir === undefined ? undefined : await restoreEntries(build, options.loadDataDir);
115
+ const plan = {
116
+ build,
117
+ storage,
118
+ serverExtensions,
119
+ clientExtensions,
120
+ restore,
121
+ settings: mergeSettings(options.settings, serverExtensions),
122
+ user: options.username ?? "postgres",
123
+ database: options.database ?? "postgres",
124
+ username: options.username,
125
+ debug: options.debug ?? 0,
126
+ relaxedDurability: options.relaxedDurability ?? false,
127
+ parsers: options.parsers,
128
+ serializers: options.serializers,
129
+ } as const;
130
+ const instance = new PgwasmInstance(plan);
131
+ await instance.boot(plan);
132
+ // The namespaces were attached under their keys during boot.
133
+ return instance as PgwasmInstance & PgwasmWithExtensions<E>;
134
+ }
@@ -0,0 +1,114 @@
1
+ // Began as a copy of drizzle-orm's PGlite driver (`src/pglite/*.ts` at 1.0.0-rc.4; Apache-2.0, © Drizzle Team
2
+ // and contributors — see NOTICE). Changes: rebound from PGlite to pgwasm; the driver never constructs its
3
+ // own database. Owned outright (ADR-0062).
4
+
5
+ import { makePgArray, parsePgArray } from "drizzle-orm/pg-core/array";
6
+ import {
7
+ arrayCompatNormalize,
8
+ castToText,
9
+ castToTextArr,
10
+ genericPgCodecs,
11
+ parseGeometryTuple,
12
+ parseGeometryXY,
13
+ parsePgArrayAndNormalize,
14
+ refineGenericPgCodecs,
15
+ textToDate,
16
+ textToDateWithTz,
17
+ type PgCodecs,
18
+ } from "drizzle-orm/pg-core/codecs";
19
+ import { base64ToUint8Array } from "drizzle-orm/utils";
20
+
21
+ import { DATE, INTERVAL, TIMESTAMP, TIMESTAMPTZ } from "../types";
22
+
23
+ /**
24
+ * The identity parsers the driver passes with every query: these types reach drizzle as Postgres'
25
+ * text, and drizzle's codecs turn them into values (dates, intervals, numeric arrays).
26
+ */
27
+ export const drizzleParsers: Readonly<Record<number, (value: string) => string>> = {
28
+ [TIMESTAMP]: (value) => value,
29
+ [TIMESTAMPTZ]: (value) => value,
30
+ [INTERVAL]: (value) => value,
31
+ [DATE]: (value) => value,
32
+ 1231: (value) => value, // numeric[]
33
+ 1115: (value) => value, // timestamp[]
34
+ 1185: (value) => value, // timestamptz[]
35
+ 1187: (value) => value, // interval[]
36
+ 1182: (value) => value, // date[]
37
+ };
38
+
39
+ const hasBuffer = typeof Buffer !== "undefined";
40
+
41
+ /** drizzle's codecs for pgwasm's value formats (the text protocol, pgwasm's default parsers). */
42
+ export const pgwasmCodecs: PgCodecs = refineGenericPgCodecs({
43
+ bigint: {
44
+ cast: castToText,
45
+ castArray: castToTextArr,
46
+ normalize: BigInt,
47
+ normalizeArray: arrayCompatNormalize(BigInt),
48
+ },
49
+ "bigint:string": { cast: castToText, castArray: castToTextArr },
50
+ "bigint:number": { cast: castToText, castArray: castToTextArr },
51
+ bigserial: {
52
+ normalize: BigInt,
53
+ normalizeArray: arrayCompatNormalize(BigInt),
54
+ cast: castToText,
55
+ castArray: castToTextArr,
56
+ },
57
+ "bigserial:number": { cast: castToText, castArray: castToTextArr },
58
+ bytea: hasBuffer
59
+ ? {
60
+ normalizeInJson: genericPgCodecs.bytea?.normalizeInJson,
61
+ normalizeArrayInJson: genericPgCodecs.bytea?.normalizeArrayInJson,
62
+ normalize: (value: Uint8Array) => Buffer.from(value),
63
+ normalizeArray: arrayCompatNormalize((value: Uint8Array) => Buffer.from(value)),
64
+ }
65
+ : {
66
+ normalizeInJson: base64ToUint8Array,
67
+ normalizeArrayInJson: arrayCompatNormalize(base64ToUint8Array),
68
+ },
69
+ interval: { castArray: castToTextArr },
70
+ date: { castArray: castToTextArr, normalize: textToDate, normalizeArray: arrayCompatNormalize(textToDate) },
71
+ "date:string": { castArray: castToTextArr },
72
+ timestamp: {
73
+ castArray: castToTextArr,
74
+ normalize: textToDateWithTz,
75
+ normalizeArray: arrayCompatNormalize(textToDateWithTz),
76
+ },
77
+ timestamptz: { castArray: castToTextArr, normalize: textToDate, normalizeArray: arrayCompatNormalize(textToDate) },
78
+ "timestamp:string": { castArray: castToTextArr },
79
+ "timestamptz:string": { castArray: castToTextArr },
80
+ json: { normalizeParam: (value: unknown) => (typeof value === "object" ? value : JSON.stringify(value)) },
81
+ jsonb: { normalizeParam: (value: unknown) => (typeof value === "object" ? value : JSON.stringify(value)) },
82
+ "geometry(point)": {
83
+ normalizeArray: parsePgArrayAndNormalize(parseGeometryXY),
84
+ castParam: (name: string) => `${name}::geometry`,
85
+ castArrayParam: (name: string, _column: unknown, dimensions: number) =>
86
+ `${name}::geometry${"[]".repeat(dimensions)}`,
87
+ normalizeParamArray: makePgArray,
88
+ },
89
+ "geometry(point):tuple": {
90
+ normalizeArray: parsePgArrayAndNormalize(parseGeometryTuple),
91
+ castParam: (name: string) => `${name}::geometry`,
92
+ castArrayParam: (name: string, _column: unknown, dimensions: number) =>
93
+ `${name}::geometry${"[]".repeat(dimensions)}`,
94
+ normalizeParamArray: makePgArray,
95
+ },
96
+ halfvec: {
97
+ castParam: (name: string) => `${name}::halfvec`,
98
+ castArrayParam: (name: string, _column: unknown, dimensions: number) =>
99
+ `${name}::halfvec${"[]".repeat(dimensions)}`,
100
+ normalizeParamArray: makePgArray,
101
+ },
102
+ vector: {
103
+ castParam: (name: string) => `${name}::vector`,
104
+ castArrayParam: (name: string, _column: unknown, dimensions: number) => `${name}::vector${"[]".repeat(dimensions)}`,
105
+ normalizeParamArray: makePgArray,
106
+ },
107
+ sparsevec: {
108
+ normalizeArray: parsePgArray,
109
+ castParam: (name: string) => `${name}::sparsevec`,
110
+ castArrayParam: (name: string, _column: unknown, dimensions: number) =>
111
+ `${name}::sparsevec${"[]".repeat(dimensions)}`,
112
+ normalizeParamArray: makePgArray,
113
+ },
114
+ });
@@ -0,0 +1,141 @@
1
+ // Began as a copy of drizzle-orm's PGlite driver (`src/pglite/*.ts` at 1.0.0-rc.4; Apache-2.0, © Drizzle Team
2
+ // and contributors — see NOTICE). Changes: rebound from PGlite to pgwasm; the driver never constructs its
3
+ // own database; its own JIT capability probe; `$cache.invalidate` bound without changing the caller's
4
+ // cache object. Owned outright (ADR-0062).
5
+
6
+ import { entityKind } from "drizzle-orm/entity";
7
+ import { DefaultLogger, type Logger } from "drizzle-orm/logger";
8
+ import { PgAsyncDatabase } from "drizzle-orm/pg-core/async/db";
9
+ import { PgDialect } from "drizzle-orm/pg-core/dialect";
10
+ import type { DrizzlePgConfig } from "drizzle-orm/pg-core/utils";
11
+ import type { AnyRelations, EmptyRelations } from "drizzle-orm/relations";
12
+
13
+ import { PgwasmError } from "../errors";
14
+ import type { Pgwasm } from "../interface";
15
+ import { pgwasmCodecs } from "./codecs";
16
+ import { PgwasmSession, type PgwasmQueryResultHKT, type PgwasmSessionClient } from "./session";
17
+
18
+ export class PgwasmDatabase<TRelations extends AnyRelations = EmptyRelations> extends PgAsyncDatabase<
19
+ PgwasmQueryResultHKT,
20
+ TRelations
21
+ > {
22
+ static override readonly [entityKind]: string = "PgwasmDatabase";
23
+ }
24
+
25
+ /**
26
+ * Whether to use JIT row mappers: only when asked for (`jit: true`) and `new Function` works here. JIT
27
+ * mappers are compiled with it, and a strict content security policy (an MV3 extension page's) makes it
28
+ * throw; the driver then falls back to the premade mappers instead of failing every query.
29
+ */
30
+ export function jitMappersUsable(requested: boolean | undefined): boolean {
31
+ if (requested !== true) return false;
32
+ try {
33
+ // oxlint-disable-next-line typescript/no-implied-eval -- the probe: does this context allow it at all
34
+ const identity = new Function("input", '"use strict"; return input;') as (input: unknown) => unknown;
35
+ return identity(true) === true;
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+
41
+ function construct<TRelations extends AnyRelations, TClient extends PgwasmSessionClient>(
42
+ client: TClient,
43
+ config: DrizzlePgConfig<TRelations> = {},
44
+ ): PgwasmDatabase<TRelations> & { $client: TClient } {
45
+ const dialect = new PgDialect({
46
+ useJitMappers: jitMappersUsable(config.jit),
47
+ codecs: config.codecs ?? pgwasmCodecs,
48
+ });
49
+ const logger: Logger | undefined =
50
+ config.logger === true ? new DefaultLogger() : config.logger === false ? undefined : config.logger;
51
+ const relations = (config.relations ?? {}) as TRelations;
52
+ const session = new PgwasmSession<TRelations>(client, dialect, relations, {
53
+ ...(logger ? { logger } : {}),
54
+ ...(config.cache ? { cache: config.cache } : {}),
55
+ });
56
+ const db = new PgwasmDatabase<TRelations>(dialect, session, relations);
57
+ // `db.$cache.invalidate` is the cache's own invalidation; with no cache it stays the no-op it starts as.
58
+ const cache = config.cache;
59
+ if (cache) db.$cache = { invalidate: (params) => cache.onMutate(params) };
60
+ return Object.assign(db, { $client: client });
61
+ }
62
+
63
+ /** drizzle's object form: its config, with the pgwasm database as `client`. */
64
+ export type PgwasmDrizzleConfig<
65
+ TRelations extends AnyRelations = EmptyRelations,
66
+ TClient extends Pgwasm = Pgwasm,
67
+ > = DrizzlePgConfig<TRelations> & { client: TClient };
68
+
69
+ /** The form of a `drizzle()` call that would have the driver open its own database. */
70
+ export type UnsupportedDrizzleForm = "connection" | "connection string" | "no client";
71
+
72
+ /**
73
+ * A `drizzle()` call without a pgwasm database: `drizzle({ connection })`, `drizzle("…")`, `drizzle()`, or a
74
+ * `client` that is not a pgwasm database. The driver never opens its own database: create one with
75
+ * `createPgwasm()` and pass it in.
76
+ */
77
+ export class UnsupportedDrizzleConfigError extends PgwasmError {
78
+ override name = "UnsupportedDrizzleConfigError";
79
+ readonly form: UnsupportedDrizzleForm;
80
+
81
+ constructor(form: UnsupportedDrizzleForm) {
82
+ const given =
83
+ form === "connection"
84
+ ? "drizzle({ connection })"
85
+ : form === "connection string"
86
+ ? "drizzle(connectionString)"
87
+ : "a drizzle() call without a pgwasm database";
88
+ super(
89
+ `@pgxsinkit/pgwasm/drizzle does not open its own database, so ${given} is not supported: create the ` +
90
+ "database with createPgwasm() and pass it as drizzle(pg, config) or drizzle({ client: pg, ...config }).",
91
+ );
92
+ this.form = form;
93
+ }
94
+ }
95
+
96
+ function isPgwasm(value: unknown): value is Pgwasm {
97
+ return typeof value === "object" && value !== null && typeof (value as Partial<Pgwasm>).query === "function";
98
+ }
99
+
100
+ /**
101
+ * A Drizzle database over a pgwasm database: `drizzle(pg, config)`, or drizzle's object form
102
+ * `drizzle({ client: pg, ...config })`, which is the same thing. The driver never opens its own database, so
103
+ * the forms that would (`{ connection }`, a connection string) are not accepted; at runtime they throw
104
+ * {@link UnsupportedDrizzleConfigError}.
105
+ */
106
+ export function drizzle<TRelations extends AnyRelations = EmptyRelations, TClient extends Pgwasm = Pgwasm>(
107
+ client: TClient,
108
+ config?: DrizzlePgConfig<TRelations>,
109
+ ): PgwasmDatabase<TRelations> & { $client: TClient };
110
+ export function drizzle<TRelations extends AnyRelations = EmptyRelations, TClient extends Pgwasm = Pgwasm>(
111
+ config: PgwasmDrizzleConfig<TRelations, TClient>,
112
+ ): PgwasmDatabase<TRelations> & { $client: TClient };
113
+ export function drizzle<TRelations extends AnyRelations = EmptyRelations>(
114
+ clientOrConfig: Pgwasm | PgwasmDrizzleConfig<TRelations>,
115
+ config?: DrizzlePgConfig<TRelations>,
116
+ ): PgwasmDatabase<TRelations> & { $client: Pgwasm } {
117
+ const given: unknown = clientOrConfig;
118
+ if (isPgwasm(given)) return construct(given, config);
119
+ if (typeof given === "string") throw new UnsupportedDrizzleConfigError("connection string");
120
+ if (typeof given === "object" && given !== null) {
121
+ const { client, ...rest } = given as Partial<PgwasmDrizzleConfig<TRelations>> & { connection?: unknown };
122
+ // A `connection` next to a pgwasm `client` is ignored, as drizzle's own drivers do.
123
+ if (isPgwasm(client)) return construct(client, rest);
124
+ if (client === undefined && "connection" in given) throw new UnsupportedDrizzleConfigError("connection");
125
+ }
126
+ throw new UnsupportedDrizzleConfigError("no client");
127
+ }
128
+
129
+ const unavailable: PgwasmSessionClient = {
130
+ query: () => {
131
+ throw new Error("drizzle.mock() has no database: build queries with it, run them elsewhere.");
132
+ },
133
+ };
134
+
135
+ /** A Drizzle database with no database behind it, for building SQL (`.toSQL()`). */
136
+ drizzle.mock = function mock<TRelations extends AnyRelations = EmptyRelations>(
137
+ config?: DrizzlePgConfig<TRelations>,
138
+ ): PgwasmDatabase<TRelations> & { $client: "$client is not available on drizzle.mock()" } {
139
+ const db = construct(unavailable, config);
140
+ return Object.assign(db, { $client: "$client is not available on drizzle.mock()" as const });
141
+ };
@@ -0,0 +1,15 @@
1
+ export {
2
+ drizzle,
3
+ PgwasmDatabase,
4
+ UnsupportedDrizzleConfigError,
5
+ type PgwasmDrizzleConfig,
6
+ type UnsupportedDrizzleForm,
7
+ } from "./driver";
8
+ export {
9
+ PgwasmSession,
10
+ PgwasmTransaction,
11
+ type PgwasmQueryResultHKT,
12
+ type PgwasmSessionClient,
13
+ type PgwasmSessionOptions,
14
+ } from "./session";
15
+ export { drizzleParsers, pgwasmCodecs } from "./codecs";
@@ -0,0 +1,133 @@
1
+ // Began as a copy of drizzle-orm's PGlite driver (`src/pglite/*.ts` at 1.0.0-rc.4; Apache-2.0, © Drizzle Team
2
+ // and contributors — see NOTICE). Changes: rebound from PGlite to pgwasm; the driver never constructs its
3
+ // own database. Owned outright (ADR-0062).
4
+
5
+ import type { Cache } from "drizzle-orm/cache/core/cache";
6
+ import { NoopCache } from "drizzle-orm/cache/core/cache";
7
+ import type { WithCacheConfig } from "drizzle-orm/cache/core/types";
8
+ import { entityKind } from "drizzle-orm/entity";
9
+ import { NoopLogger, type Logger } from "drizzle-orm/logger";
10
+ import { PgAsyncPreparedQuery, PgAsyncSession, PgAsyncTransaction } from "drizzle-orm/pg-core/async/session";
11
+ import type { PgDialect } from "drizzle-orm/pg-core/dialect";
12
+ import type { PgQueryResultHKT, PgTransactionConfig, PreparedQueryConfig } from "drizzle-orm/pg-core/session";
13
+ import type { AnyRelations } from "drizzle-orm/relations";
14
+ import { sql, type Query } from "drizzle-orm/sql/sql";
15
+ import type { Assume } from "drizzle-orm/utils";
16
+
17
+ import type { Pgwasm, Results, Row, Transaction } from "../interface";
18
+ import { drizzleParsers } from "./codecs";
19
+
20
+ /** What a session runs statements on: a database, or a transaction's handle. */
21
+ export type PgwasmSessionClient = Pick<Pgwasm, "query"> & Partial<Pick<Pgwasm, "transaction">>;
22
+
23
+ export interface PgwasmSessionOptions {
24
+ logger?: Logger;
25
+ cache?: Cache;
26
+ }
27
+
28
+ export interface PgwasmQueryResultHKT extends PgQueryResultHKT {
29
+ type: Results<Assume<this["row"], Row>>;
30
+ }
31
+
32
+ type QueryMetadata = { type: "select" | "update" | "delete" | "insert"; tables: string[] };
33
+
34
+ export class PgwasmSession<TRelations extends AnyRelations> extends PgAsyncSession<PgwasmQueryResultHKT, TRelations> {
35
+ static override readonly [entityKind]: string = "PgwasmSession";
36
+ readonly #client: PgwasmSessionClient;
37
+ readonly #relations: TRelations;
38
+ readonly #options: PgwasmSessionOptions;
39
+ readonly #logger: Logger;
40
+ readonly #cache: Cache;
41
+
42
+ constructor(
43
+ client: PgwasmSessionClient,
44
+ dialect: PgDialect,
45
+ relations: TRelations,
46
+ options: PgwasmSessionOptions = {},
47
+ ) {
48
+ super(dialect);
49
+ this.#client = client;
50
+ this.#relations = relations;
51
+ this.#options = options;
52
+ this.#logger = options.logger ?? new NoopLogger();
53
+ this.#cache = options.cache ?? new NoopCache();
54
+ }
55
+
56
+ prepareQuery<T extends PreparedQueryConfig = PreparedQueryConfig>(
57
+ query: Query,
58
+ mode: "arrays" | "objects" | "raw",
59
+ _name: string | boolean,
60
+ mapper: ((rows: unknown[]) => unknown) | undefined,
61
+ queryMetadata?: QueryMetadata,
62
+ cacheConfig?: WithCacheConfig,
63
+ ): PgAsyncPreparedQuery<T> {
64
+ const executor = async (params?: unknown[]) => {
65
+ const result = await this.#client.query(query.sql, params, {
66
+ rowMode: mode === "arrays" ? "array" : "object",
67
+ parsers: drizzleParsers,
68
+ });
69
+ return mode === "raw" ? result : result.rows;
70
+ };
71
+ return new PgAsyncPreparedQuery<T>(
72
+ executor,
73
+ query,
74
+ mapper,
75
+ mode,
76
+ this.#logger,
77
+ this.#cache,
78
+ queryMetadata,
79
+ cacheConfig,
80
+ );
81
+ }
82
+
83
+ async transaction<T>(
84
+ transaction: (tx: PgwasmTransaction<TRelations>) => Promise<T>,
85
+ config?: PgTransactionConfig,
86
+ ): Promise<T> {
87
+ const client = this.#client;
88
+ if (client.transaction === undefined) {
89
+ throw new Error("A transaction's session cannot begin another transaction; nest with tx.transaction().");
90
+ }
91
+ return await client.transaction(async (handle: Transaction) => {
92
+ const session = new PgwasmSession(handle, this.dialect, this.#relations, this.#options);
93
+ const tx = new PgwasmTransaction(this.dialect, session, this.#relations, undefined, false);
94
+ if (config) await tx.setTransaction(config);
95
+ return await transaction(tx);
96
+ });
97
+ }
98
+ }
99
+
100
+ export class PgwasmTransaction<TRelations extends AnyRelations> extends PgAsyncTransaction<
101
+ PgwasmQueryResultHKT,
102
+ TRelations
103
+ > {
104
+ static override readonly [entityKind]: string = "PgwasmTransaction";
105
+ readonly #dialect: PgDialect;
106
+ readonly #session: PgwasmSession<TRelations>;
107
+
108
+ constructor(
109
+ dialect: PgDialect,
110
+ session: PgwasmSession<TRelations>,
111
+ relations: TRelations,
112
+ nestedIndex: number | undefined,
113
+ parseRqbJson: boolean | undefined,
114
+ ) {
115
+ super(dialect, session, relations, nestedIndex, parseRqbJson);
116
+ this.#dialect = dialect;
117
+ this.#session = session;
118
+ }
119
+
120
+ async transaction<T>(transaction: (tx: PgwasmTransaction<TRelations>) => Promise<T>): Promise<T> {
121
+ const savepointName = `sp${this.nestedIndex + 1}`;
122
+ const tx = new PgwasmTransaction(this.#dialect, this.#session, this._.relations, this.nestedIndex + 1, false);
123
+ await tx.execute(sql.raw(`savepoint ${savepointName}`));
124
+ try {
125
+ const result = await transaction(tx);
126
+ await tx.execute(sql.raw(`release savepoint ${savepointName}`));
127
+ return result;
128
+ } catch (error) {
129
+ await tx.execute(sql.raw(`rollback to savepoint ${savepointName}`));
130
+ throw error;
131
+ }
132
+ }
133
+ }