import { is_date as isDate } from "@cocalc/util/misc" ; export function jsonbSet ( desc , merge = false ) { const params = [ ] ; function pushParam ( val , type ) { if ( type . toUpperCase ( ) == "JSONB" ) { val = JSON . stringify ( val ) ; } params . push ( val ) ; return params . length ; } function set ( field , data , path ) { let obj = `COALESCE(${ field }#>'{${ path . join ( "," ) }}', '{}'::JSONB)` ; for ( const key in data ) { const val = data [ key ] ; if ( val == null ) { obj = `(${ obj } - '${ key }')` ; } else { if ( merge && typeof val === "object" && ! isDate ( val ) ) { const subobj = set ( field , val , path . concat ( [ key ] ) ) ; obj = `JSONB_SET(${ obj }, '{${ key }}', ${ subobj })` ; } else { obj = `JSONB_SET(${ obj }, '{${ key }}', $${ pushParam ( val , "JSONB" ) }::JSONB)` ; } } } return obj ; } const v = [ ] ; for ( const field in desc ) { const data = desc [ field ] ; v . push ( `${ field }=${ set ( field , data , [ ] ) }` ) ; } return { set : v . join ( "," ) , params } ; }