4

What am i doing wrong here? Tried quoting new_name also , still shows error : pq: syntax error at or near "$1" Postgres + go

func ChangeDBname(new_name string) {

oldname := "intern"
quoted := pq.QuoteIdentifier(oldname)
_, e1 := db.Exec(fmt.Sprintf("ALTER TABLE %s RENAME TO $1",quoted) , new_name)
if e1 != nil {
    fmt.Println("Eroor in change name")
    log.Fatal(e1.Error())
} else {
    fmt.Println("Table name changed to", new_name)
}

}

1
  • 7
    You cannot use parameter placeholders for identifiers. You can use them for values, but not names. You cannot for example use them for table names column names etc. Commented Apr 19, 2021 at 8:10

2 Answers 2

4

Table name is not a value. So PostgreSQL parser is not expecting a placeholder in this DDL.

Check this:

db.Exec(fmt.Sprintf("ALTER TABLE %s RENAME TO %s",pq.QuoteIdentifier(oldname), pq.QuoteIdentifier(new_name)))
Sign up to request clarification or add additional context in comments.

1 Comment

but i want to inject the query , normal sting works
0

Do not use identifiers as params to SQL query.

Try this:

func ChangeDBname(newName string) {
    oldName := "intern"
    query := fmt.Sprintf("ALTER TABLE %s RENAME TO %s", pq.QuoteIdentifier(oldName), pq.QuoteIdentifier(newName))

    _, err := db.Exec(query)
    if err != nil {
        fmt.Println("Error in change name")
        log.Fatal(err)
    } else {
        fmt.Println("Table name changed to", newName)
    }
}

Comments

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.