Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

LibsqlClient.ts

404 lines13.7 KB

1/**
2 * libSQL adapter for Effect SQL, backed by `@libsql/client`.
3 *
4 * This module provides a {@link LibsqlClient} and the generic SQL client
5 * service for `@libsql/client`. It uses Effect SQL's SQLite compiler, supports
6 * managed SDK clients or caller-owned live clients, classifies libSQL and
7 * SQLite failures as `SqlError`s, and provides transaction support with
8 * savepoints. Streaming queries are not implemented by this driver.
9 *
10 * @stability unstable
11 * @since 4.0.0
12 */
13import * as Libsql from "@libsql/client"
14import * as Config from "effect/Config"
15import * as Context from "effect/Context"
16import * as Effect from "effect/Effect"
17import * as Layer from "effect/Layer"
18import * as Option from "effect/Option"
19import * as Reactivity from "effect/reactivity/Reactivity"
20import * as Redacted from "effect/Redacted"
21import type * as Scope from "effect/Scope"
22import * as Semaphore from "effect/Semaphore"
23import * as Client from "effect/sql/SqlClient"
24import type { Connection } from "effect/sql/SqlConnection"
25import { classifySqliteError, SqlError } from "effect/sql/SqlError"
26import * as Statement from "effect/sql/Statement"
27import * as Stream from "effect/Stream"
28​
29const ATTR_DB_SYSTEM_NAME = "db.system.name"
30​
31const classifyError = (cause: unknown, message: string, operation: string) =>
32 classifySqliteError(cause, { message, operation })
33​
34/**
35 * Runtime type identifier used to mark `LibsqlClient` values.
36 *
37 * @stability unstable
38 * @category type IDs
39 * @since 4.0.0
40 */
41export const TypeId: TypeId = "~@effect/sql-libsql/LibsqlClient"
42​
43/**
44 * Type-level identifier used to mark `LibsqlClient` values.
45 *
46 * @stability unstable
47 * @category type IDs
48 * @since 4.0.0
49 */
50export type TypeId = "~@effect/sql-libsql/LibsqlClient"
51​
52/**
53 * libSQL-backed SQL client service, extending `SqlClient` with its runtime type marker and client configuration.
54 *
55 * @stability unstable
56 * @category services
57 * @since 4.0.0
58 */
59export interface LibsqlClient extends Client.Base {
60 readonly [TypeId]: TypeId
61 readonly config: LibsqlClientConfig
63​
64/**
65 * Service tag for the libSQL client service.
66 *
67 * **When to use**
68 *
69 * Use to access or provide a libSQL client through the Effect context.
70 *
71 * @stability unstable
72 * @category services
73 * @since 4.0.0
74 */
75export const LibsqlClient = Context.Service<LibsqlClient, LibsqlClient & Client.SqlClient>(
76 "@effect/sql-libsql/LibsqlClient"
78​
79let clientIdCounter = 0
80​
81/**
82 * Configuration for a libSQL client, either by supplying connection options or an existing live libSQL client.
83 *
84 * @stability unstable
85 * @category models
86 * @since 4.0.0
87 */
88export type LibsqlClientConfig = LibsqlClientConfig.Full | LibsqlClientConfig.Live
89​
90/**
91 * Namespace containing the configuration variants for `LibsqlClient`.
92 *
93 * @stability unstable
94 * @since 4.0.0
95 */
96export declare namespace LibsqlClientConfig {
97 /**
98 * Shared libSQL client options for span attributes and query/result name transformations.
99 *
100 * @category models
101 * @since 4.0.0
102 */
103 export interface Base {
104 readonly spanAttributes?: Record<string, unknown> | undefined
105 readonly transformResultNames?: ((str: string) => string) | undefined
106 readonly transformQueryNames?: ((str: string) => string) | undefined
107 }
108​
109 /**
110 * Connection-based libSQL configuration used to create a managed client, including URL, credentials, sync, integer mode, TLS, and concurrency options.
111 *
112 * @category models
113 * @since 4.0.0
114 */
115 export interface Full extends Base {
116 /**
117 * The database URL.
118 *
119 * **Details**
120 *
121 * The client supports `libsql:`, `http:`/`https:`, `ws:`/`wss:` and `file:` URL. For more infomation,
122 * please refer to the project README:
123 *
124 * https://github.com/libsql/libsql-client-ts#supported-urls
125 */
126 readonly url: string | URL
127 /** Authentication token for the database. */
128 readonly authToken?: Redacted.Redacted | undefined
129 /** Encryption key for the database. */
130 readonly encryptionKey?: Redacted.Redacted | undefined
131 /** URL of a remote server to synchronize database with. */
132 readonly syncUrl?: string | URL | undefined
133 /** Sync interval in seconds. */
134 readonly syncInterval?: number | undefined
135 /**
136 * Enables or disables TLS for `libsql:` URLs.
137 *
138 * **Details**
139 *
140 * By default, `libsql:` URLs use TLS. You can set this option to `false` to disable TLS.
141 */
142 readonly tls?: boolean | undefined
143 /**
144 * How to convert SQLite integers to JavaScript values.
145 *
146 * **Details**
147 *
148 * - `"number"` (default): returns SQLite integers as JavaScript `number`-s (double precision floats).
149 * `number` cannot precisely represent integers larger than 2^53-1 in absolute value, so attempting to read
150 * larger integers will throw a `RangeError`.
151 * - `"bigint"`: returns SQLite integers as JavaScript `bigint`-s (arbitrary precision integers). Bigints can
152 * precisely represent all SQLite integers.
153 * - `"string"`: returns SQLite integers as strings.
154 */
155 readonly intMode?: "number" | "bigint" | "string" | undefined
156 /**
157 * Concurrency limit.
158 *
159 * **Details**
160 *
161 * By default, the client performs up to 20 concurrent requests. You can set this option to a higher
162 * number to increase the concurrency limit or set it to 0 to disable concurrency limits completely.
163 */
164 readonly concurrency?: number | undefined
165 }
166​
167 /**
168 * Configuration that uses an existing libSQL client. The supplied `liveClient` is caller-owned and is not closed by the Effect client.
169 *
170 * @stability unstable
171 * @category models
172 * @since 4.0.0
173 */
174 export interface Live extends Base {
175 readonly liveClient: Libsql.Client
176 }
178​
179interface LibsqlConnection extends Connection {
180 readonly beginTransaction: Effect.Effect<LibsqlConnection, SqlError>
181 readonly commit: Effect.Effect<void, SqlError>
182 readonly rollback: Effect.Effect<void, SqlError>
184​
185/**
186 * Creates a scoped libSQL SQL client with transaction support. When given connection options it creates and closes the SDK client; when given `liveClient`, the caller retains ownership.
187 *
188 * @stability unstable
189 * @category constructors
190 * @since 4.0.0
191 */
192export const make = (
193 options: LibsqlClientConfig
194): Effect.Effect<LibsqlClient & Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
195 Effect.gen(function*() {
196 const LibsqlTransaction = Context.Service<readonly [LibsqlConnection, counter: number]>(
197 `@effect/sql-libsql/LibsqlClient/LibsqlTransaction/${clientIdCounter++}`
198 )
199 const compiler = Statement.makeCompilerSqlite(options.transformQueryNames)
200 const transformRows = options.transformResultNames ?
201 Statement.defaultTransforms(
202 options.transformResultNames
203 ).array :
204 undefined
205​
206 const spanAttributes: Array<[string, unknown]> = [
207 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
208 [ATTR_DB_SYSTEM_NAME, "sqlite"]
209 ]
210​
211 class LibsqlConnectionImpl implements LibsqlConnection {
212 readonly sdk: Libsql.Client | Libsql.Transaction
213 constructor(sdk: Libsql.Client | Libsql.Transaction) {
214 this.sdk = sdk
215 }
216​
217 run(
218 sql: string,
219 params: ReadonlyArray<unknown> = []
220 ) {
221 return Effect.map(
222 Effect.tryPromise({
223 try: () => this.sdk.execute({ sql, args: params as Array<any> }),
224 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
225 }),
226 (results) => results.rows
227 )
228 }
229​
230 runRaw(
231 sql: string,
232 params: ReadonlyArray<unknown> = []
233 ) {
234 return Effect.tryPromise({
235 try: () => this.sdk.execute({ sql, args: params as Array<any> }),
236 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
237 })
238 }
239​
240 execute(
241 sql: string,
242 params: ReadonlyArray<unknown>,
243 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
244 ) {
245 return transformRows
246 ? Effect.map(this.run(sql, params), transformRows)
247 : this.run(sql, params)
248 }
249 executeRaw(sql: string, params: ReadonlyArray<unknown>) {
250 return this.runRaw(sql, params)
251 }
252 executeValues(sql: string, params: ReadonlyArray<unknown>) {
253 return Effect.map(this.run(sql, params), (rows) => rows.map((row) => Array.from(row) as Array<any>))
254 }
255 executeValuesUnprepared(sql: string, params: ReadonlyArray<unknown>) {
256 return this.executeValues(sql, params)
257 }
258 executeUnprepared(
259 sql: string,
260 params: ReadonlyArray<unknown>,
261 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
262 ) {
263 return this.execute(sql, params, transformRows)
264 }
265 executeStream() {
266 return Stream.die("executeStream not implemented")
267 }
268 get beginTransaction() {
269 return Effect.map(
270 Effect.tryPromise({
271 try: () => (this.sdk as Libsql.Client).transaction("write"),
272 catch: (cause) =>
273 new SqlError({ reason: classifyError(cause, "Failed to begin transaction", "beginTransaction") })
274 }),
275 (tx) => new LibsqlConnectionImpl(tx)
276 )
277 }
278 get commit() {
279 return Effect.tryPromise({
280 try: () => (this.sdk as Libsql.Transaction).commit(),
281 catch: (cause) =>
282 new SqlError({ reason: classifyError(cause, "Failed to commit transaction", "commitTransaction") })
283 })
284 }
285 get rollback() {
286 return Effect.tryPromise({
287 try: () => (this.sdk as Libsql.Transaction).rollback(),
288 catch: (cause) =>
289 new SqlError({ reason: classifyError(cause, "Failed to rollback transaction", "rollbackTransaction") })
290 })
291 }
292 }
293​
294 const connection = "liveClient" in options
295 ? new LibsqlConnectionImpl(options.liveClient)
296 : yield* Effect.map(
297 Effect.acquireRelease(
298 Effect.sync(() =>
299 Libsql.createClient(
300 {
301 ...options,
302 authToken: Redacted.isRedacted(options.authToken)
303 ? Redacted.value(options.authToken)
304 : options.authToken,
305 encryptionKey: Redacted.isRedacted(options.encryptionKey)
306 ? Redacted.value(options.encryptionKey)
307 : options.encryptionKey,
308 url: options.url.toString(),
309 syncUrl: options.syncUrl?.toString()
310 } as Libsql.Config
311 )
312 ),
313 (sdk) => Effect.sync(() => sdk.close())
314 ),
315 (sdk) => new LibsqlConnectionImpl(sdk)
316 )
317 // Remote transports run each statement and transaction on its own stream.
318 // Local clients may own a single connection that the SDK refuses to lend
319 // while a transaction holds it, so take turns on it instead.
320 const protocol = (connection.sdk as Libsql.Client).protocol
321 const permit: Effect.Effect<void, never, Scope.Scope> = protocol === "http" || protocol === "ws"
322 ? Effect.void
323 : (yield* Semaphore.make(1)).takeScoped(1)
324​
325 const withTransaction = Client.makeWithTransaction({
326 transactionService: LibsqlTransaction,
327 spanAttributes,
328 acquireConnection: (restore) => Effect.andThen(restore(permit), connection.beginTransaction),
329 begin: () => Effect.void, // already begun in acquireConnection
330 savepoint: (conn, id) => conn.executeRaw(`SAVEPOINT effect_sql_${id};`, []),
331 releaseSavepoint: (conn, id) => conn.executeRaw(`RELEASE SAVEPOINT effect_sql_${id};`, []),
332 commit: (conn) => conn.commit,
333 rollback: (conn) => conn.rollback,
334 rollbackSavepoint: (conn, id) => conn.executeRaw(`ROLLBACK TO SAVEPOINT effect_sql_${id};`, [])
335 })
336​
337 // Outside a transaction, hold the permit until the statement's scope
338 // closes, so no other fiber can begin a transaction while it runs.
339 const lease = Effect.as(permit, connection as LibsqlConnection)
340 const acquirer = Effect.flatMap(
341 Effect.serviceOption(LibsqlTransaction),
342 Option.match({
343 onNone: () => lease,
344 onSome: Client.activeTransactionConnection
345 })
346 )
347​
348 return Object.assign(
349 yield* Client.make({
350 driver: "libsql",
351 acquirer,
352 transactionService: LibsqlTransaction as any,
353 compiler,
354 spanAttributes,
355 transformRows
356 }),
357 {
358 [TypeId]: TypeId as TypeId,
359 config: options,
360 withTransaction,
361 sdk: connection.sdk
362 }
363 )
364 })
365​
366/**
367 * Creates a layer from a `Config`-wrapped libSQL client configuration, providing both `LibsqlClient` and `SqlClient`.
368 *
369 * @stability unstable
370 * @category layers
371 * @since 4.0.0
372 */
373export const layerConfig: (
374 config: Config.Wrap<LibsqlClientConfig>
375) => Layer.Layer<LibsqlClient | Client.SqlClient, Config.ConfigError> = (
376 config: Config.Wrap<LibsqlClientConfig>
377): Layer.Layer<LibsqlClient | Client.SqlClient, Config.ConfigError> =>
378 Layer.effectContext(
379 Config.unwrap(config).pipe(
380 Effect.flatMap(make),
381 Effect.map((client) =>
382 Context.make(LibsqlClient, client).pipe(
383 Context.add(Client.SqlClient, client)
384 )
385 )
386 )
387 ).pipe(Layer.provide(Reactivity.layer))
388​
389/**
390 * Creates a layer from a concrete libSQL client configuration, providing both `LibsqlClient` and `SqlClient`.
391 *
392 * @stability unstable
393 * @category layers
394 * @since 4.0.0
395 */
396export const layer = (
397 config: LibsqlClientConfig
398): Layer.Layer<LibsqlClient | Client.SqlClient> =>
399 Layer.effectContext(
400 Effect.map(make(config), (client) =>
401 Context.make(LibsqlClient, client).pipe(
402 Context.add(Client.SqlClient, client)
403 ))
404 ).pipe(Layer.provide(Reactivity.layer))