In my installation script for my application, I check if db contains any tables. If the database is empty, I have a DML and DDL SQL script I would like to run.
It doesn’t matter that it reads SQL from a separate .sql file, so right now I just put it right in two lines - one for DDL and one for DML - and merged them.
Now my problem is that I get this error when I try to run a script to generate tables and insert data into them using .Exec (sqlStr):
"pq: cannot insert multiple commands into a prepared statement"
I can, of course, make a workaround. Sort of:
sqlStr := sqlDML + sqlDDL
sqlStmtSlice := strings.Split(sqlStr, ";")
for i:= 0; i < len(sqlStmtSlice) i++ {
// Exec() each individual statement!
}
However, I'm not sure I like this method. Of course, there should be a much better way to just load the SQL script from the file and execute the whole batch, right? Did you know?
Ps. PostgreSQL Go, , .
Edit
, , , , , , , :
tx, err := db.Begin()
sqlStr := fmt.Sprintf(sqlDML + sqlDDL)
sqlStmtSlice := strings.Split(sqlStr, ";\r")
if err != nil {
return err
}
defer func() {
_ = tx.Rollback()
}()
for _, q := range sqlStmtSlice {
_, err := tx.Exec(q)
if err != nil {
return err
}
}
err = tx.Commit()