sqlboiler/templates/06_relationship_to_one_eager.tpl

78 lines
2.3 KiB
Smarty
Raw Normal View History

2016-08-16 09:30:08 +02:00
{{- define "relationship_to_one_eager_helper" -}}
{{- $arg := printf "maybe%s" .LocalTable.NameGo -}}
{{- $slice := printf "%sSlice" .LocalTable.NameGo -}}
2016-08-16 09:30:08 +02:00
// Load{{.Function.Name}} allows an eager lookup of values, cached into the
2016-08-23 06:53:37 +02:00
// loaded structs of the objects.
func (r *{{.LocalTable.NameGo}}Loaded) Load{{.Function.Name}}(e boil.Executor, singular bool, {{$arg}} interface{}) error {
2016-08-16 09:30:08 +02:00
var slice []*{{.LocalTable.NameGo}}
var object *{{.LocalTable.NameGo}}
count := 1
if singular {
object = {{$arg}}.(*{{.LocalTable.NameGo}})
} else {
2016-08-24 07:07:51 +02:00
slice = *{{$arg}}.(*{{$slice}})
2016-08-16 09:30:08 +02:00
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}}
}
}
query := fmt.Sprintf(
`select * from "{{.ForeignKey.ForeignTable}}" where "{{.ForeignKey.ForeignColumn}}" in (%s)`,
strmangle.Placeholders(count, 1, 1),
)
if boil.DebugMode {
fmt.Fprintf(boil.DebugWriter, "%s\n%v\n", query, args)
}
2016-08-16 09:30:08 +02:00
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.BindFast(results, &resultSlice, {{.ForeignKey.Table | singular | camelCase}}TitleCases); err != nil {
2016-08-16 09:30:08 +02:00
return errors.Wrap(err, "failed to bind eager loaded slice {{.ForeignTable}}")
}
if singular && len(resultSlice) != 0 {
2016-08-23 06:53:37 +02:00
if object.Loaded == nil {
object.Loaded = &{{.LocalTable.NameGo}}Loaded{}
2016-08-16 09:30:08 +02:00
}
2016-08-23 06:53:37 +02:00
object.Loaded.{{.Function.Name}} = resultSlice[0]
2016-08-16 09:30:08 +02:00
return nil
}
for _, foreign := range resultSlice {
for _, local := range slice {
if local.{{.Function.LocalAssignment}} == foreign.{{.Function.ForeignAssignment}} {
2016-08-23 06:53:37 +02:00
if local.Loaded == nil {
local.Loaded = &{{.LocalTable.NameGo}}Loaded{}
2016-08-16 09:30:08 +02:00
}
2016-08-23 06:53:37 +02:00
local.Loaded.{{.Function.Name}} = foreign
2016-08-16 09:30:08 +02:00
break
}
}
}
return nil
}
{{end -}}
2016-08-16 09:30:08 +02:00
{{- if .Table.IsJoinTable -}}
{{- else -}}
{{- $dot := . -}}
{{- range .Table.FKeys -}}
{{- $rel := textsFromForeignKey $dot.PkgName $dot.Tables $dot.Table . -}}
{{- template "relationship_to_one_eager_helper" $rel -}}
{{- end -}}
2016-08-16 09:30:08 +02:00
{{- end -}}