diff --git a/tpl/macros_struct.twig b/tpl/macros_struct.twig index 4cf61d0..4b45f11 100644 --- a/tpl/macros_struct.twig +++ b/tpl/macros_struct.twig @@ -225,7 +225,9 @@ func Save{{ ctx.s.name }}CollectionDiff(ctx context.Context, dbe metadb.Execer, } key := rec.changedFields.GetFieldsKey() - if _, ok := byFieldsKey[key]; !ok { + _, ok := byFieldsKey[key] + firstRecord := !ok + if firstRecord { builder := NewQueryDiffBuilder() builder.query.WriteString("INSERT INTO `{{ ctx.table_name }}` ({{ ctx.pkey_column_expr }}") @@ -263,13 +265,11 @@ func Save{{ ctx.s.name }}CollectionDiff(ctx context.Context, dbe metadb.Execer, {% 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 }}) + jsonBuilder.WriteString(",'$.{{ f|alias }}',JSON_EXTRACT(VALUES(`kv`), '$.{{ f|alias }}')") {%~ else %} jsonBuilder.WriteString(",'$.{{ f|alias }}',") jsonBytes, err := json.Marshal(rec.{{ fname }}) @@ -284,15 +284,17 @@ func Save{{ ctx.s.name }}CollectionDiff(ctx context.Context, dbe metadb.Execer, {% endfor %} if jsonBuilder.Len() > 0 { - builder.query.WriteString(",`kv`") + if firstRecord { + builder.query.WriteString(",`kv`") + + builder.update.WriteString(",`kv`=JSON_SET(`kv`") + builder.update.WriteString(jsonBuilder.String()) + builder.update.WriteRune(')') + } + 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 %}