Repository navigation
Expand file tree
/
Copy pathpgsql_convert.go
More file actions
247 lines (224 loc) · 8.34 KB
/
Copy pathpgsql_convert.go
File metadata and controls
247 lines (224 loc) · 8.34 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package pgsql
import (
"context"
"fmt"
"reflect"
"strings"
"time"
"github.com/google/uuid"
"github.com/lib/pq"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/text/gregex"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
)
// ConvertValueForField converts value to database acceptable value.
func (d *Driver) ConvertValueForField(ctx context.Context, fieldType string, fieldValue any) (any, error) {
if g.IsNil(fieldValue) {
return d.Core.ConvertValueForField(ctx, fieldType, fieldValue)
}
var fieldValueKind = reflect.TypeOf(fieldValue).Kind()
if fieldValueKind == reflect.Slice {
// For bytea type, pass []byte directly without any conversion.
if _, ok := fieldValue.([]byte); ok && gstr.Contains(fieldType, "bytea") {
return d.Core.ConvertValueForField(ctx, fieldType, fieldValue)
}
// For pgsql, json or jsonb require '[]'
if !gstr.Contains(fieldType, "json") {
fieldValue = gstr.ReplaceByMap(gconv.String(fieldValue),
map[string]string{
"[": "{",
"]": "}",
},
)
}
}
return d.Core.ConvertValueForField(ctx, fieldType, fieldValue)
}
// CheckLocalTypeForField checks and returns corresponding local golang type for given db type.
// The parameter `fieldType` is in lower case, like:
// `int2`, `int4`, `int8`, `_int2`, `_int4`, `_int8`, `_float4`, `_float8`, etc.
//
// The type name is looked up in localTypeMap, which lists every name the underlying driver
// can report. Only a name absent from it, such as a type the server knows but the driver
// does not, falls back to the core. So does `bit`, whose local type depends on its precision
// rather than its name: the core takes bit(1) as a boolean.
func (d *Driver) CheckLocalTypeForField(ctx context.Context, fieldType string, fieldValue any) (gdb.LocalType, error) {
var typeName string
match, _ := gregex.MatchString(`(.+?)\((.+)\)`, fieldType)
if len(match) == 3 {
typeName = gstr.Trim(match[1])
} else {
typeName = fieldType
}
typeName = strings.ToLower(typeName)
if typeName == "bit" {
return d.Core.CheckLocalTypeForField(ctx, fieldType, fieldValue)
}
if localType, ok := localTypeMap[typeName]; ok {
return localType, nil
}
return d.Core.CheckLocalTypeForField(ctx, fieldType, fieldValue)
}
// ConvertValueForLocal converts value to local Golang type of value according field type name from database.
// The parameter `fieldType` is in lower case, like:
// `int2`, `int4`, `int8`, `_int2`, `_int4`, `_int8`, `uuid`, `_uuid`, etc.
//
// See: https://www.postgresql.org/docs/current/datatype.html
//
// PostgreSQL type mapping:
//
// | PostgreSQL Type | SQL Type | pq Type | Go Type |
// |-----------------|--------------------------------|-----------------|-------------|
// | int2 | int2, smallint | - | int |
// | int4 | int4, integer | - | int |
// | int8 | int8, bigint, bigserial | - | int64 |
// | uuid | uuid | - | uuid.UUID |
// | _int2 | int2[], smallint[] | pq.Int32Array | []int32 |
// | _int4 | int4[], integer[] | pq.Int32Array | []int32 |
// | _int8 | int8[], bigint[] | pq.Int64Array | []int64 |
// | _float4 | float4[], real[] | pq.Float32Array | []float32 |
// | _float8 | float8[], double precision[] | pq.Float64Array | []float64 |
// | _bool | boolean[], bool[] | pq.BoolArray | []bool |
// | _varchar | varchar[], character varying[] | pq.StringArray | []string |
// | _text | text[] | pq.StringArray | []string |
// | _char, _bpchar | char[], character[] | pq.StringArray | []string |
// | _numeric | numeric[] | pq.Float64Array | []float64 |
// | _decimal | decimal[] | pq.Float64Array | []float64 |
// | _money | money[] | pq.Float64Array | []float64 |
// | bytea | bytea | - | []byte |
// | _bytea | bytea[] | pq.ByteaArray | [][]byte |
// | _uuid | uuid[] | pq.StringArray | []uuid.UUID |
// | timetz | time with time zone | time.Time | string |
//
// Note: _date, _timestamp and _timestamptz are mapped in localTypeMap and read back as
// []string, one element per array member. _json and _jsonb map to a single string on
// purpose: pq has no scanner for them, so the whole array literal is returned as text.
func (d *Driver) ConvertValueForLocal(ctx context.Context, fieldType string, fieldValue any) (any, error) {
if isTimeTZFieldType(fieldType) {
switch value := fieldValue.(type) {
case time.Time:
return formatTimeTZValue(value), nil
case []byte:
return string(value), nil
case string:
return value, nil
}
}
localType, err := d.CheckLocalTypeForField(ctx, fieldType, fieldValue)
if err != nil {
return nil, err
}
// Dispatching on the local type, rather than on the type name again, keeps this in step
// with localTypeMap: a type name is classified in one place only.
switch localType {
case gdb.LocalTypeBytes:
if v, ok := fieldValue.([]byte); ok {
return v, nil
}
return fieldValue, nil
case gdb.LocalTypeInt32Slice:
var result pq.Int32Array
if err = result.Scan(fieldValue); err != nil {
return nil, err
}
return []int32(result), nil
case gdb.LocalTypeInt64Slice:
var result pq.Int64Array
if err = result.Scan(fieldValue); err != nil {
return nil, err
}
return []int64(result), nil
case gdb.LocalTypeFloat32Slice:
var result pq.Float32Array
if err = result.Scan(fieldValue); err != nil {
return nil, err
}
return []float32(result), nil
case gdb.LocalTypeFloat64Slice:
var result pq.Float64Array
if err = result.Scan(fieldValue); err != nil {
return nil, err
}
return []float64(result), nil
case gdb.LocalTypeBoolSlice:
var result pq.BoolArray
if err = result.Scan(fieldValue); err != nil {
return nil, err
}
return []bool(result), nil
case gdb.LocalTypeStringSlice:
// Arrays without a dedicated pq scanner, such as the geometric, interval, range
// and temporal ones, are read as the text representation of their elements.
var result pq.StringArray
if err = result.Scan(fieldValue); err != nil {
return nil, err
}
return []string(result), nil
case gdb.LocalTypeUUID:
var uuidStr string
switch v := fieldValue.(type) {
case []byte:
uuidStr = string(v)
case string:
uuidStr = v
default:
uuidStr = gconv.String(fieldValue)
}
result, err := uuid.Parse(uuidStr)
if err != nil {
return nil, err
}
return result, nil
case gdb.LocalTypeUUIDSlice:
var strArray pq.StringArray
if err = strArray.Scan(fieldValue); err != nil {
return nil, err
}
result := make([]uuid.UUID, len(strArray))
for i, s := range strArray {
parsed, err := uuid.Parse(s)
if err != nil {
return nil, err
}
result[i] = parsed
}
return result, nil
case gdb.LocalTypeBytesSlice:
var result pq.ByteaArray
if err = result.Scan(fieldValue); err != nil {
return nil, err
}
return [][]byte(result), nil
default:
return d.Core.ConvertValueForLocal(ctx, fieldType, fieldValue)
}
}
// isTimeTZFieldType reports whether the database field type is timetz.
func isTimeTZFieldType(fieldType string) bool {
typeName, _, _ := strings.Cut(strings.ToLower(strings.TrimSpace(fieldType)), "(")
return typeName == "timetz"
}
// formatTimeTZValue formats a time-of-day with its numeric UTC offset.
func formatTimeTZValue(value time.Time) string {
_, offset := value.Zone()
sign := "+"
if offset < 0 {
sign = "-"
offset = -offset
}
result := value.Format("15:04:05.999999999") + fmt.Sprintf("%s%02d", sign, offset/3600)
if offset%3600 != 0 {
result += fmt.Sprintf(":%02d", offset%3600/60)
}
if offset%60 != 0 {
result += fmt.Sprintf(":%02d", offset%60)
}
return result
}