From 8110e635b5af45d27d7665f26ac2bbe7105c65ed Mon Sep 17 00:00:00 2001 From: Conrad Hoffmann Date: Wed, 7 Sep 2022 12:28:57 +0200 Subject: [PATCH] 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)...) --- database/sq.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/database/sq.go b/database/sq.go index 474c66772cac2beee97b7f811f0427c4004715b6..a2699308c4b5897edaf884fe18c929c889f30d2f 100644 --- a/database/sq.go +++ b/database/sq.go @@ -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 +}