diff --git a/tpl/macros_struct.twig b/tpl/macros_struct.twig index 3c06c41..fd16194 100644 --- a/tpl/macros_struct.twig +++ b/tpl/macros_struct.twig @@ -257,6 +257,42 @@ func Save{{ ctx.s.name }}CollectionDiff(ctx context.Context, dbe metadb.Execer, {% endfor %} {% endif %} + {% if has_token(ctx.s, 'table_json_kv') %} + var jsonBuilder strings.Builder + + jsonValues := make([]any, 0, {{ ctx.json_fields|length }}) + {% for f in ctx.json_fields %} + {% set fname = f|fname %} + if rec.{{ f|fname }}Changed() { + {%~ if f.type is builtin %} + jsonBuilder.WriteString(",'$.{{ f|alias }}',?") + jsonValues = append(jsonValues, rec.{{ f|fname }}) + {%~ else %} + jsonBuilder.WriteString(",'$.{{ f|alias }}',") + jsonBytes, err := json.Marshal(rec.{{ fname }}) + if err != nil { + return errors.WithStack(err) + } + jsonBuilder.WriteString("CAST(") + jsonBuilder.WriteString(strconv.Quote(string(jsonBytes))) + jsonBuilder.WriteString(" AS JSON)") + {%~ endif %} + } + {% endfor %} + + if jsonBuilder.Len() > 0 { + builder.query.WriteString(",`kv`") + builder.values.WriteString(",?") + + builder.update.WriteString(",`kv`=JSON_SET(`kv`") + builder.update.WriteString(jsonBuilder.String()) + builder.update.WriteRune(')') + + builder.rawValues = append(builder.rawValues, rec.{{ ctx.s.name }}JsonValues) + builder.rawValues = append(builder.rawValues, jsonValues...) + } + {% endif %} + builder.values.WriteRune(')') builder.values.WriteRune(',') }