Search code examples
gopq

How to prepare an INSERT statement with a dynamic table name for the pq driver


How do you use a dynamic table name for a prepared INSERT statement for the pq postgres driver? At the moment I've got a test table with id SERIAL and values TEXT columns, and this statement is failing:

stmt, err := db.Prepare("INSERT INTO $1(values) VALUES($2);")
if err != nil {
    log.Fatal(err)
}

That's failing with:

pq: syntax error at or near "$1"

If I can only use placeholders for values and not table names, is there a way around using Sprintf here? The table name contains a string from user input and although I can sanitize it it will slow down the insert a bit compared to letting Postgres return an error on an prepared statement.


Solution

  • To substitute table name variables, go sql package doesn't yet provide a standard interface (in progress).

    You might be able to use a database driver specific quote function, eg: QuoteIdentifier.

    See also postgres parameter quoting examples.