convert.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2022 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "database/sql"
  17. "database/sql/driver"
  18. "reflect"
  19. )
  20. func scanIntoMap(mapValue map[string]interface{}, values []interface{}, columns []string) {
  21. for idx, column := range columns {
  22. if reflectValue := reflect.Indirect(reflect.Indirect(reflect.ValueOf(values[idx]))); reflectValue.IsValid() {
  23. mapValue[column] = reflectValue.Interface()
  24. if valuer, ok := mapValue[column].(driver.Valuer); ok {
  25. mapValue[column], _ = valuer.Value()
  26. } else if b, ok := mapValue[column].(sql.RawBytes); ok {
  27. mapValue[column] = string(b)
  28. }
  29. } else {
  30. mapValue[column] = nil
  31. }
  32. }
  33. }
  34. func prepareValues(values []interface{}, columnTypes []*sql.ColumnType, columns []string) {
  35. if len(columnTypes) > 0 {
  36. for idx, columnType := range columnTypes {
  37. if columnType.ScanType() != nil {
  38. values[idx] = reflect.New(reflect.PtrTo(columnType.ScanType())).Interface()
  39. } else {
  40. values[idx] = new(interface{})
  41. }
  42. }
  43. } else {
  44. for idx := range columns {
  45. values[idx] = new(interface{})
  46. }
  47. }
  48. }