@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,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/templating.ts", "../src/core/data-dir-archive.ts", "../src/core/marker.ts", "../src/core/mutex.ts", "../src/core/storage.ts", "../src/core/pgwasm.ts", "../src/create.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nconst TemplateType = {\n part: \"part\",\n container: \"container\",\n} as const;\n\n/** A literal piece of SQL (an identifier or raw text) spliced into a template without a parameter. */\nexport interface TemplatePart {\n readonly _templateType: typeof TemplateType.part;\n readonly str: string;\n}\n\n/** A nested template: its strings and its parameter values. */\nexport interface TemplateContainer {\n readonly _templateType: typeof TemplateType.container;\n readonly strings: TemplateStringsArray;\n readonly values: unknown[];\n}\n\n/** A parametrized query: `$1`-numbered text and its parameters. */\nexport interface TemplatedQuery {\n readonly query: string;\n readonly params: unknown[];\n}\n\nfunction isTemplateValue(value: unknown): value is TemplatePart | TemplateContainer {\n return typeof value === \"object\" && value !== null && \"_templateType\" in value;\n}\n\nfunction addToLastAndPushWithSuffix(arr: string[], suffix: string, ...values: readonly string[]): void {\n const lastArrIdx = arr.length - 1;\n const lastValIdx = values.length - 1;\n if (lastValIdx === -1) return;\n if (lastValIdx === 0) {\n arr[lastArrIdx] = `${arr[lastArrIdx] ?? \"\"}${values[0] ?? \"\"}${suffix}`;\n return;\n }\n // Sandwich the values between the array's last element and the suffix.\n arr[lastArrIdx] = `${arr[lastArrIdx] ?? \"\"}${values[0] ?? \"\"}`;\n arr.push(...values.slice(1, lastValIdx));\n arr.push(`${values[lastValIdx] ?? \"\"}${suffix}`);\n}\n\n/**\n * Nest SQL templates without losing their parametrization:\n *\n * ```ts\n * pg.sql`SELECT * FROM tale ${withFilter ? sql`WHERE foo = ${fooVar}` : sql``}`\n * ```\n */\nexport function sql(strings: TemplateStringsArray, ...values: unknown[]): TemplateContainer {\n const parsedStrings: string[] = [strings[0] ?? \"\"];\n const parsedRaw: string[] = [strings.raw[0] ?? \"\"];\n const parsedValues: unknown[] = [];\n for (let i = 0; i < values.length; i++) {\n const value = values[i];\n const nextString = strings[i + 1] ?? \"\";\n const nextRaw = strings.raw[i + 1] ?? \"\";\n if (isTemplateValue(value) && value._templateType === TemplateType.part) {\n addToLastAndPushWithSuffix(parsedStrings, nextString, value.str);\n addToLastAndPushWithSuffix(parsedRaw, nextRaw, value.str);\n continue;\n }\n if (isTemplateValue(value) && value._templateType === TemplateType.container) {\n addToLastAndPushWithSuffix(parsedStrings, nextString, ...value.strings);\n addToLastAndPushWithSuffix(parsedRaw, nextRaw, ...value.strings.raw);\n parsedValues.push(...value.values);\n continue;\n }\n parsedStrings.push(nextString);\n parsedRaw.push(nextRaw);\n parsedValues.push(value);\n }\n const templateStrings = Object.assign(parsedStrings, { raw: parsedRaw });\n return { _templateType: TemplateType.container, strings: templateStrings, values: parsedValues };\n}\n\n/**\n * An identifier spliced into a template, double-quoted and not parametrized:\n *\n * ```ts\n * pg.sql`SELECT * FROM ${identifier`foo`} WHERE ${identifier`id`} = ${id}`\n * ```\n */\nexport function identifier(strings: TemplateStringsArray, ...values: unknown[]): TemplatePart {\n return { _templateType: TemplateType.part, str: `\"${String.raw(strings, ...values)}\"` };\n}\n\n/** Raw SQL spliced into a template as it is, neither parametrized nor escaped. */\nexport function raw(strings: TemplateStringsArray, ...values: unknown[]): TemplatePart {\n return { _templateType: TemplateType.part, str: String.raw(strings, ...values) };\n}\n\n/** Turn a template into `$1`-numbered query text and its parameters. */\nexport function query(strings: TemplateStringsArray, ...values: unknown[]): TemplatedQuery {\n const { strings: queryStringParts, values: params } = sql(strings, ...values);\n return {\n query: [queryStringParts[0], ...params.flatMap((_, idx) => [`$${idx + 1}`, queryStringParts[idx + 1]])].join(\"\"),\n params,\n };\n}\n",
|
|
6
|
+
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\n/**\n * Store backups: a data directory as a tarball (ADR-0035). pgwasm owns the format so every build\n * produces the same artefact: ustar, entry names relative to the data directory with a leading `/`,\n * a directory before its contents, optionally gzipped. Backups written by earlier releases restore.\n */\n\nimport type { DataDirEntry } from \"../build/seam\";\nimport { BackupFormatError } from \"../errors\";\nimport type { DumpCompression } from \"../interface\";\nimport { gunzipIfCompressed, gzip } from \"../tar/gzip\";\nimport { readTar, TarFormatError, writeTar, type TarEntry } from \"../tar/tar\";\n\n/**\n * Normalize a backup member's name to a data-directory path: a leading `/`, no trailing `/`, no empty,\n * `.` or `..` segments. A name that would leave the data directory is refused.\n */\nexport function normalizeDataDirPath(name: string): string {\n const segments = name.split(\"/\").filter((segment) => segment !== \"\" && segment !== \".\");\n if (segments.includes(\"..\")) {\n throw new BackupFormatError(`the backup member \"${name}\" points outside the data directory`);\n }\n return `/${segments.join(\"/\")}`;\n}\n\n/** Read a Store backup (gzipped or not, whatever its MIME type or name says) into entries. */\nexport async function readDataDirArchive(archive: Blob): Promise<DataDirEntry[]> {\n const bytes = await gunzipIfCompressed(new Uint8Array(await archive.arrayBuffer()));\n let members: TarEntry[];\n try {\n members = readTar(bytes);\n } catch (error) {\n if (error instanceof TarFormatError) {\n throw new BackupFormatError(`the Store backup is not a readable tarball: ${error.message}`, { cause: error });\n }\n throw error;\n }\n const entries: DataDirEntry[] = [];\n for (const entry of members) {\n const path = normalizeDataDirPath(entry.name);\n if (path === \"/\") continue;\n entries.push({ path, type: entry.type, mode: entry.mode, mtimeSeconds: entry.mtimeSeconds, data: entry.data });\n }\n return entries;\n}\n\n/** Write entries as a Store backup `File`, named `<baseName>.tar` or `<baseName>.tar.gz`. */\nexport async function writeDataDirArchive(\n entries: readonly DataDirEntry[],\n baseName: string,\n compression: DumpCompression = \"auto\",\n): Promise<File> {\n const tarball = writeTar(\n entries.map((entry) => ({\n name: entry.path,\n type: entry.type,\n mode: entry.mode,\n mtimeSeconds: entry.mtimeSeconds,\n data: entry.data,\n })),\n );\n if (compression === \"none\") {\n return new File([tarball.slice()], `${baseName}.tar`, { type: \"application/x-tar\" });\n }\n return new File([await gzip(tarball)], `${baseName}.tar.gz`, { type: \"application/x-gzip\" });\n}\n",
|
|
7
|
+
"/**\n * The build marker (ADR-0063 decision 1, build permanence).\n *\n * pgwasm records the Postgres build in every data directory it creates, as the file `PGWASM_BUILD` in\n * the data directory itself (next to `PG_VERSION`), so it works on every storage and travels inside\n * every Store backup. Its content is one line of JSON:\n *\n * {\"pgwasm\":1,\"build\":\"c\",\"dataFormat\":1}\n *\n * `pgwasm` is the marker's own format version; a newer one than this release knows is unreadable\n * (fail closed). A directory without a marker predates marking: it is the C build's, which the build\n * says through `claimsUnmarkedDirectories` rather than shared code naming a build. Existing unmarked\n * directories are never backfilled; only a directory pgwasm creates gets a marker.\n */\n\nimport type { BuildIdentity, DataDirEntry } from \"../build/seam\";\nimport { BuildMarkerUnreadableError, BuildMismatchError, DataFormatMismatchError, type RecordedBuild } from \"../errors\";\n\n/** The marker's path inside the data directory. */\nexport const BUILD_MARKER_PATH = \"/PGWASM_BUILD\";\n/** Postgres' own version file: its presence means the directory holds a cluster. */\nexport const PG_VERSION_PATH = \"/PG_VERSION\";\n\nconst MARKER_FORMAT = 1;\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\n/** The marker's bytes for a build. */\nexport function encodeBuildMarker(build: BuildIdentity): Uint8Array {\n return encoder.encode(\n `${JSON.stringify({ pgwasm: MARKER_FORMAT, build: build.name, dataFormat: build.dataFormat })}\\n`,\n );\n}\n\n/** Parse a marker; throws {@link BuildMarkerUnreadableError} for anything but a valid one. */\nexport function decodeBuildMarker(bytes: Uint8Array): { build: string; dataFormat: number } {\n const raw = decoder.decode(bytes);\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw new BuildMarkerUnreadableError(raw, \"not JSON\");\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new BuildMarkerUnreadableError(raw, \"not a JSON object\");\n }\n const { pgwasm, build, dataFormat } = parsed as Record<string, unknown>;\n if (typeof pgwasm !== \"number\" || !Number.isInteger(pgwasm) || pgwasm < 1) {\n throw new BuildMarkerUnreadableError(raw, \"no marker format version\");\n }\n if (pgwasm > MARKER_FORMAT) {\n throw new BuildMarkerUnreadableError(raw, `marker format ${pgwasm} is newer than this pgwasm reads`);\n }\n if (typeof build !== \"string\" || build === \"\") {\n throw new BuildMarkerUnreadableError(raw, \"no build name\");\n }\n if (typeof dataFormat !== \"number\" || !Number.isInteger(dataFormat) || dataFormat < 1) {\n throw new BuildMarkerUnreadableError(raw, \"no data format\");\n }\n return { build, dataFormat };\n}\n\n/**\n * Check what a data directory or backup records against the build about to open it. `marker` is the\n * marker's bytes (absent when there is none); `hasCluster` is whether `PG_VERSION` exists. Throws the\n * typed refusal when the build may not open it.\n */\nexport function checkBuildMarker(\n build: BuildIdentity,\n marker: Uint8Array | undefined,\n hasCluster: boolean,\n source: \"data-directory\" | \"backup\",\n): void {\n if (marker === undefined) {\n if (hasCluster && !build.claimsUnmarkedDirectories) {\n throw new BuildMismatchError(build, \"unmarked\", source);\n }\n return;\n }\n const recorded = decodeBuildMarker(marker);\n if (recorded.build !== build.name) {\n const found: RecordedBuild = recorded;\n throw new BuildMismatchError(build, found, source);\n }\n if (recorded.dataFormat !== build.dataFormat) {\n throw new DataFormatMismatchError(build, recorded.dataFormat, source);\n }\n}\n\n/** The marker entry of a data-directory image, if it has one. */\nexport function findEntry(entries: readonly DataDirEntry[], path: string): DataDirEntry | undefined {\n return entries.find((entry) => entry.path === path && entry.type === \"file\");\n}\n",
|
|
8
|
+
"/**\n * A FIFO async mutex: `runExclusive` runs its callback once every earlier one has settled. Not\n * re-entrant — a callback that waits on the same mutex deadlocks, as with any mutex.\n */\nexport class Mutex {\n #tail: Promise<void> = Promise.resolve();\n\n runExclusive<T>(fn: () => Promise<T> | T): Promise<T> {\n const run = this.#tail.then(fn);\n this.#tail = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n}\n",
|
|
9
|
+
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { StorageRequest } from \"../build/seam\";\nimport { OpfsAhpRemovedError, UnsupportedDataDirError } from \"../errors\";\nimport type { BaseFilesystem } from \"../fs/base-filesystem\";\nimport type { StorageDescription } from \"../interface\";\n\n/**\n * Resolve the `dataDir` / `fs` options into the storage a build mounts. A scheme is required\n * (`memory://`, `idb://<name>`, `file://<path>`); a bare path, an unknown scheme and the removed\n * `opfs-ahp://` are refused before anything is booted.\n */\nexport function resolveStorage(dataDir: string | undefined, fs: BaseFilesystem | undefined): StorageRequest {\n if (fs !== undefined) {\n if (dataDir !== undefined) {\n throw new UnsupportedDataDirError(dataDir, \"`dataDir` and `fs` are exclusive; pass one of them\");\n }\n return { kind: \"vfs\", vfs: fs };\n }\n if (dataDir === undefined || dataDir.startsWith(\"memory://\")) {\n return { kind: \"memory\" };\n }\n if (dataDir.startsWith(\"idb://\")) {\n const name = dataDir.slice(\"idb://\".length);\n if (name === \"\") throw new UnsupportedDataDirError(dataDir, \"an IndexedDB store needs a name (idb://<name>)\");\n return { kind: \"idb\", name };\n }\n if (dataDir.startsWith(\"file://\")) {\n const path = dataDir.slice(\"file://\".length);\n if (path === \"\") throw new UnsupportedDataDirError(dataDir, \"a file store needs a path (file://<path>)\");\n return { kind: \"file\", path };\n }\n if (dataDir.startsWith(\"opfs-ahp://\")) {\n throw new OpfsAhpRemovedError(dataDir);\n }\n const scheme = /^([a-z][a-z0-9+.-]*):\\/\\//i.exec(dataDir)?.[1];\n throw new UnsupportedDataDirError(\n dataDir,\n scheme === undefined\n ? \"a scheme is required: memory://, idb://<name> or file://<path>\"\n : `unknown scheme \"${scheme}://\" (supported: memory://, idb://<name>, file://<path>)`,\n );\n}\n\n/** The public description of where a data directory lives. */\nexport function describeStorage(storage: StorageRequest): StorageDescription {\n switch (storage.kind) {\n case \"memory\":\n return { kind: \"memory\" };\n case \"idb\":\n return { kind: \"idb\", name: storage.name };\n case \"file\":\n return { kind: \"file\", path: storage.path };\n case \"vfs\": {\n const { name, persistent } = storage.vfs.description;\n return persistent === undefined ? { kind: \"vfs\", name } : { kind: \"vfs\", name, persistent };\n }\n }\n}\n\n/** The file name a Store backup gets: the storage's last path segment, else `pgdata`. */\nexport function backupBaseName(storage: StorageDescription): string {\n const location = storage.kind === \"idb\" ? storage.name : storage.kind === \"file\" ? storage.path : \"\";\n const last = location\n .split(\"/\")\n .filter((segment) => segment !== \"\")\n .pop();\n return last ?? \"pgdata\";\n}\n",
|
|
10
|
+
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type {\n BuildCapabilities,\n BuildIdentity,\n DataDirEntry,\n DebugLevel,\n PostgresBuild,\n RunningPostgres,\n ServerExtension,\n StorageRequest,\n WireSession,\n} from \"../build/seam\";\nimport {\n DataDirExistsError,\n makeQueryError,\n PgwasmClosedError,\n PgwasmError,\n PgwasmFailedError,\n UnsupportedFeatureError,\n} from \"../errors\";\nimport type {\n DumpCompression,\n Extension,\n ParserOptions,\n Pgwasm,\n QueryOptions,\n Results,\n SerializerOptions,\n StorageDescription,\n Transaction,\n} from \"../interface\";\nimport {\n DatabaseError,\n NoticeMessage,\n NotificationResponseMessage,\n type BackendMessage,\n} from \"../protocol/wire/messages\";\nimport { Parser as WireParser } from \"../protocol/wire/parser\";\nimport { serialize } from \"../protocol/wire/serializer\";\nimport { query as queryTemplate } from \"../templating\";\nimport {\n arrayParser,\n arraySerializer,\n parsers as defaultParsers,\n serializers as defaultSerializers,\n toText,\n type Parser,\n type Serializer,\n} from \"../types\";\nimport { writeDataDirArchive } from \"./data-dir-archive\";\nimport {\n type ExecProtocolOptions,\n type ExecProtocolResult,\n type ExecProtocolStreamOptions,\n registerProtocolAccess,\n} from \"./internals\";\nimport { BUILD_MARKER_PATH, checkBuildMarker, encodeBuildMarker, PG_VERSION_PATH } from \"./marker\";\nimport { Mutex } from \"./mutex\";\nimport { quoteIdentifier, toPostgresName } from \"./names\";\nimport { parseDescribeStatementResults, parseResults } from \"./parse\";\nimport { backupBaseName, describeStorage } from \"./storage\";\n\n/** Everything `createPgwasm` resolved and validated before booting. */\nexport interface BootPlan {\n readonly build: PostgresBuild;\n readonly storage: StorageRequest;\n readonly serverExtensions: readonly ServerExtension[];\n readonly clientExtensions: readonly (readonly [key: string, extension: Extension])[];\n /** A Store backup's entries to create the data directory from, marker included. */\n readonly restore: readonly DataDirEntry[] | undefined;\n readonly settings: Readonly<Record<string, string>>;\n readonly user: string;\n readonly database: string;\n readonly username: string | undefined;\n readonly debug: DebugLevel;\n readonly relaxedDurability: boolean;\n readonly parsers: ParserOptions | undefined;\n readonly serializers: SerializerOptions | undefined;\n}\n\ninterface CurrentQuery {\n results: BackendMessage[];\n throwOnError: boolean;\n onNotice: ((notice: NoticeMessage) => void) | undefined;\n databaseError: DatabaseError | null;\n}\n\nfunction newQuery(throwOnError = false, onNotice?: (notice: NoticeMessage) => void): CurrentQuery {\n return { results: [], throwOnError, onNotice, databaseError: null };\n}\n\nfunction describeException(error: unknown): string {\n if (typeof error === \"object\" && error !== null && \"message\" in error) {\n const { name, message } = error as { name?: unknown; message?: unknown };\n return `${typeof name === \"string\" ? name : \"Error\"}: ${String(message)}`;\n }\n return String(error);\n}\n\nfunction concatChunks(chunks: readonly Uint8Array[]): Uint8Array {\n if (chunks.length === 1) return chunks[0] ?? new Uint8Array(0);\n const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return out;\n}\n\n/**\n * A running database over a Postgres build. Everything above the wire protocol lives here, once for\n * every build: queries and transactions, the persist scheduler and its latch, the failure latch,\n * notifications, array types, backups and the build marker.\n */\nexport class PgwasmInstance implements Pgwasm {\n readonly build: BuildIdentity;\n readonly storage: StorageDescription;\n readonly debug: DebugLevel;\n readonly waitReady: Promise<void>;\n\n readonly #capabilities: BuildCapabilities;\n readonly #relaxedDurability: boolean;\n #resolveReady: () => void = () => undefined;\n #rejectReady: (error: unknown) => void = () => undefined;\n\n #ready = false;\n #closing = false;\n #closed = false;\n // Set when the build failed underneath a statement: every later statement throws it (see #fail).\n #failure: { error: PgwasmFailedError } | undefined;\n // A background (relaxed) persist that failed: the next statement reports it.\n #persistFailure: { error: unknown } | undefined;\n #persistScheduled = false;\n\n readonly #queryMutex = new Mutex();\n readonly #transactionMutex = new Mutex();\n readonly #listenMutex = new Mutex();\n readonly #persistMutex = new Mutex();\n\n #running: RunningPostgres | undefined;\n #session: WireSession | undefined;\n readonly #extensionsClose: (() => Promise<void>)[] = [];\n\n #parser = new WireParser();\n readonly #unsolicitedParser = new WireParser();\n #currentQuery: CurrentQuery = newQuery();\n\n readonly #notifyListeners = new Map<string, Set<(payload: string) => void>>();\n readonly #globalNotifyListeners = new Set<(channel: string, payload: string) => void>();\n\n readonly #parsers: Record<number | string, Parser>;\n readonly #serializers: Record<number | string, Serializer>;\n #arrayTypesInitialized = false;\n #inTransaction = false;\n\n constructor(plan: BootPlan) {\n this.build = plan.build.identity;\n this.#capabilities = plan.build.capabilities;\n this.storage = describeStorage(plan.storage);\n this.debug = plan.debug;\n this.#relaxedDurability = plan.relaxedDurability;\n this.#parsers = { ...defaultParsers, ...plan.parsers };\n this.#serializers = { ...defaultSerializers, ...plan.serializers };\n this.waitReady = new Promise<void>((resolve, reject) => {\n this.#resolveReady = resolve;\n this.#rejectReady = reject;\n });\n // A failed boot is reported by createPgwasm; the rejection here must not also surface unhandled.\n this.waitReady.catch(() => undefined);\n registerProtocolAccess(this, {\n execProtocol: (message, options) => this.#execProtocol(message, options),\n execProtocolStream: (message, options) => this.#execProtocolStream(message, options),\n execProtocolRaw: (message, options) => this.#execProtocolRaw(message, options),\n execProtocolRawStream: (message, options) => this.#execProtocolRawStream(message, options),\n runExclusiveSession: (fn) => this.#runExclusiveSession(fn),\n capabilities: this.#capabilities,\n });\n }\n\n // ─── boot ────────────────────────────────────────────────────────────────────\n\n /** Boot the build, check the build marker, create or restore the data directory, and start. */\n async boot(plan: BootPlan): Promise<void> {\n try {\n await this.#boot(plan);\n this.#resolveReady();\n } catch (error) {\n this.#rejectReady(error);\n throw error;\n }\n }\n\n async #boot(plan: BootPlan): Promise<void> {\n const inits: (() => Promise<void>)[] = [];\n for (const [key, extension] of plan.clientExtensions) {\n const result = await extension.setup(this);\n if (result.namespace !== undefined) {\n if (key in this) {\n throw new PgwasmError(`The extension key \"${key}\" collides with a pgwasm member; use another key.`);\n }\n Object.defineProperty(this, key, { value: result.namespace, enumerable: true });\n }\n if (result.init) inits.push(result.init);\n if (result.close) this.#extensionsClose.push(result.close);\n }\n\n const identity = plan.build.identity;\n const mounted = await plan.build.boot({\n storage: plan.storage,\n extensions: plan.serverExtensions,\n user: plan.user,\n database: plan.database,\n debug: plan.debug,\n });\n let running: RunningPostgres;\n try {\n // Build permanence (ADR-0063): refuse another build's directory before anything is written.\n const marker = await mounted.readFile(BUILD_MARKER_PATH);\n const hasCluster = (await mounted.readFile(PG_VERSION_PATH)) !== undefined;\n checkBuildMarker(identity, marker, hasCluster, \"data-directory\");\n if (plan.restore !== undefined) {\n if (hasCluster) throw new DataDirExistsError();\n this.#log(\"pgwasm: creating the data directory from a Store backup\");\n await mounted.writeEntries(plan.restore);\n await mounted.persist();\n } else if (!hasCluster) {\n this.#log(\"pgwasm: no database in the data directory, creating one\");\n await mounted.createCluster();\n if (marker === undefined) await mounted.writeFile(BUILD_MARKER_PATH, encodeBuildMarker(identity));\n await mounted.persist();\n }\n running = await mounted.start({ settings: plan.settings });\n } catch (error) {\n try {\n await mounted.release();\n } catch {\n // The boot already failed; its first cause is what the caller needs.\n }\n throw error;\n }\n\n this.#running = running;\n try {\n const session = await running.openSession();\n session.onUnsolicited = (chunk) => this.#handleUnsolicited(chunk);\n this.#session = session;\n this.#ready = true;\n if (plan.username !== undefined) {\n await this.exec(`SET ROLE ${quoteIdentifier(plan.username)}`);\n }\n await this.#initArrayTypes();\n for (const init of inits) {\n await init();\n }\n } catch (error) {\n this.#ready = false;\n this.#closed = true;\n try {\n // A background persist a statement of the boot started (an extension's init) must settle first:\n // releasing tears its storage down under it.\n await this.#persistMutex.runExclusive(async () => {});\n await running.release({ afterFailedBoot: true });\n } catch {\n // Preserve the error that made the boot fail.\n }\n throw error;\n }\n }\n\n // ─── state ───────────────────────────────────────────────────────────────────\n\n get ready(): boolean {\n return this.#ready && !this.#closing && !this.#closed && this.#failure === undefined;\n }\n\n get closed(): boolean {\n return this.#closed;\n }\n\n async #checkReady(): Promise<void> {\n if (this.#closing) throw new PgwasmClosedError(\"closing\");\n if (this.#closed) throw new PgwasmClosedError(\"closed\");\n if (!this.#ready) await this.waitReady;\n }\n\n #checkOpenState(): void {\n if (this.#closing) throw new PgwasmClosedError(\"closing\");\n if (this.#closed) throw new PgwasmClosedError(\"closed\");\n if (this.#failure) throw this.#failure.error;\n }\n\n #checkPersistLatch(): void {\n if (this.#persistFailure) throw this.#persistFailure.error;\n }\n\n /**\n * Latch the instance as failed and return the error the failing statement and every later one\n * throw. It names the exception and, when Postgres reported an error first (a PANIC does, before it\n * aborts), that error.\n */\n #fail(cause: unknown): PgwasmFailedError {\n if (this.#failure) return this.#failure.error;\n const reported = this.#currentQuery.databaseError;\n const error = new PgwasmFailedError(\n \"pgwasm failed and must be closed: \" +\n (reported\n ? `Postgres reported ${reported.severity ?? \"an error\"}: ${reported.message}; the build then threw `\n : \"the build threw \") +\n describeException(cause),\n { cause },\n );\n this.#failure = { error };\n return error;\n }\n\n #log(...args: unknown[]): void {\n if (this.debug > 0) console.log(...args);\n }\n\n // ─── the wire ────────────────────────────────────────────────────────────────\n\n #exchange(message: Uint8Array, onData: (chunk: Uint8Array) => void): void | Promise<void> {\n this.#checkOpenState();\n const session = this.#session;\n if (session === undefined) throw new PgwasmClosedError(\"closed\");\n let pending: void | Promise<void>;\n try {\n pending = session.exchange(message, onData);\n } catch (error) {\n throw this.#fail(error);\n }\n if (pending === undefined) return;\n return pending.then(undefined, (error: unknown) => {\n throw this.#fail(error);\n });\n }\n\n #parseChunk(chunk: Uint8Array): void {\n this.#parser.parse(chunk, (message) => {\n const handled = this.#handleMessage(message);\n if (handled) this.#currentQuery.results.push(handled);\n });\n }\n\n #handleUnsolicited(chunk: Uint8Array): void {\n this.#unsolicitedParser.parse(chunk, (message) => {\n if (message instanceof NotificationResponseMessage) this.#dispatchNotification(message);\n });\n }\n\n #handleMessage(message: BackendMessage): BackendMessage | null {\n // Once a statement reported an error, the rest of its reply only needs acknowledging.\n if (this.#currentQuery.databaseError) return null;\n if (message instanceof DatabaseError) {\n if (this.#currentQuery.throwOnError) this.#currentQuery.databaseError = message;\n } else if (message instanceof NoticeMessage) {\n if (this.debug > 0) console.warn(message);\n this.#currentQuery.onNotice?.(message);\n } else if (message instanceof NotificationResponseMessage) {\n this.#dispatchNotification(message);\n }\n return message;\n }\n\n #dispatchNotification(message: NotificationResponseMessage): void {\n // Callbacks run after the synchronous code that received the notification.\n const listeners = this.#notifyListeners.get(message.channel);\n if (listeners) {\n for (const callback of listeners) queueMicrotask(() => callback(message.payload));\n }\n for (const callback of this.#globalNotifyListeners) {\n queueMicrotask(() => callback(message.channel, message.payload));\n }\n }\n\n async #execProtocolRaw(message: Uint8Array, { persist = true }: Pick<ExecProtocolOptions, \"persist\"> = {}) {\n // Checks only (no await) before the exchange, so a build that exchanges synchronously delivers the\n // reply inside this call's synchronous prefix.\n this.#checkPersistLatch();\n const chunks: Uint8Array[] = [];\n const pending = this.#exchange(message, (chunk) => {\n chunks.push(chunk.slice());\n this.#parseChunk(chunk);\n });\n if (pending !== undefined) await pending;\n if (persist) await this.#persistAfterStatement();\n return concatChunks(chunks);\n }\n\n async #execProtocolRawStream(\n message: Uint8Array,\n { persist = true, onRawData }: ExecProtocolStreamOptions,\n ): Promise<void> {\n // Same synchronous-prefix contract as #execProtocolRaw: pg_dump's write callback drives this from\n // inside a blocking wasm call and reads the reply back before it returns.\n this.#checkPersistLatch();\n const pending = this.#exchange(message, onRawData);\n if (pending !== undefined) await pending;\n if (persist) await this.#persistAfterStatement();\n }\n\n async #execProtocol(\n message: Uint8Array,\n { persist = true, throwOnError = true, onNotice }: ExecProtocolOptions = {},\n ): Promise<ExecProtocolResult> {\n this.#currentQuery = newQuery(throwOnError, onNotice);\n try {\n const data = await this.#execProtocolRaw(message, { persist });\n const databaseError = this.#currentQuery.databaseError;\n const result = { messages: this.#currentQuery.results, data };\n if (throwOnError && databaseError) {\n this.#parser = new WireParser();\n throw databaseError;\n }\n return result;\n } finally {\n this.#currentQuery = newQuery();\n }\n }\n\n async #execProtocolStream(\n message: Uint8Array,\n { persist = true, throwOnError = true, onNotice }: ExecProtocolOptions = {},\n ): Promise<BackendMessage[]> {\n this.#currentQuery = newQuery(throwOnError, onNotice);\n try {\n this.#checkPersistLatch();\n const pending = this.#exchange(message, (chunk) => this.#parseChunk(chunk));\n if (pending !== undefined) await pending;\n if (persist) await this.#persistAfterStatement();\n const databaseError = this.#currentQuery.databaseError;\n const results = this.#currentQuery.results;\n if (throwOnError && databaseError) {\n this.#parser = new WireParser();\n throw databaseError;\n }\n return results;\n } finally {\n this.#currentQuery = newQuery();\n }\n }\n\n // ─── durability ──────────────────────────────────────────────────────────────\n\n /**\n * Persist storage after a statement. Awaited by default; with `relaxedDurability` it runs in the\n * background and a failure is latched for the next statement. An awaited failure is not latched: the\n * caller already has it, and a filesystem with its own failure policy decides what later calls see.\n */\n async #persistAfterStatement(): Promise<void> {\n this.#checkOpenState();\n this.#checkPersistLatch();\n const running = this.#running;\n if (running === undefined || this.#persistScheduled) return;\n this.#persistScheduled = true;\n const run = () =>\n this.#persistMutex.runExclusive(async () => {\n this.#persistScheduled = false;\n await running.persist(this.#relaxedDurability);\n });\n if (this.#relaxedDurability) {\n run().catch((error: unknown) => {\n this.#persistFailure ??= { error };\n });\n } else {\n await run();\n }\n }\n\n // ─── queries ─────────────────────────────────────────────────────────────────\n\n #runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T> {\n return this.#queryMutex.runExclusive(async () => {\n this.#checkPersistLatch();\n return await fn();\n });\n }\n\n async #execNoPersist(message: Uint8Array, options?: QueryOptions): Promise<BackendMessage[]> {\n return await this.#execProtocolStream(message, {\n persist: false,\n ...(options?.onNotice ? { onNotice: options.onNotice } : {}),\n });\n }\n\n async #handleBlob(blob: Blob | undefined): Promise<void> {\n const device = this.#running?.blob;\n if (blob === undefined) {\n device?.setReadSource(undefined);\n return;\n }\n if (device === undefined) {\n throw new UnsupportedFeatureError(\n `The \"${this.build.name}\" Postgres build has no /dev/blob device, so the \\`blob\\` query option is not available.`,\n );\n }\n device.setReadSource(new Uint8Array(await blob.arrayBuffer()));\n }\n\n #cleanupBlob(): void {\n this.#running?.blob?.setReadSource(undefined);\n }\n\n #takeWrittenBlob(): Blob | undefined {\n const chunks = this.#running?.blob?.takeWritten();\n return chunks === undefined ? undefined : new Blob(chunks);\n }\n\n #serializeParams(\n params: readonly unknown[],\n dataTypeIDs: readonly number[],\n options?: QueryOptions,\n ): (string | null)[] {\n return params.map((param, index) => {\n if (param === null || param === undefined) return null;\n const oid = dataTypeIDs[index] ?? 0;\n const serializer = options?.serializers?.[oid] ?? this.#serializers[oid];\n return serializer ? serializer(param) : toText(param);\n });\n }\n\n async #runQuery<T>(sql: string, params: readonly unknown[] = [], options?: QueryOptions): Promise<Results<T>> {\n return await this.#runExclusiveQuery(async () => {\n this.#log(\"runQuery\", sql, params, options);\n await this.#handleBlob(options?.blob);\n let results: BackendMessage[] = [];\n try {\n const parsed = await this.#execNoPersist(\n serialize.parse({ text: sql, ...(options?.paramTypes ? { types: options.paramTypes } : {}) }),\n options,\n );\n const dataTypeIDs = parseDescribeStatementResults(\n await this.#execNoPersist(serialize.describe({ type: \"S\" }), options),\n );\n const values = this.#serializeParams(params, dataTypeIDs, options);\n results = [\n ...parsed,\n ...(await this.#execNoPersist(serialize.bind({ values }), options)),\n ...(await this.#execNoPersist(serialize.describe({ type: \"P\" }), options)),\n ...(await this.#execNoPersist(serialize.execute({}), options)),\n ];\n } catch (error) {\n if (error instanceof DatabaseError) {\n throw makeQueryError({ error, query: sql, params, options });\n }\n throw error;\n } finally {\n results.push(...(await this.#execNoPersist(serialize.sync(), options)));\n }\n this.#cleanupBlob();\n if (!this.#inTransaction) await this.#persistAfterStatement();\n const blob = this.#takeWrittenBlob();\n // The row type is the caller's assertion, as with any driver.\n return parseResults(results, this.#parsers, options, blob)[0] as Results<T>;\n });\n }\n\n async #runExec(sql: string, options?: QueryOptions): Promise<Results[]> {\n return await this.#runExclusiveQuery(async () => {\n this.#log(\"runExec\", sql, options);\n await this.#handleBlob(options?.blob);\n let results: BackendMessage[] = [];\n try {\n results = await this.#execNoPersist(serialize.query(sql), options);\n } catch (error) {\n if (error instanceof DatabaseError) {\n throw makeQueryError({ error, query: sql, params: undefined, options });\n }\n throw error;\n } finally {\n results.push(...(await this.#execNoPersist(serialize.sync(), options)));\n }\n this.#cleanupBlob();\n if (!this.#inTransaction) await this.#persistAfterStatement();\n const blob = this.#takeWrittenBlob();\n return parseResults(results, this.#parsers, options, blob) as Results[];\n });\n }\n\n async query<T = Record<string, unknown>>(\n sql: string,\n params?: readonly unknown[],\n options?: QueryOptions,\n ): Promise<Results<T>> {\n await this.#checkReady();\n // One statement at a time, never inside another caller's transaction.\n return await this.#transactionMutex.runExclusive(() => this.#runQuery<T>(sql, params, options));\n }\n\n async sql<T = Record<string, unknown>>(sqlStrings: TemplateStringsArray, ...params: unknown[]): Promise<Results<T>> {\n const { query, params: actualParams } = queryTemplate(sqlStrings, ...params);\n return await this.query<T>(query, actualParams);\n }\n\n async exec(sql: string, options?: QueryOptions): Promise<Results[]> {\n await this.#checkReady();\n return await this.#transactionMutex.runExclusive(() => this.#runExec(sql, options));\n }\n\n async transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T> {\n await this.#checkReady();\n return await this.#transactionMutex.runExclusive(async () => {\n await this.#runExec(\"BEGIN\");\n this.#inTransaction = true;\n\n // A transaction handle throws once its transaction has ended.\n let closed = false;\n const checkClosed = () => {\n if (closed) throw new PgwasmError(\"Transaction is closed\");\n };\n\n const tx: Transaction = {\n query: async <R>(sql: string, params?: readonly unknown[], options?: QueryOptions) => {\n checkClosed();\n return await this.#runQuery<R>(sql, params, options);\n },\n sql: async <R>(sqlStrings: TemplateStringsArray, ...params: unknown[]) => {\n checkClosed();\n const { query, params: actualParams } = queryTemplate(sqlStrings, ...params);\n return await this.#runQuery<R>(query, actualParams);\n },\n exec: async (sql: string, options?: QueryOptions) => {\n checkClosed();\n return await this.#runExec(sql, options);\n },\n rollback: async () => {\n checkClosed();\n await this.#runExec(\"ROLLBACK\");\n closed = true;\n },\n listen: async (channel: string, callback: (payload: string) => void) => {\n checkClosed();\n return await this.listen(channel, callback, tx);\n },\n get closed() {\n return closed;\n },\n };\n\n try {\n const result = await callback(tx);\n // Leave the in-transaction state before the terminal statement, so COMMIT persists like any\n // top-level statement instead of waiting for some later query.\n this.#inTransaction = false;\n if (!closed) {\n closed = true;\n await this.#runExec(\"COMMIT\");\n } else {\n // An explicit tx.rollback() ran inside the transaction; persist its outcome now.\n await this.#persistAfterStatement();\n }\n return result;\n } catch (error) {\n this.#inTransaction = false;\n if (!closed) {\n closed = true;\n await this.#runExec(\"ROLLBACK\");\n } else {\n // The transaction ended without reaching a persist: an explicit rollback, or a COMMIT that\n // threw. End at a persist boundary anyway, but never mask the original error with a persist\n // failure; a failing storage reports again on the next statement.\n try {\n await this.#persistAfterStatement();\n } catch {\n // the original error takes precedence\n }\n }\n throw error;\n }\n });\n }\n\n async runExclusive<T>(fn: () => Promise<T>): Promise<T> {\n return await this.#runExclusiveQuery(fn);\n }\n\n /** `/protocol`'s exclusive session: the transaction lock, then the query lock, for `fn`'s whole run. */\n async #runExclusiveSession<T>(fn: () => Promise<T>): Promise<T> {\n await this.#checkReady();\n return await this.#transactionMutex.runExclusive(() =>\n this.#queryMutex.runExclusive(async () => {\n this.#checkOpenState();\n this.#checkPersistLatch();\n return await fn();\n }),\n );\n }\n\n // ─── array types ─────────────────────────────────────────────────────────────\n\n async #initArrayTypes({ force = false } = {}): Promise<void> {\n if (this.#arrayTypesInitialized && !force) return;\n this.#arrayTypesInitialized = true;\n const types = await this.query<{ oid: number; typarray: number }>(`\n SELECT b.oid, b.typarray\n FROM pg_catalog.pg_type a\n LEFT JOIN pg_catalog.pg_type b ON b.oid = a.typelem\n WHERE a.typcategory = 'A'\n GROUP BY b.oid, b.typarray\n ORDER BY b.oid\n `);\n for (const type of types.rows) {\n this.#serializers[type.typarray] = (value) => arraySerializer(value, this.#serializers[type.oid], type.typarray);\n this.#parsers[type.typarray] = (value) => arrayParser(value, this.#parsers[type.oid], type.typarray);\n }\n }\n\n async refreshArrayTypes(): Promise<void> {\n await this.#initArrayTypes({ force: true });\n }\n\n // ─── notifications ───────────────────────────────────────────────────────────\n\n // Lock order: the transaction lock, then the listen lock, then the query lock. A transaction's\n // tx.listen() runs with the transaction lock already held, so a top-level listen must take the\n // transaction lock before the listen lock too, or each would hold the lock the other waits for.\n\n async listen(\n channel: string,\n callback: (payload: string) => void,\n tx?: Transaction,\n ): Promise<(tx?: Transaction) => Promise<void>> {\n return await this.#withListenLocks(tx, (exec) => this.#subscribe(channel, callback, exec));\n }\n\n async unlisten(channel: string, callback?: (payload: string) => void, tx?: Transaction): Promise<void> {\n await this.#withListenLocks(tx, (exec) => this.#unsubscribe(channel, callback, exec));\n }\n\n async #withListenLocks<T>(\n tx: Transaction | undefined,\n fn: (exec: (sql: string) => Promise<unknown>) => Promise<T>,\n ): Promise<T> {\n if (tx) return await this.#listenMutex.runExclusive(() => fn((sql) => tx.exec(sql)));\n await this.#checkReady();\n return await this.#transactionMutex.runExclusive(() =>\n this.#listenMutex.runExclusive(() => fn((sql) => this.#runExec(sql))),\n );\n }\n\n async #subscribe(\n channel: string,\n callback: (payload: string) => void,\n exec: (sql: string) => Promise<unknown>,\n ): Promise<(tx?: Transaction) => Promise<void>> {\n const pgChannel = toPostgresName(channel);\n let listeners = this.#notifyListeners.get(pgChannel);\n if (!listeners) {\n listeners = new Set();\n this.#notifyListeners.set(pgChannel, listeners);\n }\n listeners.add(callback);\n try {\n await exec(`LISTEN ${channel}`);\n } catch (error) {\n listeners.delete(callback);\n if (listeners.size === 0) this.#notifyListeners.delete(pgChannel);\n throw error;\n }\n // By the channel as the caller wrote it: unlisten() normalises it the same way listen() did.\n return async (unlistenTx?: Transaction) => {\n await this.unlisten(channel, callback, unlistenTx);\n };\n }\n\n async #unsubscribe(\n channel: string,\n callback: ((payload: string) => void) | undefined,\n exec: (sql: string) => Promise<unknown>,\n ): Promise<void> {\n const pgChannel = toPostgresName(channel);\n const cleanUp = async () => {\n await exec(`UNLISTEN ${channel}`);\n // Another caller may have subscribed while UNLISTEN ran.\n if (this.#notifyListeners.get(pgChannel)?.size === 0) this.#notifyListeners.delete(pgChannel);\n };\n if (callback) {\n this.#notifyListeners.get(pgChannel)?.delete(callback);\n if (this.#notifyListeners.get(pgChannel)?.size === 0) await cleanUp();\n } else {\n await cleanUp();\n }\n }\n\n onNotification(callback: (channel: string, payload: string) => void): () => void {\n this.#globalNotifyListeners.add(callback);\n return () => {\n this.#globalNotifyListeners.delete(callback);\n };\n }\n\n // ─── backups ─────────────────────────────────────────────────────────────────\n\n /**\n * A Store backup. It reads the data directory under the query lock, so no statement runs during the\n * read; do not call it from inside `runExclusive`.\n */\n async dumpDataDir(compression?: DumpCompression): Promise<File> {\n await this.#checkReady();\n const running = this.#running;\n if (running === undefined) throw new PgwasmClosedError(\"closed\");\n const entries = await this.#queryMutex.runExclusive(async () => {\n this.#checkOpenState();\n return await running.readEntries();\n });\n return await writeDataDirArchive(entries, backupBaseName(this.storage), compression);\n }\n\n // ─── close ───────────────────────────────────────────────────────────────────\n\n async close(): Promise<void> {\n await this.#checkReady();\n this.#closing = true;\n // After a failure the build is in an unknown state: running its shutdown or persisting what it left\n // would build on it. Close then only releases resources, and reports the failure it closed on.\n const failure = this.#failure;\n const running = this.#running;\n const session = this.#session;\n let closeFailure: { error: unknown } | undefined;\n let finalPersistFailure: { error: unknown } | undefined;\n try {\n await this.#transactionMutex.runExclusive(() =>\n this.#queryMutex.runExclusive(async () => {\n for (const closeFn of this.#extensionsClose) {\n try {\n await closeFn();\n } catch (error) {\n closeFailure ??= { error };\n }\n }\n if (failure || running === undefined) return;\n try {\n await session?.close();\n await running.shutdown();\n } catch (error) {\n closeFailure ??= { error };\n }\n // Persist shutdown's writes strictly. A successful final persist also recovers a prior\n // background failure.\n try {\n await this.#persistMutex.runExclusive(() => running.persist(false));\n this.#persistFailure = undefined;\n } catch (error) {\n finalPersistFailure = { error };\n this.#persistFailure = { error };\n }\n }),\n );\n } finally {\n try {\n // A background persist may still be running: a close after a failure skips the final persist\n // that would otherwise queue behind it. Releasing tears its storage down under it, so wait first.\n await this.#persistMutex.runExclusive(async () => {});\n // Release even when shutdown or persisting failed, so exclusive storage ownership is released.\n await running?.release();\n } finally {\n this.#closed = true;\n this.#closing = false;\n this.#ready = false;\n this.#session = undefined;\n this.#running = undefined;\n }\n }\n if (failure) throw failure.error;\n if (finalPersistFailure) throw finalPersistFailure.error;\n if (closeFailure) throw closeFailure.error;\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n await this.close();\n }\n}\n",
|
|
11
|
+
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { DataDirEntry, PostgresBuild, ServerExtension } from \"./build/seam\";\nimport { readDataDirArchive } from \"./core/data-dir-archive\";\nimport { BUILD_MARKER_PATH, checkBuildMarker, encodeBuildMarker, findEntry, PG_VERSION_PATH } from \"./core/marker\";\nimport { PgwasmInstance } from \"./core/pgwasm\";\nimport { resolveStorage } from \"./core/storage\";\nimport {\n BackupFormatError,\n CrossOriginIsolationRequiredError,\n ExtensionBuildMismatchError,\n UnsupportedFilesystemError,\n} from \"./errors\";\nimport type { Extension, Extensions, PgwasmOptions, PgwasmWithExtensions } from \"./interface\";\n\nfunction isServerExtension(extension: Extension | ServerExtension): extension is ServerExtension {\n return \"kind\" in extension && extension.kind === \"server\";\n}\n\nfunction assertBuild(build: unknown): asserts build is PostgresBuild {\n const candidate = build as Partial<PostgresBuild> | null | undefined;\n if (\n typeof candidate !== \"object\" ||\n candidate === null ||\n typeof candidate.boot !== \"function\" ||\n typeof candidate.identity?.name !== \"string\" ||\n !Array.isArray(candidate.capabilities?.filesystems)\n ) {\n throw new TypeError(\"createPgwasm needs a Postgres build in `build`, e.g. `cBuild` from @pgxsinkit/pgwasm-c.\");\n }\n}\n\n/** Merge the server extensions' preload libraries into the settings. */\nfunction mergeSettings(\n settings: Readonly<Record<string, string>> | undefined,\n serverExtensions: readonly ServerExtension[],\n): Record<string, string> {\n const merged: Record<string, string> = { ...settings };\n const preload = serverExtensions.flatMap((extension) => extension.sharedPreloadLibraries ?? []);\n if (preload.length > 0) {\n const existing = (merged[\"shared_preload_libraries\"] ?? \"\")\n .split(\",\")\n .map((library) => library.trim())\n .filter((library) => library !== \"\");\n merged[\"shared_preload_libraries\"] = [...new Set([...existing, ...preload])].join(\",\");\n }\n return merged;\n}\n\n/**\n * A Store backup's entries, checked against the build before anything is booted, with the build\n * marker added when the backup has none (it predates marking and is the C build's).\n */\nasync function restoreEntries(build: PostgresBuild, loadDataDir: Blob | File): Promise<readonly DataDirEntry[]> {\n const entries = await readDataDirArchive(loadDataDir);\n if (findEntry(entries, PG_VERSION_PATH) === undefined) {\n throw new BackupFormatError(\"The Store backup holds no data directory (it has no PG_VERSION).\");\n }\n const marker = findEntry(entries, BUILD_MARKER_PATH);\n checkBuildMarker(build.identity, marker?.data, true, \"backup\");\n if (marker !== undefined) return entries;\n return [\n ...entries,\n {\n path: BUILD_MARKER_PATH,\n type: \"file\",\n mode: 0o600,\n mtimeSeconds: Math.floor(Date.now() / 1000),\n data: encodeBuildMarker(build.identity),\n },\n ];\n}\n\n/**\n * Start a database on a Postgres build. Resolves once it is ready.\n *\n * Everything that can be checked before booting is: the `dataDir` scheme, the build's supported\n * storage and cross-origin isolation, each server extension's build, and a Store backup's recorded\n * build (ADR-0063). The booted data directory's recorded build is checked before anything is written.\n */\nexport async function createPgwasm<E extends Extensions = Record<never, never>>(\n options: PgwasmOptions<E>,\n): Promise<PgwasmWithExtensions<E>> {\n const build: unknown = options.build;\n assertBuild(build);\n const identity = build.identity;\n const capabilities = build.capabilities;\n\n const storage = resolveStorage(options.dataDir, options.fs);\n if (!capabilities.filesystems.includes(storage.kind)) {\n throw new UnsupportedFilesystemError(storage.kind, identity, capabilities.filesystems);\n }\n if (\n capabilities.requiresCrossOriginIsolation &&\n (globalThis as { crossOriginIsolated?: boolean }).crossOriginIsolated === false\n ) {\n throw new CrossOriginIsolationRequiredError(identity);\n }\n\n const serverExtensions: ServerExtension[] = [];\n const clientExtensions: [string, Extension][] = [];\n for (const [key, extension] of Object.entries(options.extensions ?? {})) {\n if (isServerExtension(extension)) {\n if (extension.build !== identity.name) {\n throw new ExtensionBuildMismatchError(extension.name, extension.build, identity);\n }\n serverExtensions.push(extension);\n } else {\n clientExtensions.push([key, extension]);\n }\n }\n\n const restore = options.loadDataDir === undefined ? undefined : await restoreEntries(build, options.loadDataDir);\n const plan = {\n build,\n storage,\n serverExtensions,\n clientExtensions,\n restore,\n settings: mergeSettings(options.settings, serverExtensions),\n user: options.username ?? \"postgres\",\n database: options.database ?? \"postgres\",\n username: options.username,\n debug: options.debug ?? 0,\n relaxedDurability: options.relaxedDurability ?? false,\n parsers: options.parsers,\n serializers: options.serializers,\n } as const;\n const instance = new PgwasmInstance(plan);\n await instance.boot(plan);\n // The namespaces were attached under their keys during boot.\n return instance as PgwasmInstance & PgwasmWithExtensions<E>;\n}\n"
|
|
12
|
+
],
|
|
13
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;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cAAc,CAAC,CAAC,GAAG;AAAA,IACvE,IAAI,kBAAkB,SAAS,GAAG;AAAA,MAChC,IAAI,UAAU,UAAU,SAAS,MAAM;AAAA,QACrC,MAAM,IAAI,6BAA4B,UAAU,MAAM,UAAU,OAAO,QAAQ;AAAA,MACjF;AAAA,MACA,iBAAiB,KAAK,SAAS;AAAA,IACjC,EAAO;AAAA,MACL,iBAAiB,KAAK,CAAC,KAAK,SAAS,CAAC;AAAA;AAAA,EAE1C;AAAA,EAEA,MAAM,UAAU,QAAQ,gBAAgB,YAAY,YAAY,MAAM,eAAe,OAAO,QAAQ,WAAW;AAAA,EAC/G,MAAM,OAAO;AAAA,IACX;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,UAAU,cAAc,QAAQ,UAAU,gBAAgB;AAAA,IAC1D,MAAM,QAAQ,YAAY;AAAA,IAC1B,UAAU,QAAQ,YAAY;AAAA,IAC9B,UAAU,QAAQ;AAAA,IAClB,OAAO,QAAQ,SAAS;AAAA,IACxB,mBAAmB,QAAQ,qBAAqB;AAAA,IAChD,SAAS,QAAQ;AAAA,IACjB,aAAa,QAAQ;AAAA,EACvB;AAAA,EACA,MAAM,WAAW,IAAI,eAAe,IAAI;AAAA,EACxC,MAAM,SAAS,KAAK,IAAI;AAAA,EAExB,OAAO;AAAA;",
|
|
14
|
+
"debugId": "EB995FC77D1C6A9B64756E2164756E21",
|
|
15
|
+
"names": []
|
|
16
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __returnValue = (v) => v;
|
|
4
|
+
function __exportSetter(name, newValue) {
|
|
5
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
6
|
+
}
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, {
|
|
10
|
+
get: all[name],
|
|
11
|
+
enumerable: true,
|
|
12
|
+
configurable: true,
|
|
13
|
+
set: __exportSetter.bind(all, name)
|
|
14
|
+
});
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export { __export };
|
|
18
|
+
|
|
19
|
+
//# debugId=C2410D0E8F6C9B0664756E2164756E21
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
parseType
|
|
4
|
+
} from "./chunk-d82gg1hx.js";
|
|
5
|
+
import {
|
|
6
|
+
RowDescriptionMessage,
|
|
7
|
+
ParameterDescriptionMessage,
|
|
8
|
+
CommandCompleteMessage,
|
|
9
|
+
DataRowMessage
|
|
10
|
+
} from "./chunk-74gcrk47.js";
|
|
11
|
+
|
|
12
|
+
// packages/pgwasm/src/core/names.ts
|
|
13
|
+
function toPostgresName(input) {
|
|
14
|
+
if (input.startsWith('"') && input.endsWith('"') && input.length >= 2) {
|
|
15
|
+
return input.slice(1, -1);
|
|
16
|
+
}
|
|
17
|
+
return input.toLowerCase();
|
|
18
|
+
}
|
|
19
|
+
function quoteIdentifier(name) {
|
|
20
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
21
|
+
}
|
|
22
|
+
function randomId() {
|
|
23
|
+
const bytes = new Uint8Array(16);
|
|
24
|
+
crypto.getRandomValues(bytes);
|
|
25
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// packages/pgwasm/src/core/parse.ts
|
|
29
|
+
function parseResults(messages, defaultParsers, options, blob) {
|
|
30
|
+
const resultSets = [];
|
|
31
|
+
let current = { rows: [], fields: [] };
|
|
32
|
+
let affectedRows = 0;
|
|
33
|
+
const parsers = { ...defaultParsers, ...options?.parsers };
|
|
34
|
+
for (const message of messages) {
|
|
35
|
+
if (message instanceof RowDescriptionMessage) {
|
|
36
|
+
current.fields = message.fields.map((field) => ({ name: field.name, dataTypeID: field.dataTypeID }));
|
|
37
|
+
} else if (message instanceof DataRowMessage) {
|
|
38
|
+
const fields = current.fields;
|
|
39
|
+
const typeOf = (index) => fields[index]?.dataTypeID ?? 0;
|
|
40
|
+
if (options?.rowMode === "array") {
|
|
41
|
+
current.rows.push(message.fields.map((value, index) => parseType(value, typeOf(index), parsers)));
|
|
42
|
+
} else {
|
|
43
|
+
const row = {};
|
|
44
|
+
message.fields.forEach((value, index) => {
|
|
45
|
+
row[fields[index]?.name ?? String(index)] = parseType(value, typeOf(index), parsers);
|
|
46
|
+
});
|
|
47
|
+
current.rows.push(row);
|
|
48
|
+
}
|
|
49
|
+
} else if (message instanceof CommandCompleteMessage) {
|
|
50
|
+
const parts = message.text.split(" ");
|
|
51
|
+
const command = parts[0] ?? "";
|
|
52
|
+
const rowCount = Number.parseInt(parts[parts.length - 1] ?? "", 10);
|
|
53
|
+
switch (command) {
|
|
54
|
+
case "INSERT":
|
|
55
|
+
case "UPDATE":
|
|
56
|
+
case "DELETE":
|
|
57
|
+
case "COPY":
|
|
58
|
+
case "MERGE":
|
|
59
|
+
affectedRows += rowCount;
|
|
60
|
+
break;
|
|
61
|
+
}
|
|
62
|
+
const result = { ...current, command, affectedRows };
|
|
63
|
+
if (!Number.isNaN(rowCount))
|
|
64
|
+
result.rowCount = rowCount;
|
|
65
|
+
if (blob)
|
|
66
|
+
result.blob = blob;
|
|
67
|
+
resultSets.push(result);
|
|
68
|
+
current = { rows: [], fields: [] };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (resultSets.length === 0) {
|
|
72
|
+
resultSets.push({ affectedRows: 0, rows: [], fields: [] });
|
|
73
|
+
}
|
|
74
|
+
return resultSets;
|
|
75
|
+
}
|
|
76
|
+
function parseDescribeStatementResults(messages) {
|
|
77
|
+
const message = messages.find((msg) => msg instanceof ParameterDescriptionMessage);
|
|
78
|
+
return message ? message.dataTypeIDs : [];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export { toPostgresName, quoteIdentifier, randomId, parseResults, parseDescribeStatementResults };
|
|
82
|
+
|
|
83
|
+
//# debugId=C407675D55809A7C64756E2164756E21
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/core/names.ts", "../src/core/parse.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\n/**\n * The name Postgres stores for an identifier: a quoted one keeps its case (quotes removed), an\n * unquoted one is folded to lower case. Used to key notification listeners the way Postgres names\n * the channel.\n */\nexport function toPostgresName(input: string): string {\n if (input.startsWith('\"') && input.endsWith('\"') && input.length >= 2) {\n return input.slice(1, -1);\n }\n return input.toLowerCase();\n}\n\n/** Quote an identifier for SQL: wrap in double quotes, doubling any inside. */\nexport function quoteIdentifier(name: string): string {\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n}\n\n/** A random 32-character hex id, for the names of temporary objects. */\nexport function randomId(): string {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n",
|
|
6
|
+
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { QueryOptions, Results, Row } from \"../interface\";\nimport {\n CommandCompleteMessage,\n DataRowMessage,\n ParameterDescriptionMessage,\n RowDescriptionMessage,\n type BackendMessage,\n} from \"../protocol/wire/messages\";\nimport { parseType, type Parser } from \"../types\";\n\n/**\n * Turn the backend messages of a simple or extended query into result sets, one per statement\n * (https://www.postgresql.org/docs/current/protocol-flow.html).\n */\nexport function parseResults(\n messages: readonly BackendMessage[],\n defaultParsers: Readonly<Record<number | string, Parser>>,\n options?: QueryOptions,\n blob?: Blob,\n): Results<unknown>[] {\n const resultSets: Results<unknown>[] = [];\n let current: Results<unknown> = { rows: [], fields: [] };\n let affectedRows = 0;\n const parsers = { ...defaultParsers, ...options?.parsers };\n\n for (const message of messages) {\n if (message instanceof RowDescriptionMessage) {\n current.fields = message.fields.map((field) => ({ name: field.name, dataTypeID: field.dataTypeID }));\n } else if (message instanceof DataRowMessage) {\n const fields = current.fields;\n const typeOf = (index: number) => fields[index]?.dataTypeID ?? 0;\n if (options?.rowMode === \"array\") {\n current.rows.push(message.fields.map((value, index) => parseType(value, typeOf(index), parsers)));\n } else {\n const row: Row = {};\n message.fields.forEach((value, index) => {\n row[fields[index]?.name ?? String(index)] = parseType(value, typeOf(index), parsers);\n });\n current.rows.push(row);\n }\n } else if (message instanceof CommandCompleteMessage) {\n // A tag that carries a row count ends in it (\"SELECT 2\", \"UPDATE 3\", \"INSERT 0 5\"); the rest end\n // in a word (\"CREATE TABLE\").\n const parts = message.text.split(\" \");\n const command = parts[0] ?? \"\";\n const rowCount = Number.parseInt(parts[parts.length - 1] ?? \"\", 10);\n switch (command) {\n case \"INSERT\":\n case \"UPDATE\":\n case \"DELETE\":\n case \"COPY\":\n case \"MERGE\":\n affectedRows += rowCount;\n break;\n }\n const result: Results<unknown> = { ...current, command, affectedRows };\n if (!Number.isNaN(rowCount)) result.rowCount = rowCount;\n if (blob) result.blob = blob;\n resultSets.push(result);\n current = { rows: [], fields: [] };\n }\n }\n\n if (resultSets.length === 0) {\n resultSets.push({ affectedRows: 0, rows: [], fields: [] });\n }\n return resultSets;\n}\n\n/** The parameter type OIDs from a Describe(statement) reply, when it has them. */\nexport function parseDescribeStatementResults(messages: readonly BackendMessage[]): number[] {\n const message = messages.find(\n (msg): msg is ParameterDescriptionMessage => msg instanceof ParameterDescriptionMessage,\n );\n return message ? message.dataTypeIDs : [];\n}\n"
|
|
7
|
+
],
|
|
8
|
+
"mappings": ";;;;;;;;;;;;AAQO,SAAS,cAAc,CAAC,OAAuB;AAAA,EACpD,IAAI,MAAM,WAAW,GAAG,KAAK,MAAM,SAAS,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F: 8,
|
|
5
|
+
EBADFD: 127,
|
|
6
|
+
EEXIST: 20,
|
|
7
|
+
EINVAL: 28,
|
|
8
|
+
EIO: 29,
|
|
9
|
+
EISDIR: 31,
|
|
10
|
+
ENODEV: 43,
|
|
11
|
+
ENOENT: 44,
|
|
12
|
+
ENOTDIR: 54,
|
|
13
|
+
ENOTEMPTY: 55
|
|
14
|
+
};
|
|
15
|
+
var MAX_SYSCALL_ERRORS = 50;
|
|
16
|
+
var DEFAULT_DESCRIPTION = Object.freeze({ name: "custom" });
|
|
17
|
+
|
|
18
|
+
class BaseFilesystem2 {
|
|
19
|
+
debug;
|
|
20
|
+
#recentSyscallErrors = [];
|
|
21
|
+
constructor({ debug = false } = {}) {
|
|
22
|
+
this.debug = debug;
|
|
23
|
+
}
|
|
24
|
+
get description() {
|
|
25
|
+
return DEFAULT_DESCRIPTION;
|
|
26
|
+
}
|
|
27
|
+
get recentSyscallErrors() {
|
|
28
|
+
return this.#recentSyscallErrors;
|
|
29
|
+
}
|
|
30
|
+
recordSyscallError(op, path, errno, message) {
|
|
31
|
+
const buffer = this.#recentSyscallErrors;
|
|
32
|
+
buffer.push({ op, path, errno, message, timeMs: Date.now() });
|
|
33
|
+
if (buffer.length > MAX_SYSCALL_ERRORS) {
|
|
34
|
+
buffer.shift();
|
|
35
|
+
}
|
|
36
|
+
if (this.debug) {
|
|
37
|
+
console.warn("[pgwasm-fs] syscall error", op, path, errno, message);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
async syncToFs(_relaxed) {}
|
|
41
|
+
async initialSyncFs() {}
|
|
42
|
+
async closeFs() {}
|
|
43
|
+
async cleanupFailedInit() {
|
|
44
|
+
await this.closeFs();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export { ERRNO_CODES2, BaseFilesystem2 };
|
|
49
|
+
|
|
50
|
+
//# debugId=A14DDD1F35E244A664756E2164756E21
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/fs/base-filesystem.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\n/** Stat results, in the shape a POSIX `stat` returns them. Times are milliseconds since the epoch. */\nexport interface FsStats {\n dev: number;\n ino: number;\n mode: number;\n nlink: number;\n uid: number;\n gid: number;\n rdev: number;\n size: number;\n blksize: number;\n blocks: number;\n atime: number;\n mtime: number;\n ctime: number;\n}\n\n/**\n * Errno values, in the numbering Postgres builds use (Emscripten's). A filesystem reports a failed\n * operation by throwing an error whose `code` is one of these; an error without a `code` is reported to\n * Postgres as `EIO`.\n */\nexport const ERRNO_CODES = {\n EBADF: 8,\n EBADFD: 127,\n EEXIST: 20,\n EINVAL: 28,\n EIO: 29,\n EISDIR: 31,\n ENODEV: 43,\n ENOENT: 44,\n ENOTDIR: 54,\n ENOTEMPTY: 55,\n} as const;\n\n/**\n * A filesystem call that failed and was reported to Postgres as an errno. Kept in a small ring so\n * that when Postgres later fails, the storage failures underneath it are visible.\n */\nexport interface SyscallError {\n readonly op: string;\n readonly path: string;\n readonly errno: number;\n readonly message: string;\n readonly timeMs: number;\n}\n\nconst MAX_SYSCALL_ERRORS = 50;\n\n/**\n * What a filesystem says about itself, reported in `pg.storage` as `{ kind: \"vfs\", ...description }`:\n * a short name for diagnostics, and whether what it holds survives the process (or the page) that wrote it.\n */\nexport interface FilesystemDescription {\n /** A short name for diagnostics, e.g. `opfs-repacked`. */\n readonly name: string;\n /**\n * Whether the data directory outlives the process (or page) that wrote it. Absent when the filesystem\n * doesn't say: nothing outside it can tell, so callers treat an undeclared filesystem as the author's\n * own call rather than as non-persistent.\n */\n readonly persistent?: boolean;\n}\n\nconst DEFAULT_DESCRIPTION: FilesystemDescription = Object.freeze({ name: \"custom\" });\n\n/**\n * A synchronous virtual filesystem that holds a data directory, mounted by a Postgres build in place\n * of its built-in storage (pass it as `createPgwasm({ fs })`). Paths are absolute within the\n * filesystem, `/`-separated, `/` being the data directory itself.\n *\n * Besides the POSIX-shaped operations, a filesystem takes part in durability: pgwasm calls\n * `syncToFs(relaxed)` after statements (see `createPgwasm`'s `relaxedDurability`), the build calls\n * `initialSyncFs()` once when it mounts the filesystem, `closeFs()` when the database closes and\n * `cleanupFailedInit()` when a boot fails after the filesystem was handed over.\n */\nexport abstract class BaseFilesystem {\n readonly debug: boolean;\n readonly #recentSyscallErrors: SyscallError[] = [];\n\n constructor({ debug = false }: { debug?: boolean } = {}) {\n this.debug = debug;\n }\n\n /**\n * What this filesystem is, as `pg.storage` reports it. Defaults to `{ name: \"custom\" }`, persistence\n * undeclared: a filesystem overrides it to name itself and to say whether its data outlives the process\n * (`persistent: true`) or not (`persistent: false`), since nothing else can tell.\n */\n get description(): FilesystemDescription {\n return DEFAULT_DESCRIPTION;\n }\n\n /** The most recent failed filesystem calls reported to Postgres (up to 50), oldest first. */\n get recentSyscallErrors(): readonly SyscallError[] {\n return this.#recentSyscallErrors;\n }\n\n /** Record a failed call. The build's mount calls this where it turns a thrown error into an errno. */\n recordSyscallError(op: string, path: string, errno: number, message: string): void {\n const buffer = this.#recentSyscallErrors;\n buffer.push({ op, path, errno, message, timeMs: Date.now() });\n if (buffer.length > MAX_SYSCALL_ERRORS) {\n buffer.shift();\n }\n if (this.debug) {\n console.warn(\"[pgwasm-fs] syscall error\", op, path, errno, message);\n }\n }\n\n /** Make everything written so far durable. `relaxed` is pgwasm's background persist. */\n async syncToFs(_relaxed?: boolean): Promise<void> {}\n\n /** Called once when the build mounts the filesystem, before anything reads it. */\n async initialSyncFs(): Promise<void> {}\n\n /** Release everything the filesystem holds. Called when the database closes. */\n async closeFs(): Promise<void> {}\n\n /** Release what the filesystem holds after a boot failed. Defaults to {@link closeFs}. */\n async cleanupFailedInit(): Promise<void> {\n await this.closeFs();\n }\n\n abstract chmod(path: string, mode: number): void;\n abstract close(fd: number): void;\n abstract fstat(fd: number): FsStats;\n abstract lstat(path: string): FsStats;\n abstract mkdir(path: string, options?: { recursive?: boolean; mode?: number }): void;\n abstract open(path: string, flags?: string, mode?: number): number;\n abstract readdir(path: string): string[];\n /** Read into `buffer[offset, offset + length)` from `position`; returns the bytes read. */\n abstract read(fd: number, buffer: Uint8Array, offset: number, length: number, position: number): number;\n abstract rename(oldPath: string, newPath: string): void;\n abstract rmdir(path: string): void;\n abstract truncate(path: string, length: number): void;\n abstract unlink(path: string): void;\n abstract utimes(path: string, atime: number, mtime: number): void;\n abstract writeFile(\n path: string,\n data: string | Uint8Array,\n options?: { encoding?: string; mode?: number; flag?: string },\n ): void;\n /** Write `buffer[offset, offset + length)` at `position`; returns the bytes written. */\n abstract write(fd: number, buffer: Uint8Array, offset: number, length: number, position: number): number;\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";;AAyBO,IAAM,eAAc;AAAA,EACzB,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,WAAW;AACb;AAcA,IAAM,qBAAqB;AAiB3B,IAAM,sBAA6C,OAAO,OAAO,EAAE,MAAM,SAAS,CAAC;AAAA;AAY5E,MAAe,gBAAe;AAAA,EAC1B;AAAA,EACA,uBAAuC,CAAC;AAAA,EAEjD,WAAW,GAAG,QAAQ,UAA+B,CAAC,GAAG;AAAA,IACvD,KAAK,QAAQ;AAAA;AAAA,MAQX,WAAW,GAA0B;AAAA,IACvC,OAAO;AAAA;AAAA,MAIL,mBAAmB,GAA4B;AAAA,IACjD,OAAO,KAAK;AAAA;AAAA,EAId,kBAAkB,CAAC,IAAY,MAAc,OAAe,SAAuB;AAAA,IACjF,MAAM,SAAS,KAAK;AAAA,IACpB,OAAO,KAAK,EAAE,IAAI,MAAM,OAAO,SAAS,QAAQ,KAAK,IAAI,EAAE,CAAC;AAAA,IAC5D,IAAI,OAAO,SAAS,oBAAoB;AAAA,MACtC,OAAO,MAAM;AAAA,IACf;AAAA,IACA,IAAI,KAAK,OAAO;AAAA,MACd,QAAQ,KAAK,6BAA6B,IAAI,MAAM,OAAO,OAAO;AAAA,IACpE;AAAA;AAAA,OAII,SAAQ,CAAC,UAAmC;AAAA,OAG5C,cAAa,GAAkB;AAAA,OAG/B,QAAO,GAAkB;AAAA,OAGzB,kBAAiB,GAAkB;AAAA,IACvC,MAAM,KAAK,QAAQ;AAAA;AAwBvB;",
|
|
8
|
+
"debugId": "A14DDD1F35E244A664756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Store backups: a data directory as a tarball (ADR-0035). pgwasm owns the format so every build
|
|
3
|
+
* produces the same artefact: ustar, entry names relative to the data directory with a leading `/`,
|
|
4
|
+
* a directory before its contents, optionally gzipped. Backups written by earlier releases restore.
|
|
5
|
+
*/
|
|
6
|
+
import type { DataDirEntry } from "../build/seam";
|
|
7
|
+
import type { DumpCompression } from "../interface";
|
|
8
|
+
/**
|
|
9
|
+
* Normalize a backup member's name to a data-directory path: a leading `/`, no trailing `/`, no empty,
|
|
10
|
+
* `.` or `..` segments. A name that would leave the data directory is refused.
|
|
11
|
+
*/
|
|
12
|
+
export declare function normalizeDataDirPath(name: string): string;
|
|
13
|
+
/** Read a Store backup (gzipped or not, whatever its MIME type or name says) into entries. */
|
|
14
|
+
export declare function readDataDirArchive(archive: Blob): Promise<DataDirEntry[]>;
|
|
15
|
+
/** Write entries as a Store backup `File`, named `<baseName>.tar` or `<baseName>.tar.gz`. */
|
|
16
|
+
export declare function writeDataDirArchive(entries: readonly DataDirEntry[], baseName: string, compression?: DumpCompression): Promise<File>;
|
|
17
|
+
//# sourceMappingURL=data-dir-archive.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"data-dir-archive.d.ts","sourceRoot":"","sources":["../../src/core/data-dir-archive.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAIpD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAMzD;AAED,8FAA8F;AAC9F,wBAAsB,kBAAkB,CAAC,OAAO,EAAE,IAAI,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,CAkB/E;AAED,6FAA6F;AAC7F,wBAAsB,mBAAmB,CACvC,OAAO,EAAE,SAAS,YAAY,EAAE,EAChC,QAAQ,EAAE,MAAM,EAChB,WAAW,GAAE,eAAwB,GACpC,OAAO,CAAC,IAAI,CAAC,CAcf"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire-level access to a pgwasm instance, kept off its public type. `@pgxsinkit/pgwasm/protocol` and the
|
|
3
|
+
* `live` extension reach it through this registry; pgwasm is bundled with code splitting, so every
|
|
4
|
+
* entry point shares this one module and its map.
|
|
5
|
+
*/
|
|
6
|
+
import type { BuildCapabilities } from "../build/seam";
|
|
7
|
+
import type { BackendMessage, NoticeMessage } from "../protocol/wire/messages";
|
|
8
|
+
export interface ExecProtocolOptions {
|
|
9
|
+
/** Persist storage after the message, as a statement does. Defaults to `true`. */
|
|
10
|
+
readonly persist?: boolean;
|
|
11
|
+
/** Throw the first ErrorResponse. Defaults to `true`. */
|
|
12
|
+
readonly throwOnError?: boolean;
|
|
13
|
+
readonly onNotice?: (notice: NoticeMessage) => void;
|
|
14
|
+
}
|
|
15
|
+
export interface ExecProtocolStreamOptions {
|
|
16
|
+
/** Persist storage after the message. Defaults to `true`. */
|
|
17
|
+
readonly persist?: boolean;
|
|
18
|
+
/** Every backend byte, as it arrives. A chunk is only valid during the call: copy it to keep it. */
|
|
19
|
+
readonly onRawData: (data: Uint8Array) => void;
|
|
20
|
+
}
|
|
21
|
+
export interface ExecProtocolResult {
|
|
22
|
+
readonly messages: BackendMessage[];
|
|
23
|
+
readonly data: Uint8Array;
|
|
24
|
+
}
|
|
25
|
+
/** What `protocol(pg)` returns. */
|
|
26
|
+
export interface PgwasmProtocol {
|
|
27
|
+
/** Run frontend message bytes; the parsed backend messages and the raw reply. */
|
|
28
|
+
execProtocol(message: Uint8Array, options?: ExecProtocolOptions): Promise<ExecProtocolResult>;
|
|
29
|
+
/** Run frontend message bytes; the parsed backend messages only. */
|
|
30
|
+
execProtocolStream(message: Uint8Array, options?: ExecProtocolOptions): Promise<BackendMessage[]>;
|
|
31
|
+
/** Run frontend message bytes; the raw reply. Notifications and errors are still dispatched. */
|
|
32
|
+
execProtocolRaw(message: Uint8Array, options?: Pick<ExecProtocolOptions, "persist">): Promise<Uint8Array>;
|
|
33
|
+
/**
|
|
34
|
+
* Run frontend message bytes and stream the raw reply. When nothing is pending and the build has
|
|
35
|
+
* `synchronousExchange`, the whole reply is delivered before this call returns its promise — what a
|
|
36
|
+
* tool driving it from inside a blocking wasm callback (pg_dump) needs.
|
|
37
|
+
*/
|
|
38
|
+
execProtocolRawStream(message: Uint8Array, options: ExecProtocolStreamOptions): Promise<void>;
|
|
39
|
+
/**
|
|
40
|
+
* Run `fn` with the database's session to itself, for a tool whose exchanges must not interleave with
|
|
41
|
+
* anything else (pg_dump). It waits for, then holds, the locks a `transaction()` holds, and the query
|
|
42
|
+
* lock: no query, exec, transaction, listen, live-query refresh or Store backup of this database runs
|
|
43
|
+
* until `fn` settles.
|
|
44
|
+
*
|
|
45
|
+
* What `fn` sends with the `execProtocol*` methods is its own responsibility: no transaction is begun
|
|
46
|
+
* or ended around it, and a message is persisted only as its options say. Inside `fn`, use only these
|
|
47
|
+
* wire methods: the database's query methods wait for the locks `fn` holds, so awaiting one deadlocks.
|
|
48
|
+
*/
|
|
49
|
+
runExclusiveSession<T>(fn: () => Promise<T>): Promise<T>;
|
|
50
|
+
/** The build's capabilities, e.g. to check `synchronousExchange` before relying on it. */
|
|
51
|
+
readonly capabilities: BuildCapabilities;
|
|
52
|
+
}
|
|
53
|
+
export declare function registerProtocolAccess(pg: object, access: PgwasmProtocol): void;
|
|
54
|
+
/** The wire-level access of a pgwasm instance. Throws for anything else. */
|
|
55
|
+
export declare function protocolAccessOf(pg: object): PgwasmProtocol;
|
|
56
|
+
export declare function registerStrictSync(pg: object, strictSync: () => void): void;
|
|
57
|
+
/** The registered strict sync of `pg`, or `undefined` when it has none (not an OPFS-repacked store). */
|
|
58
|
+
export declare function strictSyncOf(pg: object): (() => void) | undefined;
|
|
59
|
+
//# sourceMappingURL=internals.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"internals.d.ts","sourceRoot":"","sources":["../../src/core/internals.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAE/E,MAAM,WAAW,mBAAmB;IAClC,kFAAkF;IAClF,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAC3B,yDAAyD;IACzD,QAAQ,CAAC,YAAY,CAAC,EAAE,OAAO,CAAC;IAChC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,aAAa,KAAK,IAAI,CAAC;CACrD;AAED,MAAM,WAAW,yBAAyB;IACxC,6DAA6D;IAC7D,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAC3B,oGAAoG;IACpG,QAAQ,CAAC,SAAS,EAAE,CAAC,IAAI,EAAE,UAAU,KAAK,IAAI,CAAC;CAChD;AAED,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,QAAQ,EAAE,cAAc,EAAE,CAAC;IACpC,QAA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ADR-0063 decision 1, build permanence).
|
|
3
|
+
*
|
|
4
|
+
* pgwasm records the Postgres build in every data directory it creates, as the file `PGWASM_BUILD` in
|
|
5
|
+
* the data directory itself (next to `PG_VERSION`), so it works on every storage and travels inside
|
|
6
|
+
* every Store backup. Its content is one line of JSON:
|
|
7
|
+
*
|
|
8
|
+
* {"pgwasm":1,"build":"c","dataFormat":1}
|
|
9
|
+
*
|
|
10
|
+
* `pgwasm` is the marker's own format version; a newer one than this release knows is unreadable
|
|
11
|
+
* (fail closed). A directory without a marker predates marking: it is the C build's, which the build
|
|
12
|
+
* says through `claimsUnmarkedDirectories` rather than shared code naming a build. Existing unmarked
|
|
13
|
+
* directories are never backfilled; only a directory pgwasm creates gets a marker.
|
|
14
|
+
*/
|
|
15
|
+
import type { BuildIdentity, DataDirEntry } from "../build/seam";
|
|
16
|
+
/** The marker's path inside the data directory. */
|
|
17
|
+
export declare const BUILD_MARKER_PATH = "/PGWASM_BUILD";
|
|
18
|
+
/** Postgres' own version file: its presence means the directory holds a cluster. */
|
|
19
|
+
export declare const PG_VERSION_PATH = "/PG_VERSION";
|
|
20
|
+
/** The marker's bytes for a build. */
|
|
21
|
+
export declare function encodeBuildMarker(build: BuildIdentity): Uint8Array;
|
|
22
|
+
/** Parse a marker; throws {@link BuildMarkerUnreadableError} for anything but a valid one. */
|
|
23
|
+
export declare function decodeBuildMarker(bytes: Uint8Array): {
|
|
24
|
+
build: string;
|
|
25
|
+
dataFormat: number;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Check what a data directory or backup records against the build about to open it. `marker` is the
|
|
29
|
+
* marker's bytes (absent when there is none); `hasCluster` is whether `PG_VERSION` exists. Throws the
|
|
30
|
+
* typed refusal when the build may not open it.
|
|
31
|
+
*/
|
|
32
|
+
export declare function checkBuildMarker(build: BuildIdentity, marker: Uint8Array | undefined, hasCluster: boolean, source: "data-directory" | "backup"): void;
|
|
33
|
+
/** The marker entry of a data-directory image, if it has one. */
|
|
34
|
+
export declare function findEntry(entries: readonly DataDirEntry[], path: string): DataDirEntry | undefined;
|
|
35
|
+
//# sourceMappingURL=marker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"marker.d.ts","sourceRoot":"","sources":["../../src/core/marker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAGjE,mDAAmD;AACnD,eAAO,MAAM,iBAAiB,kBAAkB,CAAC;AACjD,oFAAoF;AACpF,eAAO,MAAM,eAAe,gBAAgB,CAAC;AAO7C,sCAAsC;AACtC,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,aAAa,GAAG,UAAU,CAIlE;AAED,8FAA8F;AAC9F,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,UAAU,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAyB1F;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,aAAa,EACpB,MAAM,EAAE,UAAU,GAAG,SAAS,EAC9B,UAAU,EAAE,OAAO,EACnB,MAAM,EAAE,gBAAgB,GAAG,QAAQ,GAClC,IAAI,CAeN;AAED,iEAAiE;AACjE,wBAAgB,SAAS,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS,CAElG"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A FIFO async mutex: `runExclusive` runs its callback once every earlier one has settled. Not
|
|
3
|
+
* re-entrant — a callback that waits on the same mutex deadlocks, as with any mutex.
|
|
4
|
+
*/
|
|
5
|
+
export declare class Mutex {
|
|
6
|
+
#private;
|
|
7
|
+
runExclusive<T>(fn: () => Promise<T> | T): Promise<T>;
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=mutex.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mutex.d.ts","sourceRoot":"","sources":["../../src/core/mutex.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,qBAAa,KAAK;;IAGhB,YAAY,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAOpD;CACF"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The name Postgres stores for an identifier: a quoted one keeps its case (quotes removed), an
|
|
3
|
+
* unquoted one is folded to lower case. Used to key notification listeners the way Postgres names
|
|
4
|
+
* the channel.
|
|
5
|
+
*/
|
|
6
|
+
export declare function toPostgresName(input: string): string;
|
|
7
|
+
/** Quote an identifier for SQL: wrap in double quotes, doubling any inside. */
|
|
8
|
+
export declare function quoteIdentifier(name: string): string;
|
|
9
|
+
/** A random 32-character hex id, for the names of temporary objects. */
|
|
10
|
+
export declare function randomId(): string;
|
|
11
|
+
//# sourceMappingURL=names.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"names.d.ts","sourceRoot":"","sources":["../../src/core/names.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAKpD;AAED,+EAA+E;AAC/E,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEpD;AAED,wEAAwE;AACxE,wBAAgB,QAAQ,IAAI,MAAM,CAIjC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { QueryOptions, Results } from "../interface";
|
|
2
|
+
import { type BackendMessage } from "../protocol/wire/messages";
|
|
3
|
+
import { type Parser } from "../types";
|
|
4
|
+
/**
|
|
5
|
+
* Turn the backend messages of a simple or extended query into result sets, one per statement
|
|
6
|
+
* (https://www.postgresql.org/docs/current/protocol-flow.html).
|
|
7
|
+
*/
|
|
8
|
+
export declare function parseResults(messages: readonly BackendMessage[], defaultParsers: Readonly<Record<number | string, Parser>>, options?: QueryOptions, blob?: Blob): Results<unknown>[];
|
|
9
|
+
/** The parameter type OIDs from a Describe(statement) reply, when it has them. */
|
|
10
|
+
export declare function parseDescribeStatementResults(messages: readonly BackendMessage[]): number[];
|
|
11
|
+
//# sourceMappingURL=parse.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parse.d.ts","sourceRoot":"","sources":["../../src/core/parse.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAO,MAAM,cAAc,CAAC;AAC/D,OAAO,EAKL,KAAK,cAAc,EACpB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAa,KAAK,MAAM,EAAE,MAAM,UAAU,CAAC;AAElD;;;GAGG;AACH,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,SAAS,cAAc,EAAE,EACnC,cAAc,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,GAAG,MAAM,EAAE,MAAM,CAAC,CAAC,EACzD,OAAO,CAAC,EAAE,YAAY,EACtB,IAAI,CAAC,EAAE,IAAI,GACV,OAAO,CAAC,OAAO,CAAC,EAAE,CAgDpB;AAED,kFAAkF;AAClF,wBAAgB,6BAA6B,CAAC,QAAQ,EAAE,SAAS,cAAc,EAAE,GAAG,MAAM,EAAE,CAK3F"}
|