diff --git a/.changeset/seven-foxes-perform.md b/.changeset/seven-foxes-perform.md new file mode 100644 index 0000000000..f40ac2306e --- /dev/null +++ b/.changeset/seven-foxes-perform.md @@ -0,0 +1,15 @@ +--- +"@effect/sql-sqlite-react-native": minor +"@effect/sql-sqlite-node": minor +"@effect/sql-sqlite-wasm": minor +"@effect/sql-clickhouse": minor +"@effect/sql-sqlite-bun": minor +"@effect/sql-libsql": minor +"@effect/sql-mysql2": minor +"@effect/sql-mssql": minor +"@effect/sql-d1": minor +"@effect/sql-pg": minor +"@effect/sql": minor +--- + +allow cloning a SqlClient with transforms disabled diff --git a/packages/sql-clickhouse/src/ClickhouseClient.ts b/packages/sql-clickhouse/src/ClickhouseClient.ts index 4effe74cbf..f078e59c7e 100644 --- a/packages/sql-clickhouse/src/ClickhouseClient.ts +++ b/packages/sql-clickhouse/src/ClickhouseClient.ts @@ -15,7 +15,7 @@ import type { ConfigError } from "effect/ConfigError" import * as Context from "effect/Context" import * as Effect from "effect/Effect" import * as FiberRef from "effect/FiberRef" -import { dual, identity } from "effect/Function" +import { dual } from "effect/Function" import { globalValue } from "effect/GlobalValue" import * as Layer from "effect/Layer" import type * as Scope from "effect/Scope" @@ -91,7 +91,7 @@ export const make = ( const compiler = makeCompiler(options.transformQueryNames) const transformRows = options.transformResultNames ? Statement.defaultTransforms(options.transformResultNames).array - : identity + : undefined const client = Clickhouse.createClient(options) @@ -165,28 +165,29 @@ export const make = ( ) } - private runTransform(sql: string, params: ReadonlyArray) { - return options.transformResultNames + execute( + sql: string, + params: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined + ) { + return transformRows ? Effect.map(this.run(sql, params), transformRows) : this.run(sql, params) } - - execute(sql: string, params: ReadonlyArray) { - return this.runTransform(sql, params) - } executeRaw(sql: string, params: ReadonlyArray) { return this.runRaw(sql, params) } - executeWithoutTransform(sql: string, params: ReadonlyArray) { - return this.run(sql, params) - } executeValues(sql: string, params: ReadonlyArray) { return this.run(sql, params, "JSONCompact") } - executeUnprepared(sql: string, params?: ReadonlyArray) { - return this.runTransform(sql, params ?? []) + executeUnprepared(sql: string, params: ReadonlyArray, transformRows?: any) { + return this.execute(sql, params, transformRows) } - executeStream(sql: string, params: ReadonlyArray) { + executeStream( + sql: string, + params: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined + ) { return this.runRaw(sql, params, "JSONEachRow").pipe( Effect.map((result) => { if (!("stream" in result)) { @@ -207,7 +208,8 @@ export const make = ( } } return Effect.tryPromise({ - try: () => Promise.all(promises).then((rows) => Chunk.unsafeFromArray(transformRows(rows))), + try: () => + Promise.all(promises).then((rows) => Chunk.unsafeFromArray(transformRows ? transformRows(rows) : rows)), catch: (cause) => new SqlError({ cause, message: "Failed to parse row" }) }) }), @@ -227,7 +229,8 @@ export const make = ( [Otel.SEMATTRS_DB_SYSTEM, "clickhouse"], [Otel.SEMATTRS_DB_NAME, options.database ?? "default"] ], - beginTransaction: "BEGIN TRANSACTION" + beginTransaction: "BEGIN TRANSACTION", + transformRows }), { [TypeId]: TypeId as TypeId, diff --git a/packages/sql-d1/src/D1Client.ts b/packages/sql-d1/src/D1Client.ts index cc567b97e4..7c8e59f3e4 100644 --- a/packages/sql-d1/src/D1Client.ts +++ b/packages/sql-d1/src/D1Client.ts @@ -70,9 +70,9 @@ export const make = ( ): Effect.Effect => Effect.gen(function*() { const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) - const transformRows = Statement.defaultTransforms( - options.transformResultNames! - ).array + const transformRows = options.transformResultNames ? + Statement.defaultTransforms(options.transformResultNames).array : + undefined const makeConnection = Effect.gen(function*() { const db = options.db @@ -90,7 +90,7 @@ export const make = ( const runStatement = ( statement: D1PreparedStatement, params: ReadonlyArray = [] - ) => + ): Effect.Effect, SqlError, never> => Effect.tryPromise({ try: async () => { const response = await statement.bind(...params).all() @@ -115,12 +115,7 @@ export const make = ( const runUncached = ( sql: string, params: ReadonlyArray = [] - ) => Effect.map(runRaw(sql, params), transformRows) - - const runTransform = options.transformResultNames - ? (sql: string, params?: ReadonlyArray) => - Effect.map(runCached(sql, params), transformRows) - : runCached + ) => runRaw(sql, params) const runValues = ( sql: string, @@ -142,8 +137,10 @@ export const make = ( ) return identity({ - execute(sql, params) { - return runTransform(sql, params) + execute(sql, params, transformRows) { + return transformRows + ? Effect.map(runCached(sql, params), transformRows) + : runCached(sql, params) }, executeRaw(sql, params) { return runRaw(sql, params) @@ -151,11 +148,10 @@ export const make = ( executeValues(sql, params) { return runValues(sql, params) }, - executeWithoutTransform(sql, params) { - return runCached(sql, params) - }, - executeUnprepared(sql, params) { - return runUncached(sql, params) + executeUnprepared(sql, params, transformRows) { + return transformRows + ? Effect.map(runUncached(sql, params), transformRows) + : runUncached(sql, params) }, executeStream(_sql, _params) { return Effect.dieMessage("executeStream not implemented") @@ -175,7 +171,8 @@ export const make = ( spanAttributes: [ ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), [Otel.SEMATTRS_DB_SYSTEM, Otel.DBSYSTEMVALUES_SQLITE] - ] + ], + transformRows }) as D1Client, { [TypeId]: TypeId as TypeId, diff --git a/packages/sql-libsql/src/LibsqlClient.ts b/packages/sql-libsql/src/LibsqlClient.ts index 76aedf7b0a..13a7032cd9 100644 --- a/packages/sql-libsql/src/LibsqlClient.ts +++ b/packages/sql-libsql/src/LibsqlClient.ts @@ -135,9 +135,11 @@ export const make = ( ): Effect.Effect => Effect.gen(function*() { const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) - const transformRows = Statement.defaultTransforms( - options.transformResultNames! - ).array + const transformRows = options.transformResultNames ? + Statement.defaultTransforms( + options.transformResultNames + ).array : + undefined const spanAttributes: Array<[string, unknown]> = [ ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), @@ -170,29 +172,27 @@ export const make = ( }) } - runTransform( + execute( sql: string, - params: ReadonlyArray = [] + params: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined ) { - return options.transformResultNames + return transformRows ? Effect.map(this.run(sql, params), transformRows) : this.run(sql, params) } - - execute(sql: string, params: ReadonlyArray) { - return this.runTransform(sql, params) - } executeRaw(sql: string, params: ReadonlyArray) { return this.runRaw(sql, params) } executeValues(sql: string, params: ReadonlyArray) { return Effect.map(this.run(sql, params), (rows) => rows.map((row) => Array.from(row) as Array)) } - executeWithoutTransform(sql: string, params: ReadonlyArray) { - return this.run(sql, params) - } - executeUnprepared(sql: string, params?: ReadonlyArray) { - return this.run(sql, params) + executeUnprepared( + sql: string, + params: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined + ) { + return this.execute(sql, params, transformRows) } executeStream() { return Effect.dieMessage("executeStream not implemented") @@ -264,7 +264,8 @@ export const make = ( Client.make({ acquirer, compiler, - spanAttributes + spanAttributes, + transformRows }), { [TypeId]: TypeId as TypeId, diff --git a/packages/sql-mssql/src/MssqlClient.ts b/packages/sql-mssql/src/MssqlClient.ts index 54c7e45ceb..ed40e93167 100644 --- a/packages/sql-mssql/src/MssqlClient.ts +++ b/packages/sql-mssql/src/MssqlClient.ts @@ -96,7 +96,8 @@ export interface MssqlClientConfig { interface MssqlConnection extends Connection { readonly call: ( - procedure: Procedure.ProcedureWithValues + procedure: Procedure.ProcedureWithValues, + transformRows: ((rows: ReadonlyArray) => ReadonlyArray) | undefined ) => Effect.Effect readonly begin: Effect.Effect @@ -121,9 +122,11 @@ export const make = ( const parameterTypes = options.parameterTypes ?? defaultParameterTypes const compiler = makeCompiler(options.transformQueryNames) - const transformRows = Statement.defaultTransforms( - options.transformResultNames! - ).array + const transformRows = options.transformResultNames ? + Statement.defaultTransforms( + options.transformResultNames + ).array : + undefined const spanAttributes: ReadonlyArray<[string, unknown]> = [ ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), [Otel.SEMATTRS_DB_SYSTEM, Otel.DBSYSTEMVALUES_MSSQL], @@ -176,7 +179,6 @@ export const make = ( const run = ( sql: string, values?: ReadonlyArray, - transform = true, rowsAsArray = false ) => Effect.async((resume) => { @@ -190,10 +192,6 @@ export const make = ( result = result.map((row: any) => row.map((_: any) => _.value)) } else { result = rowsToObjects(result) - - if (transform && options.transformResultNames) { - result = transformRows(result) as any - } } resume(Effect.succeed(result)) @@ -218,7 +216,10 @@ export const make = ( conn.execSql(req) }) - const runProcedure = (procedure: Procedure.ProcedureWithValues) => + const runProcedure = ( + procedure: Procedure.ProcedureWithValues, + transformRows: ((rows: ReadonlyArray) => ReadonlyArray) | undefined + ) => Effect.async((resume) => { const result: Record = {} @@ -229,7 +230,7 @@ export const make = ( resume(Effect.fail(new SqlError({ cause, message: "Failed to execute statement" }))) } else { rows = rowsToObjects(rows) - if (options.transformResultNames) { + if (transformRows) { rows = transformRows(rows) as any } resume( @@ -262,26 +263,25 @@ export const make = ( }) const connection = identity({ - execute(sql, params) { - return run(sql, params) + execute(sql, params, transformRows) { + return transformRows + ? Effect.map(run(sql, params), transformRows) + : run(sql, params) }, executeRaw(sql, params) { - return run(sql, params, false) - }, - executeWithoutTransform(sql, params) { - return run(sql, params, false) + return run(sql, params) }, executeValues(sql, params) { - return run(sql, params, true, true) + return run(sql, params, true) }, - executeUnprepared(sql, params) { - return run(sql, params) + executeUnprepared(sql, params, transformRows) { + return this.execute(sql, params, transformRows) }, executeStream() { return Effect.dieMessage("executeStream not implemented") }, - call: (procedure) => { - return runProcedure(procedure) + call(procedure, transformRows) { + return runProcedure(procedure, transformRows) }, begin: Effect.async((resume) => { conn.beginTransaction((cause) => { @@ -370,7 +370,8 @@ export const make = ( Client.make({ acquirer: pool.get, compiler, - spanAttributes + spanAttributes, + transformRows }), { [TypeId]: TypeId as TypeId, @@ -387,7 +388,27 @@ export const make = ( A >( procedure: Procedure.ProcedureWithValues - ) => Effect.scoped(Effect.flatMap(pool.get, (_) => _.call(procedure))) + ) => Effect.scoped(Effect.flatMap(pool.get, (_) => _.call(procedure, transformRows))), + withoutTransforms() { + const statement = Statement.make(pool.get, compiler.withoutTransform, spanAttributes, undefined) + const client = Object.assign( + statement, + this, + statement, + { + call: < + I extends Record>, + O extends Record>, + A + >( + procedure: Procedure.ProcedureWithValues + ) => Effect.scoped(Effect.flatMap(pool.get, (_) => _.call(procedure, undefined))) + } + ) + ;(client as any).safe = client + ;(client as any).withoutTransforms = () => client + return client + } } )) }) diff --git a/packages/sql-mssql/test/Client.test.ts b/packages/sql-mssql/test/Client.test.ts index 51430f3189..53d140b561 100644 --- a/packages/sql-mssql/test/Client.test.ts +++ b/packages/sql-mssql/test/Client.test.ts @@ -3,7 +3,7 @@ import * as Statement from "@effect/sql/Statement" import { Effect } from "effect" import { describe, expect, it } from "vitest" -const sql = Statement.make(Effect.void as any, MssqlClient.makeCompiler()) +const sql = Statement.make(Effect.void as any, MssqlClient.makeCompiler(), [], undefined) describe("mssql", () => { it("insert helper", () => { diff --git a/packages/sql-mysql2/src/MysqlClient.ts b/packages/sql-mysql2/src/MysqlClient.ts index bb081fa8d6..d46c965b11 100644 --- a/packages/sql-mysql2/src/MysqlClient.ts +++ b/packages/sql-mysql2/src/MysqlClient.ts @@ -82,9 +82,11 @@ export const make = ( ): Effect.Effect => Effect.gen(function*() { const compiler = makeCompiler(options.transformQueryNames) - const transformRows = Statement.defaultTransforms( - options.transformResultNames! - ).array + const transformRows = options.transformResultNames ? + Statement.defaultTransforms( + options.transformResultNames + ).array : + undefined class ConnectionImpl implements Connection { constructor(private readonly conn: Mysql.PoolConnection | Mysql.Pool) {} @@ -113,38 +115,45 @@ export const make = ( private run( sql: string, values?: ReadonlyArray, - transform = true, rowsAsArray = false, method: "execute" | "query" = "execute" ) { return this.runRaw(sql, values, rowsAsArray, method).pipe( - Effect.map((results) => { - if (transform && !rowsAsArray && options.transformResultNames) { - return transformRows(results as ReadonlyArray) - } - return Array.isArray(results) ? results : [] - }) + Effect.map((results) => Array.isArray(results) ? results : []) ) } - execute(sql: string, params: ReadonlyArray) { - return this.run(sql, params) + execute( + sql: string, + params: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined + ) { + return transformRows + ? Effect.map(this.run(sql, params), transformRows) + : this.run(sql, params) } executeRaw(sql: string, params: ReadonlyArray) { - return this.runRaw(sql, params, true) - } - executeWithoutTransform(sql: string, params: ReadonlyArray) { - return this.run(sql, params, false) + return this.runRaw(sql, params) } executeValues(sql: string, params: ReadonlyArray) { - return this.run(sql, params, true, true) + return this.run(sql, params, true) } - executeUnprepared(sql: string, params?: ReadonlyArray) { - return this.run(sql, params, true, false, "query") + executeUnprepared( + sql: string, + params: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined + ) { + return transformRows + ? Effect.map(this.run(sql, params, false, "query"), transformRows) + : this.run(sql, params, false, "query") } - executeStream(sql: string, params: ReadonlyArray) { + executeStream( + sql: string, + params: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined + ) { const stream = queryStream(this.conn as any, sql, params) - return options.transformResultNames + return transformRows ? Stream.mapChunks(stream, (_) => Chunk.unsafeFromArray( transformRows(Chunk.toReadonlyArray(_) as Array) @@ -235,7 +244,8 @@ export const make = ( acquirer: Effect.succeed(poolConnection), transactionAcquirer, compiler, - spanAttributes + spanAttributes, + transformRows }), { [TypeId]: TypeId as TypeId, config: options } ) diff --git a/packages/sql-pg/src/PgClient.ts b/packages/sql-pg/src/PgClient.ts index bac642a86c..3a86d92788 100644 --- a/packages/sql-pg/src/PgClient.ts +++ b/packages/sql-pg/src/PgClient.ts @@ -141,10 +141,12 @@ export const make = ( options.transformQueryNames, options.transformJson ) - const transformRows = Statement.defaultTransforms( - options.transformResultNames!, - options.transformJson - ).array + const transformRows = options.transformResultNames ? + Statement.defaultTransforms( + options.transformResultNames, + options.transformJson + ).array : + undefined const opts: PartialWithUndefined = { max: options.maxConnections ?? 10, @@ -207,14 +209,14 @@ export const make = ( }) } - private runTransform(query: postgres.PendingQuery) { - return options.transformResultNames - ? Effect.map(this.run(query), transformRows) - : this.run(query) - } - - execute(sql: string, params: ReadonlyArray) { - return this.runTransform(this.pg.unsafe(sql, params as any)) + execute( + sql: string, + params: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined + ) { + return transformRows + ? Effect.map(this.run(this.pg.unsafe(sql, params as any)), transformRows) + : this.run(this.pg.unsafe(sql, params as any)) } executeRaw(sql: string, params: ReadonlyArray) { return this.run(this.pg.unsafe(sql, params as any)) @@ -225,10 +227,18 @@ export const make = ( executeValues(sql: string, params: ReadonlyArray) { return this.run(this.pg.unsafe(sql, params as any).values()) } - executeUnprepared(sql: string, params?: ReadonlyArray) { - return this.runTransform(this.pg.unsafe(sql, params as any)) + executeUnprepared( + sql: string, + params: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined + ) { + return this.execute(sql, params, transformRows) } - executeStream(sql: string, params: ReadonlyArray) { + executeStream( + sql: string, + params: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined + ) { return Stream.mapChunks( Stream.fromAsyncIterable( this.pg.unsafe(sql, params as any).cursor(16) as AsyncIterable< @@ -236,11 +246,7 @@ export const make = ( >, (cause) => new SqlError({ cause, message: "Failed to execute statement" }) ), - Chunk.flatMap((rows) => - Chunk.unsafeFromArray( - options.transformResultNames ? transformRows(rows) : rows - ) - ) + Chunk.flatMap((rows) => Chunk.unsafeFromArray(transformRows ? transformRows(rows) : rows)) ) } } @@ -265,7 +271,8 @@ export const make = ( [Otel.SEMATTRS_DB_NAME, opts.database ?? options.username ?? "postgres"], ["server.address", opts.host ?? "localhost"], ["server.port", opts.port ?? 5432] - ] + ], + transformRows }), { [TypeId]: TypeId as TypeId, diff --git a/packages/sql-pg/test/Client.test.ts b/packages/sql-pg/test/Client.test.ts index 14295909f0..32540725d3 100644 --- a/packages/sql-pg/test/Client.test.ts +++ b/packages/sql-pg/test/Client.test.ts @@ -276,3 +276,21 @@ it.layer(PgContainer.ClientLive, { timeout: "30 seconds" })("PgClient", (it) => expect(query).toEqual(`SELECT * from "people_test"`) })) }) + +it.layer(PgContainer.ClientTransformLive, { timeout: "30 seconds" })("PgClient transforms", (it) => { + it.effect("insert helper", () => + Effect.gen(function*() { + const sql = yield* PgClient.PgClient + const [query, params] = sql`INSERT INTO people ${sql.insert({ firstName: "Tim", age: 10 })}`.compile() + expect(query).toEqual(`INSERT INTO people ("first_name","age") VALUES ($1,$2)`) + expect(params).toEqual(["Tim", 10]) + })) + + it.effect("insert helper withoutTransforms", () => + Effect.gen(function*() { + const sql = (yield* PgClient.PgClient).withoutTransforms() + const [query, params] = sql`INSERT INTO people ${sql.insert({ first_name: "Tim", age: 10 })}`.compile() + expect(query).toEqual(`INSERT INTO people ("first_name","age") VALUES ($1,$2)`) + expect(params).toEqual(["Tim", 10]) + })) +}) diff --git a/packages/sql-pg/test/utils.ts b/packages/sql-pg/test/utils.ts index 5ec0db69f8..b7d3c18413 100644 --- a/packages/sql-pg/test/utils.ts +++ b/packages/sql-pg/test/utils.ts @@ -1,6 +1,6 @@ import { PgClient } from "@effect/sql-pg" import { PostgreSqlContainer } from "@testcontainers/postgresql" -import { Data, Effect, Layer, Redacted } from "effect" +import { Data, Effect, Layer, Redacted, String } from "effect" export class ContainerError extends Data.TaggedError("ContainerError")<{ cause: unknown @@ -23,4 +23,15 @@ export class PgContainer extends Effect.Service()("test/MysqlContai }) }) ).pipe(Layer.provide(this.Default)) + + static ClientTransformLive = Layer.unwrapEffect( + Effect.gen(function*() { + const container = yield* PgContainer + return PgClient.layer({ + url: Redacted.make(container.getConnectionUri()), + transformResultNames: String.snakeToCamel, + transformQueryNames: String.camelToSnake + }) + }) + ).pipe(Layer.provide(this.Default)) } diff --git a/packages/sql-sqlite-bun/src/SqliteClient.ts b/packages/sql-sqlite-bun/src/SqliteClient.ts index 7e2072b58f..2aedac76b9 100644 --- a/packages/sql-sqlite-bun/src/SqliteClient.ts +++ b/packages/sql-sqlite-bun/src/SqliteClient.ts @@ -78,9 +78,11 @@ export const make = ( ): Effect.Effect => Effect.gen(function*(_) { const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) - const transformRows = Statement.defaultTransforms( - options.transformResultNames! - ).array + const transformRows = options.transformResultNames ? + Statement.defaultTransforms( + options.transformResultNames + ).array : + undefined const makeConnection = Effect.gen(function*(_) { const db = new Database(options.filename, { @@ -103,10 +105,6 @@ export const make = ( catch: (cause) => new SqlError({ cause, message: "Failed to execute statement" }) }) - const runTransform = options.transformResultNames - ? (sql: string, params?: ReadonlyArray) => Effect.map(run(sql, params), transformRows) - : run - const runValues = ( sql: string, params: ReadonlyArray = [] @@ -117,8 +115,10 @@ export const make = ( }) return identity({ - execute(sql, params) { - return runTransform(sql, params) + execute(sql, params, transformRows) { + return transformRows + ? Effect.map(run(sql, params), transformRows) + : run(sql, params) }, executeRaw(sql, params) { return run(sql, params) @@ -126,11 +126,8 @@ export const make = ( executeValues(sql, params) { return runValues(sql, params) }, - executeWithoutTransform(sql, params) { - return run(sql, params) - }, - executeUnprepared(sql, params) { - return runTransform(sql, params) + executeUnprepared(sql, params, transformRows) { + return this.execute(sql, params, transformRows) }, executeStream(_sql, _params) { return Effect.dieMessage("executeStream not implemented") @@ -172,7 +169,8 @@ export const make = ( spanAttributes: [ ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), [Otel.SEMATTRS_DB_SYSTEM, Otel.DBSYSTEMVALUES_SQLITE] - ] + ], + transformRows }) as SqliteClient, { [TypeId]: TypeId as TypeId, diff --git a/packages/sql-sqlite-node/src/SqliteClient.ts b/packages/sql-sqlite-node/src/SqliteClient.ts index 78ffce4d60..62319f82fa 100644 --- a/packages/sql-sqlite-node/src/SqliteClient.ts +++ b/packages/sql-sqlite-node/src/SqliteClient.ts @@ -90,9 +90,11 @@ export const make = ( ): Effect.Effect => Effect.gen(function*() { const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) - const transformRows = Statement.defaultTransforms( - options.transformResultNames! - ).array + const transformRows = options.transformResultNames ? + Statement.defaultTransforms( + options.transformResultNames + ).array : + undefined const makeConnection = Effect.gen(function*() { const scope = yield* Effect.scope @@ -141,14 +143,6 @@ export const make = ( (s) => runStatement(s, params, raw) ) - const runTransform = options.transformResultNames - ? (sql: string, params: ReadonlyArray) => - Effect.map( - run(sql, params), - transformRows - ) - : run - const runValues = ( sql: string, params: ReadonlyArray @@ -173,8 +167,10 @@ export const make = ( ) return identity({ - execute(sql, params) { - return runTransform(sql, params) + execute(sql, params, transformRows) { + return transformRows + ? Effect.map(run(sql, params), transformRows) + : run(sql, params) }, executeRaw(sql, params) { return run(sql, params, true) @@ -182,14 +178,9 @@ export const make = ( executeValues(sql, params) { return runValues(sql, params) }, - executeWithoutTransform(sql, params) { - return run(sql, params) - }, - executeUnprepared(sql, params) { - return Effect.map( - runStatement(db.prepare(sql), params ?? [], false), - transformRows - ) + executeUnprepared(sql, params, transformRows) { + const effect = runStatement(db.prepare(sql), params ?? [], false) + return transformRows ? Effect.map(effect, transformRows) : effect }, executeStream(_sql, _params) { return Effect.dieMessage("executeStream not implemented") @@ -238,7 +229,8 @@ export const make = ( spanAttributes: [ ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), [Otel.SEMATTRS_DB_SYSTEM, Otel.DBSYSTEMVALUES_SQLITE] - ] + ], + transformRows }) as SqliteClient, { [TypeId]: TypeId as TypeId, diff --git a/packages/sql-sqlite-react-native/src/SqliteClient.ts b/packages/sql-sqlite-react-native/src/SqliteClient.ts index 6494b225ce..d79dca49f3 100644 --- a/packages/sql-sqlite-react-native/src/SqliteClient.ts +++ b/packages/sql-sqlite-react-native/src/SqliteClient.ts @@ -113,9 +113,9 @@ export const make = ( } const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) - const transformRows = Statement.defaultTransforms( - options.transformResultNames! - ).array + const transformRows = options.transformResultNames ? + Statement.defaultTransforms(options.transformResultNames).array : + undefined const makeConnection = Effect.gen(function*(_) { const db = Sqlite.open(clientOptions) @@ -141,13 +141,11 @@ export const make = ( }) }) - const runTransform = options.transformResultNames - ? (sql: string, params?: ReadonlyArray) => Effect.map(run(sql, params), transformRows) - : run - return identity({ - execute(sql, params) { - return runTransform(sql, params) + execute(sql, params, transformRows) { + return transformRows + ? Effect.map(run(sql, params), transformRows) + : run(sql, params) }, executeRaw(sql, params) { return run(sql, params) @@ -161,11 +159,8 @@ export const make = ( return results.map((row) => columns.map((column) => row[column])) }) }, - executeWithoutTransform(sql, params) { - return run(sql, params) - }, - executeUnprepared(sql, params) { - return runTransform(sql, params) + executeUnprepared(sql, params, transformRows) { + return this.execute(sql, params, transformRows) }, executeStream() { return Effect.dieMessage("executeStream not implemented") @@ -180,7 +175,7 @@ export const make = ( const [query, params] = statement.compile() return Queue.sliding>(1).pipe( Effect.tap((queue) => - this.execute(query, params).pipe( + this.execute(query, params, undefined).pipe( Effect.flatMap((rows) => queue.offer(rows)) ) ), @@ -233,7 +228,8 @@ export const make = ( spanAttributes: [ ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), [Otel.SEMATTRS_DB_SYSTEM, Otel.DBSYSTEMVALUES_SQLITE] - ] + ], + transformRows }) as SqliteClient, { [TypeId]: TypeId, diff --git a/packages/sql-sqlite-wasm/src/SqliteClient.ts b/packages/sql-sqlite-wasm/src/SqliteClient.ts index 3076a5cd64..39dc24bea2 100644 --- a/packages/sql-sqlite-wasm/src/SqliteClient.ts +++ b/packages/sql-sqlite-wasm/src/SqliteClient.ts @@ -10,6 +10,7 @@ import * as WaSqlite from "@effect/wa-sqlite" import SQLiteESMFactory from "@effect/wa-sqlite/dist/wa-sqlite.mjs" import { MemoryVFS } from "@effect/wa-sqlite/src/examples/MemoryVFS.js" import * as Otel from "@opentelemetry/semantic-conventions" +import { Chunk } from "effect" import * as Config from "effect/Config" import type { ConfigError } from "effect/ConfigError" import * as Context from "effect/Context" @@ -20,8 +21,6 @@ import * as FiberRef from "effect/FiberRef" import { identity } from "effect/Function" import { globalValue } from "effect/GlobalValue" import * as Layer from "effect/Layer" -import type * as Mailbox from "effect/Mailbox" -import type { ReadonlyRecord } from "effect/Record" import * as Scope from "effect/Scope" import * as ScopedRef from "effect/ScopedRef" import * as Stream from "effect/Stream" @@ -46,14 +45,6 @@ export type TypeId = typeof TypeId export interface SqliteClient extends Client.SqlClient { readonly [TypeId]: TypeId readonly config: SqliteClientMemoryConfig - readonly reactive: ( - keys: ReadonlyArray | ReadonlyRecord>, - effect: Effect.Effect - ) => Stream.Stream - readonly reactiveMailbox: ( - keys: ReadonlyArray | ReadonlyRecord>, - effect: Effect.Effect - ) => Effect.Effect, E, R | Scope.Scope> readonly export: Effect.Effect readonly import: (data: Uint8Array) => Effect.Effect @@ -115,9 +106,11 @@ export const makeMemory = ( Effect.gen(function*() { const reactivity = yield* Reactivity.Reactivity const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) - const transformRows = Statement.defaultTransforms( - options.transformResultNames! - ).array + const transformRows = options.transformResultNames ? + Statement.defaultTransforms( + options.transformResultNames + ).array : + undefined const makeConnection = Effect.gen(function*() { const sqlite3 = yield* initEffect @@ -175,13 +168,11 @@ export const makeMemory = ( catch: (cause) => new SqlError({ cause, message: "Failed to execute statement" }) }) - const runTransform = options.transformResultNames - ? (sql: string, params?: ReadonlyArray) => Effect.map(run(sql, params), transformRows) - : run - return identity({ - execute(sql, params) { - return runTransform(sql, params) + execute(sql, params, transformRows) { + return transformRows + ? Effect.map(run(sql, params), transformRows) + : run(sql, params) }, executeRaw(sql, params) { return run(sql, params) @@ -189,31 +180,31 @@ export const makeMemory = ( executeValues(sql, params) { return run(sql, params, "array") }, - executeWithoutTransform(sql, params) { - return run(sql, params) + executeUnprepared(sql, params, transformRows) { + return this.execute(sql, params, transformRows) }, - executeUnprepared(sql, params) { - return runTransform(sql, params) - }, - executeStream(sql, params) { - return Stream.fromIterableEffect(Effect.try({ - *try() { - for (const stmt of sqlite3.statements(db, sql)) { - let columns: Array | undefined - sqlite3.bind_collection(stmt, params as any) - while (sqlite3.step(stmt) === WaSqlite.SQLITE_ROW) { - columns = columns ?? sqlite3.column_names(stmt) - const row = sqlite3.row(stmt) - const obj: Record = {} - for (let i = 0; i < columns.length; i++) { - obj[columns[i]] = row[i] - } - yield obj + executeStream(sql, params, transformRows) { + function* stream() { + for (const stmt of sqlite3.statements(db, sql)) { + let columns: Array | undefined + sqlite3.bind_collection(stmt, params as any) + while (sqlite3.step(stmt) === WaSqlite.SQLITE_ROW) { + columns = columns ?? sqlite3.column_names(stmt) + const row = sqlite3.row(stmt) + const obj: Record = {} + for (let i = 0; i < columns.length; i++) { + obj[columns[i]] = row[i] } + yield obj } - }, - catch: (cause) => new SqlError({ cause, message: "Failed to execute statement" }) - })) + } + } + return Stream.suspend(() => Stream.fromIteratorSucceed(stream()[Symbol.iterator]())).pipe( + transformRows + ? Stream.mapChunks((chunk) => Chunk.unsafeFromArray(transformRows(Chunk.toReadonlyArray(chunk)))) + : identity, + Stream.mapError((cause) => new SqlError({ cause, message: "Failed to execute statement" })) + ) }, export: Effect.try({ try: () => sqlite3.serialize(db, "main"), @@ -253,13 +244,12 @@ export const makeMemory = ( spanAttributes: [ ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), [Otel.SEMATTRS_DB_SYSTEM, Otel.DBSYSTEMVALUES_SQLITE] - ] + ], + transformRows }) as SqliteClient, { [TypeId]: TypeId as TypeId, config: options, - reactive: reactivity.stream, - reactiveMailbox: reactivity.query, export: semaphore.withPermits(1)(connection.export), import(data: Uint8Array) { return semaphore.withPermits(1)(connection.import(data)) @@ -278,9 +268,9 @@ export const make = ( Effect.gen(function*() { const reactivity = yield* Reactivity.Reactivity const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) - const transformRows = Statement.defaultTransforms( - options.transformResultNames! - ).array + const transformRows = options.transformResultNames ? + Statement.defaultTransforms(options.transformResultNames).array : + undefined const pending = new Map) => void>() const makeConnection = Effect.gen(function*() { @@ -357,13 +347,11 @@ export const make = ( : Effect.map(rows, extractRows) } - const runTransform = options.transformResultNames - ? (sql: string, params?: ReadonlyArray) => Effect.map(run(sql, params), transformRows) - : run - return identity({ - execute(sql, params) { - return runTransform(sql, params) + execute(sql, params, transformRows) { + return transformRows + ? Effect.map(run(sql, params), transformRows) + : run(sql, params) }, executeRaw(sql, params) { return run(sql, params) @@ -371,11 +359,8 @@ export const make = ( executeValues(sql, params) { return run(sql, params, "array") }, - executeWithoutTransform(sql, params) { - return run(sql, params) - }, - executeUnprepared(sql, params) { - return runTransform(sql, params) + executeUnprepared(sql, params, transformRows) { + return this.execute(sql, params, transformRows) }, executeStream() { return Effect.dieMessage("executeStream not implemented") @@ -418,13 +403,12 @@ export const make = ( spanAttributes: [ ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), [Otel.SEMATTRS_DB_SYSTEM, Otel.DBSYSTEMVALUES_SQLITE] - ] + ], + transformRows }) as SqliteClient, { [TypeId]: TypeId as TypeId, config: options, - reactive: reactivity.stream, - reactiveMailbox: reactivity.query, export: Effect.flatMap(acquirer, (connection) => connection.export), import(data: Uint8Array) { return Effect.flatMap(acquirer, (connection) => connection.import(data)) diff --git a/packages/sql/src/SqlClient.ts b/packages/sql/src/SqlClient.ts index 5409425d47..b800b8b628 100644 --- a/packages/sql/src/SqlClient.ts +++ b/packages/sql/src/SqlClient.ts @@ -34,6 +34,11 @@ export interface SqlClient extends Constructor { */ readonly safe: this + /** + * Copy of the client without transformations. + */ + readonly withoutTransforms: () => this + readonly reserve: Effect /** @@ -69,6 +74,7 @@ export namespace SqlClient { readonly commit?: string | undefined readonly savepoint?: ((name: string) => string) | undefined readonly rollbackSavepoint?: ((name: string) => string) | undefined + readonly transformRows?: ((row: ReadonlyArray) => ReadonlyArray) | undefined } } @@ -76,15 +82,7 @@ export namespace SqlClient { * @category constructors * @since 1.0.0 */ -export const make: ({ - acquirer, - beginTransaction, - commit, - rollback, - rollbackSavepoint, - savepoint, - transactionAcquirer -}: SqlClient.MakeOptions) => SqlClient = internal.make +export const make: (options: SqlClient.MakeOptions) => SqlClient = internal.make /** * @since 1.0.0 diff --git a/packages/sql/src/SqlConnection.ts b/packages/sql/src/SqlConnection.ts index c083419c6e..74b92349aa 100644 --- a/packages/sql/src/SqlConnection.ts +++ b/packages/sql/src/SqlConnection.ts @@ -15,7 +15,8 @@ import type { Primitive } from "./Statement.js" export interface Connection { readonly execute: ( sql: string, - params: ReadonlyArray + params: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined ) => Effect, SqlError> /** @@ -29,14 +30,10 @@ export interface Connection { readonly executeStream: ( sql: string, - params: ReadonlyArray + params: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined ) => Stream - readonly executeWithoutTransform: ( - sql: string, - params: ReadonlyArray - ) => Effect, SqlError> - readonly executeValues: ( sql: string, params: ReadonlyArray @@ -44,7 +41,8 @@ export interface Connection { readonly executeUnprepared: ( sql: string, - params?: ReadonlyArray | undefined + params: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined ) => Effect, SqlError> } diff --git a/packages/sql/src/Statement.ts b/packages/sql/src/Statement.ts index 0c57dde09d..f6586590e0 100644 --- a/packages/sql/src/Statement.ts +++ b/packages/sql/src/Statement.ts @@ -381,7 +381,8 @@ export interface Constructor { export const make: ( acquirer: Connection.Acquirer, compiler: Compiler, - spanAttributes?: ReadonlyArray + spanAttributes: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined ) => Constructor = internal.make /** @@ -434,6 +435,7 @@ export interface Compiler { statement: Fragment, withoutTransform: boolean ) => readonly [sql: string, params: ReadonlyArray] + readonly withoutTransform: this } /** diff --git a/packages/sql/src/internal/client.ts b/packages/sql/src/internal/client.ts index 7a3c344480..8d60e91492 100644 --- a/packages/sql/src/internal/client.ts +++ b/packages/sql/src/internal/client.ts @@ -34,7 +34,8 @@ export function make({ rollbackSavepoint = (id) => `ROLLBACK TO SAVEPOINT ${id}`, savepoint = (id) => `SAVEPOINT ${id}`, spanAttributes, - transactionAcquirer + transactionAcquirer, + transformRows }: Client.SqlClient.MakeOptions): Client.SqlClient { const getConnection = Effect.flatMap( Effect.serviceOption(TransactionConnection), @@ -52,20 +53,33 @@ export function make({ Scope.make(), (scope) => Effect.map(Scope.extend(transactionAcquirer, scope), (conn) => [scope, conn] as const) ), - begin: (conn) => conn.executeUnprepared(beginTransaction), - savepoint: (conn, id) => conn.executeUnprepared(savepoint(`effect_sql_${id}`)), - commit: (conn) => conn.executeUnprepared(commit), - rollback: (conn) => conn.executeUnprepared(rollback), - rollbackSavepoint: (conn, id) => conn.executeUnprepared(rollbackSavepoint(`effect_sql_${id}`)) + begin: (conn) => conn.executeUnprepared(beginTransaction, [], undefined), + savepoint: (conn, id) => conn.executeUnprepared(savepoint(`effect_sql_${id}`), [], undefined), + commit: (conn) => conn.executeUnprepared(commit, [], undefined), + rollback: (conn) => conn.executeUnprepared(rollback, [], undefined), + rollbackSavepoint: (conn, id) => conn.executeUnprepared(rollbackSavepoint(`effect_sql_${id}`), [], undefined) }) const client: Client.SqlClient = Object.assign( - Statement.make(getConnection, compiler, spanAttributes), + Statement.make(getConnection, compiler, spanAttributes, transformRows), { [TypeId as Client.TypeId]: TypeId as Client.TypeId, safe: undefined as any, withTransaction, - reserve: transactionAcquirer + reserve: transactionAcquirer, + withoutTransforms(): any { + if (transformRows === undefined) { + return this + } + const statement = Statement.make(getConnection, compiler.withoutTransform, spanAttributes, undefined) + const client = Object.assign(statement, { + ...this, + ...statement + }) + ;(client as any).safe = client + ;(client as any).withoutTransforms = () => client + return client + } } ) ;(client as any).safe = client diff --git a/packages/sql/src/internal/statement.ts b/packages/sql/src/internal/statement.ts index 416e9d4a32..e5b41a2336 100644 --- a/packages/sql/src/internal/statement.ts +++ b/packages/sql/src/internal/statement.ts @@ -73,7 +73,12 @@ const withStatement = ( return f(self) } return Effect.flatMap( - transform.value(self, make(self.acquirer, self.compiler), fiber.getFiberRefs(), span) as Effect.Effect< + transform.value( + self, + make(self.acquirer, self.compiler, self.spanAttributes, self.transformRows), + fiber.getFiberRefs(), + span + ) as Effect.Effect< StatementPrimitive >, f @@ -92,7 +97,8 @@ export class StatementPrimitive extends Effectable.Class, Er readonly segments: ReadonlyArray, readonly acquirer: Connection.Connection.Acquirer, readonly compiler: Statement.Compiler, - readonly spanAttributes: ReadonlyArray + readonly spanAttributes: ReadonlyArray, + readonly transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined ) { super() } @@ -125,7 +131,7 @@ export class StatementPrimitive extends Effectable.Class, Er get withoutTransform(): Effect.Effect, Error.SqlError> { return this.withConnection( "executeWithoutTransform", - (connection, sql, params) => connection.executeWithoutTransform(sql, params), + (connection, sql, params) => connection.execute(sql, params, undefined), true ) } @@ -149,7 +155,7 @@ export class StatementPrimitive extends Effectable.Class, Er } span.attribute(Otel.SEMATTRS_DB_OPERATION, "executeStream") span.attribute(Otel.SEMATTRS_DB_STATEMENT, sql) - return Effect.map(this.acquirer, (_) => _.executeStream(sql, params)) + return Effect.map(this.acquirer, (_) => _.executeStream(sql, params, this.transformRows)) }) )) } @@ -164,7 +170,7 @@ export class StatementPrimitive extends Effectable.Class, Er get unprepared(): Effect.Effect, Error.SqlError> { return this.withConnection( "executeUnprepared", - (connection, sql, params) => connection.executeUnprepared(sql, params) + (connection, sql, params) => connection.executeUnprepared(sql, params, this.transformRows) ) } @@ -172,7 +178,10 @@ export class StatementPrimitive extends Effectable.Class, Er return this.compiler.compile(this, withoutTransform ?? false) } commit(): Effect.Effect, Error.SqlError> { - return this.withConnection("execute", (connection, sql, params) => connection.execute(sql, params)) + return this.withConnection( + "execute", + (connection, sql, params) => connection.execute(sql, params, this.transformRows) + ) } toJSON() { const [sql, params] = this.compile() @@ -283,17 +292,22 @@ const isHelper = (u: unknown): u is Statement.Helper => const constructorCache = globalValue( "@effect/sql/Statement/constructorCache", - () => new WeakMap() + () => ({ + transforms: new WeakMap(), + noTransforms: new WeakMap() + }) ) /** @internal */ export const make = ( acquirer: Connection.Connection.Acquirer, compiler: Statement.Compiler, - spanAttributes: ReadonlyArray = [] + spanAttributes: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined ): Statement.Constructor => { - if (constructorCache.has(acquirer)) { - return constructorCache.get(acquirer)! + const cache = transformRows === undefined ? constructorCache.noTransforms : constructorCache.transforms + if (cache.has(acquirer)) { + return cache.get(acquirer)! } const self = Object.assign( function sql(strings: unknown, ...args: Array): any { @@ -303,7 +317,8 @@ export const make = ( compiler, strings as TemplateStringsArray, args, - spanAttributes + spanAttributes, + transformRows ) } else if (typeof strings === "string") { return new IdentifierImpl(strings) @@ -320,7 +335,8 @@ export const make = ( [new LiteralImpl(sql, params)], acquirer, compiler, - spanAttributes + spanAttributes, + transformRows ) }, literal(sql: string) { @@ -352,7 +368,7 @@ export const make = ( } ) - constructorCache.set(acquirer, self) + cache.set(acquirer, self) return self } @@ -363,7 +379,8 @@ export const statement = ( compiler: Statement.Compiler, strings: TemplateStringsArray, args: Array, - spanAttributes: ReadonlyArray + spanAttributes: ReadonlyArray, + transformRows: ((row: ReadonlyArray) => ReadonlyArray) | undefined ): Statement.Statement => { const segments: Array = strings[0].length > 0 ? [new LiteralImpl(strings[0])] : [] @@ -385,7 +402,7 @@ export const statement = ( } } - return new StatementPrimitive(segments, acquirer, compiler, spanAttributes) + return new StatementPrimitive(segments, acquirer, compiler, spanAttributes, transformRows) } /** @internal */ @@ -510,7 +527,8 @@ class CompilerImpl implements Statement.Compiler { columns: ReadonlyArray, values: ReadonlyArray, returning: readonly [sql: string, params: ReadonlyArray] | undefined - ) => readonly [sql: string, binds: ReadonlyArray] + ) => readonly [sql: string, binds: ReadonlyArray], + readonly disableTransforms = false ) {} compile( @@ -518,6 +536,7 @@ class CompilerImpl implements Statement.Compiler { withoutTransform = false, placeholderOverride?: (u: unknown) => string ): readonly [sql: string, binds: ReadonlyArray] { + withoutTransform = withoutTransform || this.disableTransforms const cacheSymbol = withoutTransform ? statementCacheNoTransformSymbol : statementCacheSymbol if (cacheSymbol in statement) { return (statement as any)[cacheSymbol] @@ -729,6 +748,19 @@ class CompilerImpl implements Statement.Compiler { } return (statement as any)[cacheSymbol] = result } + + get withoutTransform() { + return new CompilerImpl( + this.dialect, + this.parameterPlaceholder, + this.onIdentifier, + this.onRecordUpdate, + this.onCustom, + this.onInsert, + this.onRecordUpdateSingle, + true + ) as this + } } /** @internal */