github.com/ecodeclub/eorm@v0.0.2-0.20231001112437-dae71da914d0/internal/valuer/primitive.go (about) 1 // Copyright 2021 ecodeclub 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 15 package valuer 16 17 import ( 18 "database/sql" 19 "reflect" 20 21 "github.com/ecodeclub/eorm/internal/rows" 22 23 "github.com/ecodeclub/eorm/internal/model" 24 ) 25 26 // primitiveValue 支持基本类型 Value 27 type primitiveValue struct { 28 Value 29 val any 30 valType reflect.Type 31 } 32 33 // Field 返回字段值 34 func (s primitiveValue) Field(name string) (reflect.Value, error) { 35 return s.Value.Field(name) 36 } 37 38 // SetColumns 设置列值, 支持基本类型,基于 reflect 与 unsafe Value 封装 39 func (s primitiveValue) SetColumns(rows rows.Rows) error { 40 switch s.valType.Elem().Kind() { 41 case reflect.Struct: 42 if scanner, ok := s.val.(sql.Scanner); ok { 43 return rows.Scan(scanner) 44 } 45 return s.Value.SetColumns(rows) 46 default: 47 return rows.Scan(s.val) 48 } 49 } 50 51 // PrimitiveCreator 支持基本类型的 Creator, 基于原生的 Creator 扩展 52 type PrimitiveCreator struct { 53 Creator 54 } 55 56 // NewPrimitiveValue 返回一个封装好的,基于支持基本类型实现的 Value 57 // 输入 val 必须是一个指向结构体实例的指针,而不能是任何其它类型 58 func (c PrimitiveCreator) NewPrimitiveValue(val any, meta *model.TableMeta) Value { 59 return primitiveValue{ 60 val: val, 61 Value: c.Creator(val, meta), 62 valType: reflect.TypeOf(val), 63 } 64 }