package schema

import (
	
	
	
	
	
	
	
	
	

	
	
	
)

// special types' reflect type
var (
	TimeReflectType    = reflect.TypeOf(time.Time{})
	TimePtrReflectType = reflect.TypeOf(&time.Time{})
	ByteReflectType    = reflect.TypeOf(uint8(0))
)

type (
	// DataType GORM data type
	DataType string
	// TimeType GORM time type
	TimeType int64
)

// GORM time types
const (
	UnixTime        TimeType = 1
	UnixSecond      TimeType = 2
	UnixMillisecond TimeType = 3
	UnixNanosecond  TimeType = 4
)

// GORM fields types
const (
	Bool   DataType = "bool"
	Int    DataType = "int"
	Uint   DataType = "uint"
	Float  DataType = "float"
	String DataType = "string"
	Time   DataType = "time"
	Bytes  DataType = "bytes"
)

// Field is the representation of model schema's field
type Field struct {
	Name                   string
	DBName                 string
	BindNames              []string
	DataType               DataType
	GORMDataType           DataType
	PrimaryKey             bool
	AutoIncrement          bool
	AutoIncrementIncrement int64
	Creatable              bool
	Updatable              bool
	Readable               bool
	AutoCreateTime         TimeType
	AutoUpdateTime         TimeType
	HasDefaultValue        bool
	DefaultValue           string
	DefaultValueInterface  interface{}
	NotNull                bool
	Unique                 bool
	Comment                string
	Size                   int
	Precision              int
	Scale                  int
	IgnoreMigration        bool
	FieldType              reflect.Type
	IndirectFieldType      reflect.Type
	StructField            reflect.StructField
	Tag                    reflect.StructTag
	TagSettings            map[string]string
	Schema                 *Schema
	EmbeddedSchema         *Schema
	OwnerSchema            *Schema
	ReflectValueOf         func(context.Context, reflect.Value) reflect.Value
	ValueOf                func(context.Context, reflect.Value) (value interface{}, zero bool)
	Set                    func(context.Context, reflect.Value, interface{}) error
	Serializer             SerializerInterface
	NewValuePool           FieldNewValuePool
}

func ( *Field) () string {
	return strings.Join(.BindNames, ".")
}

// ParseField parses reflect.StructField to Field
func ( *Schema) ( reflect.StructField) *Field {
	var (
		        error
		 = ParseTagSetting(.Tag.Get("gorm"), ";")
	)

	 := &Field{
		Name:                   .Name,
		DBName:                 ["COLUMN"],
		BindNames:              []string{.Name},
		FieldType:              .Type,
		IndirectFieldType:      .Type,
		StructField:            ,
		Tag:                    .Tag,
		TagSettings:            ,
		Schema:                 ,
		Creatable:              true,
		Updatable:              true,
		Readable:               true,
		PrimaryKey:             utils.CheckTruth(["PRIMARYKEY"], ["PRIMARY_KEY"]),
		AutoIncrement:          utils.CheckTruth(["AUTOINCREMENT"]),
		HasDefaultValue:        utils.CheckTruth(["AUTOINCREMENT"]),
		NotNull:                utils.CheckTruth(["NOT NULL"], ["NOTNULL"]),
		Unique:                 utils.CheckTruth(["UNIQUE"]),
		Comment:                ["COMMENT"],
		AutoIncrementIncrement: 1,
	}

	for .IndirectFieldType.Kind() == reflect.Ptr {
		.IndirectFieldType = .IndirectFieldType.Elem()
	}

	 := reflect.New(.IndirectFieldType)
	// if field is valuer, used its value or first field as data type
	,  := .Interface().(driver.Valuer)
	if  {
		if ,  := .Interface().(GormDataTypeInterface); ! {
			if ,  := .Value(); reflect.ValueOf().IsValid() &&  == nil {
				 = reflect.ValueOf()
			}

			// Use the field struct's first field type as data type, e.g: use `string` for sql.NullString
			var  func(reflect.Value)
			 = func( reflect.Value) {
				var (
					     = reflect.Indirect()
					 = .Type()
				)

				if .Kind() == reflect.Struct && !.ConvertibleTo(TimeReflectType) {
					for  := 0;  < .NumField(); ++ {
						for ,  := range ParseTagSetting(.Field().Tag.Get("gorm"), ";") {
							if ,  := .TagSettings[]; ! {
								.TagSettings[] = 
							}
						}
					}

					for  := 0;  < .NumField(); ++ {
						 := .Field().Type
						for .Kind() == reflect.Ptr {
							 = .Elem()
						}

						 = reflect.New()
						if  != reflect.Indirect().Type() {
							()
						}

						if .IsValid() {
							return
						}
					}
				}
			}

			()
		}
	}

	if ,  := .Interface().(SerializerInterface);  {
		.DataType = String
		.Serializer = 
	} else {
		 := .TagSettings["JSON"]
		if  == "" {
			 = .TagSettings["SERIALIZER"]
		}
		if  != "" {
			if ,  := GetSerializer();  {
				// Set default data type to string for serializer
				.DataType = String
				.Serializer = 
			} else {
				.err = fmt.Errorf("invalid serializer type %v", )
			}
		}
	}

	if ,  := .TagSettings["AUTOINCREMENTINCREMENT"];  {
		.AutoIncrementIncrement, _ = strconv.ParseInt(, 10, 64)
	}

	if ,  := .TagSettings["DEFAULT"];  {
		.HasDefaultValue = true
		.DefaultValue = 
	}

	if ,  := .TagSettings["SIZE"];  {
		if .Size,  = strconv.Atoi();  != nil {
			.Size = -1
		}
	}

	if ,  := .TagSettings["PRECISION"];  {
		.Precision, _ = strconv.Atoi()
	}

	if ,  := .TagSettings["SCALE"];  {
		.Scale, _ = strconv.Atoi()
	}

	// default value is function or null or blank (primary keys)
	.DefaultValue = strings.TrimSpace(.DefaultValue)
	 := strings.Contains(.DefaultValue, "(") &&
		strings.Contains(.DefaultValue, ")") || strings.ToLower(.DefaultValue) == "null" || .DefaultValue == ""
	switch reflect.Indirect().Kind() {
	case reflect.Bool:
		.DataType = Bool
		if .HasDefaultValue && ! {
			if .DefaultValueInterface,  = strconv.ParseBool(.DefaultValue);  != nil {
				.err = fmt.Errorf("failed to parse %s as default value for bool, got error: %v", .DefaultValue, )
			}
		}
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		.DataType = Int
		if .HasDefaultValue && ! {
			if .DefaultValueInterface,  = strconv.ParseInt(.DefaultValue, 0, 64);  != nil {
				.err = fmt.Errorf("failed to parse %s as default value for int, got error: %v", .DefaultValue, )
			}
		}
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		.DataType = Uint
		if .HasDefaultValue && ! {
			if .DefaultValueInterface,  = strconv.ParseUint(.DefaultValue, 0, 64);  != nil {
				.err = fmt.Errorf("failed to parse %s as default value for uint, got error: %v", .DefaultValue, )
			}
		}
	case reflect.Float32, reflect.Float64:
		.DataType = Float
		if .HasDefaultValue && ! {
			if .DefaultValueInterface,  = strconv.ParseFloat(.DefaultValue, 64);  != nil {
				.err = fmt.Errorf("failed to parse %s as default value for float, got error: %v", .DefaultValue, )
			}
		}
	case reflect.String:
		.DataType = String
		if .HasDefaultValue && ! {
			.DefaultValue = strings.Trim(.DefaultValue, "'")
			.DefaultValue = strings.Trim(.DefaultValue, `"`)
			.DefaultValueInterface = .DefaultValue
		}
	case reflect.Struct:
		if ,  := .Interface().(*time.Time);  {
			.DataType = Time
		} else if .Type().ConvertibleTo(TimeReflectType) {
			.DataType = Time
		} else if .Type().ConvertibleTo(TimePtrReflectType) {
			.DataType = Time
		}
		if .HasDefaultValue && ! && .DataType == Time {
			if ,  := now.Parse(.DefaultValue);  == nil {
				.DefaultValueInterface = 
			}
		}
	case reflect.Array, reflect.Slice:
		if reflect.Indirect().Type().Elem() == ByteReflectType && .DataType == "" {
			.DataType = Bytes
		}
	}

	if ,  := .Interface().(GormDataTypeInterface);  {
		.DataType = DataType(.GormDataType())
	}

	if ,  := .TagSettings["AUTOCREATETIME"]; ( && utils.CheckTruth()) || (! && .Name == "CreatedAt" && (.DataType == Time || .DataType == Int || .DataType == Uint)) {
		if .DataType == Time {
			.AutoCreateTime = UnixTime
		} else if strings.ToUpper() == "NANO" {
			.AutoCreateTime = UnixNanosecond
		} else if strings.ToUpper() == "MILLI" {
			.AutoCreateTime = UnixMillisecond
		} else {
			.AutoCreateTime = UnixSecond
		}
	}

	if ,  := .TagSettings["AUTOUPDATETIME"]; ( && utils.CheckTruth()) || (! && .Name == "UpdatedAt" && (.DataType == Time || .DataType == Int || .DataType == Uint)) {
		if .DataType == Time {
			.AutoUpdateTime = UnixTime
		} else if strings.ToUpper() == "NANO" {
			.AutoUpdateTime = UnixNanosecond
		} else if strings.ToUpper() == "MILLI" {
			.AutoUpdateTime = UnixMillisecond
		} else {
			.AutoUpdateTime = UnixSecond
		}
	}

	if .GORMDataType == "" {
		.GORMDataType = .DataType
	}

	if ,  := .TagSettings["TYPE"];  {
		switch DataType(strings.ToLower()) {
		case Bool, Int, Uint, Float, String, Time, Bytes:
			.DataType = DataType(strings.ToLower())
		default:
			.DataType = DataType()
		}
	}

	if .Size == 0 {
		switch reflect.Indirect().Kind() {
		case reflect.Int, reflect.Int64, reflect.Uint, reflect.Uint64, reflect.Float64:
			.Size = 64
		case reflect.Int8, reflect.Uint8:
			.Size = 8
		case reflect.Int16, reflect.Uint16:
			.Size = 16
		case reflect.Int32, reflect.Uint32, reflect.Float32:
			.Size = 32
		}
	}

	// setup permission
	if ,  := .TagSettings["-"];  {
		 = strings.ToLower(strings.TrimSpace())
		switch  {
		case "-":
			.Creatable = false
			.Updatable = false
			.Readable = false
			.DataType = ""
		case "all":
			.Creatable = false
			.Updatable = false
			.Readable = false
			.DataType = ""
			.IgnoreMigration = true
		case "migration":
			.IgnoreMigration = true
		}
	}

	if ,  := .TagSettings["->"];  {
		.Creatable = false
		.Updatable = false
		if strings.ToLower() == "false" {
			.Readable = false
		} else {
			.Readable = true
		}
	}

	if ,  := .TagSettings["<-"];  {
		.Creatable = true
		.Updatable = true

		if  != "<-" {
			if !strings.Contains(, "create") {
				.Creatable = false
			}

			if !strings.Contains(, "update") {
				.Updatable = false
			}
		}
	}

	// Normal anonymous field or having `EMBEDDED` tag
	if ,  := .TagSettings["EMBEDDED"];  || (.GORMDataType != Time && .GORMDataType != Bytes && ! &&
		.Anonymous && (.Creatable || .Updatable || .Readable)) {
		 := reflect.Indirect().Kind()
		switch  {
		case reflect.Struct:
			var  error
			.Creatable = false
			.Updatable = false
			.Readable = false

			 := &sync.Map{}
			.Store(embeddedCacheKey, true)
			if .EmbeddedSchema,  = getOrParse(.Interface(), , embeddedNamer{Table: .Table, Namer: .namer});  != nil {
				.err = 
			}

			for ,  := range .EmbeddedSchema.Fields {
				.Schema = 
				.OwnerSchema = .EmbeddedSchema
				.BindNames = append([]string{.Name}, .BindNames...)
				// index is negative means is pointer
				if .FieldType.Kind() == reflect.Struct {
					.StructField.Index = append([]int{.Index[0]}, .StructField.Index...)
				} else {
					.StructField.Index = append([]int{-.Index[0] - 1}, .StructField.Index...)
				}

				if ,  := .TagSettings["EMBEDDEDPREFIX"];  && .DBName != "" {
					.DBName =  + .DBName
				}

				if .PrimaryKey {
					if !utils.CheckTruth(.TagSettings["PRIMARYKEY"], .TagSettings["PRIMARY_KEY"]) {
						.PrimaryKey = false

						if ,  := .TagSettings["AUTOINCREMENT"]; ! || !utils.CheckTruth() {
							.AutoIncrement = false
						}

						if !.AutoIncrement && .DefaultValue == "" {
							.HasDefaultValue = false
						}
					}
				}

				for ,  := range .TagSettings {
					.TagSettings[] = 
				}
			}
		case reflect.Invalid, reflect.Uintptr, reflect.Array, reflect.Chan, reflect.Func, reflect.Interface,
			reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer, reflect.Complex64, reflect.Complex128:
			.err = fmt.Errorf("invalid embedded struct for %s's field %s, should be struct, but got %v", .Schema.Name, .Name, .FieldType)
		}
	}

	return 
}

// create valuer, setter when parse struct
func ( *Field) () {
	// Setup NewValuePool
	.setupNewValuePool()

	// ValueOf returns field's value and if it is zero
	 := .StructField.Index[0]
	switch {
	case len(.StructField.Index) == 1 &&  > 0:
		.ValueOf = func( context.Context,  reflect.Value) (interface{}, bool) {
			 := reflect.Indirect().Field()
			return .Interface(), .IsZero()
		}
	default:
		.ValueOf = func( context.Context,  reflect.Value) (interface{}, bool) {
			 = reflect.Indirect()
			for ,  := range .StructField.Index {
				if  >= 0 {
					 = .Field()
				} else {
					 = .Field(- - 1)

					if !.IsNil() {
						 = .Elem()
					} else {
						return nil, true
					}
				}
			}

			,  := .Interface(), .IsZero()
			return , 
		}
	}

	if .Serializer != nil {
		 := .ValueOf
		.ValueOf = func( context.Context,  reflect.Value) (interface{}, bool) {
			,  := (, )

			,  := .(SerializerValuerInterface)
			if ! {
				 = .Serializer
			}

			return &serializer{
				Field:           ,
				SerializeValuer: ,
				Destination:     ,
				Context:         ,
				fieldValue:      ,
			}, 
		}
	}

	// ReflectValueOf returns field's reflect value
	switch {
	case len(.StructField.Index) == 1 &&  > 0:
		.ReflectValueOf = func( context.Context,  reflect.Value) reflect.Value {
			return reflect.Indirect().Field()
		}
	default:
		.ReflectValueOf = func( context.Context,  reflect.Value) reflect.Value {
			 = reflect.Indirect()
			for ,  := range .StructField.Index {
				if  >= 0 {
					 = .Field()
				} else {
					 = .Field(- - 1)

					if .IsNil() {
						.Set(reflect.New(.Type().Elem()))
					}

					if  < len(.StructField.Index)-1 {
						 = .Elem()
					}
				}
			}
			return 
		}
	}

	 := func( context.Context,  reflect.Value,  interface{},  func(context.Context, reflect.Value, interface{}) error) ( error) {
		if  == nil {
			.ReflectValueOf(, ).Set(reflect.New(.FieldType).Elem())
		} else {
			 := reflect.ValueOf()
			// Optimal value type acquisition for v
			 := .Type()

			if .AssignableTo(.FieldType) {
				if .Kind() == reflect.Ptr && .Elem().Kind() == reflect.Ptr {
					 = reflect.Indirect()
				}
				.ReflectValueOf(, ).Set()
				return
			} else if .ConvertibleTo(.FieldType) {
				.ReflectValueOf(, ).Set(.Convert(.FieldType))
				return
			} else if .FieldType.Kind() == reflect.Ptr {
				 := .ReflectValueOf(, )
				 := .FieldType.Elem()

				if .AssignableTo() {
					if !.IsValid() {
						 = reflect.New()
					} else if .IsNil() {
						.Set(reflect.New())
					}
					.Elem().Set()
					return
				} else if .ConvertibleTo() {
					if .IsNil() {
						.Set(reflect.New())
					}

					.Elem().Set(.Convert())
					return
				}
			}

			if .Kind() == reflect.Ptr {
				if .IsNil() {
					.ReflectValueOf(, ).Set(reflect.New(.FieldType).Elem())
				} else if .Type().Elem().AssignableTo(.FieldType) {
					.ReflectValueOf(, ).Set(.Elem())
					return
				} else {
					 = (, , .Elem().Interface())
				}
			} else if ,  := .(driver.Valuer);  {
				if ,  = .Value();  == nil {
					 = (, , )
				}
			} else if ,  := .(clause.Expr); ! {
				return fmt.Errorf("failed to set value %#v to field %s", , .Name)
			}
		}

		return
	}

	// Set
	switch .FieldType.Kind() {
	case reflect.Bool:
		.Set = func( context.Context,  reflect.Value,  interface{}) error {
			switch data := .(type) {
			case **bool:
				if  != nil && * != nil {
					.ReflectValueOf(, ).SetBool(**)
				}
			case bool:
				.ReflectValueOf(, ).SetBool()
			case int64:
				.ReflectValueOf(, ).SetBool( > 0)
			case string:
				,  := strconv.ParseBool()
				.ReflectValueOf(, ).SetBool()
			default:
				return (, , , .Set)
			}
			return nil
		}
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		.Set = func( context.Context,  reflect.Value,  interface{}) ( error) {
			switch data := .(type) {
			case **int64:
				if  != nil && * != nil {
					.ReflectValueOf(, ).SetInt(**)
				}
			case **int:
				if  != nil && * != nil {
					.ReflectValueOf(, ).SetInt(int64(**))
				}
			case **int8:
				if  != nil && * != nil {
					.ReflectValueOf(, ).SetInt(int64(**))
				}
			case **int16:
				if  != nil && * != nil {
					.ReflectValueOf(, ).SetInt(int64(**))
				}
			case **int32:
				if  != nil && * != nil {
					.ReflectValueOf(, ).SetInt(int64(**))
				}
			case int64:
				.ReflectValueOf(, ).SetInt()
			case int:
				.ReflectValueOf(, ).SetInt(int64())
			case int8:
				.ReflectValueOf(, ).SetInt(int64())
			case int16:
				.ReflectValueOf(, ).SetInt(int64())
			case int32:
				.ReflectValueOf(, ).SetInt(int64())
			case uint:
				.ReflectValueOf(, ).SetInt(int64())
			case uint8:
				.ReflectValueOf(, ).SetInt(int64())
			case uint16:
				.ReflectValueOf(, ).SetInt(int64())
			case uint32:
				.ReflectValueOf(, ).SetInt(int64())
			case uint64:
				.ReflectValueOf(, ).SetInt(int64())
			case float32:
				.ReflectValueOf(, ).SetInt(int64())
			case float64:
				.ReflectValueOf(, ).SetInt(int64())
			case []byte:
				return .Set(, , string())
			case string:
				if ,  := strconv.ParseInt(, 0, 64);  == nil {
					.ReflectValueOf(, ).SetInt()
				} else {
					return 
				}
			case time.Time:
				if .AutoCreateTime == UnixNanosecond || .AutoUpdateTime == UnixNanosecond {
					.ReflectValueOf(, ).SetInt(.UnixNano())
				} else if .AutoCreateTime == UnixMillisecond || .AutoUpdateTime == UnixMillisecond {
					.ReflectValueOf(, ).SetInt(.UnixNano() / 1e6)
				} else {
					.ReflectValueOf(, ).SetInt(.Unix())
				}
			case *time.Time:
				if  != nil {
					if .AutoCreateTime == UnixNanosecond || .AutoUpdateTime == UnixNanosecond {
						.ReflectValueOf(, ).SetInt(.UnixNano())
					} else if .AutoCreateTime == UnixMillisecond || .AutoUpdateTime == UnixMillisecond {
						.ReflectValueOf(, ).SetInt(.UnixNano() / 1e6)
					} else {
						.ReflectValueOf(, ).SetInt(.Unix())
					}
				} else {
					.ReflectValueOf(, ).SetInt(0)
				}
			default:
				return (, , , .Set)
			}
			return 
		}
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		.Set = func( context.Context,  reflect.Value,  interface{}) ( error) {
			switch data := .(type) {
			case **uint64:
				if  != nil && * != nil {
					.ReflectValueOf(, ).SetUint(**)
				}
			case **uint:
				if  != nil && * != nil {
					.ReflectValueOf(, ).SetUint(uint64(**))
				}
			case **uint8:
				if  != nil && * != nil {
					.ReflectValueOf(, ).SetUint(uint64(**))
				}
			case **uint16:
				if  != nil && * != nil {
					.ReflectValueOf(, ).SetUint(uint64(**))
				}
			case **uint32:
				if  != nil && * != nil {
					.ReflectValueOf(, ).SetUint(uint64(**))
				}
			case uint64:
				.ReflectValueOf(, ).SetUint()
			case uint:
				.ReflectValueOf(, ).SetUint(uint64())
			case uint8:
				.ReflectValueOf(, ).SetUint(uint64())
			case uint16:
				.ReflectValueOf(, ).SetUint(uint64())
			case uint32:
				.ReflectValueOf(, ).SetUint(uint64())
			case int64:
				.ReflectValueOf(, ).SetUint(uint64())
			case int:
				.ReflectValueOf(, ).SetUint(uint64())
			case int8:
				.ReflectValueOf(, ).SetUint(uint64())
			case int16:
				.ReflectValueOf(, ).SetUint(uint64())
			case int32:
				.ReflectValueOf(, ).SetUint(uint64())
			case float32:
				.ReflectValueOf(, ).SetUint(uint64())
			case float64:
				.ReflectValueOf(, ).SetUint(uint64())
			case []byte:
				return .Set(, , string())
			case time.Time:
				if .AutoCreateTime == UnixNanosecond || .AutoUpdateTime == UnixNanosecond {
					.ReflectValueOf(, ).SetUint(uint64(.UnixNano()))
				} else if .AutoCreateTime == UnixMillisecond || .AutoUpdateTime == UnixMillisecond {
					.ReflectValueOf(, ).SetUint(uint64(.UnixNano() / 1e6))
				} else {
					.ReflectValueOf(, ).SetUint(uint64(.Unix()))
				}
			case string:
				if ,  := strconv.ParseUint(, 0, 64);  == nil {
					.ReflectValueOf(, ).SetUint()
				} else {
					return 
				}
			default:
				return (, , , .Set)
			}
			return 
		}
	case reflect.Float32, reflect.Float64:
		.Set = func( context.Context,  reflect.Value,  interface{}) ( error) {
			switch data := .(type) {
			case **float64:
				if  != nil && * != nil {
					.ReflectValueOf(, ).SetFloat(**)
				}
			case **float32:
				if  != nil && * != nil {
					.ReflectValueOf(, ).SetFloat(float64(**))
				}
			case float64:
				.ReflectValueOf(, ).SetFloat()
			case float32:
				.ReflectValueOf(, ).SetFloat(float64())
			case int64:
				.ReflectValueOf(, ).SetFloat(float64())
			case int:
				.ReflectValueOf(, ).SetFloat(float64())
			case int8:
				.ReflectValueOf(, ).SetFloat(float64())
			case int16:
				.ReflectValueOf(, ).SetFloat(float64())
			case int32:
				.ReflectValueOf(, ).SetFloat(float64())
			case uint:
				.ReflectValueOf(, ).SetFloat(float64())
			case uint8:
				.ReflectValueOf(, ).SetFloat(float64())
			case uint16:
				.ReflectValueOf(, ).SetFloat(float64())
			case uint32:
				.ReflectValueOf(, ).SetFloat(float64())
			case uint64:
				.ReflectValueOf(, ).SetFloat(float64())
			case []byte:
				return .Set(, , string())
			case string:
				if ,  := strconv.ParseFloat(, 64);  == nil {
					.ReflectValueOf(, ).SetFloat()
				} else {
					return 
				}
			default:
				return (, , , .Set)
			}
			return 
		}
	case reflect.String:
		.Set = func( context.Context,  reflect.Value,  interface{}) ( error) {
			switch data := .(type) {
			case **string:
				if  != nil && * != nil {
					.ReflectValueOf(, ).SetString(**)
				}
			case string:
				.ReflectValueOf(, ).SetString()
			case []byte:
				.ReflectValueOf(, ).SetString(string())
			case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
				.ReflectValueOf(, ).SetString(utils.ToString())
			case float64, float32:
				.ReflectValueOf(, ).SetString(fmt.Sprintf("%."+strconv.Itoa(.Precision)+"f", ))
			default:
				return (, , , .Set)
			}
			return 
		}
	default:
		 := reflect.New(.FieldType)
		switch .Elem().Interface().(type) {
		case time.Time:
			.Set = func( context.Context,  reflect.Value,  interface{}) error {
				switch data := .(type) {
				case **time.Time:
					if  != nil && * != nil {
						.Set(, , *)
					}
				case time.Time:
					.ReflectValueOf(, ).Set(reflect.ValueOf())
				case *time.Time:
					if  != nil {
						.ReflectValueOf(, ).Set(reflect.ValueOf().Elem())
					} else {
						.ReflectValueOf(, ).Set(reflect.ValueOf(time.Time{}))
					}
				case string:
					if ,  := now.Parse();  == nil {
						.ReflectValueOf(, ).Set(reflect.ValueOf())
					} else {
						return fmt.Errorf("failed to set string %v to time.Time field %s, failed to parse it as time, got error %v", , .Name, )
					}
				default:
					return (, , , .Set)
				}
				return nil
			}
		case *time.Time:
			.Set = func( context.Context,  reflect.Value,  interface{}) error {
				switch data := .(type) {
				case **time.Time:
					if  != nil && * != nil {
						.ReflectValueOf(, ).Set(reflect.ValueOf(*))
					}
				case time.Time:
					 := .ReflectValueOf(, )
					if .IsNil() {
						.Set(reflect.New(.FieldType.Elem()))
					}
					.Elem().Set(reflect.ValueOf())
				case *time.Time:
					.ReflectValueOf(, ).Set(reflect.ValueOf())
				case string:
					if ,  := now.Parse();  == nil {
						 := .ReflectValueOf(, )
						if .IsNil() {
							if  == "" {
								return nil
							}
							.Set(reflect.New(.FieldType.Elem()))
						}
						.Elem().Set(reflect.ValueOf())
					} else {
						return fmt.Errorf("failed to set string %v to time.Time field %s, failed to parse it as time, got error %v", , .Name, )
					}
				default:
					return (, , , .Set)
				}
				return nil
			}
		default:
			if ,  := .Elem().Interface().(sql.Scanner);  {
				// pointer scanner
				.Set = func( context.Context,  reflect.Value,  interface{}) ( error) {
					 := reflect.ValueOf()
					if !.IsValid() {
						.ReflectValueOf(, ).Set(reflect.New(.FieldType).Elem())
					} else if .Kind() == reflect.Ptr && .IsNil() {
						return
					} else if .Type().AssignableTo(.FieldType) {
						.ReflectValueOf(, ).Set()
					} else if .Kind() == reflect.Ptr {
						return .Set(, , .Elem().Interface())
					} else {
						 := .ReflectValueOf(, )
						if .IsNil() {
							.Set(reflect.New(.FieldType.Elem()))
						}

						if ,  := .(driver.Valuer);  {
							, _ = .Value()
						}

						 = .Interface().(sql.Scanner).Scan()
					}
					return
				}
			} else if ,  := .Interface().(sql.Scanner);  {
				// struct scanner
				.Set = func( context.Context,  reflect.Value,  interface{}) ( error) {
					 := reflect.ValueOf()
					if !.IsValid() {
						.ReflectValueOf(, ).Set(reflect.New(.FieldType).Elem())
					} else if .Kind() == reflect.Ptr && .IsNil() {
						return
					} else if .Type().AssignableTo(.FieldType) {
						.ReflectValueOf(, ).Set()
					} else if .Kind() == reflect.Ptr {
						return .Set(, , .Elem().Interface())
					} else {
						if ,  := .(driver.Valuer);  {
							, _ = .Value()
						}

						 = .ReflectValueOf(, ).Addr().Interface().(sql.Scanner).Scan()
					}
					return
				}
			} else {
				.Set = func( context.Context,  reflect.Value,  interface{}) ( error) {
					return (, , , .Set)
				}
			}
		}
	}

	if .Serializer != nil {
		var (
			 = .Set
			   bool
			       = .FieldType == reflect.ValueOf(.Serializer).Type()
		)

		if reflect.ValueOf(.Serializer).Kind() == reflect.Ptr {
			 = .FieldType == reflect.ValueOf(.Serializer).Type().Elem()
		}

		 := reflect.Indirect(reflect.ValueOf(.Serializer))
		 := .Type()
		.Set = func( context.Context,  reflect.Value,  interface{}) ( error) {
			if ,  := .(*serializer);  {
				if .fieldValue != nil {
					 = (, , .fieldValue)
				} else if  = .Serializer.Scan(, , , .value);  == nil {
					if  {
						.ReflectValueOf(, ).Set(reflect.ValueOf(.Serializer).Elem())
					} else if  {
						.ReflectValueOf(, ).Set(reflect.ValueOf(.Serializer))
					}
					 := reflect.New()
					.Elem().Set()
					.Serializer = .Interface().(SerializerInterface)
				}
			} else {
				 = (, , )
			}
			return
		}
	}
}

func ( *Field) () {
	if .Serializer != nil {
		 := reflect.Indirect(reflect.ValueOf(.Serializer))
		 := .Type()
		.NewValuePool = &sync.Pool{
			New: func() interface{} {
				 := reflect.New()
				.Elem().Set()
				return &serializer{
					Field:      ,
					Serializer: .Interface().(SerializerInterface),
				}
			},
		}
	}

	if .NewValuePool == nil {
		.NewValuePool = poolInitializer(reflect.PtrTo(.IndirectFieldType))
	}
}