Add support for scanning columns
All checks were successful
Build / build (push) Successful in 1m36s

This commit is contained in:
Sebastiaan de Schaetzen 2025-05-31 10:30:06 +02:00
parent 33f1a94fb2
commit 25d53516e9
2 changed files with 30 additions and 0 deletions

View File

@ -119,6 +119,23 @@ func (q *Query) MustExec() {
}
}
func (q *Query) ScanColumns(results *[]string) *Query {
if q.err != nil {
return q
}
// Ensure the number of results matches the number of columns
if q.stmt.ColumnCount() != len(*results) {
*results = make([]string, q.stmt.ColumnCount())
}
// Fetch the column names
for i := 0; i < q.stmt.ColumnCount(); i++ {
(*results)[i] = q.stmt.ColumnName(i)
}
return q
}
func (q *Query) ScanSingle(results ...any) (rerr error) {
defer q.unlock()
// Scan rows

View File

@ -35,6 +35,19 @@ func TestScanWithMissingValues(t *testing.T) {
require.Equal(t, ErrMissingScan, err)
}
func TestScanColumns(t *testing.T) {
db := openTestDb(t)
var columns []string
var key string
err := db.Query("select `key` from mytable").
ScanColumns(&columns).
ScanSingle(&key)
require.NoError(t, err, "expected no error scanning columns")
require.Equal(t, 1, len(columns), "expected one column")
require.Equal(t, "key", columns[0], "expected column name 'key'")
require.Equal(t, "foo", key, "expected key to be 'foo'")
}
func TestBindInt64(t *testing.T) {
db := openTestDb(t)
var value int64