From 63d80c1f08aeb695923448d1982a7b1b106f1ed4 Mon Sep 17 00:00:00 2001 From: Sergey Polygalin Date: Sun, 17 Dec 2023 17:39:36 +0300 Subject: [PATCH] JSON fields for saving collection diff --- tpl/macros_struct.twig | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) 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(',') }