@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.
- package/LICENSE +21 -0
- package/LICENSE-APACHE-2.0 +202 -0
- package/NOTICE +111 -0
- package/README.md +56 -0
- package/dist/build/index.d.ts +8 -0
- package/dist/build/index.d.ts.map +1 -0
- package/dist/build/index.js +21 -0
- package/dist/build/index.js.map +9 -0
- package/dist/build/seam.d.ts +174 -0
- package/dist/build/seam.d.ts.map +1 -0
- package/dist/chunk-0w227vw2.js +233 -0
- package/dist/chunk-0w227vw2.js.map +11 -0
- package/dist/chunk-74gcrk47.js +563 -0
- package/dist/chunk-74gcrk47.js.map +14 -0
- package/dist/chunk-at1py5s5.js +373 -0
- package/dist/chunk-at1py5s5.js.map +12 -0
- package/dist/chunk-cpsnmzrf.js +126 -0
- package/dist/chunk-cpsnmzrf.js.map +10 -0
- package/dist/chunk-d82gg1hx.js +306 -0
- package/dist/chunk-d82gg1hx.js.map +10 -0
- package/dist/chunk-gjf102c9.js +1005 -0
- package/dist/chunk-gjf102c9.js.map +16 -0
- package/dist/chunk-kb3rsr7n.js +19 -0
- package/dist/chunk-kb3rsr7n.js.map +9 -0
- package/dist/chunk-tdvrvgt5.js +83 -0
- package/dist/chunk-tdvrvgt5.js.map +11 -0
- package/dist/chunk-z0c40tja.js +50 -0
- package/dist/chunk-z0c40tja.js.map +10 -0
- package/dist/core/data-dir-archive.d.ts +17 -0
- package/dist/core/data-dir-archive.d.ts.map +1 -0
- package/dist/core/internals.d.ts +59 -0
- package/dist/core/internals.d.ts.map +1 -0
- package/dist/core/marker.d.ts +35 -0
- package/dist/core/marker.d.ts.map +1 -0
- package/dist/core/mutex.d.ts +9 -0
- package/dist/core/mutex.d.ts.map +1 -0
- package/dist/core/names.d.ts +11 -0
- package/dist/core/names.d.ts.map +1 -0
- package/dist/core/parse.d.ts +11 -0
- package/dist/core/parse.d.ts.map +1 -0
- package/dist/core/pgwasm.d.ts +53 -0
- package/dist/core/pgwasm.d.ts.map +1 -0
- package/dist/core/storage.d.ts +14 -0
- package/dist/core/storage.d.ts.map +1 -0
- package/dist/create.d.ts +10 -0
- package/dist/create.d.ts.map +1 -0
- package/dist/drizzle/codecs.d.ts +9 -0
- package/dist/drizzle/codecs.d.ts.map +1 -0
- package/dist/drizzle/driver.d.ts +50 -0
- package/dist/drizzle/driver.d.ts.map +1 -0
- package/dist/drizzle/index.d.ts +4 -0
- package/dist/drizzle/index.d.ts.map +1 -0
- package/dist/drizzle/index.js +261 -0
- package/dist/drizzle/index.js.map +12 -0
- package/dist/drizzle/session.d.ts +39 -0
- package/dist/drizzle/session.d.ts.map +1 -0
- package/dist/errors.d.ts +115 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/fs/base-filesystem.d.ts +118 -0
- package/dist/fs/base-filesystem.d.ts.map +1 -0
- package/dist/fs/index.d.ts +2 -0
- package/dist/fs/index.d.ts.map +1 -0
- package/dist/fs/index.js +11 -0
- package/dist/fs/index.js.map +9 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +53 -0
- package/dist/index.js.map +9 -0
- package/dist/interface.d.ts +165 -0
- package/dist/interface.d.ts.map +1 -0
- package/dist/live/debounce-mutex.d.ts +6 -0
- package/dist/live/debounce-mutex.d.ts.map +1 -0
- package/dist/live/format-query.d.ts +8 -0
- package/dist/live/format-query.d.ts.map +1 -0
- package/dist/live/index.d.ts +9 -0
- package/dist/live/index.d.ts.map +1 -0
- package/dist/live/index.js +601 -0
- package/dist/live/index.js.map +12 -0
- package/dist/live/interface.d.ts +86 -0
- package/dist/live/interface.d.ts.map +1 -0
- package/dist/opfs/broker/client.d.ts +163 -0
- package/dist/opfs/broker/client.d.ts.map +1 -0
- package/dist/opfs/broker/protocol.d.ts +326 -0
- package/dist/opfs/broker/protocol.d.ts.map +1 -0
- package/dist/opfs/broker/server.d.ts +84 -0
- package/dist/opfs/broker/server.d.ts.map +1 -0
- package/dist/opfs/core/checksum.d.ts +3 -0
- package/dist/opfs/core/checksum.d.ts.map +1 -0
- package/dist/opfs/core/codec.d.ts +73 -0
- package/dist/opfs/core/codec.d.ts.map +1 -0
- package/dist/opfs/core/errors.d.ts +80 -0
- package/dist/opfs/core/errors.d.ts.map +1 -0
- package/dist/opfs/core/limits.d.ts +35 -0
- package/dist/opfs/core/limits.d.ts.map +1 -0
- package/dist/opfs/core/memory-port.d.ts +51 -0
- package/dist/opfs/core/memory-port.d.ts.map +1 -0
- package/dist/opfs/core/metadata-store.d.ts +19 -0
- package/dist/opfs/core/metadata-store.d.ts.map +1 -0
- package/dist/opfs/core/mounted-vfs.d.ts +119 -0
- package/dist/opfs/core/mounted-vfs.d.ts.map +1 -0
- package/dist/opfs/core/path.d.ts +14 -0
- package/dist/opfs/core/path.d.ts.map +1 -0
- package/dist/opfs/core/port.d.ts +30 -0
- package/dist/opfs/core/port.d.ts.map +1 -0
- package/dist/opfs/core/repacked-vfs.d.ts +138 -0
- package/dist/opfs/core/repacked-vfs.d.ts.map +1 -0
- package/dist/opfs/core/state-machine.d.ts +296 -0
- package/dist/opfs/core/state-machine.d.ts.map +1 -0
- package/dist/opfs/create.d.ts +50 -0
- package/dist/opfs/create.d.ts.map +1 -0
- package/dist/opfs/file-port.d.ts +14 -0
- package/dist/opfs/file-port.d.ts.map +1 -0
- package/dist/opfs/index.d.ts +37 -0
- package/dist/opfs/index.d.ts.map +1 -0
- package/dist/opfs/index.js +6671 -0
- package/dist/opfs/index.js.map +28 -0
- package/dist/opfs/opfs-port.d.ts +34 -0
- package/dist/opfs/opfs-port.d.ts.map +1 -0
- package/dist/opfs/opfs-repacked-fs.d.ts +55 -0
- package/dist/opfs/opfs-repacked-fs.d.ts.map +1 -0
- package/dist/opfs/wasi/preview1.d.ts +228 -0
- package/dist/opfs/wasi/preview1.d.ts.map +1 -0
- package/dist/protocol/index.d.ts +15 -0
- package/dist/protocol/index.d.ts.map +1 -0
- package/dist/protocol/index.js +23 -0
- package/dist/protocol/index.js.map +10 -0
- package/dist/protocol/wire/buffer-reader.d.ts +13 -0
- package/dist/protocol/wire/buffer-reader.d.ts.map +1 -0
- package/dist/protocol/wire/buffer-writer.d.ts +12 -0
- package/dist/protocol/wire/buffer-writer.d.ts.map +1 -0
- package/dist/protocol/wire/index.d.ts +5 -0
- package/dist/protocol/wire/index.d.ts.map +1 -0
- package/dist/protocol/wire/messages.d.ts +194 -0
- package/dist/protocol/wire/messages.d.ts.map +1 -0
- package/dist/protocol/wire/parser.d.ts +12 -0
- package/dist/protocol/wire/parser.d.ts.map +1 -0
- package/dist/protocol/wire/serializer.d.ts +61 -0
- package/dist/protocol/wire/serializer.d.ts.map +1 -0
- package/dist/protocol/wire/string-utils.d.ts +6 -0
- package/dist/protocol/wire/string-utils.d.ts.map +1 -0
- package/dist/protocol/wire/types.d.ts +7 -0
- package/dist/protocol/wire/types.d.ts.map +1 -0
- package/dist/tar/gzip.d.ts +7 -0
- package/dist/tar/gzip.d.ts.map +1 -0
- package/dist/tar/tar.d.ts +39 -0
- package/dist/tar/tar.d.ts.map +1 -0
- package/dist/templating.d.ts +42 -0
- package/dist/templating.d.ts.map +1 -0
- package/dist/types.d.ts +76 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +69 -0
- package/skills/opfs/SKILL.md +138 -0
- package/src/build/index.ts +23 -0
- package/src/build/seam.ts +179 -0
- package/src/core/data-dir-archive.ts +68 -0
- package/src/core/internals.ts +87 -0
- package/src/core/marker.ts +94 -0
- package/src/core/mutex.ts +16 -0
- package/src/core/names.ts +26 -0
- package/src/core/parse.ts +79 -0
- package/src/core/pgwasm.ts +876 -0
- package/src/core/storage.ts +70 -0
- package/src/create.ts +134 -0
- package/src/drizzle/codecs.ts +114 -0
- package/src/drizzle/driver.ts +141 -0
- package/src/drizzle/index.ts +15 -0
- package/src/drizzle/session.ts +133 -0
- package/src/errors.ts +201 -0
- package/src/fs/base-filesystem.ts +149 -0
- package/src/fs/index.ts +7 -0
- package/src/index.ts +44 -0
- package/src/interface.ts +186 -0
- package/src/live/debounce-mutex.ts +45 -0
- package/src/live/format-query.ts +47 -0
- package/src/live/index.ts +707 -0
- package/src/live/interface.ts +109 -0
- package/src/opfs/broker/client.ts +482 -0
- package/src/opfs/broker/protocol.ts +624 -0
- package/src/opfs/broker/server.ts +522 -0
- package/src/opfs/core/checksum.ts +85 -0
- package/src/opfs/core/codec.ts +1051 -0
- package/src/opfs/core/errors.ts +134 -0
- package/src/opfs/core/limits.ts +68 -0
- package/src/opfs/core/memory-port.ts +459 -0
- package/src/opfs/core/metadata-store.ts +512 -0
- package/src/opfs/core/mounted-vfs.ts +407 -0
- package/src/opfs/core/path.ts +82 -0
- package/src/opfs/core/port.ts +114 -0
- package/src/opfs/core/repacked-vfs.ts +1464 -0
- package/src/opfs/core/state-machine.ts +1699 -0
- package/src/opfs/create.ts +125 -0
- package/src/opfs/file-port.ts +183 -0
- package/src/opfs/index.ts +113 -0
- package/src/opfs/opfs-port.ts +90 -0
- package/src/opfs/opfs-repacked-fs.ts +210 -0
- package/src/opfs/wasi/preview1.ts +1016 -0
- package/src/protocol/index.ts +24 -0
- package/src/protocol/wire/buffer-reader.ts +60 -0
- package/src/protocol/wire/buffer-writer.ts +93 -0
- package/src/protocol/wire/index.ts +15 -0
- package/src/protocol/wire/messages.ts +332 -0
- package/src/protocol/wire/parser.ts +373 -0
- package/src/protocol/wire/serializer.ts +233 -0
- package/src/protocol/wire/string-utils.ts +18 -0
- package/src/protocol/wire/types.ts +12 -0
- package/src/tar/gzip.ts +36 -0
- package/src/tar/tar.ts +253 -0
- package/src/templating.ts +103 -0
- package/src/types.ts +283 -0
|
@@ -0,0 +1,1005 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
gzip2,
|
|
4
|
+
gunzipIfCompressed2,
|
|
5
|
+
TarFormatError2,
|
|
6
|
+
writeTar2,
|
|
7
|
+
readTar2
|
|
8
|
+
} from "./chunk-0w227vw2.js";
|
|
9
|
+
import {
|
|
10
|
+
PgwasmError2,
|
|
11
|
+
UnsupportedDataDirError2,
|
|
12
|
+
OpfsAhpRemovedError2,
|
|
13
|
+
UnsupportedFilesystemError2,
|
|
14
|
+
CrossOriginIsolationRequiredError2,
|
|
15
|
+
ExtensionBuildMismatchError2,
|
|
16
|
+
BuildMismatchError2,
|
|
17
|
+
DataFormatMismatchError2,
|
|
18
|
+
BuildMarkerUnreadableError2,
|
|
19
|
+
DataDirExistsError2,
|
|
20
|
+
BackupFormatError2,
|
|
21
|
+
PgwasmClosedError2,
|
|
22
|
+
PgwasmFailedError2,
|
|
23
|
+
UnsupportedFeatureError2,
|
|
24
|
+
makeQueryError
|
|
25
|
+
} from "./chunk-cpsnmzrf.js";
|
|
26
|
+
import {
|
|
27
|
+
toPostgresName,
|
|
28
|
+
quoteIdentifier,
|
|
29
|
+
parseResults,
|
|
30
|
+
parseDescribeStatementResults
|
|
31
|
+
} from "./chunk-tdvrvgt5.js";
|
|
32
|
+
import {
|
|
33
|
+
parsers,
|
|
34
|
+
serializers,
|
|
35
|
+
toText,
|
|
36
|
+
arraySerializer,
|
|
37
|
+
arrayParser
|
|
38
|
+
} from "./chunk-d82gg1hx.js";
|
|
39
|
+
import {
|
|
40
|
+
Parser2
|
|
41
|
+
} from "./chunk-at1py5s5.js";
|
|
42
|
+
import {
|
|
43
|
+
DatabaseError2,
|
|
44
|
+
NotificationResponseMessage,
|
|
45
|
+
NoticeMessage,
|
|
46
|
+
serialize2,
|
|
47
|
+
registerProtocolAccess
|
|
48
|
+
} from "./chunk-74gcrk47.js";
|
|
49
|
+
|
|
50
|
+
// packages/pgwasm/src/templating.ts
|
|
51
|
+
var TemplateType = {
|
|
52
|
+
part: "part",
|
|
53
|
+
container: "container"
|
|
54
|
+
};
|
|
55
|
+
function isTemplateValue(value) {
|
|
56
|
+
return typeof value === "object" && value !== null && "_templateType" in value;
|
|
57
|
+
}
|
|
58
|
+
function addToLastAndPushWithSuffix(arr, suffix, ...values) {
|
|
59
|
+
const lastArrIdx = arr.length - 1;
|
|
60
|
+
const lastValIdx = values.length - 1;
|
|
61
|
+
if (lastValIdx === -1)
|
|
62
|
+
return;
|
|
63
|
+
if (lastValIdx === 0) {
|
|
64
|
+
arr[lastArrIdx] = `${arr[lastArrIdx] ?? ""}${values[0] ?? ""}${suffix}`;
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
arr[lastArrIdx] = `${arr[lastArrIdx] ?? ""}${values[0] ?? ""}`;
|
|
68
|
+
arr.push(...values.slice(1, lastValIdx));
|
|
69
|
+
arr.push(`${values[lastValIdx] ?? ""}${suffix}`);
|
|
70
|
+
}
|
|
71
|
+
function sql(strings, ...values) {
|
|
72
|
+
const parsedStrings = [strings[0] ?? ""];
|
|
73
|
+
const parsedRaw = [strings.raw[0] ?? ""];
|
|
74
|
+
const parsedValues = [];
|
|
75
|
+
for (let i = 0;i < values.length; i++) {
|
|
76
|
+
const value = values[i];
|
|
77
|
+
const nextString = strings[i + 1] ?? "";
|
|
78
|
+
const nextRaw = strings.raw[i + 1] ?? "";
|
|
79
|
+
if (isTemplateValue(value) && value._templateType === TemplateType.part) {
|
|
80
|
+
addToLastAndPushWithSuffix(parsedStrings, nextString, value.str);
|
|
81
|
+
addToLastAndPushWithSuffix(parsedRaw, nextRaw, value.str);
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (isTemplateValue(value) && value._templateType === TemplateType.container) {
|
|
85
|
+
addToLastAndPushWithSuffix(parsedStrings, nextString, ...value.strings);
|
|
86
|
+
addToLastAndPushWithSuffix(parsedRaw, nextRaw, ...value.strings.raw);
|
|
87
|
+
parsedValues.push(...value.values);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
parsedStrings.push(nextString);
|
|
91
|
+
parsedRaw.push(nextRaw);
|
|
92
|
+
parsedValues.push(value);
|
|
93
|
+
}
|
|
94
|
+
const templateStrings = Object.assign(parsedStrings, { raw: parsedRaw });
|
|
95
|
+
return { _templateType: TemplateType.container, strings: templateStrings, values: parsedValues };
|
|
96
|
+
}
|
|
97
|
+
function identifier2(strings, ...values) {
|
|
98
|
+
return { _templateType: TemplateType.part, str: `"${String.raw(strings, ...values)}"` };
|
|
99
|
+
}
|
|
100
|
+
function raw2(strings, ...values) {
|
|
101
|
+
return { _templateType: TemplateType.part, str: String.raw(strings, ...values) };
|
|
102
|
+
}
|
|
103
|
+
function query(strings, ...values) {
|
|
104
|
+
const { strings: queryStringParts, values: params } = sql(strings, ...values);
|
|
105
|
+
return {
|
|
106
|
+
query: [queryStringParts[0], ...params.flatMap((_, idx) => [`$${idx + 1}`, queryStringParts[idx + 1]])].join(""),
|
|
107
|
+
params
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// packages/pgwasm/src/core/data-dir-archive.ts
|
|
112
|
+
function normalizeDataDirPath(name) {
|
|
113
|
+
const segments = name.split("/").filter((segment) => segment !== "" && segment !== ".");
|
|
114
|
+
if (segments.includes("..")) {
|
|
115
|
+
throw new BackupFormatError2(`the backup member "${name}" points outside the data directory`);
|
|
116
|
+
}
|
|
117
|
+
return `/${segments.join("/")}`;
|
|
118
|
+
}
|
|
119
|
+
async function readDataDirArchive(archive) {
|
|
120
|
+
const bytes = await gunzipIfCompressed2(new Uint8Array(await archive.arrayBuffer()));
|
|
121
|
+
let members;
|
|
122
|
+
try {
|
|
123
|
+
members = readTar2(bytes);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (error instanceof TarFormatError2) {
|
|
126
|
+
throw new BackupFormatError2(`the Store backup is not a readable tarball: ${error.message}`, { cause: error });
|
|
127
|
+
}
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
const entries = [];
|
|
131
|
+
for (const entry of members) {
|
|
132
|
+
const path = normalizeDataDirPath(entry.name);
|
|
133
|
+
if (path === "/")
|
|
134
|
+
continue;
|
|
135
|
+
entries.push({ path, type: entry.type, mode: entry.mode, mtimeSeconds: entry.mtimeSeconds, data: entry.data });
|
|
136
|
+
}
|
|
137
|
+
return entries;
|
|
138
|
+
}
|
|
139
|
+
async function writeDataDirArchive(entries, baseName, compression = "auto") {
|
|
140
|
+
const tarball = writeTar2(entries.map((entry) => ({
|
|
141
|
+
name: entry.path,
|
|
142
|
+
type: entry.type,
|
|
143
|
+
mode: entry.mode,
|
|
144
|
+
mtimeSeconds: entry.mtimeSeconds,
|
|
145
|
+
data: entry.data
|
|
146
|
+
})));
|
|
147
|
+
if (compression === "none") {
|
|
148
|
+
return new File([tarball.slice()], `${baseName}.tar`, { type: "application/x-tar" });
|
|
149
|
+
}
|
|
150
|
+
return new File([await gzip2(tarball)], `${baseName}.tar.gz`, { type: "application/x-gzip" });
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// packages/pgwasm/src/core/marker.ts
|
|
154
|
+
var BUILD_MARKER_PATH = "/PGWASM_BUILD";
|
|
155
|
+
var PG_VERSION_PATH = "/PG_VERSION";
|
|
156
|
+
var MARKER_FORMAT = 1;
|
|
157
|
+
var encoder = new TextEncoder;
|
|
158
|
+
var decoder = new TextDecoder;
|
|
159
|
+
function encodeBuildMarker(build) {
|
|
160
|
+
return encoder.encode(`${JSON.stringify({ pgwasm: MARKER_FORMAT, build: build.name, dataFormat: build.dataFormat })}
|
|
161
|
+
`);
|
|
162
|
+
}
|
|
163
|
+
function decodeBuildMarker(bytes) {
|
|
164
|
+
const raw = decoder.decode(bytes);
|
|
165
|
+
let parsed;
|
|
166
|
+
try {
|
|
167
|
+
parsed = JSON.parse(raw);
|
|
168
|
+
} catch {
|
|
169
|
+
throw new BuildMarkerUnreadableError2(raw, "not JSON");
|
|
170
|
+
}
|
|
171
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
172
|
+
throw new BuildMarkerUnreadableError2(raw, "not a JSON object");
|
|
173
|
+
}
|
|
174
|
+
const { pgwasm, build, dataFormat } = parsed;
|
|
175
|
+
if (typeof pgwasm !== "number" || !Number.isInteger(pgwasm) || pgwasm < 1) {
|
|
176
|
+
throw new BuildMarkerUnreadableError2(raw, "no marker format version");
|
|
177
|
+
}
|
|
178
|
+
if (pgwasm > MARKER_FORMAT) {
|
|
179
|
+
throw new BuildMarkerUnreadableError2(raw, `marker format ${pgwasm} is newer than this pgwasm reads`);
|
|
180
|
+
}
|
|
181
|
+
if (typeof build !== "string" || build === "") {
|
|
182
|
+
throw new BuildMarkerUnreadableError2(raw, "no build name");
|
|
183
|
+
}
|
|
184
|
+
if (typeof dataFormat !== "number" || !Number.isInteger(dataFormat) || dataFormat < 1) {
|
|
185
|
+
throw new BuildMarkerUnreadableError2(raw, "no data format");
|
|
186
|
+
}
|
|
187
|
+
return { build, dataFormat };
|
|
188
|
+
}
|
|
189
|
+
function checkBuildMarker(build, marker, hasCluster, source) {
|
|
190
|
+
if (marker === undefined) {
|
|
191
|
+
if (hasCluster && !build.claimsUnmarkedDirectories) {
|
|
192
|
+
throw new BuildMismatchError2(build, "unmarked", source);
|
|
193
|
+
}
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const recorded = decodeBuildMarker(marker);
|
|
197
|
+
if (recorded.build !== build.name) {
|
|
198
|
+
const found = recorded;
|
|
199
|
+
throw new BuildMismatchError2(build, found, source);
|
|
200
|
+
}
|
|
201
|
+
if (recorded.dataFormat !== build.dataFormat) {
|
|
202
|
+
throw new DataFormatMismatchError2(build, recorded.dataFormat, source);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
function findEntry(entries, path) {
|
|
206
|
+
return entries.find((entry) => entry.path === path && entry.type === "file");
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// packages/pgwasm/src/core/mutex.ts
|
|
210
|
+
class Mutex {
|
|
211
|
+
#tail = Promise.resolve();
|
|
212
|
+
runExclusive(fn) {
|
|
213
|
+
const run = this.#tail.then(fn);
|
|
214
|
+
this.#tail = run.then(() => {
|
|
215
|
+
return;
|
|
216
|
+
}, () => {
|
|
217
|
+
return;
|
|
218
|
+
});
|
|
219
|
+
return run;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// packages/pgwasm/src/core/storage.ts
|
|
224
|
+
function resolveStorage(dataDir, fs) {
|
|
225
|
+
if (fs !== undefined) {
|
|
226
|
+
if (dataDir !== undefined) {
|
|
227
|
+
throw new UnsupportedDataDirError2(dataDir, "`dataDir` and `fs` are exclusive; pass one of them");
|
|
228
|
+
}
|
|
229
|
+
return { kind: "vfs", vfs: fs };
|
|
230
|
+
}
|
|
231
|
+
if (dataDir === undefined || dataDir.startsWith("memory://")) {
|
|
232
|
+
return { kind: "memory" };
|
|
233
|
+
}
|
|
234
|
+
if (dataDir.startsWith("idb://")) {
|
|
235
|
+
const name = dataDir.slice("idb://".length);
|
|
236
|
+
if (name === "")
|
|
237
|
+
throw new UnsupportedDataDirError2(dataDir, "an IndexedDB store needs a name (idb://<name>)");
|
|
238
|
+
return { kind: "idb", name };
|
|
239
|
+
}
|
|
240
|
+
if (dataDir.startsWith("file://")) {
|
|
241
|
+
const path = dataDir.slice("file://".length);
|
|
242
|
+
if (path === "")
|
|
243
|
+
throw new UnsupportedDataDirError2(dataDir, "a file store needs a path (file://<path>)");
|
|
244
|
+
return { kind: "file", path };
|
|
245
|
+
}
|
|
246
|
+
if (dataDir.startsWith("opfs-ahp://")) {
|
|
247
|
+
throw new OpfsAhpRemovedError2(dataDir);
|
|
248
|
+
}
|
|
249
|
+
const scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(dataDir)?.[1];
|
|
250
|
+
throw new UnsupportedDataDirError2(dataDir, scheme === undefined ? "a scheme is required: memory://, idb://<name> or file://<path>" : `unknown scheme "${scheme}://" (supported: memory://, idb://<name>, file://<path>)`);
|
|
251
|
+
}
|
|
252
|
+
function describeStorage(storage) {
|
|
253
|
+
switch (storage.kind) {
|
|
254
|
+
case "memory":
|
|
255
|
+
return { kind: "memory" };
|
|
256
|
+
case "idb":
|
|
257
|
+
return { kind: "idb", name: storage.name };
|
|
258
|
+
case "file":
|
|
259
|
+
return { kind: "file", path: storage.path };
|
|
260
|
+
case "vfs": {
|
|
261
|
+
const { name, persistent } = storage.vfs.description;
|
|
262
|
+
return persistent === undefined ? { kind: "vfs", name } : { kind: "vfs", name, persistent };
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function backupBaseName(storage) {
|
|
267
|
+
const location = storage.kind === "idb" ? storage.name : storage.kind === "file" ? storage.path : "";
|
|
268
|
+
const last = location.split("/").filter((segment) => segment !== "").pop();
|
|
269
|
+
return last ?? "pgdata";
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// packages/pgwasm/src/core/pgwasm.ts
|
|
273
|
+
function newQuery(throwOnError = false, onNotice) {
|
|
274
|
+
return { results: [], throwOnError, onNotice, databaseError: null };
|
|
275
|
+
}
|
|
276
|
+
function describeException(error) {
|
|
277
|
+
if (typeof error === "object" && error !== null && "message" in error) {
|
|
278
|
+
const { name, message } = error;
|
|
279
|
+
return `${typeof name === "string" ? name : "Error"}: ${String(message)}`;
|
|
280
|
+
}
|
|
281
|
+
return String(error);
|
|
282
|
+
}
|
|
283
|
+
function concatChunks(chunks) {
|
|
284
|
+
if (chunks.length === 1)
|
|
285
|
+
return chunks[0] ?? new Uint8Array(0);
|
|
286
|
+
const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
|
|
287
|
+
const out = new Uint8Array(total);
|
|
288
|
+
let offset = 0;
|
|
289
|
+
for (const chunk of chunks) {
|
|
290
|
+
out.set(chunk, offset);
|
|
291
|
+
offset += chunk.byteLength;
|
|
292
|
+
}
|
|
293
|
+
return out;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
class PgwasmInstance {
|
|
297
|
+
build;
|
|
298
|
+
storage;
|
|
299
|
+
debug;
|
|
300
|
+
waitReady;
|
|
301
|
+
#capabilities;
|
|
302
|
+
#relaxedDurability;
|
|
303
|
+
#resolveReady = () => {
|
|
304
|
+
return;
|
|
305
|
+
};
|
|
306
|
+
#rejectReady = () => {
|
|
307
|
+
return;
|
|
308
|
+
};
|
|
309
|
+
#ready = false;
|
|
310
|
+
#closing = false;
|
|
311
|
+
#closed = false;
|
|
312
|
+
#failure;
|
|
313
|
+
#persistFailure;
|
|
314
|
+
#persistScheduled = false;
|
|
315
|
+
#queryMutex = new Mutex;
|
|
316
|
+
#transactionMutex = new Mutex;
|
|
317
|
+
#listenMutex = new Mutex;
|
|
318
|
+
#persistMutex = new Mutex;
|
|
319
|
+
#running;
|
|
320
|
+
#session;
|
|
321
|
+
#extensionsClose = [];
|
|
322
|
+
#parser = new Parser2;
|
|
323
|
+
#unsolicitedParser = new Parser2;
|
|
324
|
+
#currentQuery = newQuery();
|
|
325
|
+
#notifyListeners = new Map;
|
|
326
|
+
#globalNotifyListeners = new Set;
|
|
327
|
+
#parsers;
|
|
328
|
+
#serializers;
|
|
329
|
+
#arrayTypesInitialized = false;
|
|
330
|
+
#inTransaction = false;
|
|
331
|
+
constructor(plan) {
|
|
332
|
+
this.build = plan.build.identity;
|
|
333
|
+
this.#capabilities = plan.build.capabilities;
|
|
334
|
+
this.storage = describeStorage(plan.storage);
|
|
335
|
+
this.debug = plan.debug;
|
|
336
|
+
this.#relaxedDurability = plan.relaxedDurability;
|
|
337
|
+
this.#parsers = { ...parsers, ...plan.parsers };
|
|
338
|
+
this.#serializers = { ...serializers, ...plan.serializers };
|
|
339
|
+
this.waitReady = new Promise((resolve, reject) => {
|
|
340
|
+
this.#resolveReady = resolve;
|
|
341
|
+
this.#rejectReady = reject;
|
|
342
|
+
});
|
|
343
|
+
this.waitReady.catch(() => {
|
|
344
|
+
return;
|
|
345
|
+
});
|
|
346
|
+
registerProtocolAccess(this, {
|
|
347
|
+
execProtocol: (message, options) => this.#execProtocol(message, options),
|
|
348
|
+
execProtocolStream: (message, options) => this.#execProtocolStream(message, options),
|
|
349
|
+
execProtocolRaw: (message, options) => this.#execProtocolRaw(message, options),
|
|
350
|
+
execProtocolRawStream: (message, options) => this.#execProtocolRawStream(message, options),
|
|
351
|
+
runExclusiveSession: (fn) => this.#runExclusiveSession(fn),
|
|
352
|
+
capabilities: this.#capabilities
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
async boot(plan) {
|
|
356
|
+
try {
|
|
357
|
+
await this.#boot(plan);
|
|
358
|
+
this.#resolveReady();
|
|
359
|
+
} catch (error) {
|
|
360
|
+
this.#rejectReady(error);
|
|
361
|
+
throw error;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
async#boot(plan) {
|
|
365
|
+
const inits = [];
|
|
366
|
+
for (const [key, extension] of plan.clientExtensions) {
|
|
367
|
+
const result = await extension.setup(this);
|
|
368
|
+
if (result.namespace !== undefined) {
|
|
369
|
+
if (key in this) {
|
|
370
|
+
throw new PgwasmError2(`The extension key "${key}" collides with a pgwasm member; use another key.`);
|
|
371
|
+
}
|
|
372
|
+
Object.defineProperty(this, key, { value: result.namespace, enumerable: true });
|
|
373
|
+
}
|
|
374
|
+
if (result.init)
|
|
375
|
+
inits.push(result.init);
|
|
376
|
+
if (result.close)
|
|
377
|
+
this.#extensionsClose.push(result.close);
|
|
378
|
+
}
|
|
379
|
+
const identity = plan.build.identity;
|
|
380
|
+
const mounted = await plan.build.boot({
|
|
381
|
+
storage: plan.storage,
|
|
382
|
+
extensions: plan.serverExtensions,
|
|
383
|
+
user: plan.user,
|
|
384
|
+
database: plan.database,
|
|
385
|
+
debug: plan.debug
|
|
386
|
+
});
|
|
387
|
+
let running;
|
|
388
|
+
try {
|
|
389
|
+
const marker = await mounted.readFile(BUILD_MARKER_PATH);
|
|
390
|
+
const hasCluster = await mounted.readFile(PG_VERSION_PATH) !== undefined;
|
|
391
|
+
checkBuildMarker(identity, marker, hasCluster, "data-directory");
|
|
392
|
+
if (plan.restore !== undefined) {
|
|
393
|
+
if (hasCluster)
|
|
394
|
+
throw new DataDirExistsError2;
|
|
395
|
+
this.#log("pgwasm: creating the data directory from a Store backup");
|
|
396
|
+
await mounted.writeEntries(plan.restore);
|
|
397
|
+
await mounted.persist();
|
|
398
|
+
} else if (!hasCluster) {
|
|
399
|
+
this.#log("pgwasm: no database in the data directory, creating one");
|
|
400
|
+
await mounted.createCluster();
|
|
401
|
+
if (marker === undefined)
|
|
402
|
+
await mounted.writeFile(BUILD_MARKER_PATH, encodeBuildMarker(identity));
|
|
403
|
+
await mounted.persist();
|
|
404
|
+
}
|
|
405
|
+
running = await mounted.start({ settings: plan.settings });
|
|
406
|
+
} catch (error) {
|
|
407
|
+
try {
|
|
408
|
+
await mounted.release();
|
|
409
|
+
} catch {}
|
|
410
|
+
throw error;
|
|
411
|
+
}
|
|
412
|
+
this.#running = running;
|
|
413
|
+
try {
|
|
414
|
+
const session = await running.openSession();
|
|
415
|
+
session.onUnsolicited = (chunk) => this.#handleUnsolicited(chunk);
|
|
416
|
+
this.#session = session;
|
|
417
|
+
this.#ready = true;
|
|
418
|
+
if (plan.username !== undefined) {
|
|
419
|
+
await this.exec(`SET ROLE ${quoteIdentifier(plan.username)}`);
|
|
420
|
+
}
|
|
421
|
+
await this.#initArrayTypes();
|
|
422
|
+
for (const init of inits) {
|
|
423
|
+
await init();
|
|
424
|
+
}
|
|
425
|
+
} catch (error) {
|
|
426
|
+
this.#ready = false;
|
|
427
|
+
this.#closed = true;
|
|
428
|
+
try {
|
|
429
|
+
await this.#persistMutex.runExclusive(async () => {});
|
|
430
|
+
await running.release({ afterFailedBoot: true });
|
|
431
|
+
} catch {}
|
|
432
|
+
throw error;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
get ready() {
|
|
436
|
+
return this.#ready && !this.#closing && !this.#closed && this.#failure === undefined;
|
|
437
|
+
}
|
|
438
|
+
get closed() {
|
|
439
|
+
return this.#closed;
|
|
440
|
+
}
|
|
441
|
+
async#checkReady() {
|
|
442
|
+
if (this.#closing)
|
|
443
|
+
throw new PgwasmClosedError2("closing");
|
|
444
|
+
if (this.#closed)
|
|
445
|
+
throw new PgwasmClosedError2("closed");
|
|
446
|
+
if (!this.#ready)
|
|
447
|
+
await this.waitReady;
|
|
448
|
+
}
|
|
449
|
+
#checkOpenState() {
|
|
450
|
+
if (this.#closing)
|
|
451
|
+
throw new PgwasmClosedError2("closing");
|
|
452
|
+
if (this.#closed)
|
|
453
|
+
throw new PgwasmClosedError2("closed");
|
|
454
|
+
if (this.#failure)
|
|
455
|
+
throw this.#failure.error;
|
|
456
|
+
}
|
|
457
|
+
#checkPersistLatch() {
|
|
458
|
+
if (this.#persistFailure)
|
|
459
|
+
throw this.#persistFailure.error;
|
|
460
|
+
}
|
|
461
|
+
#fail(cause) {
|
|
462
|
+
if (this.#failure)
|
|
463
|
+
return this.#failure.error;
|
|
464
|
+
const reported = this.#currentQuery.databaseError;
|
|
465
|
+
const error = new PgwasmFailedError2("pgwasm failed and must be closed: " + (reported ? `Postgres reported ${reported.severity ?? "an error"}: ${reported.message}; the build then threw ` : "the build threw ") + describeException(cause), { cause });
|
|
466
|
+
this.#failure = { error };
|
|
467
|
+
return error;
|
|
468
|
+
}
|
|
469
|
+
#log(...args) {
|
|
470
|
+
if (this.debug > 0)
|
|
471
|
+
console.log(...args);
|
|
472
|
+
}
|
|
473
|
+
#exchange(message, onData) {
|
|
474
|
+
this.#checkOpenState();
|
|
475
|
+
const session = this.#session;
|
|
476
|
+
if (session === undefined)
|
|
477
|
+
throw new PgwasmClosedError2("closed");
|
|
478
|
+
let pending;
|
|
479
|
+
try {
|
|
480
|
+
pending = session.exchange(message, onData);
|
|
481
|
+
} catch (error) {
|
|
482
|
+
throw this.#fail(error);
|
|
483
|
+
}
|
|
484
|
+
if (pending === undefined)
|
|
485
|
+
return;
|
|
486
|
+
return pending.then(undefined, (error) => {
|
|
487
|
+
throw this.#fail(error);
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
#parseChunk(chunk) {
|
|
491
|
+
this.#parser.parse(chunk, (message) => {
|
|
492
|
+
const handled = this.#handleMessage(message);
|
|
493
|
+
if (handled)
|
|
494
|
+
this.#currentQuery.results.push(handled);
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
#handleUnsolicited(chunk) {
|
|
498
|
+
this.#unsolicitedParser.parse(chunk, (message) => {
|
|
499
|
+
if (message instanceof NotificationResponseMessage)
|
|
500
|
+
this.#dispatchNotification(message);
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
#handleMessage(message) {
|
|
504
|
+
if (this.#currentQuery.databaseError)
|
|
505
|
+
return null;
|
|
506
|
+
if (message instanceof DatabaseError2) {
|
|
507
|
+
if (this.#currentQuery.throwOnError)
|
|
508
|
+
this.#currentQuery.databaseError = message;
|
|
509
|
+
} else if (message instanceof NoticeMessage) {
|
|
510
|
+
if (this.debug > 0)
|
|
511
|
+
console.warn(message);
|
|
512
|
+
this.#currentQuery.onNotice?.(message);
|
|
513
|
+
} else if (message instanceof NotificationResponseMessage) {
|
|
514
|
+
this.#dispatchNotification(message);
|
|
515
|
+
}
|
|
516
|
+
return message;
|
|
517
|
+
}
|
|
518
|
+
#dispatchNotification(message) {
|
|
519
|
+
const listeners = this.#notifyListeners.get(message.channel);
|
|
520
|
+
if (listeners) {
|
|
521
|
+
for (const callback of listeners)
|
|
522
|
+
queueMicrotask(() => callback(message.payload));
|
|
523
|
+
}
|
|
524
|
+
for (const callback of this.#globalNotifyListeners) {
|
|
525
|
+
queueMicrotask(() => callback(message.channel, message.payload));
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
async#execProtocolRaw(message, { persist = true } = {}) {
|
|
529
|
+
this.#checkPersistLatch();
|
|
530
|
+
const chunks = [];
|
|
531
|
+
const pending = this.#exchange(message, (chunk) => {
|
|
532
|
+
chunks.push(chunk.slice());
|
|
533
|
+
this.#parseChunk(chunk);
|
|
534
|
+
});
|
|
535
|
+
if (pending !== undefined)
|
|
536
|
+
await pending;
|
|
537
|
+
if (persist)
|
|
538
|
+
await this.#persistAfterStatement();
|
|
539
|
+
return concatChunks(chunks);
|
|
540
|
+
}
|
|
541
|
+
async#execProtocolRawStream(message, { persist = true, onRawData }) {
|
|
542
|
+
this.#checkPersistLatch();
|
|
543
|
+
const pending = this.#exchange(message, onRawData);
|
|
544
|
+
if (pending !== undefined)
|
|
545
|
+
await pending;
|
|
546
|
+
if (persist)
|
|
547
|
+
await this.#persistAfterStatement();
|
|
548
|
+
}
|
|
549
|
+
async#execProtocol(message, { persist = true, throwOnError = true, onNotice } = {}) {
|
|
550
|
+
this.#currentQuery = newQuery(throwOnError, onNotice);
|
|
551
|
+
try {
|
|
552
|
+
const data = await this.#execProtocolRaw(message, { persist });
|
|
553
|
+
const databaseError = this.#currentQuery.databaseError;
|
|
554
|
+
const result = { messages: this.#currentQuery.results, data };
|
|
555
|
+
if (throwOnError && databaseError) {
|
|
556
|
+
this.#parser = new Parser2;
|
|
557
|
+
throw databaseError;
|
|
558
|
+
}
|
|
559
|
+
return result;
|
|
560
|
+
} finally {
|
|
561
|
+
this.#currentQuery = newQuery();
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
async#execProtocolStream(message, { persist = true, throwOnError = true, onNotice } = {}) {
|
|
565
|
+
this.#currentQuery = newQuery(throwOnError, onNotice);
|
|
566
|
+
try {
|
|
567
|
+
this.#checkPersistLatch();
|
|
568
|
+
const pending = this.#exchange(message, (chunk) => this.#parseChunk(chunk));
|
|
569
|
+
if (pending !== undefined)
|
|
570
|
+
await pending;
|
|
571
|
+
if (persist)
|
|
572
|
+
await this.#persistAfterStatement();
|
|
573
|
+
const databaseError = this.#currentQuery.databaseError;
|
|
574
|
+
const results = this.#currentQuery.results;
|
|
575
|
+
if (throwOnError && databaseError) {
|
|
576
|
+
this.#parser = new Parser2;
|
|
577
|
+
throw databaseError;
|
|
578
|
+
}
|
|
579
|
+
return results;
|
|
580
|
+
} finally {
|
|
581
|
+
this.#currentQuery = newQuery();
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
async#persistAfterStatement() {
|
|
585
|
+
this.#checkOpenState();
|
|
586
|
+
this.#checkPersistLatch();
|
|
587
|
+
const running = this.#running;
|
|
588
|
+
if (running === undefined || this.#persistScheduled)
|
|
589
|
+
return;
|
|
590
|
+
this.#persistScheduled = true;
|
|
591
|
+
const run = () => this.#persistMutex.runExclusive(async () => {
|
|
592
|
+
this.#persistScheduled = false;
|
|
593
|
+
await running.persist(this.#relaxedDurability);
|
|
594
|
+
});
|
|
595
|
+
if (this.#relaxedDurability) {
|
|
596
|
+
run().catch((error) => {
|
|
597
|
+
this.#persistFailure ??= { error };
|
|
598
|
+
});
|
|
599
|
+
} else {
|
|
600
|
+
await run();
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
#runExclusiveQuery(fn) {
|
|
604
|
+
return this.#queryMutex.runExclusive(async () => {
|
|
605
|
+
this.#checkPersistLatch();
|
|
606
|
+
return await fn();
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
async#execNoPersist(message, options) {
|
|
610
|
+
return await this.#execProtocolStream(message, {
|
|
611
|
+
persist: false,
|
|
612
|
+
...options?.onNotice ? { onNotice: options.onNotice } : {}
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
async#handleBlob(blob) {
|
|
616
|
+
const device = this.#running?.blob;
|
|
617
|
+
if (blob === undefined) {
|
|
618
|
+
device?.setReadSource(undefined);
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
if (device === undefined) {
|
|
622
|
+
throw new UnsupportedFeatureError2(`The "${this.build.name}" Postgres build has no /dev/blob device, so the \`blob\` query option is not available.`);
|
|
623
|
+
}
|
|
624
|
+
device.setReadSource(new Uint8Array(await blob.arrayBuffer()));
|
|
625
|
+
}
|
|
626
|
+
#cleanupBlob() {
|
|
627
|
+
this.#running?.blob?.setReadSource(undefined);
|
|
628
|
+
}
|
|
629
|
+
#takeWrittenBlob() {
|
|
630
|
+
const chunks = this.#running?.blob?.takeWritten();
|
|
631
|
+
return chunks === undefined ? undefined : new Blob(chunks);
|
|
632
|
+
}
|
|
633
|
+
#serializeParams(params, dataTypeIDs, options) {
|
|
634
|
+
return params.map((param, index) => {
|
|
635
|
+
if (param === null || param === undefined)
|
|
636
|
+
return null;
|
|
637
|
+
const oid = dataTypeIDs[index] ?? 0;
|
|
638
|
+
const serializer = options?.serializers?.[oid] ?? this.#serializers[oid];
|
|
639
|
+
return serializer ? serializer(param) : toText(param);
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
async#runQuery(sql, params = [], options) {
|
|
643
|
+
return await this.#runExclusiveQuery(async () => {
|
|
644
|
+
this.#log("runQuery", sql, params, options);
|
|
645
|
+
await this.#handleBlob(options?.blob);
|
|
646
|
+
let results = [];
|
|
647
|
+
try {
|
|
648
|
+
const parsed = await this.#execNoPersist(serialize2.parse({ text: sql, ...options?.paramTypes ? { types: options.paramTypes } : {} }), options);
|
|
649
|
+
const dataTypeIDs = parseDescribeStatementResults(await this.#execNoPersist(serialize2.describe({ type: "S" }), options));
|
|
650
|
+
const values = this.#serializeParams(params, dataTypeIDs, options);
|
|
651
|
+
results = [
|
|
652
|
+
...parsed,
|
|
653
|
+
...await this.#execNoPersist(serialize2.bind({ values }), options),
|
|
654
|
+
...await this.#execNoPersist(serialize2.describe({ type: "P" }), options),
|
|
655
|
+
...await this.#execNoPersist(serialize2.execute({}), options)
|
|
656
|
+
];
|
|
657
|
+
} catch (error) {
|
|
658
|
+
if (error instanceof DatabaseError2) {
|
|
659
|
+
throw makeQueryError({ error, query: sql, params, options });
|
|
660
|
+
}
|
|
661
|
+
throw error;
|
|
662
|
+
} finally {
|
|
663
|
+
results.push(...await this.#execNoPersist(serialize2.sync(), options));
|
|
664
|
+
}
|
|
665
|
+
this.#cleanupBlob();
|
|
666
|
+
if (!this.#inTransaction)
|
|
667
|
+
await this.#persistAfterStatement();
|
|
668
|
+
const blob = this.#takeWrittenBlob();
|
|
669
|
+
return parseResults(results, this.#parsers, options, blob)[0];
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
async#runExec(sql, options) {
|
|
673
|
+
return await this.#runExclusiveQuery(async () => {
|
|
674
|
+
this.#log("runExec", sql, options);
|
|
675
|
+
await this.#handleBlob(options?.blob);
|
|
676
|
+
let results = [];
|
|
677
|
+
try {
|
|
678
|
+
results = await this.#execNoPersist(serialize2.query(sql), options);
|
|
679
|
+
} catch (error) {
|
|
680
|
+
if (error instanceof DatabaseError2) {
|
|
681
|
+
throw makeQueryError({ error, query: sql, params: undefined, options });
|
|
682
|
+
}
|
|
683
|
+
throw error;
|
|
684
|
+
} finally {
|
|
685
|
+
results.push(...await this.#execNoPersist(serialize2.sync(), options));
|
|
686
|
+
}
|
|
687
|
+
this.#cleanupBlob();
|
|
688
|
+
if (!this.#inTransaction)
|
|
689
|
+
await this.#persistAfterStatement();
|
|
690
|
+
const blob = this.#takeWrittenBlob();
|
|
691
|
+
return parseResults(results, this.#parsers, options, blob);
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
async query(sql, params, options) {
|
|
695
|
+
await this.#checkReady();
|
|
696
|
+
return await this.#transactionMutex.runExclusive(() => this.#runQuery(sql, params, options));
|
|
697
|
+
}
|
|
698
|
+
async sql(sqlStrings, ...params) {
|
|
699
|
+
const { query: query2, params: actualParams } = query(sqlStrings, ...params);
|
|
700
|
+
return await this.query(query2, actualParams);
|
|
701
|
+
}
|
|
702
|
+
async exec(sql, options) {
|
|
703
|
+
await this.#checkReady();
|
|
704
|
+
return await this.#transactionMutex.runExclusive(() => this.#runExec(sql, options));
|
|
705
|
+
}
|
|
706
|
+
async transaction(callback) {
|
|
707
|
+
await this.#checkReady();
|
|
708
|
+
return await this.#transactionMutex.runExclusive(async () => {
|
|
709
|
+
await this.#runExec("BEGIN");
|
|
710
|
+
this.#inTransaction = true;
|
|
711
|
+
let closed = false;
|
|
712
|
+
const checkClosed = () => {
|
|
713
|
+
if (closed)
|
|
714
|
+
throw new PgwasmError2("Transaction is closed");
|
|
715
|
+
};
|
|
716
|
+
const tx = {
|
|
717
|
+
query: async (sql, params, options) => {
|
|
718
|
+
checkClosed();
|
|
719
|
+
return await this.#runQuery(sql, params, options);
|
|
720
|
+
},
|
|
721
|
+
sql: async (sqlStrings, ...params) => {
|
|
722
|
+
checkClosed();
|
|
723
|
+
const { query: query2, params: actualParams } = query(sqlStrings, ...params);
|
|
724
|
+
return await this.#runQuery(query2, actualParams);
|
|
725
|
+
},
|
|
726
|
+
exec: async (sql, options) => {
|
|
727
|
+
checkClosed();
|
|
728
|
+
return await this.#runExec(sql, options);
|
|
729
|
+
},
|
|
730
|
+
rollback: async () => {
|
|
731
|
+
checkClosed();
|
|
732
|
+
await this.#runExec("ROLLBACK");
|
|
733
|
+
closed = true;
|
|
734
|
+
},
|
|
735
|
+
listen: async (channel, callback) => {
|
|
736
|
+
checkClosed();
|
|
737
|
+
return await this.listen(channel, callback, tx);
|
|
738
|
+
},
|
|
739
|
+
get closed() {
|
|
740
|
+
return closed;
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
try {
|
|
744
|
+
const result = await callback(tx);
|
|
745
|
+
this.#inTransaction = false;
|
|
746
|
+
if (!closed) {
|
|
747
|
+
closed = true;
|
|
748
|
+
await this.#runExec("COMMIT");
|
|
749
|
+
} else {
|
|
750
|
+
await this.#persistAfterStatement();
|
|
751
|
+
}
|
|
752
|
+
return result;
|
|
753
|
+
} catch (error) {
|
|
754
|
+
this.#inTransaction = false;
|
|
755
|
+
if (!closed) {
|
|
756
|
+
closed = true;
|
|
757
|
+
await this.#runExec("ROLLBACK");
|
|
758
|
+
} else {
|
|
759
|
+
try {
|
|
760
|
+
await this.#persistAfterStatement();
|
|
761
|
+
} catch {}
|
|
762
|
+
}
|
|
763
|
+
throw error;
|
|
764
|
+
}
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
async runExclusive(fn) {
|
|
768
|
+
return await this.#runExclusiveQuery(fn);
|
|
769
|
+
}
|
|
770
|
+
async#runExclusiveSession(fn) {
|
|
771
|
+
await this.#checkReady();
|
|
772
|
+
return await this.#transactionMutex.runExclusive(() => this.#queryMutex.runExclusive(async () => {
|
|
773
|
+
this.#checkOpenState();
|
|
774
|
+
this.#checkPersistLatch();
|
|
775
|
+
return await fn();
|
|
776
|
+
}));
|
|
777
|
+
}
|
|
778
|
+
async#initArrayTypes({ force = false } = {}) {
|
|
779
|
+
if (this.#arrayTypesInitialized && !force)
|
|
780
|
+
return;
|
|
781
|
+
this.#arrayTypesInitialized = true;
|
|
782
|
+
const types = await this.query(`
|
|
783
|
+
SELECT b.oid, b.typarray
|
|
784
|
+
FROM pg_catalog.pg_type a
|
|
785
|
+
LEFT JOIN pg_catalog.pg_type b ON b.oid = a.typelem
|
|
786
|
+
WHERE a.typcategory = 'A'
|
|
787
|
+
GROUP BY b.oid, b.typarray
|
|
788
|
+
ORDER BY b.oid
|
|
789
|
+
`);
|
|
790
|
+
for (const type of types.rows) {
|
|
791
|
+
this.#serializers[type.typarray] = (value) => arraySerializer(value, this.#serializers[type.oid], type.typarray);
|
|
792
|
+
this.#parsers[type.typarray] = (value) => arrayParser(value, this.#parsers[type.oid], type.typarray);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
async refreshArrayTypes() {
|
|
796
|
+
await this.#initArrayTypes({ force: true });
|
|
797
|
+
}
|
|
798
|
+
async listen(channel, callback, tx) {
|
|
799
|
+
return await this.#withListenLocks(tx, (exec) => this.#subscribe(channel, callback, exec));
|
|
800
|
+
}
|
|
801
|
+
async unlisten(channel, callback, tx) {
|
|
802
|
+
await this.#withListenLocks(tx, (exec) => this.#unsubscribe(channel, callback, exec));
|
|
803
|
+
}
|
|
804
|
+
async#withListenLocks(tx, fn) {
|
|
805
|
+
if (tx)
|
|
806
|
+
return await this.#listenMutex.runExclusive(() => fn((sql) => tx.exec(sql)));
|
|
807
|
+
await this.#checkReady();
|
|
808
|
+
return await this.#transactionMutex.runExclusive(() => this.#listenMutex.runExclusive(() => fn((sql) => this.#runExec(sql))));
|
|
809
|
+
}
|
|
810
|
+
async#subscribe(channel, callback, exec) {
|
|
811
|
+
const pgChannel = toPostgresName(channel);
|
|
812
|
+
let listeners = this.#notifyListeners.get(pgChannel);
|
|
813
|
+
if (!listeners) {
|
|
814
|
+
listeners = new Set;
|
|
815
|
+
this.#notifyListeners.set(pgChannel, listeners);
|
|
816
|
+
}
|
|
817
|
+
listeners.add(callback);
|
|
818
|
+
try {
|
|
819
|
+
await exec(`LISTEN ${channel}`);
|
|
820
|
+
} catch (error) {
|
|
821
|
+
listeners.delete(callback);
|
|
822
|
+
if (listeners.size === 0)
|
|
823
|
+
this.#notifyListeners.delete(pgChannel);
|
|
824
|
+
throw error;
|
|
825
|
+
}
|
|
826
|
+
return async (unlistenTx) => {
|
|
827
|
+
await this.unlisten(channel, callback, unlistenTx);
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
async#unsubscribe(channel, callback, exec) {
|
|
831
|
+
const pgChannel = toPostgresName(channel);
|
|
832
|
+
const cleanUp = async () => {
|
|
833
|
+
await exec(`UNLISTEN ${channel}`);
|
|
834
|
+
if (this.#notifyListeners.get(pgChannel)?.size === 0)
|
|
835
|
+
this.#notifyListeners.delete(pgChannel);
|
|
836
|
+
};
|
|
837
|
+
if (callback) {
|
|
838
|
+
this.#notifyListeners.get(pgChannel)?.delete(callback);
|
|
839
|
+
if (this.#notifyListeners.get(pgChannel)?.size === 0)
|
|
840
|
+
await cleanUp();
|
|
841
|
+
} else {
|
|
842
|
+
await cleanUp();
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
onNotification(callback) {
|
|
846
|
+
this.#globalNotifyListeners.add(callback);
|
|
847
|
+
return () => {
|
|
848
|
+
this.#globalNotifyListeners.delete(callback);
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
async dumpDataDir(compression) {
|
|
852
|
+
await this.#checkReady();
|
|
853
|
+
const running = this.#running;
|
|
854
|
+
if (running === undefined)
|
|
855
|
+
throw new PgwasmClosedError2("closed");
|
|
856
|
+
const entries = await this.#queryMutex.runExclusive(async () => {
|
|
857
|
+
this.#checkOpenState();
|
|
858
|
+
return await running.readEntries();
|
|
859
|
+
});
|
|
860
|
+
return await writeDataDirArchive(entries, backupBaseName(this.storage), compression);
|
|
861
|
+
}
|
|
862
|
+
async close() {
|
|
863
|
+
await this.#checkReady();
|
|
864
|
+
this.#closing = true;
|
|
865
|
+
const failure = this.#failure;
|
|
866
|
+
const running = this.#running;
|
|
867
|
+
const session = this.#session;
|
|
868
|
+
let closeFailure;
|
|
869
|
+
let finalPersistFailure;
|
|
870
|
+
try {
|
|
871
|
+
await this.#transactionMutex.runExclusive(() => this.#queryMutex.runExclusive(async () => {
|
|
872
|
+
for (const closeFn of this.#extensionsClose) {
|
|
873
|
+
try {
|
|
874
|
+
await closeFn();
|
|
875
|
+
} catch (error) {
|
|
876
|
+
closeFailure ??= { error };
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
if (failure || running === undefined)
|
|
880
|
+
return;
|
|
881
|
+
try {
|
|
882
|
+
await session?.close();
|
|
883
|
+
await running.shutdown();
|
|
884
|
+
} catch (error) {
|
|
885
|
+
closeFailure ??= { error };
|
|
886
|
+
}
|
|
887
|
+
try {
|
|
888
|
+
await this.#persistMutex.runExclusive(() => running.persist(false));
|
|
889
|
+
this.#persistFailure = undefined;
|
|
890
|
+
} catch (error) {
|
|
891
|
+
finalPersistFailure = { error };
|
|
892
|
+
this.#persistFailure = { error };
|
|
893
|
+
}
|
|
894
|
+
}));
|
|
895
|
+
} finally {
|
|
896
|
+
try {
|
|
897
|
+
await this.#persistMutex.runExclusive(async () => {});
|
|
898
|
+
await running?.release();
|
|
899
|
+
} finally {
|
|
900
|
+
this.#closed = true;
|
|
901
|
+
this.#closing = false;
|
|
902
|
+
this.#ready = false;
|
|
903
|
+
this.#session = undefined;
|
|
904
|
+
this.#running = undefined;
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
if (failure)
|
|
908
|
+
throw failure.error;
|
|
909
|
+
if (finalPersistFailure)
|
|
910
|
+
throw finalPersistFailure.error;
|
|
911
|
+
if (closeFailure)
|
|
912
|
+
throw closeFailure.error;
|
|
913
|
+
}
|
|
914
|
+
async[Symbol.asyncDispose]() {
|
|
915
|
+
await this.close();
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
// packages/pgwasm/src/create.ts
|
|
920
|
+
function isServerExtension(extension) {
|
|
921
|
+
return "kind" in extension && extension.kind === "server";
|
|
922
|
+
}
|
|
923
|
+
function assertBuild(build) {
|
|
924
|
+
const candidate = build;
|
|
925
|
+
if (typeof candidate !== "object" || candidate === null || typeof candidate.boot !== "function" || typeof candidate.identity?.name !== "string" || !Array.isArray(candidate.capabilities?.filesystems)) {
|
|
926
|
+
throw new TypeError("createPgwasm needs a Postgres build in `build`, e.g. `cBuild` from @pgxsinkit/pgwasm-c.");
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
function mergeSettings(settings, serverExtensions) {
|
|
930
|
+
const merged = { ...settings };
|
|
931
|
+
const preload = serverExtensions.flatMap((extension) => extension.sharedPreloadLibraries ?? []);
|
|
932
|
+
if (preload.length > 0) {
|
|
933
|
+
const existing = (merged["shared_preload_libraries"] ?? "").split(",").map((library) => library.trim()).filter((library) => library !== "");
|
|
934
|
+
merged["shared_preload_libraries"] = [...new Set([...existing, ...preload])].join(",");
|
|
935
|
+
}
|
|
936
|
+
return merged;
|
|
937
|
+
}
|
|
938
|
+
async function restoreEntries(build, loadDataDir) {
|
|
939
|
+
const entries = await readDataDirArchive(loadDataDir);
|
|
940
|
+
if (findEntry(entries, PG_VERSION_PATH) === undefined) {
|
|
941
|
+
throw new BackupFormatError2("The Store backup holds no data directory (it has no PG_VERSION).");
|
|
942
|
+
}
|
|
943
|
+
const marker = findEntry(entries, BUILD_MARKER_PATH);
|
|
944
|
+
checkBuildMarker(build.identity, marker?.data, true, "backup");
|
|
945
|
+
if (marker !== undefined)
|
|
946
|
+
return entries;
|
|
947
|
+
return [
|
|
948
|
+
...entries,
|
|
949
|
+
{
|
|
950
|
+
path: BUILD_MARKER_PATH,
|
|
951
|
+
type: "file",
|
|
952
|
+
mode: 384,
|
|
953
|
+
mtimeSeconds: Math.floor(Date.now() / 1000),
|
|
954
|
+
data: encodeBuildMarker(build.identity)
|
|
955
|
+
}
|
|
956
|
+
];
|
|
957
|
+
}
|
|
958
|
+
async function createPgwasm2(options) {
|
|
959
|
+
const build = options.build;
|
|
960
|
+
assertBuild(build);
|
|
961
|
+
const identity = build.identity;
|
|
962
|
+
const capabilities = build.capabilities;
|
|
963
|
+
const storage = resolveStorage(options.dataDir, options.fs);
|
|
964
|
+
if (!capabilities.filesystems.includes(storage.kind)) {
|
|
965
|
+
throw new UnsupportedFilesystemError2(storage.kind, identity, capabilities.filesystems);
|
|
966
|
+
}
|
|
967
|
+
if (capabilities.requiresCrossOriginIsolation && globalThis.crossOriginIsolated === false) {
|
|
968
|
+
throw new CrossOriginIsolationRequiredError2(identity);
|
|
969
|
+
}
|
|
970
|
+
const serverExtensions = [];
|
|
971
|
+
const clientExtensions = [];
|
|
972
|
+
for (const [key, extension] of Object.entries(options.extensions ?? {})) {
|
|
973
|
+
if (isServerExtension(extension)) {
|
|
974
|
+
if (extension.build !== identity.name) {
|
|
975
|
+
throw new ExtensionBuildMismatchError2(extension.name, extension.build, identity);
|
|
976
|
+
}
|
|
977
|
+
serverExtensions.push(extension);
|
|
978
|
+
} else {
|
|
979
|
+
clientExtensions.push([key, extension]);
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
const restore = options.loadDataDir === undefined ? undefined : await restoreEntries(build, options.loadDataDir);
|
|
983
|
+
const plan = {
|
|
984
|
+
build,
|
|
985
|
+
storage,
|
|
986
|
+
serverExtensions,
|
|
987
|
+
clientExtensions,
|
|
988
|
+
restore,
|
|
989
|
+
settings: mergeSettings(options.settings, serverExtensions),
|
|
990
|
+
user: options.username ?? "postgres",
|
|
991
|
+
database: options.database ?? "postgres",
|
|
992
|
+
username: options.username,
|
|
993
|
+
debug: options.debug ?? 0,
|
|
994
|
+
relaxedDurability: options.relaxedDurability ?? false,
|
|
995
|
+
parsers: options.parsers,
|
|
996
|
+
serializers: options.serializers
|
|
997
|
+
};
|
|
998
|
+
const instance = new PgwasmInstance(plan);
|
|
999
|
+
await instance.boot(plan);
|
|
1000
|
+
return instance;
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
export { identifier2, raw2, createPgwasm2 };
|
|
1004
|
+
|
|
1005
|
+
//# debugId=EB995FC77D1C6A9B64756E2164756E21
|