Open History to see the last commit
1/**
2 * MySQL adapter for Effect SQL, backed by the `mysql2` driver.
3 *
4 * This module provides constructors and layers for a {@link MysqlClient} and
5 * the generic Effect SQL client service. `make` creates a managed mysql2 pool,
6 * checks the connection with `SELECT 1`, maps mysql2 failures to `SqlError`,
7 * supports transaction connections, and exposes streaming queries through
8 * mysql2 query streams. It also provides direct and config-backed layers plus a
9 * MySQL statement compiler.
10 *
11 * @stability unstable
12 * @since 4.0.0
13 */
14import * as Config from "effect/Config"
15import * as Context from "effect/Context"
16import * as Duration from "effect/Duration"
17import * as Effect from "effect/Effect"
18import * as Layer from "effect/Layer"
19import * as Reactivity from "effect/reactivity/Reactivity"
20import * as Redacted from "effect/Redacted"
21import type { 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 {
26 AuthenticationError,
27 AuthorizationError,
28 ConnectionError,
29 ConstraintError,
30 DeadlockError,
31 LockTimeoutError,
32 SqlError,
33 SqlSyntaxError,
34 StatementTimeoutError,
35 UniqueViolation,
36 UnknownError
37} from "effect/sql/SqlError"
38import { asyncPauseResume } from "effect/sql/SqlStream"
39import * as Statement from "effect/sql/Statement"
40import * as Stream from "effect/Stream"
41import * as Mysql from "mysql2"
42
43const ATTR_DB_SYSTEM_NAME = "db.system.name"
44const ATTR_DB_NAMESPACE = "db.namespace"
45const ATTR_SERVER_ADDRESS = "server.address"
46const ATTR_SERVER_PORT = "server.port"
47
48const mysqlErrnoFromCause = (cause: unknown): number | undefined => {
49 if (typeof cause !== "object" || cause === null || !("errno" in cause)) {
50 return undefined
51 }
52 const errno = cause.errno
53 return typeof errno === "number" ? errno : undefined
54}
55
56const mysqlConnectionErrorCodes = new Set([1040, 1042, 1043, 1129, 1130, 1203])
57const mysqlAuthorizationErrorCodes = new Set([1044, 1142, 1143, 1227])
58const mysqlSyntaxErrorCodes = new Set([1054, 1064, 1146])
59const mysqlConstraintErrorCodes = new Set([1022, 1048, 1169, 1216, 1217, 1451, 1452, 1557])
60
61const setTransaction = /^\s*SET\s+TRANSACTION\b/i
62
63// SET TRANSACTION without SESSION or GLOBAL applies to the next transaction,
64// so it must directly precede its BEGIN
65const begin = (conn: Connection, statement: string | undefined) =>
66 statement === undefined
67 ? conn.executeUnprepared("BEGIN", [], undefined)
68 : setTransaction.test(statement)
69 ? Effect.andThen(conn.executeUnprepared(statement, [], undefined), conn.executeUnprepared("BEGIN", [], undefined))
70 : conn.executeUnprepared(statement, [], undefined)
71
72const UNKNOWN_CONSTRAINT = "unknown"
73
74const normalizeConstraintIdentifier = (identifier: unknown): string => {
75 if (typeof identifier !== "string") {
76 return UNKNOWN_CONSTRAINT
77 }
78 const trimmed = identifier.trim()
79 return trimmed.length === 0 ? UNKNOWN_CONSTRAINT : trimmed
80}
81
82const mysqlCauseProperty = (cause: unknown, property: "constraint" | "message" | "sqlMessage"): unknown => {
83 if (typeof cause !== "object" || cause === null || !(property in cause)) {
84 return undefined
85 }
86 return (cause as Record<string, unknown>)[property]
87}
88
89const mysqlDuplicateEntryConstraintFromMessage = (message: unknown): string => {
90 if (typeof message !== "string") {
91 return UNKNOWN_CONSTRAINT
92 }
93 const match = /\bfor key\s+(?:'([^']*)'|\x60([^\x60]*)\x60|([^\s'\x60]+))/i.exec(message)
94 return match === null ?
95 UNKNOWN_CONSTRAINT :
96 normalizeConstraintIdentifier(match[1] ?? match[2] ?? match[3])
97}
98
99const mysqlDuplicateEntryConstraintFromCause = (cause: unknown): string => {
100 const constraint = normalizeConstraintIdentifier(mysqlCauseProperty(cause, "constraint"))
101 if (constraint !== UNKNOWN_CONSTRAINT) {
102 return constraint
103 }
104 const sqlMessageConstraint = mysqlDuplicateEntryConstraintFromMessage(mysqlCauseProperty(cause, "sqlMessage"))
105 if (sqlMessageConstraint !== UNKNOWN_CONSTRAINT) {
106 return sqlMessageConstraint
107 }
108 return mysqlDuplicateEntryConstraintFromMessage(mysqlCauseProperty(cause, "message"))
109}
110
111const classifyError = (
112 cause: unknown,
113 message: string,
114 operation: string
115) => {
116 const props = { cause, message, operation }
117 const errno = mysqlErrnoFromCause(cause)
118 if (errno !== undefined) {
119 if (mysqlConnectionErrorCodes.has(errno)) {
120 return new ConnectionError(props)
121 }
122 if (errno === 1045) {
123 return new AuthenticationError(props)
124 }
125 if (mysqlAuthorizationErrorCodes.has(errno)) {
126 return new AuthorizationError(props)
127 }
128 if (mysqlSyntaxErrorCodes.has(errno)) {
129 return new SqlSyntaxError(props)
130 }
131 if (errno === 1062) {
132 return new UniqueViolation({ ...props, constraint: mysqlDuplicateEntryConstraintFromCause(cause) })
133 }
134 if (mysqlConstraintErrorCodes.has(errno)) {
135 return new ConstraintError(props)
136 }
137 if (errno === 1213) {
138 return new DeadlockError(props)
139 }
140 if (errno === 1205) {
141 return new LockTimeoutError(props)
142 }
143 if (errno === 3024) {
144 return new StatementTimeoutError(props)
145 }
146 }
147 return new UnknownError(props)
148}
149
150/**
151 * Runtime type identifier used to mark `MysqlClient` values.
152 *
153 * @stability unstable
154 * @category type IDs
155 * @since 4.0.0
156 */
157export const TypeId: TypeId = "~@effect/sql-mysql2/MysqlClient"
158
159/**
160 * Type-level identifier used to mark `MysqlClient` values.
161 *
162 * @stability unstable
163 * @category type IDs
164 * @since 4.0.0
165 */
166export type TypeId = "~@effect/sql-mysql2/MysqlClient"
167
168/**
169 * mysql2-backed SQL client service, extending `SqlClient` with its runtime type marker and client configuration.
170 *
171 * @stability unstable
172 * @category services
173 * @since 4.0.0
174 */
175export interface MysqlClient extends Client.Base {
176 readonly [TypeId]: TypeId
177 readonly config: MysqlClientConfig
178}
179
180/**
181 * Service tag for the mysql2 SQL client service.
182 *
183 * **When to use**
184 *
185 * Use to access or provide a mysql2 client through the Effect context.
186 *
187 * @stability unstable
188 * @category services
189 * @since 4.0.0
190 */
191export const MysqlClient = Context.Service<MysqlClient, MysqlClient & Client.SqlClient>(
192 "@effect/sql-mysql2/MysqlClient"
193)
194
195/**
196 * Configuration for a mysql2 client, including connection URI or connection fields, pool options, span attributes, and query/result name transforms.
197 *
198 * @stability unstable
199 * @category models
200 * @since 4.0.0
201 */
202export interface MysqlClientConfig {
203 /**
204 * Connection URI. Setting this will override the other connection options
205 */
206 readonly url?: Redacted.Redacted | undefined
207
208 readonly host?: string | undefined
209 readonly port?: number | undefined
210 readonly database?: string | undefined
211 readonly username?: string | undefined
212 readonly password?: Redacted.Redacted | undefined
213
214 readonly maxConnections?: number | undefined
215 readonly connectionTTL?: Duration.Input | undefined
216
217 /**
218 * Options passed directly to the `mysql2` connection pool.
219 *
220 * @stability unstable
221 */
222 readonly poolConfig?: Mysql.PoolOptions | undefined
223
224 /**
225 * Use the text protocol instead of prepared statements, for proxies like
226 * Cloudflare Hyperdrive that do not support `COM_STMT_PREPARE`.
227 */
228 readonly disablePreparedStatements?: boolean | undefined
229
230 readonly spanAttributes?: Record<string, unknown> | undefined
231
232 readonly transformResultNames?: ((str: string) => string) | undefined
233 readonly transformQueryNames?: ((str: string) => string) | undefined
234}
235
236/**
237 * Creates a scoped MySQL client backed by a managed mysql2 pool, verifying connectivity and supporting streaming queries through mysql2 query streams.
238 *
239 * **Details**
240 *
241 * A `SqlClient.BeginTransaction` starting with `SET TRANSACTION`, such as
242 * `SET TRANSACTION ISOLATION LEVEL READ COMMITTED`, runs just before `BEGIN`,
243 * since `START TRANSACTION` can't set an isolation level. Any other statement
244 * replaces `BEGIN`.
245 *
246 * @stability unstable
247 * @category constructors
248 * @since 4.0.0
249 */
250export const make = (
251 options: MysqlClientConfig
252): Effect.Effect<MysqlClient & Client.SqlClient, SqlError, Scope | Reactivity.Reactivity> =>
253 Effect.gen(function*() {
254 const compiler = makeCompiler(options.transformQueryNames)
255 const transformRows = options.transformResultNames ?
256 Statement.defaultTransforms(
257 options.transformResultNames
258 ).array :
259 undefined
260 const defaultMethod: "execute" | "query" = options.disablePreparedStatements === true ? "query" : "execute"
261
262 class ConnectionImpl implements Connection {
263 readonly conn: Mysql.PoolConnection
264 // A transaction or reserved connection can be shared by several fibers.
265 // Each statement or stream holds this permit from before its command is
266 // queued until it has settled, so `KILL QUERY` only ever reaches the
267 // statement that was interrupted.
268 readonly permit = Semaphore.makeUnsafe(1)
269 constructor(conn: Mysql.PoolConnection) {
270 this.conn = conn
271 }
272
273 private runRaw(
274 sql: string,
275 values?: ReadonlyArray<any>,
276 rowsAsArray = false,
277 method: "execute" | "query" = defaultMethod
278 ) {
279 return this.permit.withPermit(Effect.callback<unknown, SqlError>((resume) => {
280 const operation = method === "query" ? "executeUnprepared" : "execute"
281 const statement = new ActiveStatement(connectionOptions, this.conn)
282 ;(this.conn as any)[method]({
283 sql,
284 values,
285 rowsAsArray
286 }, (cause: unknown | null, results: unknown, _fields: any) => {
287 // Once interrupted, the result is dropped.
288 if (!statement.settle()) return
289 if (cause) {
290 resume(
291 Effect.fail(new SqlError({ reason: classifyError(cause, "Failed to execute statement", operation) }))
292 )
293 } else {
294 resume(Effect.succeed(results))
295 }
296 })
297 return statement.cancel
298 }))
299 }
300
301 private run(
302 sql: string,
303 values?: ReadonlyArray<any>,
304 rowsAsArray = false,
305 method: "execute" | "query" = defaultMethod
306 ) {
307 return this.runRaw(sql, values, rowsAsArray, method).pipe(
308 Effect.map((results) => Array.isArray(results) ? results : [])
309 )
310 }
311
312 execute(
313 sql: string,
314 params: ReadonlyArray<unknown>,
315 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
316 ) {
317 return transformRows
318 ? Effect.map(this.run(sql, params), transformRows)
319 : this.run(sql, params)
320 }
321 executeRaw(sql: string, params: ReadonlyArray<unknown>) {
322 return this.runRaw(sql, params)
323 }
324 executeValues(sql: string, params: ReadonlyArray<unknown>) {
325 return this.run(sql, params, true)
326 }
327 executeValuesUnprepared(sql: string, params: ReadonlyArray<unknown>) {
328 return this.run(sql, params, true, "query")
329 }
330 executeUnprepared(
331 sql: string,
332 params: ReadonlyArray<unknown>,
333 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
334 ) {
335 return transformRows
336 ? Effect.map(this.run(sql, params, false, "query"), transformRows)
337 : this.run(sql, params, false, "query")
338 }
339 executeStream(
340 sql: string,
341 params: ReadonlyArray<unknown>,
342 transformRows: (<A extends object>(row: ReadonlyArray<A>) => ReadonlyArray<A>) | undefined
343 ) {
344 const stream = queryStream(connectionOptions, this.conn, this.permit, sql, params)
345 return transformRows
346 ? Stream.mapArray(stream, (_) => transformRows(_) as any)
347 : stream
348 }
349 }
350
351 // Shared by the pool and the one-off connections that send `KILL QUERY`.
352 const connectionOptions: Mysql.PoolOptions = options.url
353 ? {
354 uri: Redacted.value(options.url),
355 multipleStatements: true,
356 supportBigNumbers: true,
357 connectionLimit: options.maxConnections!,
358 idleTimeout: options.connectionTTL
359 ? Duration.toMillis(Duration.fromInputUnsafe(options.connectionTTL))
360 : undefined as any
361 }
362 : {
363 ...options.poolConfig,
364 host: options.host,
365 port: options.port,
366 database: options.database,
367 user: options.username,
368 password: options.password
369 ? Redacted.value(options.password)
370 : undefined,
371 multipleStatements: true,
372 supportBigNumbers: true,
373 connectionLimit: options.maxConnections ?? options.poolConfig?.connectionLimit,
374 idleTimeout: options.connectionTTL
375 ? Duration.toMillis(Duration.fromInputUnsafe(options.connectionTTL))
376 : options.poolConfig?.idleTimeout
377 } as Mysql.PoolOptions
378 const pool = Mysql.createPool(connectionOptions)
379
380 yield* Effect.acquireRelease(
381 Effect.callback<void, SqlError>((resume) => {
382 ;(pool as any).query("SELECT 1", (cause: Error) => {
383 if (cause) {
384 resume(Effect.fail(
385 new SqlError({
386 reason: classifyError(cause, "MysqlClient: Failed to connect", "connect")
387 })
388 ))
389 } else {
390 resume(Effect.void)
391 }
392 })
393 }),
394 () =>
395 Effect.callback<void>((resume) => {
396 pool.end(() => resume(Effect.void))
397 })
398 ).pipe(
399 Effect.timeoutOrElse({
400 duration: Duration.seconds(5),
401 orElse: () =>
402 Effect.fail(
403 new SqlError({
404 reason: new ConnectionError({
405 message: "MysqlClient: Connection timeout",
406 cause: new Error("connection timeout"),
407 operation: "connect"
408 })
409 })
410 )
411 })
412 )
413
414 const acquireConn = Effect.acquireRelease(
415 Effect.callback<Mysql.PoolConnection, SqlError>((resume) => {
416 let interrupted = false
417 // mysql2 cannot remove a waiter from its queue, so a connection handed
418 // over after interruption goes straight back to the pool.
419 pool.getConnection((cause, conn) => {
420 if (interrupted) {
421 conn?.release()
422 return
423 }
424 if (cause) {
425 resume(
426 Effect.fail(
427 new SqlError({
428 reason: classifyError(cause, "Failed to acquire connection", "acquireConnection")
429 })
430 )
431 )
432 } else {
433 resume(Effect.succeed(conn))
434 }
435 })
436 return Effect.sync(() => {
437 interrupted = true
438 })
439 }),
440 (conn) => Effect.sync(() => conn.release()),
441 { interruptible: true }
442 )
443
444 // Every statement checks out its own connection, so an interrupted
445 // statement can be killed by thread id before the connection is reused.
446 const acquirer = Effect.map(acquireConn, (conn) => new ConnectionImpl(conn))
447
448 const spanAttributes: Array<[string, unknown]> = [
449 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
450 [ATTR_DB_SYSTEM_NAME, "mysql"],
451 [ATTR_SERVER_ADDRESS, options.host ?? "localhost"],
452 [ATTR_SERVER_PORT, options.port ?? 3306]
453 ]
454
455 if (options.database) {
456 spanAttributes.push([ATTR_DB_NAMESPACE, options.database])
457 }
458
459 return Object.assign(
460 yield* Client.make({
461 driver: "mysql2",
462 acquirer,
463 begin,
464 releaseSavepoint: (name) => `RELEASE SAVEPOINT ${name}`,
465 compiler,
466 spanAttributes,
467 transformRows
468 }),
469 { [TypeId]: TypeId as TypeId, config: options }
470 )
471 })
472
473/**
474 * Creates a layer from a `Config`-wrapped MySQL client configuration, providing both `MysqlClient` and `SqlClient`.
475 *
476 * @stability unstable
477 * @category layers
478 * @since 4.0.0
479 */
480export const layerConfig = (
481 config: Config.Wrap<MysqlClientConfig>
482): Layer.Layer<MysqlClient | Client.SqlClient, Config.ConfigError | SqlError> =>
483 Layer.effectContext(
484 Config.unwrap(config).pipe(
485 Effect.flatMap(make),
486 Effect.map((client) =>
487 Context.make(MysqlClient, client).pipe(
488 Context.add(Client.SqlClient, client)
489 )
490 )
491 )
492 ).pipe(Layer.provide(Reactivity.layer))
493
494/**
495 * Creates a layer from a concrete MySQL client configuration, providing both `MysqlClient` and `SqlClient`.
496 *
497 * @stability unstable
498 * @category layers
499 * @since 4.0.0
500 */
501export const layer = (
502 config: MysqlClientConfig
503): Layer.Layer<MysqlClient | Client.SqlClient, Config.ConfigError | SqlError> =>
504 Layer.effectContext(
505 Effect.map(make(config), (client) =>
506 Context.make(MysqlClient, client).pipe(
507 Context.add(Client.SqlClient, client)
508 ))
509 ).pipe(Layer.provide(Reactivity.layer))
510
511/**
512 * Creates the MySQL statement compiler, using `?` placeholders and backtick-escaped identifiers.
513 *
514 * @stability unstable
515 * @category constructors
516 * @since 4.0.0
517 */
518export const makeCompiler = (transform?: (_: string) => string) =>
519 Statement.makeCompiler({
520 dialect: "mysql",
521 placeholder(_) {
522 return `?`
523 },
524 onIdentifier: transform ?
525 function(value, withoutTransform) {
526 return withoutTransform ? escape(value) : escape(transform(value))
527 } :
528 escape,
529 onCustom() {
530 return ["", []]
531 },
532 onRecordUpdate() {
533 return ["", []]
534 }
535 })
536
537const escape = Statement.defaultEscape("`")
538
539/**
540 * How long interrupting a statement waits for `KILL QUERY` and the statement to
541 * settle before destroying the connection instead.
542 */
543const cancelTimeoutMillis = 5000
544
545/**
546 * A statement running on a pool connection: records when the server is done
547 * with it, and can stop it.
548 */
549class ActiveStatement {
550 settled = false
551 private cancelling = false
552 private onSettled: (() => void) | undefined = undefined
553 private readonly connectionOptions: Mysql.ConnectionOptions
554 private readonly conn: Mysql.PoolConnection
555 constructor(connectionOptions: Mysql.ConnectionOptions, conn: Mysql.PoolConnection) {
556 this.connectionOptions = connectionOptions
557 this.conn = conn
558 }
559
560 /**
561 * Records that the server is done with the statement. Returns `true` when
562 * the caller handles the outcome, and `false` when it was already recorded
563 * or `cancel` is waiting for it.
564 */
565 settle(): boolean {
566 if (this.settled) return false
567 this.settled = true
568 if (!this.cancelling) return true
569 this.onSettled?.()
570 return false
571 }
572
573 /**
574 * Stops the statement and waits until it is safe to release the connection.
575 *
576 * Running this marks the statement as being cancelled before anything else,
577 * so a settlement from then on belongs to the cancellation, even one that
578 * happens before the kill is registered. If the statement has already
579 * settled, nothing is killed.
580 *
581 * `KILL QUERY` goes over a one-off connection, because the pool may have no
582 * free slot. The effect completes once the kill attempt has finished and the
583 * statement has settled, so a late kill can never reach another statement on
584 * the connection. Kill failures are ignored, including a kill connection that
585 * cannot be created. If both do not happen within `cancelTimeoutMillis`, the
586 * connection is destroyed, which removes it from the pool.
587 */
588 readonly cancel: Effect.Effect<void> = Effect.suspend(() => {
589 this.cancelling = true
590 return Effect.callback<void>((resume) => {
591 if (this.settled) return resume(Effect.void)
592 let done = false
593 let killed = false
594 let kill: Mysql.Connection | undefined
595 const finish = () => {
596 if (done) return
597 done = true
598 clearTimeout(timer)
599 kill?.destroy()
600 resume(Effect.void)
601 }
602 const onKilled = () => {
603 killed = true
604 if (this.settled) finish()
605 }
606 const timer = setTimeout(() => {
607 this.conn.destroy()
608 finish()
609 }, cancelTimeoutMillis)
610 this.onSettled = () => {
611 if (killed) finish()
612 }
613 try {
614 // A configured `stream` factory runs synchronously here and may throw.
615 kill = Mysql.createConnection({ ...this.connectionOptions })
616 kill.on("error", () => {})
617 ;(kill as any).query("KILL QUERY ?", [this.conn.threadId], onKilled)
618 } catch {
619 onKilled()
620 }
621 })
622 })
623}
624
625function queryStream(
626 connectionOptions: Mysql.ConnectionOptions,
627 conn: Mysql.PoolConnection,
628 permit: Semaphore.Semaphore,
629 sql: string,
630 params?: ReadonlyArray<any>
631) {
632 return asyncPauseResume<any, SqlError>(Effect.fnUntraced(function*(emit) {
633 const statement = new ActiveStatement(connectionOptions, conn)
634 let query: any
635 // The permit is returned as soon as the statement settles, because the
636 // consumer may run its own statements on this connection before the
637 // stream ends. When the stream is cancelled, it is kept until the statement
638 // has been killed and seen to settle.
639 let owned = true
640 const release = Effect.suspend(() => {
641 if (!owned) return Effect.void
642 owned = false
643 return permit.release(1)
644 })
645 // Taking the permit also installs the cleanup, so once the command starts
646 // below there is no point at which interruption could leave it running.
647 yield* Effect.acquireRelease(
648 permit.take(1),
649 () =>
650 Effect.ensuring(
651 Effect.suspend(() => {
652 if (query === undefined) return Effect.void
653 // Destroying the stream resumes a paused connection, so the
654 // remaining rows are read and discarded while the statement is
655 // killed. Rows that were already buffered are replayed
656 // synchronously and can settle the statement before `destroy`
657 // returns, in which case nothing is killed.
658 query.destroy()
659 return statement.cancel
660 }),
661 release
662 ),
663 { interruptible: true }
664 )
665 const command = (conn as any).query(sql, params)
666 query = command.stream()
667 // The command, unlike its stream, reports when the server is done with the
668 // statement, even after the stream has been destroyed.
669 const settle = () => {
670 if (statement.settle()) Effect.runSync(release)
671 }
672 command.once("end", settle)
673 command.once("error", settle)
674
675 let buffer: Array<any> = []
676 let taskPending = false
677 query.on(
678 "error",
679 (cause: unknown) =>
680 emit.fail(new SqlError({ reason: classifyError(cause, "Failed to stream statement", "stream") }))
681 )
682 query.on("data", (row: any) => {
683 buffer.push(row)
684 if (!taskPending) {
685 taskPending = true
686 queueMicrotask(() => {
687 const items = buffer
688 buffer = []
689 emit.array(items)
690 taskPending = false
691 })
692 }
693 })
694 query.on("end", () => {
695 if (buffer.length > 0) {
696 emit.array(buffer)
697 buffer = []
698 }
699 emit.end()
700 })
701
702 return {
703 onPause() {
704 query.pause()
705 },
706 onResume() {
707 query.resume()
708 }
709 }
710 }))
711}