I'm using the createUsers
func to populate my fake DB, just for tests.
I'm using the bulk imports feature of pq
(https://godoc.org/github.com/lib/pq#hdr-Bulk_imports).
func createUsers() {
users := []models.User{}
for i := 0; i < 10; i++ {
users = append(users, models.User{Username: "username"+i, Age: i})
}
connStr := "user=postgres password=postgres dbname=dbname sslmode=disable"
DB, err = sql.Open("postgres", connStr)
checkErr(err)
txn, err := DB.Begin()
checkErr(err)
stmt, err := txn.Prepare(pq.CopyIn("users", "username", "age"))
checkErr(err)
for _, user := range users {
_, err = stmt.Exec(user.Username, user.Age)
checkErr(err)
}
_, err = stmt.Exec()
checkErr(err)
err = stmt.Close()
checkErr(err)
err = txn.Commit()
checkErr(err)
}
Everything in this code is working good.
THE NEED:
What I need now is to make it "general", not just for User model.
I think I need something like:
DBBulkInsert(users, "users", "username", "age")
with func DBBulkInsert
like:
func DBBulkInsert(rows []interface{}, tableName string, tableColumns ...string) {
// DB var from connection func
txn, err := DB.Begin()
checkErr(err)
stmt, err := txn.Prepare(pq.CopyIn(tableName, tableColumns...))
checkErr(err)
for _, row := range rows {
_, err = stmt.Exec(row[0], row[1]) //THIS IS TOTALLY WRONG! WHAT TO DO HERE?
checkErr(err)
}
_, err = stmt.Exec()
checkErr(err)
err = stmt.Close()
checkErr(err)
err = txn.Commit()
checkErr(err)
}
THE PROBLEM:
Obviously _, err = stmt.Exec(row[0], row[1])
is totally wrong. I don't understand how to call DBBulkInsert
with my users array.
STILL BETTER:
Maybe I can remove also the parameters "users", "username", "age"
in DBBulkInsert(users, "users", "username", "age")
, but how? Reflection?