JSON fields for saving collection diff

This commit is contained in:
Sergey Polygalin 2023-12-17 17:39:36 +03:00
parent a643fd99f2
commit 63d80c1f08
1 changed files with 36 additions and 0 deletions

View File

@ -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(',')
}