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

LibsqlClient.ts

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