Skip to content

Commit

Permalink
refactor: move complex conditional to a method
Browse files Browse the repository at this point in the history
The `f.SQLDefault == ""` part seems redundant before addReturningField,
as RETURNING makes sense for a field that was given its default value.
  • Loading branch information
bevzzz committed Nov 29, 2023
1 parent 1412ee6 commit 6f96bd9
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions query_insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ func (q *InsertQuery) appendStructValues(
switch {
case isTemplate:
b = append(b, '?')
case f.IsPtr && f.HasNilValue(strct), f.HasZeroValue(strct) && (f.NullZero || f.SQLDefault != ""):
case q.marshalsToDefault(f, strct):
if q.db.HasFeature(feature.DefaultPlaceholder) {
b = append(b, "DEFAULT"...)
} else if f.SQLDefault != "" {
Expand Down Expand Up @@ -410,18 +410,23 @@ func (q *InsertQuery) getFields() ([]*schema.Field, error) {
q.addReturningField(f)
continue
}
if f.NotNull && f.SQLDefault == "" {
if (f.IsPtr && f.HasNilValue(strct)) || (f.NullZero && f.HasZeroValue(strct)) {
q.addReturningField(f)
continue
}
if f.NotNull && q.marshalsToDefault(f, strct) {
q.addReturningField(f)
continue
}
fields = append(fields, f)
}

return fields, nil
}

// marshalsToDefault checks if the value will be marshaled as DEFAULT or NULL (if DEFAULT placeholder is not supported)
// when appending it to the VALUES clause in place of the given field.
func (q InsertQuery) marshalsToDefault(f *schema.Field, v reflect.Value) bool {
return (f.IsPtr && f.HasNilValue(v)) ||
(f.HasZeroValue(v) && (f.NullZero || f.SQLDefault != ""))
}

func (q *InsertQuery) appendFields(
fmter schema.Formatter, b []byte, fields []*schema.Field,
) []byte {
Expand Down

0 comments on commit 6f96bd9

Please sign in to comment.