steebchen / prisma-client-go

Prisma Client Go is an auto-generated and fully type-safe database client
https://goprisma.org
Apache License 2.0
2.13k stars 95 forks source link

Batch Transactions #539

Closed TheBeachMaster closed 3 years ago

TheBeachMaster commented 3 years ago

Suppose say I have 100 records I want to insert to the DB, the js doc explains of createMany.

Also, there's a mention of transactions API. The examples for 2 inserts seems trivial.

In my example it seems very unnecessary to manually write 100 createOne statements, so I tried a hack(which failed): here's the pseudocode <- I AM FAIRLY NEW IN GO

vars :=make([]db.statesUniqueTxResult,0) // NOTE that this already fails because statesUniqueTxResult is NOT EXPORTED

// then loop over my data
for _,s := range statesInfo{
m := dbClient.State.CreateOne(...).Tx()
vars =append(vars, m) // m will have the same values, but this is an example - Go is not Groovy that supports dynamic vars
}
//Finally
if err := dbClient.Prisma.Transaction(vars...).Exec(ctx); err != nil {
    panic(err)
}

How would you advise one to handle batch inserts...?

steebchen commented 3 years ago

You should be able to use var ops []transaction.Param from github.com/prisma/prisma-client-go/runtime/transaction. This will need to be added to the docs.

TheBeachMaster commented 3 years ago

Nice, I'll close this once I have successfully tested this.

TheBeachMaster commented 3 years ago

This actually worked... Thanks @steebchen

Soln:

import "github.com/prisma/prisma-client-go/runtime/transaction"
// ...
ops := make([]transaction.Param, 0)

// ... statesInfo 

for _,s := range statesInfo{
m := dbClient.State.CreateOne(
  db.State.Name.Set(s.Name),
  db.State.Capital.Set(s.Capital),
).Tx()

ops = append(ops, m) 
}

if err := dbClient.Prisma.Transaction(ops...).Exec(ctx); err != nil {
    panic(err)
}