MCPcopy Create free account
hub / github.com/Effect-TS/effect / makeBatch

Function makeBatch

packages/sql/d1/src/D1Client.ts:130–190  ·  view source on GitHub ↗
(options: {
  readonly db: D1Database
  readonly prepareCache: Cache.Cache<string, D1PreparedStatement, SqlError>
  readonly spanAttributes: ReadonlyArray<readonly [string, unknown]>
  readonly getClient: () => D1Client
})

Source from the content-addressed store, hash-verified

128}
129
130const makeBatch = (options: {
131 readonly db: D1Database
132 readonly prepareCache: Cache.Cache<string, D1PreparedStatement, SqlError>
133 readonly spanAttributes: ReadonlyArray<readonly [string, unknown]>
134 readonly getClient: () => D1Client
135}): D1Client["batch"] =>
136<const Statements extends ReadonlyArray<Statement.Statement<any>>>(
137 statements: Statements
138) => {
139 if (statements.length === 0) {
140 return Effect.succeed([] as unknown as BatchResults<Statements>)
141 }
142 return Effect.useSpan(
143 "sql.execute",
144 { kind: "client" },
145 (span) =>
146 Effect.withFiber(Effect.fnUntraced(function*(fiber) {
147 const transformer = fiber.getRef(Statement.CurrentTransformer)
148 const prepared: Array<D1PreparedStatement> = []
149 const transforms: Array<TransformRows | undefined> = []
150 const queryTexts: Array<string> = []
151
152 for (const original of statements) {
153 const statement = transformer === undefined
154 ? original
155 : yield* transformer(original, options.getClient(), fiber, span)
156 const [sql, params] = statement.compile()
157 queryTexts.push(sql)
158 transforms.push((statement as StatementWithTransformRows).transformRows)
159 prepared.push((yield* Cache.get(options.prepareCache, sql)).bind(...params))
160 }
161
162 for (const [key, value] of options.spanAttributes) {
163 span.attribute(key, value)
164 }
165 span.attribute(ATTR_DB_OPERATION_NAME, "batch")
166 span.attribute(ATTR_DB_QUERY_TEXT, queryTexts.join("; "))
167
168 // D1 batches execute on the binding directly and intentionally cannot participate in SqlClient transactions.
169 const responses = yield* Effect.tryPromise({
170 try: () =>
171 options.db.batch<Record<string, unknown>>(prepared).then((responses) => {
172 for (const response of responses) {
173 if (response.error) {
174 throw response.error
175 }
176 }
177 return responses
178 }),
179 catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute batch", "execute") })
180 })
181
182 const results = responses.map((response, index) => {
183 const rows = response.results || []
184 const transformRows = transforms[index]
185 return transformRows ? transformRows(rows) : rows
186 })
187 return results as BatchResults<Statements>

Callers 1

makeFunction · 0.85

Calls 10

transformerFunction · 0.85
getRefMethod · 0.80
compileMethod · 0.80
pushMethod · 0.80
joinMethod · 0.80
classifyErrorFunction · 0.70
getMethod · 0.65
attributeMethod · 0.65
succeedMethod · 0.45
mapMethod · 0.45

Tested by

no test coverage detected