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

LibsqlClient.ts

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