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

LibsqlClient.ts

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