diff --git a/scripts/generate_db_helpers.go b/scripts/generate_db_helpers.go index e174902909bd0e2538f07eb114401342fbe464c8_c2NyaXB0cy9nZW5lcmF0ZV9kYl9oZWxwZXJzLmdv..2c836efb6791db5f13ed1410ae88e0f2f6e83e19_c2NyaXB0cy9nZW5lcmF0ZV9kYl9oZWxwZXJzLmdv 100644 --- a/scripts/generate_db_helpers.go +++ b/scripts/generate_db_helpers.go @@ -257,6 +257,8 @@ // This file contains constants for all db names involved in a mapped struct // It also add some accessors on the struct types so they implement a 'Mapped' interface +import "github.com/Masterminds/squirrel" + // Mapped is the common interface of all structs that are mapped in the database type Mapped interface { Table() string @@ -265,6 +267,45 @@ Values(columns ...string) []interface{} } +type TableSchema interface { + GetName() string + Sql() string +} + +type Column struct { + table TableSchema + name string +} + +func (c Column) Sql() string { + return c.table.GetName()+"."+c.name +} + +func (c Column) ToSql() (string, []interface{}, error ) { + return c.Sql(), nil, nil +} + +func (c Column) Join(col Column) Join { + return Join{ + from: c, + to: col, + } +} + +func (c Column) Eq(value interface{}) squirrel.Eq{ + return squirrel.Eq{c.Sql(): value} +} + +type Join struct { + from Column + to Column +} + +func (j Join) Sql() string { + return j.to.table.Sql() + " ON " + j.to.Sql() + " = " + j.from.Sql() +} + + const ( // table and column names {{- range $i, $dbstruct := .DBStructs}} @@ -378,4 +419,11 @@ } return values } + +{{- if .HasTable}} + +func New{{.Name}}TableSchema() *{{.Name}}TableSchema { + t := {{.Name}}TableSchema{} +{{- range .Fields}} + t.{{.Name}} = Column{&t, "{{.Column}}"} {{- end}} @@ -381,3 +429,74 @@ {{- end}} + return &t +} + +type {{.Name}}TableSchema struct { + alias string + +{{- range .Fields}} + {{.Name}} Column +{{- end}} +} + +// Columns returns the database table column names +func (t {{.Name}}TableSchema) Columns(withPKey bool) []string { + if withPKey { + return {{.Name}}Columns + } + return {{.Name}}DataColumns +} + +func (t {{.Name}}TableSchema) As(name string) *{{.Name}}TableSchema { + t.alias = name +{{- range .Fields}} + t.{{.Name}} = Column{&t, "{{.Column}}"} +{{- end}} + return &t +} + +func (t {{.Name}}TableSchema) GetName() string { + if t.alias == "" { + return {{.Name}}Table + } + return t.alias +} + +func (t {{.Name}}TableSchema) Sql() string { + if t.alias == "" { + return {{.Name}}Table + } + return {{.Name}}Table + " AS " + t.alias +} +func (t {{.Name}}TableSchema) ToSql() (string, []interface{}, error) { + return t.Sql(), nil, nil +} + + + +{{- end}} + + +{{- end}} + +func NewDBSchema() *DBSchema { + return &DBSchema{ +{{- range $dbstruct := .DBStructs}} +{{- if .HasTable}} + {{.Name}}: New{{.Name}}TableSchema(), +{{- end}} +{{- end}} + } +} + +type DBSchema struct { +{{- range $dbstruct := .DBStructs}} +{{- if .HasTable}} + {{.Name}} *{{.Name}}TableSchema +{{- end}} +{{- end}} +} + +var Schema = NewDBSchema() + `)) )