hello everyone. I am very new to prisma. when I us...
# orm-help
b
hello everyone. I am very new to prisma. when I use transaction. I met some problems. look at the test code
Copy code
const prisma = new PrismaClient();
prisma.$use(async (params, next) => {
  console.log('runInTransaction: ' + params.runInTransaction)
  const result = next(params);
  return result;
})

async function test1() {
  return await prisma.$transaction(async prisma => {
    return await prisma.user.create({
      data: {
        name: '3333',
        id: 3,
        email: '<mailto:asa@gmail.com|asa@gmail.com>'
      },
    });
  })
}

async function test2() {
  return await prisma.$transaction(async prisma => {
    const r = await prisma.user.update({
      data: {
        name: '4444',
      },
      where: {
        id: 4
      }
    });
    return r;
  });
}

async function main() {
  return await prisma.$transaction(async prisma => {
    let t1 = await test1(); // throw an error
    let t2 = await test2(); // put test2 in the first.
    console.log(t1);
    console.log(t2);
  })
}
the record which id=3 has been existed in the database, so the code will be executed throw an error. no data in database will be changed. but when I change the order test1() and test2() function.
Copy code
async function main() {
  return await prisma.$transaction(async prisma => {
    let t2 = await test2(); // put test2 in the first.
    let t1 = await test1(); // throw an error
    console.log(t1);
    console.log(t2);
  })
}
the record which id=3 has been updated in database. although the test1 throw an error. so this is the question, why the transaction is not rollback. I know I use nested transaction.
Copy code
async function main() {
    return await prisma.$transaction(async prisma => {
      try {
        // id = 3 existed in database so it will be an error
         await prisma.user.create({
          data: {
            name: '3333',
            id: 3,
            email: '<mailto:asa@gmail.com|asa@gmail.com>'
          },
        });
      } catch (error) {
        
      }
  
      await prisma.user.update({
        data: {
          name: '4444',
        },
        where: {
          id: 4
        }
      });
  
    })
  }
I use try catch around the create(id=3). just in one transaction . the transaction also not rollback. if remove try catch block the transaction works well. It is not same with JAVA. in java no matter use try catch or not . the transaction will be rollback. so I am very confused now. does the transaction have hooks like "afterCommmit" "afterRollback"?