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

Improve handling of named parameters in namedSelect and namedExec methods #892

Open suiriass opened 1 year ago

suiriass commented 1 year ago

https://github.com/go-sqlx/sqlx/issues/19 Currently, SQLx's namedSelect and namedExec methods generate variable strings and variable name arrays first, and then replace the named variables. This approach works well in most cases. However, it fails when a variable does not exist in the arg (e.g., select * from user where name = ':suiria', where :suiria is a string, not a variable). In such cases, SQLx throws an error because it expects all variables to be present in arg.

It would be more flexible if SQLx could ignore the replacement of variables that do not exist in arg, rather than throwing an error. This could be achieved by parsing variable values one by one during the string variable replacement process. If a variable is not found in arg, SQLx could simply skip it.

Example:

Current usage:

rows, err := db.NamedSelect("SELECT * FROM users WHERE name = :name", map[string]interface{}{"name": "suiria"})
// Throws an error if "name" is not present in the map

Desired usage:

rows, err := db.NamedSelect("SELECT * FROM users WHERE name = ':name'", map[string]interface{}{})
// Should not throw an error even if "name" is not present in the map

This feature is present in other ORM libraries like GORM and would be a useful addition to SQLx, making it more flexible and user-friendly in general scenarios.