Running dynamic queries #5
-
I have some queries where I dont know the columns that will be returned in advance since the user specifies them. Is there way to map a row as |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 11 replies
-
Out of curiosity, how would you use these values if you don't know what name or type they are in advance? |
Beta Was this translation helpful? Give feedback.
-
I've been thinking about this use case, I think it can be accommodated after all.
So there are two types of queries: dynamic and non-dynamic. If the user provides a list of columns, the query is dynamic (because the SELECT clause will change depending the columns specified). If the user passes in a raw SQL string, it's non-dynamic (because the query string is static and will not change). I plan to add four new methods: Dynamic queriesDynamic queries get one new method. You know the names and number of columns. func (*Row) Value(format string, values ...interface{}) interface{} Used like this: result := make(map[string]interface{})
for _, column := range columns {
result[column] = row.Value(column)
} Non-dynamic queriesNon-dynamic queries get three new methods. You don't know the names or number of columns. func (*Row) Columns() []string
func (*Row) ColumnTypes() []*sql.ColumnType
func (*Row) Values() []interface{} Used like this: result := make(map[string]interface{})
columns := row.Columns()
values := row.Values() // guranteed to have same length as row.Columns()
for i, column := range columns {
result[column] = values[i]
}
// row.ColumnTypes() is a thin wrapper over (*database/sql.Rows).ColumnsTypes(),
// usually not needed but added for completion's sake. Dynamic vs Non-dynamic queries
Basically the new methods row.Columns(), row.Values() and row.ColumnTypes() are only valid if you use them on raw SQL queries. They are invalid everywhere else. And if you are using raw SQL queries, you cannot call any other method on the row except row.Columns(), row.Values() and row.ColumnTypes(). It's a little confusing but hopefully the error message returned will be informative enough to inform the user what they are doing wrong. |
Beta Was this translation helpful? Give feedback.
Fixed in v0.3.0 009782c, should be working now.
Works as previously discussed.