-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomputed_field.go
65 lines (56 loc) · 1.72 KB
/
computed_field.go
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
58
59
60
61
62
63
64
65
package pgtalk
import (
"fmt"
)
// SQLAs returns a ColumnAccessor with a customer SQL expression.
//
// The named result will be available using the GetExpressionResult method of the record type.
func SQLAs(sql, name string) *computedField {
return &computedField{
ResultName: name,
Expression: expressionSource{SQL: sql},
}
}
type expressionSource struct {
unimplementedBooleanExpression
SQL string
}
// SQLOn is part of SQLWriter
func (e expressionSource) SQLOn(w WriteContext) {
fmt.Fprintf(w, "(%s)", e.SQL)
}
// computedField is a ColumnAccessor for read.
type computedField struct {
ResultName string
Expression SQLExpression
}
func (c *computedField) SQLOn(w WriteContext) {
c.Expression.SQLOn(w)
fmt.Fprintf(w, " AS %s", c.ResultName)
}
func (c *computedField) Name() string { return c.ResultName }
func (c *computedField) ValueToInsert() any { return nil }
func (c *computedField) Column() ColumnInfo { return ColumnInfo{columnName: c.ResultName} }
// FieldValueToScan returns the address of the value of the field in the entity
func (c *computedField) FieldValueToScan(entity any) any {
var value any
if h, ok := entity.(expressionValueHolder); ok {
// side effect to update the entity custom expressions
h.AddExpressionResult(c.ResultName, &value)
}
return &value
}
// AppendScannable collects values for scanning by a result Row
// Cannot use ValueToInsert because that looses type information such that the Scanner will use default mapping
func (c *computedField) AppendScannable(list []any) []any {
var value any
return append(list, &value)
}
// Get accesses the value from a map.
func (c *computedField) Get(values map[string]any) any {
v, ok := values[c.ResultName]
if !ok {
return nil
}
return v
}