4

I am using "database/sql" package in GO. I want to create a table with a dynamic name.

The only way I can think of is-

db.Exec(`CREATE TABLE`+table_name+`;`)

But it is not safe as there can be SQL injection.
Is there a better way to achieve this?

4 Answers 4

5

I don't code in GO, but this would probably be safe for injection:

tx.Prepare(`do $$ begin execute format($f$create table %I()$f$,$1); end; $$;`)

and then

stmt.Exec(table_name)
Sign up to request clarification or add additional context in comments.

Comments

0

We could use QuoteIdentifier

db.Exec(fmt.Sprintf("CREATE TABLE %s", pq.QuoteIdentifier(table)))

Here are the lines from the documentation -

QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to be
used as part of an SQL statement.  
For example:

    tblname := "my_table"
    data := "my_data"
    quoted := pq.QuoteIdentifier(tblname)
    err := db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", quoted), data)

Any double quotes in name will be escaped. 
The quoted identifier will be case sensitive when used in a query.  
If the input string contains a zero byte, the result will be truncated immediately before it.

Comments

-1

Just use placeholders like:

db.Exec("CREATE TABLE $1", "table_name")

wikipedia:

With most development platforms, parameterized statements that work with parameters can be used (sometimes called placeholders or bind variables) instead of embedding user input in the statement. A placeholder can only store a value of the given type and not an arbitrary SQL fragment. Hence the SQL injection would simply be treated as a strange (and probably invalid) parameter value.

1 Comment

From above statement A placeholder can only store a value of the given type and not an arbitrary SQL fragment. table_name is not a value in given case. It gives error- pq: syntax error at or near "$1".
-1

Its just like @Vao Tsun said:

stmt, err := db.Prepare("CREATE TABLE $1")
if err != nil {
    log.Fatal(err)
}
defer stmt.Close()

result, err := stmt.Exec("DB_NAME_HERE")

Go through the original documentation and look at their example as well for clear understanding.

1 Comment

This too gives error- pq: syntax error at or near "$1".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.