@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 860 lines 28.6 KB
Raw
1 /**
2 * Microsoft SQL Server client implementation for Effect SQL, backed by the
3 * `tedious` driver.
4 *
5 * This module provides the `MssqlClient` service, constructors, layers, and SQL
6 * Server statement compiler. `make` creates a pooled Tedious client, checks the
7 * connection with `SELECT 1`, maps SQL Server failures to `SqlError`, and
8 * supports transactions with savepoints. The SQL Server-specific service adds
9 * typed Tedious parameters with `param`, stored procedure calls with `call`,
10 * direct or config-backed layers, and default parameter type mappings.
11 * Streaming queries are not implemented by this driver.
12 *
13 * @stability unstable
14 * @since 4.0.0
15 */
16 import * as Config from "effect/Config"
17 import * as Context from "effect/Context"
18 import * as Deferred from "effect/Deferred"
19 import * as Duration from "effect/Duration"
20 import * as Effect from "effect/Effect"
21 import { identity } from "effect/Function"
22 import * as Layer from "effect/Layer"
23 import * as Option from "effect/Option"
24 import * as Pool from "effect/Pool"
25 import * as Reactivity from "effect/reactivity/Reactivity"
26 import * as Rec from "effect/Record"
27 import * as Redacted from "effect/Redacted"
28 import type * as Scope from "effect/Scope"
29 import * as Client from "effect/sql/SqlClient"
30 import type { Connection } from "effect/sql/SqlConnection"
31 import {
32 AuthenticationError,
33 AuthorizationError,
34 ConnectionError,
35 ConstraintError,
36 DeadlockError,
37 LockTimeoutError,
38 SerializationError,
39 SqlError,
40 SqlSyntaxError,
41 UniqueViolation,
42 UnknownError
43 } from "effect/sql/SqlError"
44 import * as Statement from "effect/sql/Statement"
45 import * as Stream from "effect/Stream"
46 import { Buffer } from "node:buffer"
47 import * as Tedious from "tedious"
48 import type { ConnectionOptions } from "tedious/lib/connection.ts"
49 import type { DataType } from "tedious/lib/data-type.ts"
50 import type { ParameterOptions } from "tedious/lib/request.ts"
51 import type { Parameter } from "./Parameter.ts"
52 import type * as Procedure from "./Procedure.ts"
53
54 const ATTR_DB_SYSTEM_NAME = "db.system.name"
55 const ATTR_DB_NAMESPACE = "db.namespace"
56 const ATTR_SERVER_ADDRESS = "server.address"
57 const ATTR_SERVER_PORT = "server.port"
58
59 const mssqlNumberFromCause = (cause: unknown): number | undefined => {
60 if (typeof cause !== "object" || cause === null || !("number" in cause)) {
61 return undefined
62 }
63 const number = cause.number
64 return typeof number === "number" ? number : undefined
65 }
66
67 const mssqlConnectionErrorCodes = new Set([233, 10054])
68 const mssqlAuthenticationErrorCodes = new Set([4060, 18452, 18456])
69 const mssqlAuthorizationErrorCodes = new Set([229, 230, 262, 297, 300])
70 const mssqlSyntaxErrorCodes = new Set([102, 207, 208, 2714])
71 const mssqlConstraintErrorCodes = new Set([515, 547])
72
73 const UNKNOWN_CONSTRAINT = "unknown"
74
75 const normalizeConstraintIdentifier = (identifier: unknown): string => {
76 if (typeof identifier !== "string") {
77 return UNKNOWN_CONSTRAINT
78 }
79 const trimmed = identifier.trim()
80 return trimmed.length === 0 ? UNKNOWN_CONSTRAINT : trimmed
81 }
82
83 const mssqlCauseProperty = (cause: unknown, property: "constraint" | "message"): unknown => {
84 if (typeof cause !== "object" || cause === null || !(property in cause)) {
85 return undefined
86 }
87 return (cause as Record<string, unknown>)[property]
88 }
89
90 const mssqlUniqueViolationConstraintFromMessage = (number: 2601 | 2627, message: unknown): string => {
91 if (typeof message !== "string") {
92 return UNKNOWN_CONSTRAINT
93 }
94 const match = number === 2627 ?
95 /\bconstraint\s+'([^']*)'/i.exec(message) :
96 /\bunique index\s+'([^']*)'/i.exec(message)
97 return match === null ? UNKNOWN_CONSTRAINT : normalizeConstraintIdentifier(match[1])
98 }
99
100 const mssqlUniqueViolationConstraintFromCause = (number: 2601 | 2627, cause: unknown): string => {
101 const constraint = normalizeConstraintIdentifier(mssqlCauseProperty(cause, "constraint"))
102 if (constraint !== UNKNOWN_CONSTRAINT) {
103 return constraint
104 }
105 return mssqlUniqueViolationConstraintFromMessage(number, mssqlCauseProperty(cause, "message"))
106 }
107
108 const classifyError = (
109 cause: unknown,
110 message: string,
111 operation: string,
112 fallback: "connection" | "unknown" = "unknown"
113 ) => {
114 const props = { cause, message, operation }
115 const number = mssqlNumberFromCause(cause)
116 if (number !== undefined) {
117 if (mssqlConnectionErrorCodes.has(number)) {
118 return new ConnectionError(props)
119 }
120 if (mssqlAuthenticationErrorCodes.has(number)) {
121 return new AuthenticationError(props)
122 }
123 if (mssqlAuthorizationErrorCodes.has(number)) {
124 return new AuthorizationError(props)
125 }
126 if (mssqlSyntaxErrorCodes.has(number)) {
127 return new SqlSyntaxError(props)
128 }
129 if (number === 2601 || number === 2627) {
130 return new UniqueViolation({ ...props, constraint: mssqlUniqueViolationConstraintFromCause(number, cause) })
131 }
132 if (mssqlConstraintErrorCodes.has(number)) {
133 return new ConstraintError(props)
134 }
135 if (number === 1205) {
136 return new DeadlockError(props)
137 }
138 if (number === 3960) {
139 return new SerializationError(props)
140 }
141 if (number === 1222) {
142 return new LockTimeoutError(props)
143 }
144 }
145 return fallback === "connection" ? new ConnectionError(props) : new UnknownError(props)
146 }
147
148 /**
149 * Runtime type identifier used to mark `MssqlClient` values.
150 *
151 * @stability unstable
152 * @category type IDs
153 * @since 4.0.0
154 */
155 export const TypeId: unique symbol = Symbol.for("@effect/sql-mssql/MssqlClient")
156
157 /**
158 * Type-level identifier used to mark `MssqlClient` values.
159 *
160 * @stability unstable
161 * @category type IDs
162 * @since 4.0.0
163 */
164 export type TypeId = typeof TypeId
165
166 /**
167 * Microsoft SQL Server client service, extending `SqlClient` with typed parameter fragments and stored procedure calls.
168 *
169 * @stability unstable
170 * @category services
171 * @since 4.0.0
172 */
173 export interface MssqlClient extends Client.SqlClient {
174 readonly [TypeId]: TypeId
175
176 readonly config: MssqlClientConfig
177
178 /**
179 * Creates a statement parameter with an explicit `tedious` data type.
180 *
181 * @stability unstable
182 */
183 readonly param: (
184 type: DataType,
185 value: unknown,
186 options?: ParameterOptions
187 ) => Statement.Fragment
188
189 readonly call: <
190 I extends Record<string, Parameter<any>>,
191 O extends Record<string, Parameter<any>>,
192 A extends object
193 >(
194 procedure: Procedure.ProcedureWithValues<I, O, A>
195 ) => Effect.Effect<Procedure.Procedure.Result<O, A>, SqlError>
196 }
197
198 /**
199 * Service tag for the Microsoft SQL Server client service.
200 *
201 * **When to use**
202 *
203 * Use to access or provide a Microsoft SQL Server client through the Effect
204 * context.
205 *
206 * @stability unstable
207 * @category services
208 * @since 4.0.0
209 */
210 export const MssqlClient = Context.Service<MssqlClient>("@effect/sql-mssql/MssqlClient")
211
212 /**
213 * Configuration for a Microsoft SQL Server client, including connection, authentication, pool, parameter type, span attribute, and query/result name transform options.
214 *
215 * @stability unstable
216 * @category models
217 * @since 4.0.0
218 */
219 export interface MssqlClientConfig {
220 readonly domain?: string | undefined
221 readonly server: string
222 readonly instanceName?: string | undefined
223 /**
224 * Whether to encrypt traffic between the client and server. Defaults to `true`. Setting this to `false` disables transport encryption and transmits credentials in cleartext.
225 */
226 readonly encrypt?: boolean | undefined
227 /**
228 * Whether to trust the server certificate without validating it. Defaults to `false`. Setting this to `true` disables TLS certificate validation.
229 */
230 readonly trustServer?: boolean | undefined
231 readonly port?: number | undefined
232 readonly authType?: string | undefined
233 readonly database?: string | undefined
234 readonly username?: string | undefined
235 readonly password?: Redacted.Redacted | undefined
236 readonly connectTimeout?: Duration.Input | undefined
237 /**
238 * How long Tedious waits for the server to acknowledge a cancelled request
239 * before it closes the connection. Defaults to 5 seconds. Interrupting a
240 * request waits for that acknowledgement, so a zero duration (which disables
241 * the timer) leaves interruption unbounded rather than making it faster.
242 */
243 readonly cancelTimeout?: Duration.Input | undefined
244 readonly connectionRetryInterval?: Duration.Input | undefined
245 readonly multiSubnetFailover?: boolean | undefined
246 readonly maxRetriesOnTransientErrors?: number | undefined
247
248 readonly minConnections?: number | undefined
249 readonly maxConnections?: number | undefined
250 readonly connectionTTL?: Duration.Input | undefined
251
252 /**
253 * Overrides the `tedious` data type used for each primitive parameter kind.
254 *
255 * @stability unstable
256 */
257 readonly parameterTypes?: Record<Statement.PrimitiveKind, DataType> | undefined
258
259 readonly spanAttributes?: Record<string, unknown> | undefined
260
261 readonly transformResultNames?: ((str: string) => string) | undefined
262 readonly transformQueryNames?: ((str: string) => string) | undefined
263 }
264
265 interface MssqlConnection extends Connection {
266 readonly call: (
267 procedure: Procedure.ProcedureWithValues<any, any, any>,
268 transformRows: ((rows: ReadonlyArray<any>) => ReadonlyArray<any>) | undefined
269 ) => Effect.Effect<any, SqlError>
270
271 readonly begin: Effect.Effect<void, SqlError>
272 readonly commit: Effect.Effect<void, SqlError>
273 readonly savepoint: (name: string) => Effect.Effect<void, SqlError>
274 readonly rollback: (name?: string) => Effect.Effect<void, SqlError>
275 }
276
277 const TransactionConnection = Client.TransactionConnection as unknown as (clientId: number) => Context.Service<
278 readonly [conn: MssqlConnection, counter: number],
279 readonly [conn: MssqlConnection, counter: number]
280 >
281
282 let clientIdCounter = 0
283
284 /**
285 * Creates a scoped Microsoft SQL Server client backed by a connection pool, with transaction and stored procedure support. Streaming queries are not implemented.
286 *
287 * @stability unstable
288 * @category constructors
289 * @since 4.0.0
290 */
291 export const make = (
292 options: MssqlClientConfig
293 ): Effect.Effect<MssqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> =>
294 Effect.gen(function*() {
295 const parameterTypes = options.parameterTypes ?? defaultParameterTypes
296 const compiler = makeCompiler(options.transformQueryNames)
297
298 const transformRows = options.transformResultNames ?
299 Statement.defaultTransforms(
300 options.transformResultNames
301 ).array :
302 undefined
303 const spanAttributes: ReadonlyArray<[string, unknown]> = [
304 ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
305 [ATTR_DB_SYSTEM_NAME, "microsoft.sql_server"],
306 [ATTR_DB_NAMESPACE, options.database ?? "master"],
307 [ATTR_SERVER_ADDRESS, options.server],
308 [ATTR_SERVER_PORT, options.port ?? 1433]
309 ]
310
311 // oxlint-disable-next-line prefer-const
312 let pool: Pool.Pool<MssqlConnection, SqlError>
313 const connectionEnded = new WeakMap<MssqlConnection, Deferred.Deferred<void>>()
314 // Invalidation can run before acquisition publishes the pool item. Check
315 // the latch on every lease so an early event cannot leave it reusable.
316 const acquireConnection: Effect.Effect<MssqlConnection, SqlError, Scope.Scope> = Effect.suspend(() =>
317 Effect.flatMap(Pool.get(pool), (connection) =>
318 Deferred.isDoneUnsafe(connectionEnded.get(connection)!)
319 ? Effect.andThen(Pool.invalidate(pool, connection), acquireConnection)
320 : Effect.succeed(connection))
321 )
322
323 const makeConnection = Effect.gen(function*() {
324 const conn = new Tedious.Connection({
325 options: {
326 port: options.port,
327 database: options.database,
328 trustServerCertificate: options.trustServer ?? false,
329 multiSubnetFailover: options.multiSubnetFailover,
330 connectTimeout: options.connectTimeout
331 ? Duration.toMillis(Duration.fromInputUnsafe(options.connectTimeout))
332 : undefined,
333 rowCollectionOnRequestCompletion: true,
334 useColumnNames: false,
335 instanceName: options.instanceName,
336 encrypt: options.encrypt ?? true,
337 cancelTimeout: options.cancelTimeout
338 ? Duration.toMillis(Duration.fromInputUnsafe(options.cancelTimeout))
339 : undefined,
340 connectionRetryInterval: options.connectionRetryInterval
341 ? Duration.toMillis(Duration.fromInputUnsafe(options.connectionRetryInterval))
342 : undefined,
343 maxRetriesOnTransientErrors: options.maxRetriesOnTransientErrors
344 } as ConnectionOptions,
345 server: options.server,
346 authentication: {
347 type: (options.authType as any) ?? "default",
348 options: {
349 domain: options.domain,
350 userName: options.username,
351 password: options.password
352 ? Redacted.value(options.password)
353 : undefined
354 }
355 }
356 })
357
358 const ended = Deferred.makeUnsafe<void>()
359 let closing = false
360 let endEmitted = false
361 const onError = () => {
362 Deferred.doneUnsafe(ended, Effect.void)
363 }
364 const removeListeners = () => {
365 // Tedious can emit a queued error after end, even once pool cleanup
366 // has closed the connection. Keep onError for the connection lifetime.
367 conn.removeListener("end", onEnd)
368 }
369 const onEnd = () => {
370 endEmitted = true
371 Deferred.doneUnsafe(ended, Effect.void)
372 if (closing) removeListeners()
373 }
374
375 // Install before connect and keep the error handler through asynchronous
376 // close. The latch also records events before the pool item exists.
377 conn.on("error", onError)
378 conn.on("end", onEnd)
379 yield* Effect.addFinalizer(() =>
380 Effect.sync(() => {
381 closing = true
382 conn.close()
383 if (endEmitted) removeListeners()
384 })
385 )
386
387 yield* Effect.callback<void, SqlError>((resume) => {
388 conn.connect((cause) => {
389 if (cause) {
390 resume(
391 Effect.fail(new SqlError({ reason: classifyError(cause, "Failed to connect", "connect", "connection") }))
392 )
393 } else {
394 resume(Effect.void)
395 }
396 })
397 })
398
399 // Tedious calls a request back once it is settled: completed, cancelled
400 // by the server, or failed when the connection ends or the cancellation
401 // times out. Interruption cancels the request and waits for that callback
402 // so the connection is not released while it is still SentClientRequest.
403 const request = <A>(
404 start: (resume: (effect: Effect.Effect<A, SqlError>) => void) => void
405 ) =>
406 Effect.callback<A, SqlError>((resume) => {
407 let settled = false
408 let onSettled: (() => void) | undefined
409 start((effect) => {
410 // A request that failed because the connection closed settles
411 // before tedious emits end. Record it now, before resuming can
412 // release the connection back to the pool.
413 if (conn.closed) Deferred.doneUnsafe(ended, Effect.void)
414 settled = true
415 resume(effect)
416 onSettled?.()
417 })
418 return Effect.callback<void>((done) => {
419 if (settled) return done(Effect.void)
420 onSettled = () => done(Effect.void)
421 conn.cancel()
422 })
423 })
424
425 const run = (
426 sql: string,
427 values?: ReadonlyArray<any>,
428 rowsAsArray = false
429 ) =>
430 request<any>((resume) => {
431 const req = new Tedious.Request(sql, (cause, _rowCount, result) => {
432 if (cause) {
433 resume(
434 Effect.fail(new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") }))
435 )
436 return
437 }
438
439 if (rowsAsArray) {
440 result = result.map((row: any) => row.map((_: any) => _.value))
441 } else {
442 result = rowsToObjects(result)
443 }
444
445 resume(Effect.succeed(result))
446 })
447
448 if (values) {
449 for (let i = 0, len = values.length; i < len; i++) {
450 const value = values[i]
451 const name = numberToParamName(i)
452
453 if (isMssqlParam(value)) {
454 req.addParameter(name, value.paramA, value.paramB, value.paramC)
455 } else {
456 const kind = Statement.primitiveKind(value)
457 const type = parameterTypes[kind]
458 req.addParameter(name, type, value)
459 }
460 }
461 }
462
463 conn.execSql(req)
464 })
465
466 const runProcedure = (
467 procedure: Procedure.ProcedureWithValues<any, any, any>,
468 transformRows: ((rows: ReadonlyArray<any>) => ReadonlyArray<any>) | undefined
469 ) =>
470 request<any>((resume) => {
471 const result: Record<string, any> = {}
472
473 const req = new Tedious.Request(
474 escape(procedure.name),
475 (cause, _, rows) => {
476 if (cause) {
477 resume(
478 Effect.fail(new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") }))
479 )
480 } else {
481 rows = rowsToObjects(rows)
482 if (transformRows) {
483 rows = transformRows(rows) as any
484 }
485 resume(
486 Effect.succeed({
487 output: result,
488 rows
489 })
490 )
491 }
492 }
493 )
494
495 for (const name in procedure.params) {
496 const param = procedure.params[name]
497 const value = procedure.values[name]
498 req.addParameter(name, param.type, value, param.options)
499 }
500
501 for (const name in procedure.outputParams) {
502 const param = procedure.outputParams[name]
503 req.addOutputParameter(name, param.type, undefined, param.options)
504 }
505
506 req.on("returnValue", (name, value) => {
507 Rec.assignProperty(result, name, value)
508 })
509
510 conn.callProcedure(req)
511 })
512
513 const connection = identity<MssqlConnection>({
514 execute(sql, params, transformRows) {
515 return transformRows
516 ? Effect.map(run(sql, params), transformRows)
517 : run(sql, params)
518 },
519 executeRaw(sql, params) {
520 return run(sql, params)
521 },
522 executeValues(sql, params) {
523 return run(sql, params, true)
524 },
525 executeValuesUnprepared(sql, params) {
526 return run(sql, params, true)
527 },
528 executeUnprepared(sql, params, transformRows) {
529 return this.execute(sql, params, transformRows)
530 },
531 executeStream() {
532 return Stream.die("executeStream not implemented")
533 },
534 call(procedure, transformRows) {
535 return runProcedure(procedure, transformRows)
536 },
537 begin: Effect.callback<void, SqlError>((resume) => {
538 conn.beginTransaction((cause) => {
539 if (cause) {
540 resume(
541 Effect.fail(
542 new SqlError({
543 reason: classifyError(cause, "Failed to begin transaction", "beginTransaction")
544 })
545 )
546 )
547 } else {
548 resume(Effect.void)
549 }
550 })
551 }),
552 commit: Effect.callback<void, SqlError>((resume) => {
553 conn.commitTransaction((cause) => {
554 if (cause) {
555 resume(
556 Effect.fail(
557 new SqlError({
558 reason: classifyError(cause, "Failed to commit transaction", "commitTransaction")
559 })
560 )
561 )
562 } else {
563 resume(Effect.void)
564 }
565 })
566 }),
567 savepoint: (name: string) =>
568 Effect.callback<void, SqlError>((resume) => {
569 conn.saveTransaction((cause) => {
570 if (cause) {
571 resume(
572 Effect.fail(
573 new SqlError({ reason: classifyError(cause, "Failed to create savepoint", "createSavepoint") })
574 )
575 )
576 } else {
577 resume(Effect.void)
578 }
579 }, name)
580 }),
581 rollback: (name?: string) =>
582 Effect.callback<void, SqlError>((resume) => {
583 conn.rollbackTransaction((cause) => {
584 if (cause) {
585 resume(
586 Effect.fail(
587 new SqlError({
588 reason: classifyError(cause, "Failed to rollback transaction", "rollbackTransaction")
589 })
590 )
591 )
592 } else {
593 resume(Effect.void)
594 }
595 }, name)
596 })
597 })
598
599 connectionEnded.set(connection, ended)
600 yield* Deferred.await(ended).pipe(
601 Effect.andThen(Effect.suspend(() => pool ? Pool.invalidate(pool, connection) : Effect.void)),
602 Effect.interruptible,
603 Effect.forkScoped
604 )
605
606 return connection
607 })
608
609 pool = yield* Pool.makeWithTTL({
610 acquire: makeConnection,
611 min: options.minConnections ?? 1,
612 max: options.maxConnections ?? 10,
613 timeToLive: options.connectionTTL ?? Duration.minutes(45),
614 timeToLiveStrategy: "creation"
615 })
616
617 yield* acquireConnection.pipe(
618 Effect.tap((connection) => connection.executeUnprepared("SELECT 1", [], undefined)),
619 Effect.mapError((cause) =>
620 new SqlError({ reason: classifyError(cause, "MssqlClient: Failed to connect", "connect", "connection") })
621 ),
622 Effect.scoped,
623 Effect.timeoutOrElse({
624 duration: options.connectTimeout ?? Duration.seconds(5),
625 orElse: () =>
626 Effect.fail(
627 new SqlError({
628 reason: new ConnectionError({
629 message: "MssqlClient: Connection timeout",
630 cause: new Error("connection timeout"),
631 operation: "connect"
632 })
633 })
634 )
635 })
636 )
637
638 const transactionService = TransactionConnection(clientIdCounter++)
639 // Inside `withTransaction`, statements and procedures use its connection.
640 const getConnection = Effect.flatMap(
641 Effect.serviceOption(transactionService),
642 Option.match({
643 onNone: () => acquireConnection,
644 onSome: ([conn]) => Effect.succeed(conn)
645 })
646 )
647
648 const withTransaction = Client.makeWithTransaction({
649 transactionService,
650 spanAttributes,
651 acquireConnection: (restore) => restore(acquireConnection),
652 begin: (conn) => conn.begin,
653 savepoint: (conn, id) => conn.savepoint(`effect_sql_${id}`),
654 commit: (conn) => conn.commit,
655 rollback: (conn) => conn.rollback(),
656 rollbackSavepoint: (conn, id) => conn.rollback(`effect_sql_${id}`)
657 })
658
659 return identity<MssqlClient>(Object.assign(
660 yield* Client.make({
661 driver: "mssql",
662 acquirer: acquireConnection,
663 compiler,
664 transactionService: transactionService as any,
665 spanAttributes,
666 transformRows
667 }),
668 {
669 [TypeId]: TypeId as TypeId,
670 config: options,
671 withTransaction,
672 param: (
673 type: DataType,
674 value: unknown,
675 options: ParameterOptions = {}
676 ) => Statement.fragment([mssqlParam(type, value, options)]),
677 call: <
678 I extends Record<string, Parameter<any>>,
679 O extends Record<string, Parameter<any>>,
680 A
681 >(
682 procedure: Procedure.ProcedureWithValues<I, O, A>
683 ) => Effect.scoped(Effect.flatMap(getConnection, (_) => _.call(procedure, transformRows))),
684 withoutTransforms() {
685 const statement = Statement.make(getConnection, compiler.withoutTransform, spanAttributes, undefined)
686 const client = Object.assign(
687 statement,
688 this,
689 statement,
690 {
691 call: <
692 I extends Record<string, Parameter<any>>,
693 O extends Record<string, Parameter<any>>,
694 A
695 >(
696 procedure: Procedure.ProcedureWithValues<I, O, A>
697 ) => Effect.scoped(Effect.flatMap(getConnection, (_) => _.call(procedure, undefined)))
698 }
699 )
700 ;(client as any).safe = client
701 ;(client as any).withoutTransforms = () => client
702 return client
703 }
704 }
705 ))
706 })
707
708 /**
709 * Creates a layer from a `Config`-wrapped SQL Server client configuration, providing both `MssqlClient` and `SqlClient`.
710 *
711 * @stability unstable
712 * @category layers
713 * @since 4.0.0
714 */
715 export const layerConfig: (
716 config: Config.Wrap<MssqlClientConfig>
717 ) => Layer.Layer<Client.SqlClient | MssqlClient, Config.ConfigError | SqlError> = (
718 config: Config.Wrap<MssqlClientConfig>
719 ): Layer.Layer<Client.SqlClient | MssqlClient, Config.ConfigError | SqlError> =>
720 Layer.effectContext(
721 Config.unwrap(config).pipe(
722 Effect.flatMap(make),
723 Effect.map((client) =>
724 Context.make(MssqlClient, client).pipe(
725 Context.add(Client.SqlClient, client)
726 )
727 )
728 )
729 ).pipe(Layer.provide(Reactivity.layer))
730
731 /**
732 * Creates a layer from a concrete SQL Server client configuration, providing both `MssqlClient` and `SqlClient`.
733 *
734 * @stability unstable
735 * @category layers
736 * @since 4.0.0
737 */
738 export const layer = (
739 config: MssqlClientConfig
740 ): Layer.Layer<Client.SqlClient | MssqlClient, never | SqlError> =>
741 Layer.effectContext(
742 Effect.map(make(config), (client) =>
743 Context.make(MssqlClient, client).pipe(
744 Context.add(Client.SqlClient, client)
745 ))
746 ).pipe(Layer.provide(Reactivity.layer))
747
748 /**
749 * Creates the SQL Server statement compiler, using `@1`-style placeholders, bracket-escaped identifiers, and SQL Server `OUTPUT INSERTED` returning clauses.
750 *
751 * @stability unstable
752 * @category constructors
753 * @since 4.0.0
754 */
755 export const makeCompiler = (transform?: (_: string) => string) =>
756 Statement.makeCompiler<MssqlCustom>({
757 dialect: "mssql",
758 placeholder(_) {
759 return `@${numberToParamName(_ - 1)}`
760 },
761 onIdentifier: transform ?
762 function(value, withoutTransform) {
763 return withoutTransform ? escape(value) : escape(transform(value))
764 } :
765 escape,
766 onRecordUpdate(placeholders, valueAlias, valueColumns, values, returning) {
767 const returningSql = returning ? returning[0] === "*" ? "OUTPUT INSERTED.* " : `OUTPUT ${returning[0]} ` : ""
768 return [
769 `${returningSql}FROM (values ${placeholders}) AS ${valueAlias}${valueColumns}`,
770 returning ?
771 returning[1].concat(values.flat()) :
772 values.flat()
773 ]
774 },
775 onCustom(type, placeholder) {
776 switch (type.kind) {
777 case "MssqlParam": {
778 return [placeholder(undefined), [type] as any]
779 }
780 }
781 },
782 onInsert(columns, placeholders, values, returning) {
783 const returningSql = returning ? returning[0] === "*" ? " OUTPUT INSERTED.*" : ` OUTPUT ${returning[0]}` : ""
784 return [
785 `(${columns.join(",")})${returningSql} VALUES ${placeholders}`,
786 returning ?
787 returning[1].concat(values.flat()) :
788 values.flat()
789 ]
790 }
791 })
792
793 // compiler helpers
794
795 const escape = (str: string) => "[" + str.replace(/\]/g, "]]").replace(/\./g, "].[") + "]"
796
797 function numberToParamName(n: number) {
798 return `${Math.ceil(n + 1)}`
799 }
800
801 const byteArrayParameterType: DataType = {
802 ...Tedious.TYPES.VarBinary,
803 validate(value, collation, options) {
804 return Tedious.TYPES.VarBinary.validate(
805 Buffer.isBuffer(value) ? value : Buffer.from(value.buffer, value.byteOffset, value.byteLength),
806 collation,
807 options
808 )
809 }
810 }
811
812 /**
813 * Default mapping from Effect SQL primitive value kinds to Tedious SQL Server parameter data types.
814 *
815 * @stability unstable
816 * @category constants
817 * @since 4.0.0
818 */
819 export const defaultParameterTypes: Record<Statement.PrimitiveKind, DataType> = {
820 string: Tedious.TYPES.NVarChar,
821 number: Tedious.TYPES.Float,
822 bigint: Tedious.TYPES.BigInt,
823 boolean: Tedious.TYPES.Bit,
824 Date: Tedious.TYPES.DateTime,
825 Uint8Array: byteArrayParameterType,
826 Int8Array: byteArrayParameterType,
827 null: Tedious.TYPES.Bit
828 }
829
830 // custom types
831
832 type MssqlCustom = MssqlParam
833
834 interface MssqlParam extends
835 Statement.Custom<
836 "MssqlParam",
837 DataType,
838 unknown,
839 ParameterOptions
840 >
841 {}
842
843 const mssqlParam = Statement.custom<MssqlParam>("MssqlParam")
844 const isMssqlParam = Statement.isCustom<MssqlParam>("MssqlParam")
845
846 function rowsToObjects(rows: ReadonlyArray<any>) {
847 const newRows = new Array(rows.length)
848
849 for (let i = 0, len = rows.length; i < len; i++) {
850 const row = rows[i]
851 const newRow: any = {}
852 for (let j = 0, columnLen = row.length; j < columnLen; j++) {
853 const column = row[j]
854 Rec.assignProperty(newRow, column.metadata.colName, column.value)
855 }
856 newRows[i] = newRow
857 }
858
859 return newRows
860 }