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