I want to write a generic function which handles SQL queries.
Sqlx module provides function StructScan()
, which automatically scans results into struct fields.
type Place struct {
Country string
City sql.NullString
TelephoneCode int `db:"telcode"`
}
rows, err := db.Queryx("SELECT * FROM place")
for rows.Next() {
var p Place
err = rows.StructScan(&p)
}
So, proposed function signature looks as:
func Query(db *sql.DB, query) {
rows, err := db.Queryx("SELECT * FROM place")
for rows.Next() {
var p CustomType
err = rows.StructScan(&p)
}
}
The problem is that I do not know in advance the exact type of the variable denoted as Custom Type since it differs depending on a particular query (some queries returns string, another int etc).
One of the options would be to pass type CustomType
as argument to Query
. However, I do not know how to initialise the local variable p
with needed type.
Is there a way to do it?