ConvertValueForField converts value to the type of the record field. The parameter `fieldType` is the target record field. The parameter `fieldValue` is the value that to be committed to record field.
(ctx context.Context, fieldType string, fieldValue any)
| 93 | // The parameter `fieldType` is the target record field. |
| 94 | // The parameter `fieldValue` is the value that to be committed to record field. |
| 95 | func (c *Core) ConvertValueForField(ctx context.Context, fieldType string, fieldValue any) (any, error) { |
| 96 | var ( |
| 97 | err error |
| 98 | convertedValue = fieldValue |
| 99 | ) |
| 100 | switch fieldValue.(type) { |
| 101 | case time.Time, *time.Time, gtime.Time, *gtime.Time: |
| 102 | goto Default |
| 103 | } |
| 104 | // If `value` implements interface `driver.Valuer`, it then uses the interface for value converting. |
| 105 | if valuer, ok := fieldValue.(driver.Valuer); ok { |
| 106 | if convertedValue, err = valuer.Value(); err != nil { |
| 107 | return nil, err |
| 108 | } |
| 109 | return convertedValue, nil |
| 110 | } |
| 111 | Default: |
| 112 | // Default value converting. |
| 113 | var ( |
| 114 | rvValue = reflect.ValueOf(fieldValue) |
| 115 | rvKind = rvValue.Kind() |
| 116 | ) |
| 117 | for rvKind == reflect.Pointer { |
| 118 | rvValue = rvValue.Elem() |
| 119 | rvKind = rvValue.Kind() |
| 120 | } |
| 121 | switch rvKind { |
| 122 | case reflect.Invalid: |
| 123 | convertedValue = nil |
| 124 | |
| 125 | case reflect.Slice, reflect.Array, reflect.Map: |
| 126 | // It should ignore the bytes type. |
| 127 | if _, ok := fieldValue.([]byte); !ok { |
| 128 | // Convert the value to JSON. |
| 129 | convertedValue, err = json.Marshal(fieldValue) |
| 130 | if err != nil { |
| 131 | return nil, err |
| 132 | } |
| 133 | } |
| 134 | case reflect.Struct: |
| 135 | switch r := fieldValue.(type) { |
| 136 | // If the time is zero, it then updates it to nil, |
| 137 | // which will insert/update the value to database as "null". |
| 138 | case time.Time: |
| 139 | if r.IsZero() { |
| 140 | convertedValue = nil |
| 141 | } else { |
| 142 | switch fieldType { |
| 143 | case fieldTypeYear: |
| 144 | convertedValue = r.Format("2006") |
| 145 | case fieldTypeDate: |
| 146 | convertedValue = r.Format("2006-01-02") |
| 147 | case fieldTypeTime: |
| 148 | convertedValue = r.Format("15:04:05") |
| 149 | default: |
| 150 | } |
| 151 | } |
| 152 |