From 72ef58cd55ab14e759c217db6603d51decb4f738 Mon Sep 17 00:00:00 2001 From: Pavel Merzlyakov Date: Tue, 5 Mar 2024 20:24:15 +0300 Subject: [PATCH] fix saving table_json_kv field diff --- tpl/macros_struct.twig | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) 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 %}