Add MySQL Upsert, fix identation in all tpls

This commit is contained in:
Patrick O'brien 2016-09-14 18:08:30 +10:00
parent 4f1565147a
commit 83f7092dc6
43 changed files with 2457 additions and 2360 deletions

View file

@ -1003,6 +1003,12 @@ p1.Name = "Hogan"
err := p1.Upsert(db, true, []string{"id"}, []string{"name"}, "id", "name") err := p1.Upsert(db, true, []string{"id"}, []string{"name"}, "id", "name")
``` ```
The `updateOnConflict` argument allows you to specify whether you would like Postgres
to perform a `DO NOTHING` on conflict, opposed to a `DO UPDATE`. For MySQL, this param will not be generated.
The `conflictColumns` argument allows you to specify the `ON CONFLICT` columns for Postgres.
For MySQL, this param will not be generated.
Note: Passing a different set of column values to the update component is not currently supported. Note: Passing a different set of column values to the update component is not currently supported.
If this feature is important to you let us know and we can consider adding something for this. If this feature is important to you let us know and we can consider adding something for this.

View file

@ -3,6 +3,7 @@ package bdb
import ( import (
"fmt" "fmt"
"regexp" "regexp"
"strings"
) )
var rgxAutoIncColumn = regexp.MustCompile(`^nextval\(.*\)`) var rgxAutoIncColumn = regexp.MustCompile(`^nextval\(.*\)`)
@ -79,3 +80,30 @@ func SQLColDefinitions(cols []Column, names []string) SQLColumnDefs {
return ret return ret
} }
// AutoIncPrimaryKey returns the auto-increment primary key column name or an
// empty string. Primary key columns with default values are presumed
// to be auto-increment, because pkeys need to be unique and a static
// default value would cause collisions.
func AutoIncPrimaryKey(cols []Column, pkey *PrimaryKey) *Column {
if pkey == nil {
return nil
}
for _, pkeyColumn := range pkey.Columns {
for _, c := range cols {
if c.Name != pkeyColumn {
continue
}
if c.Default != "auto_increment" || c.Nullable ||
!(strings.HasPrefix(c.Type, "int") || strings.HasPrefix(c.Type, "uint")) {
continue
}
return &c
}
}
return nil
}

View file

@ -183,8 +183,37 @@ func buildUpdateQuery(q *Query) (*bytes.Buffer, []interface{}) {
return buf, args return buf, args
} }
// BuildUpsertQuery builds a SQL statement string using the upsertData provided. // BuildUpsertQueryMySQL builds a SQL statement string using the upsertData provided.
func BuildUpsertQuery(dia Dialect, tableName string, updateOnConflict bool, ret, update, conflict, whitelist []string) string { func BuildUpsertQueryMySQL(dia Dialect, tableName string, update, whitelist []string) string {
whitelist = strmangle.IdentQuoteSlice(dia.LQ, dia.RQ, whitelist)
buf := strmangle.GetBuffer()
defer strmangle.PutBuffer(buf)
fmt.Fprintf(
buf,
"INSERT INTO %s (%s) VALUES (%s) ON DUPLICATE KEY UPDATE ",
tableName,
strings.Join(whitelist, ", "),
strmangle.Placeholders(dia.IndexPlaceholders, len(whitelist), 1, 1),
)
for i, v := range update {
if i != 0 {
buf.WriteByte(',')
}
quoted := strmangle.IdentQuote(dia.LQ, dia.RQ, v)
buf.WriteString(quoted)
buf.WriteString(" = VALUES(")
buf.WriteString(quoted)
buf.WriteByte(')')
}
return buf.String()
}
// BuildUpsertQueryPostgres builds a SQL statement string using the upsertData provided.
func BuildUpsertQueryPostgres(dia Dialect, tableName string, updateOnConflict bool, ret, update, conflict, whitelist []string) string {
conflict = strmangle.IdentQuoteSlice(dia.LQ, dia.RQ, conflict) conflict = strmangle.IdentQuoteSlice(dia.LQ, dia.RQ, conflict)
whitelist = strmangle.IdentQuoteSlice(dia.LQ, dia.RQ, whitelist) whitelist = strmangle.IdentQuoteSlice(dia.LQ, dia.RQ, whitelist)
ret = strmangle.IdentQuoteSlice(dia.LQ, dia.RQ, ret) ret = strmangle.IdentQuoteSlice(dia.LQ, dia.RQ, ret)

View file

@ -174,6 +174,7 @@ var templateFunctions = template.FuncMap{
// dbdrivers ops // dbdrivers ops
"filterColumnsByDefault": bdb.FilterColumnsByDefault, "filterColumnsByDefault": bdb.FilterColumnsByDefault,
"autoIncPrimaryKey": bdb.AutoIncPrimaryKey,
"sqlColDefinitions": bdb.SQLColDefinitions, "sqlColDefinitions": bdb.SQLColDefinitions,
"columnNames": bdb.ColumnNames, "columnNames": bdb.ColumnNames,
"columnDBTypes": bdb.ColumnDBTypes, "columnDBTypes": bdb.ColumnDBTypes,

View file

@ -1,5 +1,5 @@
{{- define "relationship_to_one_struct_helper" -}} {{- define "relationship_to_one_struct_helper" -}}
{{.Function.Name}} *{{.ForeignTable.NameGo}} {{.Function.Name}} *{{.ForeignTable.NameGo}}
{{- end -}} {{- end -}}
{{- $dot := . -}} {{- $dot := . -}}
@ -8,30 +8,30 @@
{{- $modelNameCamel := $tableNameSingular | camelCase -}} {{- $modelNameCamel := $tableNameSingular | camelCase -}}
// {{$modelName}} is an object representing the database table. // {{$modelName}} is an object representing the database table.
type {{$modelName}} struct { type {{$modelName}} struct {
{{range $column := .Table.Columns -}} {{range $column := .Table.Columns -}}
{{titleCase $column.Name}} {{$column.Type}} `{{generateTags $dot.Tags $column.Name}}boil:"{{$column.Name}}" json:"{{$column.Name}}{{if $column.Nullable}},omitempty{{end}}" toml:"{{$column.Name}}" yaml:"{{$column.Name}}{{if $column.Nullable}},omitempty{{end}}"` {{titleCase $column.Name}} {{$column.Type}} `{{generateTags $dot.Tags $column.Name}}boil:"{{$column.Name}}" json:"{{$column.Name}}{{if $column.Nullable}},omitempty{{end}}" toml:"{{$column.Name}}" yaml:"{{$column.Name}}{{if $column.Nullable}},omitempty{{end}}"`
{{end -}} {{end -}}
{{- if .Table.IsJoinTable -}} {{- if .Table.IsJoinTable -}}
{{- else}} {{- else}}
R *{{$modelNameCamel}}R `{{generateIgnoreTags $dot.Tags}}boil:"-" json:"-" toml:"-" yaml:"-"` R *{{$modelNameCamel}}R `{{generateIgnoreTags $dot.Tags}}boil:"-" json:"-" toml:"-" yaml:"-"`
L {{$modelNameCamel}}L `{{generateIgnoreTags $dot.Tags}}boil:"-" json:"-" toml:"-" yaml:"-"` L {{$modelNameCamel}}L `{{generateIgnoreTags $dot.Tags}}boil:"-" json:"-" toml:"-" yaml:"-"`
{{end -}} {{end -}}
} }
{{- if .Table.IsJoinTable -}} {{- if .Table.IsJoinTable -}}
{{- else}} {{- else}}
// {{$modelNameCamel}}R is where relationships are stored. // {{$modelNameCamel}}R is where relationships are stored.
type {{$modelNameCamel}}R struct { type {{$modelNameCamel}}R struct {
{{range .Table.FKeys -}} {{range .Table.FKeys -}}
{{- $rel := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table . -}} {{- $rel := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table . -}}
{{- template "relationship_to_one_struct_helper" $rel}} {{- template "relationship_to_one_struct_helper" $rel}}
{{end -}} {{end -}}
{{- range .Table.ToManyRelationships -}} {{- range .Table.ToManyRelationships -}}
{{- if (and .ForeignColumnUnique (not .ToJoinTable)) -}} {{- if (and .ForeignColumnUnique (not .ToJoinTable)) -}}
{{- template "relationship_to_one_struct_helper" (textsFromOneToOneRelationship $dot.PkgName $dot.Tables $dot.Table .)}} {{- template "relationship_to_one_struct_helper" (textsFromOneToOneRelationship $dot.PkgName $dot.Tables $dot.Table .)}}
{{else -}} {{else -}}
{{- $rel := textsFromRelationship $dot.Tables $dot.Table . -}} {{- $rel := textsFromRelationship $dot.Tables $dot.Table . -}}
{{$rel.Function.Name}} {{$rel.ForeignTable.Slice}} {{$rel.Function.Name}} {{$rel.ForeignTable.Slice}}
{{end -}}{{/* if ForeignColumnUnique */}} {{end -}}{{/* if ForeignColumnUnique */}}
{{- end -}}{{/* range tomany */}} {{- end -}}{{/* range tomany */}}
} }

View file

@ -3,31 +3,31 @@
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
{{- $tableNameSingular := .Table.Name | singular | titleCase -}} {{- $tableNameSingular := .Table.Name | singular | titleCase -}}
var ( var (
{{$varNameSingular}}Columns = []string{{"{"}}{{.Table.Columns | columnNames | stringMap .StringFuncs.quoteWrap | join ", "}}{{"}"}} {{$varNameSingular}}Columns = []string{{"{"}}{{.Table.Columns | columnNames | stringMap .StringFuncs.quoteWrap | join ", "}}{{"}"}}
{{$varNameSingular}}ColumnsWithoutDefault = []string{{"{"}}{{.Table.Columns | filterColumnsByDefault false | columnNames | stringMap .StringFuncs.quoteWrap | join ","}}{{"}"}} {{$varNameSingular}}ColumnsWithoutDefault = []string{{"{"}}{{.Table.Columns | filterColumnsByDefault false | columnNames | stringMap .StringFuncs.quoteWrap | join ","}}{{"}"}}
{{$varNameSingular}}ColumnsWithDefault = []string{{"{"}}{{.Table.Columns | filterColumnsByDefault true | columnNames | stringMap .StringFuncs.quoteWrap | join ","}}{{"}"}} {{$varNameSingular}}ColumnsWithDefault = []string{{"{"}}{{.Table.Columns | filterColumnsByDefault true | columnNames | stringMap .StringFuncs.quoteWrap | join ","}}{{"}"}}
{{$varNameSingular}}PrimaryKeyColumns = []string{{"{"}}{{.Table.PKey.Columns | stringMap .StringFuncs.quoteWrap | join ", "}}{{"}"}} {{$varNameSingular}}PrimaryKeyColumns = []string{{"{"}}{{.Table.PKey.Columns | stringMap .StringFuncs.quoteWrap | join ", "}}{{"}"}}
) )
type ( type (
{{$tableNameSingular}}Slice []*{{$tableNameSingular}} {{$tableNameSingular}}Slice []*{{$tableNameSingular}}
{{if eq .NoHooks false -}} {{if eq .NoHooks false -}}
{{$tableNameSingular}}Hook func(boil.Executor, *{{$tableNameSingular}}) error {{$tableNameSingular}}Hook func(boil.Executor, *{{$tableNameSingular}}) error
{{- end}} {{- end}}
{{$varNameSingular}}Query struct { {{$varNameSingular}}Query struct {
*boil.Query *boil.Query
} }
) )
// Cache for insert and update // Cache for insert and update
var ( var (
{{$varNameSingular}}Type = reflect.TypeOf(&{{$tableNameSingular}}{}) {{$varNameSingular}}Type = reflect.TypeOf(&{{$tableNameSingular}}{})
{{$varNameSingular}}Mapping = boil.MakeStructMapping({{$varNameSingular}}Type) {{$varNameSingular}}Mapping = boil.MakeStructMapping({{$varNameSingular}}Type)
{{$varNameSingular}}InsertCacheMut sync.RWMutex {{$varNameSingular}}InsertCacheMut sync.RWMutex
{{$varNameSingular}}InsertCache = make(map[string]insertCache) {{$varNameSingular}}InsertCache = make(map[string]insertCache)
{{$varNameSingular}}UpdateCacheMut sync.RWMutex {{$varNameSingular}}UpdateCacheMut sync.RWMutex
{{$varNameSingular}}UpdateCache = make(map[string]updateCache) {{$varNameSingular}}UpdateCache = make(map[string]updateCache)
) )
// Force time package dependency for automated UpdatedAt/CreatedAt. // Force time package dependency for automated UpdatedAt/CreatedAt.

View file

@ -14,123 +14,123 @@ var {{$varNameSingular}}AfterUpsertHooks []{{$tableNameSingular}}Hook
// doBeforeInsertHooks executes all "before insert" hooks. // doBeforeInsertHooks executes all "before insert" hooks.
func (o *{{$tableNameSingular}}) doBeforeInsertHooks(exec boil.Executor) (err error) { func (o *{{$tableNameSingular}}) doBeforeInsertHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}BeforeInsertHooks { for _, hook := range {{$varNameSingular}}BeforeInsertHooks {
if err := hook(exec, o); err != nil { if err := hook(exec, o); err != nil {
return err return err
} }
} }
return nil return nil
} }
// doBeforeUpdateHooks executes all "before Update" hooks. // doBeforeUpdateHooks executes all "before Update" hooks.
func (o *{{$tableNameSingular}}) doBeforeUpdateHooks(exec boil.Executor) (err error) { func (o *{{$tableNameSingular}}) doBeforeUpdateHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}BeforeUpdateHooks { for _, hook := range {{$varNameSingular}}BeforeUpdateHooks {
if err := hook(exec, o); err != nil { if err := hook(exec, o); err != nil {
return err return err
} }
} }
return nil return nil
} }
// doBeforeDeleteHooks executes all "before Delete" hooks. // doBeforeDeleteHooks executes all "before Delete" hooks.
func (o *{{$tableNameSingular}}) doBeforeDeleteHooks(exec boil.Executor) (err error) { func (o *{{$tableNameSingular}}) doBeforeDeleteHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}BeforeDeleteHooks { for _, hook := range {{$varNameSingular}}BeforeDeleteHooks {
if err := hook(exec, o); err != nil { if err := hook(exec, o); err != nil {
return err return err
} }
} }
return nil return nil
} }
// doBeforeUpsertHooks executes all "before Upsert" hooks. // doBeforeUpsertHooks executes all "before Upsert" hooks.
func (o *{{$tableNameSingular}}) doBeforeUpsertHooks(exec boil.Executor) (err error) { func (o *{{$tableNameSingular}}) doBeforeUpsertHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}BeforeUpsertHooks { for _, hook := range {{$varNameSingular}}BeforeUpsertHooks {
if err := hook(exec, o); err != nil { if err := hook(exec, o); err != nil {
return err return err
} }
} }
return nil return nil
} }
// doAfterInsertHooks executes all "after Insert" hooks. // doAfterInsertHooks executes all "after Insert" hooks.
func (o *{{$tableNameSingular}}) doAfterInsertHooks(exec boil.Executor) (err error) { func (o *{{$tableNameSingular}}) doAfterInsertHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}AfterInsertHooks { for _, hook := range {{$varNameSingular}}AfterInsertHooks {
if err := hook(exec, o); err != nil { if err := hook(exec, o); err != nil {
return err return err
} }
} }
return nil return nil
} }
// doAfterSelectHooks executes all "after Select" hooks. // doAfterSelectHooks executes all "after Select" hooks.
func (o *{{$tableNameSingular}}) doAfterSelectHooks(exec boil.Executor) (err error) { func (o *{{$tableNameSingular}}) doAfterSelectHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}AfterSelectHooks { for _, hook := range {{$varNameSingular}}AfterSelectHooks {
if err := hook(exec, o); err != nil { if err := hook(exec, o); err != nil {
return err return err
} }
} }
return nil return nil
} }
// doAfterUpdateHooks executes all "after Update" hooks. // doAfterUpdateHooks executes all "after Update" hooks.
func (o *{{$tableNameSingular}}) doAfterUpdateHooks(exec boil.Executor) (err error) { func (o *{{$tableNameSingular}}) doAfterUpdateHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}AfterUpdateHooks { for _, hook := range {{$varNameSingular}}AfterUpdateHooks {
if err := hook(exec, o); err != nil { if err := hook(exec, o); err != nil {
return err return err
} }
} }
return nil return nil
} }
// doAfterDeleteHooks executes all "after Delete" hooks. // doAfterDeleteHooks executes all "after Delete" hooks.
func (o *{{$tableNameSingular}}) doAfterDeleteHooks(exec boil.Executor) (err error) { func (o *{{$tableNameSingular}}) doAfterDeleteHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}AfterDeleteHooks { for _, hook := range {{$varNameSingular}}AfterDeleteHooks {
if err := hook(exec, o); err != nil { if err := hook(exec, o); err != nil {
return err return err
} }
} }
return nil return nil
} }
// doAfterUpsertHooks executes all "after Upsert" hooks. // doAfterUpsertHooks executes all "after Upsert" hooks.
func (o *{{$tableNameSingular}}) doAfterUpsertHooks(exec boil.Executor) (err error) { func (o *{{$tableNameSingular}}) doAfterUpsertHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}AfterUpsertHooks { for _, hook := range {{$varNameSingular}}AfterUpsertHooks {
if err := hook(exec, o); err != nil { if err := hook(exec, o); err != nil {
return err return err
} }
} }
return nil return nil
} }
func Add{{$tableNameSingular}}Hook(hookPoint boil.HookPoint, {{$varNameSingular}}Hook {{$tableNameSingular}}Hook) { func Add{{$tableNameSingular}}Hook(hookPoint boil.HookPoint, {{$varNameSingular}}Hook {{$tableNameSingular}}Hook) {
switch hookPoint { switch hookPoint {
case boil.BeforeInsertHook: case boil.BeforeInsertHook:
{{$varNameSingular}}BeforeInsertHooks = append({{$varNameSingular}}BeforeInsertHooks, {{$varNameSingular}}Hook) {{$varNameSingular}}BeforeInsertHooks = append({{$varNameSingular}}BeforeInsertHooks, {{$varNameSingular}}Hook)
case boil.BeforeUpdateHook: case boil.BeforeUpdateHook:
{{$varNameSingular}}BeforeUpdateHooks = append({{$varNameSingular}}BeforeUpdateHooks, {{$varNameSingular}}Hook) {{$varNameSingular}}BeforeUpdateHooks = append({{$varNameSingular}}BeforeUpdateHooks, {{$varNameSingular}}Hook)
case boil.BeforeDeleteHook: case boil.BeforeDeleteHook:
{{$varNameSingular}}BeforeDeleteHooks = append({{$varNameSingular}}BeforeDeleteHooks, {{$varNameSingular}}Hook) {{$varNameSingular}}BeforeDeleteHooks = append({{$varNameSingular}}BeforeDeleteHooks, {{$varNameSingular}}Hook)
case boil.BeforeUpsertHook: case boil.BeforeUpsertHook:
{{$varNameSingular}}BeforeUpsertHooks = append({{$varNameSingular}}BeforeUpsertHooks, {{$varNameSingular}}Hook) {{$varNameSingular}}BeforeUpsertHooks = append({{$varNameSingular}}BeforeUpsertHooks, {{$varNameSingular}}Hook)
case boil.AfterInsertHook: case boil.AfterInsertHook:
{{$varNameSingular}}AfterInsertHooks = append({{$varNameSingular}}AfterInsertHooks, {{$varNameSingular}}Hook) {{$varNameSingular}}AfterInsertHooks = append({{$varNameSingular}}AfterInsertHooks, {{$varNameSingular}}Hook)
case boil.AfterSelectHook: case boil.AfterSelectHook:
{{$varNameSingular}}AfterSelectHooks = append({{$varNameSingular}}AfterSelectHooks, {{$varNameSingular}}Hook) {{$varNameSingular}}AfterSelectHooks = append({{$varNameSingular}}AfterSelectHooks, {{$varNameSingular}}Hook)
case boil.AfterUpdateHook: case boil.AfterUpdateHook:
{{$varNameSingular}}AfterUpdateHooks = append({{$varNameSingular}}AfterUpdateHooks, {{$varNameSingular}}Hook) {{$varNameSingular}}AfterUpdateHooks = append({{$varNameSingular}}AfterUpdateHooks, {{$varNameSingular}}Hook)
case boil.AfterDeleteHook: case boil.AfterDeleteHook:
{{$varNameSingular}}AfterDeleteHooks = append({{$varNameSingular}}AfterDeleteHooks, {{$varNameSingular}}Hook) {{$varNameSingular}}AfterDeleteHooks = append({{$varNameSingular}}AfterDeleteHooks, {{$varNameSingular}}Hook)
case boil.AfterUpsertHook: case boil.AfterUpsertHook:
{{$varNameSingular}}AfterUpsertHooks = append({{$varNameSingular}}AfterUpsertHooks, {{$varNameSingular}}Hook) {{$varNameSingular}}AfterUpsertHooks = append({{$varNameSingular}}AfterUpsertHooks, {{$varNameSingular}}Hook)
} }
} }
{{- end}} {{- end}}

View file

@ -2,115 +2,115 @@
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
// OneP returns a single {{$varNameSingular}} record from the query, and panics on error. // OneP returns a single {{$varNameSingular}} record from the query, and panics on error.
func (q {{$varNameSingular}}Query) OneP() (*{{$tableNameSingular}}) { func (q {{$varNameSingular}}Query) OneP() (*{{$tableNameSingular}}) {
o, err := q.One() o, err := q.One()
if err != nil { if err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
return o return o
} }
// One returns a single {{$varNameSingular}} record from the query. // One returns a single {{$varNameSingular}} record from the query.
func (q {{$varNameSingular}}Query) One() (*{{$tableNameSingular}}, error) { func (q {{$varNameSingular}}Query) One() (*{{$tableNameSingular}}, error) {
o := &{{$tableNameSingular}}{} o := &{{$tableNameSingular}}{}
boil.SetLimit(q.Query, 1) boil.SetLimit(q.Query, 1)
err := q.Bind(o) err := q.Bind(o)
if err != nil { if err != nil {
if errors.Cause(err) == sql.ErrNoRows { if errors.Cause(err) == sql.ErrNoRows {
return nil, sql.ErrNoRows return nil, sql.ErrNoRows
} }
return nil, errors.Wrap(err, "{{.PkgName}}: failed to execute a one query for {{.Table.Name}}") return nil, errors.Wrap(err, "{{.PkgName}}: failed to execute a one query for {{.Table.Name}}")
} }
{{if not .NoHooks -}} {{if not .NoHooks -}}
if err := o.doAfterSelectHooks(boil.GetExecutor(q.Query)); err != nil { if err := o.doAfterSelectHooks(boil.GetExecutor(q.Query)); err != nil {
return o, err return o, err
} }
{{- end}} {{- end}}
return o, nil return o, nil
} }
// AllP returns all {{$tableNameSingular}} records from the query, and panics on error. // AllP returns all {{$tableNameSingular}} records from the query, and panics on error.
func (q {{$varNameSingular}}Query) AllP() {{$tableNameSingular}}Slice { func (q {{$varNameSingular}}Query) AllP() {{$tableNameSingular}}Slice {
o, err := q.All() o, err := q.All()
if err != nil { if err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
return o return o
} }
// All returns all {{$tableNameSingular}} records from the query. // All returns all {{$tableNameSingular}} records from the query.
func (q {{$varNameSingular}}Query) All() ({{$tableNameSingular}}Slice, error) { func (q {{$varNameSingular}}Query) All() ({{$tableNameSingular}}Slice, error) {
var o {{$tableNameSingular}}Slice var o {{$tableNameSingular}}Slice
err := q.Bind(&o) err := q.Bind(&o)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "{{.PkgName}}: failed to assign all query results to {{$tableNameSingular}} slice") return nil, errors.Wrap(err, "{{.PkgName}}: failed to assign all query results to {{$tableNameSingular}} slice")
} }
{{if not .NoHooks -}} {{if not .NoHooks -}}
if len({{$varNameSingular}}AfterSelectHooks) != 0 { if len({{$varNameSingular}}AfterSelectHooks) != 0 {
for _, obj := range o { for _, obj := range o {
if err := obj.doAfterSelectHooks(boil.GetExecutor(q.Query)); err != nil { if err := obj.doAfterSelectHooks(boil.GetExecutor(q.Query)); err != nil {
return o, err return o, err
} }
} }
} }
{{- end}} {{- end}}
return o, nil return o, nil
} }
// CountP returns the count of all {{$tableNameSingular}} records in the query, and panics on error. // CountP returns the count of all {{$tableNameSingular}} records in the query, and panics on error.
func (q {{$varNameSingular}}Query) CountP() int64 { func (q {{$varNameSingular}}Query) CountP() int64 {
c, err := q.Count() c, err := q.Count()
if err != nil { if err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
return c return c
} }
// Count returns the count of all {{$tableNameSingular}} records in the query. // Count returns the count of all {{$tableNameSingular}} records in the query.
func (q {{$varNameSingular}}Query) Count() (int64, error) { func (q {{$varNameSingular}}Query) Count() (int64, error) {
var count int64 var count int64
boil.SetSelect(q.Query, nil) boil.SetSelect(q.Query, nil)
boil.SetCount(q.Query) boil.SetCount(q.Query)
err := q.Query.ExecQueryOne().Scan(&count) err := q.Query.ExecQueryOne().Scan(&count)
if err != nil { if err != nil {
return 0, errors.Wrap(err, "{{.PkgName}}: failed to count {{.Table.Name}} rows") return 0, errors.Wrap(err, "{{.PkgName}}: failed to count {{.Table.Name}} rows")
} }
return count, nil return count, nil
} }
// Exists checks if the row exists in the table, and panics on error. // Exists checks if the row exists in the table, and panics on error.
func (q {{$varNameSingular}}Query) ExistsP() bool { func (q {{$varNameSingular}}Query) ExistsP() bool {
e, err := q.Exists() e, err := q.Exists()
if err != nil { if err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
return e return e
} }
// Exists checks if the row exists in the table. // Exists checks if the row exists in the table.
func (q {{$varNameSingular}}Query) Exists() (bool, error) { func (q {{$varNameSingular}}Query) Exists() (bool, error) {
var count int64 var count int64
boil.SetCount(q.Query) boil.SetCount(q.Query)
boil.SetLimit(q.Query, 1) boil.SetLimit(q.Query, 1)
err := q.Query.ExecQueryOne().Scan(&count) err := q.Query.ExecQueryOne().Scan(&count)
if err != nil { if err != nil {
return false, errors.Wrap(err, "{{.PkgName}}: failed to check if {{.Table.Name}} exists") return false, errors.Wrap(err, "{{.PkgName}}: failed to check if {{.Table.Name}} exists")
} }
return count > 0, nil return count > 0, nil
} }

View file

@ -1,34 +1,34 @@
{{- define "relationship_to_one_helper" -}} {{- define "relationship_to_one_helper" -}}
{{- $dot := .Dot -}}{{/* .Dot holds the root templateData struct, passed in through preserveDot */}} {{- $dot := .Dot -}}{{/* .Dot holds the root templateData struct, passed in through preserveDot */}}
{{- with .Rel -}}{{/* Rel holds the text helper data, passed in through preserveDot */}} {{- with .Rel -}}{{/* Rel holds the text helper data, passed in through preserveDot */}}
{{- $varNameSingular := .ForeignKey.ForeignTable | singular | camelCase -}} {{- $varNameSingular := .ForeignKey.ForeignTable | singular | camelCase -}}
// {{.Function.Name}}G pointed to by the foreign key. // {{.Function.Name}}G pointed to by the foreign key.
func ({{.Function.Receiver}} *{{.LocalTable.NameGo}}) {{.Function.Name}}G(mods ...qm.QueryMod) {{$varNameSingular}}Query { func ({{.Function.Receiver}} *{{.LocalTable.NameGo}}) {{.Function.Name}}G(mods ...qm.QueryMod) {{$varNameSingular}}Query {
return {{.Function.Receiver}}.{{.Function.Name}}(boil.GetDB(), mods...) return {{.Function.Receiver}}.{{.Function.Name}}(boil.GetDB(), mods...)
} }
// {{.Function.Name}} pointed to by the foreign key. // {{.Function.Name}} pointed to by the foreign key.
func ({{.Function.Receiver}} *{{.LocalTable.NameGo}}) {{.Function.Name}}(exec boil.Executor, mods ...qm.QueryMod) ({{$varNameSingular}}Query) { func ({{.Function.Receiver}} *{{.LocalTable.NameGo}}) {{.Function.Name}}(exec boil.Executor, mods ...qm.QueryMod) ({{$varNameSingular}}Query) {
queryMods := []qm.QueryMod{ queryMods := []qm.QueryMod{
qm.Where("{{.ForeignTable.ColumnName}}={{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}}", {{.Function.Receiver}}.{{.LocalTable.ColumnNameGo}}), qm.Where("{{.ForeignTable.ColumnName}}={{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}}", {{.Function.Receiver}}.{{.LocalTable.ColumnNameGo}}),
} }
queryMods = append(queryMods, mods...) queryMods = append(queryMods, mods...)
query := {{.ForeignTable.NamePluralGo}}(exec, queryMods...) query := {{.ForeignTable.NamePluralGo}}(exec, queryMods...)
boil.SetFrom(query.Query, "{{.ForeignTable.Name | $dot.SchemaTable}}") boil.SetFrom(query.Query, "{{.ForeignTable.Name | $dot.SchemaTable}}")
return query return query
} }
{{- end -}}{{/* end with */}} {{- end -}}{{/* end with */}}
{{end -}}{{/* end define */}} {{end -}}{{/* end define */}}
{{- /* Begin execution of template for one-to-one relationship */ -}} {{- /* Begin execution of template for one-to-one relationship */ -}}
{{- if .Table.IsJoinTable -}} {{- if .Table.IsJoinTable -}}
{{- else -}} {{- else -}}
{{- $dot := . -}} {{- $dot := . -}}
{{- range .Table.FKeys -}} {{- range .Table.FKeys -}}
{{- $txt := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table . -}} {{- $txt := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table . -}}
{{- template "relationship_to_one_helper" (preserveDot $dot $txt) -}} {{- template "relationship_to_one_helper" (preserveDot $dot $txt) -}}
{{- end -}} {{- end -}}
{{- end -}} {{- end -}}

View file

@ -1,49 +1,49 @@
{{- /* Begin execution of template for many-to-one or many-to-many relationship helper */ -}} {{- /* Begin execution of template for many-to-one or many-to-many relationship helper */ -}}
{{- if .Table.IsJoinTable -}} {{- if .Table.IsJoinTable -}}
{{- else -}} {{- else -}}
{{- $dot := . -}} {{- $dot := . -}}
{{- $table := .Table -}} {{- $table := .Table -}}
{{- range .Table.ToManyRelationships -}} {{- range .Table.ToManyRelationships -}}
{{- $varNameSingular := .ForeignTable | singular | camelCase -}} {{- $varNameSingular := .ForeignTable | singular | camelCase -}}
{{- if (and .ForeignColumnUnique (not .ToJoinTable)) -}} {{- if (and .ForeignColumnUnique (not .ToJoinTable)) -}}
{{- /* Begin execution of template for many-to-one relationship. */ -}} {{- /* Begin execution of template for many-to-one relationship. */ -}}
{{- $txt := textsFromOneToOneRelationship $dot.PkgName $dot.Tables $table . -}} {{- $txt := textsFromOneToOneRelationship $dot.PkgName $dot.Tables $table . -}}
{{- template "relationship_to_one_helper" (preserveDot $dot $txt) -}} {{- template "relationship_to_one_helper" (preserveDot $dot $txt) -}}
{{- else -}} {{- else -}}
{{- /* Begin execution of template for many-to-many relationship. */ -}} {{- /* Begin execution of template for many-to-many relationship. */ -}}
{{- $rel := textsFromRelationship $dot.Tables $table . -}} {{- $rel := textsFromRelationship $dot.Tables $table . -}}
{{- $schemaForeignTable := .ForeignTable | $dot.SchemaTable -}} {{- $schemaForeignTable := .ForeignTable | $dot.SchemaTable -}}
// {{$rel.Function.Name}}G retrieves all the {{$rel.LocalTable.NameSingular}}'s {{$rel.ForeignTable.NameHumanReadable}} // {{$rel.Function.Name}}G retrieves all the {{$rel.LocalTable.NameSingular}}'s {{$rel.ForeignTable.NameHumanReadable}}
{{- if not (eq $rel.Function.Name $rel.ForeignTable.NamePluralGo)}} via {{.ForeignColumn}} column{{- end}}. {{- if not (eq $rel.Function.Name $rel.ForeignTable.NamePluralGo)}} via {{.ForeignColumn}} column{{- end}}.
func ({{$rel.Function.Receiver}} *{{$rel.LocalTable.NameGo}}) {{$rel.Function.Name}}G(mods ...qm.QueryMod) {{$varNameSingular}}Query { func ({{$rel.Function.Receiver}} *{{$rel.LocalTable.NameGo}}) {{$rel.Function.Name}}G(mods ...qm.QueryMod) {{$varNameSingular}}Query {
return {{$rel.Function.Receiver}}.{{$rel.Function.Name}}(boil.GetDB(), mods...) return {{$rel.Function.Receiver}}.{{$rel.Function.Name}}(boil.GetDB(), mods...)
} }
// {{$rel.Function.Name}} retrieves all the {{$rel.LocalTable.NameSingular}}'s {{$rel.ForeignTable.NameHumanReadable}} with an executor // {{$rel.Function.Name}} retrieves all the {{$rel.LocalTable.NameSingular}}'s {{$rel.ForeignTable.NameHumanReadable}} with an executor
{{- if not (eq $rel.Function.Name $rel.ForeignTable.NamePluralGo)}} via {{.ForeignColumn}} column{{- end}}. {{- if not (eq $rel.Function.Name $rel.ForeignTable.NamePluralGo)}} via {{.ForeignColumn}} column{{- end}}.
func ({{$rel.Function.Receiver}} *{{$rel.LocalTable.NameGo}}) {{$rel.Function.Name}}(exec boil.Executor, mods ...qm.QueryMod) {{$varNameSingular}}Query { func ({{$rel.Function.Receiver}} *{{$rel.LocalTable.NameGo}}) {{$rel.Function.Name}}(exec boil.Executor, mods ...qm.QueryMod) {{$varNameSingular}}Query {
queryMods := []qm.QueryMod{ queryMods := []qm.QueryMod{
qm.Select("{{id 0 | $dot.Quotes}}.*"), qm.Select("{{id 0 | $dot.Quotes}}.*"),
} }
if len(mods) != 0 { if len(mods) != 0 {
queryMods = append(queryMods, mods...) queryMods = append(queryMods, mods...)
} }
{{if .ToJoinTable -}} {{if .ToJoinTable -}}
queryMods = append(queryMods, queryMods = append(queryMods,
qm.InnerJoin("{{.JoinTable | $dot.SchemaTable}} as {{id 1 | $dot.Quotes}} on {{id 0 | $dot.Quotes}}.{{.ForeignColumn | $dot.Quotes}} = {{id 1 | $dot.Quotes}}.{{.JoinForeignColumn | $dot.Quotes}}"), qm.InnerJoin("{{.JoinTable | $dot.SchemaTable}} as {{id 1 | $dot.Quotes}} on {{id 0 | $dot.Quotes}}.{{.ForeignColumn | $dot.Quotes}} = {{id 1 | $dot.Quotes}}.{{.JoinForeignColumn | $dot.Quotes}}"),
qm.Where("{{id 1 | $dot.Quotes}}.{{.JoinLocalColumn | $dot.Quotes}}={{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}}", {{$rel.Function.Receiver}}.{{$rel.LocalTable.ColumnNameGo}}), qm.Where("{{id 1 | $dot.Quotes}}.{{.JoinLocalColumn | $dot.Quotes}}={{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}}", {{$rel.Function.Receiver}}.{{$rel.LocalTable.ColumnNameGo}}),
) )
{{else -}} {{else -}}
queryMods = append(queryMods, queryMods = append(queryMods,
qm.Where("{{id 0 | $dot.Quotes}}.{{.ForeignColumn | $dot.Quotes}}={{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}}", {{$rel.Function.Receiver}}.{{$rel.LocalTable.ColumnNameGo}}), qm.Where("{{id 0 | $dot.Quotes}}.{{.ForeignColumn | $dot.Quotes}}={{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}}", {{$rel.Function.Receiver}}.{{$rel.LocalTable.ColumnNameGo}}),
) )
{{end}} {{end}}
query := {{$rel.ForeignTable.NamePluralGo}}(exec, queryMods...) query := {{$rel.ForeignTable.NamePluralGo}}(exec, queryMods...)
boil.SetFrom(query.Query, "{{$schemaForeignTable}} as {{id 0 | $dot.Quotes}}") boil.SetFrom(query.Query, "{{$schemaForeignTable}} as {{id 0 | $dot.Quotes}}")
return query return query
} }
{{end -}}{{- /* if unique foreign key */ -}} {{end -}}{{- /* if unique foreign key */ -}}

View file

@ -1,93 +1,93 @@
{{- define "relationship_to_one_eager_helper" -}} {{- define "relationship_to_one_eager_helper" -}}
{{- $dot := .Dot -}}{{/* .Dot holds the root templateData struct, passed in through preserveDot */}} {{- $dot := .Dot -}}{{/* .Dot holds the root templateData struct, passed in through preserveDot */}}
{{- $varNameSingular := $dot.Table.Name | singular | camelCase -}} {{- $varNameSingular := $dot.Table.Name | singular | camelCase -}}
{{- with .Rel -}} {{- with .Rel -}}
{{- $arg := printf "maybe%s" .LocalTable.NameGo -}} {{- $arg := printf "maybe%s" .LocalTable.NameGo -}}
{{- $slice := printf "%sSlice" .LocalTable.NameGo -}} {{- $slice := printf "%sSlice" .LocalTable.NameGo -}}
// Load{{.Function.Name}} allows an eager lookup of values, cached into the // Load{{.Function.Name}} allows an eager lookup of values, cached into the
// loaded structs of the objects. // loaded structs of the objects.
func ({{$varNameSingular}}L) Load{{.Function.Name}}(e boil.Executor, singular bool, {{$arg}} interface{}) error { func ({{$varNameSingular}}L) Load{{.Function.Name}}(e boil.Executor, singular bool, {{$arg}} interface{}) error {
var slice []*{{.LocalTable.NameGo}} var slice []*{{.LocalTable.NameGo}}
var object *{{.LocalTable.NameGo}} var object *{{.LocalTable.NameGo}}
count := 1 count := 1
if singular { if singular {
object = {{$arg}}.(*{{.LocalTable.NameGo}}) object = {{$arg}}.(*{{.LocalTable.NameGo}})
} else { } else {
slice = *{{$arg}}.(*{{$slice}}) slice = *{{$arg}}.(*{{$slice}})
count = len(slice) count = len(slice)
} }
args := make([]interface{}, count) args := make([]interface{}, count)
if singular { if singular {
args[0] = object.{{.LocalTable.ColumnNameGo}} args[0] = object.{{.LocalTable.ColumnNameGo}}
} else { } else {
for i, obj := range slice { for i, obj := range slice {
args[i] = obj.{{.LocalTable.ColumnNameGo}} args[i] = obj.{{.LocalTable.ColumnNameGo}}
} }
} }
query := fmt.Sprintf( query := fmt.Sprintf(
"select * from {{.ForeignKey.ForeignTable | $dot.SchemaTable}} where {{.ForeignKey.ForeignColumn | $dot.Quotes}} in (%s)", "select * from {{.ForeignKey.ForeignTable | $dot.SchemaTable}} where {{.ForeignKey.ForeignColumn | $dot.Quotes}} in (%s)",
strmangle.Placeholders(dialect.IndexPlaceholders, count, 1, 1), strmangle.Placeholders(dialect.IndexPlaceholders, count, 1, 1),
) )
if boil.DebugMode { if boil.DebugMode {
fmt.Fprintf(boil.DebugWriter, "%s\n%v\n", query, args) fmt.Fprintf(boil.DebugWriter, "%s\n%v\n", query, args)
} }
results, err := e.Query(query, args...) results, err := e.Query(query, args...)
if err != nil { if err != nil {
return errors.Wrap(err, "failed to eager load {{.ForeignTable.NameGo}}") return errors.Wrap(err, "failed to eager load {{.ForeignTable.NameGo}}")
} }
defer results.Close() defer results.Close()
var resultSlice []*{{.ForeignTable.NameGo}} var resultSlice []*{{.ForeignTable.NameGo}}
if err = boil.Bind(results, &resultSlice); err != nil { if err = boil.Bind(results, &resultSlice); err != nil {
return errors.Wrap(err, "failed to bind eager loaded slice {{.ForeignTable.NameGo}}") return errors.Wrap(err, "failed to bind eager loaded slice {{.ForeignTable.NameGo}}")
} }
{{if not $dot.NoHooks -}} {{if not $dot.NoHooks -}}
if len({{.ForeignTable.Name | singular | camelCase}}AfterSelectHooks) != 0 { if len({{.ForeignTable.Name | singular | camelCase}}AfterSelectHooks) != 0 {
for _, obj := range resultSlice { for _, obj := range resultSlice {
if err := obj.doAfterSelectHooks(e); err != nil { if err := obj.doAfterSelectHooks(e); err != nil {
return err return err
} }
} }
} }
{{- end}} {{- end}}
if singular && len(resultSlice) != 0 { if singular && len(resultSlice) != 0 {
if object.R == nil { if object.R == nil {
object.R = &{{$varNameSingular}}R{} object.R = &{{$varNameSingular}}R{}
} }
object.R.{{.Function.Name}} = resultSlice[0] object.R.{{.Function.Name}} = resultSlice[0]
return nil return nil
} }
for _, foreign := range resultSlice { for _, foreign := range resultSlice {
for _, local := range slice { for _, local := range slice {
if local.{{.Function.LocalAssignment}} == foreign.{{.Function.ForeignAssignment}} { if local.{{.Function.LocalAssignment}} == foreign.{{.Function.ForeignAssignment}} {
if local.R == nil { if local.R == nil {
local.R = &{{$varNameSingular}}R{} local.R = &{{$varNameSingular}}R{}
} }
local.R.{{.Function.Name}} = foreign local.R.{{.Function.Name}} = foreign
break break
} }
} }
} }
return nil return nil
} }
{{- end -}}{{- /* end with */ -}} {{- end -}}{{- /* end with */ -}}
{{end -}}{{- /* end define */ -}} {{end -}}{{- /* end define */ -}}
{{- /* Begin execution of template for one-to-one eager load */ -}} {{- /* Begin execution of template for one-to-one eager load */ -}}
{{- if .Table.IsJoinTable -}} {{- if .Table.IsJoinTable -}}
{{- else -}} {{- else -}}
{{- $dot := . -}} {{- $dot := . -}}
{{- range .Table.FKeys -}} {{- range .Table.FKeys -}}
{{- $txt := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table . -}} {{- $txt := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table . -}}
{{- template "relationship_to_one_eager_helper" (preserveDot $dot $txt) -}} {{- template "relationship_to_one_eager_helper" (preserveDot $dot $txt) -}}
{{- end -}} {{- end -}}
{{end}} {{end}}

View file

@ -1,139 +1,139 @@
{{- /* Begin execution of template for many-to-one or many-to-many eager load */ -}} {{- /* Begin execution of template for many-to-one or many-to-many eager load */ -}}
{{- if .Table.IsJoinTable -}} {{- if .Table.IsJoinTable -}}
{{- else -}} {{- else -}}
{{- $dot := . -}} {{- $dot := . -}}
{{- range .Table.ToManyRelationships -}} {{- range .Table.ToManyRelationships -}}
{{- if (and .ForeignColumnUnique (not .ToJoinTable)) -}} {{- if (and .ForeignColumnUnique (not .ToJoinTable)) -}}
{{- /* Begin execution of template for many-to-one eager load */ -}} {{- /* Begin execution of template for many-to-one eager load */ -}}
{{- $txt := textsFromOneToOneRelationship $dot.PkgName $dot.Tables $dot.Table . -}} {{- $txt := textsFromOneToOneRelationship $dot.PkgName $dot.Tables $dot.Table . -}}
{{- template "relationship_to_one_eager_helper" (preserveDot $dot $txt) -}} {{- template "relationship_to_one_eager_helper" (preserveDot $dot $txt) -}}
{{- else -}} {{- else -}}
{{- /* Begin execution of template for many-to-many eager load */ -}} {{- /* Begin execution of template for many-to-many eager load */ -}}
{{- $varNameSingular := $dot.Table.Name | singular | camelCase -}} {{- $varNameSingular := $dot.Table.Name | singular | camelCase -}}
{{- $txt := textsFromRelationship $dot.Tables $dot.Table . -}} {{- $txt := textsFromRelationship $dot.Tables $dot.Table . -}}
{{- $arg := printf "maybe%s" $txt.LocalTable.NameGo -}} {{- $arg := printf "maybe%s" $txt.LocalTable.NameGo -}}
{{- $slice := printf "%sSlice" $txt.LocalTable.NameGo -}} {{- $slice := printf "%sSlice" $txt.LocalTable.NameGo -}}
{{- $schemaForeignTable := .ForeignTable | $dot.SchemaTable -}} {{- $schemaForeignTable := .ForeignTable | $dot.SchemaTable -}}
// Load{{$txt.Function.Name}} allows an eager lookup of values, cached into the // Load{{$txt.Function.Name}} allows an eager lookup of values, cached into the
// loaded structs of the objects. // loaded structs of the objects.
func ({{$varNameSingular}}L) Load{{$txt.Function.Name}}(e boil.Executor, singular bool, {{$arg}} interface{}) error { func ({{$varNameSingular}}L) Load{{$txt.Function.Name}}(e boil.Executor, singular bool, {{$arg}} interface{}) error {
var slice []*{{$txt.LocalTable.NameGo}} var slice []*{{$txt.LocalTable.NameGo}}
var object *{{$txt.LocalTable.NameGo}} var object *{{$txt.LocalTable.NameGo}}
count := 1 count := 1
if singular { if singular {
object = {{$arg}}.(*{{$txt.LocalTable.NameGo}}) object = {{$arg}}.(*{{$txt.LocalTable.NameGo}})
} else { } else {
slice = *{{$arg}}.(*{{$slice}}) slice = *{{$arg}}.(*{{$slice}})
count = len(slice) count = len(slice)
} }
args := make([]interface{}, count) args := make([]interface{}, count)
if singular { if singular {
args[0] = object.{{.Column | titleCase}} args[0] = object.{{.Column | titleCase}}
} else { } else {
for i, obj := range slice { for i, obj := range slice {
args[i] = obj.{{.Column | titleCase}} args[i] = obj.{{.Column | titleCase}}
} }
} }
{{if .ToJoinTable -}} {{if .ToJoinTable -}}
{{- $schemaJoinTable := .JoinTable | $dot.SchemaTable -}} {{- $schemaJoinTable := .JoinTable | $dot.SchemaTable -}}
query := fmt.Sprintf( query := fmt.Sprintf(
"select {{id 0 | $dot.Quotes}}.*, {{id 1 | $dot.Quotes}}.{{.JoinLocalColumn | $dot.Quotes}} from {{$schemaForeignTable}} as {{id 0 | $dot.Quotes}} inner join {{$schemaJoinTable}} as {{id 1 | $dot.Quotes}} on {{id 0 | $dot.Quotes}}.{{.ForeignColumn | $dot.Quotes}} = {{id 1 | $dot.Quotes}}.{{.JoinForeignColumn | $dot.Quotes}} where {{id 1 | $dot.Quotes}}.{{.JoinLocalColumn | $dot.Quotes}} in (%s)", "select {{id 0 | $dot.Quotes}}.*, {{id 1 | $dot.Quotes}}.{{.JoinLocalColumn | $dot.Quotes}} from {{$schemaForeignTable}} as {{id 0 | $dot.Quotes}} inner join {{$schemaJoinTable}} as {{id 1 | $dot.Quotes}} on {{id 0 | $dot.Quotes}}.{{.ForeignColumn | $dot.Quotes}} = {{id 1 | $dot.Quotes}}.{{.JoinForeignColumn | $dot.Quotes}} where {{id 1 | $dot.Quotes}}.{{.JoinLocalColumn | $dot.Quotes}} in (%s)",
strmangle.Placeholders(dialect.IndexPlaceholders, count, 1, 1), strmangle.Placeholders(dialect.IndexPlaceholders, count, 1, 1),
) )
{{else -}} {{else -}}
query := fmt.Sprintf( query := fmt.Sprintf(
"select * from {{$schemaForeignTable}} where {{.ForeignColumn | $dot.Quotes}} in (%s)", "select * from {{$schemaForeignTable}} where {{.ForeignColumn | $dot.Quotes}} in (%s)",
strmangle.Placeholders(dialect.IndexPlaceholders, count, 1, 1), strmangle.Placeholders(dialect.IndexPlaceholders, count, 1, 1),
) )
{{end -}} {{end -}}
if boil.DebugMode { if boil.DebugMode {
fmt.Fprintf(boil.DebugWriter, "%s\n%v\n", query, args) fmt.Fprintf(boil.DebugWriter, "%s\n%v\n", query, args)
} }
results, err := e.Query(query, args...) results, err := e.Query(query, args...)
if err != nil { if err != nil {
return errors.Wrap(err, "failed to eager load {{.ForeignTable}}") return errors.Wrap(err, "failed to eager load {{.ForeignTable}}")
} }
defer results.Close() defer results.Close()
var resultSlice []*{{$txt.ForeignTable.NameGo}} var resultSlice []*{{$txt.ForeignTable.NameGo}}
{{if .ToJoinTable -}} {{if .ToJoinTable -}}
{{- $foreignTable := getTable $dot.Tables .ForeignTable -}} {{- $foreignTable := getTable $dot.Tables .ForeignTable -}}
{{- $joinTable := getTable $dot.Tables .JoinTable -}} {{- $joinTable := getTable $dot.Tables .JoinTable -}}
{{- $localCol := $joinTable.GetColumn .JoinLocalColumn}} {{- $localCol := $joinTable.GetColumn .JoinLocalColumn}}
var localJoinCols []{{$localCol.Type}} var localJoinCols []{{$localCol.Type}}
for results.Next() { for results.Next() {
one := new({{$txt.ForeignTable.NameGo}}) one := new({{$txt.ForeignTable.NameGo}})
var localJoinCol {{$localCol.Type}} var localJoinCol {{$localCol.Type}}
err = results.Scan({{$foreignTable.Columns | columnNames | stringMap $dot.StringFuncs.titleCase | prefixStringSlice "&one." | join ", "}}, &localJoinCol) err = results.Scan({{$foreignTable.Columns | columnNames | stringMap $dot.StringFuncs.titleCase | prefixStringSlice "&one." | join ", "}}, &localJoinCol)
if err = results.Err(); err != nil { if err = results.Err(); err != nil {
return errors.Wrap(err, "failed to plebian-bind eager loaded slice {{.ForeignTable}}") return errors.Wrap(err, "failed to plebian-bind eager loaded slice {{.ForeignTable}}")
} }
resultSlice = append(resultSlice, one) resultSlice = append(resultSlice, one)
localJoinCols = append(localJoinCols, localJoinCol) localJoinCols = append(localJoinCols, localJoinCol)
} }
if err = results.Err(); err != nil { if err = results.Err(); err != nil {
return errors.Wrap(err, "failed to plebian-bind eager loaded slice {{.ForeignTable}}") return errors.Wrap(err, "failed to plebian-bind eager loaded slice {{.ForeignTable}}")
} }
{{else -}} {{else -}}
if err = boil.Bind(results, &resultSlice); err != nil { if err = boil.Bind(results, &resultSlice); err != nil {
return errors.Wrap(err, "failed to bind eager loaded slice {{.ForeignTable}}") return errors.Wrap(err, "failed to bind eager loaded slice {{.ForeignTable}}")
} }
{{end}} {{end}}
{{if not $dot.NoHooks -}} {{if not $dot.NoHooks -}}
if len({{.ForeignTable | singular | camelCase}}AfterSelectHooks) != 0 { if len({{.ForeignTable | singular | camelCase}}AfterSelectHooks) != 0 {
for _, obj := range resultSlice { for _, obj := range resultSlice {
if err := obj.doAfterSelectHooks(e); err != nil { if err := obj.doAfterSelectHooks(e); err != nil {
return err return err
} }
} }
} }
{{- end}} {{- end}}
if singular { if singular {
if object.R == nil { if object.R == nil {
object.R = &{{$varNameSingular}}R{} object.R = &{{$varNameSingular}}R{}
} }
object.R.{{$txt.Function.Name}} = resultSlice object.R.{{$txt.Function.Name}} = resultSlice
return nil return nil
} }
{{if .ToJoinTable -}} {{if .ToJoinTable -}}
for i, foreign := range resultSlice { for i, foreign := range resultSlice {
localJoinCol := localJoinCols[i] localJoinCol := localJoinCols[i]
for _, local := range slice { for _, local := range slice {
if local.{{$txt.Function.LocalAssignment}} == localJoinCol { if local.{{$txt.Function.LocalAssignment}} == localJoinCol {
if local.R == nil { if local.R == nil {
local.R = &{{$varNameSingular}}R{} local.R = &{{$varNameSingular}}R{}
} }
local.R.{{$txt.Function.Name}} = append(local.R.{{$txt.Function.Name}}, foreign) local.R.{{$txt.Function.Name}} = append(local.R.{{$txt.Function.Name}}, foreign)
break break
} }
} }
} }
{{else -}} {{else -}}
for _, foreign := range resultSlice { for _, foreign := range resultSlice {
for _, local := range slice { for _, local := range slice {
if local.{{$txt.Function.LocalAssignment}} == foreign.{{$txt.Function.ForeignAssignment}} { if local.{{$txt.Function.LocalAssignment}} == foreign.{{$txt.Function.ForeignAssignment}} {
if local.R == nil { if local.R == nil {
local.R = &{{$varNameSingular}}R{} local.R = &{{$varNameSingular}}R{}
} }
local.R.{{$txt.Function.Name}} = append(local.R.{{$txt.Function.Name}}, foreign) local.R.{{$txt.Function.Name}} = append(local.R.{{$txt.Function.Name}}, foreign)
break break
} }
} }
} }
{{end}} {{end}}
return nil return nil
} }
{{end -}}{{/* if ForeignColumnUnique */}} {{end -}}{{/* if ForeignColumnUnique */}}

View file

@ -1,105 +1,105 @@
{{- define "relationship_to_one_setops_helper" -}} {{- define "relationship_to_one_setops_helper" -}}
{{- $tmplData := .Dot -}}{{/* .Dot holds the root templateData struct, passed in through preserveDot */}} {{- $tmplData := .Dot -}}{{/* .Dot holds the root templateData struct, passed in through preserveDot */}}
{{- with .Rel -}} {{- with .Rel -}}
{{- $varNameSingular := .ForeignKey.ForeignTable | singular | camelCase -}} {{- $varNameSingular := .ForeignKey.ForeignTable | singular | camelCase -}}
{{- $localNameSingular := .ForeignKey.Table | singular | camelCase}} {{- $localNameSingular := .ForeignKey.Table | singular | camelCase}}
// Set{{.Function.Name}} of the {{.ForeignKey.Table | singular}} to the related item. // Set{{.Function.Name}} of the {{.ForeignKey.Table | singular}} to the related item.
// Sets {{.Function.Receiver}}.R.{{.Function.Name}} to related. // Sets {{.Function.Receiver}}.R.{{.Function.Name}} to related.
// Adds {{.Function.Receiver}} to related.R.{{.Function.ForeignName}}. // Adds {{.Function.Receiver}} to related.R.{{.Function.ForeignName}}.
func ({{.Function.Receiver}} *{{.LocalTable.NameGo}}) Set{{.Function.Name}}(exec boil.Executor, insert bool, related *{{.ForeignTable.NameGo}}) error { func ({{.Function.Receiver}} *{{.LocalTable.NameGo}}) Set{{.Function.Name}}(exec boil.Executor, insert bool, related *{{.ForeignTable.NameGo}}) error {
var err error var err error
if insert { if insert {
if err = related.Insert(exec); err != nil { if err = related.Insert(exec); err != nil {
return errors.Wrap(err, "failed to insert into foreign table") return errors.Wrap(err, "failed to insert into foreign table")
} }
} }
oldVal := {{.Function.Receiver}}.{{.LocalTable.ColumnNameGo}} oldVal := {{.Function.Receiver}}.{{.LocalTable.ColumnNameGo}}
{{.Function.Receiver}}.{{.Function.LocalAssignment}} = related.{{.Function.ForeignAssignment}} {{.Function.Receiver}}.{{.Function.LocalAssignment}} = related.{{.Function.ForeignAssignment}}
if err = {{.Function.Receiver}}.Update(exec, "{{.ForeignKey.Column}}"); err != nil { if err = {{.Function.Receiver}}.Update(exec, "{{.ForeignKey.Column}}"); err != nil {
{{.Function.Receiver}}.{{.LocalTable.ColumnNameGo}} = oldVal {{.Function.Receiver}}.{{.LocalTable.ColumnNameGo}} = oldVal
return errors.Wrap(err, "failed to update local table") return errors.Wrap(err, "failed to update local table")
} }
if {{.Function.Receiver}}.R == nil { if {{.Function.Receiver}}.R == nil {
{{.Function.Receiver}}.R = &{{$localNameSingular}}R{ {{.Function.Receiver}}.R = &{{$localNameSingular}}R{
{{.Function.Name}}: related, {{.Function.Name}}: related,
} }
} else { } else {
{{.Function.Receiver}}.R.{{.Function.Name}} = related {{.Function.Receiver}}.R.{{.Function.Name}} = related
} }
{{if (or .ForeignKey.Unique .Function.OneToOne) -}} {{if (or .ForeignKey.Unique .Function.OneToOne) -}}
if related.R == nil { if related.R == nil {
related.R = &{{$varNameSingular}}R{ related.R = &{{$varNameSingular}}R{
{{.Function.ForeignName}}: {{.Function.Receiver}}, {{.Function.ForeignName}}: {{.Function.Receiver}},
} }
} else { } else {
related.R.{{.Function.ForeignName}} = {{.Function.Receiver}} related.R.{{.Function.ForeignName}} = {{.Function.Receiver}}
} }
{{else -}} {{else -}}
if related.R == nil { if related.R == nil {
related.R = &{{$varNameSingular}}R{ related.R = &{{$varNameSingular}}R{
{{.Function.ForeignName}}: {{.LocalTable.NameGo}}Slice{{"{"}}{{.Function.Receiver}}{{"}"}}, {{.Function.ForeignName}}: {{.LocalTable.NameGo}}Slice{{"{"}}{{.Function.Receiver}}{{"}"}},
} }
} else { } else {
related.R.{{.Function.ForeignName}} = append(related.R.{{.Function.ForeignName}}, {{.Function.Receiver}}) related.R.{{.Function.ForeignName}} = append(related.R.{{.Function.ForeignName}}, {{.Function.Receiver}})
} }
{{end -}} {{end -}}
{{if .ForeignKey.Nullable}} {{if .ForeignKey.Nullable}}
{{.Function.Receiver}}.{{.LocalTable.ColumnNameGo}}.Valid = true {{.Function.Receiver}}.{{.LocalTable.ColumnNameGo}}.Valid = true
{{end -}} {{end -}}
return nil return nil
} }
{{- if .ForeignKey.Nullable}} {{- if .ForeignKey.Nullable}}
// Remove{{.Function.Name}} relationship. // Remove{{.Function.Name}} relationship.
// Sets {{.Function.Receiver}}.R.{{.Function.Name}} to nil. // Sets {{.Function.Receiver}}.R.{{.Function.Name}} to nil.
// Removes {{.Function.Receiver}} from all passed in related items' relationships struct (Optional). // Removes {{.Function.Receiver}} from all passed in related items' relationships struct (Optional).
func ({{.Function.Receiver}} *{{.LocalTable.NameGo}}) Remove{{.Function.Name}}(exec boil.Executor, related *{{.ForeignTable.NameGo}}) error { func ({{.Function.Receiver}} *{{.LocalTable.NameGo}}) Remove{{.Function.Name}}(exec boil.Executor, related *{{.ForeignTable.NameGo}}) error {
var err error var err error
{{.Function.Receiver}}.{{.LocalTable.ColumnNameGo}}.Valid = false {{.Function.Receiver}}.{{.LocalTable.ColumnNameGo}}.Valid = false
if err = {{.Function.Receiver}}.Update(exec, "{{.ForeignKey.Column}}"); err != nil { if err = {{.Function.Receiver}}.Update(exec, "{{.ForeignKey.Column}}"); err != nil {
{{.Function.Receiver}}.{{.LocalTable.ColumnNameGo}}.Valid = true {{.Function.Receiver}}.{{.LocalTable.ColumnNameGo}}.Valid = true
return errors.Wrap(err, "failed to update local table") return errors.Wrap(err, "failed to update local table")
} }
{{.Function.Receiver}}.R.{{.Function.Name}} = nil {{.Function.Receiver}}.R.{{.Function.Name}} = nil
if related == nil || related.R == nil { if related == nil || related.R == nil {
return nil return nil
} }
{{if .ForeignKey.Unique -}} {{if .ForeignKey.Unique -}}
related.R.{{.Function.ForeignName}} = nil related.R.{{.Function.ForeignName}} = nil
{{else -}} {{else -}}
for i, ri := range related.R.{{.Function.ForeignName}} { for i, ri := range related.R.{{.Function.ForeignName}} {
if {{.Function.Receiver}}.{{.Function.LocalAssignment}} != ri.{{.Function.LocalAssignment}} { if {{.Function.Receiver}}.{{.Function.LocalAssignment}} != ri.{{.Function.LocalAssignment}} {
continue continue
} }
ln := len(related.R.{{.Function.ForeignName}}) ln := len(related.R.{{.Function.ForeignName}})
if ln > 1 && i < ln-1 { if ln > 1 && i < ln-1 {
related.R.{{.Function.ForeignName}}[i] = related.R.{{.Function.ForeignName}}[ln-1] related.R.{{.Function.ForeignName}}[i] = related.R.{{.Function.ForeignName}}[ln-1]
} }
related.R.{{.Function.ForeignName}} = related.R.{{.Function.ForeignName}}[:ln-1] related.R.{{.Function.ForeignName}} = related.R.{{.Function.ForeignName}}[:ln-1]
break break
} }
{{end -}} {{end -}}
return nil return nil
} }
{{- end -}}{{/* if foreignkey nullable */}} {{- end -}}{{/* if foreignkey nullable */}}
{{end -}}{{/* end with */}} {{end -}}{{/* end with */}}
{{- end -}}{{/* end define */}} {{- end -}}{{/* end define */}}
{{- /* Begin execution of template for one-to-one setops */ -}} {{- /* Begin execution of template for one-to-one setops */ -}}
{{- if .Table.IsJoinTable -}} {{- if .Table.IsJoinTable -}}
{{- else -}} {{- else -}}
{{- $dot := . -}} {{- $dot := . -}}
{{- range .Table.FKeys -}} {{- range .Table.FKeys -}}
{{- $txt := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table . -}} {{- $txt := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table . -}}
{{- template "relationship_to_one_setops_helper" (preserveDot $dot $txt) -}} {{- template "relationship_to_one_setops_helper" (preserveDot $dot $txt) -}}
{{- end -}} {{- end -}}
{{- end -}} {{- end -}}

View file

@ -1,93 +1,93 @@
{{- /* Begin execution of template for many-to-one or many-to-many setops */ -}} {{- /* Begin execution of template for many-to-one or many-to-many setops */ -}}
{{- if .Table.IsJoinTable -}} {{- if .Table.IsJoinTable -}}
{{- else -}} {{- else -}}
{{- $dot := . -}} {{- $dot := . -}}
{{- $table := .Table -}} {{- $table := .Table -}}
{{- range .Table.ToManyRelationships -}} {{- range .Table.ToManyRelationships -}}
{{- $varNameSingular := .ForeignTable | singular | camelCase -}} {{- $varNameSingular := .ForeignTable | singular | camelCase -}}
{{- if (and .ForeignColumnUnique (not .ToJoinTable)) -}} {{- if (and .ForeignColumnUnique (not .ToJoinTable)) -}}
{{- /* Begin execution of template for many-to-one setops */ -}} {{- /* Begin execution of template for many-to-one setops */ -}}
{{- $txt := textsFromOneToOneRelationship $dot.PkgName $dot.Tables $table . -}} {{- $txt := textsFromOneToOneRelationship $dot.PkgName $dot.Tables $table . -}}
{{- template "relationship_to_one_setops_helper" (preserveDot $dot $txt) -}} {{- template "relationship_to_one_setops_helper" (preserveDot $dot $txt) -}}
{{- else -}} {{- else -}}
{{- $rel := textsFromRelationship $dot.Tables $table . -}} {{- $rel := textsFromRelationship $dot.Tables $table . -}}
{{- $localNameSingular := .Table | singular | camelCase -}} {{- $localNameSingular := .Table | singular | camelCase -}}
{{- $foreignNameSingular := .ForeignTable | singular | camelCase}} {{- $foreignNameSingular := .ForeignTable | singular | camelCase}}
// Add{{$rel.Function.Name}} adds the given related objects to the existing relationships // Add{{$rel.Function.Name}} adds the given related objects to the existing relationships
// of the {{$table.Name | singular}}, optionally inserting them as new records. // of the {{$table.Name | singular}}, optionally inserting them as new records.
// Appends related to {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}}. // Appends related to {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}}.
// Sets related.R.{{$rel.Function.ForeignName}} appropriately. // Sets related.R.{{$rel.Function.ForeignName}} appropriately.
func ({{$rel.Function.Receiver}} *{{$rel.LocalTable.NameGo}}) Add{{$rel.Function.Name}}(exec boil.Executor, insert bool, related ...*{{$rel.ForeignTable.NameGo}}) error { func ({{$rel.Function.Receiver}} *{{$rel.LocalTable.NameGo}}) Add{{$rel.Function.Name}}(exec boil.Executor, insert bool, related ...*{{$rel.ForeignTable.NameGo}}) error {
var err error var err error
for _, rel := range related { for _, rel := range related {
{{if not .ToJoinTable -}} {{if not .ToJoinTable -}}
rel.{{$rel.Function.ForeignAssignment}} = {{$rel.Function.Receiver}}.{{$rel.Function.LocalAssignment}} rel.{{$rel.Function.ForeignAssignment}} = {{$rel.Function.Receiver}}.{{$rel.Function.LocalAssignment}}
{{if .ForeignColumnNullable -}} {{if .ForeignColumnNullable -}}
rel.{{$rel.ForeignTable.ColumnNameGo}}.Valid = true rel.{{$rel.ForeignTable.ColumnNameGo}}.Valid = true
{{end -}} {{end -}}
{{end -}} {{end -}}
if insert { if insert {
if err = rel.Insert(exec); err != nil { if err = rel.Insert(exec); err != nil {
return errors.Wrap(err, "failed to insert into foreign table") return errors.Wrap(err, "failed to insert into foreign table")
} }
}{{if not .ToJoinTable}} else { }{{if not .ToJoinTable}} else {
if err = rel.Update(exec, "{{.ForeignColumn}}"); err != nil { if err = rel.Update(exec, "{{.ForeignColumn}}"); err != nil {
return errors.Wrap(err, "failed to update foreign table") return errors.Wrap(err, "failed to update foreign table")
} }
}{{end -}} }{{end -}}
} }
{{if .ToJoinTable -}} {{if .ToJoinTable -}}
for _, rel := range related { for _, rel := range related {
query := "insert into {{.JoinTable | $dot.SchemaTable}} ({{.JoinLocalColumn | $dot.Quotes}}, {{.JoinForeignColumn | $dot.Quotes}}) values {{if $dot.Dialect.IndexPlaceholders}}($1, $2){{else}}(?, ?){{end}}" query := "insert into {{.JoinTable | $dot.SchemaTable}} ({{.JoinLocalColumn | $dot.Quotes}}, {{.JoinForeignColumn | $dot.Quotes}}) values {{if $dot.Dialect.IndexPlaceholders}}($1, $2){{else}}(?, ?){{end}}"
values := []interface{}{{"{"}}{{$rel.Function.Receiver}}.{{$rel.LocalTable.ColumnNameGo}}, rel.{{$rel.ForeignTable.ColumnNameGo}}} values := []interface{}{{"{"}}{{$rel.Function.Receiver}}.{{$rel.LocalTable.ColumnNameGo}}, rel.{{$rel.ForeignTable.ColumnNameGo}}}
if boil.DebugMode { if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, query) fmt.Fprintln(boil.DebugWriter, query)
fmt.Fprintln(boil.DebugWriter, values) fmt.Fprintln(boil.DebugWriter, values)
} }
_, err = exec.Exec(query, values...) _, err = exec.Exec(query, values...)
if err != nil { if err != nil {
return errors.Wrap(err, "failed to insert into join table") return errors.Wrap(err, "failed to insert into join table")
} }
} }
{{end -}} {{end -}}
if {{$rel.Function.Receiver}}.R == nil { if {{$rel.Function.Receiver}}.R == nil {
{{$rel.Function.Receiver}}.R = &{{$localNameSingular}}R{ {{$rel.Function.Receiver}}.R = &{{$localNameSingular}}R{
{{$rel.Function.Name}}: related, {{$rel.Function.Name}}: related,
} }
} else { } else {
{{$rel.Function.Receiver}}.R.{{$rel.Function.Name}} = append({{$rel.Function.Receiver}}.R.{{$rel.Function.Name}}, related...) {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}} = append({{$rel.Function.Receiver}}.R.{{$rel.Function.Name}}, related...)
} }
{{if .ToJoinTable -}} {{if .ToJoinTable -}}
for _, rel := range related { for _, rel := range related {
if rel.R == nil { if rel.R == nil {
rel.R = &{{$foreignNameSingular}}R{ rel.R = &{{$foreignNameSingular}}R{
{{$rel.Function.ForeignName}}: {{$rel.LocalTable.NameGo}}Slice{{"{"}}{{$rel.Function.Receiver}}{{"}"}}, {{$rel.Function.ForeignName}}: {{$rel.LocalTable.NameGo}}Slice{{"{"}}{{$rel.Function.Receiver}}{{"}"}},
} }
} else { } else {
rel.R.{{$rel.Function.ForeignName}} = append(rel.R.{{$rel.Function.ForeignName}}, {{$rel.Function.Receiver}}) rel.R.{{$rel.Function.ForeignName}} = append(rel.R.{{$rel.Function.ForeignName}}, {{$rel.Function.Receiver}})
} }
} }
{{else -}} {{else -}}
for _, rel := range related { for _, rel := range related {
if rel.R == nil { if rel.R == nil {
rel.R = &{{$foreignNameSingular}}R{ rel.R = &{{$foreignNameSingular}}R{
{{$rel.Function.ForeignName}}: {{$rel.Function.Receiver}}, {{$rel.Function.ForeignName}}: {{$rel.Function.Receiver}},
} }
} else { } else {
rel.R.{{$rel.Function.ForeignName}} = {{$rel.Function.Receiver}} rel.R.{{$rel.Function.ForeignName}} = {{$rel.Function.Receiver}}
} }
} }
{{end -}} {{end -}}
return nil return nil
} }
{{- if (or .ForeignColumnNullable .ToJoinTable)}} {{- if (or .ForeignColumnNullable .ToJoinTable)}}
// Set{{$rel.Function.Name}} removes all previously related items of the // Set{{$rel.Function.Name}} removes all previously related items of the
// {{$table.Name | singular}} replacing them completely with the passed // {{$table.Name | singular}} replacing them completely with the passed
// in related items, optionally inserting them as new records. // in related items, optionally inserting them as new records.
@ -95,126 +95,126 @@ func ({{$rel.Function.Receiver}} *{{$rel.LocalTable.NameGo}}) Add{{$rel.Function
// Replaces {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}} with related. // Replaces {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}} with related.
// Sets related.R.{{$rel.Function.ForeignName}}'s {{$rel.Function.Name}} accordingly. // Sets related.R.{{$rel.Function.ForeignName}}'s {{$rel.Function.Name}} accordingly.
func ({{$rel.Function.Receiver}} *{{$rel.LocalTable.NameGo}}) Set{{$rel.Function.Name}}(exec boil.Executor, insert bool, related ...*{{$rel.ForeignTable.NameGo}}) error { func ({{$rel.Function.Receiver}} *{{$rel.LocalTable.NameGo}}) Set{{$rel.Function.Name}}(exec boil.Executor, insert bool, related ...*{{$rel.ForeignTable.NameGo}}) error {
{{if .ToJoinTable -}} {{if .ToJoinTable -}}
query := "delete from {{.JoinTable | $dot.SchemaTable}} where {{.JoinLocalColumn | $dot.Quotes}} = {{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}}" query := "delete from {{.JoinTable | $dot.SchemaTable}} where {{.JoinLocalColumn | $dot.Quotes}} = {{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}}"
values := []interface{}{{"{"}}{{$rel.Function.Receiver}}.{{$rel.LocalTable.ColumnNameGo}}} values := []interface{}{{"{"}}{{$rel.Function.Receiver}}.{{$rel.LocalTable.ColumnNameGo}}}
{{else -}} {{else -}}
query := "update {{.ForeignTable | $dot.SchemaTable}} set {{.ForeignColumn | $dot.Quotes}} = null where {{.ForeignColumn | $dot.Quotes}} = {{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}}" query := "update {{.ForeignTable | $dot.SchemaTable}} set {{.ForeignColumn | $dot.Quotes}} = null where {{.ForeignColumn | $dot.Quotes}} = {{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}}"
values := []interface{}{{"{"}}{{$rel.Function.Receiver}}.{{$rel.LocalTable.ColumnNameGo}}} values := []interface{}{{"{"}}{{$rel.Function.Receiver}}.{{$rel.LocalTable.ColumnNameGo}}}
{{end -}} {{end -}}
if boil.DebugMode { if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, query) fmt.Fprintln(boil.DebugWriter, query)
fmt.Fprintln(boil.DebugWriter, values) fmt.Fprintln(boil.DebugWriter, values)
} }
_, err := exec.Exec(query, values...) _, err := exec.Exec(query, values...)
if err != nil { if err != nil {
return errors.Wrap(err, "failed to remove relationships before set") return errors.Wrap(err, "failed to remove relationships before set")
} }
{{if .ToJoinTable -}} {{if .ToJoinTable -}}
remove{{$rel.LocalTable.NameGo}}From{{$rel.ForeignTable.NameGo}}Slice({{$rel.Function.Receiver}}, related) remove{{$rel.LocalTable.NameGo}}From{{$rel.ForeignTable.NameGo}}Slice({{$rel.Function.Receiver}}, related)
{{$rel.Function.Receiver}}.R.{{$rel.Function.Name}} = nil {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}} = nil
{{else -}} {{else -}}
if {{$rel.Function.Receiver}}.R != nil { if {{$rel.Function.Receiver}}.R != nil {
for _, rel := range {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}} { for _, rel := range {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}} {
rel.{{$rel.ForeignTable.ColumnNameGo}}.Valid = false rel.{{$rel.ForeignTable.ColumnNameGo}}.Valid = false
if rel.R == nil { if rel.R == nil {
continue continue
} }
rel.R.{{$rel.Function.ForeignName}} = nil rel.R.{{$rel.Function.ForeignName}} = nil
} }
{{$rel.Function.Receiver}}.R.{{$rel.Function.Name}} = nil {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}} = nil
} }
{{end -}} {{end -}}
return {{$rel.Function.Receiver}}.Add{{$rel.Function.Name}}(exec, insert, related...) return {{$rel.Function.Receiver}}.Add{{$rel.Function.Name}}(exec, insert, related...)
} }
// Remove{{$rel.Function.Name}} relationships from objects passed in. // Remove{{$rel.Function.Name}} relationships from objects passed in.
// Removes related items from R.{{$rel.Function.Name}} (uses pointer comparison, removal does not keep order) // Removes related items from R.{{$rel.Function.Name}} (uses pointer comparison, removal does not keep order)
// Sets related.R.{{$rel.Function.ForeignName}}. // Sets related.R.{{$rel.Function.ForeignName}}.
func ({{$rel.Function.Receiver}} *{{$rel.LocalTable.NameGo}}) Remove{{$rel.Function.Name}}(exec boil.Executor, related ...*{{$rel.ForeignTable.NameGo}}) error { func ({{$rel.Function.Receiver}} *{{$rel.LocalTable.NameGo}}) Remove{{$rel.Function.Name}}(exec boil.Executor, related ...*{{$rel.ForeignTable.NameGo}}) error {
var err error var err error
{{if .ToJoinTable -}} {{if .ToJoinTable -}}
query := fmt.Sprintf( query := fmt.Sprintf(
"delete from {{.JoinTable | $dot.SchemaTable}} where {{.JoinLocalColumn | $dot.Quotes}} = {{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}} and {{.JoinForeignColumn | $dot.Quotes}} in (%s)", "delete from {{.JoinTable | $dot.SchemaTable}} where {{.JoinLocalColumn | $dot.Quotes}} = {{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}} and {{.JoinForeignColumn | $dot.Quotes}} in (%s)",
strmangle.Placeholders(dialect.IndexPlaceholders, len(related), 1, 1), strmangle.Placeholders(dialect.IndexPlaceholders, len(related), 1, 1),
) )
values := []interface{}{{"{"}}{{$rel.Function.Receiver}}.{{$rel.LocalTable.ColumnNameGo}}} values := []interface{}{{"{"}}{{$rel.Function.Receiver}}.{{$rel.LocalTable.ColumnNameGo}}}
if boil.DebugMode { if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, query) fmt.Fprintln(boil.DebugWriter, query)
fmt.Fprintln(boil.DebugWriter, values) fmt.Fprintln(boil.DebugWriter, values)
} }
_, err = exec.Exec(query, values...) _, err = exec.Exec(query, values...)
if err != nil { if err != nil {
return errors.Wrap(err, "failed to remove relationships before set") return errors.Wrap(err, "failed to remove relationships before set")
} }
{{else -}} {{else -}}
for _, rel := range related { for _, rel := range related {
rel.{{$rel.ForeignTable.ColumnNameGo}}.Valid = false rel.{{$rel.ForeignTable.ColumnNameGo}}.Valid = false
{{if not .ToJoinTable -}} {{if not .ToJoinTable -}}
if rel.R != nil { if rel.R != nil {
rel.R.{{$rel.Function.ForeignName}} = nil rel.R.{{$rel.Function.ForeignName}} = nil
} }
{{end -}} {{end -}}
if err = rel.Update(exec, "{{.ForeignColumn}}"); err != nil { if err = rel.Update(exec, "{{.ForeignColumn}}"); err != nil {
return err return err
} }
} }
{{end -}} {{end -}}
{{if .ToJoinTable -}} {{if .ToJoinTable -}}
remove{{$rel.LocalTable.NameGo}}From{{$rel.ForeignTable.NameGo}}Slice({{$rel.Function.Receiver}}, related) remove{{$rel.LocalTable.NameGo}}From{{$rel.ForeignTable.NameGo}}Slice({{$rel.Function.Receiver}}, related)
{{end -}} {{end -}}
if {{$rel.Function.Receiver}}.R == nil { if {{$rel.Function.Receiver}}.R == nil {
return nil return nil
} }
for _, rel := range related { for _, rel := range related {
for i, ri := range {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}} { for i, ri := range {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}} {
if rel != ri { if rel != ri {
continue continue
} }
ln := len({{$rel.Function.Receiver}}.R.{{$rel.Function.Name}}) ln := len({{$rel.Function.Receiver}}.R.{{$rel.Function.Name}})
if ln > 1 && i < ln-1 { if ln > 1 && i < ln-1 {
{{$rel.Function.Receiver}}.R.{{$rel.Function.Name}}[i] = {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}}[ln-1] {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}}[i] = {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}}[ln-1]
} }
{{$rel.Function.Receiver}}.R.{{$rel.Function.Name}} = {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}}[:ln-1] {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}} = {{$rel.Function.Receiver}}.R.{{$rel.Function.Name}}[:ln-1]
break break
} }
} }
return nil return nil
} }
{{if .ToJoinTable -}} {{if .ToJoinTable -}}
func remove{{$rel.LocalTable.NameGo}}From{{$rel.ForeignTable.NameGo}}Slice({{$rel.Function.Receiver}} *{{$rel.LocalTable.NameGo}}, related []*{{$rel.ForeignTable.NameGo}}) { func remove{{$rel.LocalTable.NameGo}}From{{$rel.ForeignTable.NameGo}}Slice({{$rel.Function.Receiver}} *{{$rel.LocalTable.NameGo}}, related []*{{$rel.ForeignTable.NameGo}}) {
for _, rel := range related { for _, rel := range related {
if rel.R == nil { if rel.R == nil {
continue continue
} }
for i, ri := range rel.R.{{$rel.Function.ForeignName}} { for i, ri := range rel.R.{{$rel.Function.ForeignName}} {
if {{$rel.Function.Receiver}}.{{$rel.Function.LocalAssignment}} != ri.{{$rel.Function.LocalAssignment}} { if {{$rel.Function.Receiver}}.{{$rel.Function.LocalAssignment}} != ri.{{$rel.Function.LocalAssignment}} {
continue continue
} }
ln := len(rel.R.{{$rel.Function.ForeignName}}) ln := len(rel.R.{{$rel.Function.ForeignName}})
if ln > 1 && i < ln-1 { if ln > 1 && i < ln-1 {
rel.R.{{$rel.Function.ForeignName}}[i] = rel.R.{{$rel.Function.ForeignName}}[ln-1] rel.R.{{$rel.Function.ForeignName}}[i] = rel.R.{{$rel.Function.ForeignName}}[ln-1]
} }
rel.R.{{$rel.Function.ForeignName}} = rel.R.{{$rel.Function.ForeignName}}[:ln-1] rel.R.{{$rel.Function.ForeignName}} = rel.R.{{$rel.Function.ForeignName}}[:ln-1]
break break
} }
} }
} }
{{end -}}{{- /* if ToJoinTable */ -}} {{end -}}{{- /* if ToJoinTable */ -}}
{{- end -}}{{- /* if nullable foreign key */ -}} {{- end -}}{{- /* if nullable foreign key */ -}}
{{- end -}}{{- /* if unique foreign key */ -}} {{- end -}}{{- /* if unique foreign key */ -}}
{{- end -}}{{- /* range relationships */ -}} {{- end -}}{{- /* range relationships */ -}}
{{- end -}}{{- /* if IsJoinTable */ -}} {{- end -}}{{- /* if IsJoinTable */ -}}

View file

@ -3,11 +3,11 @@
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
// {{$tableNamePlural}}G retrieves all records. // {{$tableNamePlural}}G retrieves all records.
func {{$tableNamePlural}}G(mods ...qm.QueryMod) {{$varNameSingular}}Query { func {{$tableNamePlural}}G(mods ...qm.QueryMod) {{$varNameSingular}}Query {
return {{$tableNamePlural}}(boil.GetDB(), mods...) return {{$tableNamePlural}}(boil.GetDB(), mods...)
} }
// {{$tableNamePlural}} retrieves all the records using an executor. // {{$tableNamePlural}} retrieves all the records using an executor.
func {{$tableNamePlural}}(exec boil.Executor, mods ...qm.QueryMod) {{$varNameSingular}}Query { func {{$tableNamePlural}}(exec boil.Executor, mods ...qm.QueryMod) {{$varNameSingular}}Query {
mods = append(mods, qm.From("{{.Table.Name | .SchemaTable}}")) mods = append(mods, qm.From("{{.Table.Name | .SchemaTable}}"))
return {{$varNameSingular}}Query{NewQuery(exec, mods...)} return {{$varNameSingular}}Query{NewQuery(exec, mods...)}
} }

View file

@ -6,51 +6,51 @@
{{- $pkArgs := joinSlices " " $pkNames $colDefs.Types | join ", " -}} {{- $pkArgs := joinSlices " " $pkNames $colDefs.Types | join ", " -}}
// {{$tableNameSingular}}FindG retrieves a single record by ID. // {{$tableNameSingular}}FindG retrieves a single record by ID.
func Find{{$tableNameSingular}}G({{$pkArgs}}, selectCols ...string) (*{{$tableNameSingular}}, error) { func Find{{$tableNameSingular}}G({{$pkArgs}}, selectCols ...string) (*{{$tableNameSingular}}, error) {
return Find{{$tableNameSingular}}(boil.GetDB(), {{$pkNames | join ", "}}, selectCols...) return Find{{$tableNameSingular}}(boil.GetDB(), {{$pkNames | join ", "}}, selectCols...)
} }
// {{$tableNameSingular}}FindGP retrieves a single record by ID, and panics on error. // {{$tableNameSingular}}FindGP retrieves a single record by ID, and panics on error.
func Find{{$tableNameSingular}}GP({{$pkArgs}}, selectCols ...string) *{{$tableNameSingular}} { func Find{{$tableNameSingular}}GP({{$pkArgs}}, selectCols ...string) *{{$tableNameSingular}} {
retobj, err := Find{{$tableNameSingular}}(boil.GetDB(), {{$pkNames | join ", "}}, selectCols...) retobj, err := Find{{$tableNameSingular}}(boil.GetDB(), {{$pkNames | join ", "}}, selectCols...)
if err != nil { if err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
return retobj return retobj
} }
// {{$tableNameSingular}}Find retrieves a single record by ID with an executor. // {{$tableNameSingular}}Find retrieves a single record by ID with an executor.
// If selectCols is empty Find will return all columns. // If selectCols is empty Find will return all columns.
func Find{{$tableNameSingular}}(exec boil.Executor, {{$pkArgs}}, selectCols ...string) (*{{$tableNameSingular}}, error) { func Find{{$tableNameSingular}}(exec boil.Executor, {{$pkArgs}}, selectCols ...string) (*{{$tableNameSingular}}, error) {
{{$varNameSingular}}Obj := &{{$tableNameSingular}}{} {{$varNameSingular}}Obj := &{{$tableNameSingular}}{}
sel := "*" sel := "*"
if len(selectCols) > 0 { if len(selectCols) > 0 {
sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",") sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",")
} }
query := fmt.Sprintf( query := fmt.Sprintf(
"select %s from {{.Table.Name | .SchemaTable}} where {{if .Dialect.IndexPlaceholders}}{{whereClause .LQ .RQ 1 .Table.PKey.Columns}}{{else}}{{whereClause .LQ .RQ 0 .Table.PKey.Columns}}{{end}}", sel, "select %s from {{.Table.Name | .SchemaTable}} where {{if .Dialect.IndexPlaceholders}}{{whereClause .LQ .RQ 1 .Table.PKey.Columns}}{{else}}{{whereClause .LQ .RQ 0 .Table.PKey.Columns}}{{end}}", sel,
) )
q := boil.SQL(exec, query, {{$pkNames | join ", "}}) q := boil.SQL(exec, query, {{$pkNames | join ", "}})
err := q.Bind({{$varNameSingular}}Obj) err := q.Bind({{$varNameSingular}}Obj)
if err != nil { if err != nil {
if errors.Cause(err) == sql.ErrNoRows { if errors.Cause(err) == sql.ErrNoRows {
return nil, sql.ErrNoRows return nil, sql.ErrNoRows
} }
return nil, errors.Wrap(err, "{{.PkgName}}: unable to select from {{.Table.Name}}") return nil, errors.Wrap(err, "{{.PkgName}}: unable to select from {{.Table.Name}}")
} }
return {{$varNameSingular}}Obj, nil return {{$varNameSingular}}Obj, nil
} }
// {{$tableNameSingular}}FindP retrieves a single record by ID with an executor, and panics on error. // {{$tableNameSingular}}FindP retrieves a single record by ID with an executor, and panics on error.
func Find{{$tableNameSingular}}P(exec boil.Executor, {{$pkArgs}}, selectCols ...string) *{{$tableNameSingular}} { func Find{{$tableNameSingular}}P(exec boil.Executor, {{$pkArgs}}, selectCols ...string) *{{$tableNameSingular}} {
retobj, err := Find{{$tableNameSingular}}(exec, {{$pkNames | join ", "}}, selectCols...) retobj, err := Find{{$tableNameSingular}}(exec, {{$pkNames | join ", "}}, selectCols...)
if err != nil { if err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
return retobj return retobj
} }

View file

@ -3,23 +3,23 @@
{{- $schemaTable := .Table.Name | .SchemaTable -}} {{- $schemaTable := .Table.Name | .SchemaTable -}}
// InsertG a single record. See Insert for whitelist behavior description. // InsertG a single record. See Insert for whitelist behavior description.
func (o *{{$tableNameSingular}}) InsertG(whitelist ... string) error { func (o *{{$tableNameSingular}}) InsertG(whitelist ... string) error {
return o.Insert(boil.GetDB(), whitelist...) return o.Insert(boil.GetDB(), whitelist...)
} }
// InsertGP a single record, and panics on error. See Insert for whitelist // InsertGP a single record, and panics on error. See Insert for whitelist
// behavior description. // behavior description.
func (o *{{$tableNameSingular}}) InsertGP(whitelist ... string) { func (o *{{$tableNameSingular}}) InsertGP(whitelist ... string) {
if err := o.Insert(boil.GetDB(), whitelist...); err != nil { if err := o.Insert(boil.GetDB(), whitelist...); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// InsertP a single record using an executor, and panics on error. See Insert // InsertP a single record using an executor, and panics on error. See Insert
// for whitelist behavior description. // for whitelist behavior description.
func (o *{{$tableNameSingular}}) InsertP(exec boil.Executor, whitelist ... string) { func (o *{{$tableNameSingular}}) InsertP(exec boil.Executor, whitelist ... string) {
if err := o.Insert(exec, whitelist...); err != nil { if err := o.Insert(exec, whitelist...); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// Insert a single record using an executor. // Insert a single record using an executor.
@ -28,115 +28,115 @@ func (o *{{$tableNameSingular}}) InsertP(exec boil.Executor, whitelist ... strin
// - All columns without a default value are included (i.e. name, age) // - All columns without a default value are included (i.e. name, age)
// - All columns with a default, but non-zero are included (i.e. health = 75) // - All columns with a default, but non-zero are included (i.e. health = 75)
func (o *{{$tableNameSingular}}) Insert(exec boil.Executor, whitelist ... string) error { func (o *{{$tableNameSingular}}) Insert(exec boil.Executor, whitelist ... string) error {
if o == nil { if o == nil {
return errors.New("{{.PkgName}}: no {{.Table.Name}} provided for insertion") return errors.New("{{.PkgName}}: no {{.Table.Name}} provided for insertion")
} }
var err error var err error
{{- template "timestamp_insert_helper" . }} {{- template "timestamp_insert_helper" . }}
{{if not .NoHooks -}} {{if not .NoHooks -}}
if err := o.doBeforeInsertHooks(exec); err != nil { if err := o.doBeforeInsertHooks(exec); err != nil {
return err return err
} }
{{- end}} {{- end}}
nzDefaults := boil.NonZeroDefaultSet({{$varNameSingular}}ColumnsWithDefault, o) nzDefaults := boil.NonZeroDefaultSet({{$varNameSingular}}ColumnsWithDefault, o)
key := makeCacheKey(whitelist, nzDefaults) key := makeCacheKey(whitelist, nzDefaults)
{{$varNameSingular}}InsertCacheMut.RLock() {{$varNameSingular}}InsertCacheMut.RLock()
cache, cached := {{$varNameSingular}}InsertCache[key] cache, cached := {{$varNameSingular}}InsertCache[key]
{{$varNameSingular}}InsertCacheMut.RUnlock() {{$varNameSingular}}InsertCacheMut.RUnlock()
if !cached { if !cached {
wl, returnColumns := strmangle.InsertColumnSet( wl, returnColumns := strmangle.InsertColumnSet(
{{$varNameSingular}}Columns, {{$varNameSingular}}Columns,
{{$varNameSingular}}ColumnsWithDefault, {{$varNameSingular}}ColumnsWithDefault,
{{$varNameSingular}}ColumnsWithoutDefault, {{$varNameSingular}}ColumnsWithoutDefault,
nzDefaults, nzDefaults,
whitelist, whitelist,
) )
cache.valueMapping, err = boil.BindMapping({{$varNameSingular}}Type, {{$varNameSingular}}Mapping, wl) cache.valueMapping, err = boil.BindMapping({{$varNameSingular}}Type, {{$varNameSingular}}Mapping, wl)
if err != nil { if err != nil {
return err return err
} }
cache.retMapping, err = boil.BindMapping({{$varNameSingular}}Type, {{$varNameSingular}}Mapping, returnColumns) cache.retMapping, err = boil.BindMapping({{$varNameSingular}}Type, {{$varNameSingular}}Mapping, returnColumns)
if err != nil { if err != nil {
return err return err
} }
cache.query = fmt.Sprintf("INSERT INTO {{$schemaTable}} ({{.LQ}}%s{{.RQ}}) VALUES (%s)", strings.Join(wl, "{{.LQ}},{{.RQ}}"), strmangle.Placeholders(dialect.IndexPlaceholders, len(wl), 1, 1)) cache.query = fmt.Sprintf("INSERT INTO {{$schemaTable}} ({{.LQ}}%s{{.RQ}}) VALUES (%s)", strings.Join(wl, "{{.LQ}},{{.RQ}}"), strmangle.Placeholders(dialect.IndexPlaceholders, len(wl), 1, 1))
if len(cache.retMapping) != 0 { if len(cache.retMapping) != 0 {
{{if .UseLastInsertID -}} {{if .UseLastInsertID -}}
cache.retQuery = fmt.Sprintf("SELECT %s FROM {{$schemaTable}} WHERE %s", strings.Join(returnColumns, "{{.LQ}},{{.RQ}}"), strmangle.WhereClause("{{.LQ}}", "{{.RQ}}", {{if .Dialect.IndexPlaceholders}}1{{else}}0{{end}}, {{$varNameSingular}}PrimaryKeyColumns)) cache.retQuery = fmt.Sprintf("SELECT %s FROM {{$schemaTable}} WHERE %s", strings.Join(returnColumns, "{{.LQ}},{{.RQ}}"), strmangle.WhereClause("{{.LQ}}", "{{.RQ}}", {{if .Dialect.IndexPlaceholders}}1{{else}}0{{end}}, {{$varNameSingular}}PrimaryKeyColumns))
{{else -}} {{else -}}
cache.query += fmt.Sprintf(" RETURNING {{.LQ}}%s{{.RQ}}", strings.Join(returnColumns, "{{.LQ}},{{.RQ}}")) cache.query += fmt.Sprintf(" RETURNING {{.LQ}}%s{{.RQ}}", strings.Join(returnColumns, "{{.LQ}},{{.RQ}}"))
{{end -}} {{end -}}
} }
} }
value := reflect.Indirect(reflect.ValueOf(o)) value := reflect.Indirect(reflect.ValueOf(o))
vals := boil.ValuesFromMapping(value, cache.valueMapping) vals := boil.ValuesFromMapping(value, cache.valueMapping)
{{if .UseLastInsertID}} {{if .UseLastInsertID}}
if boil.DebugMode { if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, cache.query) fmt.Fprintln(boil.DebugWriter, cache.query)
fmt.Fprintln(boil.DebugWriter, vals) fmt.Fprintln(boil.DebugWriter, vals)
} }
result, err := exec.Exec(cache.query, vals...) result, err := exec.Exec(cache.query, vals...)
if err != nil { if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to insert into {{.Table.Name}}") return errors.Wrap(err, "{{.PkgName}}: unable to insert into {{.Table.Name}}")
} }
if len(cache.retMapping) == 0 { if len(cache.retMapping) == 0 {
{{if not .NoHooks -}} {{if not .NoHooks -}}
return o.doAfterInsertHooks(exec) return o.doAfterInsertHooks(exec)
{{else -}} {{else -}}
return nil return nil
{{end -}} {{end -}}
} }
lastID, err := result.LastInsertId() lastID, err := result.LastInsertId()
if err != nil || lastID == 0 || len({{$varNameSingular}}PrimaryKeyColumns) != 1 { if err != nil || lastID == 0 || len({{$varNameSingular}}PrimaryKeyColumns) != 1 {
return ErrSyncFail return ErrSyncFail
} }
if boil.DebugMode { if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, cache.retQuery) fmt.Fprintln(boil.DebugWriter, cache.retQuery)
fmt.Fprintln(boil.DebugWriter, lastID) fmt.Fprintln(boil.DebugWriter, lastID)
} }
err = exec.QueryRow(cache.retQuery, lastID).Scan(boil.PtrsFromMapping(value, cache.retMapping)...) err = exec.QueryRow(cache.retQuery, lastID).Scan(boil.PtrsFromMapping(value, cache.retMapping)...)
if err != nil { if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to populate default values for {{.Table.Name}}") return errors.Wrap(err, "{{.PkgName}}: unable to populate default values for {{.Table.Name}}")
} }
{{else}} {{else}}
if len(cache.retMapping) != 0 { if len(cache.retMapping) != 0 {
err = exec.QueryRow(cache.query, vals...).Scan(boil.PtrsFromMapping(value, cache.retMapping)...) err = exec.QueryRow(cache.query, vals...).Scan(boil.PtrsFromMapping(value, cache.retMapping)...)
} else { } else {
_, err = exec.Exec(cache.query, vals...) _, err = exec.Exec(cache.query, vals...)
} }
if boil.DebugMode { if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, cache.query) fmt.Fprintln(boil.DebugWriter, cache.query)
fmt.Fprintln(boil.DebugWriter, vals) fmt.Fprintln(boil.DebugWriter, vals)
} }
if err != nil { if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to insert into {{.Table.Name}}") return errors.Wrap(err, "{{.PkgName}}: unable to insert into {{.Table.Name}}")
} }
{{end}} {{end}}
if !cached { if !cached {
{{$varNameSingular}}InsertCacheMut.Lock() {{$varNameSingular}}InsertCacheMut.Lock()
{{$varNameSingular}}InsertCache[key] = cache {{$varNameSingular}}InsertCache[key] = cache
{{$varNameSingular}}InsertCacheMut.Unlock() {{$varNameSingular}}InsertCacheMut.Unlock()
} }
{{if not .NoHooks -}} {{if not .NoHooks -}}
return o.doAfterInsertHooks(exec) return o.doAfterInsertHooks(exec)
{{- else -}} {{- else -}}
return nil return nil
{{- end}} {{- end}}
} }

View file

@ -7,25 +7,25 @@
// UpdateG a single {{$tableNameSingular}} record. See Update for // UpdateG a single {{$tableNameSingular}} record. See Update for
// whitelist behavior description. // whitelist behavior description.
func (o *{{$tableNameSingular}}) UpdateG(whitelist ...string) error { func (o *{{$tableNameSingular}}) UpdateG(whitelist ...string) error {
return o.Update(boil.GetDB(), whitelist...) return o.Update(boil.GetDB(), whitelist...)
} }
// UpdateGP a single {{$tableNameSingular}} record. // UpdateGP a single {{$tableNameSingular}} record.
// UpdateGP takes a whitelist of column names that should be updated. // UpdateGP takes a whitelist of column names that should be updated.
// Panics on error. See Update for whitelist behavior description. // Panics on error. See Update for whitelist behavior description.
func (o *{{$tableNameSingular}}) UpdateGP(whitelist ...string) { func (o *{{$tableNameSingular}}) UpdateGP(whitelist ...string) {
if err := o.Update(boil.GetDB(), whitelist...); err != nil { if err := o.Update(boil.GetDB(), whitelist...); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// UpdateP uses an executor to update the {{$tableNameSingular}}, and panics on error. // UpdateP uses an executor to update the {{$tableNameSingular}}, and panics on error.
// See Update for whitelist behavior description. // See Update for whitelist behavior description.
func (o *{{$tableNameSingular}}) UpdateP(exec boil.Executor, whitelist ... string) { func (o *{{$tableNameSingular}}) UpdateP(exec boil.Executor, whitelist ... string) {
err := o.Update(exec, whitelist...) err := o.Update(exec, whitelist...)
if err != nil { if err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// Update uses an executor to update the {{$tableNameSingular}}. // Update uses an executor to update the {{$tableNameSingular}}.
@ -36,147 +36,147 @@ func (o *{{$tableNameSingular}}) UpdateP(exec boil.Executor, whitelist ... strin
// Update does not automatically update the record in case of default values. Use .Reload() // Update does not automatically update the record in case of default values. Use .Reload()
// to refresh the records. // to refresh the records.
func (o *{{$tableNameSingular}}) Update(exec boil.Executor, whitelist ... string) error { func (o *{{$tableNameSingular}}) Update(exec boil.Executor, whitelist ... string) error {
{{- template "timestamp_update_helper" . -}} {{- template "timestamp_update_helper" . -}}
var err error var err error
{{if not .NoHooks -}} {{if not .NoHooks -}}
if err = o.doBeforeUpdateHooks(exec); err != nil { if err = o.doBeforeUpdateHooks(exec); err != nil {
return err return err
} }
{{end -}} {{end -}}
key := makeCacheKey(whitelist, nil) key := makeCacheKey(whitelist, nil)
{{$varNameSingular}}UpdateCacheMut.RLock() {{$varNameSingular}}UpdateCacheMut.RLock()
cache, cached := {{$varNameSingular}}UpdateCache[key] cache, cached := {{$varNameSingular}}UpdateCache[key]
{{$varNameSingular}}UpdateCacheMut.RUnlock() {{$varNameSingular}}UpdateCacheMut.RUnlock()
if !cached { if !cached {
wl := strmangle.UpdateColumnSet({{$varNameSingular}}Columns, {{$varNameSingular}}PrimaryKeyColumns, whitelist) wl := strmangle.UpdateColumnSet({{$varNameSingular}}Columns, {{$varNameSingular}}PrimaryKeyColumns, whitelist)
cache.query = fmt.Sprintf("UPDATE {{$schemaTable}} SET %s WHERE %s", cache.query = fmt.Sprintf("UPDATE {{$schemaTable}} SET %s WHERE %s",
strmangle.SetParamNames("{{.LQ}}", "{{.RQ}}", {{if .Dialect.IndexPlaceholders}}1{{else}}0{{end}}, wl), strmangle.SetParamNames("{{.LQ}}", "{{.RQ}}", {{if .Dialect.IndexPlaceholders}}1{{else}}0{{end}}, wl),
strmangle.WhereClause("{{.LQ}}", "{{.RQ}}", {{if .Dialect.IndexPlaceholders}}len(wl)+1{{else}}0{{end}}, {{$varNameSingular}}PrimaryKeyColumns), strmangle.WhereClause("{{.LQ}}", "{{.RQ}}", {{if .Dialect.IndexPlaceholders}}len(wl)+1{{else}}0{{end}}, {{$varNameSingular}}PrimaryKeyColumns),
) )
cache.valueMapping, err = boil.BindMapping({{$varNameSingular}}Type, {{$varNameSingular}}Mapping, append(wl, {{$varNameSingular}}PrimaryKeyColumns...)) cache.valueMapping, err = boil.BindMapping({{$varNameSingular}}Type, {{$varNameSingular}}Mapping, append(wl, {{$varNameSingular}}PrimaryKeyColumns...))
if err != nil { if err != nil {
return err return err
} }
} }
if len(cache.valueMapping) == 0 { if len(cache.valueMapping) == 0 {
return errors.New("{{.PkgName}}: unable to update {{.Table.Name}}, could not build whitelist") return errors.New("{{.PkgName}}: unable to update {{.Table.Name}}, could not build whitelist")
} }
values := boil.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping) values := boil.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)
if boil.DebugMode { if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, cache.query) fmt.Fprintln(boil.DebugWriter, cache.query)
fmt.Fprintln(boil.DebugWriter, values) fmt.Fprintln(boil.DebugWriter, values)
} }
result, err := exec.Exec(cache.query, values...) result, err := exec.Exec(cache.query, values...)
if err != nil { if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to update {{.Table.Name}} row") return errors.Wrap(err, "{{.PkgName}}: unable to update {{.Table.Name}} row")
} }
if r, err := result.RowsAffected(); err == nil && r != 1 { if r, err := result.RowsAffected(); err == nil && r != 1 {
return errors.Errorf("failed to update single row, updated %d rows", r) return errors.Errorf("failed to update single row, updated %d rows", r)
} }
if !cached { if !cached {
{{$varNameSingular}}UpdateCacheMut.Lock() {{$varNameSingular}}UpdateCacheMut.Lock()
{{$varNameSingular}}UpdateCache[key] = cache {{$varNameSingular}}UpdateCache[key] = cache
{{$varNameSingular}}UpdateCacheMut.Unlock() {{$varNameSingular}}UpdateCacheMut.Unlock()
} }
{{if not .NoHooks -}} {{if not .NoHooks -}}
return o.doAfterUpdateHooks(exec) return o.doAfterUpdateHooks(exec)
{{- else -}} {{- else -}}
return nil return nil
{{- end}} {{- end}}
} }
// UpdateAllP updates all rows with matching column names, and panics on error. // UpdateAllP updates all rows with matching column names, and panics on error.
func (q {{$varNameSingular}}Query) UpdateAllP(cols M) { func (q {{$varNameSingular}}Query) UpdateAllP(cols M) {
if err := q.UpdateAll(cols); err != nil { if err := q.UpdateAll(cols); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// UpdateAll updates all rows with the specified column values. // UpdateAll updates all rows with the specified column values.
func (q {{$varNameSingular}}Query) UpdateAll(cols M) error { func (q {{$varNameSingular}}Query) UpdateAll(cols M) error {
boil.SetUpdate(q.Query, cols) boil.SetUpdate(q.Query, cols)
_, err := q.Query.ExecQuery() _, err := q.Query.ExecQuery()
if err != nil { if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to update all for {{.Table.Name}}") return errors.Wrap(err, "{{.PkgName}}: unable to update all for {{.Table.Name}}")
} }
return nil return nil
} }
// UpdateAllG updates all rows with the specified column values. // UpdateAllG updates all rows with the specified column values.
func (o {{$tableNameSingular}}Slice) UpdateAllG(cols M) error { func (o {{$tableNameSingular}}Slice) UpdateAllG(cols M) error {
return o.UpdateAll(boil.GetDB(), cols) return o.UpdateAll(boil.GetDB(), cols)
} }
// UpdateAllGP updates all rows with the specified column values, and panics on error. // UpdateAllGP updates all rows with the specified column values, and panics on error.
func (o {{$tableNameSingular}}Slice) UpdateAllGP(cols M) { func (o {{$tableNameSingular}}Slice) UpdateAllGP(cols M) {
if err := o.UpdateAll(boil.GetDB(), cols); err != nil { if err := o.UpdateAll(boil.GetDB(), cols); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// UpdateAllP updates all rows with the specified column values, and panics on error. // UpdateAllP updates all rows with the specified column values, and panics on error.
func (o {{$tableNameSingular}}Slice) UpdateAllP(exec boil.Executor, cols M) { func (o {{$tableNameSingular}}Slice) UpdateAllP(exec boil.Executor, cols M) {
if err := o.UpdateAll(exec, cols); err != nil { if err := o.UpdateAll(exec, cols); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// UpdateAll updates all rows with the specified column values, using an executor. // UpdateAll updates all rows with the specified column values, using an executor.
func (o {{$tableNameSingular}}Slice) UpdateAll(exec boil.Executor, cols M) error { func (o {{$tableNameSingular}}Slice) UpdateAll(exec boil.Executor, cols M) error {
ln := int64(len(o)) ln := int64(len(o))
if ln == 0 { if ln == 0 {
return nil return nil
} }
if len(cols) == 0 { if len(cols) == 0 {
return errors.New("{{.PkgName}}: update all requires at least one column argument") return errors.New("{{.PkgName}}: update all requires at least one column argument")
} }
colNames := make([]string, len(cols)) colNames := make([]string, len(cols))
args := make([]interface{}, len(cols)) args := make([]interface{}, len(cols))
i := 0 i := 0
for name, value := range cols { for name, value := range cols {
colNames[i] = name colNames[i] = name
args[i] = value args[i] = value
i++ i++
} }
// Append all of the primary key values for each column // Append all of the primary key values for each column
args = append(args, o.inPrimaryKeyArgs()...) args = append(args, o.inPrimaryKeyArgs()...)
sql := fmt.Sprintf( sql := fmt.Sprintf(
"UPDATE {{$schemaTable}} SET %s WHERE ({{.LQ}}{{.Table.PKey.Columns | join (printf "%s,%s" .LQ .RQ)}}{{.RQ}}) IN (%s)", "UPDATE {{$schemaTable}} SET %s WHERE ({{.LQ}}{{.Table.PKey.Columns | join (printf "%s,%s" .LQ .RQ)}}{{.RQ}}) IN (%s)",
strmangle.SetParamNames("{{.LQ}}", "{{.RQ}}", {{if .Dialect.IndexPlaceholders}}1{{else}}0{{end}}, colNames), strmangle.SetParamNames("{{.LQ}}", "{{.RQ}}", {{if .Dialect.IndexPlaceholders}}1{{else}}0{{end}}, colNames),
strmangle.Placeholders(dialect.IndexPlaceholders, len(o) * len({{$varNameSingular}}PrimaryKeyColumns), len(colNames)+1, len({{$varNameSingular}}PrimaryKeyColumns)), strmangle.Placeholders(dialect.IndexPlaceholders, len(o) * len({{$varNameSingular}}PrimaryKeyColumns), len(colNames)+1, len({{$varNameSingular}}PrimaryKeyColumns)),
) )
if boil.DebugMode { if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, sql) fmt.Fprintln(boil.DebugWriter, sql)
fmt.Fprintln(boil.DebugWriter, args...) fmt.Fprintln(boil.DebugWriter, args...)
} }
result, err := exec.Exec(sql, args...) result, err := exec.Exec(sql, args...)
if err != nil { if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to update all in {{$varNameSingular}} slice") return errors.Wrap(err, "{{.PkgName}}: unable to update all in {{$varNameSingular}} slice")
} }
if r, err := result.RowsAffected(); err == nil && r != ln { if r, err := result.RowsAffected(); err == nil && r != ln {
return errors.Errorf("failed to update %d rows, only affected %d", ln, r) return errors.Errorf("failed to update %d rows, only affected %d", ln, r)
} }
return nil return nil
} }

View file

@ -1,85 +1,109 @@
{{- $tableNameSingular := .Table.Name | singular | titleCase -}} {{- $tableNameSingular := .Table.Name | singular | titleCase -}}
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
// UpsertG attempts an insert, and does an update or ignore on conflict. // UpsertG attempts an insert, and does an update or ignore on conflict.
func (o *{{$tableNameSingular}}) UpsertG(updateOnConflict bool, conflictColumns []string, updateColumns []string, whitelist ...string) error { func (o *{{$tableNameSingular}}) UpsertG({{if eq .DriverName "postgres"}}updateOnConflict bool, conflictColumns []string, {{end}}updateColumns []string, whitelist ...string) error {
return o.Upsert(boil.GetDB(), updateOnConflict, conflictColumns, updateColumns, whitelist...) return o.Upsert(boil.GetDB(), {{if eq .DriverName "postgres"}}updateOnConflict, conflictColumns, {{end}}updateColumns, whitelist...)
} }
// UpsertGP attempts an insert, and does an update or ignore on conflict. Panics on error. // UpsertGP attempts an insert, and does an update or ignore on conflict. Panics on error.
func (o *{{$tableNameSingular}}) UpsertGP(updateOnConflict bool, conflictColumns []string, updateColumns []string, whitelist ...string) { func (o *{{$tableNameSingular}}) UpsertGP({{if eq .DriverName "postgres"}}updateOnConflict bool, conflictColumns []string, {{end}}updateColumns []string, whitelist ...string) {
if err := o.Upsert(boil.GetDB(), updateOnConflict, conflictColumns, updateColumns, whitelist...); err != nil { if err := o.Upsert(boil.GetDB(), {{if eq .DriverName "postgres"}}updateOnConflict, conflictColumns, {{end}}updateColumns, whitelist...); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// UpsertP attempts an insert using an executor, and does an update or ignore on conflict. // UpsertP attempts an insert using an executor, and does an update or ignore on conflict.
// UpsertP panics on error. // UpsertP panics on error.
func (o *{{$tableNameSingular}}) UpsertP(exec boil.Executor, updateOnConflict bool, conflictColumns []string, updateColumns []string, whitelist ...string) { func (o *{{$tableNameSingular}}) UpsertP(exec boil.Executor, {{if eq .DriverName "postgres"}}updateOnConflict bool, conflictColumns []string, {{end}}updateColumns []string, whitelist ...string) {
if err := o.Upsert(exec, updateOnConflict, conflictColumns, updateColumns, whitelist...); err != nil { if err := o.Upsert(exec, {{if eq .DriverName "postgres"}}updateOnConflict, conflictColumns, {{end}}updateColumns, whitelist...); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// Upsert attempts an insert using an executor, and does an update or ignore on conflict. // Upsert attempts an insert using an executor, and does an update or ignore on conflict.
func (o *{{$tableNameSingular}}) Upsert(exec boil.Executor, updateOnConflict bool, conflictColumns []string, updateColumns []string, whitelist ...string) error { func (o *{{$tableNameSingular}}) Upsert(exec boil.Executor, {{if eq .DriverName "postgres"}}updateOnConflict bool, conflictColumns []string, {{end}}updateColumns []string, whitelist ...string) error {
if o == nil { if o == nil {
return errors.New("{{.PkgName}}: no {{.Table.Name}} provided for upsert") return errors.New("{{.PkgName}}: no {{.Table.Name}} provided for upsert")
} }
{{- template "timestamp_upsert_helper" . }} {{- template "timestamp_upsert_helper" . }}
{{if not .NoHooks -}} {{if not .NoHooks -}}
if err := o.doBeforeUpsertHooks(exec); err != nil { if err := o.doBeforeUpsertHooks(exec); err != nil {
return err return err
} }
{{- end}} {{- end}}
var err error var err error
var ret []string var ret []string
whitelist, ret = strmangle.InsertColumnSet( whitelist, ret = strmangle.InsertColumnSet(
{{$varNameSingular}}Columns, {{$varNameSingular}}Columns,
{{$varNameSingular}}ColumnsWithDefault, {{$varNameSingular}}ColumnsWithDefault,
{{$varNameSingular}}ColumnsWithoutDefault, {{$varNameSingular}}ColumnsWithoutDefault,
boil.NonZeroDefaultSet({{$varNameSingular}}ColumnsWithDefault, o), boil.NonZeroDefaultSet({{$varNameSingular}}ColumnsWithDefault, o),
whitelist, whitelist,
) )
update := strmangle.UpdateColumnSet( update := strmangle.UpdateColumnSet(
{{$varNameSingular}}Columns, {{$varNameSingular}}Columns,
{{$varNameSingular}}PrimaryKeyColumns, {{$varNameSingular}}PrimaryKeyColumns,
updateColumns, updateColumns,
) )
conflict := conflictColumns
if len(conflict) == 0 {
conflict = make([]string, len({{$varNameSingular}}PrimaryKeyColumns))
copy(conflict, {{$varNameSingular}}PrimaryKeyColumns)
}
query := boil.BuildUpsertQuery(dialect, "{{.Table.Name}}", updateOnConflict, ret, update, conflict, whitelist) {{if eq .DriverName "postgres" -}}
conflict := conflictColumns
if len(conflict) == 0 {
conflict = make([]string, len({{$varNameSingular}}PrimaryKeyColumns))
copy(conflict, {{$varNameSingular}}PrimaryKeyColumns)
}
{{- end}}
if boil.DebugMode { {{if eq .DriverName "postgres" -}}
fmt.Fprintln(boil.DebugWriter, query) query := boil.BuildUpsertQueryPostgres(dialect, "{{.Table.Name}}", updateOnConflict, ret, update, conflict, whitelist)
fmt.Fprintln(boil.DebugWriter, boil.GetStructValues(o, whitelist...)) {{- else if eq .DriverName "mysql" -}}
} query := boil.BuildUpsertQueryMySQL(dialect, "{{.Table.Name}}", update, whitelist)
{{- end}}
{{- if .UseLastInsertID}} if boil.DebugMode {
return errors.New("don't know how to do this yet") fmt.Fprintln(boil.DebugWriter, query)
{{- else}} fmt.Fprintln(boil.DebugWriter, boil.GetStructValues(o, whitelist...))
if len(ret) != 0 { }
err = exec.QueryRow(query, boil.GetStructValues(o, whitelist...)...).Scan(boil.GetStructPointers(o, ret...)...)
} else {
_, err = exec.Exec(query, boil.GetStructValues(o, whitelist...)...)
}
{{- end}}
if err != nil { {{- if .UseLastInsertID}}
return errors.Wrap(err, "{{.PkgName}}: unable to upsert for {{.Table.Name}}") res, err := exec.Exec(query, boil.GetStructValues(o, whitelist...)...)
} {{- else}}
if len(ret) != 0 {
err = exec.QueryRow(query, boil.GetStructValues(o, whitelist...)...).Scan(boil.GetStructPointers(o, ret...)...)
} else {
_, err = exec.Exec(query, boil.GetStructValues(o, whitelist...)...)
}
{{- end}}
{{if not .NoHooks -}} if err != nil {
if err := o.doAfterUpsertHooks(exec); err != nil { return errors.Wrap(err, "{{.PkgName}}: unable to upsert for {{.Table.Name}}")
return err }
}
{{- end}}
return nil {{if .UseLastInsertID -}}
if len(ret) != 0 {
lid, err := res.LastInsertId()
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to get last insert id for {{.Table.Name}}")
}
{{$aipk := autoIncPrimaryKey .Table.Columns .Table.PKey}}
aipk := "{{$aipk.Name}}"
// if the update did not change anything, lid will be 0
if lid == 0 && aipk == "" {
// do a select using all pkeys
} else if lid != 0 {
// do a select using all pkeys + lid
}
}
{{- end}}
{{if not .NoHooks -}}
if err := o.doAfterUpsertHooks(exec); err != nil {
return err
}
{{- end}}
return nil
} }

View file

@ -5,158 +5,158 @@
// DeleteP will match against the primary key column to find the record to delete. // DeleteP will match against the primary key column to find the record to delete.
// Panics on error. // Panics on error.
func (o *{{$tableNameSingular}}) DeleteP(exec boil.Executor) { func (o *{{$tableNameSingular}}) DeleteP(exec boil.Executor) {
if err := o.Delete(exec); err != nil { if err := o.Delete(exec); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// DeleteG deletes a single {{$tableNameSingular}} record. // DeleteG deletes a single {{$tableNameSingular}} record.
// DeleteG will match against the primary key column to find the record to delete. // DeleteG will match against the primary key column to find the record to delete.
func (o *{{$tableNameSingular}}) DeleteG() error { func (o *{{$tableNameSingular}}) DeleteG() error {
if o == nil { if o == nil {
return errors.New("{{.PkgName}}: no {{$tableNameSingular}} provided for deletion") return errors.New("{{.PkgName}}: no {{$tableNameSingular}} provided for deletion")
} }
return o.Delete(boil.GetDB()) return o.Delete(boil.GetDB())
} }
// DeleteGP deletes a single {{$tableNameSingular}} record. // DeleteGP deletes a single {{$tableNameSingular}} record.
// DeleteGP will match against the primary key column to find the record to delete. // DeleteGP will match against the primary key column to find the record to delete.
// Panics on error. // Panics on error.
func (o *{{$tableNameSingular}}) DeleteGP() { func (o *{{$tableNameSingular}}) DeleteGP() {
if err := o.DeleteG(); err != nil { if err := o.DeleteG(); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// Delete deletes a single {{$tableNameSingular}} record with an executor. // Delete deletes a single {{$tableNameSingular}} record with an executor.
// Delete will match against the primary key column to find the record to delete. // Delete will match against the primary key column to find the record to delete.
func (o *{{$tableNameSingular}}) Delete(exec boil.Executor) error { func (o *{{$tableNameSingular}}) Delete(exec boil.Executor) error {
if o == nil { if o == nil {
return errors.New("{{.PkgName}}: no {{$tableNameSingular}} provided for delete") return errors.New("{{.PkgName}}: no {{$tableNameSingular}} provided for delete")
} }
{{if not .NoHooks -}} {{if not .NoHooks -}}
if err := o.doBeforeDeleteHooks(exec); err != nil { if err := o.doBeforeDeleteHooks(exec); err != nil {
return err return err
} }
{{- end}} {{- end}}
args := o.inPrimaryKeyArgs() args := o.inPrimaryKeyArgs()
sql := "DELETE FROM {{$schemaTable}} WHERE {{if .Dialect.IndexPlaceholders}}{{whereClause .LQ .RQ 1 .Table.PKey.Columns}}{{else}}{{whereClause .LQ .RQ 0 .Table.PKey.Columns}}{{end}}" sql := "DELETE FROM {{$schemaTable}} WHERE {{if .Dialect.IndexPlaceholders}}{{whereClause .LQ .RQ 1 .Table.PKey.Columns}}{{else}}{{whereClause .LQ .RQ 0 .Table.PKey.Columns}}{{end}}"
if boil.DebugMode { if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, sql) fmt.Fprintln(boil.DebugWriter, sql)
fmt.Fprintln(boil.DebugWriter, args...) fmt.Fprintln(boil.DebugWriter, args...)
} }
_, err := exec.Exec(sql, args...) _, err := exec.Exec(sql, args...)
if err != nil { if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to delete from {{.Table.Name}}") return errors.Wrap(err, "{{.PkgName}}: unable to delete from {{.Table.Name}}")
} }
{{if not .NoHooks -}} {{if not .NoHooks -}}
if err := o.doAfterDeleteHooks(exec); err != nil { if err := o.doAfterDeleteHooks(exec); err != nil {
return err return err
} }
{{- end}} {{- end}}
return nil return nil
} }
// DeleteAllP deletes all rows, and panics on error. // DeleteAllP deletes all rows, and panics on error.
func (q {{$varNameSingular}}Query) DeleteAllP() { func (q {{$varNameSingular}}Query) DeleteAllP() {
if err := q.DeleteAll(); err != nil { if err := q.DeleteAll(); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// DeleteAll deletes all matching rows. // DeleteAll deletes all matching rows.
func (q {{$varNameSingular}}Query) DeleteAll() error { func (q {{$varNameSingular}}Query) DeleteAll() error {
if q.Query == nil { if q.Query == nil {
return errors.New("{{.PkgName}}: no {{$varNameSingular}}Query provided for delete all") return errors.New("{{.PkgName}}: no {{$varNameSingular}}Query provided for delete all")
} }
boil.SetDelete(q.Query) boil.SetDelete(q.Query)
_, err := q.Query.ExecQuery() _, err := q.Query.ExecQuery()
if err != nil { if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to delete all from {{.Table.Name}}") return errors.Wrap(err, "{{.PkgName}}: unable to delete all from {{.Table.Name}}")
} }
return nil return nil
} }
// DeleteAll deletes all rows in the slice, and panics on error. // DeleteAll deletes all rows in the slice, and panics on error.
func (o {{$tableNameSingular}}Slice) DeleteAllGP() { func (o {{$tableNameSingular}}Slice) DeleteAllGP() {
if err := o.DeleteAllG(); err != nil { if err := o.DeleteAllG(); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// DeleteAllG deletes all rows in the slice. // DeleteAllG deletes all rows in the slice.
func (o {{$tableNameSingular}}Slice) DeleteAllG() error { func (o {{$tableNameSingular}}Slice) DeleteAllG() error {
if o == nil { if o == nil {
return errors.New("{{.PkgName}}: no {{$tableNameSingular}} slice provided for delete all") return errors.New("{{.PkgName}}: no {{$tableNameSingular}} slice provided for delete all")
} }
return o.DeleteAll(boil.GetDB()) return o.DeleteAll(boil.GetDB())
} }
// DeleteAllP deletes all rows in the slice, using an executor, and panics on error. // DeleteAllP deletes all rows in the slice, using an executor, and panics on error.
func (o {{$tableNameSingular}}Slice) DeleteAllP(exec boil.Executor) { func (o {{$tableNameSingular}}Slice) DeleteAllP(exec boil.Executor) {
if err := o.DeleteAll(exec); err != nil { if err := o.DeleteAll(exec); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// DeleteAll deletes all rows in the slice, using an executor. // DeleteAll deletes all rows in the slice, using an executor.
func (o {{$tableNameSingular}}Slice) DeleteAll(exec boil.Executor) error { func (o {{$tableNameSingular}}Slice) DeleteAll(exec boil.Executor) error {
if o == nil { if o == nil {
return errors.New("{{.PkgName}}: no {{$tableNameSingular}} slice provided for delete all") return errors.New("{{.PkgName}}: no {{$tableNameSingular}} slice provided for delete all")
} }
if len(o) == 0 { if len(o) == 0 {
return nil return nil
} }
{{if not .NoHooks -}} {{if not .NoHooks -}}
if len({{$varNameSingular}}BeforeDeleteHooks) != 0 { if len({{$varNameSingular}}BeforeDeleteHooks) != 0 {
for _, obj := range o { for _, obj := range o {
if err := obj.doBeforeDeleteHooks(exec); err != nil { if err := obj.doBeforeDeleteHooks(exec); err != nil {
return err return err
} }
} }
} }
{{- end}} {{- end}}
args := o.inPrimaryKeyArgs() args := o.inPrimaryKeyArgs()
sql := fmt.Sprintf( sql := fmt.Sprintf(
"DELETE FROM {{$schemaTable}} WHERE (%s) IN (%s)", "DELETE FROM {{$schemaTable}} WHERE (%s) IN (%s)",
strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, {{$varNameSingular}}PrimaryKeyColumns), ","), strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, {{$varNameSingular}}PrimaryKeyColumns), ","),
strmangle.Placeholders(dialect.IndexPlaceholders, len(o) * len({{$varNameSingular}}PrimaryKeyColumns), 1, len({{$varNameSingular}}PrimaryKeyColumns)), strmangle.Placeholders(dialect.IndexPlaceholders, len(o) * len({{$varNameSingular}}PrimaryKeyColumns), 1, len({{$varNameSingular}}PrimaryKeyColumns)),
) )
if boil.DebugMode { if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, sql) fmt.Fprintln(boil.DebugWriter, sql)
fmt.Fprintln(boil.DebugWriter, args) fmt.Fprintln(boil.DebugWriter, args)
} }
_, err := exec.Exec(sql, args...) _, err := exec.Exec(sql, args...)
if err != nil { if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to delete all from {{$varNameSingular}} slice") return errors.Wrap(err, "{{.PkgName}}: unable to delete all from {{$varNameSingular}} slice")
} }
{{if not .NoHooks -}} {{if not .NoHooks -}}
if len({{$varNameSingular}}AfterDeleteHooks) != 0 { if len({{$varNameSingular}}AfterDeleteHooks) != 0 {
for _, obj := range o { for _, obj := range o {
if err := obj.doAfterDeleteHooks(exec); err != nil { if err := obj.doAfterDeleteHooks(exec); err != nil {
return err return err
} }
} }
} }
{{- end}} {{- end}}
return nil return nil
} }

View file

@ -4,83 +4,83 @@
{{- $schemaTable := .Table.Name | .SchemaTable -}} {{- $schemaTable := .Table.Name | .SchemaTable -}}
// ReloadGP refetches the object from the database and panics on error. // ReloadGP refetches the object from the database and panics on error.
func (o *{{$tableNameSingular}}) ReloadGP() { func (o *{{$tableNameSingular}}) ReloadGP() {
if err := o.ReloadG(); err != nil { if err := o.ReloadG(); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// ReloadP refetches the object from the database with an executor. Panics on error. // ReloadP refetches the object from the database with an executor. Panics on error.
func (o *{{$tableNameSingular}}) ReloadP(exec boil.Executor) { func (o *{{$tableNameSingular}}) ReloadP(exec boil.Executor) {
if err := o.Reload(exec); err != nil { if err := o.Reload(exec); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
// ReloadG refetches the object from the database using the primary keys. // ReloadG refetches the object from the database using the primary keys.
func (o *{{$tableNameSingular}}) ReloadG() error { func (o *{{$tableNameSingular}}) ReloadG() error {
if o == nil { if o == nil {
return errors.New("{{.PkgName}}: no {{$tableNameSingular}} provided for reload") return errors.New("{{.PkgName}}: no {{$tableNameSingular}} provided for reload")
} }
return o.Reload(boil.GetDB()) return o.Reload(boil.GetDB())
} }
// Reload refetches the object from the database // Reload refetches the object from the database
// using the primary keys with an executor. // using the primary keys with an executor.
func (o *{{$tableNameSingular}}) Reload(exec boil.Executor) error { func (o *{{$tableNameSingular}}) Reload(exec boil.Executor) error {
ret, err := Find{{$tableNameSingular}}(exec, {{.Table.PKey.Columns | stringMap .StringFuncs.titleCase | prefixStringSlice "o." | join ", "}}) ret, err := Find{{$tableNameSingular}}(exec, {{.Table.PKey.Columns | stringMap .StringFuncs.titleCase | prefixStringSlice "o." | join ", "}})
if err != nil { if err != nil {
return err return err
} }
*o = *ret *o = *ret
return nil return nil
} }
func (o *{{$tableNameSingular}}Slice) ReloadAllGP() { func (o *{{$tableNameSingular}}Slice) ReloadAllGP() {
if err := o.ReloadAllG(); err != nil { if err := o.ReloadAllG(); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
func (o *{{$tableNameSingular}}Slice) ReloadAllP(exec boil.Executor) { func (o *{{$tableNameSingular}}Slice) ReloadAllP(exec boil.Executor) {
if err := o.ReloadAll(exec); err != nil { if err := o.ReloadAll(exec); err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
} }
func (o *{{$tableNameSingular}}Slice) ReloadAllG() error { func (o *{{$tableNameSingular}}Slice) ReloadAllG() error {
if o == nil { if o == nil {
return errors.New("{{.PkgName}}: empty {{$tableNameSingular}}Slice provided for reload all") return errors.New("{{.PkgName}}: empty {{$tableNameSingular}}Slice provided for reload all")
} }
return o.ReloadAll(boil.GetDB()) return o.ReloadAll(boil.GetDB())
} }
// ReloadAll refetches every row with matching primary key column values // ReloadAll refetches every row with matching primary key column values
// and overwrites the original object slice with the newly updated slice. // and overwrites the original object slice with the newly updated slice.
func (o *{{$tableNameSingular}}Slice) ReloadAll(exec boil.Executor) error { func (o *{{$tableNameSingular}}Slice) ReloadAll(exec boil.Executor) error {
if o == nil || len(*o) == 0 { if o == nil || len(*o) == 0 {
return nil return nil
} }
{{$varNamePlural}} := {{$tableNameSingular}}Slice{} {{$varNamePlural}} := {{$tableNameSingular}}Slice{}
args := o.inPrimaryKeyArgs() args := o.inPrimaryKeyArgs()
sql := fmt.Sprintf( sql := fmt.Sprintf(
"SELECT {{$schemaTable}}.* FROM {{$schemaTable}} WHERE (%s) IN (%s)", "SELECT {{$schemaTable}}.* FROM {{$schemaTable}} WHERE (%s) IN (%s)",
strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, {{$varNameSingular}}PrimaryKeyColumns), ","), strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, {{$varNameSingular}}PrimaryKeyColumns), ","),
strmangle.Placeholders(dialect.IndexPlaceholders, len(*o) * len({{$varNameSingular}}PrimaryKeyColumns), 1, len({{$varNameSingular}}PrimaryKeyColumns)), strmangle.Placeholders(dialect.IndexPlaceholders, len(*o) * len({{$varNameSingular}}PrimaryKeyColumns), 1, len({{$varNameSingular}}PrimaryKeyColumns)),
) )
q := boil.SQL(exec, sql, args...) q := boil.SQL(exec, sql, args...)
err := q.Bind(&{{$varNamePlural}}) err := q.Bind(&{{$varNamePlural}})
if err != nil { if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to reload all in {{$tableNameSingular}}Slice") return errors.Wrap(err, "{{.PkgName}}: unable to reload all in {{$tableNameSingular}}Slice")
} }
*o = {{$varNamePlural}} *o = {{$varNamePlural}}
return nil return nil
} }

View file

@ -5,46 +5,46 @@
{{- $schemaTable := .Table.Name | .SchemaTable -}} {{- $schemaTable := .Table.Name | .SchemaTable -}}
// {{$tableNameSingular}}Exists checks if the {{$tableNameSingular}} row exists. // {{$tableNameSingular}}Exists checks if the {{$tableNameSingular}} row exists.
func {{$tableNameSingular}}Exists(exec boil.Executor, {{$pkArgs}}) (bool, error) { func {{$tableNameSingular}}Exists(exec boil.Executor, {{$pkArgs}}) (bool, error) {
var exists bool var exists bool
sql := "select exists(select 1 from {{$schemaTable}} where {{if .Dialect.IndexPlaceholders}}{{whereClause .LQ .RQ 1 .Table.PKey.Columns}}{{else}}{{whereClause .LQ .RQ 0 .Table.PKey.Columns}}{{end}} limit 1)" sql := "select exists(select 1 from {{$schemaTable}} where {{if .Dialect.IndexPlaceholders}}{{whereClause .LQ .RQ 1 .Table.PKey.Columns}}{{else}}{{whereClause .LQ .RQ 0 .Table.PKey.Columns}}{{end}} limit 1)"
if boil.DebugMode { if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, sql) fmt.Fprintln(boil.DebugWriter, sql)
fmt.Fprintln(boil.DebugWriter, {{$pkNames | join ", "}}) fmt.Fprintln(boil.DebugWriter, {{$pkNames | join ", "}})
} }
row := exec.QueryRow(sql, {{$pkNames | join ", "}}) row := exec.QueryRow(sql, {{$pkNames | join ", "}})
err := row.Scan(&exists) err := row.Scan(&exists)
if err != nil { if err != nil {
return false, errors.Wrap(err, "{{.PkgName}}: unable to check if {{.Table.Name}} exists") return false, errors.Wrap(err, "{{.PkgName}}: unable to check if {{.Table.Name}} exists")
} }
return exists, nil return exists, nil
} }
// {{$tableNameSingular}}ExistsG checks if the {{$tableNameSingular}} row exists. // {{$tableNameSingular}}ExistsG checks if the {{$tableNameSingular}} row exists.
func {{$tableNameSingular}}ExistsG({{$pkArgs}}) (bool, error) { func {{$tableNameSingular}}ExistsG({{$pkArgs}}) (bool, error) {
return {{$tableNameSingular}}Exists(boil.GetDB(), {{$pkNames | join ", "}}) return {{$tableNameSingular}}Exists(boil.GetDB(), {{$pkNames | join ", "}})
} }
// {{$tableNameSingular}}ExistsGP checks if the {{$tableNameSingular}} row exists. Panics on error. // {{$tableNameSingular}}ExistsGP checks if the {{$tableNameSingular}} row exists. Panics on error.
func {{$tableNameSingular}}ExistsGP({{$pkArgs}}) bool { func {{$tableNameSingular}}ExistsGP({{$pkArgs}}) bool {
e, err := {{$tableNameSingular}}Exists(boil.GetDB(), {{$pkNames | join ", "}}) e, err := {{$tableNameSingular}}Exists(boil.GetDB(), {{$pkNames | join ", "}})
if err != nil { if err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
return e return e
} }
// {{$tableNameSingular}}ExistsP checks if the {{$tableNameSingular}} row exists. Panics on error. // {{$tableNameSingular}}ExistsP checks if the {{$tableNameSingular}} row exists. Panics on error.
func {{$tableNameSingular}}ExistsP(exec boil.Executor, {{$pkArgs}}) bool { func {{$tableNameSingular}}ExistsP(exec boil.Executor, {{$pkArgs}}) bool {
e, err := {{$tableNameSingular}}Exists(exec, {{$pkNames | join ", "}}) e, err := {{$tableNameSingular}}Exists(exec, {{$pkNames | join ", "}})
if err != nil { if err != nil {
panic(boil.WrapErr(err)) panic(boil.WrapErr(err))
} }
return e return e
} }

View file

@ -1,23 +1,23 @@
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
{{- $tableNameSingular := .Table.Name | singular | titleCase -}} {{- $tableNameSingular := .Table.Name | singular | titleCase -}}
func (o {{$tableNameSingular}}) inPrimaryKeyArgs() []interface{} { func (o {{$tableNameSingular}}) inPrimaryKeyArgs() []interface{} {
var args []interface{} var args []interface{}
{{- range $key, $value := .Table.PKey.Columns }} {{- range $key, $value := .Table.PKey.Columns }}
args = append(args, o.{{titleCase $value}}) args = append(args, o.{{titleCase $value}})
{{ end -}} {{ end -}}
return args return args
} }
func (o {{$tableNameSingular}}Slice) inPrimaryKeyArgs() []interface{} { func (o {{$tableNameSingular}}Slice) inPrimaryKeyArgs() []interface{} {
var args []interface{} var args []interface{}
for i := 0; i < len(o); i++ { for i := 0; i < len(o); i++ {
{{- range $key, $value := .Table.PKey.Columns }} {{- range $key, $value := .Table.PKey.Columns }}
args = append(args, o[i].{{titleCase $value}}) args = append(args, o[i].{{titleCase $value}})
{{ end -}} {{ end -}}
} }
return args return args
} }

View file

@ -1,82 +1,82 @@
{{- define "timestamp_insert_helper" -}} {{- define "timestamp_insert_helper" -}}
{{- if not .NoAutoTimestamps -}} {{- if not .NoAutoTimestamps -}}
{{- $colNames := .Table.Columns | columnNames -}} {{- $colNames := .Table.Columns | columnNames -}}
{{if containsAny $colNames "created_at" "updated_at"}} {{if containsAny $colNames "created_at" "updated_at"}}
currTime := time.Now().In(boil.GetLocation()) currTime := time.Now().In(boil.GetLocation())
{{range $ind, $col := .Table.Columns}} {{range $ind, $col := .Table.Columns}}
{{- if eq $col.Name "created_at" -}} {{- if eq $col.Name "created_at" -}}
{{- if $col.Nullable}} {{- if $col.Nullable}}
if o.CreatedAt.Time.IsZero() { if o.CreatedAt.Time.IsZero() {
o.CreatedAt.Time = currTime o.CreatedAt.Time = currTime
o.CreatedAt.Valid = true o.CreatedAt.Valid = true
} }
{{- else}} {{- else}}
if o.CreatedAt.IsZero() { if o.CreatedAt.IsZero() {
o.CreatedAt = currTime o.CreatedAt = currTime
} }
{{- end -}} {{- end -}}
{{- end -}} {{- end -}}
{{- if eq $col.Name "updated_at" -}} {{- if eq $col.Name "updated_at" -}}
{{- if $col.Nullable}} {{- if $col.Nullable}}
if o.UpdatedAt.Time.IsZero() { if o.UpdatedAt.Time.IsZero() {
o.UpdatedAt.Time = currTime o.UpdatedAt.Time = currTime
o.UpdatedAt.Valid = true o.UpdatedAt.Valid = true
} }
{{- else}} {{- else}}
if o.UpdatedAt.IsZero() { if o.UpdatedAt.IsZero() {
o.UpdatedAt = currTime o.UpdatedAt = currTime
} }
{{- end -}} {{- end -}}
{{- end -}} {{- end -}}
{{end}} {{end}}
{{end}} {{end}}
{{- end}} {{- end}}
{{- end -}} {{- end -}}
{{- define "timestamp_update_helper" -}} {{- define "timestamp_update_helper" -}}
{{- if not .NoAutoTimestamps -}} {{- if not .NoAutoTimestamps -}}
{{- $colNames := .Table.Columns | columnNames -}} {{- $colNames := .Table.Columns | columnNames -}}
{{if containsAny $colNames "updated_at"}} {{if containsAny $colNames "updated_at"}}
currTime := time.Now().In(boil.GetLocation()) currTime := time.Now().In(boil.GetLocation())
{{range $ind, $col := .Table.Columns}} {{range $ind, $col := .Table.Columns}}
{{- if eq $col.Name "updated_at" -}} {{- if eq $col.Name "updated_at" -}}
{{- if $col.Nullable}} {{- if $col.Nullable}}
o.UpdatedAt.Time = currTime o.UpdatedAt.Time = currTime
o.UpdatedAt.Valid = true o.UpdatedAt.Valid = true
{{- else}} {{- else}}
o.UpdatedAt = currTime o.UpdatedAt = currTime
{{- end -}} {{- end -}}
{{- end -}} {{- end -}}
{{end}} {{end}}
{{end}} {{end}}
{{- end}} {{- end}}
{{end -}} {{end -}}
{{- define "timestamp_upsert_helper" -}} {{- define "timestamp_upsert_helper" -}}
{{- if not .NoAutoTimestamps -}} {{- if not .NoAutoTimestamps -}}
{{- $colNames := .Table.Columns | columnNames -}} {{- $colNames := .Table.Columns | columnNames -}}
{{if containsAny $colNames "created_at" "updated_at"}} {{if containsAny $colNames "created_at" "updated_at"}}
currTime := time.Now().In(boil.GetLocation()) currTime := time.Now().In(boil.GetLocation())
{{range $ind, $col := .Table.Columns}} {{range $ind, $col := .Table.Columns}}
{{- if eq $col.Name "created_at" -}} {{- if eq $col.Name "created_at" -}}
{{- if $col.Nullable}} {{- if $col.Nullable}}
if o.CreatedAt.Time.IsZero() { if o.CreatedAt.Time.IsZero() {
o.CreatedAt.Time = currTime o.CreatedAt.Time = currTime
o.CreatedAt.Valid = true o.CreatedAt.Valid = true
} }
{{- else}} {{- else}}
if o.CreatedAt.IsZero() { if o.CreatedAt.IsZero() {
o.CreatedAt = currTime o.CreatedAt = currTime
} }
{{- end -}} {{- end -}}
{{- end -}} {{- end -}}
{{- if eq $col.Name "updated_at" -}} {{- if eq $col.Name "updated_at" -}}
{{- if $col.Nullable}} {{- if $col.Nullable}}
o.UpdatedAt.Time = currTime o.UpdatedAt.Time = currTime
o.UpdatedAt.Valid = true o.UpdatedAt.Valid = true
{{- else}} {{- else}}
o.UpdatedAt = currTime o.UpdatedAt = currTime
{{- end -}} {{- end -}}
{{- end -}} {{- end -}}
{{end}} {{end}}
{{end}} {{end}}
{{- end}} {{- end}}
{{end -}} {{end -}}

View file

@ -1,20 +1,20 @@
var dialect = boil.Dialect{ var dialect = boil.Dialect{
LQ: 0x{{printf "%x" .Dialect.LQ}}, LQ: 0x{{printf "%x" .Dialect.LQ}},
RQ: 0x{{printf "%x" .Dialect.RQ}}, RQ: 0x{{printf "%x" .Dialect.RQ}},
IndexPlaceholders: {{.Dialect.IndexPlaceholders}}, IndexPlaceholders: {{.Dialect.IndexPlaceholders}},
} }
// NewQueryG initializes a new Query using the passed in QueryMods // NewQueryG initializes a new Query using the passed in QueryMods
func NewQueryG(mods ...qm.QueryMod) *boil.Query { func NewQueryG(mods ...qm.QueryMod) *boil.Query {
return NewQuery(boil.GetDB(), mods...) return NewQuery(boil.GetDB(), mods...)
} }
// NewQuery initializes a new Query using the passed in QueryMods // NewQuery initializes a new Query using the passed in QueryMods
func NewQuery(exec boil.Executor, mods ...qm.QueryMod) *boil.Query { func NewQuery(exec boil.Executor, mods ...qm.QueryMod) *boil.Query {
q := &boil.Query{} q := &boil.Query{}
boil.SetExecutor(q, exec) boil.SetExecutor(q, exec)
boil.SetDialect(q, &dialect) boil.SetDialect(q, &dialect)
qm.Apply(q, mods...) qm.Apply(q, mods...)
return q return q
} }

View file

@ -7,32 +7,32 @@ type M map[string]interface{}
var ErrSyncFail = errors.New("{{.PkgName}}: failed to synchronize data after insert") var ErrSyncFail = errors.New("{{.PkgName}}: failed to synchronize data after insert")
type insertCache struct{ type insertCache struct{
query string query string
retQuery string retQuery string
valueMapping []uint64 valueMapping []uint64
retMapping []uint64 retMapping []uint64
} }
type updateCache struct{ type updateCache struct{
query string query string
valueMapping []uint64 valueMapping []uint64
} }
func makeCacheKey(wl, nzDefaults []string) string { func makeCacheKey(wl, nzDefaults []string) string {
buf := strmangle.GetBuffer() buf := strmangle.GetBuffer()
for _, w := range wl { for _, w := range wl {
buf.WriteString(w) buf.WriteString(w)
} }
if len(nzDefaults) != 0 { if len(nzDefaults) != 0 {
buf.WriteByte('.') buf.WriteByte('.')
} }
for _, nz := range nzDefaults { for _, nz := range nzDefaults {
buf.WriteString(nz) buf.WriteString(nz)
} }
str := buf.String() str := buf.String()
strmangle.PutBuffer(buf) strmangle.PutBuffer(buf)
return str return str
} }

View file

@ -3,11 +3,11 @@
{{- $varNamePlural := .Table.Name | plural | camelCase -}} {{- $varNamePlural := .Table.Name | plural | camelCase -}}
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
func test{{$tableNamePlural}}(t *testing.T) { func test{{$tableNamePlural}}(t *testing.T) {
t.Parallel() t.Parallel()
query := {{$tableNamePlural}}(nil) query := {{$tableNamePlural}}(nil)
if query.Query == nil { if query.Query == nil {
t.Error("expected a query, got nothing") t.Error("expected a query, got nothing")
} }
} }

View file

@ -3,93 +3,93 @@
{{- $varNamePlural := .Table.Name | plural | camelCase -}} {{- $varNamePlural := .Table.Name | plural | camelCase -}}
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
func test{{$tableNamePlural}}Delete(t *testing.T) { func test{{$tableNamePlural}}Delete(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}} := &{{$tableNameSingular}}{} {{$varNameSingular}} := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Insert(tx); err != nil { if err = {{$varNameSingular}}.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
if err = {{$varNameSingular}}.Delete(tx); err != nil { if err = {{$varNameSingular}}.Delete(tx); err != nil {
t.Error(err) t.Error(err)
} }
count, err := {{$tableNamePlural}}(tx).Count() count, err := {{$tableNamePlural}}(tx).Count()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if count != 0 { if count != 0 {
t.Error("want zero records, got:", count) t.Error("want zero records, got:", count)
} }
} }
func test{{$tableNamePlural}}QueryDeleteAll(t *testing.T) { func test{{$tableNamePlural}}QueryDeleteAll(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}} := &{{$tableNameSingular}}{} {{$varNameSingular}} := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Insert(tx); err != nil { if err = {{$varNameSingular}}.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
if err = {{$tableNamePlural}}(tx).DeleteAll(); err != nil { if err = {{$tableNamePlural}}(tx).DeleteAll(); err != nil {
t.Error(err) t.Error(err)
} }
count, err := {{$tableNamePlural}}(tx).Count() count, err := {{$tableNamePlural}}(tx).Count()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if count != 0 { if count != 0 {
t.Error("want zero records, got:", count) t.Error("want zero records, got:", count)
} }
} }
func test{{$tableNamePlural}}SliceDeleteAll(t *testing.T) { func test{{$tableNamePlural}}SliceDeleteAll(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}} := &{{$tableNameSingular}}{} {{$varNameSingular}} := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Insert(tx); err != nil { if err = {{$varNameSingular}}.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
slice := {{$tableNameSingular}}Slice{{"{"}}{{$varNameSingular}}{{"}"}} slice := {{$tableNameSingular}}Slice{{"{"}}{{$varNameSingular}}{{"}"}}
if err = slice.DeleteAll(tx); err != nil { if err = slice.DeleteAll(tx); err != nil {
t.Error(err) t.Error(err)
} }
count, err := {{$tableNamePlural}}(tx).Count() count, err := {{$tableNamePlural}}(tx).Count()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if count != 0 { if count != 0 {
t.Error("want zero records, got:", count) t.Error("want zero records, got:", count)
} }
} }

View file

@ -3,27 +3,27 @@
{{- $varNamePlural := .Table.Name | plural | camelCase -}} {{- $varNamePlural := .Table.Name | plural | camelCase -}}
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
func test{{$tableNamePlural}}Exists(t *testing.T) { func test{{$tableNamePlural}}Exists(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}} := &{{$tableNameSingular}}{} {{$varNameSingular}} := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Insert(tx); err != nil { if err = {{$varNameSingular}}.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
{{$pkeyArgs := .Table.PKey.Columns | stringMap .StringFuncs.titleCase | prefixStringSlice (printf "%s." $varNameSingular) | join ", " -}} {{$pkeyArgs := .Table.PKey.Columns | stringMap .StringFuncs.titleCase | prefixStringSlice (printf "%s." $varNameSingular) | join ", " -}}
e, err := {{$tableNameSingular}}Exists(tx, {{$pkeyArgs}}) e, err := {{$tableNameSingular}}Exists(tx, {{$pkeyArgs}})
if err != nil { if err != nil {
t.Errorf("Unable to check if {{$tableNameSingular}} exists: %s", err) t.Errorf("Unable to check if {{$tableNameSingular}} exists: %s", err)
} }
if e != true { if e != true {
t.Errorf("Expected {{$tableNameSingular}}ExistsG to return true, but got false.") t.Errorf("Expected {{$tableNameSingular}}ExistsG to return true, but got false.")
} }
} }

View file

@ -3,27 +3,27 @@
{{- $varNamePlural := .Table.Name | plural | camelCase -}} {{- $varNamePlural := .Table.Name | plural | camelCase -}}
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
func test{{$tableNamePlural}}Find(t *testing.T) { func test{{$tableNamePlural}}Find(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}} := &{{$tableNameSingular}}{} {{$varNameSingular}} := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Insert(tx); err != nil { if err = {{$varNameSingular}}.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
{{$varNameSingular}}Found, err := Find{{$tableNameSingular}}(tx, {{.Table.PKey.Columns | stringMap .StringFuncs.titleCase | prefixStringSlice (printf "%s." $varNameSingular) | join ", "}}) {{$varNameSingular}}Found, err := Find{{$tableNameSingular}}(tx, {{.Table.PKey.Columns | stringMap .StringFuncs.titleCase | prefixStringSlice (printf "%s." $varNameSingular) | join ", "}})
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if {{$varNameSingular}}Found == nil { if {{$varNameSingular}}Found == nil {
t.Error("want a record, got nil") t.Error("want a record, got nil")
} }
} }

View file

@ -3,111 +3,111 @@
{{- $varNamePlural := .Table.Name | plural | camelCase -}} {{- $varNamePlural := .Table.Name | plural | camelCase -}}
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
func test{{$tableNamePlural}}Bind(t *testing.T) { func test{{$tableNamePlural}}Bind(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}} := &{{$tableNameSingular}}{} {{$varNameSingular}} := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Insert(tx); err != nil { if err = {{$varNameSingular}}.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
if err = {{$tableNamePlural}}(tx).Bind({{$varNameSingular}}); err != nil { if err = {{$tableNamePlural}}(tx).Bind({{$varNameSingular}}); err != nil {
t.Error(err) t.Error(err)
} }
} }
func test{{$tableNamePlural}}One(t *testing.T) { func test{{$tableNamePlural}}One(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}} := &{{$tableNameSingular}}{} {{$varNameSingular}} := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Insert(tx); err != nil { if err = {{$varNameSingular}}.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
if x, err := {{$tableNamePlural}}(tx).One(); err != nil { if x, err := {{$tableNamePlural}}(tx).One(); err != nil {
t.Error(err) t.Error(err)
} else if x == nil { } else if x == nil {
t.Error("expected to get a non nil record") t.Error("expected to get a non nil record")
} }
} }
func test{{$tableNamePlural}}All(t *testing.T) { func test{{$tableNamePlural}}All(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}}One := &{{$tableNameSingular}}{} {{$varNameSingular}}One := &{{$tableNameSingular}}{}
{{$varNameSingular}}Two := &{{$tableNameSingular}}{} {{$varNameSingular}}Two := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}One, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}ColumnsWithDefault...); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}One, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}ColumnsWithDefault...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
if err = randomize.Struct(seed, {{$varNameSingular}}Two, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}ColumnsWithDefault...); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}Two, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}ColumnsWithDefault...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}One.Insert(tx); err != nil { if err = {{$varNameSingular}}One.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
if err = {{$varNameSingular}}Two.Insert(tx); err != nil { if err = {{$varNameSingular}}Two.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
slice, err := {{$tableNamePlural}}(tx).All() slice, err := {{$tableNamePlural}}(tx).All()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if len(slice) != 2 { if len(slice) != 2 {
t.Error("want 2 records, got:", len(slice)) t.Error("want 2 records, got:", len(slice))
} }
} }
func test{{$tableNamePlural}}Count(t *testing.T) { func test{{$tableNamePlural}}Count(t *testing.T) {
t.Parallel() t.Parallel()
var err error var err error
seed := randomize.NewSeed() seed := randomize.NewSeed()
{{$varNameSingular}}One := &{{$tableNameSingular}}{} {{$varNameSingular}}One := &{{$tableNameSingular}}{}
{{$varNameSingular}}Two := &{{$tableNameSingular}}{} {{$varNameSingular}}Two := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}One, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}ColumnsWithDefault...); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}One, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}ColumnsWithDefault...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
if err = randomize.Struct(seed, {{$varNameSingular}}Two, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}ColumnsWithDefault...); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}Two, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}ColumnsWithDefault...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}One.Insert(tx); err != nil { if err = {{$varNameSingular}}One.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
if err = {{$varNameSingular}}Two.Insert(tx); err != nil { if err = {{$varNameSingular}}Two.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
count, err := {{$tableNamePlural}}(tx).Count() count, err := {{$tableNamePlural}}(tx).Count()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if count != 2 { if count != 2 {
t.Error("want 2 records, got:", count) t.Error("want 2 records, got:", count)
} }
} }

View file

@ -5,57 +5,57 @@
var {{$varNameSingular}}DBTypes = map[string]string{{"{"}}{{.Table.Columns | columnDBTypes | makeStringMap}}{{"}"}} var {{$varNameSingular}}DBTypes = map[string]string{{"{"}}{{.Table.Columns | columnDBTypes | makeStringMap}}{{"}"}}
func test{{$tableNamePlural}}InPrimaryKeyArgs(t *testing.T) { func test{{$tableNamePlural}}InPrimaryKeyArgs(t *testing.T) {
t.Parallel() t.Parallel()
var err error var err error
var o {{$tableNameSingular}} var o {{$tableNameSingular}}
o = {{$tableNameSingular}}{} o = {{$tableNameSingular}}{}
seed := randomize.NewSeed() seed := randomize.NewSeed()
if err = randomize.Struct(seed, &o, {{$varNameSingular}}DBTypes, true); err != nil { if err = randomize.Struct(seed, &o, {{$varNameSingular}}DBTypes, true); err != nil {
t.Errorf("Could not randomize struct: %s", err) t.Errorf("Could not randomize struct: %s", err)
} }
args := o.inPrimaryKeyArgs() args := o.inPrimaryKeyArgs()
if len(args) != len({{$varNameSingular}}PrimaryKeyColumns) { if len(args) != len({{$varNameSingular}}PrimaryKeyColumns) {
t.Errorf("Expected args to be len %d, but got %d", len({{$varNameSingular}}PrimaryKeyColumns), len(args)) t.Errorf("Expected args to be len %d, but got %d", len({{$varNameSingular}}PrimaryKeyColumns), len(args))
} }
{{range $key, $value := .Table.PKey.Columns}} {{range $key, $value := .Table.PKey.Columns}}
if o.{{titleCase $value}} != args[{{$key}}] { if o.{{titleCase $value}} != args[{{$key}}] {
t.Errorf("Expected args[{{$key}}] to be value of o.{{titleCase $value}}, but got %#v", args[{{$key}}]) t.Errorf("Expected args[{{$key}}] to be value of o.{{titleCase $value}}, but got %#v", args[{{$key}}])
} }
{{- end}} {{- end}}
} }
func test{{$tableNamePlural}}SliceInPrimaryKeyArgs(t *testing.T) { func test{{$tableNamePlural}}SliceInPrimaryKeyArgs(t *testing.T) {
t.Parallel() t.Parallel()
var err error var err error
o := make({{$tableNameSingular}}Slice, 3) o := make({{$tableNameSingular}}Slice, 3)
seed := randomize.NewSeed() seed := randomize.NewSeed()
for i := range o { for i := range o {
o[i] = &{{$tableNameSingular}}{} o[i] = &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, o[i], {{$varNameSingular}}DBTypes, true); err != nil { if err = randomize.Struct(seed, o[i], {{$varNameSingular}}DBTypes, true); err != nil {
t.Errorf("Could not randomize struct: %s", err) t.Errorf("Could not randomize struct: %s", err)
} }
} }
args := o.inPrimaryKeyArgs() args := o.inPrimaryKeyArgs()
if len(args) != len({{$varNameSingular}}PrimaryKeyColumns) * 3 { if len(args) != len({{$varNameSingular}}PrimaryKeyColumns) * 3 {
t.Errorf("Expected args to be len %d, but got %d", len({{$varNameSingular}}PrimaryKeyColumns) * 3, len(args)) t.Errorf("Expected args to be len %d, but got %d", len({{$varNameSingular}}PrimaryKeyColumns) * 3, len(args))
} }
argC := 0 argC := 0
for i := 0; i < 3; i++ { for i := 0; i < 3; i++ {
{{range $key, $value := .Table.PKey.Columns}} {{range $key, $value := .Table.PKey.Columns}}
if o[i].{{titleCase $value}} != args[argC] { if o[i].{{titleCase $value}} != args[argC] {
t.Errorf("Expected args[%d] to be value of o.{{titleCase $value}}, but got %#v", i, args[i]) t.Errorf("Expected args[%d] to be value of o.{{titleCase $value}}, but got %#v", i, args[i])
} }
argC++ argC++
{{- end}} {{- end}}
} }
} }

View file

@ -4,142 +4,142 @@
{{- $varNamePlural := .Table.Name | plural | camelCase -}} {{- $varNamePlural := .Table.Name | plural | camelCase -}}
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
func {{$varNameSingular}}BeforeInsertHook(e boil.Executor, o *{{$tableNameSingular}}) error { func {{$varNameSingular}}BeforeInsertHook(e boil.Executor, o *{{$tableNameSingular}}) error {
*o = {{$tableNameSingular}}{} *o = {{$tableNameSingular}}{}
return nil return nil
} }
func {{$varNameSingular}}AfterInsertHook(e boil.Executor, o *{{$tableNameSingular}}) error { func {{$varNameSingular}}AfterInsertHook(e boil.Executor, o *{{$tableNameSingular}}) error {
*o = {{$tableNameSingular}}{} *o = {{$tableNameSingular}}{}
return nil return nil
} }
func {{$varNameSingular}}AfterSelectHook(e boil.Executor, o *{{$tableNameSingular}}) error { func {{$varNameSingular}}AfterSelectHook(e boil.Executor, o *{{$tableNameSingular}}) error {
*o = {{$tableNameSingular}}{} *o = {{$tableNameSingular}}{}
return nil return nil
} }
func {{$varNameSingular}}BeforeUpdateHook(e boil.Executor, o *{{$tableNameSingular}}) error { func {{$varNameSingular}}BeforeUpdateHook(e boil.Executor, o *{{$tableNameSingular}}) error {
*o = {{$tableNameSingular}}{} *o = {{$tableNameSingular}}{}
return nil return nil
} }
func {{$varNameSingular}}AfterUpdateHook(e boil.Executor, o *{{$tableNameSingular}}) error { func {{$varNameSingular}}AfterUpdateHook(e boil.Executor, o *{{$tableNameSingular}}) error {
*o = {{$tableNameSingular}}{} *o = {{$tableNameSingular}}{}
return nil return nil
} }
func {{$varNameSingular}}BeforeDeleteHook(e boil.Executor, o *{{$tableNameSingular}}) error { func {{$varNameSingular}}BeforeDeleteHook(e boil.Executor, o *{{$tableNameSingular}}) error {
*o = {{$tableNameSingular}}{} *o = {{$tableNameSingular}}{}
return nil return nil
} }
func {{$varNameSingular}}AfterDeleteHook(e boil.Executor, o *{{$tableNameSingular}}) error { func {{$varNameSingular}}AfterDeleteHook(e boil.Executor, o *{{$tableNameSingular}}) error {
*o = {{$tableNameSingular}}{} *o = {{$tableNameSingular}}{}
return nil return nil
} }
func {{$varNameSingular}}BeforeUpsertHook(e boil.Executor, o *{{$tableNameSingular}}) error { func {{$varNameSingular}}BeforeUpsertHook(e boil.Executor, o *{{$tableNameSingular}}) error {
*o = {{$tableNameSingular}}{} *o = {{$tableNameSingular}}{}
return nil return nil
} }
func {{$varNameSingular}}AfterUpsertHook(e boil.Executor, o *{{$tableNameSingular}}) error { func {{$varNameSingular}}AfterUpsertHook(e boil.Executor, o *{{$tableNameSingular}}) error {
*o = {{$tableNameSingular}}{} *o = {{$tableNameSingular}}{}
return nil return nil
} }
func test{{$tableNamePlural}}Hooks(t *testing.T) { func test{{$tableNamePlural}}Hooks(t *testing.T) {
t.Parallel() t.Parallel()
var err error var err error
empty := &{{$tableNameSingular}}{} empty := &{{$tableNameSingular}}{}
o := &{{$tableNameSingular}}{} o := &{{$tableNameSingular}}{}
seed := randomize.NewSeed() seed := randomize.NewSeed()
if err = randomize.Struct(seed, o, {{$varNameSingular}}DBTypes, false); err != nil { if err = randomize.Struct(seed, o, {{$varNameSingular}}DBTypes, false); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} object: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} object: %s", err)
} }
Add{{$tableNameSingular}}Hook(boil.BeforeInsertHook, {{$varNameSingular}}BeforeInsertHook) Add{{$tableNameSingular}}Hook(boil.BeforeInsertHook, {{$varNameSingular}}BeforeInsertHook)
if err = o.doBeforeInsertHooks(nil); err != nil { if err = o.doBeforeInsertHooks(nil); err != nil {
t.Errorf("Unable to execute doBeforeInsertHooks: %s", err) t.Errorf("Unable to execute doBeforeInsertHooks: %s", err)
} }
if !reflect.DeepEqual(o, empty) { if !reflect.DeepEqual(o, empty) {
t.Errorf("Expected BeforeInsertHook function to empty object, but got: %#v", o) t.Errorf("Expected BeforeInsertHook function to empty object, but got: %#v", o)
} }
{{$varNameSingular}}BeforeInsertHooks = []{{$tableNameSingular}}Hook{} {{$varNameSingular}}BeforeInsertHooks = []{{$tableNameSingular}}Hook{}
Add{{$tableNameSingular}}Hook(boil.AfterInsertHook, {{$varNameSingular}}AfterInsertHook) Add{{$tableNameSingular}}Hook(boil.AfterInsertHook, {{$varNameSingular}}AfterInsertHook)
if err = o.doAfterInsertHooks(nil); err != nil { if err = o.doAfterInsertHooks(nil); err != nil {
t.Errorf("Unable to execute doAfterInsertHooks: %s", err) t.Errorf("Unable to execute doAfterInsertHooks: %s", err)
} }
if !reflect.DeepEqual(o, empty) { if !reflect.DeepEqual(o, empty) {
t.Errorf("Expected AfterInsertHook function to empty object, but got: %#v", o) t.Errorf("Expected AfterInsertHook function to empty object, but got: %#v", o)
} }
{{$varNameSingular}}AfterInsertHooks = []{{$tableNameSingular}}Hook{} {{$varNameSingular}}AfterInsertHooks = []{{$tableNameSingular}}Hook{}
Add{{$tableNameSingular}}Hook(boil.AfterSelectHook, {{$varNameSingular}}AfterSelectHook) Add{{$tableNameSingular}}Hook(boil.AfterSelectHook, {{$varNameSingular}}AfterSelectHook)
if err = o.doAfterSelectHooks(nil); err != nil { if err = o.doAfterSelectHooks(nil); err != nil {
t.Errorf("Unable to execute doAfterSelectHooks: %s", err) t.Errorf("Unable to execute doAfterSelectHooks: %s", err)
} }
if !reflect.DeepEqual(o, empty) { if !reflect.DeepEqual(o, empty) {
t.Errorf("Expected AfterSelectHook function to empty object, but got: %#v", o) t.Errorf("Expected AfterSelectHook function to empty object, but got: %#v", o)
} }
{{$varNameSingular}}AfterSelectHooks = []{{$tableNameSingular}}Hook{} {{$varNameSingular}}AfterSelectHooks = []{{$tableNameSingular}}Hook{}
Add{{$tableNameSingular}}Hook(boil.BeforeUpdateHook, {{$varNameSingular}}BeforeUpdateHook) Add{{$tableNameSingular}}Hook(boil.BeforeUpdateHook, {{$varNameSingular}}BeforeUpdateHook)
if err = o.doBeforeUpdateHooks(nil); err != nil { if err = o.doBeforeUpdateHooks(nil); err != nil {
t.Errorf("Unable to execute doBeforeUpdateHooks: %s", err) t.Errorf("Unable to execute doBeforeUpdateHooks: %s", err)
} }
if !reflect.DeepEqual(o, empty) { if !reflect.DeepEqual(o, empty) {
t.Errorf("Expected BeforeUpdateHook function to empty object, but got: %#v", o) t.Errorf("Expected BeforeUpdateHook function to empty object, but got: %#v", o)
} }
{{$varNameSingular}}BeforeUpdateHooks = []{{$tableNameSingular}}Hook{} {{$varNameSingular}}BeforeUpdateHooks = []{{$tableNameSingular}}Hook{}
Add{{$tableNameSingular}}Hook(boil.AfterUpdateHook, {{$varNameSingular}}AfterUpdateHook) Add{{$tableNameSingular}}Hook(boil.AfterUpdateHook, {{$varNameSingular}}AfterUpdateHook)
if err = o.doAfterUpdateHooks(nil); err != nil { if err = o.doAfterUpdateHooks(nil); err != nil {
t.Errorf("Unable to execute doAfterUpdateHooks: %s", err) t.Errorf("Unable to execute doAfterUpdateHooks: %s", err)
} }
if !reflect.DeepEqual(o, empty) { if !reflect.DeepEqual(o, empty) {
t.Errorf("Expected AfterUpdateHook function to empty object, but got: %#v", o) t.Errorf("Expected AfterUpdateHook function to empty object, but got: %#v", o)
} }
{{$varNameSingular}}AfterUpdateHooks = []{{$tableNameSingular}}Hook{} {{$varNameSingular}}AfterUpdateHooks = []{{$tableNameSingular}}Hook{}
Add{{$tableNameSingular}}Hook(boil.BeforeDeleteHook, {{$varNameSingular}}BeforeDeleteHook) Add{{$tableNameSingular}}Hook(boil.BeforeDeleteHook, {{$varNameSingular}}BeforeDeleteHook)
if err = o.doBeforeDeleteHooks(nil); err != nil { if err = o.doBeforeDeleteHooks(nil); err != nil {
t.Errorf("Unable to execute doBeforeDeleteHooks: %s", err) t.Errorf("Unable to execute doBeforeDeleteHooks: %s", err)
} }
if !reflect.DeepEqual(o, empty) { if !reflect.DeepEqual(o, empty) {
t.Errorf("Expected BeforeDeleteHook function to empty object, but got: %#v", o) t.Errorf("Expected BeforeDeleteHook function to empty object, but got: %#v", o)
} }
{{$varNameSingular}}BeforeDeleteHooks = []{{$tableNameSingular}}Hook{} {{$varNameSingular}}BeforeDeleteHooks = []{{$tableNameSingular}}Hook{}
Add{{$tableNameSingular}}Hook(boil.AfterDeleteHook, {{$varNameSingular}}AfterDeleteHook) Add{{$tableNameSingular}}Hook(boil.AfterDeleteHook, {{$varNameSingular}}AfterDeleteHook)
if err = o.doAfterDeleteHooks(nil); err != nil { if err = o.doAfterDeleteHooks(nil); err != nil {
t.Errorf("Unable to execute doAfterDeleteHooks: %s", err) t.Errorf("Unable to execute doAfterDeleteHooks: %s", err)
} }
if !reflect.DeepEqual(o, empty) { if !reflect.DeepEqual(o, empty) {
t.Errorf("Expected AfterDeleteHook function to empty object, but got: %#v", o) t.Errorf("Expected AfterDeleteHook function to empty object, but got: %#v", o)
} }
{{$varNameSingular}}AfterDeleteHooks = []{{$tableNameSingular}}Hook{} {{$varNameSingular}}AfterDeleteHooks = []{{$tableNameSingular}}Hook{}
Add{{$tableNameSingular}}Hook(boil.BeforeUpsertHook, {{$varNameSingular}}BeforeUpsertHook) Add{{$tableNameSingular}}Hook(boil.BeforeUpsertHook, {{$varNameSingular}}BeforeUpsertHook)
if err = o.doBeforeUpsertHooks(nil); err != nil { if err = o.doBeforeUpsertHooks(nil); err != nil {
t.Errorf("Unable to execute doBeforeUpsertHooks: %s", err) t.Errorf("Unable to execute doBeforeUpsertHooks: %s", err)
} }
if !reflect.DeepEqual(o, empty) { if !reflect.DeepEqual(o, empty) {
t.Errorf("Expected BeforeUpsertHook function to empty object, but got: %#v", o) t.Errorf("Expected BeforeUpsertHook function to empty object, but got: %#v", o)
} }
{{$varNameSingular}}BeforeUpsertHooks = []{{$tableNameSingular}}Hook{} {{$varNameSingular}}BeforeUpsertHooks = []{{$tableNameSingular}}Hook{}
Add{{$tableNameSingular}}Hook(boil.AfterUpsertHook, {{$varNameSingular}}AfterUpsertHook) Add{{$tableNameSingular}}Hook(boil.AfterUpsertHook, {{$varNameSingular}}AfterUpsertHook)
if err = o.doAfterUpsertHooks(nil); err != nil { if err = o.doAfterUpsertHooks(nil); err != nil {
t.Errorf("Unable to execute doAfterUpsertHooks: %s", err) t.Errorf("Unable to execute doAfterUpsertHooks: %s", err)
} }
if !reflect.DeepEqual(o, empty) { if !reflect.DeepEqual(o, empty) {
t.Errorf("Expected AfterUpsertHook function to empty object, but got: %#v", o) t.Errorf("Expected AfterUpsertHook function to empty object, but got: %#v", o)
} }
{{$varNameSingular}}AfterUpsertHooks = []{{$tableNameSingular}}Hook{} {{$varNameSingular}}AfterUpsertHooks = []{{$tableNameSingular}}Hook{}
} }
{{- end}} {{- end}}

View file

@ -4,53 +4,53 @@
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
{{- $parent := . -}} {{- $parent := . -}}
func test{{$tableNamePlural}}Insert(t *testing.T) { func test{{$tableNamePlural}}Insert(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}} := &{{$tableNameSingular}}{} {{$varNameSingular}} := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Insert(tx); err != nil { if err = {{$varNameSingular}}.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
count, err := {{$tableNamePlural}}(tx).Count() count, err := {{$tableNamePlural}}(tx).Count()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if count != 1 { if count != 1 {
t.Error("want one record, got:", count) t.Error("want one record, got:", count)
} }
} }
func test{{$tableNamePlural}}InsertWhitelist(t *testing.T) { func test{{$tableNamePlural}}InsertWhitelist(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}} := &{{$tableNameSingular}}{} {{$varNameSingular}} := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Insert(tx, {{$varNameSingular}}Columns...); err != nil { if err = {{$varNameSingular}}.Insert(tx, {{$varNameSingular}}Columns...); err != nil {
t.Error(err) t.Error(err)
} }
count, err := {{$tableNamePlural}}(tx).Count() count, err := {{$tableNamePlural}}(tx).Count()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if count != 1 { if count != 1 {
t.Error("want one record, got:", count) t.Error("want one record, got:", count)
} }
} }

View file

@ -1,157 +1,166 @@
type mysqlTester struct { type mysqlTester struct {
dbConn *sql.DB dbConn *sql.DB
dbName string dbName string
host string host string
user string user string
pass string pass string
sslmode string sslmode string
port int port int
optionFile string optionFile string
testDBName string testDBName string
} }
func init() { func init() {
dbMain = &mysqlTester{} dbMain = &mysqlTester{}
} }
func (m *mysqlTester) setup() error { func (m *mysqlTester) setup() error {
var err error var err error
m.dbName = viper.GetString("mysql.dbname") m.dbName = viper.GetString("mysql.dbname")
m.host = viper.GetString("mysql.host") m.host = viper.GetString("mysql.host")
m.user = viper.GetString("mysql.user") m.user = viper.GetString("mysql.user")
m.pass = viper.GetString("mysql.pass") m.pass = viper.GetString("mysql.pass")
m.port = viper.GetInt("mysql.port") m.port = viper.GetInt("mysql.port")
m.sslmode = viper.GetString("mysql.sslmode") m.sslmode = viper.GetString("mysql.sslmode")
// Create a randomized db name. // Create a randomized db name.
m.testDBName = randomize.StableDBName(m.dbName) m.testDBName = randomize.StableDBName(m.dbName)
if err = m.makeOptionFile(); err != nil { if err = m.makeOptionFile(); err != nil {
return errors.Wrap(err, "couldn't make option file") return errors.Wrap(err, "couldn't make option file")
} }
if err = m.dropTestDB(); err != nil { if err = m.dropTestDB(); err != nil {
return err return err
} }
if err = m.createTestDB(); err != nil { if err = m.createTestDB(); err != nil {
return err return err
} }
dumpCmd := exec.Command("mysqldump", m.defaultsFile(), m.dbName) dumpCmd := exec.Command("mysqldump", m.defaultsFile(), m.dbName)
createCmd := exec.Command("mysql", m.defaultsFile(), "--database", m.testDBName) createCmd := exec.Command("mysql", m.defaultsFile(), "--database", m.testDBName)
r, w := io.Pipe() r, w := io.Pipe()
dumpCmd.Stdout = w dumpCmd.Stdout = w
createCmd.Stdin = newFKeyDestroyer(rgxMySQLkey, r) createCmd.Stdin = newFKeyDestroyer(rgxMySQLkey, r)
if err = dumpCmd.Start(); err != nil { if err = dumpCmd.Start(); err != nil {
return errors.Wrap(err, "failed to start mysqldump command") return errors.Wrap(err, "failed to start mysqldump command")
} }
if err = createCmd.Start(); err != nil { if err = createCmd.Start(); err != nil {
return errors.Wrap(err, "failed to start mysql command") return errors.Wrap(err, "failed to start mysql command")
} }
if err = dumpCmd.Wait(); err != nil { if err = dumpCmd.Wait(); err != nil {
fmt.Println(err) fmt.Println(err)
return errors.Wrap(err, "failed to wait for mysqldump command") return errors.Wrap(err, "failed to wait for mysqldump command")
} }
w.Close() // After dumpCmd is done, close the write end of the pipe w.Close() // After dumpCmd is done, close the write end of the pipe
if err = createCmd.Wait(); err != nil { if err = createCmd.Wait(); err != nil {
fmt.Println(err) fmt.Println(err)
return errors.Wrap(err, "failed to wait for mysql command") return errors.Wrap(err, "failed to wait for mysql command")
} }
return nil return nil
}
func (m *mysqlTester) sslMode(mode string) string {
switch mode {
case "true":
return "REQUIRED"
case "false":
return "DISABLED"
default:
return "PREFERRED"
}
} }
func (m *mysqlTester) defaultsFile() string { func (m *mysqlTester) defaultsFile() string {
return fmt.Sprintf("--defaults-file=%s", m.optionFile) return fmt.Sprintf("--defaults-file=%s", m.optionFile)
} }
func (m *mysqlTester) makeOptionFile() error { func (m *mysqlTester) makeOptionFile() error {
tmp, err := ioutil.TempFile("", "optionfile") tmp, err := ioutil.TempFile("", "optionfile")
if err != nil { if err != nil {
return errors.Wrap(err, "failed to create option file") return errors.Wrap(err, "failed to create option file")
} }
fmt.Fprintln(tmp, "[client]") fmt.Fprintln(tmp, "[client]")
fmt.Fprintf(tmp, "host=%s\n", m.host) fmt.Fprintf(tmp, "host=%s\n", m.host)
fmt.Fprintf(tmp, "port=%d\n", m.port) fmt.Fprintf(tmp, "port=%d\n", m.port)
fmt.Fprintf(tmp, "user=%s\n", m.user) fmt.Fprintf(tmp, "user=%s\n", m.user)
fmt.Fprintf(tmp, "password=%s\n", m.pass) fmt.Fprintf(tmp, "password=%s\n", m.pass)
// BUG: SSL Mode for whatever reason is backwards in the mysql driver fmt.Fprintf(tmp, "ssl-mode=%s\n", m.sslMode(m.sslmode))
// taking options like true or false, but here taking options like
// required/disabled. Until this gets sorted, ignore this.
//fmt.Fprintf("ssl-mode=%s\n", m.password)
fmt.Fprintln(tmp, "[mysqldump]") fmt.Fprintln(tmp, "[mysqldump]")
fmt.Fprintf(tmp, "host=%s\n", m.host) fmt.Fprintf(tmp, "host=%s\n", m.host)
fmt.Fprintf(tmp, "port=%d\n", m.port) fmt.Fprintf(tmp, "port=%d\n", m.port)
fmt.Fprintf(tmp, "user=%s\n", m.user) fmt.Fprintf(tmp, "user=%s\n", m.user)
fmt.Fprintf(tmp, "password=%s\n", m.pass) fmt.Fprintf(tmp, "password=%s\n", m.pass)
fmt.Fprintf(tmp, "ssl-mode=%s\n", m.sslMode(m.sslmode))
m.optionFile = tmp.Name() m.optionFile = tmp.Name()
return tmp.Close() return tmp.Close()
} }
func (m *mysqlTester) createTestDB() error { func (m *mysqlTester) createTestDB() error {
sql := fmt.Sprintf("create database %s;", m.testDBName) sql := fmt.Sprintf("create database %s;", m.testDBName)
return m.runCmd(sql, "mysql") return m.runCmd(sql, "mysql")
} }
func (m *mysqlTester) dropTestDB() error { func (m *mysqlTester) dropTestDB() error {
sql := fmt.Sprintf("drop database if exists %s;", m.testDBName) sql := fmt.Sprintf("drop database if exists %s;", m.testDBName)
return m.runCmd(sql, "mysql") return m.runCmd(sql, "mysql")
} }
func (m *mysqlTester) teardown() error { func (m *mysqlTester) teardown() error {
if m.dbConn != nil { if m.dbConn != nil {
m.dbConn.Close() m.dbConn.Close()
} }
if err := m.dropTestDB(); err != nil { if err := m.dropTestDB(); err != nil {
return err return err
} }
return os.Remove(m.optionFile) return os.Remove(m.optionFile)
} }
func (m *mysqlTester) runCmd(stdin, command string, args ...string) error { func (m *mysqlTester) runCmd(stdin, command string, args ...string) error {
args = append([]string{m.defaultsFile()}, args...) args = append([]string{m.defaultsFile()}, args...)
cmd := exec.Command(command, args...) cmd := exec.Command(command, args...)
cmd.Stdin = strings.NewReader(stdin) cmd.Stdin = strings.NewReader(stdin)
stdout := &bytes.Buffer{} stdout := &bytes.Buffer{}
stderr := &bytes.Buffer{} stderr := &bytes.Buffer{}
cmd.Stdout = stdout cmd.Stdout = stdout
cmd.Stderr = stderr cmd.Stderr = stderr
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
fmt.Println("failed running:", command, args) fmt.Println("failed running:", command, args)
fmt.Println(stdout.String()) fmt.Println(stdout.String())
fmt.Println(stderr.String()) fmt.Println(stderr.String())
return err return err
} }
return nil return nil
} }
func (m *mysqlTester) conn() (*sql.DB, error) { func (m *mysqlTester) conn() (*sql.DB, error) {
if m.dbConn != nil { if m.dbConn != nil {
return m.dbConn, nil return m.dbConn, nil
} }
var err error var err error
m.dbConn, err = sql.Open("mysql", drivers.MySQLBuildQueryString(m.user, m.pass, m.testDBName, m.host, m.port, m.sslmode)) m.dbConn, err = sql.Open("mysql", drivers.MySQLBuildQueryString(m.user, m.pass, m.testDBName, m.host, m.port, m.sslmode))
if err != nil { if err != nil {
return nil, err return nil, err
} }
return m.dbConn, nil return m.dbConn, nil
} }

View file

@ -1,98 +1,98 @@
{{- if .Table.IsJoinTable -}} {{- if .Table.IsJoinTable -}}
{{- else -}} {{- else -}}
{{- $dot := . }} {{- $dot := . }}
{{- $table := .Table }} {{- $table := .Table }}
{{- range .Table.ToManyRelationships -}} {{- range .Table.ToManyRelationships -}}
{{- if (and .ForeignColumnUnique (not .ToJoinTable)) -}} {{- if (and .ForeignColumnUnique (not .ToJoinTable)) -}}
{{- template "relationship_to_one_test_helper" (textsFromOneToOneRelationship $dot.PkgName $dot.Tables $table .) -}} {{- template "relationship_to_one_test_helper" (textsFromOneToOneRelationship $dot.PkgName $dot.Tables $table .) -}}
{{- else -}} {{- else -}}
{{- $rel := textsFromRelationship $dot.Tables $table . -}} {{- $rel := textsFromRelationship $dot.Tables $table . -}}
func test{{$rel.LocalTable.NameGo}}ToMany{{$rel.Function.Name}}(t *testing.T) { func test{{$rel.LocalTable.NameGo}}ToMany{{$rel.Function.Name}}(t *testing.T) {
var err error var err error
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
var a {{$rel.LocalTable.NameGo}} var a {{$rel.LocalTable.NameGo}}
var b, c {{$rel.ForeignTable.NameGo}} var b, c {{$rel.ForeignTable.NameGo}}
if err := a.Insert(tx); err != nil { if err := a.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
seed := randomize.NewSeed() seed := randomize.NewSeed()
randomize.Struct(seed, &b, {{$rel.ForeignTable.NameSingular | camelCase}}DBTypes, false, "{{.ForeignColumn}}") randomize.Struct(seed, &b, {{$rel.ForeignTable.NameSingular | camelCase}}DBTypes, false, "{{.ForeignColumn}}")
randomize.Struct(seed, &c, {{$rel.ForeignTable.NameSingular | camelCase}}DBTypes, false, "{{.ForeignColumn}}") randomize.Struct(seed, &c, {{$rel.ForeignTable.NameSingular | camelCase}}DBTypes, false, "{{.ForeignColumn}}")
{{if .Nullable -}} {{if .Nullable -}}
a.{{.Column | titleCase}}.Valid = true a.{{.Column | titleCase}}.Valid = true
{{- end}} {{- end}}
{{- if .ForeignColumnNullable -}} {{- if .ForeignColumnNullable -}}
b.{{.ForeignColumn | titleCase}}.Valid = true b.{{.ForeignColumn | titleCase}}.Valid = true
c.{{.ForeignColumn | titleCase}}.Valid = true c.{{.ForeignColumn | titleCase}}.Valid = true
{{- end}} {{- end}}
{{if not .ToJoinTable -}} {{if not .ToJoinTable -}}
b.{{$rel.Function.ForeignAssignment}} = a.{{$rel.Function.LocalAssignment}} b.{{$rel.Function.ForeignAssignment}} = a.{{$rel.Function.LocalAssignment}}
c.{{$rel.Function.ForeignAssignment}} = a.{{$rel.Function.LocalAssignment}} c.{{$rel.Function.ForeignAssignment}} = a.{{$rel.Function.LocalAssignment}}
{{- end}} {{- end}}
if err = b.Insert(tx); err != nil { if err = b.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err = c.Insert(tx); err != nil { if err = c.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
{{if .ToJoinTable -}} {{if .ToJoinTable -}}
_, err = tx.Exec("insert into {{.JoinTable | $dot.SchemaTable}} ({{.JoinLocalColumn | $dot.Quotes}}, {{.JoinForeignColumn | $dot.Quotes}}) values {{if $dot.Dialect.IndexPlaceholders}}($1, $2){{else}}(?, ?){{end}}", a.{{$rel.LocalTable.ColumnNameGo}}, b.{{$rel.ForeignTable.ColumnNameGo}}) _, err = tx.Exec("insert into {{.JoinTable | $dot.SchemaTable}} ({{.JoinLocalColumn | $dot.Quotes}}, {{.JoinForeignColumn | $dot.Quotes}}) values {{if $dot.Dialect.IndexPlaceholders}}($1, $2){{else}}(?, ?){{end}}", a.{{$rel.LocalTable.ColumnNameGo}}, b.{{$rel.ForeignTable.ColumnNameGo}})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
_, err = tx.Exec("insert into {{.JoinTable | $dot.SchemaTable}} ({{.JoinLocalColumn | $dot.Quotes}}, {{.JoinForeignColumn | $dot.Quotes}}) values {{if $dot.Dialect.IndexPlaceholders}}($1, $2){{else}}(?, ?){{end}}", a.{{$rel.LocalTable.ColumnNameGo}}, c.{{$rel.ForeignTable.ColumnNameGo}}) _, err = tx.Exec("insert into {{.JoinTable | $dot.SchemaTable}} ({{.JoinLocalColumn | $dot.Quotes}}, {{.JoinForeignColumn | $dot.Quotes}}) values {{if $dot.Dialect.IndexPlaceholders}}($1, $2){{else}}(?, ?){{end}}", a.{{$rel.LocalTable.ColumnNameGo}}, c.{{$rel.ForeignTable.ColumnNameGo}})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
{{end}} {{end}}
{{$varname := .ForeignTable | singular | camelCase -}} {{$varname := .ForeignTable | singular | camelCase -}}
{{$varname}}, err := a.{{$rel.Function.Name}}(tx).All() {{$varname}}, err := a.{{$rel.Function.Name}}(tx).All()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
bFound, cFound := false, false bFound, cFound := false, false
for _, v := range {{$varname}} { for _, v := range {{$varname}} {
if v.{{$rel.Function.ForeignAssignment}} == b.{{$rel.Function.ForeignAssignment}} { if v.{{$rel.Function.ForeignAssignment}} == b.{{$rel.Function.ForeignAssignment}} {
bFound = true bFound = true
} }
if v.{{$rel.Function.ForeignAssignment}} == c.{{$rel.Function.ForeignAssignment}} { if v.{{$rel.Function.ForeignAssignment}} == c.{{$rel.Function.ForeignAssignment}} {
cFound = true cFound = true
} }
} }
if !bFound { if !bFound {
t.Error("expected to find b") t.Error("expected to find b")
} }
if !cFound { if !cFound {
t.Error("expected to find c") t.Error("expected to find c")
} }
slice := {{$rel.LocalTable.NameGo}}Slice{&a} slice := {{$rel.LocalTable.NameGo}}Slice{&a}
if err = a.L.Load{{$rel.Function.Name}}(tx, false, &slice); err != nil { if err = a.L.Load{{$rel.Function.Name}}(tx, false, &slice); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if got := len(a.R.{{$rel.Function.Name}}); got != 2 { if got := len(a.R.{{$rel.Function.Name}}); got != 2 {
t.Error("number of eager loaded records wrong, got:", got) t.Error("number of eager loaded records wrong, got:", got)
} }
a.R.{{$rel.Function.Name}} = nil a.R.{{$rel.Function.Name}} = nil
if err = a.L.Load{{$rel.Function.Name}}(tx, true, &a); err != nil { if err = a.L.Load{{$rel.Function.Name}}(tx, true, &a); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if got := len(a.R.{{$rel.Function.Name}}); got != 2 { if got := len(a.R.{{$rel.Function.Name}}); got != 2 {
t.Error("number of eager loaded records wrong, got:", got) t.Error("number of eager loaded records wrong, got:", got)
} }
if t.Failed() { if t.Failed() {
t.Logf("%#v", {{$varname}}) t.Logf("%#v", {{$varname}})
} }
} }
{{end -}}{{- /* if unique */ -}} {{end -}}{{- /* if unique */ -}}

View file

@ -1,306 +1,306 @@
{{- if .Table.IsJoinTable -}} {{- if .Table.IsJoinTable -}}
{{- else -}} {{- else -}}
{{- $dot := . -}} {{- $dot := . -}}
{{- $table := .Table -}} {{- $table := .Table -}}
{{- range .Table.ToManyRelationships -}} {{- range .Table.ToManyRelationships -}}
{{- if (and .ForeignColumnUnique (not .ToJoinTable)) -}} {{- if (and .ForeignColumnUnique (not .ToJoinTable)) -}}
{{- template "relationship_to_one_setops_test_helper" (textsFromOneToOneRelationship $dot.PkgName $dot.Tables $table .) -}} {{- template "relationship_to_one_setops_test_helper" (textsFromOneToOneRelationship $dot.PkgName $dot.Tables $table .) -}}
{{- else -}} {{- else -}}
{{- $varNameSingular := .Table | singular | camelCase -}} {{- $varNameSingular := .Table | singular | camelCase -}}
{{- $foreignVarNameSingular := .ForeignTable | singular | camelCase -}} {{- $foreignVarNameSingular := .ForeignTable | singular | camelCase -}}
{{- $rel := textsFromRelationship $dot.Tables $table .}} {{- $rel := textsFromRelationship $dot.Tables $table .}}
func test{{$rel.LocalTable.NameGo}}ToManyAddOp{{$rel.Function.Name}}(t *testing.T) { func test{{$rel.LocalTable.NameGo}}ToManyAddOp{{$rel.Function.Name}}(t *testing.T) {
var err error var err error
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
var a {{$rel.LocalTable.NameGo}} var a {{$rel.LocalTable.NameGo}}
var b, c, d, e {{$rel.ForeignTable.NameGo}} var b, c, d, e {{$rel.ForeignTable.NameGo}}
seed := randomize.NewSeed() seed := randomize.NewSeed()
if err = randomize.Struct(seed, &a, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}PrimaryKeyColumns...); err != nil { if err = randomize.Struct(seed, &a, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}PrimaryKeyColumns...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
foreigners := []*{{$rel.ForeignTable.NameGo}}{&b, &c, &d, &e} foreigners := []*{{$rel.ForeignTable.NameGo}}{&b, &c, &d, &e}
for _, x := range foreigners { for _, x := range foreigners {
if err = randomize.Struct(seed, x, {{$foreignVarNameSingular}}DBTypes, false, {{$foreignVarNameSingular}}PrimaryKeyColumns...); err != nil { if err = randomize.Struct(seed, x, {{$foreignVarNameSingular}}DBTypes, false, {{$foreignVarNameSingular}}PrimaryKeyColumns...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
if err := a.Insert(tx); err != nil { if err := a.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err = b.Insert(tx); err != nil { if err = b.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err = c.Insert(tx); err != nil { if err = c.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
foreignersSplitByInsertion := [][]*{{$rel.ForeignTable.NameGo}}{ foreignersSplitByInsertion := [][]*{{$rel.ForeignTable.NameGo}}{
{&b, &c}, {&b, &c},
{&d, &e}, {&d, &e},
} }
for i, x := range foreignersSplitByInsertion { for i, x := range foreignersSplitByInsertion {
err = a.Add{{$rel.Function.Name}}(tx, i != 0, x...) err = a.Add{{$rel.Function.Name}}(tx, i != 0, x...)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
first := x[0] first := x[0]
second := x[1] second := x[1]
{{- if .ToJoinTable}} {{- if .ToJoinTable}}
if first.R.{{$rel.Function.ForeignName}}[0] != &a { if first.R.{{$rel.Function.ForeignName}}[0] != &a {
t.Error("relationship was not added properly to the slice") t.Error("relationship was not added properly to the slice")
} }
if second.R.{{$rel.Function.ForeignName}}[0] != &a { if second.R.{{$rel.Function.ForeignName}}[0] != &a {
t.Error("relationship was not added properly to the slice") t.Error("relationship was not added properly to the slice")
} }
{{- else}} {{- else}}
if a.{{$rel.Function.LocalAssignment}} != first.{{$rel.Function.ForeignAssignment}} { if a.{{$rel.Function.LocalAssignment}} != first.{{$rel.Function.ForeignAssignment}} {
t.Error("foreign key was wrong value", a.{{$rel.Function.LocalAssignment}}, first.{{$rel.Function.ForeignAssignment}}) t.Error("foreign key was wrong value", a.{{$rel.Function.LocalAssignment}}, first.{{$rel.Function.ForeignAssignment}})
} }
if a.{{$rel.Function.LocalAssignment}} != second.{{$rel.Function.ForeignAssignment}} { if a.{{$rel.Function.LocalAssignment}} != second.{{$rel.Function.ForeignAssignment}} {
t.Error("foreign key was wrong value", a.{{$rel.Function.LocalAssignment}}, second.{{$rel.Function.ForeignAssignment}}) t.Error("foreign key was wrong value", a.{{$rel.Function.LocalAssignment}}, second.{{$rel.Function.ForeignAssignment}})
} }
if first.R.{{$rel.Function.ForeignName}} != &a { if first.R.{{$rel.Function.ForeignName}} != &a {
t.Error("relationship was not added properly to the foreign slice") t.Error("relationship was not added properly to the foreign slice")
} }
if second.R.{{$rel.Function.ForeignName}} != &a { if second.R.{{$rel.Function.ForeignName}} != &a {
t.Error("relationship was not added properly to the foreign slice") t.Error("relationship was not added properly to the foreign slice")
} }
{{- end}} {{- end}}
if a.R.{{$rel.Function.Name}}[i*2] != first { if a.R.{{$rel.Function.Name}}[i*2] != first {
t.Error("relationship struct slice not set to correct value") t.Error("relationship struct slice not set to correct value")
} }
if a.R.{{$rel.Function.Name}}[i*2+1] != second { if a.R.{{$rel.Function.Name}}[i*2+1] != second {
t.Error("relationship struct slice not set to correct value") t.Error("relationship struct slice not set to correct value")
} }
count, err := a.{{$rel.Function.Name}}(tx).Count() count, err := a.{{$rel.Function.Name}}(tx).Count()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if want := int64((i+1)*2); count != want { if want := int64((i+1)*2); count != want {
t.Error("want", want, "got", count) t.Error("want", want, "got", count)
} }
} }
} }
{{- if (or .ForeignColumnNullable .ToJoinTable)}} {{- if (or .ForeignColumnNullable .ToJoinTable)}}
func test{{$rel.LocalTable.NameGo}}ToManySetOp{{$rel.Function.Name}}(t *testing.T) { func test{{$rel.LocalTable.NameGo}}ToManySetOp{{$rel.Function.Name}}(t *testing.T) {
var err error var err error
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
var a {{$rel.LocalTable.NameGo}} var a {{$rel.LocalTable.NameGo}}
var b, c, d, e {{$rel.ForeignTable.NameGo}} var b, c, d, e {{$rel.ForeignTable.NameGo}}
seed := randomize.NewSeed() seed := randomize.NewSeed()
if err = randomize.Struct(seed, &a, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}PrimaryKeyColumns...); err != nil { if err = randomize.Struct(seed, &a, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}PrimaryKeyColumns...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
foreigners := []*{{$rel.ForeignTable.NameGo}}{&b, &c, &d, &e} foreigners := []*{{$rel.ForeignTable.NameGo}}{&b, &c, &d, &e}
for _, x := range foreigners { for _, x := range foreigners {
if err = randomize.Struct(seed, x, {{$foreignVarNameSingular}}DBTypes, false, {{$foreignVarNameSingular}}PrimaryKeyColumns...); err != nil { if err = randomize.Struct(seed, x, {{$foreignVarNameSingular}}DBTypes, false, {{$foreignVarNameSingular}}PrimaryKeyColumns...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
if err = a.Insert(tx); err != nil { if err = a.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err = b.Insert(tx); err != nil { if err = b.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err = c.Insert(tx); err != nil { if err = c.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
err = a.Set{{$rel.Function.Name}}(tx, false, &b, &c) err = a.Set{{$rel.Function.Name}}(tx, false, &b, &c)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
count, err := a.{{$rel.Function.Name}}(tx).Count() count, err := a.{{$rel.Function.Name}}(tx).Count()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if count != 2 { if count != 2 {
t.Error("count was wrong:", count) t.Error("count was wrong:", count)
} }
err = a.Set{{$rel.Function.Name}}(tx, true, &d, &e) err = a.Set{{$rel.Function.Name}}(tx, true, &d, &e)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
count, err = a.{{$rel.Function.Name}}(tx).Count() count, err = a.{{$rel.Function.Name}}(tx).Count()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if count != 2 { if count != 2 {
t.Error("count was wrong:", count) t.Error("count was wrong:", count)
} }
{{- if .ToJoinTable}} {{- if .ToJoinTable}}
if len(b.R.{{$rel.Function.ForeignName}}) != 0 { if len(b.R.{{$rel.Function.ForeignName}}) != 0 {
t.Error("relationship was not removed properly from the slice") t.Error("relationship was not removed properly from the slice")
} }
if len(c.R.{{$rel.Function.ForeignName}}) != 0 { if len(c.R.{{$rel.Function.ForeignName}}) != 0 {
t.Error("relationship was not removed properly from the slice") t.Error("relationship was not removed properly from the slice")
} }
if d.R.{{$rel.Function.ForeignName}}[0] != &a { if d.R.{{$rel.Function.ForeignName}}[0] != &a {
t.Error("relationship was not added properly to the slice") t.Error("relationship was not added properly to the slice")
} }
if e.R.{{$rel.Function.ForeignName}}[0] != &a { if e.R.{{$rel.Function.ForeignName}}[0] != &a {
t.Error("relationship was not added properly to the slice") t.Error("relationship was not added properly to the slice")
} }
{{- else}} {{- else}}
if b.{{$rel.ForeignTable.ColumnNameGo}}.Valid { if b.{{$rel.ForeignTable.ColumnNameGo}}.Valid {
t.Error("want b's foreign key value to be nil") t.Error("want b's foreign key value to be nil")
} }
if c.{{$rel.ForeignTable.ColumnNameGo}}.Valid { if c.{{$rel.ForeignTable.ColumnNameGo}}.Valid {
t.Error("want c's foreign key value to be nil") t.Error("want c's foreign key value to be nil")
} }
if a.{{$rel.Function.LocalAssignment}} != d.{{$rel.Function.ForeignAssignment}} { if a.{{$rel.Function.LocalAssignment}} != d.{{$rel.Function.ForeignAssignment}} {
t.Error("foreign key was wrong value", a.{{$rel.Function.LocalAssignment}}, d.{{$rel.Function.ForeignAssignment}}) t.Error("foreign key was wrong value", a.{{$rel.Function.LocalAssignment}}, d.{{$rel.Function.ForeignAssignment}})
} }
if a.{{$rel.Function.LocalAssignment}} != e.{{$rel.Function.ForeignAssignment}} { if a.{{$rel.Function.LocalAssignment}} != e.{{$rel.Function.ForeignAssignment}} {
t.Error("foreign key was wrong value", a.{{$rel.Function.LocalAssignment}}, e.{{$rel.Function.ForeignAssignment}}) t.Error("foreign key was wrong value", a.{{$rel.Function.LocalAssignment}}, e.{{$rel.Function.ForeignAssignment}})
} }
if b.R.{{$rel.Function.ForeignName}} != nil { if b.R.{{$rel.Function.ForeignName}} != nil {
t.Error("relationship was not removed properly from the foreign struct") t.Error("relationship was not removed properly from the foreign struct")
} }
if c.R.{{$rel.Function.ForeignName}} != nil { if c.R.{{$rel.Function.ForeignName}} != nil {
t.Error("relationship was not removed properly from the foreign struct") t.Error("relationship was not removed properly from the foreign struct")
} }
if d.R.{{$rel.Function.ForeignName}} != &a { if d.R.{{$rel.Function.ForeignName}} != &a {
t.Error("relationship was not added properly to the foreign struct") t.Error("relationship was not added properly to the foreign struct")
} }
if e.R.{{$rel.Function.ForeignName}} != &a { if e.R.{{$rel.Function.ForeignName}} != &a {
t.Error("relationship was not added properly to the foreign struct") t.Error("relationship was not added properly to the foreign struct")
} }
{{- end}} {{- end}}
if a.R.{{$rel.Function.Name}}[0] != &d { if a.R.{{$rel.Function.Name}}[0] != &d {
t.Error("relationship struct slice not set to correct value") t.Error("relationship struct slice not set to correct value")
} }
if a.R.{{$rel.Function.Name}}[1] != &e { if a.R.{{$rel.Function.Name}}[1] != &e {
t.Error("relationship struct slice not set to correct value") t.Error("relationship struct slice not set to correct value")
} }
} }
func test{{$rel.LocalTable.NameGo}}ToManyRemoveOp{{$rel.Function.Name}}(t *testing.T) { func test{{$rel.LocalTable.NameGo}}ToManyRemoveOp{{$rel.Function.Name}}(t *testing.T) {
var err error var err error
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
var a {{$rel.LocalTable.NameGo}} var a {{$rel.LocalTable.NameGo}}
var b, c, d, e {{$rel.ForeignTable.NameGo}} var b, c, d, e {{$rel.ForeignTable.NameGo}}
seed := randomize.NewSeed() seed := randomize.NewSeed()
if err = randomize.Struct(seed, &a, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}PrimaryKeyColumns...); err != nil { if err = randomize.Struct(seed, &a, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}PrimaryKeyColumns...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
foreigners := []*{{$rel.ForeignTable.NameGo}}{&b, &c, &d, &e} foreigners := []*{{$rel.ForeignTable.NameGo}}{&b, &c, &d, &e}
for _, x := range foreigners { for _, x := range foreigners {
if err = randomize.Struct(seed, x, {{$foreignVarNameSingular}}DBTypes, false, {{$foreignVarNameSingular}}PrimaryKeyColumns...); err != nil { if err = randomize.Struct(seed, x, {{$foreignVarNameSingular}}DBTypes, false, {{$foreignVarNameSingular}}PrimaryKeyColumns...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
if err := a.Insert(tx); err != nil { if err := a.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
err = a.Add{{$rel.Function.Name}}(tx, true, foreigners...) err = a.Add{{$rel.Function.Name}}(tx, true, foreigners...)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
count, err := a.{{$rel.Function.Name}}(tx).Count() count, err := a.{{$rel.Function.Name}}(tx).Count()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if count != 4 { if count != 4 {
t.Error("count was wrong:", count) t.Error("count was wrong:", count)
} }
err = a.Remove{{$rel.Function.Name}}(tx, foreigners[:2]...) err = a.Remove{{$rel.Function.Name}}(tx, foreigners[:2]...)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
count, err = a.{{$rel.Function.Name}}(tx).Count() count, err = a.{{$rel.Function.Name}}(tx).Count()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if count != 2 { if count != 2 {
t.Error("count was wrong:", count) t.Error("count was wrong:", count)
} }
{{- if .ToJoinTable}} {{- if .ToJoinTable}}
if len(b.R.{{$rel.Function.ForeignName}}) != 0 { if len(b.R.{{$rel.Function.ForeignName}}) != 0 {
t.Error("relationship was not removed properly from the slice") t.Error("relationship was not removed properly from the slice")
} }
if len(c.R.{{$rel.Function.ForeignName}}) != 0 { if len(c.R.{{$rel.Function.ForeignName}}) != 0 {
t.Error("relationship was not removed properly from the slice") t.Error("relationship was not removed properly from the slice")
} }
if d.R.{{$rel.Function.ForeignName}}[0] != &a { if d.R.{{$rel.Function.ForeignName}}[0] != &a {
t.Error("relationship was not added properly to the foreign struct") t.Error("relationship was not added properly to the foreign struct")
} }
if e.R.{{$rel.Function.ForeignName}}[0] != &a { if e.R.{{$rel.Function.ForeignName}}[0] != &a {
t.Error("relationship was not added properly to the foreign struct") t.Error("relationship was not added properly to the foreign struct")
} }
{{- else}} {{- else}}
if b.{{$rel.ForeignTable.ColumnNameGo}}.Valid { if b.{{$rel.ForeignTable.ColumnNameGo}}.Valid {
t.Error("want b's foreign key value to be nil") t.Error("want b's foreign key value to be nil")
} }
if c.{{$rel.ForeignTable.ColumnNameGo}}.Valid { if c.{{$rel.ForeignTable.ColumnNameGo}}.Valid {
t.Error("want c's foreign key value to be nil") t.Error("want c's foreign key value to be nil")
} }
if b.R.{{$rel.Function.ForeignName}} != nil { if b.R.{{$rel.Function.ForeignName}} != nil {
t.Error("relationship was not removed properly from the foreign struct") t.Error("relationship was not removed properly from the foreign struct")
} }
if c.R.{{$rel.Function.ForeignName}} != nil { if c.R.{{$rel.Function.ForeignName}} != nil {
t.Error("relationship was not removed properly from the foreign struct") t.Error("relationship was not removed properly from the foreign struct")
} }
if d.R.{{$rel.Function.ForeignName}} != &a { if d.R.{{$rel.Function.ForeignName}} != &a {
t.Error("relationship to a should have been preserved") t.Error("relationship to a should have been preserved")
} }
if e.R.{{$rel.Function.ForeignName}} != &a { if e.R.{{$rel.Function.ForeignName}} != &a {
t.Error("relationship to a should have been preserved") t.Error("relationship to a should have been preserved")
} }
{{- end}} {{- end}}
if len(a.R.{{$rel.Function.Name}}) != 2 { if len(a.R.{{$rel.Function.Name}}) != 2 {
t.Error("should have preserved two relationships") t.Error("should have preserved two relationships")
} }
// Removal doesn't do a stable deletion for performance so we have to flip the order // Removal doesn't do a stable deletion for performance so we have to flip the order
if a.R.{{$rel.Function.Name}}[1] != &d { if a.R.{{$rel.Function.Name}}[1] != &d {
t.Error("relationship to d should have been preserved") t.Error("relationship to d should have been preserved")
} }
if a.R.{{$rel.Function.Name}}[0] != &e { if a.R.{{$rel.Function.Name}}[0] != &e {
t.Error("relationship to e should have been preserved") t.Error("relationship to e should have been preserved")
} }
} }
{{end -}} {{end -}}
{{- end -}}{{- /* if unique foreign key */ -}} {{- end -}}{{- /* if unique foreign key */ -}}

View file

@ -1,69 +1,69 @@
{{- define "relationship_to_one_test_helper"}} {{- define "relationship_to_one_test_helper"}}
func test{{.LocalTable.NameGo}}ToOne{{.ForeignTable.NameGo}}_{{.Function.Name}}(t *testing.T) { func test{{.LocalTable.NameGo}}ToOne{{.ForeignTable.NameGo}}_{{.Function.Name}}(t *testing.T) {
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
var foreign {{.ForeignTable.NameGo}} var foreign {{.ForeignTable.NameGo}}
var local {{.LocalTable.NameGo}} var local {{.LocalTable.NameGo}}
{{if .ForeignKey.Nullable -}} {{if .ForeignKey.Nullable -}}
local.{{.ForeignKey.Column | titleCase}}.Valid = true local.{{.ForeignKey.Column | titleCase}}.Valid = true
{{end}} {{end}}
{{- if .ForeignKey.ForeignColumnNullable -}} {{- if .ForeignKey.ForeignColumnNullable -}}
foreign.{{.ForeignKey.ForeignColumn | titleCase}}.Valid = true foreign.{{.ForeignKey.ForeignColumn | titleCase}}.Valid = true
{{end}} {{end}}
{{if not .Function.OneToOne -}} {{if not .Function.OneToOne -}}
if err := foreign.Insert(tx); err != nil { if err := foreign.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
local.{{.Function.LocalAssignment}} = foreign.{{.Function.ForeignAssignment}} local.{{.Function.LocalAssignment}} = foreign.{{.Function.ForeignAssignment}}
if err := local.Insert(tx); err != nil { if err := local.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
{{else -}} {{else -}}
if err := local.Insert(tx); err != nil { if err := local.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
foreign.{{.Function.ForeignAssignment}} = local.{{.Function.LocalAssignment}} foreign.{{.Function.ForeignAssignment}} = local.{{.Function.LocalAssignment}}
if err := foreign.Insert(tx); err != nil { if err := foreign.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
{{end -}} {{end -}}
check, err := local.{{.Function.Name}}(tx).One() check, err := local.{{.Function.Name}}(tx).One()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if check.{{.Function.ForeignAssignment}} != foreign.{{.Function.ForeignAssignment}} { if check.{{.Function.ForeignAssignment}} != foreign.{{.Function.ForeignAssignment}} {
t.Errorf("want: %v, got %v", foreign.{{.Function.ForeignAssignment}}, check.{{.Function.ForeignAssignment}}) t.Errorf("want: %v, got %v", foreign.{{.Function.ForeignAssignment}}, check.{{.Function.ForeignAssignment}})
} }
slice := {{.LocalTable.NameGo}}Slice{&local} slice := {{.LocalTable.NameGo}}Slice{&local}
if err = local.L.Load{{.Function.Name}}(tx, false, &slice); err != nil { if err = local.L.Load{{.Function.Name}}(tx, false, &slice); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if local.R.{{.Function.Name}} == nil { if local.R.{{.Function.Name}} == nil {
t.Error("struct should have been eager loaded") t.Error("struct should have been eager loaded")
} }
local.R.{{.Function.Name}} = nil local.R.{{.Function.Name}} = nil
if err = local.L.Load{{.Function.Name}}(tx, true, &local); err != nil { if err = local.L.Load{{.Function.Name}}(tx, true, &local); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if local.R.{{.Function.Name}} == nil { if local.R.{{.Function.Name}} == nil {
t.Error("struct should have been eager loaded") t.Error("struct should have been eager loaded")
} }
} }
{{end -}} {{end -}}
{{- if .Table.IsJoinTable -}} {{- if .Table.IsJoinTable -}}
{{- else -}} {{- else -}}
{{- $dot := . -}} {{- $dot := . -}}
{{- range .Table.FKeys -}} {{- range .Table.FKeys -}}
{{- $rel := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table . -}} {{- $rel := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table . -}}
{{- template "relationship_to_one_test_helper" $rel -}} {{- template "relationship_to_one_test_helper" $rel -}}
{{end -}} {{end -}}
{{- end -}} {{- end -}}

View file

@ -2,131 +2,131 @@
{{- $varNameSingular := .ForeignKey.Table | singular | camelCase -}} {{- $varNameSingular := .ForeignKey.Table | singular | camelCase -}}
{{- $foreignVarNameSingular := .ForeignKey.ForeignTable | singular | camelCase -}} {{- $foreignVarNameSingular := .ForeignKey.ForeignTable | singular | camelCase -}}
func test{{.LocalTable.NameGo}}ToOneSetOp{{.ForeignTable.NameGo}}_{{.Function.Name}}(t *testing.T) { func test{{.LocalTable.NameGo}}ToOneSetOp{{.ForeignTable.NameGo}}_{{.Function.Name}}(t *testing.T) {
var err error var err error
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
var a {{.LocalTable.NameGo}} var a {{.LocalTable.NameGo}}
var b, c {{.ForeignTable.NameGo}} var b, c {{.ForeignTable.NameGo}}
seed := randomize.NewSeed() seed := randomize.NewSeed()
if err = randomize.Struct(seed, &a, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}PrimaryKeyColumns...); err != nil { if err = randomize.Struct(seed, &a, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}PrimaryKeyColumns...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err = randomize.Struct(seed, &b, {{$foreignVarNameSingular}}DBTypes, false, {{$foreignVarNameSingular}}PrimaryKeyColumns...); err != nil { if err = randomize.Struct(seed, &b, {{$foreignVarNameSingular}}DBTypes, false, {{$foreignVarNameSingular}}PrimaryKeyColumns...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err = randomize.Struct(seed, &c, {{$foreignVarNameSingular}}DBTypes, false, {{$foreignVarNameSingular}}PrimaryKeyColumns...); err != nil { if err = randomize.Struct(seed, &c, {{$foreignVarNameSingular}}DBTypes, false, {{$foreignVarNameSingular}}PrimaryKeyColumns...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := a.Insert(tx); err != nil { if err := a.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err = b.Insert(tx); err != nil { if err = b.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
for i, x := range []*{{.ForeignTable.NameGo}}{&b, &c} { for i, x := range []*{{.ForeignTable.NameGo}}{&b, &c} {
err = a.Set{{.Function.Name}}(tx, i != 0, x) err = a.Set{{.Function.Name}}(tx, i != 0, x)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if a.{{.Function.LocalAssignment}} != x.{{.Function.ForeignAssignment}} { if a.{{.Function.LocalAssignment}} != x.{{.Function.ForeignAssignment}} {
t.Error("foreign key was wrong value", a.{{.Function.LocalAssignment}}) t.Error("foreign key was wrong value", a.{{.Function.LocalAssignment}})
} }
if a.R.{{.Function.Name}} != x { if a.R.{{.Function.Name}} != x {
t.Error("relationship struct not set to correct value") t.Error("relationship struct not set to correct value")
} }
zero := reflect.Zero(reflect.TypeOf(a.{{.Function.LocalAssignment}})) zero := reflect.Zero(reflect.TypeOf(a.{{.Function.LocalAssignment}}))
reflect.Indirect(reflect.ValueOf(&a.{{.Function.LocalAssignment}})).Set(zero) reflect.Indirect(reflect.ValueOf(&a.{{.Function.LocalAssignment}})).Set(zero)
if err = a.Reload(tx); err != nil { if err = a.Reload(tx); err != nil {
t.Fatal("failed to reload", err) t.Fatal("failed to reload", err)
} }
if a.{{.Function.LocalAssignment}} != x.{{.Function.ForeignAssignment}} { if a.{{.Function.LocalAssignment}} != x.{{.Function.ForeignAssignment}} {
t.Error("foreign key was wrong value", a.{{.Function.LocalAssignment}}, x.{{.Function.ForeignAssignment}}) t.Error("foreign key was wrong value", a.{{.Function.LocalAssignment}}, x.{{.Function.ForeignAssignment}})
} }
{{if .ForeignKey.Unique -}} {{if .ForeignKey.Unique -}}
if x.R.{{.Function.ForeignName}} != &a { if x.R.{{.Function.ForeignName}} != &a {
t.Error("failed to append to foreign relationship struct") t.Error("failed to append to foreign relationship struct")
} }
{{else -}} {{else -}}
if x.R.{{.Function.ForeignName}}[0] != &a { if x.R.{{.Function.ForeignName}}[0] != &a {
t.Error("failed to append to foreign relationship struct") t.Error("failed to append to foreign relationship struct")
} }
{{end -}} {{end -}}
} }
} }
{{- if .ForeignKey.Nullable}} {{- if .ForeignKey.Nullable}}
func test{{.LocalTable.NameGo}}ToOneRemoveOp{{.ForeignTable.NameGo}}_{{.Function.Name}}(t *testing.T) { func test{{.LocalTable.NameGo}}ToOneRemoveOp{{.ForeignTable.NameGo}}_{{.Function.Name}}(t *testing.T) {
var err error var err error
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
var a {{.LocalTable.NameGo}} var a {{.LocalTable.NameGo}}
var b {{.ForeignTable.NameGo}} var b {{.ForeignTable.NameGo}}
seed := randomize.NewSeed() seed := randomize.NewSeed()
if err = randomize.Struct(seed, &a, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}PrimaryKeyColumns...); err != nil { if err = randomize.Struct(seed, &a, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}PrimaryKeyColumns...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err = randomize.Struct(seed, &b, {{$foreignVarNameSingular}}DBTypes, false, {{$foreignVarNameSingular}}PrimaryKeyColumns...); err != nil { if err = randomize.Struct(seed, &b, {{$foreignVarNameSingular}}DBTypes, false, {{$foreignVarNameSingular}}PrimaryKeyColumns...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err = a.Insert(tx); err != nil { if err = a.Insert(tx); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err = a.Set{{.Function.Name}}(tx, true, &b); err != nil { if err = a.Set{{.Function.Name}}(tx, true, &b); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err = a.Remove{{.Function.Name}}(tx, &b); err != nil { if err = a.Remove{{.Function.Name}}(tx, &b); err != nil {
t.Error("failed to remove relationship") t.Error("failed to remove relationship")
} }
count, err := a.{{.Function.Name}}(tx).Count() count, err := a.{{.Function.Name}}(tx).Count()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if count != 0 { if count != 0 {
t.Error("want no relationships remaining") t.Error("want no relationships remaining")
} }
if a.R.{{.Function.Name}} != nil { if a.R.{{.Function.Name}} != nil {
t.Error("R struct entry should be nil") t.Error("R struct entry should be nil")
} }
if a.{{.LocalTable.ColumnNameGo}}.Valid { if a.{{.LocalTable.ColumnNameGo}}.Valid {
t.Error("R struct entry should be nil") t.Error("R struct entry should be nil")
} }
{{if .ForeignKey.Unique -}} {{if .ForeignKey.Unique -}}
if b.R.{{.Function.ForeignName}} != nil { if b.R.{{.Function.ForeignName}} != nil {
t.Error("failed to remove a from b's relationships") t.Error("failed to remove a from b's relationships")
} }
{{else -}} {{else -}}
if len(b.R.{{.Function.ForeignName}}) != 0 { if len(b.R.{{.Function.ForeignName}}) != 0 {
t.Error("failed to remove a from b's relationships") t.Error("failed to remove a from b's relationships")
} }
{{end -}} {{end -}}
} }
{{end -}} {{end -}}
{{- end -}} {{- end -}}
{{- if .Table.IsJoinTable -}} {{- if .Table.IsJoinTable -}}
{{- else -}} {{- else -}}
{{- $dot := . -}} {{- $dot := . -}}
{{- range .Table.FKeys -}} {{- range .Table.FKeys -}}
{{- $rel := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table .}} {{- $rel := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table .}}
{{template "relationship_to_one_setops_test_helper" $rel -}} {{template "relationship_to_one_setops_test_helper" $rel -}}
{{- end -}} {{- end -}}

View file

@ -3,45 +3,45 @@
{{- $varNamePlural := .Table.Name | plural | camelCase -}} {{- $varNamePlural := .Table.Name | plural | camelCase -}}
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
func test{{$tableNamePlural}}Reload(t *testing.T) { func test{{$tableNamePlural}}Reload(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}} := &{{$tableNameSingular}}{} {{$varNameSingular}} := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Insert(tx); err != nil { if err = {{$varNameSingular}}.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
if err = {{$varNameSingular}}.Reload(tx); err != nil { if err = {{$varNameSingular}}.Reload(tx); err != nil {
t.Error(err) t.Error(err)
} }
} }
func test{{$tableNamePlural}}ReloadAll(t *testing.T) { func test{{$tableNamePlural}}ReloadAll(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}} := &{{$tableNameSingular}}{} {{$varNameSingular}} := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Insert(tx); err != nil { if err = {{$varNameSingular}}.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
slice := {{$tableNameSingular}}Slice{{"{"}}{{$varNameSingular}}{{"}"}} slice := {{$tableNameSingular}}Slice{{"{"}}{{$varNameSingular}}{{"}"}}
if err = slice.ReloadAll(tx); err != nil { if err = slice.ReloadAll(tx); err != nil {
t.Error(err) t.Error(err)
} }
} }

View file

@ -3,27 +3,27 @@
{{- $varNamePlural := .Table.Name | plural | camelCase -}} {{- $varNamePlural := .Table.Name | plural | camelCase -}}
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
func test{{$tableNamePlural}}Select(t *testing.T) { func test{{$tableNamePlural}}Select(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}} := &{{$tableNameSingular}}{} {{$varNameSingular}} := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}ColumnsWithDefault...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Insert(tx); err != nil { if err = {{$varNameSingular}}.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
slice, err := {{$tableNamePlural}}(tx).All() slice, err := {{$tableNamePlural}}(tx).All()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if len(slice) != 1 { if len(slice) != 1 {
t.Error("want one record, got:", len(slice)) t.Error("want one record, got:", len(slice))
} }
} }

View file

@ -3,97 +3,97 @@
{{- $varNamePlural := .Table.Name | plural | camelCase -}} {{- $varNamePlural := .Table.Name | plural | camelCase -}}
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
func test{{$tableNamePlural}}Update(t *testing.T) { func test{{$tableNamePlural}}Update(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}} := &{{$tableNameSingular}}{} {{$varNameSingular}} := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Insert(tx); err != nil { if err = {{$varNameSingular}}.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
count, err := {{$tableNamePlural}}(tx).Count() count, err := {{$tableNamePlural}}(tx).Count()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if count != 1 { if count != 1 {
t.Error("want one record, got:", count) t.Error("want one record, got:", count)
} }
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}PrimaryKeyColumns...); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}PrimaryKeyColumns...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
// If table only contains primary key columns, we need to pass // If table only contains primary key columns, we need to pass
// them into a whitelist to get a valid test result, // them into a whitelist to get a valid test result,
// otherwise the Update method will error because it will not be able to // otherwise the Update method will error because it will not be able to
// generate a whitelist (due to it excluding primary key columns). // generate a whitelist (due to it excluding primary key columns).
if strmangle.StringSliceMatch({{$varNameSingular}}Columns, {{$varNameSingular}}PrimaryKeyColumns) { if strmangle.StringSliceMatch({{$varNameSingular}}Columns, {{$varNameSingular}}PrimaryKeyColumns) {
if err = {{$varNameSingular}}.Update(tx, {{$varNameSingular}}PrimaryKeyColumns...); err != nil { if err = {{$varNameSingular}}.Update(tx, {{$varNameSingular}}PrimaryKeyColumns...); err != nil {
t.Error(err) t.Error(err)
} }
} else { } else {
if err = {{$varNameSingular}}.Update(tx); err != nil { if err = {{$varNameSingular}}.Update(tx); err != nil {
t.Error(err) t.Error(err)
} }
} }
} }
func test{{$tableNamePlural}}SliceUpdateAll(t *testing.T) { func test{{$tableNamePlural}}SliceUpdateAll(t *testing.T) {
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
{{$varNameSingular}} := &{{$tableNameSingular}}{} {{$varNameSingular}} := &{{$tableNameSingular}}{}
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Insert(tx); err != nil { if err = {{$varNameSingular}}.Insert(tx); err != nil {
t.Error(err) t.Error(err)
} }
count, err := {{$tableNamePlural}}(tx).Count() count, err := {{$tableNamePlural}}(tx).Count()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if count != 1 { if count != 1 {
t.Error("want one record, got:", count) t.Error("want one record, got:", count)
} }
if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}PrimaryKeyColumns...); err != nil { if err = randomize.Struct(seed, {{$varNameSingular}}, {{$varNameSingular}}DBTypes, true, {{$varNameSingular}}PrimaryKeyColumns...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
// Remove Primary keys and unique columns from what we plan to update // Remove Primary keys and unique columns from what we plan to update
var fields []string var fields []string
if strmangle.StringSliceMatch({{$varNameSingular}}Columns, {{$varNameSingular}}PrimaryKeyColumns) { if strmangle.StringSliceMatch({{$varNameSingular}}Columns, {{$varNameSingular}}PrimaryKeyColumns) {
fields = {{$varNameSingular}}Columns fields = {{$varNameSingular}}Columns
} else { } else {
fields = strmangle.SetComplement( fields = strmangle.SetComplement(
{{$varNameSingular}}Columns, {{$varNameSingular}}Columns,
{{$varNameSingular}}PrimaryKeyColumns, {{$varNameSingular}}PrimaryKeyColumns,
) )
} }
value := reflect.Indirect(reflect.ValueOf({{$varNameSingular}})) value := reflect.Indirect(reflect.ValueOf({{$varNameSingular}}))
updateMap := M{} updateMap := M{}
for _, col := range fields { for _, col := range fields {
updateMap[col] = value.FieldByName(strmangle.TitleCase(col)).Interface() updateMap[col] = value.FieldByName(strmangle.TitleCase(col)).Interface()
} }
slice := {{$tableNameSingular}}Slice{{"{"}}{{$varNameSingular}}{{"}"}} slice := {{$tableNameSingular}}Slice{{"{"}}{{$varNameSingular}}{{"}"}}
if err = slice.UpdateAll(tx, updateMap); err != nil { if err = slice.UpdateAll(tx, updateMap); err != nil {
t.Error(err) t.Error(err)
} }
} }

View file

@ -3,47 +3,47 @@
{{- $varNamePlural := .Table.Name | plural | camelCase -}} {{- $varNamePlural := .Table.Name | plural | camelCase -}}
{{- $varNameSingular := .Table.Name | singular | camelCase -}} {{- $varNameSingular := .Table.Name | singular | camelCase -}}
func test{{$tableNamePlural}}Upsert(t *testing.T) { func test{{$tableNamePlural}}Upsert(t *testing.T) {
{{if not (eq .DriverName "postgres") -}} {{if not (eq .DriverName "postgres") -}}
t.Skip("not implemented for {{.DriverName}}") t.Skip("not implemented for {{.DriverName}}")
{{end -}} {{end -}}
t.Parallel() t.Parallel()
seed := randomize.NewSeed() seed := randomize.NewSeed()
var err error var err error
// Attempt the INSERT side of an UPSERT // Attempt the INSERT side of an UPSERT
{{$varNameSingular}} := {{$tableNameSingular}}{} {{$varNameSingular}} := {{$tableNameSingular}}{}
if err = randomize.Struct(seed, &{{$varNameSingular}}, {{$varNameSingular}}DBTypes, true); err != nil { if err = randomize.Struct(seed, &{{$varNameSingular}}, {{$varNameSingular}}DBTypes, true); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
tx := MustTx(boil.Begin()) tx := MustTx(boil.Begin())
defer tx.Rollback() defer tx.Rollback()
if err = {{$varNameSingular}}.Upsert(tx, false, nil, nil); err != nil { if err = {{$varNameSingular}}.Upsert(tx, {{if eq .DriverName "postgres"}}false, nil, {{end}}nil); err != nil {
t.Errorf("Unable to upsert {{$tableNameSingular}}: %s", err) t.Errorf("Unable to upsert {{$tableNameSingular}}: %s", err)
} }
count, err := {{$tableNamePlural}}(tx).Count() count, err := {{$tableNamePlural}}(tx).Count()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if count != 1 { if count != 1 {
t.Error("want one record, got:", count) t.Error("want one record, got:", count)
} }
// Attempt the UPDATE side of an UPSERT // Attempt the UPDATE side of an UPSERT
if err = randomize.Struct(seed, &{{$varNameSingular}}, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}PrimaryKeyColumns...); err != nil { if err = randomize.Struct(seed, &{{$varNameSingular}}, {{$varNameSingular}}DBTypes, false, {{$varNameSingular}}PrimaryKeyColumns...); err != nil {
t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err) t.Errorf("Unable to randomize {{$tableNameSingular}} struct: %s", err)
} }
if err = {{$varNameSingular}}.Upsert(tx, true, nil, nil); err != nil { if err = {{$varNameSingular}}.Upsert(tx, {{if eq .DriverName "postgres"}}true, nil, {{end}}nil); err != nil {
t.Errorf("Unable to upsert {{$tableNameSingular}}: %s", err) t.Errorf("Unable to upsert {{$tableNameSingular}}: %s", err)
} }
count, err = {{$tableNamePlural}}(tx).Count() count, err = {{$tableNamePlural}}(tx).Count()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
if count != 1 { if count != 1 {
t.Error("want one record, got:", count) t.Error("want one record, got:", count)
} }
} }