~bigbes/core-go

8110e635b5af45d27d7665f26ac2bbe7105c65ed — Conrad Hoffmann 3 years ago 12000f4
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)...)
1 files changed, 30 insertions(+), 0 deletions(-)

M database/sq.go
M database/sq.go => database/sq.go +30 -0
@@ 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
}