(j JSON, key string, newVal JSON, insertAfter bool)
| 1254 | var errCannotReplaceExistingKey = pgerror.WithCandidateCode(errors.New("cannot replace existing key"), pgcode.InvalidParameterValue) |
| 1255 | |
| 1256 | func 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. |
no test coverage detected