(j JSON, key string, newVal JSON, insertAfter bool)
| 2264 | var errCannotReplaceExistingKey = pgerror.WithCandidateCode(errors.New("cannot replace existing key"), pgcode.InvalidParameterValue) |
| 2265 | |
| 2266 | func insertValKeyOrIdx(j JSON, key string, newVal JSON, insertAfter bool) (JSON, error) { |
| 2267 | switch v := j.(type) { |
| 2268 | case *jsonEncoded: |
| 2269 | n, err := v.shallowDecode() |
| 2270 | if err != nil { |
| 2271 | return nil, err |
| 2272 | } |
| 2273 | return insertValKeyOrIdx(n, key, newVal, insertAfter) |
| 2274 | case jsonObject: |
| 2275 | result, err := v.SetKey(key, newVal, true) |
| 2276 | if err != nil { |
| 2277 | return nil, err |
| 2278 | } |
| 2279 | if len(result) == len(v) { |
| 2280 | return nil, errCannotReplaceExistingKey |
| 2281 | } |
| 2282 | return result, nil |
| 2283 | case jsonArray: |
| 2284 | idx, err := strconv.Atoi(key) |
| 2285 | if err != nil { |
| 2286 | return nil, err |
| 2287 | } |
| 2288 | if idx < 0 { |
| 2289 | idx = len(v) + idx |
| 2290 | } |
| 2291 | if insertAfter { |
| 2292 | idx++ |
| 2293 | } |
| 2294 | |
| 2295 | var result = make(jsonArray, len(v)+1) |
| 2296 | if idx <= 0 { |
| 2297 | copy(result[1:], v) |
| 2298 | result[0] = newVal |
| 2299 | } else if idx >= len(v) { |
| 2300 | copy(result, v) |
| 2301 | result[len(result)-1] = newVal |
| 2302 | } else { |
| 2303 | copy(result[:idx], v[:idx]) |
| 2304 | copy(result[idx+1:], v[idx:]) |
| 2305 | result[idx] = newVal |
| 2306 | } |
| 2307 | return result, nil |
| 2308 | } |
| 2309 | return j, nil |
| 2310 | } |
| 2311 | |
| 2312 | // DeepInsert inserts a value at a path in a JSON document. |
| 2313 | // Implements the jsonb_insert builtin. |
no test coverage detected
searching dependent graphs…