@effect/sql-pglite 4.0.0-beta.100

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-present The Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # `@effect/sql-pglite`
2
+
3
+ An Effect SQL implementation using the `@electric-sql/pglite` library.
4
+
5
+ ## Documentation
6
+
7
+ - **API Reference**: [View the full documentation](https://effect-ts.github.io/effect/docs/sql-pglite).
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Connects Effect SQL to PGlite, the embedded PostgreSQL-compatible database
3
+ * from `@electric-sql/pglite`.
4
+ *
5
+ * This module can create a managed PGlite instance or wrap an existing one and
6
+ * expose it as both `PgliteClient` and the generic Effect SQL client. The client
7
+ * runs PostgreSQL-style SQL, adds helpers for JSON values and LISTEN/NOTIFY
8
+ * messages, can dump the PGlite data directory, and can refresh PGlite array
9
+ * types. It also provides layers and maps common PostgreSQL-style failures into
10
+ * Effect SQL errors.
11
+ *
12
+ * @since 4.0.0
13
+ */
14
+ import { type PGliteInterface, type PGliteOptions } from "@electric-sql/pglite";
15
+ import * as Config from "effect/Config";
16
+ import * as Context from "effect/Context";
17
+ import * as Effect from "effect/Effect";
18
+ import * as Layer from "effect/Layer";
19
+ import * as Scope from "effect/Scope";
20
+ import * as Stream from "effect/Stream";
21
+ import * as Reactivity from "effect/unstable/reactivity/Reactivity";
22
+ import * as Client from "effect/unstable/sql/SqlClient";
23
+ import { SqlError } from "effect/unstable/sql/SqlError";
24
+ import type { Custom, Fragment } from "effect/unstable/sql/Statement";
25
+ import * as Statement from "effect/unstable/sql/Statement";
26
+ /**
27
+ * Runtime type identifier used to mark `PgliteClient` values.
28
+ *
29
+ * @category type IDs
30
+ * @since 4.0.0
31
+ */
32
+ export declare const TypeId: TypeId;
33
+ /**
34
+ * Type-level identifier used to mark `PgliteClient` values.
35
+ *
36
+ * @category type IDs
37
+ * @since 4.0.0
38
+ */
39
+ export type TypeId = "~@effect/sql-pglite/PgliteClient";
40
+ /**
41
+ * PGlite-backed PostgreSQL client service, extending `SqlClient` with access to the PGlite instance, JSON fragments, LISTEN/NOTIFY, data directory dumps, and array type refresh.
42
+ *
43
+ * @category models
44
+ * @since 4.0.0
45
+ */
46
+ export interface PgliteClient extends Client.SqlClient {
47
+ readonly [TypeId]: TypeId;
48
+ readonly config: PgliteClientConfig;
49
+ readonly pglite: PGliteInterface;
50
+ readonly json: (_: unknown) => Fragment;
51
+ readonly listen: (channel: string) => Stream.Stream<string, SqlError>;
52
+ readonly notify: (channel: string, payload: string) => Effect.Effect<void, SqlError>;
53
+ readonly dumpDataDir: (compression?: "none" | "gzip" | "auto") => Effect.Effect<File | Blob, SqlError>;
54
+ readonly refreshArrayTypes: Effect.Effect<void, SqlError>;
55
+ }
56
+ /**
57
+ * Service tag for the PGlite client service.
58
+ *
59
+ * **When to use**
60
+ *
61
+ * Use to access or provide a PGlite client through the Effect context.
62
+ *
63
+ * @category services
64
+ * @since 4.0.0
65
+ */
66
+ export declare const PgliteClient: Context.Service<PgliteClient, PgliteClient>;
67
+ /**
68
+ * Configuration for a PGlite client, either by supplying PGlite creation options or an existing live PGlite client.
69
+ *
70
+ * @category models
71
+ * @since 4.0.0
72
+ */
73
+ export type PgliteClientConfig = PgliteClientConfig.Create | PgliteClientConfig.Live;
74
+ /**
75
+ * Namespace containing the configuration variants for `PgliteClient`.
76
+ *
77
+ * @since 4.0.0
78
+ */
79
+ export declare namespace PgliteClientConfig {
80
+ /**
81
+ * Shared PGlite client options for span attributes, query/result name transformations, and JSON value transformation.
82
+ *
83
+ * @category models
84
+ * @since 4.0.0
85
+ */
86
+ interface Base {
87
+ readonly spanAttributes?: Record<string, unknown> | undefined;
88
+ readonly transformResultNames?: ((str: string) => string) | undefined;
89
+ readonly transformQueryNames?: ((str: string) => string) | undefined;
90
+ readonly transformJson?: boolean | undefined;
91
+ }
92
+ /**
93
+ * Configuration used to create a managed PGlite instance from PGlite constructor options.
94
+ *
95
+ * @category models
96
+ * @since 4.0.0
97
+ */
98
+ interface Create extends Base, PGliteOptions {
99
+ }
100
+ /**
101
+ * Configuration that uses an existing PGlite client. The supplied `liveClient` is caller-owned and is not closed by the Effect client.
102
+ *
103
+ * @category models
104
+ * @since 4.0.0
105
+ */
106
+ interface Live extends Base {
107
+ readonly liveClient: PGliteInterface;
108
+ }
109
+ /**
110
+ * Config-friendly subset of PGlite creation options, including data directory, username, database, relaxed durability, and shared transform options.
111
+ *
112
+ * @category models
113
+ * @since 4.0.0
114
+ */
115
+ interface ConfigBase extends Base {
116
+ readonly dataDir?: string | undefined;
117
+ readonly username?: string | undefined;
118
+ readonly database?: string | undefined;
119
+ readonly relaxedDurability?: boolean | undefined;
120
+ }
121
+ }
122
+ /**
123
+ * Creates a scoped PGlite SQL client. When no live client is supplied it creates and closes a PGlite instance; when `liveClient` is supplied, the caller retains ownership.
124
+ *
125
+ * @category constructors
126
+ * @since 4.0.0
127
+ */
128
+ export declare const make: (options?: PgliteClientConfig) => Effect.Effect<PgliteClient, SqlError, Scope.Scope | Reactivity.Reactivity>;
129
+ /**
130
+ * Builds a `PgliteClient` around an existing PGlite instance, adding SQL client operations, LISTEN/NOTIFY, dump helpers, and serialized access.
131
+ *
132
+ * @category constructors
133
+ * @since 4.0.0
134
+ */
135
+ export declare const fromClient: (options: PgliteClientConfig.Base & {
136
+ readonly liveClient: PGliteInterface;
137
+ }) => Effect.Effect<PgliteClient, SqlError, Scope.Scope | Reactivity.Reactivity>;
138
+ /**
139
+ * Creates a layer from an effect that acquires a `PgliteClient`, providing both `PgliteClient` and `SqlClient`.
140
+ *
141
+ * @category layers
142
+ * @since 4.0.0
143
+ */
144
+ export declare const layerFrom: <E, R>(acquire: Effect.Effect<PgliteClient, E, R>) => Layer.Layer<PgliteClient | Client.SqlClient, E, Exclude<R, Scope.Scope | Reactivity.Reactivity>>;
145
+ /**
146
+ * Creates a layer from a `Config`-wrapped PGlite client configuration, providing both `PgliteClient` and `SqlClient`.
147
+ *
148
+ * @category layers
149
+ * @since 4.0.0
150
+ */
151
+ export declare const layerConfig: (config: Config.Wrap<PgliteClientConfig.ConfigBase>) => Layer.Layer<PgliteClient | Client.SqlClient, Config.ConfigError | SqlError>;
152
+ /**
153
+ * Creates a layer from a concrete PGlite client configuration, providing both `PgliteClient` and `SqlClient`.
154
+ *
155
+ * @category layers
156
+ * @since 4.0.0
157
+ */
158
+ export declare const layer: (config?: PgliteClientConfig | undefined) => Layer.Layer<PgliteClient | Client.SqlClient, SqlError>;
159
+ /**
160
+ * Creates the PGlite statement compiler, using PostgreSQL `$1` placeholders, double-quoted identifiers, returning clauses, and optional JSON value transformation.
161
+ *
162
+ * @category constructors
163
+ * @since 4.0.0
164
+ */
165
+ export declare const makeCompiler: (transform?: (_: string) => string, transformJson?: boolean) => Statement.Compiler;
166
+ /**
167
+ * PGlite-specific custom statement fragments supported by the compiler, currently JSON parameter fragments.
168
+ *
169
+ * @category custom types
170
+ * @since 4.0.0
171
+ */
172
+ export type PgCustom = PgJson;
173
+ /**
174
+ * @category custom types
175
+ * @since 4.0.0
176
+ */
177
+ interface PgJson extends Custom<"PgJson", unknown> {
178
+ }
179
+ declare const PgJson: (paramA: unknown, paramB: void, paramC: void) => PgJson;
180
+ export {};
181
+ //# sourceMappingURL=PgliteClient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PgliteClient.d.ts","sourceRoot":"","sources":["../src/PgliteClient.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAU,KAAK,eAAe,EAAE,KAAK,aAAa,EAAE,MAAM,sBAAsB,CAAA;AACvF,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAA;AACzC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAEvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AAErC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AAErC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,UAAU,MAAM,uCAAuC,CAAA;AACnE,OAAO,KAAK,MAAM,MAAM,+BAA+B,CAAA;AAEvD,OAAO,EAQL,QAAQ,EAKT,MAAM,8BAA8B,CAAA;AACrC,OAAO,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAA;AACrE,OAAO,KAAK,SAAS,MAAM,+BAA+B,CAAA;AAE1D;;;;;GAKG;AACH,eAAO,MAAM,MAAM,EAAE,MAA2C,CAAA;AAEhE;;;;;GAKG;AACH,MAAM,MAAM,MAAM,GAAG,kCAAkC,CAAA;AAEvD;;;;;GAKG;AACH,MAAM,WAAW,YAAa,SAAQ,MAAM,CAAC,SAAS;IACpD,QAAQ,CAAC,CAAC,MAA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,CAAC,UAAU,CAAC,CAMlD,CAAA;AAEhD;;;;;GAKG;AACH,eAAO,MAAM,WAAW,EAAE,CACxB,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,UAAU,CAAC,KAC/C,KAAK,CAAC,KAAK,CAAC,YAAY,GAAG,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC,WAAW,GAAG,QAAQ,CAM3E,CAAA;AAEJ;;;;;GAKG;AACH,eAAO,MAAM,KAAK,YACP,kBAAkB,GAAG,SAAS,KACtC,KAAK,CAAC,KAAK,CAAC,YAAY,GAAG,MAAM,CAAC,SAAS,EAAE,QAAQ,CAA4B,CAAA;AAEpF;;;;;GAKG;AACH,eAAO,MAAM,YAAY,eACX,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,8BAEhC,SAAS,CAAC,QAsCZ,CAAA;AAKD;;;;;GAKG;AACH,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAA;AAE7B;;;GAGG;AACH,UAAU,MAAO,SAAQ,MAAM,CAAC,QAAQ,EAAE,OAAO,CAAC;CAAG;AACrD,QAAA,MAAM,MAAM,yDAAqC,CAAA"}
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Connects Effect SQL to PGlite, the embedded PostgreSQL-compatible database
3
+ * from `@electric-sql/pglite`.
4
+ *
5
+ * This module can create a managed PGlite instance or wrap an existing one and
6
+ * expose it as both `PgliteClient` and the generic Effect SQL client. The client
7
+ * runs PostgreSQL-style SQL, adds helpers for JSON values and LISTEN/NOTIFY
8
+ * messages, can dump the PGlite data directory, and can refresh PGlite array
9
+ * types. It also provides layers and maps common PostgreSQL-style failures into
10
+ * Effect SQL errors.
11
+ *
12
+ * @since 4.0.0
13
+ */
14
+ import { PGlite } from "@electric-sql/pglite";
15
+ import * as Config from "effect/Config";
16
+ import * as Context from "effect/Context";
17
+ import * as Effect from "effect/Effect";
18
+ import * as Fiber from "effect/Fiber";
19
+ import * as Layer from "effect/Layer";
20
+ import * as Queue from "effect/Queue";
21
+ import * as Scope from "effect/Scope";
22
+ import * as Semaphore from "effect/Semaphore";
23
+ import * as Stream from "effect/Stream";
24
+ import * as Reactivity from "effect/unstable/reactivity/Reactivity";
25
+ import * as Client from "effect/unstable/sql/SqlClient";
26
+ import { AuthenticationError, AuthorizationError, ConnectionError, ConstraintError, DeadlockError, LockTimeoutError, SerializationError, SqlError, SqlSyntaxError, StatementTimeoutError, UniqueViolation, UnknownError } from "effect/unstable/sql/SqlError";
27
+ import * as Statement from "effect/unstable/sql/Statement";
28
+ /**
29
+ * Runtime type identifier used to mark `PgliteClient` values.
30
+ *
31
+ * @category type IDs
32
+ * @since 4.0.0
33
+ */
34
+ export const TypeId = "~@effect/sql-pglite/PgliteClient";
35
+ /**
36
+ * Service tag for the PGlite client service.
37
+ *
38
+ * **When to use**
39
+ *
40
+ * Use to access or provide a PGlite client through the Effect context.
41
+ *
42
+ * @category services
43
+ * @since 4.0.0
44
+ */
45
+ export const PgliteClient = /*#__PURE__*/Context.Service("@effect/sql-pglite/PgliteClient");
46
+ /**
47
+ * Creates a scoped PGlite SQL client. When no live client is supplied it creates and closes a PGlite instance; when `liveClient` is supplied, the caller retains ownership.
48
+ *
49
+ * @category constructors
50
+ * @since 4.0.0
51
+ */
52
+ export const make = (options = {}) => Effect.gen(function* () {
53
+ const pglite = "liveClient" in options ? options.liveClient : yield* Effect.acquireRelease(Effect.tryPromise({
54
+ try: async () => {
55
+ const pg = new PGlite(options);
56
+ await pg.waitReady;
57
+ return pg;
58
+ },
59
+ catch: cause => new SqlError({
60
+ reason: classifyError(cause, "PgliteClient: Failed to connect", "connect")
61
+ })
62
+ }), pg => Effect.promise(() => pg.close()).pipe(Effect.timeoutOption(1000)), {
63
+ interruptible: true
64
+ });
65
+ return yield* fromClient({
66
+ ...options,
67
+ liveClient: pglite
68
+ });
69
+ });
70
+ /**
71
+ * Builds a `PgliteClient` around an existing PGlite instance, adding SQL client operations, LISTEN/NOTIFY, dump helpers, and serialized access.
72
+ *
73
+ * @category constructors
74
+ * @since 4.0.0
75
+ */
76
+ export const fromClient = options => Effect.gen(function* () {
77
+ const pglite = options.liveClient;
78
+ const compiler = makeCompiler(options.transformQueryNames, options.transformJson);
79
+ const transformRows = options.transformResultNames ? Statement.defaultTransforms(options.transformResultNames, options.transformJson).array : undefined;
80
+ const spanAttributes = [...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), [ATTR_DB_SYSTEM_NAME, "postgresql"]];
81
+ const connection = new PgliteConnection(pglite);
82
+ const semaphore = Semaphore.makeUnsafe(1);
83
+ const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
84
+ const transactionAcquirer = Effect.uninterruptibleMask(restore => {
85
+ const fiber = Fiber.getCurrent();
86
+ const scope = Context.getUnsafe(fiber.context, Scope.Scope);
87
+ return Effect.as(Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))), connection);
88
+ });
89
+ const config = options;
90
+ const client = yield* Client.make({
91
+ acquirer,
92
+ compiler,
93
+ transactionAcquirer,
94
+ spanAttributes,
95
+ transformRows
96
+ });
97
+ return Object.assign(client, {
98
+ [TypeId]: TypeId,
99
+ config,
100
+ pglite,
101
+ json: _ => Statement.fragment([PgJson(_)]),
102
+ listen: channel => Stream.callback(queue => Effect.acquireRelease(Effect.tryPromise({
103
+ try: () => pglite.listen(channel, payload => {
104
+ Queue.offerUnsafe(queue, payload);
105
+ }),
106
+ catch: cause => new SqlError({
107
+ reason: classifyError(cause, "Failed to listen", "listen")
108
+ })
109
+ }), unlisten => Effect.promise(() => unlisten()), {
110
+ interruptible: true
111
+ })),
112
+ notify: (channel, payload) => Effect.tryPromise({
113
+ try: () => pglite.exec(`NOTIFY ${escape(channel)}, ${escapeLiteral(payload)}`),
114
+ catch: cause => new SqlError({
115
+ reason: classifyError(cause, "Failed to notify", "notify")
116
+ })
117
+ }).pipe(semaphore.withPermit, Effect.asVoid),
118
+ dumpDataDir: compression => semaphore.withPermit(Effect.tryPromise({
119
+ try: () => pglite.dumpDataDir(compression),
120
+ catch: cause => new SqlError({
121
+ reason: classifyError(cause, "Failed to dump data dir", "dumpDataDir")
122
+ })
123
+ })),
124
+ refreshArrayTypes: semaphore.withPermit(Effect.tryPromise({
125
+ try: () => pglite.refreshArrayTypes(),
126
+ catch: cause => new SqlError({
127
+ reason: classifyError(cause, "Failed to refresh array types", "refreshArrayTypes")
128
+ })
129
+ }))
130
+ });
131
+ });
132
+ class PgliteConnection {
133
+ pglite;
134
+ constructor(pglite) {
135
+ this.pglite = pglite;
136
+ }
137
+ run(method, sql, params) {
138
+ return Effect.map(Effect.tryPromise({
139
+ try: () => this.pglite.query(sql, params),
140
+ catch: cause => new SqlError({
141
+ reason: classifyError(cause, "Failed to execute statement", method)
142
+ })
143
+ }), result => result.rows);
144
+ }
145
+ execute(sql, params, transformRows) {
146
+ return transformRows ? Effect.map(this.run("execute", sql, params), transformRows) : this.run("execute", sql, params);
147
+ }
148
+ executeRaw(sql, params) {
149
+ return Effect.tryPromise({
150
+ try: () => this.pglite.query(sql, params),
151
+ catch: cause => new SqlError({
152
+ reason: classifyError(cause, "Failed to execute statement", "executeRaw")
153
+ })
154
+ });
155
+ }
156
+ executeValues(sql, params) {
157
+ return Effect.map(Effect.tryPromise({
158
+ try: () => this.pglite.query(sql, params, {
159
+ rowMode: "array"
160
+ }),
161
+ catch: cause => new SqlError({
162
+ reason: classifyError(cause, "Failed to execute statement", "executeValues")
163
+ })
164
+ }), result => result.rows);
165
+ }
166
+ executeValuesUnprepared(sql, params) {
167
+ return Effect.map(Effect.tryPromise({
168
+ try: () => this.pglite.query(sql, params, {
169
+ rowMode: "array"
170
+ }),
171
+ catch: cause => new SqlError({
172
+ reason: classifyError(cause, "Failed to execute statement", "executeValuesUnprepared")
173
+ })
174
+ }), result => result.rows);
175
+ }
176
+ executeUnprepared(sql, params, transformRows) {
177
+ return transformRows ? Effect.map(this.run("executeUnprepared", sql, params), transformRows) : this.run("executeUnprepared", sql, params);
178
+ }
179
+ executeStream(sql, params, transformRows) {
180
+ const eff = transformRows ? Effect.map(this.run("executeStream", sql, params), transformRows) : this.run("executeStream", sql, params);
181
+ return Stream.fromArrayEffect(eff);
182
+ }
183
+ }
184
+ /**
185
+ * Creates a layer from an effect that acquires a `PgliteClient`, providing both `PgliteClient` and `SqlClient`.
186
+ *
187
+ * @category layers
188
+ * @since 4.0.0
189
+ */
190
+ export const layerFrom = acquire => Layer.effectContext(Effect.map(acquire, client => Context.make(PgliteClient, client).pipe(Context.add(Client.SqlClient, client)))).pipe(Layer.provide(Reactivity.layer));
191
+ /**
192
+ * Creates a layer from a `Config`-wrapped PGlite client configuration, providing both `PgliteClient` and `SqlClient`.
193
+ *
194
+ * @category layers
195
+ * @since 4.0.0
196
+ */
197
+ export const layerConfig = config => layerFrom(Effect.flatMap(Config.unwrap(config), resolved => make(resolved)));
198
+ /**
199
+ * Creates a layer from a concrete PGlite client configuration, providing both `PgliteClient` and `SqlClient`.
200
+ *
201
+ * @category layers
202
+ * @since 4.0.0
203
+ */
204
+ export const layer = config => layerFrom(make(config));
205
+ /**
206
+ * Creates the PGlite statement compiler, using PostgreSQL `$1` placeholders, double-quoted identifiers, returning clauses, and optional JSON value transformation.
207
+ *
208
+ * @category constructors
209
+ * @since 4.0.0
210
+ */
211
+ export const makeCompiler = (transform, transformJson = true) => {
212
+ const transformValue = transformJson && transform ? Statement.defaultTransforms(transform).value : undefined;
213
+ return Statement.makeCompiler({
214
+ dialect: "pg",
215
+ placeholder(_) {
216
+ return `$${_}`;
217
+ },
218
+ onIdentifier: transform ? function (value, withoutTransform) {
219
+ return withoutTransform ? escape(value) : escape(transform(value));
220
+ } : escape,
221
+ onRecordUpdate(placeholders, valueAlias, valueColumns, values, returning) {
222
+ return [`(values ${placeholders}) AS ${valueAlias}${valueColumns}${returning ? ` RETURNING ${returning[0]}` : ""}`, returning ? values.flat().concat(returning[1]) : values.flat()];
223
+ },
224
+ onCustom(type, placeholder, withoutTransform) {
225
+ switch (type.kind) {
226
+ case "PgJson":
227
+ {
228
+ return [placeholder(undefined), [withoutTransform || transformValue === undefined ? type.paramA : transformValue(type.paramA)]];
229
+ }
230
+ }
231
+ }
232
+ });
233
+ };
234
+ const escape = /*#__PURE__*/Statement.defaultEscape("\"");
235
+ const escapeLiteral = value => `'${value.replace(/'/g, "''")}'`;
236
+ const PgJson = /*#__PURE__*/Statement.custom("PgJson");
237
+ const ATTR_DB_SYSTEM_NAME = "db.system.name";
238
+ const pgCodeFromCause = cause => {
239
+ if (typeof cause !== "object" || cause === null || !("code" in cause)) {
240
+ return undefined;
241
+ }
242
+ const code = cause.code;
243
+ return typeof code === "string" ? code : undefined;
244
+ };
245
+ const pgConstraintFromCause = cause => {
246
+ if (typeof cause !== "object" || cause === null || !("constraint" in cause)) {
247
+ return "unknown";
248
+ }
249
+ const constraint = cause.constraint;
250
+ if (typeof constraint !== "string") {
251
+ return "unknown";
252
+ }
253
+ const normalized = constraint.trim();
254
+ return normalized.length === 0 ? "unknown" : normalized;
255
+ };
256
+ const classifyError = (cause, message, operation) => {
257
+ const props = {
258
+ cause,
259
+ message,
260
+ operation
261
+ };
262
+ const code = pgCodeFromCause(cause);
263
+ if (code !== undefined) {
264
+ if (code.startsWith("08")) {
265
+ return new ConnectionError(props);
266
+ }
267
+ if (code.startsWith("28")) {
268
+ return new AuthenticationError(props);
269
+ }
270
+ if (code === "42501") {
271
+ return new AuthorizationError(props);
272
+ }
273
+ if (code.startsWith("42")) {
274
+ return new SqlSyntaxError(props);
275
+ }
276
+ if (code === "23505") {
277
+ return new UniqueViolation({
278
+ ...props,
279
+ constraint: pgConstraintFromCause(cause)
280
+ });
281
+ }
282
+ if (code.startsWith("23")) {
283
+ return new ConstraintError(props);
284
+ }
285
+ if (code === "40P01") {
286
+ return new DeadlockError(props);
287
+ }
288
+ if (code === "40001") {
289
+ return new SerializationError(props);
290
+ }
291
+ if (code === "55P03") {
292
+ return new LockTimeoutError(props);
293
+ }
294
+ if (code === "57014") {
295
+ return new StatementTimeoutError(props);
296
+ }
297
+ }
298
+ return new UnknownError(props);
299
+ };
300
+ //# sourceMappingURL=PgliteClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PgliteClient.js","names":["PGlite","Config","Context","Effect","Fiber","Layer","Queue","Scope","Semaphore","Stream","Reactivity","Client","AuthenticationError","AuthorizationError","ConnectionError","ConstraintError","DeadlockError","LockTimeoutError","SerializationError","SqlError","SqlSyntaxError","StatementTimeoutError","UniqueViolation","UnknownError","Statement","TypeId","PgliteClient","Service","make","options","gen","pglite","liveClient","acquireRelease","tryPromise","try","pg","waitReady","catch","cause","reason","classifyError","promise","close","pipe","timeoutOption","interruptible","fromClient","compiler","makeCompiler","transformQueryNames","transformJson","transformRows","transformResultNames","defaultTransforms","array","undefined","spanAttributes","Object","entries","ATTR_DB_SYSTEM_NAME","connection","PgliteConnection","semaphore","makeUnsafe","acquirer","withPermits","succeed","transactionAcquirer","uninterruptibleMask","restore","fiber","getCurrent","scope","getUnsafe","context","as","tap","take","addFinalizer","release","config","client","assign","json","_","fragment","PgJson","listen","channel","callback","queue","payload","offerUnsafe","unlisten","notify","exec","escape","escapeLiteral","withPermit","asVoid","dumpDataDir","compression","refreshArrayTypes","constructor","run","method","sql","params","map","query","result","rows","execute","executeRaw","executeValues","rowMode","executeValuesUnprepared","executeUnprepared","executeStream","eff","fromArrayEffect","layerFrom","acquire","effectContext","add","SqlClient","provide","layer","layerConfig","flatMap","unwrap","resolved","transform","transformValue","value","dialect","placeholder","onIdentifier","withoutTransform","onRecordUpdate","placeholders","valueAlias","valueColumns","values","returning","flat","concat","onCustom","type","kind","paramA","defaultEscape","replace","custom","pgCodeFromCause","code","pgConstraintFromCause","constraint","normalized","trim","length","message","operation","props","startsWith"],"sources":["../src/PgliteClient.ts"],"sourcesContent":[null],"mappings":"AAAA;;;;;;;;;;;;;AAaA,SAASA,MAAM,QAAkD,sBAAsB;AACvF,OAAO,KAAKC,MAAM,MAAM,eAAe;AACvC,OAAO,KAAKC,OAAO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,CAAC,EAAE;MACzB,OAAO,IAAIjJ,cAAc,CAACgJ,KAAK,CAAC;IAClC;IACA,IAAIR,IAAI,KAAK,OAAO,EAAE;MACpB,OAAO,IAAItI,eAAe,CAAC;QAAE,GAAG8I,KAAK;QAAEN,UAAU,EAAED,qBAAqB,CAACtH,KAAK;MAAC,CAAE,CAAC;IACpF;IACA,IAAIqH,IAAI,CAACS,UAAU,CAAC,IAAI,CAAC,EAAE;MACzB,OAAO,IAAItJ,eAAe,CAACqJ,KAAK,CAAC;IACnC;IACA,IAAIR,IAAI,KAAK,OAAO,EAAE;MACpB,OAAO,IAAI5I,aAAa,CAACoJ,KAAK,CAAC;IACjC;IACA,IAAIR,IAAI,KAAK,OAAO,EAAE;MACpB,OAAO,IAAI1I,kBAAkB,CAACkJ,KAAK,CAAC;IACtC;IACA,IAAIR,IAAI,KAAK,OAAO,EAAE;MACpB,OAAO,IAAI3I,gBAAgB,CAACmJ,KAAK,CAAC;IACpC;IACA,IAAIR,IAAI,KAAK,OAAO,EAAE;MACpB,OAAO,IAAIvI,qBAAqB,CAAC+I,KAAK,CAAC;IACzC;EACF;EACA,OAAO,IAAI7I,YAAY,CAAC6I,KAAK,CAAC;AAChC,CAAC","ignoreList":[]}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Runs database migrations for PGlite projects that use Effect SQL.
3
+ *
4
+ * This module re-exports the shared migration loaders and errors, then provides
5
+ * `run` and `layer` helpers that apply pending migration files with the current
6
+ * `SqlClient`. It does not require a separate PGlite service; the active SQL
7
+ * client supplies the database connection.
8
+ *
9
+ * @since 4.0.0
10
+ */
11
+ import type * as Effect from "effect/Effect";
12
+ import * as Layer from "effect/Layer";
13
+ import * as Migrator from "effect/unstable/sql/Migrator";
14
+ import type * as Client from "effect/unstable/sql/SqlClient";
15
+ import type { SqlError } from "effect/unstable/sql/SqlError";
16
+ /**
17
+ * @since 4.0.0
18
+ */
19
+ export * from "effect/unstable/sql/Migrator";
20
+ /**
21
+ * Runs SQL migrations using the configured `SqlClient`, returning the migrations that were applied.
22
+ *
23
+ * @category constructors
24
+ * @since 4.0.0
25
+ */
26
+ export declare const run: <R2 = never>(options: Migrator.MigratorOptions<R2>) => Effect.Effect<ReadonlyArray<readonly [id: number, name: string]>, Migrator.MigrationError | SqlError, Client.SqlClient | R2>;
27
+ /**
28
+ * Creates a layer that runs the configured SQL migrations during layer construction.
29
+ *
30
+ * @category constructors
31
+ * @since 4.0.0
32
+ */
33
+ export declare const layer: <R>(options: Migrator.MigratorOptions<R>) => Layer.Layer<never, Migrator.MigrationError | SqlError, Client.SqlClient | R>;
34
+ //# sourceMappingURL=PgliteMigrator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PgliteMigrator.d.ts","sourceRoot":"","sources":["../src/PgliteMigrator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,KAAK,KAAK,MAAM,MAAM,eAAe,CAAA;AAC5C,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,QAAQ,MAAM,8BAA8B,CAAA;AACxD,OAAO,KAAK,KAAK,MAAM,MAAM,+BAA+B,CAAA;AAC5D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAA;AAE5D;;GAEG;AACH,cAAc,8BAA8B,CAAA;AAE5C;;;;;GAKG;AACH,eAAO,MAAM,GAAG,EAAE,CAAC,EAAE,GAAG,KAAK,EAC3B,OAAO,EAAE,QAAQ,CAAC,eAAe,CAAC,EAAE,CAAC,KAClC,MAAM,CAAC,MAAM,CAChB,aAAa,CAAC,SAAS,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,EAClD,QAAQ,CAAC,cAAc,GAAG,QAAQ,EAClC,MAAM,CAAC,SAAS,GAAG,EAAE,CACF,CAAA;AAErB;;;;;GAKG;AACH,eAAO,MAAM,KAAK,GAAI,CAAC,WACZ,QAAQ,CAAC,eAAe,CAAC,CAAC,CAAC,KACnC,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,QAAQ,CAAC,cAAc,GAAG,QAAQ,EAAE,MAAM,CAAC,SAAS,GAAG,CAAC,CAAsC,CAAA"}
@@ -0,0 +1,21 @@
1
+ import * as Layer from "effect/Layer";
2
+ import * as Migrator from "effect/unstable/sql/Migrator";
3
+ /**
4
+ * @since 4.0.0
5
+ */
6
+ export * from "effect/unstable/sql/Migrator";
7
+ /**
8
+ * Runs SQL migrations using the configured `SqlClient`, returning the migrations that were applied.
9
+ *
10
+ * @category constructors
11
+ * @since 4.0.0
12
+ */
13
+ export const run = /*#__PURE__*/Migrator.make({});
14
+ /**
15
+ * Creates a layer that runs the configured SQL migrations during layer construction.
16
+ *
17
+ * @category constructors
18
+ * @since 4.0.0
19
+ */
20
+ export const layer = options => Layer.effectDiscard(run(options));
21
+ //# sourceMappingURL=PgliteMigrator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PgliteMigrator.js","names":["Layer","Migrator","run","make","layer","options","effectDiscard"],"sources":["../src/PgliteMigrator.ts"],"sourcesContent":[null],"mappings":"AAWA,OAAO,KAAKA,KAAK,MAAM,cAAc;AACrC,OAAO,KAAKC,QAAQ,MAAM,8BAA8B;AAIxD;;;AAGA,cAAc,8BAA8B;AAE5C;;;;;;AAMA,OAAO,MAAMC,GAAG,gBAMZD,QAAQ,CAACE,IAAI,CAAC,EAAE,CAAC;AAErB;;;;;;AAMA,OAAO,MAAMC,KAAK,GAChBC,OAAoC,IAC6CL,KAAK,CAACM,aAAa,CAACJ,GAAG,CAACG,OAAO,CAAC,CAAC","ignoreList":[]}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @since 4.0.0
3
+ */
4
+ /**
5
+ * @since 4.0.0
6
+ */
7
+ export * as PgliteClient from "./PgliteClient.ts";
8
+ /**
9
+ * @since 4.0.0
10
+ */
11
+ export * as PgliteMigrator from "./PgliteMigrator.ts";
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH;;GAEG;AACH,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAA;AAEjD;;GAEG;AACH,OAAO,KAAK,cAAc,MAAM,qBAAqB,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @since 4.0.0
3
+ */
4
+ // @barrel: Auto-generated exports. Do not edit manually.
5
+ /**
6
+ * @since 4.0.0
7
+ */
8
+ export * as PgliteClient from "./PgliteClient.js";
9
+ /**
10
+ * @since 4.0.0
11
+ */
12
+ export * as PgliteMigrator from "./PgliteMigrator.js";
13
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["PgliteClient","PgliteMigrator"],"sources":["../src/index.ts"],"sourcesContent":[null],"mappings":"AAAA;;;AAIA;AAEA;;;AAGA,OAAO,KAAKA,YAAY,MAAM,mBAAmB;AAEjD;;;AAGA,OAAO,KAAKC,cAAc,MAAM,qBAAqB","ignoreList":[]}
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@effect/sql-pglite",
3
+ "version": "4.0.0-beta.100",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "description": "A PGlite toolkit for Effect",
7
+ "homepage": "https://effect.website",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/Effect-TS/effect.git",
11
+ "directory": "packages/sql/pglite"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/Effect-TS/effect/issues"
15
+ },
16
+ "tags": [
17
+ "typescript",
18
+ "sql",
19
+ "pglite",
20
+ "postgres",
21
+ "database"
22
+ ],
23
+ "keywords": [
24
+ "typescript",
25
+ "sql",
26
+ "pglite",
27
+ "postgres",
28
+ "database"
29
+ ],
30
+ "sideEffects": [],
31
+ "exports": {
32
+ "./package.json": "./package.json",
33
+ ".": "./dist/index.js",
34
+ "./*": "./dist/*.js",
35
+ "./internal/*": null,
36
+ "./*/index": null
37
+ },
38
+ "files": [
39
+ "src/**/*.ts",
40
+ "dist/**/*.js",
41
+ "dist/**/*.js.map",
42
+ "dist/**/*.d.ts",
43
+ "dist/**/*.d.ts.map"
44
+ ],
45
+ "publishConfig": {
46
+ "access": "public",
47
+ "provenance": true
48
+ },
49
+ "devDependencies": {
50
+ "effect": "^4.0.0-beta.100"
51
+ },
52
+ "peerDependencies": {
53
+ "effect": "^4.0.0-beta.100"
54
+ },
55
+ "dependencies": {
56
+ "@electric-sql/pglite": "^0.5.4"
57
+ },
58
+ "scripts": {
59
+ "codegen": "effect-utils codegen",
60
+ "build": "tsc -b tsconfig.json && pnpm babel",
61
+ "babel": "babel dist --plugins annotate-pure-calls --out-dir dist --source-maps",
62
+ "check": "tsc -b tsconfig.json",
63
+ "test": "vitest",
64
+ "coverage": "vitest --coverage"
65
+ }
66
+ }
@@ -0,0 +1,513 @@
1
+ /**
2
+ * Connects Effect SQL to PGlite, the embedded PostgreSQL-compatible database
3
+ * from `@electric-sql/pglite`.
4
+ *
5
+ * This module can create a managed PGlite instance or wrap an existing one and
6
+ * expose it as both `PgliteClient` and the generic Effect SQL client. The client
7
+ * runs PostgreSQL-style SQL, adds helpers for JSON values and LISTEN/NOTIFY
8
+ * messages, can dump the PGlite data directory, and can refresh PGlite array
9
+ * types. It also provides layers and maps common PostgreSQL-style failures into
10
+ * Effect SQL errors.
11
+ *
12
+ * @since 4.0.0
13
+ */
14
+ import { PGlite, type PGliteInterface, type PGliteOptions } from "@electric-sql/pglite"
15
+ import * as Config from "effect/Config"
16
+ import * as Context from "effect/Context"
17
+ import * as Effect from "effect/Effect"
18
+ import * as Fiber from "effect/Fiber"
19
+ import * as Layer from "effect/Layer"
20
+ import * as Queue from "effect/Queue"
21
+ import * as Scope from "effect/Scope"
22
+ import * as Semaphore from "effect/Semaphore"
23
+ import * as Stream from "effect/Stream"
24
+ import * as Reactivity from "effect/unstable/reactivity/Reactivity"
25
+ import * as Client from "effect/unstable/sql/SqlClient"
26
+ import type { Connection } from "effect/unstable/sql/SqlConnection"
27
+ import {
28
+ AuthenticationError,
29
+ AuthorizationError,
30
+ ConnectionError,
31
+ ConstraintError,
32
+ DeadlockError,
33
+ LockTimeoutError,
34
+ SerializationError,
35
+ SqlError,
36
+ SqlSyntaxError,
37
+ StatementTimeoutError,
38
+ UniqueViolation,
39
+ UnknownError
40
+ } from "effect/unstable/sql/SqlError"
41
+ import type { Custom, Fragment } from "effect/unstable/sql/Statement"
42
+ import * as Statement from "effect/unstable/sql/Statement"
43
+
44
+ /**
45
+ * Runtime type identifier used to mark `PgliteClient` values.
46
+ *
47
+ * @category type IDs
48
+ * @since 4.0.0
49
+ */
50
+ export const TypeId: TypeId = "~@effect/sql-pglite/PgliteClient"
51
+
52
+ /**
53
+ * Type-level identifier used to mark `PgliteClient` values.
54
+ *
55
+ * @category type IDs
56
+ * @since 4.0.0
57
+ */
58
+ export type TypeId = "~@effect/sql-pglite/PgliteClient"
59
+
60
+ /**
61
+ * PGlite-backed PostgreSQL client service, extending `SqlClient` with access to the PGlite instance, JSON fragments, LISTEN/NOTIFY, data directory dumps, and array type refresh.
62
+ *
63
+ * @category models
64
+ * @since 4.0.0
65
+ */
66
+ export interface PgliteClient extends Client.SqlClient {
67
+ readonly [TypeId]: TypeId
68
+ readonly config: PgliteClientConfig
69
+ readonly pglite: PGliteInterface
70
+ readonly json: (_: unknown) => Fragment
71
+ readonly listen: (channel: string) => Stream.Stream<string, SqlError>
72
+ readonly notify: (channel: string, payload: string) => Effect.Effect<void, SqlError>
73
+ readonly dumpDataDir: (compression?: "none" | "gzip" | "auto") => Effect.Effect<File | Blob, SqlError>
74
+ readonly refreshArrayTypes: Effect.Effect<void, SqlError>
75
+ }
76
+
77
+ /**
78
+ * Service tag for the PGlite client service.
79
+ *
80
+ * **When to use**
81
+ *
82
+ * Use to access or provide a PGlite client through the Effect context.
83
+ *
84
+ * @category services
85
+ * @since 4.0.0
86
+ */
87
+ export const PgliteClient = Context.Service<PgliteClient>("@effect/sql-pglite/PgliteClient")
88
+
89
+ /**
90
+ * Configuration for a PGlite client, either by supplying PGlite creation options or an existing live PGlite client.
91
+ *
92
+ * @category models
93
+ * @since 4.0.0
94
+ */
95
+ export type PgliteClientConfig = PgliteClientConfig.Create | PgliteClientConfig.Live
96
+
97
+ /**
98
+ * Namespace containing the configuration variants for `PgliteClient`.
99
+ *
100
+ * @since 4.0.0
101
+ */
102
+ export declare namespace PgliteClientConfig {
103
+ /**
104
+ * Shared PGlite client options for span attributes, query/result name transformations, and JSON value transformation.
105
+ *
106
+ * @category models
107
+ * @since 4.0.0
108
+ */
109
+ export interface Base {
110
+ readonly spanAttributes?: Record<string, unknown> | undefined
111
+ readonly transformResultNames?: ((str: string) => string) | undefined
112
+ readonly transformQueryNames?: ((str: string) => string) | undefined
113
+ readonly transformJson?: boolean | undefined
114
+ }
115
+
116
+ /**
117
+ * Configuration used to create a managed PGlite instance from PGlite constructor options.
118
+ *
119
+ * @category models
120
+ * @since 4.0.0
121
+ */
122
+ export interface Create extends Base, PGliteOptions {}
123
+
124
+ /**
125
+ * Configuration that uses an existing PGlite client. The supplied `liveClient` is caller-owned and is not closed by the Effect client.
126
+ *
127
+ * @category models
128
+ * @since 4.0.0
129
+ */
130
+ export interface Live extends Base {
131
+ readonly liveClient: PGliteInterface
132
+ }
133
+
134
+ /**
135
+ * Config-friendly subset of PGlite creation options, including data directory, username, database, relaxed durability, and shared transform options.
136
+ *
137
+ * @category models
138
+ * @since 4.0.0
139
+ */
140
+ export interface ConfigBase extends Base {
141
+ readonly dataDir?: string | undefined
142
+ readonly username?: string | undefined
143
+ readonly database?: string | undefined
144
+ readonly relaxedDurability?: boolean | undefined
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Creates a scoped PGlite SQL client. When no live client is supplied it creates and closes a PGlite instance; when `liveClient` is supplied, the caller retains ownership.
150
+ *
151
+ * @category constructors
152
+ * @since 4.0.0
153
+ */
154
+ export const make = (
155
+ options: PgliteClientConfig = {}
156
+ ): Effect.Effect<PgliteClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
157
+ Effect.gen(function*() {
158
+ const pglite = "liveClient" in options
159
+ ? options.liveClient
160
+ : yield* Effect.acquireRelease(
161
+ Effect.tryPromise({
162
+ try: async () => {
163
+ const pg = new PGlite(options)
164
+ await pg.waitReady
165
+ return pg
166
+ },
167
+ catch: (cause) => new SqlError({ reason: classifyError(cause, "PgliteClient: Failed to connect", "connect") })
168
+ }),
169
+ (pg) => Effect.promise(() => pg.close()).pipe(Effect.timeoutOption(1000)),
170
+ { interruptible: true }
171
+ )
172
+
173
+ return yield* fromClient({ ...options, liveClient: pglite })
174
+ })
175
+
176
+ /**
177
+ * Builds a `PgliteClient` around an existing PGlite instance, adding SQL client operations, LISTEN/NOTIFY, dump helpers, and serialized access.
178
+ *
179
+ * @category constructors
180
+ * @since 4.0.0
181
+ */
182
+ export const fromClient = (
183
+ options:
184
+ & PgliteClientConfig.Base
185
+ & {
186
+ readonly liveClient: PGliteInterface
187
+ }
188
+ ): Effect.Effect<PgliteClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
189
+ Effect.gen(function*() {
190
+ const pglite = options.liveClient
191
+ const compiler = makeCompiler(options.transformQueryNames, options.transformJson)
192
+ const transformRows = options.transformResultNames
193
+ ? Statement.defaultTransforms(options.transformResultNames, options.transformJson).array
194
+ : undefined
195
+
196
+ const spanAttributes: Array<[string, unknown]> = [
197
+ ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
198
+ [ATTR_DB_SYSTEM_NAME, "postgresql"]
199
+ ]
200
+
201
+ const connection = new PgliteConnection(pglite)
202
+ const semaphore = Semaphore.makeUnsafe(1)
203
+ const acquirer = semaphore.withPermits(1)(Effect.succeed(connection))
204
+ const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
205
+ const fiber = Fiber.getCurrent()!
206
+ const scope = Context.getUnsafe(fiber.context, Scope.Scope)
207
+ return Effect.as(
208
+ Effect.tap(
209
+ restore(semaphore.take(1)),
210
+ () => Scope.addFinalizer(scope, semaphore.release(1))
211
+ ),
212
+ connection
213
+ )
214
+ })
215
+
216
+ const config = options as PgliteClientConfig
217
+ const client = yield* Client.make({
218
+ acquirer,
219
+ compiler,
220
+ transactionAcquirer,
221
+ spanAttributes,
222
+ transformRows
223
+ })
224
+
225
+ return Object.assign(
226
+ client,
227
+ {
228
+ [TypeId]: TypeId as TypeId,
229
+ config,
230
+ pglite,
231
+ json: (_: unknown) => Statement.fragment([PgJson(_)]),
232
+ listen: (channel: string) =>
233
+ Stream.callback<string, SqlError>((queue) =>
234
+ Effect.acquireRelease(
235
+ Effect.tryPromise({
236
+ try: () =>
237
+ pglite.listen(channel, (payload) => {
238
+ Queue.offerUnsafe(queue, payload)
239
+ }),
240
+ catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to listen", "listen") })
241
+ }),
242
+ (unlisten) => Effect.promise(() => unlisten()),
243
+ { interruptible: true }
244
+ )
245
+ ),
246
+ notify: (channel: string, payload: string) =>
247
+ Effect.tryPromise({
248
+ try: () => pglite.exec(`NOTIFY ${escape(channel)}, ${escapeLiteral(payload)}`),
249
+ catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to notify", "notify") })
250
+ }).pipe(
251
+ semaphore.withPermit,
252
+ Effect.asVoid
253
+ ),
254
+ dumpDataDir: (compression?: "none" | "gzip" | "auto") =>
255
+ semaphore.withPermit(
256
+ Effect.tryPromise({
257
+ try: () => pglite.dumpDataDir(compression),
258
+ catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to dump data dir", "dumpDataDir") })
259
+ })
260
+ ),
261
+ refreshArrayTypes: semaphore.withPermit(
262
+ Effect.tryPromise({
263
+ try: () => pglite.refreshArrayTypes(),
264
+ catch: (cause) =>
265
+ new SqlError({ reason: classifyError(cause, "Failed to refresh array types", "refreshArrayTypes") })
266
+ })
267
+ )
268
+ }
269
+ )
270
+ })
271
+
272
+ class PgliteConnection implements Connection {
273
+ readonly pglite: PGliteInterface
274
+ constructor(pglite: PGliteInterface) {
275
+ this.pglite = pglite
276
+ }
277
+
278
+ private run(method: string, sql: string, params: ReadonlyArray<unknown>) {
279
+ return Effect.map(
280
+ Effect.tryPromise({
281
+ try: () => this.pglite.query<any>(sql, params as Array<any>),
282
+ catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", method) })
283
+ }),
284
+ (result) => result.rows
285
+ )
286
+ }
287
+ execute(
288
+ sql: string,
289
+ params: ReadonlyArray<unknown>,
290
+ transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
291
+ ) {
292
+ return transformRows
293
+ ? Effect.map(this.run("execute", sql, params), transformRows)
294
+ : this.run("execute", sql, params)
295
+ }
296
+ executeRaw(sql: string, params: ReadonlyArray<unknown>) {
297
+ return Effect.tryPromise({
298
+ try: () => this.pglite.query<any>(sql, params as Array<any>),
299
+ catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "executeRaw") })
300
+ })
301
+ }
302
+ executeValues(sql: string, params: ReadonlyArray<unknown>) {
303
+ return Effect.map(
304
+ Effect.tryPromise({
305
+ try: () => this.pglite.query<any>(sql, params as Array<any>, { rowMode: "array" }),
306
+ catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "executeValues") })
307
+ }),
308
+ (result) => result.rows as ReadonlyArray<ReadonlyArray<any>>
309
+ )
310
+ }
311
+ executeValuesUnprepared(sql: string, params: ReadonlyArray<unknown>) {
312
+ return Effect.map(
313
+ Effect.tryPromise({
314
+ try: () => this.pglite.query<any>(sql, params as Array<any>, { rowMode: "array" }),
315
+ catch: (cause) =>
316
+ new SqlError({ reason: classifyError(cause, "Failed to execute statement", "executeValuesUnprepared") })
317
+ }),
318
+ (result) => result.rows as ReadonlyArray<ReadonlyArray<any>>
319
+ )
320
+ }
321
+ executeUnprepared(
322
+ sql: string,
323
+ params: ReadonlyArray<unknown>,
324
+ transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
325
+ ) {
326
+ return transformRows
327
+ ? Effect.map(this.run("executeUnprepared", sql, params), transformRows)
328
+ : this.run("executeUnprepared", sql, params)
329
+ }
330
+ executeStream(
331
+ sql: string,
332
+ params: ReadonlyArray<unknown>,
333
+ transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
334
+ ) {
335
+ const eff = transformRows
336
+ ? Effect.map(this.run("executeStream", sql, params), transformRows)
337
+ : this.run("executeStream", sql, params)
338
+ return Stream.fromArrayEffect(eff)
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Creates a layer from an effect that acquires a `PgliteClient`, providing both `PgliteClient` and `SqlClient`.
344
+ *
345
+ * @category layers
346
+ * @since 4.0.0
347
+ */
348
+ export const layerFrom = <E, R>(
349
+ acquire: Effect.Effect<PgliteClient, E, R>
350
+ ): Layer.Layer<PgliteClient | Client.SqlClient, E, Exclude<R, Scope.Scope | Reactivity.Reactivity>> =>
351
+ Layer.effectContext(
352
+ Effect.map(acquire, (client) =>
353
+ Context.make(PgliteClient, client).pipe(
354
+ Context.add(Client.SqlClient, client)
355
+ ))
356
+ ).pipe(Layer.provide(Reactivity.layer)) as any
357
+
358
+ /**
359
+ * Creates a layer from a `Config`-wrapped PGlite client configuration, providing both `PgliteClient` and `SqlClient`.
360
+ *
361
+ * @category layers
362
+ * @since 4.0.0
363
+ */
364
+ export const layerConfig: (
365
+ config: Config.Wrap<PgliteClientConfig.ConfigBase>
366
+ ) => Layer.Layer<PgliteClient | Client.SqlClient, Config.ConfigError | SqlError> = (
367
+ config: Config.Wrap<PgliteClientConfig.ConfigBase>
368
+ ): Layer.Layer<PgliteClient | Client.SqlClient, Config.ConfigError | SqlError> =>
369
+ layerFrom(Effect.flatMap(
370
+ Config.unwrap(config),
371
+ (resolved) => make(resolved as PgliteClientConfig)
372
+ ))
373
+
374
+ /**
375
+ * Creates a layer from a concrete PGlite client configuration, providing both `PgliteClient` and `SqlClient`.
376
+ *
377
+ * @category layers
378
+ * @since 4.0.0
379
+ */
380
+ export const layer = (
381
+ config?: PgliteClientConfig | undefined
382
+ ): Layer.Layer<PgliteClient | Client.SqlClient, SqlError> => layerFrom(make(config))
383
+
384
+ /**
385
+ * Creates the PGlite statement compiler, using PostgreSQL `$1` placeholders, double-quoted identifiers, returning clauses, and optional JSON value transformation.
386
+ *
387
+ * @category constructors
388
+ * @since 4.0.0
389
+ */
390
+ export const makeCompiler = (
391
+ transform?: (_: string) => string,
392
+ transformJson = true
393
+ ): Statement.Compiler => {
394
+ const transformValue = transformJson && transform
395
+ ? Statement.defaultTransforms(transform).value
396
+ : undefined
397
+
398
+ return Statement.makeCompiler<PgCustom>({
399
+ dialect: "pg",
400
+ placeholder(_) {
401
+ return `$${_}`
402
+ },
403
+ onIdentifier: transform ?
404
+ function(value, withoutTransform) {
405
+ return withoutTransform ? escape(value) : escape(transform(value))
406
+ } :
407
+ escape,
408
+ onRecordUpdate(placeholders, valueAlias, valueColumns, values, returning) {
409
+ return [
410
+ `(values ${placeholders}) AS ${valueAlias}${valueColumns}${returning ? ` RETURNING ${returning[0]}` : ""}`,
411
+ returning ?
412
+ values.flat().concat(returning[1]) :
413
+ values.flat()
414
+ ]
415
+ },
416
+ onCustom(type, placeholder, withoutTransform) {
417
+ switch (type.kind) {
418
+ case "PgJson": {
419
+ return [
420
+ placeholder(undefined),
421
+ [
422
+ withoutTransform || transformValue === undefined
423
+ ? type.paramA
424
+ : transformValue(type.paramA)
425
+ ]
426
+ ]
427
+ }
428
+ }
429
+ }
430
+ })
431
+ }
432
+
433
+ const escape = Statement.defaultEscape("\"")
434
+ const escapeLiteral = (value: string) => `'${value.replace(/'/g, "''")}'`
435
+
436
+ /**
437
+ * PGlite-specific custom statement fragments supported by the compiler, currently JSON parameter fragments.
438
+ *
439
+ * @category custom types
440
+ * @since 4.0.0
441
+ */
442
+ export type PgCustom = PgJson
443
+
444
+ /**
445
+ * @category custom types
446
+ * @since 4.0.0
447
+ */
448
+ interface PgJson extends Custom<"PgJson", unknown> {}
449
+ const PgJson = Statement.custom<PgJson>("PgJson")
450
+
451
+ const ATTR_DB_SYSTEM_NAME = "db.system.name"
452
+
453
+ const pgCodeFromCause = (cause: unknown): string | undefined => {
454
+ if (typeof cause !== "object" || cause === null || !("code" in cause)) {
455
+ return undefined
456
+ }
457
+ const code = cause.code
458
+ return typeof code === "string" ? code : undefined
459
+ }
460
+
461
+ const pgConstraintFromCause = (cause: unknown): string => {
462
+ if (typeof cause !== "object" || cause === null || !("constraint" in cause)) {
463
+ return "unknown"
464
+ }
465
+ const constraint = cause.constraint
466
+ if (typeof constraint !== "string") {
467
+ return "unknown"
468
+ }
469
+ const normalized = constraint.trim()
470
+ return normalized.length === 0 ? "unknown" : normalized
471
+ }
472
+
473
+ const classifyError = (
474
+ cause: unknown,
475
+ message: string,
476
+ operation: string
477
+ ) => {
478
+ const props = { cause, message, operation }
479
+ const code = pgCodeFromCause(cause)
480
+ if (code !== undefined) {
481
+ if (code.startsWith("08")) {
482
+ return new ConnectionError(props)
483
+ }
484
+ if (code.startsWith("28")) {
485
+ return new AuthenticationError(props)
486
+ }
487
+ if (code === "42501") {
488
+ return new AuthorizationError(props)
489
+ }
490
+ if (code.startsWith("42")) {
491
+ return new SqlSyntaxError(props)
492
+ }
493
+ if (code === "23505") {
494
+ return new UniqueViolation({ ...props, constraint: pgConstraintFromCause(cause) })
495
+ }
496
+ if (code.startsWith("23")) {
497
+ return new ConstraintError(props)
498
+ }
499
+ if (code === "40P01") {
500
+ return new DeadlockError(props)
501
+ }
502
+ if (code === "40001") {
503
+ return new SerializationError(props)
504
+ }
505
+ if (code === "55P03") {
506
+ return new LockTimeoutError(props)
507
+ }
508
+ if (code === "57014") {
509
+ return new StatementTimeoutError(props)
510
+ }
511
+ }
512
+ return new UnknownError(props)
513
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Runs database migrations for PGlite projects that use Effect SQL.
3
+ *
4
+ * This module re-exports the shared migration loaders and errors, then provides
5
+ * `run` and `layer` helpers that apply pending migration files with the current
6
+ * `SqlClient`. It does not require a separate PGlite service; the active SQL
7
+ * client supplies the database connection.
8
+ *
9
+ * @since 4.0.0
10
+ */
11
+ import type * as Effect from "effect/Effect"
12
+ import * as Layer from "effect/Layer"
13
+ import * as Migrator from "effect/unstable/sql/Migrator"
14
+ import type * as Client from "effect/unstable/sql/SqlClient"
15
+ import type { SqlError } from "effect/unstable/sql/SqlError"
16
+
17
+ /**
18
+ * @since 4.0.0
19
+ */
20
+ export * from "effect/unstable/sql/Migrator"
21
+
22
+ /**
23
+ * Runs SQL migrations using the configured `SqlClient`, returning the migrations that were applied.
24
+ *
25
+ * @category constructors
26
+ * @since 4.0.0
27
+ */
28
+ export const run: <R2 = never>(
29
+ options: Migrator.MigratorOptions<R2>
30
+ ) => Effect.Effect<
31
+ ReadonlyArray<readonly [id: number, name: string]>,
32
+ Migrator.MigrationError | SqlError,
33
+ Client.SqlClient | R2
34
+ > = Migrator.make({})
35
+
36
+ /**
37
+ * Creates a layer that runs the configured SQL migrations during layer construction.
38
+ *
39
+ * @category constructors
40
+ * @since 4.0.0
41
+ */
42
+ export const layer = <R>(
43
+ options: Migrator.MigratorOptions<R>
44
+ ): Layer.Layer<never, Migrator.MigrationError | SqlError, Client.SqlClient | R> => Layer.effectDiscard(run(options))
package/src/index.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @since 4.0.0
3
+ */
4
+
5
+ // @barrel: Auto-generated exports. Do not edit manually.
6
+
7
+ /**
8
+ * @since 4.0.0
9
+ */
10
+ export * as PgliteClient from "./PgliteClient.ts"
11
+
12
+ /**
13
+ * @since 4.0.0
14
+ */
15
+ export * as PgliteMigrator from "./PgliteMigrator.ts"