Refactored codegen tool
This commit is contained in:
@@ -0,0 +1,480 @@
|
||||
package {{ .Package }}
|
||||
|
||||
// This file is auto-generated.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
//
|
||||
// Definitions file that controls how this file is generated:
|
||||
// {{ .Source }}
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"errors"
|
||||
"time"
|
||||
{{- if $.SupportHttpErrors }}
|
||||
"net/http"
|
||||
{{- end }}
|
||||
|
||||
"github.com/cortezaproject/corteza-server/pkg/actionlog"
|
||||
{{- range $import := $.Import }}
|
||||
{{ normalizeImport $import }}
|
||||
{{- end }}
|
||||
)
|
||||
|
||||
type (
|
||||
{{ $.Service }}ActionProps struct {
|
||||
{{- range $prop := $.Props }}
|
||||
{{ $prop.Name }} {{ $prop.Type }}
|
||||
{{- end }}
|
||||
}
|
||||
|
||||
{{ if $.Actions }}
|
||||
{{ $.Service }}Action struct {
|
||||
timestamp time.Time
|
||||
resource string
|
||||
action string
|
||||
log string
|
||||
severity actionlog.Severity
|
||||
|
||||
// prefix for error when action fails
|
||||
errorMessage string
|
||||
|
||||
props *{{ $.Service }}ActionProps
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
{{ if $.Errors }}
|
||||
{{ $.Service }}Error struct {
|
||||
timestamp time.Time
|
||||
error string
|
||||
resource string
|
||||
action string
|
||||
message string
|
||||
log string
|
||||
severity actionlog.Severity
|
||||
|
||||
wrap error
|
||||
|
||||
props *{{ $.Service }}ActionProps
|
||||
|
||||
{{ if $.SupportHttpErrors }}
|
||||
httpStatusCode int
|
||||
{{ end }}
|
||||
}
|
||||
{{ end }}
|
||||
)
|
||||
|
||||
var (
|
||||
// just a placeholder to cover template cases w/o fmt package use
|
||||
_ = fmt.Println
|
||||
)
|
||||
|
||||
// *********************************************************************************************************************
|
||||
// *********************************************************************************************************************
|
||||
// Props methods
|
||||
|
||||
{{- range $prop := $.Props }}
|
||||
// {{ camelCase "set" $prop.Name }} updates {{ $.Service }}ActionProps's {{ $prop.Name }}
|
||||
//
|
||||
// Allows method chaining
|
||||
//
|
||||
// This function is auto-generated.
|
||||
//
|
||||
func (p *{{ $.Service }}ActionProps) {{ camelCase "set" $prop.Name }}({{ $prop.Name }} {{ $prop.Type }}) *{{ $.Service }}ActionProps {
|
||||
p.{{ $prop.Name }} = {{ $prop.Name }}
|
||||
return p
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
|
||||
// serialize converts {{ $.Service }}ActionProps to actionlog.Meta
|
||||
//
|
||||
// This function is auto-generated.
|
||||
//
|
||||
func (p {{ $.Service }}ActionProps) serialize() actionlog.Meta {
|
||||
var (
|
||||
m = make(actionlog.Meta)
|
||||
)
|
||||
|
||||
{{ range $prop := $.Props }}
|
||||
{{- if $prop.Builtin }}
|
||||
m.Set("{{ $prop.Name }}", p.{{ $prop.Name }}, true)
|
||||
{{- else }}
|
||||
if p.{{ $prop.Name }} != nil {
|
||||
{{- range $f := $prop.Fields }}
|
||||
m.Set("{{ $prop.Name }}.{{ $f }}", p.{{ $prop.Name }}.{{ camelCase " " $f }}, true)
|
||||
{{- end }}
|
||||
}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
// tr translates string and replaces meta value placeholder with values
|
||||
//
|
||||
// This function is auto-generated.
|
||||
//
|
||||
func (p {{ $.Service }}ActionProps) tr(in string, err error) string {
|
||||
var (
|
||||
pairs = []string{"{err}"}
|
||||
|
||||
{{- if $.Props }}
|
||||
// first non-empty string
|
||||
fns = func(ii ... interface{}) string {
|
||||
for _, i:= range ii {
|
||||
if s :=fmt.Sprintf("%v", i); len(s) > 0 {
|
||||
return s
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
{{- end }}
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
for {
|
||||
// Unwrap errors
|
||||
ue := errors.Unwrap(err)
|
||||
if ue == nil {
|
||||
break
|
||||
}
|
||||
|
||||
err = ue
|
||||
}
|
||||
|
||||
pairs = append(pairs, err.Error())
|
||||
} else {
|
||||
pairs = append(pairs, "nil")
|
||||
}
|
||||
|
||||
{{- range $prop := $.Props }}
|
||||
{{- if $prop.Builtin }}
|
||||
pairs = append(pairs, "{{"{"}}{{ $prop.Name }}}", fns(p.{{ $prop.Name }}))
|
||||
{{- else }}
|
||||
|
||||
if p.{{ $prop.Name }} != nil {
|
||||
// replacement for "{{"{"}}{{ $prop.Name }}}" (in order how fields are defined)
|
||||
pairs = append(
|
||||
pairs,
|
||||
"{{"{"}}{{ $prop.Name }}}",
|
||||
fns(
|
||||
{{- range $f := $prop.Fields }}
|
||||
p.{{ $prop.Name }}.{{ camelCase " " $f }},
|
||||
{{- end }}
|
||||
),
|
||||
)
|
||||
|
||||
{{- range $f := $prop.Fields }}
|
||||
pairs = append(pairs, "{{"{"}}{{ $prop.Name }}.{{ $f }}}", fns(p.{{ $prop.Name }}.{{ camelCase " " $f }}))
|
||||
{{- end }}
|
||||
}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
return strings.NewReplacer(pairs...).Replace(in)
|
||||
}
|
||||
|
||||
{{ if $.Actions }}
|
||||
// *********************************************************************************************************************
|
||||
// *********************************************************************************************************************
|
||||
// Action methods
|
||||
|
||||
// String returns loggable description as string
|
||||
//
|
||||
// This function is auto-generated.
|
||||
//
|
||||
func (a *{{ $.Service }}Action) String() string {
|
||||
var props = &{{ $.Service }}ActionProps{}
|
||||
|
||||
if a.props != nil {
|
||||
props = a.props
|
||||
}
|
||||
|
||||
return props.tr(a.log, nil)
|
||||
}
|
||||
|
||||
func (e *{{ $.Service }}Action) LoggableAction() *actionlog.Action {
|
||||
return &actionlog.Action{
|
||||
Timestamp: e.timestamp,
|
||||
Resource: e.resource,
|
||||
Action: e.action,
|
||||
Severity: e.severity,
|
||||
Description: e.String(),
|
||||
Meta: e.props.serialize(),
|
||||
}
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
{{ if $.Errors }}
|
||||
// *********************************************************************************************************************
|
||||
// *********************************************************************************************************************
|
||||
// Error methods
|
||||
|
||||
// String returns loggable description as string
|
||||
//
|
||||
// It falls back to message if log is not set
|
||||
//
|
||||
// This function is auto-generated.
|
||||
//
|
||||
func (e *{{ $.Service }}Error) String() string {
|
||||
var props = &{{ $.Service }}ActionProps{}
|
||||
|
||||
if e.props != nil {
|
||||
props = e.props
|
||||
}
|
||||
|
||||
|
||||
if e.wrap != nil && !strings.Contains(e.log, "{err}") {
|
||||
// Suffix error log with {err} to ensure
|
||||
// we log the cause for this error
|
||||
e.log += ": {err}"
|
||||
}
|
||||
|
||||
return props.tr(e.log, e.wrap)
|
||||
}
|
||||
|
||||
// Error satisfies
|
||||
//
|
||||
// This function is auto-generated.
|
||||
//
|
||||
func (e *{{ $.Service }}Error) Error() string {
|
||||
var props = &{{ $.Service }}ActionProps{}
|
||||
|
||||
if e.props != nil {
|
||||
props = e.props
|
||||
}
|
||||
|
||||
return props.tr(e.message, e.wrap)
|
||||
}
|
||||
|
||||
// Is fn for error equality check
|
||||
//
|
||||
// This function is auto-generated.
|
||||
//
|
||||
func (e *{{ $.Service }}Error) Is(Resource error) bool {
|
||||
t, ok := Resource.(*{{ $.Service }}Error)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
return t.resource == e.resource && t.error == e.error
|
||||
}
|
||||
|
||||
// Wrap wraps {{ $.Service }}Error around another error
|
||||
//
|
||||
// This function is auto-generated.
|
||||
//
|
||||
func (e *{{ $.Service }}Error) Wrap(err error) *{{ $.Service }}Error {
|
||||
e.wrap = err
|
||||
return e
|
||||
}
|
||||
|
||||
// Unwrap returns wrapped error
|
||||
//
|
||||
// This function is auto-generated.
|
||||
//
|
||||
func (e *{{ $.Service }}Error) Unwrap() error {
|
||||
return e.wrap
|
||||
}
|
||||
|
||||
func (e *{{ $.Service }}Error) LoggableAction() *actionlog.Action {
|
||||
return &actionlog.Action{
|
||||
Timestamp: e.timestamp,
|
||||
Resource: e.resource,
|
||||
Action: e.action,
|
||||
Severity: e.severity,
|
||||
Description: e.String(),
|
||||
Error: e.Error(),
|
||||
Meta: e.props.serialize(),
|
||||
}
|
||||
}
|
||||
|
||||
{{ if $.SupportHttpErrors }}
|
||||
func (e *{{ $.Service }}Error) HttpResponse(w http.ResponseWriter) {
|
||||
var code = e.httpStatusCode
|
||||
if code == 0 {
|
||||
code = http.StatusInternalServerError
|
||||
}
|
||||
|
||||
http.Error(w, e.message, code)
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
|
||||
{{ if $.Actions }}
|
||||
// *********************************************************************************************************************
|
||||
// *********************************************************************************************************************
|
||||
// Action constructors
|
||||
|
||||
{{ range $a := $.Actions }}
|
||||
// {{ camelCase "" $.Service "Action" $a.Action }} returns "{{ $.Resource }}.{{ $a.Action }}" error
|
||||
//
|
||||
// This function is auto-generated.
|
||||
//
|
||||
func {{ camelCase "" $.Service "Action" $a.Action }}(props ... *{{ $.Service }}ActionProps) *{{ $.Service }}Action {
|
||||
a := &{{ $.Service }}Action{
|
||||
timestamp: time.Now(),
|
||||
resource: "{{ $.Resource }}",
|
||||
action: "{{ $a.Action }}",
|
||||
log: "{{ $a.Log }}",
|
||||
severity: {{ $a.SeverityConstName }},
|
||||
}
|
||||
|
||||
if len(props) > 0 {
|
||||
a.props = props[0]
|
||||
}
|
||||
|
||||
return a
|
||||
}
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
|
||||
{{ if $.Errors }}
|
||||
// *********************************************************************************************************************
|
||||
// *********************************************************************************************************************
|
||||
// Error constructors
|
||||
|
||||
{{ range $e := $.Errors }}
|
||||
{{- if $e.Safe }}
|
||||
// {{ camelCase "" $.Service "Err" $e.Error }} returns "{{ $.Resource }}.{{ $e.Safe }}" audit event as {{ $e.SeverityConstName }}
|
||||
{{- else }}
|
||||
// {{ camelCase "" $.Service "Err" $e.Error }} returns "{{ $.Resource }}.{{ $e.Error }}" audit event as {{ $e.SeverityConstName }}
|
||||
{{- end }}
|
||||
//
|
||||
{{- if $e.Safe }}
|
||||
// Note: This error will be wrapped with safe ({{ $e.Safe }}) error!
|
||||
{{- end }}
|
||||
//
|
||||
// This function is auto-generated.
|
||||
//
|
||||
func {{ camelCase "" $.Service "Err" $e.Error }}(props ... *{{ $.Service }}ActionProps) *{{ $.Service }}Error {
|
||||
var e = &{{ $.Service }}Error{
|
||||
timestamp: time.Now(),
|
||||
resource: "{{ $.Resource }}",
|
||||
error: "{{ $e.Error }}",
|
||||
action: "error",
|
||||
message: "{{ $e.Message }}",
|
||||
log: "{{ $e.Log }}",
|
||||
severity: {{ $e.SeverityConstName }},
|
||||
props: func() *{{ $.Service }}ActionProps { if len(props) > 0 { return props[0] }; return nil}(),
|
||||
|
||||
{{ if $e.HttpStatus }}
|
||||
httpStatusCode: http.{{ $e.HttpStatus }},
|
||||
{{ end }}
|
||||
}
|
||||
|
||||
if len(props) > 0 {
|
||||
e.props = props[0]
|
||||
}
|
||||
|
||||
{{ if $e.Safe }}
|
||||
// Wrap with safe error
|
||||
return {{ camelCase "" $.Service "Err" $e.Safe }}().Wrap(e)
|
||||
{{ else }}
|
||||
return e
|
||||
{{ end }}
|
||||
}
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
|
||||
// *********************************************************************************************************************
|
||||
// *********************************************************************************************************************
|
||||
|
||||
// recordAction is a service helper function wraps function that can return error
|
||||
//
|
||||
// context is used to enrich audit log entry with current user info, request ID, IP address...
|
||||
// props are collected action/error properties
|
||||
// action (optional) fn will be used to construct {{ $.Service }}Action struct from given props (and error)
|
||||
// err is any error that occurred while action was happening
|
||||
//
|
||||
// Action has success and fail (error) state:
|
||||
// - when recorded without an error (4th param), action is recorded as successful.
|
||||
// - when an additional error is given (4th param), action is used to wrap
|
||||
// the additional error
|
||||
//
|
||||
// This function is auto-generated.
|
||||
//
|
||||
func (svc {{ $.Service }}) recordAction(ctx context.Context, props *{{ $.Service }}ActionProps, action func(... *{{ $.Service }}ActionProps) *{{ $.Service }}Action, err error) error {
|
||||
var (
|
||||
ok bool
|
||||
|
||||
// Return error
|
||||
retError *{{ $.Service }}Error
|
||||
|
||||
// Recorder error
|
||||
recError *{{ $.Service }}Error
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
if retError, ok = err.(*{{ $.Service }}Error); !ok {
|
||||
// got non-{{ $.Service }} error, wrap it with {{ camelCase "" $.Service "err" "generic" }}
|
||||
retError = {{ camelCase "" $.Service "err" "generic" }}(props).Wrap(err)
|
||||
|
||||
if action != nil {
|
||||
// copy action to returning and recording error
|
||||
retError.action = action().action
|
||||
}
|
||||
|
||||
// we'll use {{ camelCase "" $.Service "err" "generic" }} for recording too
|
||||
// because it can hold more info
|
||||
recError = retError
|
||||
} else if retError != nil {
|
||||
if action != nil {
|
||||
// copy action to returning and recording error
|
||||
retError.action = action().action
|
||||
}
|
||||
// start with copy of return error for recording
|
||||
// this will be updated with tha root cause as we try and
|
||||
// unwrap the error
|
||||
recError = retError
|
||||
|
||||
// find the original recError for this error
|
||||
// for the purpose of logging
|
||||
var unwrappedError error = retError
|
||||
for {
|
||||
if unwrappedError = errors.Unwrap(unwrappedError); unwrappedError == nil {
|
||||
// nothing wrapped
|
||||
break
|
||||
}
|
||||
|
||||
// update recError ONLY of wrapped error is of type {{ $.Service }}Error
|
||||
if unwrappedSinkError, ok := unwrappedError.(*{{ $.Service }}Error); ok {
|
||||
recError = unwrappedSinkError
|
||||
}
|
||||
}
|
||||
|
||||
if retError.props == nil {
|
||||
// set props on returning error if empty
|
||||
retError.props = props
|
||||
}
|
||||
|
||||
if recError.props == nil {
|
||||
// set props on recording error if empty
|
||||
recError.props = props
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if svc.actionlog != nil {
|
||||
if retError != nil {
|
||||
// failed action, log error
|
||||
svc.actionlog.Record(ctx, recError)
|
||||
} else if action != nil {
|
||||
// successful
|
||||
svc.actionlog.Record(ctx, action(props))
|
||||
}
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
// retError not an interface and that WILL (!!) cause issues
|
||||
// with nil check (== nil) when it is not explicitly returned
|
||||
return nil
|
||||
}
|
||||
|
||||
return retError
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// This file is auto-generated.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
//
|
||||
// Definitions file that controls how this file is generated:
|
||||
// {{ .Source }}
|
||||
|
||||
= {{ $.ResourceString }}
|
||||
|
||||
|
||||
.List of events on `{{ $.ResourceString }}`
|
||||
{{- range $event := $.Events.MakeEvents }}
|
||||
- `{{ $event }}`
|
||||
{{- end }}
|
||||
|
||||
.Event arguments for `{{ $.ResourceString }}`
|
||||
[%header,cols=3*]
|
||||
|===
|
||||
|Name
|
||||
|Type
|
||||
|Immutable
|
||||
|
||||
{{- range $p := $.Events.Properties }}
|
||||
|`{{ camelCase $p.Name }}`
|
||||
|`{{ $p.Type }}`
|
||||
|{{ $p.Immutable }}
|
||||
{{- end }}
|
||||
|===
|
||||
@@ -0,0 +1,183 @@
|
||||
package {{ .Package }}
|
||||
|
||||
// This file is auto-generated.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
//
|
||||
// Definitions file that controls how this file is generated:
|
||||
// {{ .Source }}
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
{{- range $i, $import := .Imports }}
|
||||
{{ normalizeImport $import }}
|
||||
{{- end }}
|
||||
)
|
||||
|
||||
// dummy placing to simplify import generation logic
|
||||
var _ = json.NewEncoder
|
||||
|
||||
type (
|
||||
{{ range $r := $.Resources }}
|
||||
// {{ camelCase $r.ResourceIdent "base" }}
|
||||
//
|
||||
// This type is auto-generated.
|
||||
{{ camelCase $r.ResourceIdent "base" }} struct {
|
||||
immutable bool
|
||||
{{- range $p := $r.Properties }}
|
||||
{{ $p.Name }} {{ $p.Type }}
|
||||
{{- end }}
|
||||
}
|
||||
|
||||
{{ range $event := $r.Events }}
|
||||
// {{ camelCase $r.ResourceIdent $event }}
|
||||
//
|
||||
// This type is auto-generated.
|
||||
{{ camelCase $r.ResourceIdent $event }} struct {
|
||||
*{{ camelCase $r.ResourceIdent "base" }}
|
||||
}
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
)
|
||||
|
||||
|
||||
{{ range $r := $.Resources }}
|
||||
|
||||
// ResourceType returns "{{ $r.ResourceString }}"
|
||||
//
|
||||
// This function is auto-generated.
|
||||
func ({{ camelCase .ResourceIdent "base" }}) ResourceType() string {
|
||||
return "{{ .ResourceString }}"
|
||||
}
|
||||
|
||||
{{ range $event := $r.Events }}
|
||||
// EventType on {{ camelCase $r.ResourceIdent $event }} returns "{{ $event }}"
|
||||
//
|
||||
// This function is auto-generated.
|
||||
func ({{ camelCase $r.ResourceIdent $event }}) EventType() string {
|
||||
return "{{ $event }}"
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
{{ range $event := $r.Events }}
|
||||
// {{ camelCase "" $r.ResourceIdent $event }} creates {{ $event }} for {{ $r.ResourceString }} resource
|
||||
//
|
||||
// This function is auto-generated.
|
||||
func {{ camelCase "" $r.ResourceIdent $event }}(
|
||||
{{- range $p := $r.Properties }}
|
||||
{{- if not $p.Internal }}
|
||||
{{ camelCase "arg" $p.Name }} {{ $p.Type }},
|
||||
{{- end -}}
|
||||
{{- end}}
|
||||
) *{{ camelCase $r.ResourceIdent $event }} {
|
||||
return &{{ camelCase $r.ResourceIdent $event }}{
|
||||
{{ camelCase $r.ResourceIdent "base" }}: &{{ camelCase $r.ResourceIdent "base" }}{
|
||||
immutable: false,
|
||||
{{- range $p := $r.Properties }}
|
||||
{{- if not $p.Internal }}
|
||||
{{ $p.Name }}: {{ camelCase "arg" $p.Name }},
|
||||
{{- end -}}
|
||||
{{- end}}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// {{ camelCase "" $r.ResourceIdent $event "Immutable" }} creates {{ $event }} for {{ $r.ResourceString }} resource
|
||||
//
|
||||
// None of the arguments will be mutable!
|
||||
//
|
||||
// This function is auto-generated.
|
||||
func {{ camelCase "" $r.ResourceIdent $event "Immutable" }}(
|
||||
{{- range $p := $r.Properties }}
|
||||
{{- if not $p.Internal }}
|
||||
{{ camelCase "arg" $p.Name }} {{ $p.Type }},
|
||||
{{- end -}}
|
||||
{{- end}}
|
||||
) *{{ camelCase $r.ResourceIdent $event }} {
|
||||
return &{{ camelCase $r.ResourceIdent $event }}{
|
||||
{{ camelCase $r.ResourceIdent "base" }}: &{{ camelCase $r.ResourceIdent "base" }}{
|
||||
immutable: true,
|
||||
{{- range $p := $r.Properties }}
|
||||
{{- if not $p.Internal }}
|
||||
{{ $p.Name }}: {{ camelCase "arg" $p.Name }},
|
||||
{{- end -}}
|
||||
{{- end}}
|
||||
},
|
||||
}
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
|
||||
|
||||
{{ range $p := $r.Properties }}
|
||||
{{ if not $p.Immutable }}
|
||||
// {{ camelCase "Set" $p.Name }} sets new {{ $p.Name }} value
|
||||
//
|
||||
// This function is auto-generated.
|
||||
func (res *{{ camelCase $r.ResourceIdent "base" }}) {{ camelCase "Set" $p.Name }}({{ camelCase "arg" $p.Name }} {{ $p.Type }}) {
|
||||
res.{{ $p.Name }} = {{ camelCase "arg" $p.Name }}
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
// {{ camelCase "" $p.Name }} returns {{ $p.Name }}
|
||||
//
|
||||
// This function is auto-generated.
|
||||
func (res {{ camelCase $r.ResourceIdent "base" }}) {{ camelCase "" $p.Name }}() {{ $p.Type }} {
|
||||
return res.{{ $p.Name }}
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
|
||||
// Encode internal data to be passed as event params & arguments to triggered Corredor script
|
||||
func (res {{ camelCase .ResourceIdent "base" }}) Encode() (args map[string][]byte, err error) {
|
||||
{{- if $r.Properties }}
|
||||
args = make(map[string][]byte)
|
||||
|
||||
{{ range $prop := $r.Properties }}
|
||||
if args["{{ $prop.Name }}"], err = json.Marshal(res.{{ $prop.Name }}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
{{ end }}
|
||||
{{ else }}
|
||||
// Handle argument encoding
|
||||
{{ end -}}
|
||||
return
|
||||
}
|
||||
|
||||
// Decode return values from Corredor script into struct props
|
||||
func (res *{{ camelCase .ResourceIdent "base" }}) Decode(results map[string][]byte)( err error) {
|
||||
if res.immutable {
|
||||
// Respect immutability
|
||||
return
|
||||
}
|
||||
|
||||
{{- if $r.Result }}
|
||||
if res.{{ $r.Result }} != nil {
|
||||
if r, ok := results["result"]; ok && len(results) == 1 {
|
||||
if err = json.Unmarshal(r, res.{{ $r.Result }}); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
{{ end -}}
|
||||
|
||||
{{- range $prop := $r.Properties }}
|
||||
{{- if not $prop.Immutable }}
|
||||
if res.{{ $prop.Name }} != nil {
|
||||
if r, ok := results["{{ $prop.Name }}"]; ok {
|
||||
if err = json.Unmarshal(r, res.{{ $prop.Name }}); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
{{ else }}
|
||||
// Do not decode {{ $prop.Name }}; marked as immutable
|
||||
{{ end -}}
|
||||
{{ end -}}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
{{ end }}
|
||||
@@ -0,0 +1,19 @@
|
||||
package {{ .Package }}
|
||||
|
||||
import (
|
||||
"github.com/cortezaproject/corteza-server/pkg/eventbus"
|
||||
)
|
||||
|
||||
var _=eventbus.ConstraintMaker
|
||||
|
||||
// Match returns false if given conditions do not match event & resource internals
|
||||
func (res {{ camelCase .ResourceIdent "base" }}) Match(c eventbus.ConstraintMatcher) bool {
|
||||
// By default we match no mather what kind of constraints we receive
|
||||
//
|
||||
// Function will be called multiple times - once for every trigger constraint
|
||||
// All should match (return true):
|
||||
// constraint#1 AND constraint#2 AND constraint#3 ...
|
||||
//
|
||||
// When there are multiple values, Match() can decide how to treat them (OR, AND...)
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package handlers
|
||||
|
||||
// This file is auto-generated.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
//
|
||||
// Definitions file that controls how this file is generated:
|
||||
// {{ .Source }}
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/titpetric/factory/resputil"
|
||||
|
||||
"github.com/cortezaproject/corteza-server/{{ .App }}/rest/request"
|
||||
"github.com/cortezaproject/corteza-server/pkg/logger"
|
||||
)
|
||||
|
||||
type (
|
||||
// Internal API interface
|
||||
{{ pubIdent $.Endpoint.Entrypoint }}API interface {
|
||||
{{- range $a := $.Endpoint.Apis }}
|
||||
{{ pubIdent $a.Name }}(context.Context, *request.{{ pubIdent $.Endpoint.Entrypoint $a.Name }}) (interface{}, error)
|
||||
{{- end }}
|
||||
}
|
||||
|
||||
// HTTP API interface
|
||||
{{ pubIdent .Endpoint.Entrypoint }} struct {
|
||||
{{- range $a := .Endpoint.Apis }}
|
||||
{{ pubIdent $a.Name }} func(http.ResponseWriter, *http.Request)
|
||||
{{- end }}
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
func {{ pubIdent "New" $.Endpoint.Entrypoint }}(h {{ pubIdent $.Endpoint.Entrypoint }}API) *{{ pubIdent $.Endpoint.Entrypoint }} {
|
||||
return &{{ pubIdent $.Endpoint.Entrypoint }}{
|
||||
{{- range $a := .Endpoint.Apis }}
|
||||
{{ pubIdent $a.Name }}: func(w http.ResponseWriter, r *http.Request) {
|
||||
defer r.Body.Close()
|
||||
params := request.New{{ pubIdent $.Endpoint.Entrypoint $a.Name }}()
|
||||
if err := params.Fill(r); err != nil {
|
||||
logger.LogParamError("{{ pubIdent $.Endpoint.Entrypoint }}.{{ pubIdent $a.Name }}", r, err)
|
||||
resputil.JSON(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
value, err := h.{{ pubIdent $a.Name }}(r.Context(), params)
|
||||
if err != nil {
|
||||
logger.LogControllerError("{{ pubIdent $.Endpoint.Entrypoint }}.{{ pubIdent $a.Name }}", r, err, params.Auditable())
|
||||
resputil.JSON(w, err)
|
||||
return
|
||||
}
|
||||
logger.LogControllerCall("{{ pubIdent $.Endpoint.Entrypoint }}.{{ pubIdent $a.Name }}", r, params.Auditable())
|
||||
if !serveHTTP(value, w, r) {
|
||||
resputil.JSON(w, value)
|
||||
}
|
||||
},
|
||||
{{- end }}
|
||||
}
|
||||
}
|
||||
|
||||
func (h {{ pubIdent $.Endpoint.Entrypoint }}) MountRoutes(r chi.Router, middlewares ...func(http.Handler) http.Handler) {
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middlewares...)
|
||||
|
||||
{{- range $a := .Endpoint.Apis }}
|
||||
r.{{ pubIdent ( toLower $a.Method ) }}("{{ $.Endpoint.Path }}{{ $a.Path }}", h.{{ pubIdent $a.Name }})
|
||||
{{- end }}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package request
|
||||
|
||||
// This file is auto-generated.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
//
|
||||
// Definitions file that controls how this file is generated:
|
||||
// {{ .Source }}
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/cortezaproject/corteza-server/pkg/payload"
|
||||
"github.com/go-chi/chi"
|
||||
"io"
|
||||
"fmt"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"strings"
|
||||
{{- range $i, $import := $.Imports }}
|
||||
{{ normalizeImport $import }}
|
||||
{{- end }}
|
||||
)
|
||||
|
||||
// dummy vars to prevent
|
||||
// unused imports complain
|
||||
var (
|
||||
_ = chi.URLParam
|
||||
_ = multipart.ErrMessageTooLarge
|
||||
_ = payload.ParseUint64s
|
||||
)
|
||||
|
||||
type (
|
||||
// Internal API interface
|
||||
{{- range $a := $.Endpoint.Apis }}
|
||||
{{ pubIdent $.Endpoint.Entrypoint $a.Name }} struct {
|
||||
{{- range $p := $a.Params.All }}
|
||||
// {{ pubIdent $p.Name }} {{ $p.Origin }} parameter
|
||||
//
|
||||
// {{ $p.Title }}
|
||||
{{ pubIdent $p.Name }} {{ $p.Type }} {{ $p.FieldTag }}
|
||||
{{ end }}
|
||||
}
|
||||
{{ end }}
|
||||
)
|
||||
|
||||
{{- range $a := $.Endpoint.Apis }}
|
||||
// {{ pubIdent "New" $.Endpoint.Entrypoint $a.Name }} request
|
||||
func {{ pubIdent "New" $.Endpoint.Entrypoint $a.Name }}() *{{ pubIdent $.Endpoint.Entrypoint $a.Name }} {
|
||||
return &{{ pubIdent $.Endpoint.Entrypoint $a.Name }}{}
|
||||
}
|
||||
|
||||
// Auditable returns all auditable/loggable parameters
|
||||
func (r {{ pubIdent $.Endpoint.Entrypoint $a.Name }}) Auditable() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
{{- range $p := $a.Params.All }}
|
||||
"{{ $p.Name }}": r.{{ pubIdent $p.Name }},
|
||||
{{- end }}
|
||||
}
|
||||
}
|
||||
|
||||
{{- range $p := $a.Params.All }}
|
||||
// Auditable returns all auditable/loggable parameters
|
||||
func (r {{ pubIdent $.Endpoint.Entrypoint $a.Name }}) Get{{ pubIdent $p.Name }}() {{ $p.Type }} {
|
||||
return r.{{ pubIdent $p.Name }}
|
||||
}
|
||||
{{- end }}
|
||||
|
||||
|
||||
|
||||
// Fill processes request and fills internal variables
|
||||
func (r *{{ pubIdent $.Endpoint.Entrypoint $a.Name }}) Fill(req *http.Request) (err error) {
|
||||
if strings.ToLower(req.Header.Get("content-type")) == "application/json" {
|
||||
err = json.NewDecoder(req.Body).Decode(r)
|
||||
|
||||
switch {
|
||||
case err == io.EOF:
|
||||
err = nil
|
||||
case err != nil:
|
||||
return fmt.Errorf("error parsing http request body: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
{{ if $a.Params.Get }}
|
||||
{
|
||||
// GET params
|
||||
tmp := req.URL.Query()
|
||||
{{ range $p := $a.Params.Get }}
|
||||
{{- if not $p.IsSlice }}
|
||||
if val, ok := tmp["{{ $p.Name }}"]; ok && len(val) > 0 {
|
||||
r.{{ pubIdent $p.Name }}, err = {{ $p.Parser "val[0]" }}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
{{- end }}
|
||||
{{- if $p.IsSlice }}
|
||||
if val, ok := tmp["{{ $p.Name }}[]"]; ok {
|
||||
r.{{ pubIdent $p.Name }}, err = {{ $p.Parser "val" }}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else if val, ok := tmp["{{ $p.Name }}"]; ok {
|
||||
r.{{ pubIdent $p.Name }}, err = {{ $p.Parser "val" }}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
}
|
||||
{{- end }}
|
||||
|
||||
{{ if $a.Params.Post }}
|
||||
{
|
||||
if err = req.ParseForm(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// POST params
|
||||
{{ range $p := $a.Params.Post }}
|
||||
{{ if $p.IsUpload }}
|
||||
if _, r.{{ pubIdent $p.Name }}, err = req.FormFile("{{ $p.Name }}"); err != nil {
|
||||
return fmt.Errorf("error processing uploaded file: %w", err)
|
||||
}
|
||||
{{ else }}
|
||||
{{- if not $p.IsSlice }}
|
||||
if val, ok := req.Form["{{ $p.Name }}"]; ok && len(val) > 0 {
|
||||
r.{{ pubIdent $p.Name }}, err = {{ $p.Parser "val[0]" }}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
{{- end }}
|
||||
{{- if $p.IsSlice }}
|
||||
//if val, ok := req.Form["{{ $p.Name }}[]"]; ok && len(val) > 0 {
|
||||
// r.{{ pubIdent $p.Name }}, err = {{ $p.Parser "val" }}
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
//}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
{{- end }}
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
{{ if $a.Params.Path }}
|
||||
{
|
||||
var val string
|
||||
// path params
|
||||
{{ range $p := $a.Params.Path }}
|
||||
val = chi.URLParam(req, "{{ $p.Name }}")
|
||||
r.{{ pubIdent $p.Name }}, err = {{ $p.Parser "val" }}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
{{- end }}
|
||||
@@ -0,0 +1,74 @@
|
||||
package bulk
|
||||
|
||||
// This file is auto-generated.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// Definitions file that controls how this file is generated:
|
||||
// {{ .Source }}
|
||||
|
||||
import (
|
||||
"context"
|
||||
{{- range $import := $.Import }}
|
||||
{{ normalizeImport $import }}
|
||||
{{- end }}
|
||||
)
|
||||
|
||||
type (
|
||||
{{ unpubIdent $.Types.Singular }}Create struct {
|
||||
Done chan struct{}
|
||||
res *{{ $.Types.GoType }}
|
||||
err error
|
||||
}
|
||||
|
||||
{{ unpubIdent $.Types.Singular }}Update struct {
|
||||
Done chan struct{}
|
||||
res *{{ $.Types.GoType }}
|
||||
err error
|
||||
}
|
||||
|
||||
{{ unpubIdent $.Types.Singular }}Remove struct {
|
||||
Done chan struct{}
|
||||
res *{{ $.Types.GoType }}
|
||||
err error
|
||||
}
|
||||
)
|
||||
|
||||
// Create{{ pubIdent $.Types.Singular }} creates a new {{ pubIdent $.Types.Singular }}
|
||||
// create job that can be pushed to store's transaction handler
|
||||
func Create{{ pubIdent $.Types.Singular }}(res *{{ $.Types.GoType }}) *{{ unpubIdent $.Types.Singular }}Create {
|
||||
return &{{ unpubIdent $.Types.Singular }}Create{res: res}
|
||||
}
|
||||
|
||||
// Do Executes {{ unpubIdent $.Types.Singular }}Create job
|
||||
func (j *{{ unpubIdent $.Types.Singular }}Create) Do(ctx context.Context, s storeInterface) error {
|
||||
j.err = s.Create{{ pubIdent $.Types.Singular }}(ctx, j.res)
|
||||
j.Done <- struct{}{}
|
||||
return j.err
|
||||
}
|
||||
|
||||
// Update{{ pubIdent $.Types.Singular }} creates a new {{ pubIdent $.Types.Singular }}
|
||||
// update job that can be pushed to store's transaction handler
|
||||
func Update{{ pubIdent $.Types.Singular }}(res *{{ $.Types.GoType }}) *{{ unpubIdent $.Types.Singular }}Update {
|
||||
return &{{ unpubIdent $.Types.Singular }}Update{res: res}
|
||||
}
|
||||
|
||||
// Do Executes {{ unpubIdent $.Types.Singular }}Update job
|
||||
func (j *{{ unpubIdent $.Types.Singular }}Update) Do(ctx context.Context, s storeInterface) error {
|
||||
j.err = s.Update{{ pubIdent $.Types.Singular }}(ctx, j.res)
|
||||
j.Done <- struct{}{}
|
||||
return j.err
|
||||
}
|
||||
|
||||
// Remove{{ pubIdent $.Types.Singular }} creates a new {{ pubIdent $.Types.Singular }}
|
||||
// remove job that can be pushed to store's transaction handler
|
||||
func Remove{{ pubIdent $.Types.Singular }}(res *{{ $.Types.GoType }}) *{{ unpubIdent $.Types.Singular }}Remove {
|
||||
return &{{ unpubIdent $.Types.Singular }}Remove{res: res}
|
||||
}
|
||||
|
||||
// Do Executes {{ unpubIdent $.Types.Singular }}Remove job
|
||||
func (j *{{ unpubIdent $.Types.Singular }}Remove) Do(ctx context.Context, s storeInterface) error {
|
||||
j.err = s.Remove{{ pubIdent $.Types.Singular }}(ctx, j.res)
|
||||
j.Done <- struct{}{}
|
||||
return j.err
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package {{ .Package }}
|
||||
|
||||
// This file is auto-generated.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
//
|
||||
// Definitions file that controls how this file is generated:
|
||||
// - {{ .Source }}
|
||||
|
||||
import (
|
||||
"context"
|
||||
{{- range .Import }}
|
||||
{{ normalizeImport . }}
|
||||
{{- end }}
|
||||
)
|
||||
|
||||
type (
|
||||
{{- $Types := .Types }}
|
||||
{{- $Fields := .Fields }}
|
||||
|
||||
{{ unpubIdent .Types.Plural }}Store interface {
|
||||
{{- if not .Search.Disable }}
|
||||
Search{{ pubIdent $Types.Plural }}(ctx context.Context, f {{ $Types.GoFilterType }}) ({{ $Types.GoSetType }}, {{ $Types.GoFilterType }}, error)
|
||||
{{- end }}
|
||||
{{- range .Lookups }}
|
||||
Lookup{{ pubIdent $Types.Singular }}By{{ pubIdent .Suffix }}(ctx context.Context{{- range $field := .Fields }}, {{ cc2underscore $field }} {{ ($field | $Fields.Find).Type }}{{- end }}) (*{{ $Types.GoType }}, error)
|
||||
{{- end }}
|
||||
Create{{ pubIdent $Types.Singular }}(ctx context.Context, rr ... *{{ $Types.GoType }}) error
|
||||
Update{{ pubIdent $Types.Singular }}(ctx context.Context, rr ... *{{ $Types.GoType }}) error
|
||||
PartialUpdate{{ pubIdent $Types.Singular }}(ctx context.Context, onlyColumns []string, rr ... *{{ $Types.GoType }}) error
|
||||
Remove{{ pubIdent $Types.Singular }}(ctx context.Context, rr ... *{{ $Types.GoType }}) error
|
||||
Remove{{ pubIdent $Types.Singular }}By{{ template "primaryKeySuffix" $Fields }}(ctx context.Context {{ template "primaryKeyArgs" $Fields }}) error
|
||||
|
||||
Truncate{{ pubIdent $Types.Plural }}(ctx context.Context) error
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,20 @@
|
||||
package {{ .Package }}
|
||||
|
||||
// This file is auto-generated.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
//
|
||||
// Definitions file that controls how this file is generated:
|
||||
{{- range .Definitions }}
|
||||
// - {{ .Source }}
|
||||
{{- end }}
|
||||
|
||||
type (
|
||||
// Interface combines interfaces of all supported store interfaces
|
||||
storeInterface interface {
|
||||
{{ range .Definitions -}}
|
||||
{{ unpubIdent .Types.Plural }}Store
|
||||
{{ end }}
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
{{- define "primaryKeyArgs" -}}
|
||||
{{- range $field := . -}}
|
||||
{{- if $field.IsPrimaryKey -}}
|
||||
, {{ $field.Arg }} {{ camelCase $field.Type }}
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "primaryKeySuffix" -}}
|
||||
{{- range $field := . }}{{ if $field.IsPrimaryKey }}{{ $field.Field }}{{ end }}{{ end -}}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "partialUpdateArgs" -}}
|
||||
{{- range .Args -}}
|
||||
, {{ .Arg }} {{ .Type }}
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
@@ -0,0 +1,291 @@
|
||||
package rdbms
|
||||
|
||||
// This file is an auto-generated file
|
||||
//
|
||||
// Template: pkg/codegen/assets/store_rdbms.gen.go.tpl
|
||||
// Definitions: {{ .Source }}
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior
|
||||
// and will be lost if the code is regenerated.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/cortezaproject/corteza-server/store"
|
||||
|
||||
{{- range $import := $.Import }}
|
||||
{{ normalizeImport $import }}
|
||||
{{- end }}
|
||||
)
|
||||
|
||||
{{ if not $.Search.Disable }}
|
||||
// Search{{ pubIdent $.Types.Plural }} returns all matching rows
|
||||
//
|
||||
// This function calls convert{{ pubIdent $.Types.Singular }}Filter with the given
|
||||
// {{ $.Types.GoFilterType }} and expects to receive a working squirrel.SelectBuilder
|
||||
func (s Store) Search{{ pubIdent $.Types.Plural }}(ctx context.Context, f {{ $.Types.GoFilterType }}) ({{ $.Types.GoSetType }}, {{ $.Types.GoFilterType }}, error) {
|
||||
{{- if .RDBMS.CustomFilterConverter }}
|
||||
q, err := s.convert{{ pubIdent $.Types.Singular }}Filter(f)
|
||||
if err != nil {
|
||||
return nil, f, err
|
||||
}
|
||||
{{- else }}
|
||||
q := s.Query{{ pubIdent $.Types.Plural }}()
|
||||
{{- end }}
|
||||
|
||||
{{ if $.Search.DisablePaging }}
|
||||
scap := DefaultSliceCapacity
|
||||
{{ else }}
|
||||
q = ApplyPaging(q, f.PageFilter)
|
||||
|
||||
scap := f.PerPage
|
||||
if scap == 0 {
|
||||
scap = DefaultSliceCapacity
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
var (
|
||||
set = make([]*{{ $.Types.GoType }}, 0, scap)
|
||||
res *{{ $.Types.GoType }}
|
||||
)
|
||||
|
||||
return set, f, func() error {
|
||||
{{- if not $.Search.DisablePaging }}
|
||||
if f.Count, err = Count(ctx, s.db, q); err != nil || f.Count == 0 {
|
||||
return err
|
||||
}
|
||||
{{- end }}
|
||||
rows, err := s.Query(ctx, q)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for rows.Next() {
|
||||
if res, err = s.internal{{ pubIdent $.Types.Singular }}RowScanner(rows, rows.Err()); err != nil {
|
||||
if cerr := rows.Close(); cerr != nil {
|
||||
return fmt.Errorf("could not close rows (%v) after scan error: %w", cerr, err)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
set = append(set, res)
|
||||
}
|
||||
|
||||
return rows.Close()
|
||||
}()
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
{{- range $lookup := $.Lookups }}
|
||||
// Lookup{{ pubIdent $.Types.Singular }}By{{ pubIdent $lookup.Suffix }} {{ comment $lookup.Description true -}}
|
||||
func (s Store) Lookup{{ pubIdent $.Types.Singular }}By{{ pubIdent $lookup.Suffix }}(ctx context.Context{{- range $field := $lookup.Fields }}, {{ cc2underscore $field }} {{ ($field | $.Fields.Find).Type }}{{- end }}) (*{{ $.Types.GoType }}, error) {
|
||||
return s.{{ $.Types.Singular }}Lookup(ctx, squirrel.Eq{
|
||||
{{- range $field := $lookup.Fields }}
|
||||
"{{ ($field | $.Fields.Find).AliasedColumn }}": {{ cc2underscore $field }},
|
||||
{{- end }}
|
||||
{{- range $field, $value := $lookup.Filter }}
|
||||
"{{ ($field | $.Fields.Find).AliasedColumn }}": {{ $value }},
|
||||
{{- end }}
|
||||
})
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
// Create{{ pubIdent $.Types.Singular }} creates one or more rows in {{ $.RDBMS.Table }} table
|
||||
func (s Store) Create{{ pubIdent $.Types.Singular }}(ctx context.Context, rr ... *{{ $.Types.GoType }}) error {
|
||||
if len(rr) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return Tx(ctx, s.db, s.config, nil, func(db *sqlx.Tx) (err error) {
|
||||
for _, res := range rr {
|
||||
err = ExecuteSqlizer(ctx, s.DB(), s.Insert(s.{{ $.Types.Singular }}Table()).SetMap(s.internal{{ pubIdent $.Types.Singular }}Encoder(res)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Update{{ pubIdent $.Types.Singular }} updates one or more existing rows in {{ $.RDBMS.Table }}
|
||||
func (s Store) Update{{ pubIdent $.Types.Singular }}(ctx context.Context, rr ... *{{ $.Types.GoType }}) error {
|
||||
return s.PartialUpdate{{ pubIdent $.Types.Singular }}(ctx, nil, rr...)
|
||||
}
|
||||
|
||||
// PartialUpdate{{ pubIdent $.Types.Singular }} updates one or more existing rows in {{ $.RDBMS.Table }}
|
||||
//
|
||||
// It wraps the update into transaction and can perform partial update by providing list of updatable columns
|
||||
func (s Store) PartialUpdate{{ pubIdent $.Types.Singular }}(ctx context.Context, onlyColumns []string, rr ... *{{ $.Types.GoType }}) error {
|
||||
if len(rr) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return Tx(ctx, s.db, s.config, nil, func(db *sqlx.Tx) (err error) {
|
||||
for _, res := range rr {
|
||||
err = s.ExecUpdate{{ pubIdent $.Types.Plural }}(
|
||||
ctx,
|
||||
{{ template "filterByPrimaryKeys" $.Fields }},
|
||||
s.internal{{ pubIdent $.Types.Singular }}Encoder(res).Skip(
|
||||
{{- range $field := $.Fields -}}
|
||||
{{- if $field.IsPrimaryKey -}}
|
||||
{{ printf "%q" $field.Column }},
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
).Only(onlyColumns...))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Remove{{ pubIdent $.Types.Singular }} removes one or more rows from {{ $.RDBMS.Table }} table
|
||||
func (s Store) Remove{{ pubIdent $.Types.Singular }}(ctx context.Context, rr ... *{{ $.Types.GoType }}) error {
|
||||
if len(rr) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return Tx(ctx, s.db, s.config, nil, func(db *sqlx.Tx) (err error) {
|
||||
for _, res := range rr {
|
||||
err = ExecuteSqlizer(ctx, s.DB(), s.Delete(s.{{ $.Types.Singular }}Table({{ printf "%q" .RDBMS.Alias }})).Where({{ template "filterByPrimaryKeys" $.Fields }},))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
// Remove{{ pubIdent $.Types.Singular }}By{{ template "primaryKeySuffix" $.Fields }} removes row from the {{ $.RDBMS.Table }} table
|
||||
func (s Store) Remove{{ pubIdent $.Types.Singular }}By{{ template "primaryKeySuffix" $.Fields }}(ctx context.Context {{ template "primaryKeyArgs" $.Fields }}) error {
|
||||
return ExecuteSqlizer(ctx, s.DB(), s.Delete(s.{{ $.Types.Singular }}Table()).Where({{ template "filterByPrimaryKeysWithArgs" $.Fields }},))
|
||||
}
|
||||
|
||||
|
||||
// Truncate{{ pubIdent $.Types.Plural }} removes all rows from the {{ $.RDBMS.Table }} table
|
||||
func (s Store) Truncate{{ pubIdent $.Types.Plural }}(ctx context.Context) error {
|
||||
return Truncate(ctx, s.DB(), s.{{ $.Types.Singular }}Table())
|
||||
}
|
||||
|
||||
|
||||
// ExecUpdate{{ pubIdent $.Types.Plural }} updates all matched (by cnd) rows in {{ $.RDBMS.Table }} with given data
|
||||
func (s Store) ExecUpdate{{ pubIdent $.Types.Plural }}(ctx context.Context, cnd squirrel.Sqlizer, set store.Payload) error {
|
||||
return ExecuteSqlizer(ctx, s.DB(), s.Update(s.{{ $.Types.Singular }}Table({{ printf "%q" .RDBMS.Alias }})).Where(cnd).SetMap(set))
|
||||
}
|
||||
|
||||
// {{ $.Types.Singular }}Lookup prepares {{ $.Types.Singular }} query and executes it,
|
||||
// returning {{ $.Types.GoType }} (or error)
|
||||
func (s Store) {{ $.Types.Singular }}Lookup(ctx context.Context, cnd squirrel.Sqlizer) (*{{ $.Types.GoType }}, error) {
|
||||
return s.internal{{ $.Types.Singular }}RowScanner(s.QueryRow(ctx, s.Query{{ pubIdent $.Types.Plural }}().Where(cnd)))
|
||||
}
|
||||
|
||||
func (s Store) internal{{ $.Types.Singular }}RowScanner(row rowScanner, err error) (*{{ $.Types.GoType }}, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var res = &{{ $.Types.GoType }}{}
|
||||
if _, has := s.config.RowScanners[{{ printf "%q" (unpubIdent $.Types.Singular) }}]; has {
|
||||
scanner := s.config.RowScanners[{{ printf "%q" (unpubIdent $.Types.Singular) }}].(func(rowScanner, *{{ $.Types.GoType }}) error)
|
||||
err = scanner(row, res)
|
||||
} else {
|
||||
{{- if .RDBMS.CustomRowScanner }}
|
||||
err = s.scan{{ $.Types.Singular }}Row(row, res)
|
||||
{{- else }}
|
||||
err = row.Scan(
|
||||
{{- range $.Fields }}
|
||||
&res.{{ .Field }},
|
||||
{{- end }}
|
||||
)
|
||||
{{- end }}
|
||||
}
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, store.ErrNotFound
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not scan db row for {{ $.Types.Singular }}: %w", err)
|
||||
} else {
|
||||
return res, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Query{{ pubIdent $.Types.Plural }} returns squirrel.SelectBuilder with set table and all columns
|
||||
func (s Store) Query{{ pubIdent $.Types.Plural }}() squirrel.SelectBuilder {
|
||||
return s.Select(s.{{ $.Types.Singular }}Table({{ printf "%q" .RDBMS.Alias }}), s.{{ $.Types.Singular }}Columns({{ printf "%q" $.RDBMS.Alias }})...)
|
||||
}
|
||||
|
||||
// {{ $.Types.Singular }}Table name of the db table
|
||||
func (Store) {{ $.Types.Singular }}Table(aa ... string) string {
|
||||
var alias string
|
||||
if len(aa) > 0 {
|
||||
alias = " AS " + aa[0]
|
||||
}
|
||||
|
||||
return "{{ $.RDBMS.Table }}" + alias
|
||||
}
|
||||
|
||||
// {{ $.Types.Singular }}Columns returns all defined table columns
|
||||
//
|
||||
// With optional string arg, all columns are returned aliased
|
||||
func (Store) {{ $.Types.Singular }}Columns(aa ... string) []string {
|
||||
var alias string
|
||||
if len(aa) > 0 {
|
||||
alias = aa[0] + "."
|
||||
}
|
||||
|
||||
return []string{
|
||||
{{- range $.Fields }}
|
||||
alias + "{{ .Column }}",
|
||||
{{- end }}
|
||||
}
|
||||
}
|
||||
|
||||
// internal{{ pubIdent $.Types.Singular }}Encoder encodes fields from {{ $.Types.GoType }} to store.Payload (map)
|
||||
//
|
||||
// Encoding is done by using generic approach or by calling encode{{ pubIdent $.Types.Singular }}
|
||||
// func when rdbms.customEncoder=true
|
||||
func (s Store) internal{{ pubIdent $.Types.Singular }}Encoder(res *{{ $.Types.GoType }}) store.Payload {
|
||||
{{- if .RDBMS.CustomEncoder }}
|
||||
return s.encode{{ pubIdent $.Types.Singular }}(res)
|
||||
{{- else }}
|
||||
return store.Payload{
|
||||
{{- range $.Fields }}
|
||||
"{{ .Column }}": res.{{ .Field }},
|
||||
{{- end }}
|
||||
}
|
||||
{{- end }}
|
||||
}
|
||||
|
||||
{{/* ************************************************************ */}}
|
||||
|
||||
{{- define "filterByPrimaryKeys" -}}
|
||||
squirrel.Eq{
|
||||
{{- range $field := . -}}
|
||||
{{- if $field.IsPrimaryKey -}}
|
||||
s.preprocessColumn({{ printf "%q" $field.AliasedColumn }}, {{ printf "%q" $field.LookupFilterPreprocess }}): s.preprocessValue(res.{{ $field.Field }}, {{ printf "%q" $field.LookupFilterPreprocess }}),
|
||||
{{ end }}
|
||||
{{- end -}}
|
||||
}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "filterByPrimaryKeysWithArgs" -}}
|
||||
squirrel.Eq{
|
||||
{{- range $field := . }}
|
||||
{{- if $field.IsPrimaryKey -}}
|
||||
s.preprocessColumn({{ printf "%q" $field.AliasedColumn }}, {{ printf "%q" $field.LookupFilterPreprocess }}): s.preprocessValue({{ $field.Arg }}, {{ printf "%q" $field.LookupFilterPreprocess }}),
|
||||
{{ end }}
|
||||
{{ end -}}
|
||||
}
|
||||
{{- end -}}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package tests
|
||||
|
||||
// This file is auto-generated.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
//
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/stretchr/testify/require"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func testAllGenerated(t *testing.T, all interface{}) {
|
||||
{{ range . }}
|
||||
// Run generated tests for {{ .Types.Base }}
|
||||
t.Run({{ printf "%q" .Types.Base }}, func(t *testing.T) {
|
||||
var s = all.({{ unpubIdent .Types.Plural }}Store)
|
||||
require.New(t).NoError(s.Truncate{{ pubIdent .Types.Plural }}(context.Background()))
|
||||
test{{ pubIdent .Types.Base }}(t, s)
|
||||
})
|
||||
{{ end }}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package {{ .Package }}
|
||||
|
||||
// This file is auto-generated.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
//
|
||||
// Definitions file that controls how this file is generated:
|
||||
// {{ .Source }}
|
||||
|
||||
|
||||
{{ if .Imports }}
|
||||
import (
|
||||
{{ range $i, $import := .Imports }}
|
||||
"{{ $import }}"
|
||||
{{ end }}
|
||||
)
|
||||
{{ end }}
|
||||
|
||||
type (
|
||||
{{ range $name, $set := .Types }}
|
||||
// {{ $name }}Set slice of {{ $name }}
|
||||
//
|
||||
// This type is auto-generated.
|
||||
{{ $name }}Set []*{{ $name }}
|
||||
{{ end }}
|
||||
)
|
||||
|
||||
{{ range $name, $set := .Types }}
|
||||
// Walk iterates through every slice item and calls w({{ $name }}) err
|
||||
//
|
||||
// This function is auto-generated.
|
||||
func (set {{ $name }}Set) Walk(w func(*{{ $name }}) error) (err error) {
|
||||
for i := range set {
|
||||
if err = w(set[i]); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Filter iterates through every slice item, calls f({{ $name }}) (bool, err) and return filtered slice
|
||||
//
|
||||
// This function is auto-generated.
|
||||
func (set {{ $name }}Set) Filter(f func(*{{ $name }}) (bool, error)) (out {{ $name }}Set, err error) {
|
||||
var ok bool
|
||||
out = {{ $name }}Set{}
|
||||
for i := range set {
|
||||
if ok, err = f(set[i]); err != nil {
|
||||
return
|
||||
} else if ok {
|
||||
out = append(out, set[i])
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
{{ if not $set.NoIdField }}
|
||||
// FindByID finds items from slice by its ID property
|
||||
//
|
||||
// This function is auto-generated.
|
||||
func (set {{ $name }}Set) FindByID(ID uint64) *{{ $name }} {
|
||||
for i := range set {
|
||||
if set[i].ID == ID {
|
||||
return set[i]
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// IDs returns a slice of uint64s from all items in the set
|
||||
//
|
||||
// This function is auto-generated.
|
||||
func (set {{ $name }}Set) IDs() (IDs []uint64) {
|
||||
IDs = make([]uint64, len(set))
|
||||
|
||||
for i := range set {
|
||||
IDs[i] = set[i].ID
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
|
||||
{{ end }}
|
||||
@@ -0,0 +1,116 @@
|
||||
package {{ .Package }}
|
||||
|
||||
// This file is auto-generated.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
//
|
||||
// Definitions file that controls how this file is generated:
|
||||
// {{ .Source }}
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/stretchr/testify/require"
|
||||
"testing"
|
||||
|
||||
{{ range $i, $import := .Imports }}
|
||||
"{{ $import }}"
|
||||
{{ end }}
|
||||
)
|
||||
|
||||
|
||||
{{ range $name, $set := .Types }}
|
||||
|
||||
func Test{{ $name }}SetWalk(t *testing.T) {
|
||||
var (
|
||||
value = make({{ $name }}Set, 3)
|
||||
req = require.New(t)
|
||||
)
|
||||
|
||||
// check walk with no errors
|
||||
{
|
||||
err := value.Walk(func(*{{ $name }}) error {
|
||||
return nil
|
||||
})
|
||||
req.NoError(err)
|
||||
}
|
||||
|
||||
// check walk with error
|
||||
req.Error(value.Walk(func(*{{ $name }}) error { return fmt.Errorf("walk error") }))
|
||||
}
|
||||
|
||||
func Test{{ $name }}SetFilter(t *testing.T) {
|
||||
var (
|
||||
value = make({{ $name }}Set, 3)
|
||||
req = require.New(t)
|
||||
)
|
||||
|
||||
// filter nothing
|
||||
{
|
||||
set, err := value.Filter(func(*{{ $name }}) (bool, error) {
|
||||
return true, nil
|
||||
})
|
||||
req.NoError(err)
|
||||
req.Equal(len(set), len(value))
|
||||
}
|
||||
|
||||
// filter one item
|
||||
{
|
||||
found := false
|
||||
set, err := value.Filter(func(*{{ $name }}) (bool, error) {
|
||||
if !found {
|
||||
found = true
|
||||
return found, nil
|
||||
}
|
||||
return false, nil
|
||||
})
|
||||
req.NoError(err)
|
||||
req.Len(set, 1)
|
||||
}
|
||||
|
||||
// filter error
|
||||
{
|
||||
_, err := value.Filter(func(*{{ $name }}) (bool, error) {
|
||||
return false, fmt.Errorf("filter error")
|
||||
})
|
||||
req.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
{{ if not $set.NoIdField }}
|
||||
func Test{{ $name }}SetIDs(t *testing.T) {
|
||||
var (
|
||||
value = make({{ $name }}Set, 3)
|
||||
req = require.New(t)
|
||||
)
|
||||
|
||||
// construct objects
|
||||
value[0] = new({{ $name }})
|
||||
value[1] = new({{ $name }})
|
||||
value[2] = new({{ $name }})
|
||||
// set ids
|
||||
value[0].ID = 1
|
||||
value[1].ID = 2
|
||||
value[2].ID = 3
|
||||
|
||||
// Find existing
|
||||
{
|
||||
val := value.FindByID(2)
|
||||
req.Equal(uint64(2), val.ID)
|
||||
}
|
||||
|
||||
// Find non-existing
|
||||
{
|
||||
val := value.FindByID(4)
|
||||
req.Nil(val)
|
||||
}
|
||||
|
||||
// List IDs from set
|
||||
{
|
||||
val := value.IDs()
|
||||
req.Equal(len(val), len(value))
|
||||
}
|
||||
}
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
Reference in New Issue
Block a user