'How to insert multiple records into postgres database using go-pg

I went through the documentation to insert multiple records into postgres using the package pg https://pkg.go.dev/github.com/go-pg/pg/v10#example-DB.Model-BulkInsert .

db := modelDB()

book1 := &Book{
    Title: "new book 1",
}
book2 := &Book{
    Title: "new book 2",
}
_, err := db.Model(book1, book2).Insert()
if err != nil {
    panic(err)
}
fmt.Println(book1, book2)

Honestly i dont like this solution since it does not allow me to pass an array of books. Cause the use case i have is that i wont know the number of books i need to insert.

Should i be using transactions here cause i might have to insert more than 20 record at once. If yes, please help as am not finding good examples for this one.

PS: Must use pg library.



Solution 1:[1]

Just put your book, in array of slices, and insert it, go-pg support insert batch

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kai - Kazuya Ito