summaryrefslogtreecommitdiff
path: root/vendor/github.com/uptrace/bun/dialect/pgdialect/append.go
blob: c95fa86e79b75c3b5431763cefed24355961c892 (plain)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package pgdialect

import (
	"database/sql/driver"
	"fmt"
	"reflect"
	"time"

	"github.com/uptrace/bun/dialect"
	"github.com/uptrace/bun/schema"
)

var (
	driverValuerType = reflect.TypeOf((*driver.Valuer)(nil)).Elem()

	stringType      = reflect.TypeOf((*string)(nil)).Elem()
	sliceStringType = reflect.TypeOf([]string(nil))

	intType      = reflect.TypeOf((*int)(nil)).Elem()
	sliceIntType = reflect.TypeOf([]int(nil))

	int64Type      = reflect.TypeOf((*int64)(nil)).Elem()
	sliceInt64Type = reflect.TypeOf([]int64(nil))

	float64Type      = reflect.TypeOf((*float64)(nil)).Elem()
	sliceFloat64Type = reflect.TypeOf([]float64(nil))

	timeType      = reflect.TypeOf((*time.Time)(nil)).Elem()
	sliceTimeType = reflect.TypeOf([]time.Time(nil))
)

func appendTime(buf []byte, tm time.Time) []byte {
	return tm.UTC().AppendFormat(buf, "2006-01-02 15:04:05.999999-07:00")
}

var mapStringStringType = reflect.TypeOf(map[string]string(nil))

func (d *Dialect) hstoreAppender(typ reflect.Type) schema.AppenderFunc {
	kind := typ.Kind()

	switch kind {
	case reflect.Ptr:
		if fn := d.hstoreAppender(typ.Elem()); fn != nil {
			return schema.PtrAppender(fn)
		}
	case reflect.Map:
		// ok:
	default:
		return nil
	}

	if typ.Key() == stringType && typ.Elem() == stringType {
		return appendMapStringStringValue
	}

	return func(fmter schema.Formatter, b []byte, v reflect.Value) []byte {
		err := fmt.Errorf("bun: Hstore(unsupported %s)", v.Type())
		return dialect.AppendError(b, err)
	}
}

func appendMapStringString(b []byte, m map[string]string) []byte {
	if m == nil {
		return dialect.AppendNull(b)
	}

	b = append(b, '\'')

	for key, value := range m {
		b = arrayAppendString(b, key)
		b = append(b, '=', '>')
		b = arrayAppendString(b, value)
		b = append(b, ',')
	}
	if len(m) > 0 {
		b = b[:len(b)-1] // Strip trailing comma.
	}

	b = append(b, '\'')

	return b
}

func appendMapStringStringValue(fmter schema.Formatter, b []byte, v reflect.Value) []byte {
	m := v.Convert(mapStringStringType).Interface().(map[string]string)
	return appendMapStringString(b, m)
}