jmoiron / sqlx

general purpose extensions to golang's database/sql
http://jmoiron.github.io/sqlx/
MIT License
16.3k stars 1.09k forks source link

NamedExec cannot handle column names with hyphens #874

Closed richardvk closed 1 year ago

richardvk commented 1 year ago

I have a database column defined as :

`NS-Var-ID` char(50) DEFAULT NULL,

I have a struct with

NSVarID         string         `db:"NS-Var-ID"`

Trying to use NamedExec with this name fails, something like this:

q := "INSERT INTO table (`NS-Var-ID`) VALUES (:NS-Var-ID)"
_, err := dstDbh.NamedExec(q, d)

panic: could not find name NS in ...........

I have tried all sorts of quoting, but I am unable to find anything that works. The biggest downside is that Im unable to use batch inserting which seems to only be supported by NamedExec.

gurza commented 1 year ago

When you have a dash in a tag, the Go sqlx package's name mapper treats it as a word separator. Therefore, "NS-Var-ID" is being interpreted as three separate words: "NS", "Var", and "ID". Unfortunately, it is not possible to escape the dashes in the tags.

If you can, change the column name to not include dashes.

Alternatively

q := "INSERT INTO table (`NS-Var-ID`) VALUES (?)"
_, err := dstDbh.Exec(q, d.NSVarID)
gurza commented 1 year ago

@richardvk if you have no more questions, please close this issue.

richardvk commented 1 year ago

Thanks for the help and explanation. If anyone else is interested, I solved this with

SELECT NS-Var-ID AS ns_var_id FROM table

so that i could create my struct as

NSVarID         string         `db:"ns_var_id"`

This then worked fine, bearing in mind I specifically wanted to use NamedExec to do batch inserts with a slice of db rows:

q := "INSERT INTO table (`NS-Var-ID`) VALUES (:ns_var_id)"
_, err := dstDbh.NamedExec(q, d)