jet/execution/execution.go

872 lines
20 KiB
Go
Raw Normal View History

package execution
import (
2019-06-20 12:22:19 +02:00
"context"
"database/sql"
2019-03-16 14:02:45 +01:00
"database/sql/driver"
"errors"
2019-03-14 09:18:23 +01:00
"fmt"
2019-06-23 18:55:57 +02:00
"github.com/go-jet/jet/execution/internal"
2019-07-20 17:44:43 +02:00
"github.com/go-jet/jet/internal/utils"
2019-07-29 18:08:53 +02:00
"github.com/google/uuid"
"reflect"
2019-03-15 21:55:43 +01:00
"strconv"
2019-03-14 09:18:23 +01:00
"strings"
2019-03-09 14:20:44 +01:00
"time"
)
// Query executes query with arguments over database connection with context and stores result into destination.
// Destination can be either pointer to struct or pointer to slice of structs.
2019-07-19 10:46:41 +02:00
func Query(context context.Context, db DB, query string, args []interface{}, destinationPtr interface{}) error {
2019-05-20 17:37:55 +02:00
2019-07-20 17:44:43 +02:00
if utils.IsNil(destinationPtr) {
return errors.New("jet: Destination is nil")
2019-05-20 17:37:55 +02:00
}
destinationPtrType := reflect.TypeOf(destinationPtr)
if destinationPtrType.Kind() != reflect.Ptr {
2019-07-08 13:00:44 +02:00
return errors.New("jet: Destination has to be a pointer to slice or pointer to struct")
2019-05-20 17:37:55 +02:00
}
if destinationPtrType.Elem().Kind() == reflect.Slice {
2019-07-19 10:46:41 +02:00
return queryToSlice(context, db, query, args, destinationPtr)
2019-05-20 17:37:55 +02:00
} else if destinationPtrType.Elem().Kind() == reflect.Struct {
tempSlicePtrValue := reflect.New(reflect.SliceOf(destinationPtrType))
tempSliceValue := tempSlicePtrValue.Elem()
2019-07-19 10:46:41 +02:00
err := queryToSlice(context, db, query, args, tempSlicePtrValue.Interface())
2019-05-20 17:37:55 +02:00
if err != nil {
return err
}
if tempSliceValue.Len() == 0 {
return nil
}
structValue := reflect.ValueOf(destinationPtr).Elem()
firstTempStruct := tempSliceValue.Index(0).Elem()
if structValue.Type().AssignableTo(firstTempStruct.Type()) {
structValue.Set(tempSliceValue.Index(0).Elem())
}
return nil
} else {
2019-07-08 13:00:44 +02:00
return errors.New("jet: unsupported destination type")
2019-05-20 17:37:55 +02:00
}
}
2019-07-19 10:46:41 +02:00
func queryToSlice(ctx context.Context, db DB, query string, args []interface{}, slicePtr interface{}) error {
if db == nil {
2019-07-08 13:00:44 +02:00
return errors.New("jet: db is nil")
}
2019-05-20 17:37:55 +02:00
if slicePtr == nil {
2019-07-08 13:00:44 +02:00
return errors.New("jet: Destination is nil. ")
}
2019-05-20 17:37:55 +02:00
destinationType := reflect.TypeOf(slicePtr)
if destinationType.Kind() != reflect.Ptr && destinationType.Elem().Kind() != reflect.Slice {
2019-07-08 13:00:44 +02:00
return errors.New("jet: Destination has to be a pointer to slice. ")
}
2019-06-20 12:22:19 +02:00
if ctx == nil {
ctx = context.Background()
}
rows, err := db.QueryContext(ctx, query, args...)
if err != nil {
return err
}
2019-03-09 14:20:44 +01:00
defer rows.Close()
2019-05-20 17:37:55 +02:00
scanContext, err := newScanContext(rows)
2019-03-14 09:18:23 +01:00
2019-05-20 17:37:55 +02:00
if err != nil {
return err
2019-03-14 09:18:23 +01:00
}
2019-05-20 17:37:55 +02:00
if len(scanContext.row) == 0 {
return nil
}
slicePtrValue := reflect.ValueOf(slicePtr)
for rows.Next() {
2019-04-04 13:07:21 +02:00
err := rows.Scan(scanContext.row...)
if err != nil {
return err
}
2019-03-15 21:55:43 +01:00
scanContext.rowNum++
_, err = mapRowToSlice(scanContext, "", slicePtrValue, nil)
2019-05-20 17:37:55 +02:00
if err != nil {
return err
}
}
err = rows.Close()
if err != nil {
return err
}
err = rows.Err()
if err != nil {
return err
}
return nil
}
2019-07-13 13:17:28 +02:00
func mapRowToSlice(scanContext *scanContext, groupKey string, slicePtrValue reflect.Value, field *reflect.StructField) (updated bool, err error) {
2019-04-04 13:07:21 +02:00
2019-05-20 17:37:55 +02:00
sliceElemType := getSliceElemType(slicePtrValue)
2019-03-14 09:18:23 +01:00
2019-07-29 18:08:53 +02:00
if isSimpleModelType(sliceElemType) {
2019-07-13 13:17:28 +02:00
updated, err = mapRowToBaseTypeSlice(scanContext, slicePtrValue, field)
2019-05-20 17:37:55 +02:00
return
2019-03-14 09:18:23 +01:00
}
2019-05-20 17:37:55 +02:00
if sliceElemType.Kind() != reflect.Struct {
2019-07-13 13:17:28 +02:00
return false, errors.New("jet: Unsupported dest type: " + field.Name + " " + field.Type.String())
2019-05-20 17:37:55 +02:00
}
2019-03-14 09:18:23 +01:00
2019-07-13 13:17:28 +02:00
structGroupKey := scanContext.getGroupKey(sliceElemType, field)
2019-03-30 09:59:24 +01:00
2019-07-13 13:17:28 +02:00
groupKey = groupKey + "," + structGroupKey
2019-03-30 09:59:24 +01:00
index, ok := scanContext.uniqueDestObjectsMap[groupKey]
2019-03-30 09:59:24 +01:00
2019-05-20 17:37:55 +02:00
if ok {
structPtrValue := getSliceElemPtrAt(slicePtrValue, index)
2019-03-30 09:59:24 +01:00
2019-07-13 13:17:28 +02:00
return mapRowToStruct(scanContext, groupKey, structPtrValue, field, true)
}
2019-03-30 09:59:24 +01:00
destinationStructPtr := newElemPtrValueForSlice(slicePtrValue)
2019-03-30 09:59:24 +01:00
updated, err = mapRowToStruct(scanContext, groupKey, destinationStructPtr, field)
2019-05-20 17:37:55 +02:00
if err != nil {
return
}
2019-05-22 11:28:32 +02:00
if updated {
scanContext.uniqueDestObjectsMap[groupKey] = slicePtrValue.Elem().Len()
err = appendElemToSlice(slicePtrValue, destinationStructPtr)
if err != nil {
return
2019-05-20 17:37:55 +02:00
}
2019-03-30 09:59:24 +01:00
}
2019-05-20 17:37:55 +02:00
return
}
2019-07-13 13:17:28 +02:00
func mapRowToBaseTypeSlice(scanContext *scanContext, slicePtrValue reflect.Value, field *reflect.StructField) (updated bool, err error) {
index := 0
if field != nil {
typeName, columnName := getTypeAndFieldName("", *field)
if index = scanContext.typeToColumnIndex(typeName, columnName); index < 0 {
return
}
}
rowElemPtr := scanContext.rowElemValuePtr(index)
2019-03-14 09:18:23 +01:00
2019-07-13 13:17:28 +02:00
if !rowElemPtr.IsNil() {
updated = true
err = appendElemToSlice(slicePtrValue, rowElemPtr)
if err != nil {
return
}
2019-03-14 09:18:23 +01:00
}
2019-07-13 13:17:28 +02:00
return
2019-03-14 09:18:23 +01:00
}
2019-07-13 13:17:28 +02:00
type typeInfo struct {
fieldMappings []fieldMapping
}
2019-03-14 09:18:23 +01:00
2019-07-13 13:17:28 +02:00
type fieldMapping struct {
complexType bool
columnIndex int
implementsScanner bool
2019-03-30 09:59:24 +01:00
}
2019-07-13 13:17:28 +02:00
func (s *scanContext) getTypeInfo(structType reflect.Type, parentField *reflect.StructField) typeInfo {
2019-03-15 21:55:43 +01:00
2019-07-13 13:17:28 +02:00
typeMapKey := structType.String()
2019-03-14 09:18:23 +01:00
2019-07-13 13:17:28 +02:00
if parentField != nil {
typeMapKey += string(parentField.Tag)
2019-03-14 09:18:23 +01:00
}
2019-07-13 13:17:28 +02:00
if typeInfo, ok := s.typeInfoMap[typeMapKey]; ok {
return typeInfo
2019-03-14 09:18:23 +01:00
}
2019-05-22 11:28:32 +02:00
2019-07-13 13:17:28 +02:00
typeName := getTypeName(structType, parentField)
2019-05-22 11:28:32 +02:00
2019-07-13 13:17:28 +02:00
newTypeInfo := typeInfo{}
for i := 0; i < structType.NumField(); i++ {
field := structType.Field(i)
newTypeName, fieldName := getTypeAndFieldName(typeName, field)
columnIndex := s.typeToColumnIndex(newTypeName, fieldName)
fieldMap := fieldMapping{
columnIndex: columnIndex,
}
if implementsScannerType(field.Type) {
fieldMap.implementsScanner = true
2019-07-29 18:08:53 +02:00
} else if !isSimpleModelType(field.Type) {
2019-07-13 13:17:28 +02:00
fieldMap.complexType = true
}
newTypeInfo.fieldMappings = append(newTypeInfo.fieldMappings, fieldMap)
}
s.typeInfoMap[typeMapKey] = newTypeInfo
return newTypeInfo
}
2019-07-13 13:17:28 +02:00
func mapRowToStruct(scanContext *scanContext, groupKey string, structPtrValue reflect.Value, parentField *reflect.StructField, onlySlices ...bool) (updated bool, err error) {
structType := structPtrValue.Type().Elem()
2019-03-14 09:18:23 +01:00
2019-07-13 13:17:28 +02:00
typeInf := scanContext.getTypeInfo(structType, parentField)
structValue := structPtrValue.Elem()
for i := 0; i < structValue.NumField(); i++ {
field := structType.Field(i)
fieldValue := structValue.Field(i)
2019-07-30 15:04:36 +02:00
if !fieldValue.CanSet() { // private field
continue
}
2019-07-13 13:17:28 +02:00
fieldMap := typeInf.fieldMappings[i]
if fieldMap.complexType {
var changed bool
changed, err = mapRowToDestinationValue(scanContext, groupKey, fieldValue, &field)
if err != nil {
return
}
if changed {
updated = true
}
} else if len(onlySlices) == 0 {
if fieldMap.columnIndex == -1 {
continue
}
if fieldMap.implementsScanner {
cellValue := scanContext.rowElem(fieldMap.columnIndex)
if cellValue == nil {
continue
}
initializeValueIfNilPtr(fieldValue)
scanner := getScanner(fieldValue)
err = scanner.Scan(cellValue)
if err != nil {
err = fmt.Errorf("%s, at struct field: %s %s of type %s. ", err.Error(), field.Name, field.Type.String(), structType.String())
return
}
updated = true
} else {
cellValue := scanContext.rowElem(fieldMap.columnIndex)
if cellValue != nil {
updated = true
initializeValueIfNilPtr(fieldValue)
err = setReflectValue(reflect.ValueOf(cellValue), fieldValue)
if err != nil {
err = fmt.Errorf("%s, at struct field: %s %s of type %s. ", err.Error(), field.Name, field.Type.String(), structType.String())
return
}
}
}
}
}
return
2019-03-14 09:18:23 +01:00
}
2019-05-20 17:37:55 +02:00
func mapRowToDestinationPtr(scanContext *scanContext, groupKey string, destPtrValue reflect.Value, structField *reflect.StructField) (updated bool, err error) {
2019-03-14 09:18:23 +01:00
2019-05-20 17:37:55 +02:00
if destPtrValue.Kind() != reflect.Ptr {
2019-07-08 13:00:44 +02:00
return false, errors.New("jet: Internal error. ")
2019-05-20 17:37:55 +02:00
}
2019-03-14 09:18:23 +01:00
2019-05-20 17:37:55 +02:00
destValueKind := destPtrValue.Elem().Kind()
2019-03-14 09:18:23 +01:00
2019-05-20 17:37:55 +02:00
if destValueKind == reflect.Struct {
return mapRowToStruct(scanContext, groupKey, destPtrValue, structField)
} else if destValueKind == reflect.Slice {
return mapRowToSlice(scanContext, groupKey, destPtrValue, structField)
} else {
2019-07-08 13:00:44 +02:00
return false, errors.New("jet: Unsupported dest type: " + structField.Name + " " + structField.Type.String())
2019-05-20 17:37:55 +02:00
}
}
2019-05-20 17:37:55 +02:00
func mapRowToDestinationValue(scanContext *scanContext, groupKey string, dest reflect.Value, structField *reflect.StructField) (updated bool, err error) {
2019-03-14 09:18:23 +01:00
2019-05-20 17:37:55 +02:00
var destPtrValue reflect.Value
2019-03-14 09:18:23 +01:00
2019-05-20 17:37:55 +02:00
if dest.Kind() != reflect.Ptr {
destPtrValue = dest.Addr()
} else if dest.Kind() == reflect.Ptr {
if dest.IsNil() {
destPtrValue = reflect.New(dest.Type().Elem())
2019-03-14 09:18:23 +01:00
} else {
2019-05-20 17:37:55 +02:00
destPtrValue = dest
2019-03-14 09:18:23 +01:00
}
} else {
2019-07-08 13:00:44 +02:00
return false, errors.New("jet: Internal error. ")
2019-03-14 09:18:23 +01:00
}
2019-05-20 17:37:55 +02:00
updated, err = mapRowToDestinationPtr(scanContext, groupKey, destPtrValue, structField)
if err != nil {
return
}
if dest.Kind() == reflect.Ptr && dest.IsNil() && updated {
dest.Set(destPtrValue)
}
return
}
2019-07-13 13:17:28 +02:00
var scannerInterfaceType = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
2019-03-30 09:59:24 +01:00
2019-07-13 13:17:28 +02:00
func implementsScannerType(fieldType reflect.Type) bool {
if fieldType.Implements(scannerInterfaceType) {
return true
}
2019-03-30 09:59:24 +01:00
2019-07-13 13:17:28 +02:00
typePtr := reflect.New(fieldType).Type()
2019-07-13 13:17:28 +02:00
return typePtr.Implements(scannerInterfaceType)
}
2019-03-09 14:20:44 +01:00
2019-07-13 13:17:28 +02:00
func getScanner(value reflect.Value) sql.Scanner {
if scanner, ok := value.Interface().(sql.Scanner); ok {
return scanner
}
2019-07-13 13:17:28 +02:00
return value.Addr().Interface().(sql.Scanner)
}
2019-04-03 19:21:46 +02:00
2019-07-13 13:17:28 +02:00
func getSliceElemType(slicePtrValue reflect.Value) reflect.Type {
sliceTypePtr := slicePtrValue.Type()
2019-04-03 19:21:46 +02:00
2019-07-13 13:17:28 +02:00
elemType := sliceTypePtr.Elem().Elem()
2019-04-03 19:21:46 +02:00
2019-07-13 13:17:28 +02:00
if elemType.Kind() == reflect.Ptr {
return elemType.Elem()
}
2019-04-03 19:21:46 +02:00
2019-07-13 13:17:28 +02:00
return elemType
}
2019-04-03 19:21:46 +02:00
2019-07-13 13:17:28 +02:00
func getSliceElemPtrAt(slicePtrValue reflect.Value, index int) reflect.Value {
sliceValue := slicePtrValue.Elem()
elem := sliceValue.Index(index)
2019-07-13 13:17:28 +02:00
if elem.Kind() == reflect.Ptr {
return elem
}
2019-05-21 17:34:43 +02:00
2019-07-13 13:17:28 +02:00
return elem.Addr()
}
2019-05-22 11:28:32 +02:00
2019-07-13 13:17:28 +02:00
func appendElemToSlice(slicePtrValue reflect.Value, objPtrValue reflect.Value) error {
if slicePtrValue.IsNil() {
panic("Slice is nil")
}
sliceValue := slicePtrValue.Elem()
sliceElemType := sliceValue.Type().Elem()
2019-03-14 09:18:23 +01:00
2019-07-13 13:17:28 +02:00
newElemValue := objPtrValue
2019-05-20 17:37:55 +02:00
2019-07-13 13:17:28 +02:00
if sliceElemType.Kind() != reflect.Ptr {
newElemValue = objPtrValue.Elem()
}
2019-07-13 13:17:28 +02:00
if !newElemValue.Type().AssignableTo(sliceElemType) {
return fmt.Errorf("jet: can't append %s to %s slice ", newElemValue.Type().String(), sliceValue.Type().String())
}
sliceValue.Set(reflect.Append(sliceValue, newElemValue))
return nil
}
func newElemPtrValueForSlice(slicePtrValue reflect.Value) reflect.Value {
destinationSliceType := slicePtrValue.Type().Elem()
elemType := indirectType(destinationSliceType.Elem())
return reflect.New(elemType)
2019-05-20 17:37:55 +02:00
}
func getTypeName(structType reflect.Type, parentField *reflect.StructField) string {
if parentField == nil {
return structType.Name()
}
aliasTag := parentField.Tag.Get("alias")
2019-06-26 10:30:31 +02:00
if aliasTag == "" {
return structType.Name()
}
2019-06-26 10:30:31 +02:00
aliasParts := strings.Split(aliasTag, ".")
2019-07-13 13:17:28 +02:00
return toCommonIdentifier(aliasParts[0])
}
func getTypeAndFieldName(structType string, field reflect.StructField) (string, string) {
aliasTag := field.Tag.Get("alias")
if aliasTag == "" {
return structType, field.Name
}
aliasParts := strings.Split(aliasTag, ".")
if len(aliasParts) == 1 {
return structType, toCommonIdentifier(aliasParts[0])
}
return toCommonIdentifier(aliasParts[0]), toCommonIdentifier(aliasParts[1])
}
var replacer = strings.NewReplacer(" ", "", "-", "", "_", "")
func toCommonIdentifier(name string) string {
return strings.ToLower(replacer.Replace(name))
}
func initializeValueIfNilPtr(value reflect.Value) {
2019-07-30 15:04:36 +02:00
2019-05-20 17:37:55 +02:00
if !value.IsValid() || !value.CanSet() {
return
}
if value.Kind() == reflect.Ptr && value.IsNil() {
2019-05-20 17:37:55 +02:00
value.Set(reflect.New(value.Type().Elem()))
}
}
func valueToString(value reflect.Value) string {
2019-03-16 14:02:45 +01:00
if !value.IsValid() {
return "nil"
}
2019-03-16 14:02:45 +01:00
2019-03-14 09:18:23 +01:00
var valueInterface interface{}
if value.Kind() == reflect.Ptr {
if value.IsNil() {
return "nil"
}
valueInterface = value.Elem().Interface()
2019-03-14 09:18:23 +01:00
} else {
valueInterface = value.Interface()
}
if t, ok := valueInterface.(time.Time); ok {
return t.String()
}
return fmt.Sprintf("%#v", valueInterface)
}
2019-07-29 18:08:53 +02:00
var timeType = reflect.TypeOf(time.Now())
var uuidType = reflect.TypeOf(uuid.New())
2019-03-09 14:20:44 +01:00
2019-07-29 18:08:53 +02:00
func isSimpleModelType(objType reflect.Type) bool {
objType = indirectType(objType)
switch objType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64,
reflect.String,
reflect.Bool:
return true
case reflect.Slice:
return objType.Elem().Kind() == reflect.Uint8 //[]byte
case reflect.Struct:
return objType == timeType || objType == uuidType // time.Time || uuid.UUID
}
return false
}
2019-07-30 11:18:12 +02:00
func isIntegerType(value reflect.Type) bool {
switch value {
case int8Type, unit8Type, int16Type, uint16Type,
int32Type, uint32Type, int64Type, uint64Type:
return true
}
return false
}
2019-07-29 18:08:53 +02:00
func tryAssign(source, destination reflect.Value) bool {
if source.Type().ConvertibleTo(destination.Type()) {
source = source.Convert(destination.Type())
}
2019-07-30 11:18:12 +02:00
if isIntegerType(source.Type()) && destination.Type() == boolType {
intValue := source.Int()
if intValue == 1 {
source = reflect.ValueOf(true)
} else if intValue == 0 {
source = reflect.ValueOf(false)
}
}
2019-07-29 18:08:53 +02:00
if source.Type().AssignableTo(destination.Type()) {
destination.Set(source)
2019-03-09 14:20:44 +01:00
return true
}
return false
}
2019-05-21 17:34:43 +02:00
func setReflectValue(source, destination reflect.Value) error {
2019-07-29 18:08:53 +02:00
if tryAssign(source, destination) {
return nil
}
if destination.Kind() == reflect.Ptr {
if source.Kind() == reflect.Ptr {
2019-07-29 18:08:53 +02:00
if !source.IsNil() {
if destination.IsNil() {
initializeValueIfNilPtr(destination)
}
tryAssign(source.Elem(), destination.Elem())
}
} else {
2019-05-21 17:34:43 +02:00
if source.CanAddr() {
2019-07-29 18:08:53 +02:00
source = source.Addr()
2019-05-21 17:34:43 +02:00
} else {
sourceCopy := reflect.New(source.Type())
sourceCopy.Elem().Set(source)
2019-05-21 17:34:43 +02:00
2019-07-29 18:08:53 +02:00
source = sourceCopy
}
if tryAssign(source, destination) {
return nil
}
if tryAssign(source.Elem(), destination.Elem()) {
return nil
2019-05-21 17:34:43 +02:00
}
}
} else {
if source.Kind() == reflect.Ptr {
2019-07-29 18:08:53 +02:00
source = source.Elem()
}
2019-05-21 17:34:43 +02:00
2019-07-29 18:08:53 +02:00
if tryAssign(source, destination) {
return nil
}
2019-05-21 17:34:43 +02:00
}
2019-07-29 18:08:53 +02:00
return errors.New("jet: can't set " + source.Type().String() + " to " + destination.Type().String())
}
func createScanValue(columnTypes []*sql.ColumnType) []interface{} {
values := make([]interface{}, len(columnTypes))
for i, sqlColumnType := range columnTypes {
2019-03-16 14:02:45 +01:00
columnType := newScanType(sqlColumnType)
columnValue := reflect.New(columnType)
values[i] = columnValue.Interface()
}
return values
}
2019-03-09 14:20:44 +01:00
2019-07-30 11:18:12 +02:00
var boolType = reflect.TypeOf(true)
2019-07-29 18:08:53 +02:00
var int8Type = reflect.TypeOf(int8(1))
var unit8Type = reflect.TypeOf(uint8(1))
var int16Type = reflect.TypeOf(int16(1))
var uint16Type = reflect.TypeOf(uint16(1))
var int32Type = reflect.TypeOf(int32(1))
var uint32Type = reflect.TypeOf(uint32(1))
var int64Type = reflect.TypeOf(int64(1))
var uint64Type = reflect.TypeOf(uint64(1))
2019-08-08 18:30:11 +02:00
var nullBoolType = reflect.TypeOf(sql.NullBool{})
2019-07-29 18:08:53 +02:00
var nullInt8Type = reflect.TypeOf(internal.NullInt8{})
2019-06-23 18:55:57 +02:00
var nullInt16Type = reflect.TypeOf(internal.NullInt16{})
var nullInt32Type = reflect.TypeOf(internal.NullInt32{})
2019-03-16 14:02:45 +01:00
var nullInt64Type = reflect.TypeOf(sql.NullInt64{})
2019-07-29 18:08:53 +02:00
var nullFloat32Type = reflect.TypeOf(internal.NullFloat32{})
var nullFloat64Type = reflect.TypeOf(sql.NullFloat64{})
2019-03-16 14:02:45 +01:00
var nullStringType = reflect.TypeOf(sql.NullString{})
2019-06-23 18:55:57 +02:00
var nullTimeType = reflect.TypeOf(internal.NullTime{})
var nullByteArrayType = reflect.TypeOf(internal.NullByteArray{})
2019-03-09 14:20:44 +01:00
2019-03-16 14:02:45 +01:00
func newScanType(columnType *sql.ColumnType) reflect.Type {
2019-07-29 18:08:53 +02:00
2019-03-09 14:20:44 +01:00
switch columnType.DatabaseTypeName() {
2019-07-29 18:08:53 +02:00
case "TINYINT":
return nullInt8Type
case "INT2", "SMALLINT", "YEAR":
2019-03-16 14:02:45 +01:00
return nullInt16Type
2019-07-29 18:08:53 +02:00
case "INT4", "MEDIUMINT", "INT":
2019-03-16 14:02:45 +01:00
return nullInt32Type
2019-07-29 18:08:53 +02:00
case "INT8", "BIGINT":
2019-03-16 14:02:45 +01:00
return nullInt64Type
2019-07-29 18:08:53 +02:00
case "CHAR", "VARCHAR", "TEXT", "", "_TEXT", "TSVECTOR", "BPCHAR", "UUID", "JSON", "JSONB", "INTERVAL", "POINT", "BIT", "VARBIT", "XML":
2019-03-16 14:02:45 +01:00
return nullStringType
2019-03-09 14:20:44 +01:00
case "FLOAT4":
2019-07-29 18:08:53 +02:00
return nullFloat32Type
case "FLOAT8", "NUMERIC", "DECIMAL", "FLOAT", "DOUBLE":
2019-03-30 09:59:24 +01:00
return nullFloat64Type
2019-03-16 14:02:45 +01:00
case "BOOL":
return nullBoolType
2019-07-29 18:08:53 +02:00
case "BYTEA", "BINARY", "VARBINARY", "BLOB":
return nullByteArrayType
2019-07-30 11:18:12 +02:00
case "DATE", "DATETIME", "TIMESTAMP", "TIMESTAMPTZ", "TIME", "TIMETZ":
2019-03-16 14:02:45 +01:00
return nullTimeType
2019-03-09 14:20:44 +01:00
default:
return nullStringType
2019-03-09 14:20:44 +01:00
}
}
2019-05-20 17:37:55 +02:00
type scanContext struct {
rowNum int
row []interface{}
uniqueDestObjectsMap map[string]int
2019-05-20 17:37:55 +02:00
2019-07-13 13:17:28 +02:00
typeToColumnIndexMap map[string]int
groupKeyInfoCache map[string]groupKeyInfo
2019-07-13 13:17:28 +02:00
typeInfoMap map[string]typeInfo
2019-05-20 17:37:55 +02:00
}
func newScanContext(rows *sql.Rows) (*scanContext, error) {
aliases, err := rows.Columns()
2019-05-20 17:37:55 +02:00
if err != nil {
return nil, err
}
columnTypes, err := rows.ColumnTypes()
if err != nil {
return nil, err
}
2019-07-13 13:17:28 +02:00
typeToIndexMap := map[string]int{}
for i, alias := range aliases {
names := strings.SplitN(alias, ".", 2)
2019-07-13 13:17:28 +02:00
goName := toCommonIdentifier(names[0])
if len(names) > 1 {
2019-07-13 13:17:28 +02:00
goName += "." + toCommonIdentifier(names[1])
}
2019-06-17 12:05:52 +02:00
2019-07-13 13:17:28 +02:00
typeToIndexMap[strings.ToLower(goName)] = i
2019-06-17 12:05:52 +02:00
}
2019-05-20 17:37:55 +02:00
return &scanContext{
row: createScanValue(columnTypes),
uniqueDestObjectsMap: make(map[string]int),
2019-07-13 13:17:28 +02:00
groupKeyInfoCache: make(map[string]groupKeyInfo),
typeToColumnIndexMap: typeToIndexMap,
typeInfoMap: make(map[string]typeInfo),
2019-05-20 17:37:55 +02:00
}, nil
}
2019-07-13 13:17:28 +02:00
type groupKeyInfo struct {
typeName string
indexes []int
subTypes []groupKeyInfo
}
func (s *scanContext) getGroupKey(structType reflect.Type, structField *reflect.StructField) string {
mapKey := structType.Name()
if structField != nil {
mapKey += structField.Type.String()
}
if groupKeyInfo, ok := s.groupKeyInfoCache[mapKey]; ok {
return s.constructGroupKey(groupKeyInfo)
}
groupKeyInfo := s.getGroupKeyInfo(structType, structField)
s.groupKeyInfoCache[mapKey] = groupKeyInfo
return s.constructGroupKey(groupKeyInfo)
}
func (s *scanContext) constructGroupKey(groupKeyInfo groupKeyInfo) string {
if len(groupKeyInfo.indexes) == 0 && len(groupKeyInfo.subTypes) == 0 {
return "|ROW: " + strconv.Itoa(s.rowNum) + "|"
}
groupKeys := []string{}
for _, index := range groupKeyInfo.indexes {
cellValue := s.rowElem(index)
subKey := valueToString(reflect.ValueOf(cellValue))
groupKeys = append(groupKeys, subKey)
}
subTypesGroupKeys := []string{}
for _, subType := range groupKeyInfo.subTypes {
subTypesGroupKeys = append(subTypesGroupKeys, s.constructGroupKey(subType))
}
2019-07-13 13:17:28 +02:00
return groupKeyInfo.typeName + "(" + strings.Join(groupKeys, ",") + strings.Join(subTypesGroupKeys, ",") + ")"
}
func (s *scanContext) getGroupKeyInfo(structType reflect.Type, parentField *reflect.StructField) groupKeyInfo {
typeName := getTypeName(structType, parentField)
ret := groupKeyInfo{typeName: structType.Name()}
for i := 0; i < structType.NumField(); i++ {
field := structType.Field(i)
2019-07-13 13:17:28 +02:00
newTypeName, fieldName := getTypeAndFieldName(typeName, field)
2019-07-29 18:08:53 +02:00
if !isSimpleModelType(field.Type) {
var structType reflect.Type
if field.Type.Kind() == reflect.Struct {
structType = field.Type
} else if field.Type.Kind() == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct {
structType = field.Type.Elem()
} else {
continue
}
subType := s.getGroupKeyInfo(structType, &field)
if len(subType.indexes) != 0 || len(subType.subTypes) != 0 {
ret.subTypes = append(ret.subTypes, subType)
}
2019-06-26 10:30:31 +02:00
} else if isPrimaryKey(field) {
2019-07-13 13:17:28 +02:00
index := s.typeToColumnIndex(newTypeName, fieldName)
if index < 0 {
continue
}
ret.indexes = append(ret.indexes, index)
}
}
return ret
}
2019-07-13 13:17:28 +02:00
func (s *scanContext) typeToColumnIndex(typeName, fieldName string) int {
var key string
2019-06-17 12:05:52 +02:00
if typeName != "" {
key = strings.ToLower(typeName + "." + fieldName)
} else {
key = strings.ToLower(fieldName)
}
2019-06-17 12:05:52 +02:00
2019-07-13 13:17:28 +02:00
index, ok := s.typeToColumnIndexMap[key]
if !ok {
return -1
2019-06-17 12:05:52 +02:00
}
return index
2019-06-17 12:05:52 +02:00
}
2019-05-20 17:37:55 +02:00
func (s *scanContext) rowElem(index int) interface{} {
valuer, ok := s.row[index].(driver.Valuer)
if !ok {
panic("Scan value doesn't implement driver.Valuer")
}
value, err := valuer.Value()
if err != nil {
panic(err)
}
return value
}
2019-05-21 17:34:43 +02:00
func (s *scanContext) rowElemValuePtr(index int) reflect.Value {
2019-05-20 17:37:55 +02:00
rowElem := s.rowElem(index)
rowElemValue := reflect.ValueOf(rowElem)
if rowElemValue.Kind() == reflect.Ptr {
return rowElemValue
}
if rowElemValue.CanAddr() {
return rowElemValue.Addr()
}
newElem := reflect.New(rowElemValue.Type())
newElem.Elem().Set(rowElemValue)
return newElem
}
2019-06-12 12:47:30 +02:00
2019-06-26 10:30:31 +02:00
func isPrimaryKey(field reflect.StructField) bool {
2019-06-12 12:47:30 +02:00
2019-06-26 10:30:31 +02:00
sqlTag := field.Tag.Get("sql")
2019-06-12 12:47:30 +02:00
2019-06-26 10:30:31 +02:00
return sqlTag == "primary_key"
2019-06-12 12:47:30 +02:00
}
func indirectType(reflectType reflect.Type) reflect.Type {
if reflectType.Kind() != reflect.Ptr {
return reflectType
}
return reflectType.Elem()
}