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

LibsqlClient.ts

407 lines14.0 KB

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