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")
```
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.
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 (
"fmt"
"regexp"
"strings"
)
var rgxAutoIncColumn = regexp.MustCompile(`^nextval\(.*\)`)
@ -79,3 +80,30 @@ func SQLColDefinitions(cols []Column, names []string) SQLColumnDefs {
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
}
// BuildUpsertQuery builds a SQL statement string using the upsertData provided.
func BuildUpsertQuery(dia Dialect, tableName string, updateOnConflict bool, ret, update, conflict, whitelist []string) string {
// BuildUpsertQueryMySQL builds a SQL statement string using the upsertData provided.
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)
whitelist = strmangle.IdentQuoteSlice(dia.LQ, dia.RQ, whitelist)
ret = strmangle.IdentQuoteSlice(dia.LQ, dia.RQ, ret)

View file

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

View file

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

View file

@ -3,31 +3,31 @@
{{- $varNameSingular := .Table.Name | singular | camelCase -}}
{{- $tableNameSingular := .Table.Name | singular | titleCase -}}
var (
{{$varNameSingular}}Columns = []string{{"{"}}{{.Table.Columns | 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}}PrimaryKeyColumns = []string{{"{"}}{{.Table.PKey.Columns | 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}}ColumnsWithDefault = []string{{"{"}}{{.Table.Columns | filterColumnsByDefault true | columnNames | stringMap .StringFuncs.quoteWrap | join ","}}{{"}"}}
{{$varNameSingular}}PrimaryKeyColumns = []string{{"{"}}{{.Table.PKey.Columns | stringMap .StringFuncs.quoteWrap | join ", "}}{{"}"}}
)
type (
{{$tableNameSingular}}Slice []*{{$tableNameSingular}}
{{if eq .NoHooks false -}}
{{$tableNameSingular}}Hook func(boil.Executor, *{{$tableNameSingular}}) error
{{- end}}
{{$tableNameSingular}}Slice []*{{$tableNameSingular}}
{{if eq .NoHooks false -}}
{{$tableNameSingular}}Hook func(boil.Executor, *{{$tableNameSingular}}) error
{{- end}}
{{$varNameSingular}}Query struct {
*boil.Query
}
{{$varNameSingular}}Query struct {
*boil.Query
}
)
// Cache for insert and update
var (
{{$varNameSingular}}Type = reflect.TypeOf(&{{$tableNameSingular}}{})
{{$varNameSingular}}Mapping = boil.MakeStructMapping({{$varNameSingular}}Type)
{{$varNameSingular}}InsertCacheMut sync.RWMutex
{{$varNameSingular}}InsertCache = make(map[string]insertCache)
{{$varNameSingular}}UpdateCacheMut sync.RWMutex
{{$varNameSingular}}UpdateCache = make(map[string]updateCache)
{{$varNameSingular}}Type = reflect.TypeOf(&{{$tableNameSingular}}{})
{{$varNameSingular}}Mapping = boil.MakeStructMapping({{$varNameSingular}}Type)
{{$varNameSingular}}InsertCacheMut sync.RWMutex
{{$varNameSingular}}InsertCache = make(map[string]insertCache)
{{$varNameSingular}}UpdateCacheMut sync.RWMutex
{{$varNameSingular}}UpdateCache = make(map[string]updateCache)
)
// 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.
func (o *{{$tableNameSingular}}) doBeforeInsertHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}BeforeInsertHooks {
if err := hook(exec, o); err != nil {
return err
}
}
for _, hook := range {{$varNameSingular}}BeforeInsertHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
return nil
}
// doBeforeUpdateHooks executes all "before Update" hooks.
func (o *{{$tableNameSingular}}) doBeforeUpdateHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}BeforeUpdateHooks {
if err := hook(exec, o); err != nil {
return err
}
}
for _, hook := range {{$varNameSingular}}BeforeUpdateHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
return nil
}
// doBeforeDeleteHooks executes all "before Delete" hooks.
func (o *{{$tableNameSingular}}) doBeforeDeleteHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}BeforeDeleteHooks {
if err := hook(exec, o); err != nil {
return err
}
}
for _, hook := range {{$varNameSingular}}BeforeDeleteHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
return nil
}
// doBeforeUpsertHooks executes all "before Upsert" hooks.
func (o *{{$tableNameSingular}}) doBeforeUpsertHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}BeforeUpsertHooks {
if err := hook(exec, o); err != nil {
return err
}
}
for _, hook := range {{$varNameSingular}}BeforeUpsertHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
return nil
}
// doAfterInsertHooks executes all "after Insert" hooks.
func (o *{{$tableNameSingular}}) doAfterInsertHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}AfterInsertHooks {
if err := hook(exec, o); err != nil {
return err
}
}
for _, hook := range {{$varNameSingular}}AfterInsertHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
return nil
}
// doAfterSelectHooks executes all "after Select" hooks.
func (o *{{$tableNameSingular}}) doAfterSelectHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}AfterSelectHooks {
if err := hook(exec, o); err != nil {
return err
}
}
for _, hook := range {{$varNameSingular}}AfterSelectHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
return nil
}
// doAfterUpdateHooks executes all "after Update" hooks.
func (o *{{$tableNameSingular}}) doAfterUpdateHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}AfterUpdateHooks {
if err := hook(exec, o); err != nil {
return err
}
}
for _, hook := range {{$varNameSingular}}AfterUpdateHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
return nil
}
// doAfterDeleteHooks executes all "after Delete" hooks.
func (o *{{$tableNameSingular}}) doAfterDeleteHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}AfterDeleteHooks {
if err := hook(exec, o); err != nil {
return err
}
}
for _, hook := range {{$varNameSingular}}AfterDeleteHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
return nil
}
// doAfterUpsertHooks executes all "after Upsert" hooks.
func (o *{{$tableNameSingular}}) doAfterUpsertHooks(exec boil.Executor) (err error) {
for _, hook := range {{$varNameSingular}}AfterUpsertHooks {
if err := hook(exec, o); err != nil {
return err
}
}
for _, hook := range {{$varNameSingular}}AfterUpsertHooks {
if err := hook(exec, o); err != nil {
return err
}
}
return nil
return nil
}
func Add{{$tableNameSingular}}Hook(hookPoint boil.HookPoint, {{$varNameSingular}}Hook {{$tableNameSingular}}Hook) {
switch hookPoint {
case boil.BeforeInsertHook:
{{$varNameSingular}}BeforeInsertHooks = append({{$varNameSingular}}BeforeInsertHooks, {{$varNameSingular}}Hook)
case boil.BeforeUpdateHook:
{{$varNameSingular}}BeforeUpdateHooks = append({{$varNameSingular}}BeforeUpdateHooks, {{$varNameSingular}}Hook)
case boil.BeforeDeleteHook:
{{$varNameSingular}}BeforeDeleteHooks = append({{$varNameSingular}}BeforeDeleteHooks, {{$varNameSingular}}Hook)
case boil.BeforeUpsertHook:
{{$varNameSingular}}BeforeUpsertHooks = append({{$varNameSingular}}BeforeUpsertHooks, {{$varNameSingular}}Hook)
case boil.AfterInsertHook:
{{$varNameSingular}}AfterInsertHooks = append({{$varNameSingular}}AfterInsertHooks, {{$varNameSingular}}Hook)
case boil.AfterSelectHook:
{{$varNameSingular}}AfterSelectHooks = append({{$varNameSingular}}AfterSelectHooks, {{$varNameSingular}}Hook)
case boil.AfterUpdateHook:
{{$varNameSingular}}AfterUpdateHooks = append({{$varNameSingular}}AfterUpdateHooks, {{$varNameSingular}}Hook)
case boil.AfterDeleteHook:
{{$varNameSingular}}AfterDeleteHooks = append({{$varNameSingular}}AfterDeleteHooks, {{$varNameSingular}}Hook)
case boil.AfterUpsertHook:
{{$varNameSingular}}AfterUpsertHooks = append({{$varNameSingular}}AfterUpsertHooks, {{$varNameSingular}}Hook)
}
switch hookPoint {
case boil.BeforeInsertHook:
{{$varNameSingular}}BeforeInsertHooks = append({{$varNameSingular}}BeforeInsertHooks, {{$varNameSingular}}Hook)
case boil.BeforeUpdateHook:
{{$varNameSingular}}BeforeUpdateHooks = append({{$varNameSingular}}BeforeUpdateHooks, {{$varNameSingular}}Hook)
case boil.BeforeDeleteHook:
{{$varNameSingular}}BeforeDeleteHooks = append({{$varNameSingular}}BeforeDeleteHooks, {{$varNameSingular}}Hook)
case boil.BeforeUpsertHook:
{{$varNameSingular}}BeforeUpsertHooks = append({{$varNameSingular}}BeforeUpsertHooks, {{$varNameSingular}}Hook)
case boil.AfterInsertHook:
{{$varNameSingular}}AfterInsertHooks = append({{$varNameSingular}}AfterInsertHooks, {{$varNameSingular}}Hook)
case boil.AfterSelectHook:
{{$varNameSingular}}AfterSelectHooks = append({{$varNameSingular}}AfterSelectHooks, {{$varNameSingular}}Hook)
case boil.AfterUpdateHook:
{{$varNameSingular}}AfterUpdateHooks = append({{$varNameSingular}}AfterUpdateHooks, {{$varNameSingular}}Hook)
case boil.AfterDeleteHook:
{{$varNameSingular}}AfterDeleteHooks = append({{$varNameSingular}}AfterDeleteHooks, {{$varNameSingular}}Hook)
case boil.AfterUpsertHook:
{{$varNameSingular}}AfterUpsertHooks = append({{$varNameSingular}}AfterUpsertHooks, {{$varNameSingular}}Hook)
}
}
{{- end}}

View file

@ -2,115 +2,115 @@
{{- $varNameSingular := .Table.Name | singular | camelCase -}}
// OneP returns a single {{$varNameSingular}} record from the query, and panics on error.
func (q {{$varNameSingular}}Query) OneP() (*{{$tableNameSingular}}) {
o, err := q.One()
if err != nil {
panic(boil.WrapErr(err))
}
o, err := q.One()
if err != nil {
panic(boil.WrapErr(err))
}
return o
return o
}
// One returns a single {{$varNameSingular}} record from the query.
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)
if err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, sql.ErrNoRows
}
return nil, errors.Wrap(err, "{{.PkgName}}: failed to execute a one query for {{.Table.Name}}")
}
err := q.Bind(o)
if err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, sql.ErrNoRows
}
return nil, errors.Wrap(err, "{{.PkgName}}: failed to execute a one query for {{.Table.Name}}")
}
{{if not .NoHooks -}}
if err := o.doAfterSelectHooks(boil.GetExecutor(q.Query)); err != nil {
return o, err
}
{{- end}}
{{if not .NoHooks -}}
if err := o.doAfterSelectHooks(boil.GetExecutor(q.Query)); err != nil {
return o, err
}
{{- end}}
return o, nil
return o, nil
}
// AllP returns all {{$tableNameSingular}} records from the query, and panics on error.
func (q {{$varNameSingular}}Query) AllP() {{$tableNameSingular}}Slice {
o, err := q.All()
if err != nil {
panic(boil.WrapErr(err))
}
o, err := q.All()
if err != nil {
panic(boil.WrapErr(err))
}
return o
return o
}
// All returns all {{$tableNameSingular}} records from the query.
func (q {{$varNameSingular}}Query) All() ({{$tableNameSingular}}Slice, error) {
var o {{$tableNameSingular}}Slice
var o {{$tableNameSingular}}Slice
err := q.Bind(&o)
if err != nil {
return nil, errors.Wrap(err, "{{.PkgName}}: failed to assign all query results to {{$tableNameSingular}} slice")
}
err := q.Bind(&o)
if err != nil {
return nil, errors.Wrap(err, "{{.PkgName}}: failed to assign all query results to {{$tableNameSingular}} slice")
}
{{if not .NoHooks -}}
if len({{$varNameSingular}}AfterSelectHooks) != 0 {
for _, obj := range o {
if err := obj.doAfterSelectHooks(boil.GetExecutor(q.Query)); err != nil {
return o, err
}
}
}
{{- end}}
{{if not .NoHooks -}}
if len({{$varNameSingular}}AfterSelectHooks) != 0 {
for _, obj := range o {
if err := obj.doAfterSelectHooks(boil.GetExecutor(q.Query)); err != nil {
return o, err
}
}
}
{{- end}}
return o, nil
return o, nil
}
// CountP returns the count of all {{$tableNameSingular}} records in the query, and panics on error.
func (q {{$varNameSingular}}Query) CountP() int64 {
c, err := q.Count()
if err != nil {
panic(boil.WrapErr(err))
}
c, err := q.Count()
if err != nil {
panic(boil.WrapErr(err))
}
return c
return c
}
// Count returns the count of all {{$tableNameSingular}} records in the query.
func (q {{$varNameSingular}}Query) Count() (int64, error) {
var count int64
var count int64
boil.SetSelect(q.Query, nil)
boil.SetCount(q.Query)
boil.SetSelect(q.Query, nil)
boil.SetCount(q.Query)
err := q.Query.ExecQueryOne().Scan(&count)
if err != nil {
return 0, errors.Wrap(err, "{{.PkgName}}: failed to count {{.Table.Name}} rows")
}
err := q.Query.ExecQueryOne().Scan(&count)
if err != nil {
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.
func (q {{$varNameSingular}}Query) ExistsP() bool {
e, err := q.Exists()
if err != nil {
panic(boil.WrapErr(err))
}
e, err := q.Exists()
if err != nil {
panic(boil.WrapErr(err))
}
return e
return e
}
// Exists checks if the row exists in the table.
func (q {{$varNameSingular}}Query) Exists() (bool, error) {
var count int64
var count int64
boil.SetCount(q.Query)
boil.SetLimit(q.Query, 1)
boil.SetCount(q.Query)
boil.SetLimit(q.Query, 1)
err := q.Query.ExecQueryOne().Scan(&count)
if err != nil {
return false, errors.Wrap(err, "{{.PkgName}}: failed to check if {{.Table.Name}} exists")
}
err := q.Query.ExecQueryOne().Scan(&count)
if err != nil {
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" -}}
{{- $dot := .Dot -}}{{/* .Dot holds the root templateData struct, passed in through preserveDot */}}
{{- with .Rel -}}{{/* Rel holds the text helper data, passed in through preserveDot */}}
{{- $varNameSingular := .ForeignKey.ForeignTable | singular | camelCase -}}
{{- $dot := .Dot -}}{{/* .Dot holds the root templateData struct, passed in through preserveDot */}}
{{- with .Rel -}}{{/* Rel holds the text helper data, passed in through preserveDot */}}
{{- $varNameSingular := .ForeignKey.ForeignTable | singular | camelCase -}}
// {{.Function.Name}}G pointed to by the foreign key.
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.
func ({{.Function.Receiver}} *{{.LocalTable.NameGo}}) {{.Function.Name}}(exec boil.Executor, mods ...qm.QueryMod) ({{$varNameSingular}}Query) {
queryMods := []qm.QueryMod{
qm.Where("{{.ForeignTable.ColumnName}}={{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}}", {{.Function.Receiver}}.{{.LocalTable.ColumnNameGo}}),
}
queryMods := []qm.QueryMod{
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...)
boil.SetFrom(query.Query, "{{.ForeignTable.Name | $dot.SchemaTable}}")
query := {{.ForeignTable.NamePluralGo}}(exec, queryMods...)
boil.SetFrom(query.Query, "{{.ForeignTable.Name | $dot.SchemaTable}}")
return query
return query
}
{{- end -}}{{/* end with */}}
{{- end -}}{{/* end with */}}
{{end -}}{{/* end define */}}
{{- /* Begin execution of template for one-to-one relationship */ -}}
{{- if .Table.IsJoinTable -}}
{{- else -}}
{{- $dot := . -}}
{{- range .Table.FKeys -}}
{{- $txt := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table . -}}
{{- $dot := . -}}
{{- range .Table.FKeys -}}
{{- $txt := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table . -}}
{{- template "relationship_to_one_helper" (preserveDot $dot $txt) -}}
{{- end -}}
{{- end -}}

View file

@ -1,49 +1,49 @@
{{- /* Begin execution of template for many-to-one or many-to-many relationship helper */ -}}
{{- if .Table.IsJoinTable -}}
{{- else -}}
{{- $dot := . -}}
{{- $table := .Table -}}
{{- range .Table.ToManyRelationships -}}
{{- $varNameSingular := .ForeignTable | singular | camelCase -}}
{{- if (and .ForeignColumnUnique (not .ToJoinTable)) -}}
{{- /* Begin execution of template for many-to-one relationship. */ -}}
{{- $txt := textsFromOneToOneRelationship $dot.PkgName $dot.Tables $table . -}}
{{- template "relationship_to_one_helper" (preserveDot $dot $txt) -}}
{{- else -}}
{{- /* Begin execution of template for many-to-many relationship. */ -}}
{{- $rel := textsFromRelationship $dot.Tables $table . -}}
{{- $schemaForeignTable := .ForeignTable | $dot.SchemaTable -}}
{{- $dot := . -}}
{{- $table := .Table -}}
{{- range .Table.ToManyRelationships -}}
{{- $varNameSingular := .ForeignTable | singular | camelCase -}}
{{- if (and .ForeignColumnUnique (not .ToJoinTable)) -}}
{{- /* Begin execution of template for many-to-one relationship. */ -}}
{{- $txt := textsFromOneToOneRelationship $dot.PkgName $dot.Tables $table . -}}
{{- template "relationship_to_one_helper" (preserveDot $dot $txt) -}}
{{- else -}}
{{- /* Begin execution of template for many-to-many relationship. */ -}}
{{- $rel := textsFromRelationship $dot.Tables $table . -}}
{{- $schemaForeignTable := .ForeignTable | $dot.SchemaTable -}}
// {{$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}}.
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
{{- 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 {
queryMods := []qm.QueryMod{
qm.Select("{{id 0 | $dot.Quotes}}.*"),
}
queryMods := []qm.QueryMod{
qm.Select("{{id 0 | $dot.Quotes}}.*"),
}
if len(mods) != 0 {
queryMods = append(queryMods, mods...)
}
if len(mods) != 0 {
queryMods = append(queryMods, mods...)
}
{{if .ToJoinTable -}}
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.Where("{{id 1 | $dot.Quotes}}.{{.JoinLocalColumn | $dot.Quotes}}={{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}}", {{$rel.Function.Receiver}}.{{$rel.LocalTable.ColumnNameGo}}),
)
{{else -}}
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}}),
)
{{end}}
{{if .ToJoinTable -}}
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.Where("{{id 1 | $dot.Quotes}}.{{.JoinLocalColumn | $dot.Quotes}}={{if $dot.Dialect.IndexPlaceholders}}$1{{else}}?{{end}}", {{$rel.Function.Receiver}}.{{$rel.LocalTable.ColumnNameGo}}),
)
{{else -}}
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}}),
)
{{end}}
query := {{$rel.ForeignTable.NamePluralGo}}(exec, queryMods...)
boil.SetFrom(query.Query, "{{$schemaForeignTable}} as {{id 0 | $dot.Quotes}}")
return query
query := {{$rel.ForeignTable.NamePluralGo}}(exec, queryMods...)
boil.SetFrom(query.Query, "{{$schemaForeignTable}} as {{id 0 | $dot.Quotes}}")
return query
}
{{end -}}{{- /* if unique foreign key */ -}}

View file

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

View file

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

View file

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

View file

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

View file

@ -3,11 +3,11 @@
{{- $varNameSingular := .Table.Name | singular | camelCase -}}
// {{$tableNamePlural}}G retrieves all records.
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.
func {{$tableNamePlural}}(exec boil.Executor, mods ...qm.QueryMod) {{$varNameSingular}}Query {
mods = append(mods, qm.From("{{.Table.Name | .SchemaTable}}"))
return {{$varNameSingular}}Query{NewQuery(exec, mods...)}
mods = append(mods, qm.From("{{.Table.Name | .SchemaTable}}"))
return {{$varNameSingular}}Query{NewQuery(exec, mods...)}
}

View file

@ -6,51 +6,51 @@
{{- $pkArgs := joinSlices " " $pkNames $colDefs.Types | join ", " -}}
// {{$tableNameSingular}}FindG retrieves a single record by ID.
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.
func Find{{$tableNameSingular}}GP({{$pkArgs}}, selectCols ...string) *{{$tableNameSingular}} {
retobj, err := Find{{$tableNameSingular}}(boil.GetDB(), {{$pkNames | join ", "}}, selectCols...)
if err != nil {
panic(boil.WrapErr(err))
}
retobj, err := Find{{$tableNameSingular}}(boil.GetDB(), {{$pkNames | join ", "}}, selectCols...)
if err != nil {
panic(boil.WrapErr(err))
}
return retobj
return retobj
}
// {{$tableNameSingular}}Find retrieves a single record by ID with an executor.
// If selectCols is empty Find will return all columns.
func Find{{$tableNameSingular}}(exec boil.Executor, {{$pkArgs}}, selectCols ...string) (*{{$tableNameSingular}}, error) {
{{$varNameSingular}}Obj := &{{$tableNameSingular}}{}
{{$varNameSingular}}Obj := &{{$tableNameSingular}}{}
sel := "*"
if len(selectCols) > 0 {
sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",")
}
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,
)
sel := "*"
if len(selectCols) > 0 {
sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",")
}
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,
)
q := boil.SQL(exec, query, {{$pkNames | join ", "}})
q := boil.SQL(exec, query, {{$pkNames | join ", "}})
err := q.Bind({{$varNameSingular}}Obj)
if err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, sql.ErrNoRows
}
return nil, errors.Wrap(err, "{{.PkgName}}: unable to select from {{.Table.Name}}")
}
err := q.Bind({{$varNameSingular}}Obj)
if err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, sql.ErrNoRows
}
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.
func Find{{$tableNameSingular}}P(exec boil.Executor, {{$pkArgs}}, selectCols ...string) *{{$tableNameSingular}} {
retobj, err := Find{{$tableNameSingular}}(exec, {{$pkNames | join ", "}}, selectCols...)
if err != nil {
panic(boil.WrapErr(err))
}
retobj, err := Find{{$tableNameSingular}}(exec, {{$pkNames | join ", "}}, selectCols...)
if err != nil {
panic(boil.WrapErr(err))
}
return retobj
return retobj
}

View file

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

View file

@ -7,25 +7,25 @@
// UpdateG a single {{$tableNameSingular}} record. See Update for
// whitelist behavior description.
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 takes a whitelist of column names that should be updated.
// Panics on error. See Update for whitelist behavior description.
func (o *{{$tableNameSingular}}) UpdateGP(whitelist ...string) {
if err := o.Update(boil.GetDB(), whitelist...); err != nil {
panic(boil.WrapErr(err))
}
if err := o.Update(boil.GetDB(), whitelist...); err != nil {
panic(boil.WrapErr(err))
}
}
// UpdateP uses an executor to update the {{$tableNameSingular}}, and panics on error.
// See Update for whitelist behavior description.
func (o *{{$tableNameSingular}}) UpdateP(exec boil.Executor, whitelist ... string) {
err := o.Update(exec, whitelist...)
if err != nil {
panic(boil.WrapErr(err))
}
err := o.Update(exec, whitelist...)
if err != nil {
panic(boil.WrapErr(err))
}
}
// 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()
// to refresh the records.
func (o *{{$tableNameSingular}}) Update(exec boil.Executor, whitelist ... string) error {
{{- template "timestamp_update_helper" . -}}
{{- template "timestamp_update_helper" . -}}
var err error
{{if not .NoHooks -}}
if err = o.doBeforeUpdateHooks(exec); err != nil {
return err
}
{{end -}}
var err error
{{if not .NoHooks -}}
if err = o.doBeforeUpdateHooks(exec); err != nil {
return err
}
{{end -}}
key := makeCacheKey(whitelist, nil)
{{$varNameSingular}}UpdateCacheMut.RLock()
cache, cached := {{$varNameSingular}}UpdateCache[key]
{{$varNameSingular}}UpdateCacheMut.RUnlock()
key := makeCacheKey(whitelist, nil)
{{$varNameSingular}}UpdateCacheMut.RLock()
cache, cached := {{$varNameSingular}}UpdateCache[key]
{{$varNameSingular}}UpdateCacheMut.RUnlock()
if !cached {
wl := strmangle.UpdateColumnSet({{$varNameSingular}}Columns, {{$varNameSingular}}PrimaryKeyColumns, whitelist)
if !cached {
wl := strmangle.UpdateColumnSet({{$varNameSingular}}Columns, {{$varNameSingular}}PrimaryKeyColumns, whitelist)
cache.query = fmt.Sprintf("UPDATE {{$schemaTable}} SET %s WHERE %s",
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),
)
cache.valueMapping, err = boil.BindMapping({{$varNameSingular}}Type, {{$varNameSingular}}Mapping, append(wl, {{$varNameSingular}}PrimaryKeyColumns...))
if err != nil {
return err
}
}
cache.query = fmt.Sprintf("UPDATE {{$schemaTable}} SET %s WHERE %s",
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),
)
cache.valueMapping, err = boil.BindMapping({{$varNameSingular}}Type, {{$varNameSingular}}Mapping, append(wl, {{$varNameSingular}}PrimaryKeyColumns...))
if err != nil {
return err
}
}
if len(cache.valueMapping) == 0 {
return errors.New("{{.PkgName}}: unable to update {{.Table.Name}}, could not build whitelist")
}
if len(cache.valueMapping) == 0 {
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 {
fmt.Fprintln(boil.DebugWriter, cache.query)
fmt.Fprintln(boil.DebugWriter, values)
}
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, cache.query)
fmt.Fprintln(boil.DebugWriter, values)
}
result, err := exec.Exec(cache.query, values...)
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to update {{.Table.Name}} row")
}
result, err := exec.Exec(cache.query, values...)
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to update {{.Table.Name}} row")
}
if r, err := result.RowsAffected(); err == nil && r != 1 {
return errors.Errorf("failed to update single row, updated %d rows", r)
}
if r, err := result.RowsAffected(); err == nil && r != 1 {
return errors.Errorf("failed to update single row, updated %d rows", r)
}
if !cached {
{{$varNameSingular}}UpdateCacheMut.Lock()
{{$varNameSingular}}UpdateCache[key] = cache
{{$varNameSingular}}UpdateCacheMut.Unlock()
}
if !cached {
{{$varNameSingular}}UpdateCacheMut.Lock()
{{$varNameSingular}}UpdateCache[key] = cache
{{$varNameSingular}}UpdateCacheMut.Unlock()
}
{{if not .NoHooks -}}
return o.doAfterUpdateHooks(exec)
{{- else -}}
return nil
{{- end}}
{{if not .NoHooks -}}
return o.doAfterUpdateHooks(exec)
{{- else -}}
return nil
{{- end}}
}
// UpdateAllP updates all rows with matching column names, and panics on error.
func (q {{$varNameSingular}}Query) UpdateAllP(cols M) {
if err := q.UpdateAll(cols); err != nil {
panic(boil.WrapErr(err))
}
if err := q.UpdateAll(cols); err != nil {
panic(boil.WrapErr(err))
}
}
// UpdateAll updates all rows with the specified column values.
func (q {{$varNameSingular}}Query) UpdateAll(cols M) error {
boil.SetUpdate(q.Query, cols)
boil.SetUpdate(q.Query, cols)
_, err := q.Query.ExecQuery()
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to update all for {{.Table.Name}}")
}
_, err := q.Query.ExecQuery()
if err != nil {
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.
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.
func (o {{$tableNameSingular}}Slice) UpdateAllGP(cols M) {
if err := o.UpdateAll(boil.GetDB(), cols); err != nil {
panic(boil.WrapErr(err))
}
if err := o.UpdateAll(boil.GetDB(), cols); err != nil {
panic(boil.WrapErr(err))
}
}
// UpdateAllP updates all rows with the specified column values, and panics on error.
func (o {{$tableNameSingular}}Slice) UpdateAllP(exec boil.Executor, cols M) {
if err := o.UpdateAll(exec, cols); err != nil {
panic(boil.WrapErr(err))
}
if err := o.UpdateAll(exec, cols); err != nil {
panic(boil.WrapErr(err))
}
}
// UpdateAll updates all rows with the specified column values, using an executor.
func (o {{$tableNameSingular}}Slice) UpdateAll(exec boil.Executor, cols M) error {
ln := int64(len(o))
if ln == 0 {
return nil
}
ln := int64(len(o))
if ln == 0 {
return nil
}
if len(cols) == 0 {
return errors.New("{{.PkgName}}: update all requires at least one column argument")
}
if len(cols) == 0 {
return errors.New("{{.PkgName}}: update all requires at least one column argument")
}
colNames := make([]string, len(cols))
args := make([]interface{}, len(cols))
colNames := make([]string, len(cols))
args := make([]interface{}, len(cols))
i := 0
for name, value := range cols {
colNames[i] = name
args[i] = value
i++
}
i := 0
for name, value := range cols {
colNames[i] = name
args[i] = value
i++
}
// Append all of the primary key values for each column
args = append(args, o.inPrimaryKeyArgs()...)
// Append all of the primary key values for each column
args = append(args, o.inPrimaryKeyArgs()...)
sql := fmt.Sprintf(
"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.Placeholders(dialect.IndexPlaceholders, len(o) * len({{$varNameSingular}}PrimaryKeyColumns), len(colNames)+1, len({{$varNameSingular}}PrimaryKeyColumns)),
)
sql := fmt.Sprintf(
"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.Placeholders(dialect.IndexPlaceholders, len(o) * len({{$varNameSingular}}PrimaryKeyColumns), len(colNames)+1, len({{$varNameSingular}}PrimaryKeyColumns)),
)
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, sql)
fmt.Fprintln(boil.DebugWriter, args...)
}
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, sql)
fmt.Fprintln(boil.DebugWriter, args...)
}
result, err := exec.Exec(sql, args...)
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to update all in {{$varNameSingular}} slice")
}
result, err := exec.Exec(sql, args...)
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to update all in {{$varNameSingular}} slice")
}
if r, err := result.RowsAffected(); err == nil && r != ln {
return errors.Errorf("failed to update %d rows, only affected %d", ln, r)
}
if r, err := result.RowsAffected(); err == nil && r != ln {
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 -}}
{{- $varNameSingular := .Table.Name | singular | camelCase -}}
// 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 {
return o.Upsert(boil.GetDB(), updateOnConflict, conflictColumns, updateColumns, whitelist...)
func (o *{{$tableNameSingular}}) UpsertG({{if eq .DriverName "postgres"}}updateOnConflict bool, conflictColumns []string, {{end}}updateColumns []string, whitelist ...string) error {
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.
func (o *{{$tableNameSingular}}) UpsertGP(updateOnConflict bool, conflictColumns []string, updateColumns []string, whitelist ...string) {
if err := o.Upsert(boil.GetDB(), updateOnConflict, conflictColumns, updateColumns, whitelist...); err != nil {
panic(boil.WrapErr(err))
}
func (o *{{$tableNameSingular}}) UpsertGP({{if eq .DriverName "postgres"}}updateOnConflict bool, conflictColumns []string, {{end}}updateColumns []string, whitelist ...string) {
if err := o.Upsert(boil.GetDB(), {{if eq .DriverName "postgres"}}updateOnConflict, conflictColumns, {{end}}updateColumns, whitelist...); err != nil {
panic(boil.WrapErr(err))
}
}
// UpsertP attempts an insert using an executor, and does an update or ignore on conflict.
// UpsertP panics on error.
func (o *{{$tableNameSingular}}) UpsertP(exec boil.Executor, updateOnConflict bool, conflictColumns []string, updateColumns []string, whitelist ...string) {
if err := o.Upsert(exec, updateOnConflict, conflictColumns, updateColumns, whitelist...); err != nil {
panic(boil.WrapErr(err))
}
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, {{if eq .DriverName "postgres"}}updateOnConflict, conflictColumns, {{end}}updateColumns, whitelist...); err != nil {
panic(boil.WrapErr(err))
}
}
// 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 {
if o == nil {
return errors.New("{{.PkgName}}: no {{.Table.Name}} provided for upsert")
}
func (o *{{$tableNameSingular}}) Upsert(exec boil.Executor, {{if eq .DriverName "postgres"}}updateOnConflict bool, conflictColumns []string, {{end}}updateColumns []string, whitelist ...string) error {
if o == nil {
return errors.New("{{.PkgName}}: no {{.Table.Name}} provided for upsert")
}
{{- template "timestamp_upsert_helper" . }}
{{- template "timestamp_upsert_helper" . }}
{{if not .NoHooks -}}
if err := o.doBeforeUpsertHooks(exec); err != nil {
return err
}
{{- end}}
{{if not .NoHooks -}}
if err := o.doBeforeUpsertHooks(exec); err != nil {
return err
}
{{- end}}
var err error
var ret []string
whitelist, ret = strmangle.InsertColumnSet(
{{$varNameSingular}}Columns,
{{$varNameSingular}}ColumnsWithDefault,
{{$varNameSingular}}ColumnsWithoutDefault,
boil.NonZeroDefaultSet({{$varNameSingular}}ColumnsWithDefault, o),
whitelist,
)
update := strmangle.UpdateColumnSet(
{{$varNameSingular}}Columns,
{{$varNameSingular}}PrimaryKeyColumns,
updateColumns,
)
conflict := conflictColumns
if len(conflict) == 0 {
conflict = make([]string, len({{$varNameSingular}}PrimaryKeyColumns))
copy(conflict, {{$varNameSingular}}PrimaryKeyColumns)
}
var err error
var ret []string
whitelist, ret = strmangle.InsertColumnSet(
{{$varNameSingular}}Columns,
{{$varNameSingular}}ColumnsWithDefault,
{{$varNameSingular}}ColumnsWithoutDefault,
boil.NonZeroDefaultSet({{$varNameSingular}}ColumnsWithDefault, o),
whitelist,
)
update := strmangle.UpdateColumnSet(
{{$varNameSingular}}Columns,
{{$varNameSingular}}PrimaryKeyColumns,
updateColumns,
)
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 {
fmt.Fprintln(boil.DebugWriter, query)
fmt.Fprintln(boil.DebugWriter, boil.GetStructValues(o, whitelist...))
}
{{if eq .DriverName "postgres" -}}
query := boil.BuildUpsertQueryPostgres(dialect, "{{.Table.Name}}", updateOnConflict, ret, update, conflict, whitelist)
{{- else if eq .DriverName "mysql" -}}
query := boil.BuildUpsertQueryMySQL(dialect, "{{.Table.Name}}", update, whitelist)
{{- end}}
{{- if .UseLastInsertID}}
return errors.New("don't know how to do this yet")
{{- 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 boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, query)
fmt.Fprintln(boil.DebugWriter, boil.GetStructValues(o, whitelist...))
}
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to upsert for {{.Table.Name}}")
}
{{- if .UseLastInsertID}}
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 := o.doAfterUpsertHooks(exec); err != nil {
return err
}
{{- end}}
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to upsert for {{.Table.Name}}")
}
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.
// Panics on error.
func (o *{{$tableNameSingular}}) DeleteP(exec boil.Executor) {
if err := o.Delete(exec); err != nil {
panic(boil.WrapErr(err))
}
if err := o.Delete(exec); err != nil {
panic(boil.WrapErr(err))
}
}
// DeleteG deletes a single {{$tableNameSingular}} record.
// DeleteG will match against the primary key column to find the record to delete.
func (o *{{$tableNameSingular}}) DeleteG() error {
if o == nil {
return errors.New("{{.PkgName}}: no {{$tableNameSingular}} provided for deletion")
}
if o == nil {
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 will match against the primary key column to find the record to delete.
// Panics on error.
func (o *{{$tableNameSingular}}) DeleteGP() {
if err := o.DeleteG(); err != nil {
panic(boil.WrapErr(err))
}
if err := o.DeleteG(); err != nil {
panic(boil.WrapErr(err))
}
}
// Delete deletes a single {{$tableNameSingular}} record with an executor.
// Delete will match against the primary key column to find the record to delete.
func (o *{{$tableNameSingular}}) Delete(exec boil.Executor) error {
if o == nil {
return errors.New("{{.PkgName}}: no {{$tableNameSingular}} provided for delete")
}
if o == nil {
return errors.New("{{.PkgName}}: no {{$tableNameSingular}} provided for delete")
}
{{if not .NoHooks -}}
if err := o.doBeforeDeleteHooks(exec); err != nil {
return err
}
{{- end}}
{{if not .NoHooks -}}
if err := o.doBeforeDeleteHooks(exec); err != nil {
return err
}
{{- 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 {
fmt.Fprintln(boil.DebugWriter, sql)
fmt.Fprintln(boil.DebugWriter, args...)
}
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, sql)
fmt.Fprintln(boil.DebugWriter, args...)
}
_, err := exec.Exec(sql, args...)
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to delete from {{.Table.Name}}")
}
_, err := exec.Exec(sql, args...)
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to delete from {{.Table.Name}}")
}
{{if not .NoHooks -}}
if err := o.doAfterDeleteHooks(exec); err != nil {
return err
}
{{- end}}
{{if not .NoHooks -}}
if err := o.doAfterDeleteHooks(exec); err != nil {
return err
}
{{- end}}
return nil
return nil
}
// DeleteAllP deletes all rows, and panics on error.
func (q {{$varNameSingular}}Query) DeleteAllP() {
if err := q.DeleteAll(); err != nil {
panic(boil.WrapErr(err))
}
if err := q.DeleteAll(); err != nil {
panic(boil.WrapErr(err))
}
}
// DeleteAll deletes all matching rows.
func (q {{$varNameSingular}}Query) DeleteAll() error {
if q.Query == nil {
return errors.New("{{.PkgName}}: no {{$varNameSingular}}Query provided for delete all")
}
if q.Query == nil {
return errors.New("{{.PkgName}}: no {{$varNameSingular}}Query provided for delete all")
}
boil.SetDelete(q.Query)
boil.SetDelete(q.Query)
_, err := q.Query.ExecQuery()
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to delete all from {{.Table.Name}}")
}
_, err := q.Query.ExecQuery()
if err != nil {
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.
func (o {{$tableNameSingular}}Slice) DeleteAllGP() {
if err := o.DeleteAllG(); err != nil {
panic(boil.WrapErr(err))
}
if err := o.DeleteAllG(); err != nil {
panic(boil.WrapErr(err))
}
}
// DeleteAllG deletes all rows in the slice.
func (o {{$tableNameSingular}}Slice) DeleteAllG() error {
if o == nil {
return errors.New("{{.PkgName}}: no {{$tableNameSingular}} slice provided for delete all")
}
return o.DeleteAll(boil.GetDB())
if o == nil {
return errors.New("{{.PkgName}}: no {{$tableNameSingular}} slice provided for delete all")
}
return o.DeleteAll(boil.GetDB())
}
// DeleteAllP deletes all rows in the slice, using an executor, and panics on error.
func (o {{$tableNameSingular}}Slice) DeleteAllP(exec boil.Executor) {
if err := o.DeleteAll(exec); err != nil {
panic(boil.WrapErr(err))
}
if err := o.DeleteAll(exec); err != nil {
panic(boil.WrapErr(err))
}
}
// DeleteAll deletes all rows in the slice, using an executor.
func (o {{$tableNameSingular}}Slice) DeleteAll(exec boil.Executor) error {
if o == nil {
return errors.New("{{.PkgName}}: no {{$tableNameSingular}} slice provided for delete all")
}
if o == nil {
return errors.New("{{.PkgName}}: no {{$tableNameSingular}} slice provided for delete all")
}
if len(o) == 0 {
return nil
}
if len(o) == 0 {
return nil
}
{{if not .NoHooks -}}
if len({{$varNameSingular}}BeforeDeleteHooks) != 0 {
for _, obj := range o {
if err := obj.doBeforeDeleteHooks(exec); err != nil {
return err
}
}
}
{{- end}}
{{if not .NoHooks -}}
if len({{$varNameSingular}}BeforeDeleteHooks) != 0 {
for _, obj := range o {
if err := obj.doBeforeDeleteHooks(exec); err != nil {
return err
}
}
}
{{- end}}
args := o.inPrimaryKeyArgs()
args := o.inPrimaryKeyArgs()
sql := fmt.Sprintf(
"DELETE FROM {{$schemaTable}} WHERE (%s) IN (%s)",
strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, {{$varNameSingular}}PrimaryKeyColumns), ","),
strmangle.Placeholders(dialect.IndexPlaceholders, len(o) * len({{$varNameSingular}}PrimaryKeyColumns), 1, len({{$varNameSingular}}PrimaryKeyColumns)),
)
sql := fmt.Sprintf(
"DELETE FROM {{$schemaTable}} WHERE (%s) IN (%s)",
strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, {{$varNameSingular}}PrimaryKeyColumns), ","),
strmangle.Placeholders(dialect.IndexPlaceholders, len(o) * len({{$varNameSingular}}PrimaryKeyColumns), 1, len({{$varNameSingular}}PrimaryKeyColumns)),
)
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, sql)
fmt.Fprintln(boil.DebugWriter, args)
}
if boil.DebugMode {
fmt.Fprintln(boil.DebugWriter, sql)
fmt.Fprintln(boil.DebugWriter, args)
}
_, err := exec.Exec(sql, args...)
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to delete all from {{$varNameSingular}} slice")
}
_, err := exec.Exec(sql, args...)
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to delete all from {{$varNameSingular}} slice")
}
{{if not .NoHooks -}}
if len({{$varNameSingular}}AfterDeleteHooks) != 0 {
for _, obj := range o {
if err := obj.doAfterDeleteHooks(exec); err != nil {
return err
}
}
}
{{- end}}
{{if not .NoHooks -}}
if len({{$varNameSingular}}AfterDeleteHooks) != 0 {
for _, obj := range o {
if err := obj.doAfterDeleteHooks(exec); err != nil {
return err
}
}
}
{{- end}}
return nil
return nil
}

View file

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

View file

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

View file

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

View file

@ -1,20 +1,20 @@
var dialect = boil.Dialect{
LQ: 0x{{printf "%x" .Dialect.LQ}},
RQ: 0x{{printf "%x" .Dialect.RQ}},
IndexPlaceholders: {{.Dialect.IndexPlaceholders}},
LQ: 0x{{printf "%x" .Dialect.LQ}},
RQ: 0x{{printf "%x" .Dialect.RQ}},
IndexPlaceholders: {{.Dialect.IndexPlaceholders}},
}
// NewQueryG initializes a new Query using the passed in QueryMods
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
func NewQuery(exec boil.Executor, mods ...qm.QueryMod) *boil.Query {
q := &boil.Query{}
boil.SetExecutor(q, exec)
boil.SetDialect(q, &dialect)
qm.Apply(q, mods...)
q := &boil.Query{}
boil.SetExecutor(q, exec)
boil.SetDialect(q, &dialect)
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")
type insertCache struct{
query string
retQuery string
valueMapping []uint64
retMapping []uint64
query string
retQuery string
valueMapping []uint64
retMapping []uint64
}
type updateCache struct{
query string
valueMapping []uint64
query string
valueMapping []uint64
}
func makeCacheKey(wl, nzDefaults []string) string {
buf := strmangle.GetBuffer()
buf := strmangle.GetBuffer()
for _, w := range wl {
buf.WriteString(w)
}
if len(nzDefaults) != 0 {
buf.WriteByte('.')
}
for _, nz := range nzDefaults {
buf.WriteString(nz)
}
for _, w := range wl {
buf.WriteString(w)
}
if len(nzDefaults) != 0 {
buf.WriteByte('.')
}
for _, nz := range nzDefaults {
buf.WriteString(nz)
}
str := buf.String()
strmangle.PutBuffer(buf)
return str
str := buf.String()
strmangle.PutBuffer(buf)
return str
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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