ants icon indicating copy to clipboard operation
ants copied to clipboard

How do I call database insert operation using ants

Open kiranupadhyak opened this issue 3 years ago • 2 comments

I have a for loop, which inserts data into the 2 different tables. How can I use ants in this case.


for _, row := range rows {
 user := User{}
 user.Name = row.Name
 user.Email = row.Email
 err := dm.Insert(&user)
 if err != nil {
  panic(err)
 }
 address := Address{}
 address.Address1 = row.Address1
 address.Address2 = row.Address2
 address.PinCode = row.PinCode
 address.City = row.City
 err := dm.Insert(&address)
 if err != nil {
  panic(err)
 }
}

kiranupadhyak avatar Nov 08 '21 20:11 kiranupadhyak

@kiranupadhyak Can you share more details about your use case, eg: why you want to use ant for db inserts ? In ant order of function invocation by worker is not deterministic. Can it cause problems if you are expecting some order during insert ?

May be you can use ants.NewPoolWithFunc

abhipranay avatar Nov 09 '21 18:11 abhipranay

u can try this: first u can declare a func() chan:

task:=make(chan func())

then use for range receive the task :

go func() { for t:=range task { ants.Submit(t) } }

last:

for _, row := range rows { f:=func() { user := User{} user.Name = row.Name user.Email = row.Email err := dm.Insert(&user) if err != nil { panic(err) } address := Address{} address.Address1 = row.Address1 address.Address2 = row.Address2 address.PinCode = row.PinCode address.City = row.City err := dm.Insert(&address) if err != nil { panic(err) } } task<- f }

yunduansing avatar Mar 10 '22 07:03 yunduansing