(j JSON, key string, newVal JSON, insertAfter bool)
| 1169 | var errCannotReplaceExistingKey = pgerror.WithCandidateCode(errors.New("cannot replace existing key"), pgcode.InvalidParameterValue) |
| 1170 | |
| 1171 | func insertValKeyOrIdx(j JSON, key string, newVal JSON, insertAfter bool) (JSON, error) { |
| 1172 | switch v := j.(type) { |
| 1173 | case *jsonEncoded: |
| 1174 | n, err := v.shallowDecode() |
| 1175 | if err != nil { |
| 1176 | return nil, err |
| 1177 | } |
| 1178 | return insertValKeyOrIdx(n, key, newVal, insertAfter) |
| 1179 | case jsonObject: |
| 1180 | result, err := v.SetKey(key, newVal, true) |
| 1181 | if err != nil { |
| 1182 | return nil, err |
| 1183 | } |
| 1184 | if len(result) == len(v) { |
| 1185 | return nil, errCannotReplaceExistingKey |
| 1186 | } |
| 1187 | return result, nil |
| 1188 | case jsonArray: |
| 1189 | idx, err := strconv.Atoi(key) |
| 1190 | if err != nil { |
| 1191 | return nil, err |
| 1192 | } |
| 1193 | if idx < 0 { |
| 1194 | idx = len(v) + idx |
| 1195 | } |
| 1196 | if insertAfter { |
| 1197 | idx++ |
| 1198 | } |
| 1199 | |
| 1200 | var result = make(jsonArray, len(v)+1) |
| 1201 | if idx <= 0 { |
| 1202 | copy(result[1:], v) |
| 1203 | result[0] = newVal |
| 1204 | } else if idx >= len(v) { |
| 1205 | copy(result, v) |
| 1206 | result[len(result)-1] = newVal |
| 1207 | } else { |
| 1208 | copy(result[:idx], v[:idx]) |
| 1209 | copy(result[idx+1:], v[idx:]) |
| 1210 | result[idx] = newVal |
| 1211 | } |
| 1212 | return result, nil |
| 1213 | } |
| 1214 | return j, nil |
| 1215 | } |
| 1216 | |
| 1217 | // DeepInsert inserts a value at a path in a JSON document. |
| 1218 | // Implements the jsonb_insert builtin. |
no test coverage detected
searching dependent graphs…