forked from sijms/go-ora
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathudt.go
410 lines (397 loc) · 11.2 KB
/
udt.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
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
package go_ora
import (
"database/sql/driver"
"errors"
"fmt"
"github.com/sijms/go-ora/v2/converters"
"io"
"reflect"
"strings"
)
type customType struct {
owner string
name string
attribs []ParameterInfo
typ reflect.Type
toid []byte // type oid
filedMap map[string]int
}
// RegisterType register user defined type with owner equal to user id
func (conn *Connection) RegisterType(typeName string, typeObj interface{}) error {
return conn.RegisterTypeWithOwner(conn.connOption.UserID, typeName, typeObj)
}
// RegisterTypeWithOwner take typename, owner and go type object and make an information
// structure that used to create a new type during query and store values in it
//
// DataType of UDT field that can be manipulated by this function are: NUMBER,
// VARCHAR2, NVARCHAR2, TIMESTAMP, DATE AND RAW
func (conn *Connection) RegisterTypeWithOwner(owner, typeName string, typeObj interface{}) error {
if typeObj == nil {
return errors.New("type object cannot be nil")
}
typ := reflect.TypeOf(typeObj)
switch typ.Kind() {
case reflect.Ptr:
return errors.New("unsupported type object: Ptr")
case reflect.Array:
return errors.New("unsupported type object: Array")
case reflect.Chan:
return errors.New("unsupported type object: Chan")
case reflect.Map:
return errors.New("unsupported type object: Map")
case reflect.Slice:
return errors.New("unsupported type object: Slice")
}
if typ.Kind() != reflect.Struct {
return errors.New("type object should be of structure type")
}
cust := customType{
owner: owner,
name: typeName,
typ: typ,
filedMap: map[string]int{},
}
err := cust.getTOID(conn)
if err != nil {
return err
}
sqlText := `SELECT ATTR_NAME, ATTR_TYPE_NAME, LENGTH, ATTR_NO
FROM ALL_TYPE_ATTRS WHERE UPPER(OWNER)=:1 AND UPPER(TYPE_NAME)=:2`
stmt := NewStmt(sqlText, conn)
defer func(stmt *Stmt) {
_ = stmt.Close()
}(stmt)
err = stmt.AddParam("1", strings.ToUpper(owner), 40, Input)
if err != nil {
return err
}
err = stmt.AddParam("2", strings.ToUpper(typeName), 40, Input)
if err != nil {
return err
}
values := make([]driver.Value, 4)
rows, err := stmt.Query(nil)
if err != nil {
return err
}
var (
attName string
attOrder int64
attTypeName string
length int64
ok bool
)
for {
err = rows.Next(values)
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return err
}
if attName, ok = values[0].(string); !ok {
return errors.New(fmt.Sprint("error reading attribute properties for type: ", typeName))
}
if attTypeName, ok = values[1].(string); !ok {
return errors.New(fmt.Sprint("error reading attribute properties for type: ", typeName))
}
if values[2] == nil {
length = 0
} else {
if length, ok = values[2].(int64); !ok {
return fmt.Errorf("error reading attribute properties for type: %s", typeName)
}
}
if attOrder, ok = values[3].(int64); !ok {
return fmt.Errorf("error reading attribute properties for type: %s", typeName)
}
for int(attOrder) > len(cust.attribs) {
cust.attribs = append(cust.attribs, ParameterInfo{
Direction: Input,
Flag: 3,
CharsetID: conn.tcpNego.ServerCharset,
CharsetForm: 1,
})
}
param := &cust.attribs[attOrder-1]
param.Name = attName
param.TypeName = attTypeName
switch strings.ToUpper(attTypeName) {
case "NUMBER":
param.setForNumber()
case "VARCHAR2":
param.DataType = NCHAR
param.CharsetForm = 1
param.ContFlag = 16
param.MaxCharLen = int(length)
param.MaxLen = int(length) * converters.MaxBytePerChar(param.CharsetID)
case "NVARCHAR2":
param.DataType = NCHAR
param.CharsetForm = 2
param.ContFlag = 16
param.MaxCharLen = int(length)
param.MaxLen = int(length) * converters.MaxBytePerChar(param.CharsetID)
case "TIMESTAMP":
fallthrough
case "DATE":
param.DataType = DATE
param.ContFlag = 0
param.MaxLen = 11
//param.MaxCharLen = 11
case "RAW":
param.DataType = RAW
param.ContFlag = 0
param.MaxLen = int(length)
param.MaxCharLen = 0
param.CharsetForm = 0
default:
return fmt.Errorf("unsupported attribute type: %s", attTypeName)
}
}
if len(cust.attribs) == 0 {
return fmt.Errorf("unknown or empty type: %s", typeName)
}
cust.loadFieldMap()
conn.cusTyp[strings.ToUpper(typeName)] = cust
return nil
}
// RegisterType2 same as RegisterType but get user defined type data
// with pl/sql package function: dbms_pickler.get_type_shape
//
// DataType of UDT field that can be manipulated by this function are: NUMBER,
// VARCHAR2, NVARCHAR2, TIMESTAMP, DATE AND RAW
func (conn *Connection) RegisterType2(typeName string, typeObj interface{}) error {
if typeObj == nil {
return errors.New("type object cannot be nil")
}
typ := reflect.TypeOf(typeObj)
switch typ.Kind() {
case reflect.Ptr:
return errors.New("unsupported type object: Ptr")
case reflect.Array:
return errors.New("unsupported type object: Array")
case reflect.Chan:
return errors.New("unsupported type object: Chan")
case reflect.Map:
return errors.New("unsupported type object: Map")
case reflect.Slice:
return errors.New("unsupported type object: Slice")
}
if typ.Kind() != reflect.Struct {
return errors.New("type object should be of structure type")
}
cust := customType{typ: typ, filedMap: map[string]int{}}
sqlText := `
DECLARE
toid raw(128);
vers number;
tds long raw;
instantiable varchar(100);
supertype_owner varchar(100);
supertype_name varchar(100);
attr_rc sys_refcursor;
subtype_rc sys_refcursor;
retVal number;
BEGIN
:retVal := dbms_pickler.get_type_shape(:typeName, toid, vers, tds,
instantiable, supertype_owner, supertype_name, :att_rc, subtype_rc);
END;`
stmt := NewStmt(sqlText, conn)
defer func(stmt *Stmt) {
_ = stmt.Close()
}(stmt)
stmt.AddParam("retVal", 0, 8, Output)
stmt.AddParam("typeName", typeName, 40, Input)
stmt.AddRefCursorParam("att_rc")
_, err := stmt.Exec(nil)
if err != nil {
return err
}
if stmt.Pars[0].Value.(int64) != 0 {
return errors.New(fmt.Sprint("unknown type: ", typeName))
}
if cursor, ok := stmt.Pars[2].Value.(RefCursor); ok {
defer func(cursor *RefCursor) {
_ = cursor.Close()
}(&cursor)
rows, err := cursor.Query()
if err != nil {
return err
}
var (
attName string
attOrder int64
attTypeName string
)
values := make([]driver.Value, 10)
for {
err = rows.Next(values)
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return err
}
// check for error and if == io.EOF break
if attName, ok = values[1].(string); !ok {
return errors.New(fmt.Sprint("error reading attribute properties for type: ", typeName))
}
if attOrder, ok = values[2].(int64); !ok {
return errors.New(fmt.Sprint("error reading attribute properties for type: ", typeName))
}
if attTypeName, ok = values[3].(string); !ok {
return errors.New(fmt.Sprint("error reading attribute properties for type: ", typeName))
}
//fmt.Println(attOrder, "\t", attName, "\t", attTypeName)
for int(attOrder) > len(cust.attribs) {
cust.attribs = append(cust.attribs, ParameterInfo{
Direction: Input,
Flag: 3,
CharsetID: conn.tcpNego.ServerCharset,
CharsetForm: 1,
})
}
param := &cust.attribs[attOrder-1]
param.Name = attName
param.TypeName = attTypeName
switch strings.ToUpper(attTypeName) {
case "NUMBER":
param.DataType = NUMBER
param.ContFlag = 0
param.MaxCharLen = 0
param.MaxLen = 22
param.CharsetForm = 0
case "VARCHAR2":
param.DataType = NCHAR
param.CharsetForm = 1
param.ContFlag = 16
param.MaxCharLen = 1000
param.MaxLen = 1000 * converters.MaxBytePerChar(param.CharsetID)
case "NVARCHAR2":
param.DataType = NCHAR
param.CharsetForm = 2
param.ContFlag = 16
param.MaxCharLen = 1000
param.MaxLen = 1000 * converters.MaxBytePerChar(param.CharsetID)
case "TIMESTAMP":
fallthrough
case "DATE":
param.DataType = DATE
param.ContFlag = 0
param.MaxLen = 11
param.MaxCharLen = 11
case "RAW":
param.DataType = RAW
param.ContFlag = 0
param.MaxLen = 1000
param.MaxCharLen = 0
param.CharsetForm = 0
default:
return errors.New(fmt.Sprint("unsupported attribute type: ", attTypeName))
}
}
}
cust.loadFieldMap()
conn.cusTyp[strings.ToUpper(typeName)] = cust
return nil
}
func (cust *customType) getTOID(conn *Connection) error {
sqlText := `SELECT type_oid FROM ALL_TYPES WHERE UPPER(OWNER)=:1 AND UPPER(TYPE_NAME)=:2`
stmt := NewStmt(sqlText, conn)
defer func(stmt *Stmt) {
_ = stmt.Close()
}(stmt)
stmt.AddParam("1", strings.ToUpper(cust.owner), 0, Input)
stmt.AddParam("2", strings.ToUpper(cust.name), 0, Input)
rows, err := stmt.Query_(nil)
if err != nil {
return err
}
if rows.Next_() {
err = rows.Scan(&cust.toid)
if err != nil {
return err
}
}
if len(cust.toid) == 0 {
return fmt.Errorf("unknown type: %s", cust.name)
}
return rows.Err()
}
// loadFieldMap read struct tag that supplied with golang type object passed in RegisterType
// function
func (cust *customType) loadFieldMap() {
typ := cust.typ
for x := 0; x < typ.NumField(); x++ {
f := typ.Field(x)
tag := f.Tag.Get("oracle")
if len(tag) == 0 {
continue
}
tag = strings.Trim(tag, "\"")
parts := strings.Split(tag, ",")
for _, part := range parts {
subs := strings.Split(part, ":")
if len(subs) == 0 {
continue
}
if strings.TrimSpace(strings.ToLower(subs[0])) == "name" {
if len(subs) == 1 {
continue
}
fieldID := strings.TrimSpace(strings.ToUpper(subs[1]))
cust.filedMap[fieldID] = x
}
}
}
}
// getObject return an object of Golang type supplied in RegisterType function
// the object is filled with data from attrib []ParameterInfo
// which is filled inside Stmt during data reading
func (cust *customType) getObject() interface{} {
typ := cust.typ
obj := reflect.New(typ)
for _, attrib := range cust.attribs {
if fieldIndex, ok := cust.filedMap[attrib.Name]; ok {
if attrib.Value != nil {
//tempField := obj.Elem().Field(fieldIndex)
//err := setValue(&tempField, attrib.Value)
//if err != nil {
// panic(err)
//}
tempPar := ParameterInfo{Value: obj.Elem().Field(fieldIndex).Interface()}
err := tempPar.setParameterValue(attrib.Value)
if err != nil {
return err
}
obj.Elem().Field(fieldIndex).Set(reflect.ValueOf(tempPar.Value))
}
}
}
return obj.Elem().Interface()
}
//func (cust *customType) getFieldRepr(index int, input_value interface{}) ([]byte, error) {
// attrib := cust.attribs[index]
// //typ := reflect.TypeOf(val)
// val := reflect.ValueOf(input_value)
// typ := val.Type()
// switch attrib.DataType {
// case NUMBER:
// switch typ.Kind() {
// case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
// fallthrough
// case reflect.Int, reflect.Int32, reflect.Int16, reflect.Int64, reflect.Int8:
// return converters.EncodeInt64(reflect.ValueOf(val).Int()), nil
// case reflect.Float32, reflect.Float64:
// return converters.EncodeDouble(reflect.ValueOf(val).Float())
// default:
// return nil, fmt.Errorf("field %d require NUMBER data type", index)
// }
// case DATE:
// if typ == reflect.TypeOf(time.Time{}) {
// //return converters.EncodeDate(val.Interface())
// }
//
// }
// return nil, nil
//}