mirror of https://git.sr.ht/~sircmpwn/core-go
database: add helpers to fetch all columns
The current solution of fetching columns based on the GraphQL context has some limits. While probably not the solution for all use-cases, it sometimes can be desirable to simply fetch all columns from the database when retrieving objects. This commit adds two simple functions doing just that. They can be used when building SQL queries, like query := database.SelectAll(new(model.Email)) and rows.Scan(database.ScanAll(&email)...)
This commit is contained in:
parent
12000f491a
commit
8110e635b5
|
@ -3,6 +3,7 @@ package database
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
sq "github.com/Masterminds/squirrel"
|
||||
)
|
||||
|
@ -104,3 +105,32 @@ func Select(ctx context.Context, cols ...interface{}) sq.SelectBuilder {
|
|||
}
|
||||
return q
|
||||
}
|
||||
|
||||
func SelectAll(m Model) sq.SelectBuilder {
|
||||
mf := m.Fields()
|
||||
mf.buildCache()
|
||||
var cols []string
|
||||
for col, fields := range mf.bySQL {
|
||||
for _, _ = range fields {
|
||||
cols = append(cols, WithAlias(m.Alias(), col))
|
||||
}
|
||||
}
|
||||
sort.Strings(cols)
|
||||
q := sq.Select().PlaceholderFormat(sq.Dollar)
|
||||
return q.Columns(cols...)
|
||||
}
|
||||
|
||||
func ScanAll(m Model) []interface{} {
|
||||
fms := m.Fields().All()
|
||||
sort.Slice(fms, func(a, b int) bool {
|
||||
return fms[a].SQL < fms[b].SQL
|
||||
})
|
||||
|
||||
var fields []interface{}
|
||||
for _, f := range fms {
|
||||
if f.SQL != "" {
|
||||
fields = append(fields, f.Ptr)
|
||||
}
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue