Replies: 3 comments
-
I'm not sure what you mean. Do you want to generate insert/update queries depending on model fields? |
Beta Was this translation helpful? Give feedback.
-
For example i want to do a patch request and then update only fields that are specified (valid values or explicit nil provided) and ignore unspecified fields.
And then i can update like this:
Basically i have to keep in sync this second model with generated one. |
Beta Was this translation helpful? Give feedback.
-
Aha, I see. I think you can make type Optional interface {
IsSpecified() bool
IsNil() bool
MustGet() any
}
func Patch[T any](patch any, allColumns ColumnList) (ColumnList, T) {
var columnsToUpdate ColumnList
var modelToUpdate T
patchValue := reflect.ValueOf(patch)
modelValue := reflect.ValueOf(modelToUpdate)
for i := 0; i < patchValue.NumField(); i++ {
fieldValue := patchValue.Field(i)
field := fieldValue.Interface().(Optional)
if field.IsSpecified() {
columnsToUpdate = append(columnsToUpdate, allColumns[i])
if !field.IsNil() {
modelValue.Field(i).Set(reflect.ValueOf(field.MustGet()))
}
}
}
return columnsToUpdate, modelToUpdate
} Then you can call it for any table update: func UpdatePost(ctx context.Context, db *sql.DB, postID int64, in PostSetter) {
cols, m := Patch[model.Post](in, Post.AllColumns)
q := t.Post.UPDATE(cols).
MODEL(m).
WHERE(t.Post.ID.EQ(p.Int(postID))).
RETURNING(t.Post.AllColumns)
var dest model.Post
if err := q.QueryContext(ctx, db, &dest); err != nil {
fmt.Println("failed:", err.Error())
}
} Then, to generate patch models (PostSetter), you can add another jet generator call, with your optional field type customization. Check generator customization. |
Beta Was this translation helpful? Give feedback.
-
Hey thanks for this cool lib!
Just wanted to ask how you guys deal with creates or updates from a model or manually?
Ofc i can create my own "omit" pkg with that neat map trick (what oapi-codegen is doing with its nullable pkg...) and pass it to every repo func to do stuff if explicit null was provided or if value was unspecified, but could it be generated by this library?
Something like what go bob sql builder is doing, they create one "read" model and one "setter' with those omit/nullable fields.
I guess i could just modify the fields of the existing model in the code gen like in #360, but i still think it would be better to have those two separate, what do you think in general?
Beta Was this translation helpful? Give feedback.
All reactions