Run SQL script in Go directly from file or line

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()
+4
2

, , . , database/sql. , , - ( , ).

, , SQL . , , .

golang :

: rambler. , , .

+4

. ( ).

, database/sql . , python script ( sql_runner.py), , exec exec python script ( ).

, python SQL : cursor.execute(open("setting_up.sql"), "r").read())

Go :

cmd := exec.Command("sql.py")

cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
log.Println(cmd.Run())
+1

All Articles