@@ -225,8 +225,6 @@ export class BatchService {
225225 data : { id : string ; values : { [ key : string ] : unknown } } [ ]
226226 ) {
227227 const tempTableName = `temp_` + customAlphabet ( 'abcdefghijklmnopqrstuvwxyz' , 10 ) ( ) ;
228- const prisma = this . prismaService . txClient ( ) ;
229-
230228 // 1.create temporary table structure
231229 const createTempTableSchema = this . knex . schema . createTable ( tempTableName , ( table ) => {
232230 table . string ( idFieldName ) . primary ( ) ;
@@ -238,7 +236,6 @@ export class BatchService {
238236 const createTempTableSql = createTempTableSchema
239237 . toQuery ( )
240238 . replace ( 'create table' , 'create temporary table' ) ;
241- await prisma . $executeRawUnsafe ( createTempTableSql ) ;
242239
243240 const { insertTempTableSql, updateRecordSql } = this . dbProvider . executeUpdateRecordsSqlList ( {
244241 dbTableName,
@@ -247,16 +244,28 @@ export class BatchService {
247244 dbFieldNames : schemas . map ( ( s ) => s . dbFieldName ) ,
248245 data,
249246 } ) ;
247+ const dropTempTableSql = this . knex . schema . dropTable ( tempTableName ) . toQuery ( ) ;
250248
251- // 2.initialize temporary table data
252- await prisma . $executeRawUnsafe ( insertTempTableSql ) ;
249+ const prisma = this . prismaService . txClient ( ) ;
253250
254- // 3.update data
255- await wrapWithValidationErrorHandler ( ( ) => prisma . $executeRawUnsafe ( updateRecordSql ) ) ;
251+ const batchOperators = async ( ) => {
252+ // temp table should in one transaction
253+ await prisma . $executeRawUnsafe ( createTempTableSql ) ;
254+ // 2.initialize temporary table data
255+ await prisma . $executeRawUnsafe ( insertTempTableSql ) ;
256+ // 3.update data
257+ await wrapWithValidationErrorHandler ( ( ) => prisma . $executeRawUnsafe ( updateRecordSql ) ) ;
258+ // 4.delete temporary table
259+ await prisma . $executeRawUnsafe ( dropTempTableSql ) ;
260+ } ;
256261
257- // 4.delete temporary table
258- const dropTempTableSql = this . knex . schema . dropTable ( tempTableName ) . toQuery ( ) ;
259- await prisma . $executeRawUnsafe ( dropTempTableSql ) ;
262+ if ( this . cls . get ( 'tx.id' ) ) {
263+ await batchOperators ( ) ;
264+ } else {
265+ await this . prismaService . $transaction ( async ( ) => {
266+ await batchOperators ( ) ;
267+ } ) ;
268+ }
260269 }
261270
262271 private async executeUpdateRecordsInner (
0 commit comments