From 9f755c9838587a55c555fce009209e5eb90c80bd Mon Sep 17 00:00:00 2001 From: Mirek Rusin Date: Thu, 17 Aug 2023 09:04:41 +0200 Subject: [PATCH] feat(json): support force mode in jsonModify --- src/json-modify.test.ts | 14 ++++++++++++++ src/json-modify.ts | 31 ++++++++++++++++++++++++------- src/sql.test.ts | 9 ++++++++- 3 files changed, 46 insertions(+), 8 deletions(-) diff --git a/src/json-modify.test.ts b/src/json-modify.test.ts index 2452d01..5e0072d 100644 --- a/src/json-modify.test.ts +++ b/src/json-modify.test.ts @@ -21,3 +21,17 @@ test('jsonModify', () => { ) `)) }) + +test('jsonModify force', () => { + expect(Tsql.jsonModify(Tsql.raw('fooJson'), { 'force ref': null }).toString()).toEqual(Tsql.demargin(` + json_modify( + json_modify( + fooJson, + N'lax $.ref', + cast(1 as bit) + ), + N'strict $.ref', + null + ) + `)) +}) diff --git a/src/json-modify.ts b/src/json-modify.ts index 5cf988e..772abab 100644 --- a/src/json-modify.ts +++ b/src/json-modify.ts @@ -1,18 +1,35 @@ import auto from './auto.js' import jsonPath from './json-path.js' +import trueValue from './true-value.js' import tsql from './template.js' import type S from './sanitised.js' export const jsonModify = (target: S, kvs: Record): S => { const paths = Object.keys(kvs) - return paths.reduce((result, path) => tsql` - json_modify( - ${result}, - ${jsonPath(path)}, - ${auto(kvs[path])} - ) - `, target) + return paths.reduce((result, path) => { + if (path.startsWith('force ')) { + const path_ = path.slice('force '.length) + return tsql` + json_modify( + json_modify( + ${result}, + ${'lax ' + jsonPath(path_)}, + ${trueValue} + ), + ${'strict ' + jsonPath(path_)}, + ${auto(kvs[path])} + ) + ` + } + return tsql` + json_modify( + ${result}, + ${jsonPath(path)}, + ${auto(kvs[path])} + ) + ` + }, target) } export default jsonModify diff --git a/src/sql.test.ts b/src/sql.test.ts index d765c2e..bf52ddb 100644 --- a/src/sql.test.ts +++ b/src/sql.test.ts @@ -1,5 +1,5 @@ +import * as Tsql from './index.js' import Sql from './test/sql.js' -import type * as Tsql from './index.js' let sql: Sql @@ -142,3 +142,10 @@ describe('merge1n', () => { }) }) + +test('force json mode', async () => { + await expect(sql.value`select ${Tsql.jsonModify(Tsql.auto({ foo: 1 }), { 'force bar': null })}`).resolves.toEqual(JSON.stringify({ + foo: 1, + bar: null + })) +})