forked from xo/xo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgres.index.go.tpl
58 lines (49 loc) · 1.39 KB
/
postgres.index.go.tpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
{{- $short := (shortname .Type.Name "err" "sqlstr" "db" "q" "res" "XOLog" .Fields) -}}
{{- $table := (schema .Schema .Type.Table.TableName) -}}
// {{ .FuncName }} retrieves a row from '{{ $table }}' as a {{ .Type.Name }}.
//
// Generated from index '{{ .Index.IndexName }}'.
func {{ .FuncName }}(db XODB{{ goparamlist .Fields true true }}) ({{ if not .Index.IsUnique }}[]{{ end }}*{{ .Type.Name }}, error) {
var err error
// sql query
const sqlstr = `SELECT ` +
`{{ colnames .Type.Fields }} ` +
`FROM {{ $table }} ` +
`WHERE {{ colnamesquery .Fields " AND " }}`
// run query
XOLog(sqlstr{{ goparamlist .Fields true false }})
{{- if .Index.IsUnique }}
{{ $short }} := {{ .Type.Name }}{
{{- if .Type.PrimaryKey }}
_exists: true,
{{ end -}}
}
err = db.QueryRow(sqlstr{{ goparamlist .Fields true false }}).Scan({{ fieldnames .Type.Fields (print "&" $short) }})
if err != nil {
return nil, err
}
return &{{ $short }}, nil
{{- else }}
q, err := db.Query(sqlstr{{ goparamlist .Fields true false }})
if err != nil {
return nil, err
}
defer q.Close()
// load results
res := []*{{ .Type.Name }}{}
for q.Next() {
{{ $short }} := {{ .Type.Name }}{
{{- if .Type.PrimaryKey }}
_exists: true,
{{ end -}}
}
// scan
err = q.Scan({{ fieldnames .Type.Fields (print "&" $short) }})
if err != nil {
return nil, err
}
res = append(res, &{{ $short }})
}
return res, nil
{{- end }}
}