MCPcopy Create free account
hub / github.com/dolthub/doltgresql / insertValKeyOrIdx

Function insertValKeyOrIdx

postgres/parser/json/json.go:1256–1300  ·  view source on GitHub ↗
(j JSON, key string, newVal JSON, insertAfter bool)

Source from the content-addressed store, hash-verified

1254var errCannotReplaceExistingKey = pgerror.WithCandidateCode(errors.New("cannot replace existing key"), pgcode.InvalidParameterValue)
1255
1256func insertValKeyOrIdx(j JSON, key string, newVal JSON, insertAfter bool) (JSON, error) {
1257 switch v := j.(type) {
1258 case *jsonEncoded:
1259 n, err := v.shallowDecode()
1260 if err != nil {
1261 return nil, err
1262 }
1263 return insertValKeyOrIdx(n, key, newVal, insertAfter)
1264 case jsonObject:
1265 result, err := v.SetKey(key, newVal, true)
1266 if err != nil {
1267 return nil, err
1268 }
1269 if len(result) == len(v) {
1270 return nil, errCannotReplaceExistingKey
1271 }
1272 return result, nil
1273 case jsonArray:
1274 idx, err := strconv.Atoi(key)
1275 if err != nil {
1276 return nil, err
1277 }
1278 if idx < 0 {
1279 idx = len(v) + idx
1280 }
1281 if insertAfter {
1282 idx++
1283 }
1284
1285 var result = make(jsonArray, len(v)+1)
1286 if idx <= 0 {
1287 copy(result[1:], v)
1288 result[0] = newVal
1289 } else if idx >= len(v) {
1290 copy(result, v)
1291 result[len(result)-1] = newVal
1292 } else {
1293 copy(result[:idx], v[:idx])
1294 copy(result[idx+1:], v[idx:])
1295 result[idx] = newVal
1296 }
1297 return result, nil
1298 }
1299 return j, nil
1300}
1301
1302// DeepInsert inserts a value at a path in a JSON document.
1303// Implements the jsonb_insert builtin.

Callers 1

deepInsertFunction · 0.85

Calls 2

shallowDecodeMethod · 0.80
SetKeyMethod · 0.80

Tested by

no test coverage detected