jsonb.go 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852
  1. package executor
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "math/big"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. "unicode/utf8"
  12. "github.com/danfragoso/pizzasql-next/pkg/lexer"
  13. "github.com/danfragoso/pizzasql-next/pkg/parser"
  14. "github.com/danfragoso/pizzasql-next/pkg/pgerror"
  15. "github.com/danfragoso/pizzasql-next/pkg/storage"
  16. )
  17. // JSONB values are carried as canonical JSON text: object keys sorted, duplicate
  18. // keys collapsed last-wins, no insignificant whitespace, and numbers written as
  19. // exact normalized decimals. The canonical form is idempotent and is what every
  20. // write path stores, so a reload returns the same bytes and equality can be
  21. // defined on them.
  22. //
  23. // A JSONB column is distinguished from JSON/TEXT by its declared type. The
  24. // executor resolves that type from the statement's column-type scopes (the same
  25. // mechanism arrays use), so operators and functions know whether a text value is
  26. // a jsonb document or ordinary SQL text.
  27. // maxJSONBNumberDigits bounds the decimal expansion of a jsonb number. It
  28. // matches PostgreSQL's numeric digit limit and keeps a short exponent such as
  29. // 1e1000000 from allocating an enormous canonical string.
  30. const maxJSONBNumberDigits = 131072
  31. // CanonicalizeJSONB validates JSON text and returns its canonical JSONB form.
  32. // It is exported so the protocol layer can canonicalize a text-format jsonb
  33. // parameter at Bind time.
  34. func CanonicalizeJSONB(text string) (string, error) {
  35. node, err := decodeJSONB(text)
  36. if err != nil {
  37. return "", invalidJSONBInput(text)
  38. }
  39. canonical, err := encodeJSONB(node, false)
  40. if err != nil {
  41. return "", invalidJSONBInput(text)
  42. }
  43. return canonical, nil
  44. }
  45. func invalidJSONBInput(text string) error {
  46. return pgerror.InvalidText("invalid input syntax for type jsonb: %q", text)
  47. }
  48. // decodeJSONB parses one JSON document strictly. Duplicate object keys collapse
  49. // last-wins (encoding/json's map decoding), invalid UTF-8 and trailing content
  50. // are rejected, and numbers stay exact as json.Number.
  51. func decodeJSONB(text string) (interface{}, error) {
  52. if !utf8.ValidString(text) {
  53. return nil, invalidJSONBInput(text)
  54. }
  55. if err := validateJSONBUnicodeEscapes(text); err != nil {
  56. return nil, err
  57. }
  58. dec := json.NewDecoder(strings.NewReader(text))
  59. dec.UseNumber()
  60. var node interface{}
  61. if err := dec.Decode(&node); err != nil {
  62. return nil, invalidJSONBInput(text)
  63. }
  64. var trailing interface{}
  65. if err := dec.Decode(&trailing); err != io.EOF {
  66. return nil, invalidJSONBInput(text)
  67. }
  68. return node, nil
  69. }
  70. // validateJSONBUnicodeEscapes rejects escapes that encoding/json would accept
  71. // by rewriting them: U+0000 and unpaired UTF-16 surrogates. PostgreSQL rejects
  72. // both in jsonb input with 22P02 instead of silently producing U+FFFD.
  73. func validateJSONBUnicodeEscapes(text string) error {
  74. inString := false
  75. for i := 0; i < len(text); i++ {
  76. c := text[i]
  77. if !inString {
  78. if c == '"' {
  79. inString = true
  80. }
  81. continue
  82. }
  83. if c == '"' {
  84. inString = false
  85. continue
  86. }
  87. if c != '\\' {
  88. continue
  89. }
  90. if i+1 >= len(text) {
  91. return invalidJSONBInput(text)
  92. }
  93. i++
  94. if text[i] != 'u' {
  95. continue
  96. }
  97. if i+4 >= len(text) {
  98. return invalidJSONBInput(text)
  99. }
  100. value, ok := parseJSONBHex4(text[i+1 : i+5])
  101. if !ok {
  102. return invalidJSONBInput(text)
  103. }
  104. i += 4
  105. switch {
  106. case value == 0:
  107. return invalidJSONBInput(text)
  108. case value >= 0xD800 && value <= 0xDBFF:
  109. // A high surrogate must be followed by a low surrogate escape.
  110. if i+7 > len(text) || text[i+1] != '\\' || text[i+2] != 'u' {
  111. return invalidJSONBInput(text)
  112. }
  113. low, ok := parseJSONBHex4(text[i+3 : i+7])
  114. if !ok || low < 0xDC00 || low > 0xDFFF {
  115. return invalidJSONBInput(text)
  116. }
  117. i += 6
  118. case value >= 0xDC00 && value <= 0xDFFF:
  119. return invalidJSONBInput(text)
  120. }
  121. }
  122. return nil
  123. }
  124. func parseJSONBHex4(text string) (uint32, bool) {
  125. var value uint32
  126. for i := 0; i < 4; i++ {
  127. digit := text[i]
  128. var nibble uint32
  129. switch {
  130. case digit >= '0' && digit <= '9':
  131. nibble = uint32(digit - '0')
  132. case digit >= 'a' && digit <= 'f':
  133. nibble = uint32(digit-'a') + 10
  134. case digit >= 'A' && digit <= 'F':
  135. nibble = uint32(digit-'A') + 10
  136. default:
  137. return 0, false
  138. }
  139. value = value<<4 | nibble
  140. }
  141. return value, true
  142. }
  143. // encodeJSONB writes a decoded JSON tree in canonical form. pretty selects the
  144. // four-space indented jsonb_pretty rendering.
  145. func encodeJSONB(node interface{}, pretty bool) (string, error) {
  146. var buf bytes.Buffer
  147. if err := writeJSONBNode(&buf, node, pretty, 0); err != nil {
  148. return "", err
  149. }
  150. return buf.String(), nil
  151. }
  152. func writeJSONBNode(buf *bytes.Buffer, node interface{}, pretty bool, depth int) error {
  153. switch value := node.(type) {
  154. case nil:
  155. buf.WriteString("null")
  156. case bool:
  157. if value {
  158. buf.WriteString("true")
  159. } else {
  160. buf.WriteString("false")
  161. }
  162. case json.Number:
  163. text, err := canonicalJSONBNumber(value)
  164. if err != nil {
  165. return err
  166. }
  167. buf.WriteString(text)
  168. case string:
  169. writeJSONBString(buf, value)
  170. case []interface{}:
  171. if len(value) == 0 {
  172. buf.WriteString("[]")
  173. return nil
  174. }
  175. buf.WriteByte('[')
  176. for i, element := range value {
  177. if i > 0 {
  178. buf.WriteByte(',')
  179. }
  180. if pretty {
  181. buf.WriteByte('\n')
  182. writeJSONBIndent(buf, depth+1)
  183. }
  184. if err := writeJSONBNode(buf, element, pretty, depth+1); err != nil {
  185. return err
  186. }
  187. }
  188. if pretty {
  189. buf.WriteByte('\n')
  190. writeJSONBIndent(buf, depth)
  191. }
  192. buf.WriteByte(']')
  193. case map[string]interface{}:
  194. if len(value) == 0 {
  195. buf.WriteString("{}")
  196. return nil
  197. }
  198. keys := make([]string, 0, len(value))
  199. for key := range value {
  200. keys = append(keys, key)
  201. }
  202. sort.Strings(keys)
  203. buf.WriteByte('{')
  204. for i, key := range keys {
  205. if i > 0 {
  206. buf.WriteByte(',')
  207. }
  208. if pretty {
  209. buf.WriteByte('\n')
  210. writeJSONBIndent(buf, depth+1)
  211. }
  212. writeJSONBString(buf, key)
  213. buf.WriteByte(':')
  214. if pretty {
  215. buf.WriteByte(' ')
  216. }
  217. if err := writeJSONBNode(buf, value[key], pretty, depth+1); err != nil {
  218. return err
  219. }
  220. }
  221. if pretty {
  222. buf.WriteByte('\n')
  223. writeJSONBIndent(buf, depth)
  224. }
  225. buf.WriteByte('}')
  226. default:
  227. return pgerror.InvalidParameter("unsupported jsonb node type %T", node)
  228. }
  229. return nil
  230. }
  231. func writeJSONBIndent(buf *bytes.Buffer, depth int) {
  232. for i := 0; i < depth; i++ {
  233. buf.WriteString(" ")
  234. }
  235. }
  236. // writeJSONBString writes a JSON string literal without HTML escaping and
  237. // without rewriting valid UTF-8. Control characters use the short escapes JSON
  238. // defines, or \u00XX for the rest.
  239. func writeJSONBString(buf *bytes.Buffer, value string) {
  240. buf.WriteByte('"')
  241. for _, r := range value {
  242. switch r {
  243. case '"':
  244. buf.WriteString(`\"`)
  245. case '\\':
  246. buf.WriteString(`\\`)
  247. case '\n':
  248. buf.WriteString(`\n`)
  249. case '\r':
  250. buf.WriteString(`\r`)
  251. case '\t':
  252. buf.WriteString(`\t`)
  253. case '\b':
  254. buf.WriteString(`\b`)
  255. case '\f':
  256. buf.WriteString(`\f`)
  257. default:
  258. if r < 0x20 {
  259. const hex = "0123456789abcdef"
  260. buf.WriteString(`\u00`)
  261. buf.WriteByte(hex[byte(r)>>4])
  262. buf.WriteByte(hex[byte(r)&0x0f])
  263. continue
  264. }
  265. buf.WriteRune(r)
  266. }
  267. }
  268. buf.WriteByte('"')
  269. }
  270. // canonicalJSONBNumber normalizes a JSON number to an exact decimal spelling:
  271. // no exponent, no trailing fractional zeros, and no negative zero. The input is
  272. // a finite decimal, so the exact expansion always terminates.
  273. func canonicalJSONBNumber(number json.Number) (string, error) {
  274. text := string(number)
  275. negative := false
  276. i := 0
  277. if i < len(text) && text[i] == '-' {
  278. negative = true
  279. i++
  280. }
  281. start := i
  282. for i < len(text) && text[i] >= '0' && text[i] <= '9' {
  283. i++
  284. }
  285. digits := text[start:i]
  286. if digits == "" {
  287. return "", invalidJSONBInput(text)
  288. }
  289. fraction := ""
  290. if i < len(text) && text[i] == '.' {
  291. i++
  292. fractionStart := i
  293. for i < len(text) && text[i] >= '0' && text[i] <= '9' {
  294. i++
  295. }
  296. fraction = text[fractionStart:i]
  297. }
  298. exponent := 0
  299. if i < len(text) && (text[i] == 'e' || text[i] == 'E') {
  300. i++
  301. parsed, err := strconv.Atoi(text[i:])
  302. if err != nil {
  303. return "", invalidJSONBInput(text)
  304. }
  305. exponent = parsed
  306. } else if i != len(text) {
  307. return "", invalidJSONBInput(text)
  308. }
  309. allDigits := digits + fraction
  310. if len(allDigits) > maxJSONBNumberDigits {
  311. return "", pgerror.InvalidText("jsonb number field overflow")
  312. }
  313. mantissa := new(big.Int)
  314. if _, ok := mantissa.SetString(allDigits, 10); !ok {
  315. return "", invalidJSONBInput(text)
  316. }
  317. if mantissa.Sign() == 0 {
  318. return "0", nil
  319. }
  320. // value = mantissa / 10^scale, where scale = len(fraction) - exponent.
  321. scale := len(fraction) - exponent
  322. rendered := mantissa.String()
  323. if scale <= 0 {
  324. if len(rendered)-scale > maxJSONBNumberDigits {
  325. return "", pgerror.InvalidText("jsonb number field overflow")
  326. }
  327. rendered += strings.Repeat("0", -scale)
  328. } else {
  329. // Strip trailing zeros in the fractional part before rendering.
  330. for scale > 0 && len(rendered) > 1 && rendered[len(rendered)-1] == '0' {
  331. rendered = rendered[:len(rendered)-1]
  332. scale--
  333. }
  334. if scale >= len(rendered) {
  335. if scale > maxJSONBNumberDigits {
  336. return "", pgerror.InvalidText("jsonb number field overflow")
  337. }
  338. rendered = "0." + strings.Repeat("0", scale-len(rendered)) + rendered
  339. } else if scale > 0 {
  340. rendered = rendered[:len(rendered)-scale] + "." + rendered[len(rendered)-scale:]
  341. }
  342. }
  343. if negative {
  344. return "-" + rendered, nil
  345. }
  346. return rendered, nil
  347. }
  348. // jsonbNodeFromArg resolves a jsonb function or operator operand to a decoded
  349. // tree. NULL stays SQL NULL; text and the JSON subtype are parsed as a document.
  350. func jsonbNodeFromArg(value interface{}) (interface{}, error) {
  351. switch typed := value.(type) {
  352. case nil:
  353. return nil, nil
  354. case string:
  355. return decodeJSONB(typed)
  356. case jsonText:
  357. return decodeJSONB(string(typed))
  358. case []byte:
  359. return decodeJSONB(string(typed))
  360. default:
  361. return nil, pgerror.DatatypeMismatch("jsonb value must be JSON text, got %T", value)
  362. }
  363. }
  364. // jsonbNodeFromSQLValue converts a SQL value into a JSON tree node for
  365. // to_jsonb, jsonb_build_array, and jsonb_build_object values. NULL maps to JSON
  366. // null; callers decide whether a top-level NULL stays SQL NULL.
  367. func jsonbNodeFromSQLValue(value interface{}) (interface{}, error) {
  368. switch typed := value.(type) {
  369. case nil:
  370. return nil, nil
  371. case bool:
  372. return typed, nil
  373. case int:
  374. return json.Number(strconv.FormatInt(int64(typed), 10)), nil
  375. case int8:
  376. return json.Number(strconv.FormatInt(int64(typed), 10)), nil
  377. case int16:
  378. return json.Number(strconv.FormatInt(int64(typed), 10)), nil
  379. case int32:
  380. return json.Number(strconv.FormatInt(int64(typed), 10)), nil
  381. case int64:
  382. return json.Number(strconv.FormatInt(typed, 10)), nil
  383. case uint:
  384. return json.Number(strconv.FormatUint(uint64(typed), 10)), nil
  385. case uint32:
  386. return json.Number(strconv.FormatUint(uint64(typed), 10)), nil
  387. case uint64:
  388. return json.Number(strconv.FormatUint(typed, 10)), nil
  389. case float32:
  390. return json.Number(strconv.FormatFloat(float64(typed), 'g', -1, 32)), nil
  391. case float64:
  392. if typed != typed {
  393. return nil, pgerror.InvalidParameter("cannot convert NaN to jsonb")
  394. }
  395. if typed > 1.7976931348623157e308 || typed < -1.7976931348623157e308 {
  396. return nil, pgerror.InvalidParameter("cannot convert infinity to jsonb")
  397. }
  398. return json.Number(strconv.FormatFloat(typed, 'g', -1, 64)), nil
  399. case string:
  400. return typed, nil
  401. case jsonText:
  402. return string(typed), nil
  403. case []byte:
  404. return string(typed), nil
  405. default:
  406. return toString(value), nil
  407. }
  408. }
  409. // jsonbNodeToText renders a jsonb node as the SQL text that ->> and the *_text
  410. // set-returning functions return. JSON null becomes SQL NULL.
  411. func jsonbNodeToText(node interface{}) (interface{}, error) {
  412. switch value := node.(type) {
  413. case nil:
  414. return nil, nil
  415. case bool:
  416. if value {
  417. return "true", nil
  418. }
  419. return "false", nil
  420. case json.Number:
  421. return canonicalJSONBNumber(value)
  422. case string:
  423. return value, nil
  424. default:
  425. return encodeJSONB(node, false)
  426. }
  427. }
  428. // isJSONBExpr reports whether an expression produces a jsonb value. It follows
  429. // the statement's column-type scopes, so a JSONB column, a cast, and a jsonb
  430. // function are all recognized even though their runtime carrier is text.
  431. func (e *Executor) isJSONBExpr(expr parser.Expr) bool {
  432. switch typed := expr.(type) {
  433. case nil:
  434. return false
  435. case *parser.ParenExpr:
  436. return e.isJSONBExpr(typed.Expr)
  437. case *parser.CastExpr:
  438. return strings.EqualFold(strings.TrimSpace(typed.Type.Name), "JSONB")
  439. case *parser.BinaryExpr:
  440. switch typed.Op {
  441. case lexer.TokenArrow, lexer.TokenHashArrow, lexer.TokenHashMinus:
  442. return e.isJSONBExpr(typed.Left)
  443. case lexer.TokenConcat:
  444. return e.isJSONBExpr(typed.Left) || e.isJSONBExpr(typed.Right)
  445. case lexer.TokenMinus:
  446. return e.isJSONBExpr(typed.Left)
  447. }
  448. return false
  449. case *parser.FunctionCall:
  450. if jsonbFunctionReturnsJSONB(typed.Name) {
  451. return true
  452. }
  453. }
  454. return strings.EqualFold(strings.TrimSpace(inferExprType(expr, e.resolveColumnType)), "JSONB")
  455. }
  456. // jsonbFunctionReturnsJSONB reports whether a scalar function returns jsonb.
  457. func jsonbFunctionReturnsJSONB(name string) bool {
  458. switch strings.ToUpper(name) {
  459. case "TO_JSONB", "JSONB_SET", "JSONB_INSERT", "JSONB_REPLACE", "JSONB_REMOVE",
  460. "JSONB_STRIP_NULLS", "JSONB_BUILD_OBJECT", "JSONB_BUILD_ARRAY":
  461. return true
  462. default:
  463. return false
  464. }
  465. }
  466. // evalJSONBBinary applies the jsonb operators. handled is false when the operator
  467. // and operands are not a jsonb form, leaving ordinary SQL semantics untouched.
  468. func (e *Executor) evalJSONBBinary(op lexer.TokenType, leftExpr, rightExpr parser.Expr, left, right interface{}) (interface{}, bool, error) {
  469. leftJSONB := e.isJSONBExpr(leftExpr)
  470. rightJSONB := e.isJSONBExpr(rightExpr)
  471. if isComparisonOp(op) && (leftJSONB || rightJSONB) {
  472. if left == nil || right == nil {
  473. return nil, true, nil
  474. }
  475. if (leftJSONB && !jsonbComparisonValue(right)) || (rightJSONB && !jsonbComparisonValue(left)) {
  476. return nil, true, pgerror.DatatypeMismatch("jsonb comparison requires jsonb or text operands")
  477. }
  478. // jsonb equality and ordering compare the exact canonical bytes. Using
  479. // the engine's numeric-aware compare here would round through float64 and
  480. // report 1 = 1.0000000000000000001 or collapse integers above 2^53.
  481. leftText, err := CanonicalizeJSONB(toString(left))
  482. if err != nil {
  483. return nil, true, err
  484. }
  485. rightText, err := CanonicalizeJSONB(toString(right))
  486. if err != nil {
  487. return nil, true, err
  488. }
  489. result, err := comparisonOperatorResult(op, strings.Compare(leftText, rightText))
  490. return result, true, err
  491. }
  492. switch op {
  493. case lexer.TokenArrow, lexer.TokenArrowText:
  494. if !leftJSONB {
  495. return nil, false, nil
  496. }
  497. value, err := jsonbArrowExtract(left, right, op == lexer.TokenArrowText)
  498. return value, true, err
  499. case lexer.TokenHashArrow, lexer.TokenHashArrowText:
  500. value, err := jsonbPathExtract(left, right, op == lexer.TokenHashArrowText)
  501. return value, true, err
  502. case lexer.TokenHashMinus:
  503. value, err := jsonbPathDelete(left, right)
  504. return value, true, err
  505. case lexer.TokenAtArrow, lexer.TokenLtAt:
  506. value, err := e.jsonbContainment(op, leftExpr, rightExpr, left, right)
  507. return value, true, err
  508. case lexer.TokenQuestion:
  509. value, err := jsonbKeyExists(left, right)
  510. return value, true, err
  511. case lexer.TokenQuestionPipe, lexer.TokenQuestionAmp:
  512. value, err := jsonbAnyKeysExist(op, left, right)
  513. return value, true, err
  514. case lexer.TokenConcat:
  515. if !leftJSONB && !rightJSONB {
  516. return nil, false, nil
  517. }
  518. if left == nil || right == nil {
  519. return nil, true, nil
  520. }
  521. leftNode, err := jsonbNodeFromArg(left)
  522. if err != nil {
  523. return nil, true, err
  524. }
  525. rightNode, err := jsonbNodeFromArg(right)
  526. if err != nil {
  527. return nil, true, err
  528. }
  529. text, err := encodeJSONB(jsonbConcatNodes(leftNode, rightNode), false)
  530. return text, true, err
  531. case lexer.TokenMinus:
  532. if !leftJSONB {
  533. if rightJSONB {
  534. return nil, true, pgerror.DatatypeMismatch("cannot subtract a jsonb value from a non-jsonb value")
  535. }
  536. return nil, false, nil
  537. }
  538. if left == nil || right == nil {
  539. return nil, true, nil
  540. }
  541. value, err := e.jsonbDeleteValue(leftExpr, rightExpr, left, right)
  542. return value, true, err
  543. case lexer.TokenPlus, lexer.TokenStar, lexer.TokenSlash, lexer.TokenPercent:
  544. if leftJSONB || rightJSONB {
  545. return nil, true, pgerror.DatatypeMismatch("arithmetic operator %s requires numeric operands, got jsonb", op.String())
  546. }
  547. }
  548. return nil, false, nil
  549. }
  550. // jsonbComparisonValue reports whether a runtime value can be read as a jsonb
  551. // document on the other side of a comparison. SQL numbers and booleans are not
  552. // silently reinterpreted as JSON (PostgreSQL has no jsonb = integer operator).
  553. func jsonbComparisonValue(value interface{}) bool {
  554. switch value.(type) {
  555. case string, jsonText, []byte:
  556. return true
  557. default:
  558. return false
  559. }
  560. }
  561. // canonicalizeJSONBReadValue canonicalizes a JSONB-typed value on read so a
  562. // legacy row written before native JSONB still presents canonical text to
  563. // projections, DISTINCT, GROUP BY, and ORDER BY.
  564. func canonicalizeJSONBReadValue(typeName string, value interface{}) (interface{}, error) {
  565. if value == nil || !strings.EqualFold(strings.TrimSpace(typeName), "JSONB") {
  566. return value, nil
  567. }
  568. text, ok := value.(string)
  569. if !ok {
  570. if jsonValue, isJSON := value.(jsonText); isJSON {
  571. text = string(jsonValue)
  572. } else {
  573. return value, nil
  574. }
  575. }
  576. return CanonicalizeJSONB(text)
  577. }
  578. // canonicalizeJSONBColumnValue applies read canonicalization to a column
  579. // reference. It is a no-op for columns whose declared type is not JSONB.
  580. func (e *Executor) canonicalizeJSONBColumnValue(ref *parser.ColumnRef, value interface{}) (interface{}, error) {
  581. if ref == nil || value == nil {
  582. return value, nil
  583. }
  584. typeName, ok := e.resolveColumnType(ref.Table, ref.Column)
  585. if !ok {
  586. return value, nil
  587. }
  588. return canonicalizeJSONBReadValue(typeName, value)
  589. }
  590. // jsonbArrowPath resolves the right operand of -> and ->> for a jsonb document.
  591. // A $ path is validated like every other jsonb path, so wildcards and slices
  592. // are rejected with 0A000 rather than misinterpreted as member names.
  593. func jsonbArrowPath(key interface{}) ([]jsonPathSeg, error) {
  594. switch typed := key.(type) {
  595. case string:
  596. if strings.HasPrefix(strings.TrimSpace(typed), "$") {
  597. return parseJSONBJSONPath(typed)
  598. }
  599. return jsonArrowPath(key)
  600. case jsonText:
  601. if strings.HasPrefix(strings.TrimSpace(string(typed)), "$") {
  602. return parseJSONBJSONPath(string(typed))
  603. }
  604. return jsonArrowPath(key)
  605. default:
  606. return jsonArrowPath(key)
  607. }
  608. }
  609. // jsonbArrowExtract evaluates -> and ->> against a jsonb document. A missing
  610. // path is SQL NULL; a JSON null member is the jsonb value "null" for -> and SQL
  611. // NULL for ->>.
  612. func jsonbArrowExtract(document, key interface{}, scalar bool) (interface{}, error) {
  613. if document == nil || key == nil {
  614. return nil, nil
  615. }
  616. node, err := jsonbNodeFromArg(document)
  617. if err != nil {
  618. return nil, err
  619. }
  620. segs, err := jsonbArrowPath(key)
  621. if err != nil {
  622. return nil, err
  623. }
  624. found, ok := jsonLookup(node, segs)
  625. if !ok {
  626. return nil, nil
  627. }
  628. if scalar {
  629. return jsonbNodeToText(found)
  630. }
  631. return encodeJSONB(found, false)
  632. }
  633. // jsonbPathExtract evaluates #> and #>>. The path operand is a PostgreSQL
  634. // text[] (canonical array text) or a $ path.
  635. func jsonbPathExtract(document, path interface{}, scalar bool) (interface{}, error) {
  636. if document == nil || path == nil {
  637. return nil, nil
  638. }
  639. node, err := jsonbNodeFromArg(document)
  640. if err != nil {
  641. return nil, err
  642. }
  643. segs, err := jsonbPathArg(path)
  644. if err != nil {
  645. return nil, err
  646. }
  647. found, ok, err := jsonLookupE(node, segs)
  648. if err != nil {
  649. return nil, err
  650. }
  651. if !ok {
  652. return nil, nil
  653. }
  654. if scalar {
  655. return jsonbNodeToText(found)
  656. }
  657. return encodeJSONB(found, false)
  658. }
  659. // jsonbPathDelete evaluates #-. A missing path leaves the document unchanged.
  660. func jsonbPathDelete(document, path interface{}) (interface{}, error) {
  661. if document == nil || path == nil {
  662. return nil, nil
  663. }
  664. node, err := jsonbNodeFromArg(document)
  665. if err != nil {
  666. return nil, err
  667. }
  668. segs, err := jsonbPathArg(path)
  669. if err != nil {
  670. return nil, err
  671. }
  672. updated, err := jsonRemove(node, segs)
  673. if err != nil {
  674. return nil, err
  675. }
  676. return encodeJSONB(updated, false)
  677. }
  678. // jsonbContainment evaluates @> and <@. The jsonb operand must be present on at
  679. // least one side so a text-only comparison is not silently reinterpreted.
  680. func (e *Executor) jsonbContainment(op lexer.TokenType, leftExpr, rightExpr parser.Expr, left, right interface{}) (interface{}, error) {
  681. leftJSONB := e.isJSONBExpr(leftExpr)
  682. rightJSONB := e.isJSONBExpr(rightExpr)
  683. if !leftJSONB && !rightJSONB {
  684. return nil, pgerror.DatatypeMismatch("jsonb containment requires a jsonb operand; cast one side with ::jsonb")
  685. }
  686. if left == nil || right == nil {
  687. return nil, nil
  688. }
  689. leftNode, err := jsonbNodeFromArg(left)
  690. if err != nil {
  691. return nil, err
  692. }
  693. rightNode, err := jsonbNodeFromArg(right)
  694. if err != nil {
  695. return nil, err
  696. }
  697. switch op {
  698. case lexer.TokenAtArrow:
  699. return jsonbContains(leftNode, rightNode), nil
  700. case lexer.TokenLtAt:
  701. return jsonbContains(rightNode, leftNode), nil
  702. }
  703. return nil, pgerror.InvalidParameter("unsupported jsonb containment operator")
  704. }
  705. // jsonbKeyExists evaluates the ? operator: an object key or a top-level string
  706. // array element.
  707. func jsonbKeyExists(left, right interface{}) (interface{}, error) {
  708. if left == nil || right == nil {
  709. return nil, nil
  710. }
  711. node, err := jsonbNodeFromArg(left)
  712. if err != nil {
  713. return nil, err
  714. }
  715. key := toString(right)
  716. switch value := node.(type) {
  717. case map[string]interface{}:
  718. _, exists := value[key]
  719. return exists, nil
  720. case []interface{}:
  721. for _, element := range value {
  722. if text, ok := element.(string); ok && text == key {
  723. return true, nil
  724. }
  725. }
  726. return false, nil
  727. default:
  728. // Scalar strings never match: jsonb_exists only looks at object keys and
  729. // top-level string array elements.
  730. return false, nil
  731. }
  732. }
  733. // jsonbAnyKeysExist evaluates ?| and ?& against a text[] of keys.
  734. func jsonbAnyKeysExist(op lexer.TokenType, left, right interface{}) (interface{}, error) {
  735. if left == nil || right == nil {
  736. return nil, nil
  737. }
  738. node, err := jsonbNodeFromArg(left)
  739. if err != nil {
  740. return nil, err
  741. }
  742. keys, err := jsonbKeyListArg(right)
  743. if err != nil {
  744. return nil, err
  745. }
  746. matches := 0
  747. switch value := node.(type) {
  748. case map[string]interface{}:
  749. for _, key := range keys {
  750. if _, exists := value[key]; exists {
  751. matches++
  752. }
  753. }
  754. case []interface{}:
  755. for _, key := range keys {
  756. for _, element := range value {
  757. if text, ok := element.(string); ok && text == key {
  758. matches++
  759. break
  760. }
  761. }
  762. }
  763. default:
  764. return false, nil
  765. }
  766. if op == lexer.TokenQuestionAmp {
  767. return matches == len(keys), nil
  768. }
  769. return matches > 0, nil
  770. }
  771. // jsonbDeleteValue evaluates jsonb - text, jsonb - integer, and jsonb - text[].
  772. func (e *Executor) jsonbDeleteValue(leftExpr, rightExpr parser.Expr, left, right interface{}) (interface{}, error) {
  773. if e.isJSONBExpr(rightExpr) {
  774. return nil, pgerror.DatatypeMismatch("jsonb deletion requires a text key, integer index, or text[] path, not a jsonb operand")
  775. }
  776. node, err := jsonbNodeFromArg(left)
  777. if err != nil {
  778. return nil, err
  779. }
  780. if _, isArray := e.arrayTypeOf(rightExpr); isArray {
  781. elements, parseErr := parseArrayLiteral(toString(right))
  782. if parseErr != nil {
  783. return nil, parseErr
  784. }
  785. keys := make([]string, 0, len(elements))
  786. for _, element := range elements {
  787. if element == nil {
  788. return nil, pgerror.InvalidParameter("jsonb delete path contains a NULL element")
  789. }
  790. keys = append(keys, *element)
  791. }
  792. return encodeJSONB(jsonbDeleteKeys(node, keys), false)
  793. }
  794. switch value := right.(type) {
  795. case int64:
  796. array, ok := node.([]interface{})
  797. if !ok {
  798. if _, isObject := node.(map[string]interface{}); isObject {
  799. return nil, pgerror.InvalidParameter("cannot delete from object using integer index")
  800. }
  801. return nil, pgerror.InvalidParameter("cannot delete an array element from a jsonb %s", jsonbNodeTypeName(node))
  802. }
  803. return encodeJSONB(jsonbDeleteIndex(array, int(value)), false)
  804. case int:
  805. return e.jsonbDeleteValue(leftExpr, rightExpr, left, int64(value))
  806. case string, jsonText:
  807. // jsonb - text deletes an object key, or every string element equal to
  808. // the text when the document is an array.
  809. key := toString(value)
  810. return encodeJSONB(jsonbDeleteKeys(node, []string{key}), false)
  811. default:
  812. return nil, pgerror.DatatypeMismatch("cannot delete %T from jsonb", right)
  813. }
  814. }
  815. func jsonbDeleteKeys(node interface{}, keys []string) interface{} {
  816. switch container := node.(type) {
  817. case map[string]interface{}:
  818. out := make(map[string]interface{}, len(container))
  819. for key, value := range container {
  820. out[key] = value
  821. }
  822. for _, key := range keys {
  823. delete(out, key)
  824. }
  825. return out
  826. case []interface{}:
  827. out := make([]interface{}, 0, len(container))
  828. for _, element := range container {
  829. remove := false
  830. if text, ok := element.(string); ok {
  831. for _, key := range keys {
  832. if text == key {
  833. remove = true
  834. break
  835. }
  836. }
  837. }
  838. if !remove {
  839. out = append(out, element)
  840. }
  841. }
  842. return out
  843. default:
  844. return node
  845. }
  846. }
  847. func jsonbDeleteIndex(array []interface{}, index int) []interface{} {
  848. if index < 0 {
  849. index += len(array)
  850. }
  851. if index < 0 || index >= len(array) {
  852. return array
  853. }
  854. out := make([]interface{}, 0, len(array)-1)
  855. out = append(out, array[:index]...)
  856. out = append(out, array[index+1:]...)
  857. return out
  858. }
  859. // jsonbConcatNodes implements jsonb || jsonb: objects merge right-wins, arrays
  860. // concatenate, and any non-array operand becomes a single-element array.
  861. func jsonbConcatNodes(left, right interface{}) interface{} {
  862. leftObject, leftIsObject := left.(map[string]interface{})
  863. rightObject, rightIsObject := right.(map[string]interface{})
  864. if leftIsObject && rightIsObject {
  865. out := make(map[string]interface{}, len(leftObject)+len(rightObject))
  866. for key, value := range leftObject {
  867. out[key] = value
  868. }
  869. for key, value := range rightObject {
  870. out[key] = value
  871. }
  872. return out
  873. }
  874. asArray := func(node interface{}) []interface{} {
  875. if array, ok := node.([]interface{}); ok {
  876. return array
  877. }
  878. return []interface{}{node}
  879. }
  880. out := append([]interface{}{}, asArray(left)...)
  881. return append(out, asArray(right)...)
  882. }
  883. // jsonbContains implements jsonb containment: object keys/values recurse, array
  884. // elements are order-independent, top-level arrays contain scalars, and scalars
  885. // compare by type.
  886. func jsonbContains(container, candidate interface{}) bool {
  887. // A top-level array contains a scalar candidate when any element does.
  888. switch candidate.(type) {
  889. case nil, bool, string, json.Number:
  890. if containerArray, ok := container.([]interface{}); ok {
  891. for _, element := range containerArray {
  892. if jsonbContains(element, candidate) {
  893. return true
  894. }
  895. }
  896. return false
  897. }
  898. }
  899. switch candidateValue := candidate.(type) {
  900. case map[string]interface{}:
  901. containerObject, ok := container.(map[string]interface{})
  902. if !ok {
  903. return false
  904. }
  905. for key, value := range candidateValue {
  906. other, exists := containerObject[key]
  907. if !exists || !jsonbContains(other, value) {
  908. return false
  909. }
  910. }
  911. return true
  912. case []interface{}:
  913. containerArray, ok := container.([]interface{})
  914. if ok {
  915. // PostgreSQL array containment does not require multiplicity: each
  916. // candidate element only needs some container element, and duplicates
  917. // may match the same element.
  918. for _, candidateElement := range candidateValue {
  919. matched := false
  920. for _, containerElement := range containerArray {
  921. if jsonbContains(containerElement, candidateElement) {
  922. matched = true
  923. break
  924. }
  925. }
  926. if !matched {
  927. return false
  928. }
  929. }
  930. return true
  931. }
  932. // A non-array container can still contain a nested empty array? No.
  933. return false
  934. case nil:
  935. return container == nil
  936. case bool:
  937. other, ok := container.(bool)
  938. return ok && other == candidateValue
  939. case string:
  940. other, ok := container.(string)
  941. return ok && other == candidateValue
  942. case json.Number:
  943. candidateText, err := canonicalJSONBNumber(candidateValue)
  944. if err != nil {
  945. return false
  946. }
  947. other, ok := container.(json.Number)
  948. if !ok {
  949. return false
  950. }
  951. containerText, err := canonicalJSONBNumber(other)
  952. if err != nil {
  953. return false
  954. }
  955. return containerText == candidateText
  956. }
  957. return false
  958. }
  959. // jsonbNodeTypeName returns the PostgreSQL jsonb type name.
  960. func jsonbNodeTypeName(node interface{}) string {
  961. switch node.(type) {
  962. case nil:
  963. return "null"
  964. case bool:
  965. return "boolean"
  966. case json.Number:
  967. return "number"
  968. case string:
  969. return "string"
  970. case []interface{}:
  971. return "array"
  972. case map[string]interface{}:
  973. return "object"
  974. default:
  975. return "unknown"
  976. }
  977. }
  978. // jsonbPathArg resolves a path operand to path steps. A text[] value (canonical
  979. // array text) is PostgreSQL's path form; a $string is the JSON1 path form this
  980. // engine already uses for -> and json_extract.
  981. func jsonbPathArg(value interface{}) ([]jsonPathSeg, error) {
  982. text := strings.TrimSpace(toString(value))
  983. switch {
  984. case strings.HasPrefix(text, "{"):
  985. return parseJSONBArrayPath(text)
  986. case strings.HasPrefix(text, "$"):
  987. return parseJSONBJSONPath(text)
  988. default:
  989. return nil, pgerror.InvalidParameter("jsonb path must be a text[] array literal such as '{a,0}' or a $ path, got %q", text)
  990. }
  991. }
  992. // jsonbKeyListArg parses a text[] of object keys. Unlike a path, every element
  993. // is a key: a numeric-looking key such as "1" must not become an array index.
  994. func jsonbKeyListArg(value interface{}) ([]string, error) {
  995. text := strings.TrimSpace(toString(value))
  996. if !strings.HasPrefix(text, "{") {
  997. return nil, pgerror.InvalidParameter("jsonb key list must be a text[] array literal, got %q", text)
  998. }
  999. elements, err := parseArrayLiteral(text)
  1000. if err != nil {
  1001. return nil, err
  1002. }
  1003. keys := make([]string, 0, len(elements))
  1004. for _, element := range elements {
  1005. if element == nil {
  1006. return nil, pgerror.InvalidParameter("jsonb key list element must not be NULL")
  1007. }
  1008. keys = append(keys, *element)
  1009. }
  1010. return keys, nil
  1011. }
  1012. // parseJSONBArrayPath parses PostgreSQL text[] path text into steps. A path
  1013. // element is kept as raw text because its meaning depends on the container it
  1014. // is applied to: an object key, or an integer array index. Numeric-looking
  1015. // object keys such as "1", "01", "-1", and "1.5" therefore stay keys when the
  1016. // container is an object.
  1017. func parseJSONBArrayPath(text string) ([]jsonPathSeg, error) {
  1018. elements, err := parseArrayLiteral(text)
  1019. if err != nil {
  1020. return nil, err
  1021. }
  1022. segs := make([]jsonPathSeg, 0, len(elements))
  1023. for _, element := range elements {
  1024. if element == nil {
  1025. return nil, pgerror.InvalidParameter("jsonb path element must not be NULL")
  1026. }
  1027. segs = append(segs, jsonPathSeg{dynamic: true, element: *element})
  1028. }
  1029. return segs, nil
  1030. }
  1031. // resolveJSONBPathSegment converts a PostgreSQL path element into a concrete
  1032. // object key or array index for the container it is applied to. Concrete steps
  1033. // (JSON1 $ paths and index/key steps) pass through unchanged. resolved is false
  1034. // when container is a scalar or missing; callers decide whether that is a
  1035. // not-found, an unchanged target, or an error. strict selects whether a
  1036. // non-integer element on an array is an error (jsonb path mutation and #-) or a
  1037. // non-match (jsonb #>).
  1038. func resolveJSONBPathSegment(seg jsonPathSeg, container interface{}, strict bool) (jsonPathSeg, bool, error) {
  1039. if !seg.dynamic {
  1040. return seg, true, nil
  1041. }
  1042. switch container.(type) {
  1043. case map[string]interface{}:
  1044. return jsonPathSeg{key: seg.element}, true, nil
  1045. case []interface{}:
  1046. index, err := strconv.Atoi(seg.element)
  1047. if err != nil {
  1048. if strict {
  1049. return seg, false, pgerror.InvalidText("path element %q is not an integer", seg.element)
  1050. }
  1051. return seg, false, nil
  1052. }
  1053. return jsonPathSeg{isIndex: true, index: index, fromEnd: index < 0}, true, nil
  1054. default:
  1055. return seg, false, nil
  1056. }
  1057. }
  1058. // parseJSONBJSONPath parses a JSON1 $ path for jsonb use and rejects the
  1059. // jsonpath shapes the engine cannot execute (wildcards, slices, unbounded
  1060. // expansion) with SQLSTATE 0A000.
  1061. func parseJSONBJSONPath(path string) ([]jsonPathSeg, error) {
  1062. if unsupportedJSONPathShape(path) {
  1063. return nil, pgerror.Unsupported("jsonpath wildcards, slices, and unbounded expansion are not supported; pass an explicit path")
  1064. }
  1065. segs, err := parseJSONPath(path)
  1066. if err != nil {
  1067. return nil, err
  1068. }
  1069. for _, segment := range segs {
  1070. if !segment.isIndex && (segment.key == "*" || strings.HasPrefix(segment.key, "**")) {
  1071. return nil, pgerror.Unsupported("jsonpath wildcards and unbounded expansion are not supported; pass an explicit path")
  1072. }
  1073. }
  1074. return segs, nil
  1075. }
  1076. // unsupportedJSONPathShape reports whether path text contains a jsonpath
  1077. // wildcard, slice, or deep-expansion marker inside brackets or as a bare member.
  1078. func unsupportedJSONPathShape(path string) bool {
  1079. for i := 0; i < len(path); i++ {
  1080. if path[i] != '[' {
  1081. continue
  1082. }
  1083. end := strings.IndexByte(path[i:], ']')
  1084. if end < 0 {
  1085. return false
  1086. }
  1087. inner := path[i+1 : i+end]
  1088. if strings.ContainsAny(inner, "*:") {
  1089. return true
  1090. }
  1091. i += end
  1092. }
  1093. return false
  1094. }
  1095. // jsonbSetPG implements PostgreSQL's jsonb_set path semantics. An empty path
  1096. // leaves the target unchanged. All steps except the last must exist and be
  1097. // containers; missing keys or a scalar on the way leave the target unchanged. A
  1098. // missing array position at the last step is appended when create is true, and
  1099. // an index before the start is clamped to the first position.
  1100. func jsonbSetPG(node interface{}, segs []jsonPathSeg, value interface{}, create bool) (interface{}, error) {
  1101. if len(segs) == 0 {
  1102. return node, nil
  1103. }
  1104. segment, resolved, err := resolveJSONBPathSegment(segs[0], node, true)
  1105. if err != nil {
  1106. return nil, err
  1107. }
  1108. if !resolved {
  1109. return nil, pgerror.InvalidParameter("cannot set path in scalar")
  1110. }
  1111. if len(segs) > 1 {
  1112. child, exists, err := jsonbPathChild(node, segment)
  1113. if err != nil {
  1114. return nil, err
  1115. }
  1116. if !exists {
  1117. return node, nil
  1118. }
  1119. switch child.(type) {
  1120. case map[string]interface{}, []interface{}:
  1121. default:
  1122. // PostgreSQL leaves the target unchanged when an intermediate step
  1123. // names a scalar rather than a container.
  1124. return node, nil
  1125. }
  1126. updated, err := jsonbSetPG(child, segs[1:], value, create)
  1127. if err != nil {
  1128. return nil, err
  1129. }
  1130. return jsonbReplaceChild(node, segment, updated)
  1131. }
  1132. switch container := node.(type) {
  1133. case map[string]interface{}:
  1134. if segment.isIndex {
  1135. return nil, pgerror.InvalidText("path element is not an object key")
  1136. }
  1137. if _, exists := container[segment.key]; !exists && !create {
  1138. return node, nil
  1139. }
  1140. out := make(map[string]interface{}, len(container)+1)
  1141. for key, item := range container {
  1142. out[key] = item
  1143. }
  1144. out[segment.key] = value
  1145. return out, nil
  1146. case []interface{}:
  1147. if !segment.isIndex {
  1148. return nil, pgerror.InvalidText("path element %q is not an integer", segment.key)
  1149. }
  1150. index := segment.index
  1151. if index < 0 {
  1152. index += len(container)
  1153. }
  1154. if index < 0 {
  1155. if !create {
  1156. return node, nil
  1157. }
  1158. out := make([]interface{}, 0, len(container)+1)
  1159. out = append(out, value)
  1160. return append(out, container...), nil
  1161. }
  1162. if index >= len(container) {
  1163. if !create {
  1164. return node, nil
  1165. }
  1166. out := append([]interface{}{}, container...)
  1167. return append(out, value), nil
  1168. }
  1169. out := append([]interface{}{}, container...)
  1170. out[index] = value
  1171. return out, nil
  1172. default:
  1173. return nil, pgerror.InvalidParameter("cannot set path in scalar")
  1174. }
  1175. }
  1176. // jsonbInsertPG implements PostgreSQL's jsonb_insert path semantics: array
  1177. // elements are inserted before or after an index (clamped into range), and an
  1178. // object key is inserted only when it is absent. An existing object key is an
  1179. // error, matching PostgreSQL.
  1180. func jsonbInsertPG(node interface{}, segs []jsonPathSeg, value interface{}, after bool) (interface{}, error) {
  1181. if len(segs) == 0 {
  1182. return node, nil
  1183. }
  1184. segment, resolved, err := resolveJSONBPathSegment(segs[0], node, true)
  1185. if err != nil {
  1186. return nil, err
  1187. }
  1188. if !resolved {
  1189. return nil, pgerror.InvalidParameter("cannot set path in scalar")
  1190. }
  1191. if len(segs) > 1 {
  1192. child, exists, err := jsonbPathChild(node, segment)
  1193. if err != nil {
  1194. return nil, err
  1195. }
  1196. if !exists {
  1197. return node, nil
  1198. }
  1199. switch child.(type) {
  1200. case map[string]interface{}, []interface{}:
  1201. default:
  1202. return node, nil
  1203. }
  1204. updated, err := jsonbInsertPG(child, segs[1:], value, after)
  1205. if err != nil {
  1206. return nil, err
  1207. }
  1208. return jsonbReplaceChild(node, segment, updated)
  1209. }
  1210. switch container := node.(type) {
  1211. case map[string]interface{}:
  1212. if segment.isIndex {
  1213. return nil, pgerror.InvalidText("path element is not an object key")
  1214. }
  1215. if _, exists := container[segment.key]; exists {
  1216. return nil, pgerror.InvalidParameter("cannot replace existing key")
  1217. }
  1218. out := make(map[string]interface{}, len(container)+1)
  1219. for key, item := range container {
  1220. out[key] = item
  1221. }
  1222. out[segment.key] = value
  1223. return out, nil
  1224. case []interface{}:
  1225. if !segment.isIndex {
  1226. return nil, pgerror.InvalidText("path element %q is not an integer", segment.key)
  1227. }
  1228. index := segment.index
  1229. if index < 0 {
  1230. index += len(container)
  1231. }
  1232. if index < 0 {
  1233. index = 0
  1234. }
  1235. if index > len(container) {
  1236. index = len(container)
  1237. }
  1238. if after {
  1239. index++
  1240. }
  1241. if index > len(container) {
  1242. index = len(container)
  1243. }
  1244. out := make([]interface{}, 0, len(container)+1)
  1245. out = append(out, container[:index]...)
  1246. out = append(out, value)
  1247. out = append(out, container[index:]...)
  1248. return out, nil
  1249. default:
  1250. return nil, pgerror.InvalidParameter("cannot set path in scalar")
  1251. }
  1252. }
  1253. // jsonbPathChild resolves one non-final path step to an existing child.
  1254. func jsonbPathChild(node interface{}, segment jsonPathSeg) (interface{}, bool, error) {
  1255. switch container := node.(type) {
  1256. case map[string]interface{}:
  1257. if segment.isIndex {
  1258. return nil, false, pgerror.InvalidParameter("jsonb path element %d does not identify an object key", segment.index)
  1259. }
  1260. child, exists := container[segment.key]
  1261. return child, exists, nil
  1262. case []interface{}:
  1263. if !segment.isIndex {
  1264. return nil, false, pgerror.InvalidParameter("jsonb path element %q does not identify an array index", segment.key)
  1265. }
  1266. index := segment.index
  1267. if index < 0 {
  1268. index += len(container)
  1269. }
  1270. if index < 0 || index >= len(container) {
  1271. return nil, false, nil
  1272. }
  1273. return container[index], true, nil
  1274. default:
  1275. return nil, false, pgerror.InvalidParameter("cannot walk a jsonb path through a %s", jsonbNodeTypeName(node))
  1276. }
  1277. }
  1278. // jsonbReplaceChild writes an updated child back into its container.
  1279. func jsonbReplaceChild(node interface{}, segment jsonPathSeg, child interface{}) (interface{}, error) {
  1280. switch container := node.(type) {
  1281. case map[string]interface{}:
  1282. if segment.isIndex {
  1283. return nil, pgerror.InvalidParameter("jsonb path element %d does not identify an object key", segment.index)
  1284. }
  1285. out := make(map[string]interface{}, len(container)+1)
  1286. for key, item := range container {
  1287. out[key] = item
  1288. }
  1289. out[segment.key] = child
  1290. return out, nil
  1291. case []interface{}:
  1292. if !segment.isIndex {
  1293. return nil, pgerror.InvalidParameter("jsonb path element %q does not identify an array index", segment.key)
  1294. }
  1295. index := segment.index
  1296. if index < 0 {
  1297. index += len(container)
  1298. }
  1299. if index < 0 || index >= len(container) {
  1300. return nil, pgerror.InvalidParameter("jsonb path array index %d is out of range", segment.index)
  1301. }
  1302. out := append([]interface{}{}, container...)
  1303. out[index] = child
  1304. return out, nil
  1305. default:
  1306. return nil, pgerror.InvalidParameter("cannot write a jsonb path through a %s", jsonbNodeTypeName(node))
  1307. }
  1308. }
  1309. // jsonbStripNulls removes object members whose value is JSON null. Array
  1310. // elements are kept, matching jsonb_strip_nulls.
  1311. func jsonbStripNulls(node interface{}) interface{} {
  1312. switch value := node.(type) {
  1313. case map[string]interface{}:
  1314. out := make(map[string]interface{}, len(value))
  1315. for key, item := range value {
  1316. if item == nil {
  1317. continue
  1318. }
  1319. out[key] = jsonbStripNulls(item)
  1320. }
  1321. return out
  1322. case []interface{}:
  1323. out := make([]interface{}, len(value))
  1324. for i, item := range value {
  1325. out[i] = jsonbStripNulls(item)
  1326. }
  1327. return out
  1328. default:
  1329. return node
  1330. }
  1331. }
  1332. // jsonbEncodeNode canonicalizes a tree that has already been validated.
  1333. func jsonbEncodeNode(node interface{}) (string, error) {
  1334. return encodeJSONB(node, false)
  1335. }
  1336. // evalJSONBFunction evaluates a native jsonb scalar function. handled is false
  1337. // for names it does not own, keeping the JSON1 surface untouched.
  1338. func (e *Executor) evalJSONBFunction(name string, fn *parser.FunctionCall, args []interface{}) (interface{}, bool, error) {
  1339. upper := strings.ToUpper(name)
  1340. switch upper {
  1341. case "TO_JSONB":
  1342. if len(args) != 1 {
  1343. return nil, true, pgerror.InvalidParameter("to_jsonb() requires exactly one argument")
  1344. }
  1345. if args[0] == nil {
  1346. return nil, true, nil
  1347. }
  1348. node, err := e.toJSONBNode(firstFunctionArg(fn), args[0])
  1349. if err != nil {
  1350. return nil, true, err
  1351. }
  1352. text, err := jsonbEncodeNode(node)
  1353. return text, true, err
  1354. case "JSONB_TYPEOF":
  1355. if len(args) != 1 {
  1356. return nil, true, pgerror.InvalidParameter("jsonb_typeof() requires exactly one argument")
  1357. }
  1358. node, err := jsonbNodeFromArg(args[0])
  1359. if err != nil {
  1360. return nil, true, err
  1361. }
  1362. if node == nil && args[0] == nil {
  1363. return nil, true, nil
  1364. }
  1365. return jsonbNodeTypeName(node), true, nil
  1366. case "JSONB_ARRAY_LENGTH":
  1367. if len(args) != 1 {
  1368. return nil, true, pgerror.InvalidParameter("jsonb_array_length() requires exactly one argument")
  1369. }
  1370. node, err := jsonbNodeFromArg(args[0])
  1371. if err != nil {
  1372. return nil, true, err
  1373. }
  1374. if node == nil && args[0] == nil {
  1375. return nil, true, nil
  1376. }
  1377. array, ok := node.([]interface{})
  1378. if !ok {
  1379. return nil, true, pgerror.InvalidParameter("cannot get array length of a jsonb %s", jsonbNodeTypeName(node))
  1380. }
  1381. return int64(len(array)), true, nil
  1382. case "JSONB_PRETTY":
  1383. if len(args) != 1 {
  1384. return nil, true, pgerror.InvalidParameter("jsonb_pretty() requires exactly one argument")
  1385. }
  1386. if args[0] == nil {
  1387. return nil, true, nil
  1388. }
  1389. node, err := jsonbNodeFromArg(args[0])
  1390. if err != nil {
  1391. return nil, true, err
  1392. }
  1393. text, err := encodeJSONB(node, true)
  1394. return text, true, err
  1395. case "JSONB_STRIP_NULLS":
  1396. if len(args) != 1 {
  1397. return nil, true, pgerror.InvalidParameter("jsonb_strip_nulls() requires exactly one argument")
  1398. }
  1399. if args[0] == nil {
  1400. return nil, true, nil
  1401. }
  1402. node, err := jsonbNodeFromArg(args[0])
  1403. if err != nil {
  1404. return nil, true, err
  1405. }
  1406. text, err := jsonbEncodeNode(jsonbStripNulls(node))
  1407. return text, true, err
  1408. case "JSONB_BUILD_ARRAY":
  1409. values := make([]interface{}, len(args))
  1410. for i, arg := range args {
  1411. node, err := e.toJSONBNode(functionArgAt(fn, i), arg)
  1412. if err != nil {
  1413. return nil, true, err
  1414. }
  1415. values[i] = node
  1416. }
  1417. text, err := jsonbEncodeNode(values)
  1418. return text, true, err
  1419. case "JSONB_BUILD_OBJECT":
  1420. if len(args)%2 != 0 {
  1421. return nil, true, pgerror.InvalidParameter("jsonb_build_object() argument list must have an even number of elements")
  1422. }
  1423. object := make(map[string]interface{}, len(args)/2)
  1424. for i := 0; i+1 < len(args); i += 2 {
  1425. if args[i] == nil {
  1426. return nil, true, pgerror.InvalidParameter("jsonb_build_object() argument %d: key must not be null", i+1)
  1427. }
  1428. key := toString(args[i])
  1429. node, err := e.toJSONBNode(functionArgAt(fn, i+1), args[i+1])
  1430. if err != nil {
  1431. return nil, true, err
  1432. }
  1433. object[key] = node
  1434. }
  1435. text, err := jsonbEncodeNode(object)
  1436. return text, true, err
  1437. case "JSONB_SET", "JSONB_INSERT", "JSONB_REPLACE", "JSONB_REMOVE":
  1438. value, err := e.evalJSONBPatch(upper, fn, args)
  1439. return value, true, err
  1440. case "JSONB_EACH", "JSONB_EACH_TEXT", "JSONB_ARRAY_ELEMENTS", "JSONB_ARRAY_ELEMENTS_TEXT", "JSONB_OBJECT_KEYS":
  1441. return nil, true, pgerror.Unsupported("%s() is a set-returning function and is only supported as the single FROM item, as in SELECT * FROM %s(jsonb_column)", name, strings.ToLower(name))
  1442. case "JSONB_PATH_EXISTS", "JSONB_PATH_EXISTS_TZ", "JSONB_PATH_MATCH", "JSONB_PATH_MATCH_TZ",
  1443. "JSONB_PATH_QUERY", "JSONB_PATH_QUERY_TZ", "JSONB_PATH_QUERY_ARRAY", "JSONB_PATH_QUERY_ARRAY_TZ",
  1444. "JSONB_PATH_QUERY_FIRST", "JSONB_PATH_QUERY_FIRST_TZ":
  1445. return nil, true, pgerror.Unsupported("jsonpath (%s) is not supported", strings.ToLower(name))
  1446. }
  1447. return nil, false, nil
  1448. }
  1449. // firstFunctionArg returns the first argument expression of a call, or nil when
  1450. // the call has no arguments.
  1451. func firstFunctionArg(fn *parser.FunctionCall) parser.Expr {
  1452. if fn == nil || len(fn.Args) == 0 {
  1453. return nil
  1454. }
  1455. return fn.Args[0]
  1456. }
  1457. func functionArgAt(fn *parser.FunctionCall, index int) parser.Expr {
  1458. if fn == nil || index < 0 || index >= len(fn.Args) {
  1459. return nil
  1460. }
  1461. return fn.Args[index]
  1462. }
  1463. // toJSONBNode converts a SQL value to a JSON tree node, decoding arrays into
  1464. // JSON arrays so to_jsonb(jsonb_build_array(...)) and to_jsonb(array_column)
  1465. // keep their element types.
  1466. func (e *Executor) toJSONBNode(expr parser.Expr, value interface{}) (interface{}, error) {
  1467. if value == nil {
  1468. return nil, nil
  1469. }
  1470. // to_jsonb(jsonb) is the identity: a jsonb argument is embedded as its
  1471. // document, not as a JSON string.
  1472. if e.isJSONBExpr(expr) {
  1473. return jsonbNodeFromArg(value)
  1474. }
  1475. if typeName, ok := e.arrayTypeOf(expr); ok {
  1476. elements, err := parseArrayLiteral(toString(value))
  1477. if err != nil {
  1478. return nil, err
  1479. }
  1480. elementType, _ := arrayElementType(typeName)
  1481. nodes := make([]interface{}, len(elements))
  1482. for i, element := range elements {
  1483. typed, valueErr := arrayElementValue(element, elementType)
  1484. if valueErr != nil {
  1485. return nil, valueErr
  1486. }
  1487. node, nodeErr := jsonbNodeFromSQLValue(typed)
  1488. if nodeErr != nil {
  1489. return nil, nodeErr
  1490. }
  1491. nodes[i] = node
  1492. }
  1493. return nodes, nil
  1494. }
  1495. return jsonbNodeFromSQLValue(value)
  1496. }
  1497. // jsonbPatchNode converts a JSON1 $ path patch value to a JSON tree node. A
  1498. // float64 must become a json.Number before it reaches the encoder, and NaN and
  1499. // infinity are rejected instead of producing invalid JSON.
  1500. func jsonbPatchNode(value interface{}) (interface{}, error) {
  1501. switch typed := value.(type) {
  1502. case jsonText:
  1503. if node, err := jsonDecode(string(typed)); err == nil {
  1504. return node, nil
  1505. }
  1506. return string(typed), nil
  1507. case nil, bool, int, int8, int16, int32, int64,
  1508. uint, uint32, uint64, float32, float64, string, []byte:
  1509. return jsonbNodeFromSQLValue(value)
  1510. default:
  1511. return jsonArgToNode(value), nil
  1512. }
  1513. }
  1514. // evalJSONBPatch evaluates the jsonb_set/jsonb_insert/jsonb_replace/
  1515. // jsonb_remove family. A $ path keeps the JSON1 semantics the engine already
  1516. // exposed; a PostgreSQL text[] path uses PostgreSQL's jsonb_set/jsonb_insert
  1517. // rules and accepts the optional boolean fourth argument.
  1518. func (e *Executor) evalJSONBPatch(name string, fn *parser.FunctionCall, args []interface{}) (interface{}, error) {
  1519. minArgs := 2
  1520. if name != "JSONB_REMOVE" {
  1521. minArgs = 3
  1522. }
  1523. if len(args) < minArgs {
  1524. return nil, pgerror.InvalidParameter("%s() requires at least %d arguments", strings.ToLower(name), minArgs)
  1525. }
  1526. if args[0] == nil || args[1] == nil {
  1527. return nil, nil
  1528. }
  1529. node, err := jsonbNodeFromArg(args[0])
  1530. if err != nil {
  1531. return nil, err
  1532. }
  1533. if name == "JSONB_REMOVE" {
  1534. for _, path := range args[1:] {
  1535. if path == nil {
  1536. return nil, nil
  1537. }
  1538. segs, pathErr := jsonbPathArg(path)
  1539. if pathErr != nil {
  1540. return nil, pathErr
  1541. }
  1542. node, err = jsonRemove(node, segs)
  1543. if err != nil {
  1544. return nil, err
  1545. }
  1546. }
  1547. return jsonbEncodeNode(node)
  1548. }
  1549. // JSON1 multi-path form: jsonb_set(doc, path, value, path, value, ...).
  1550. // PostgreSQL's form has exactly three or four arguments.
  1551. pathText := strings.TrimSpace(toString(args[1]))
  1552. pgPath := strings.HasPrefix(pathText, "{")
  1553. if pgPath && len(args) > 4 {
  1554. return nil, pgerror.InvalidParameter("%s() with a PostgreSQL path accepts at most four arguments", strings.ToLower(name))
  1555. }
  1556. if len(args) == 4 && !pgPath {
  1557. return nil, pgerror.Unsupported("%s() accepts the optional insert_after/create_if_missing argument only with a PostgreSQL text[] path; a $ path uses the JSON1 form", strings.ToLower(name))
  1558. }
  1559. flag := false
  1560. if len(args) == 4 {
  1561. if args[3] == nil {
  1562. return nil, nil
  1563. }
  1564. flag = toBool(args[3])
  1565. }
  1566. if !pgPath {
  1567. // JSON1 form: every path/value pair is applied in order. A plain SQL
  1568. // string becomes a JSON string, which is the behavior this engine exposed
  1569. // before JSONB became native; a jsonb-typed value embeds its document.
  1570. mode := "set"
  1571. switch name {
  1572. case "JSONB_INSERT":
  1573. mode = "insert"
  1574. case "JSONB_REPLACE":
  1575. mode = "replace"
  1576. }
  1577. for i := 1; i+1 < len(args); i += 2 {
  1578. if args[i] == nil || args[i+1] == nil {
  1579. return nil, nil
  1580. }
  1581. segs, pathErr := jsonbPathArg(args[i])
  1582. if pathErr != nil {
  1583. return nil, pathErr
  1584. }
  1585. var patchValue interface{}
  1586. if e.isJSONBExpr(functionArgAt(fn, i+1)) {
  1587. patchValue, err = jsonbNodeFromArg(args[i+1])
  1588. } else {
  1589. patchValue, err = jsonbPatchNode(args[i+1])
  1590. }
  1591. if err != nil {
  1592. return nil, err
  1593. }
  1594. node, err = jsonApplyPatch(node, segs, patchValue, mode)
  1595. if err != nil {
  1596. return nil, err
  1597. }
  1598. }
  1599. return jsonbEncodeNode(node)
  1600. }
  1601. if args[2] == nil {
  1602. return nil, nil
  1603. }
  1604. newValueNode, err := jsonbNodeFromArg(args[2])
  1605. if err != nil {
  1606. return nil, err
  1607. }
  1608. segs, err := jsonbPathArg(args[1])
  1609. if err != nil {
  1610. return nil, err
  1611. }
  1612. switch name {
  1613. case "JSONB_SET":
  1614. create := true
  1615. if len(args) == 4 {
  1616. create = flag
  1617. }
  1618. node, err = jsonbSetPG(node, segs, newValueNode, create)
  1619. case "JSONB_INSERT":
  1620. node, err = jsonbInsertPG(node, segs, newValueNode, flag)
  1621. case "JSONB_REPLACE":
  1622. return nil, pgerror.Unsupported("jsonb_replace() with a PostgreSQL path is not supported; use jsonb_set or the JSON1 $ path form")
  1623. }
  1624. if err != nil {
  1625. return nil, err
  1626. }
  1627. return jsonbEncodeNode(node)
  1628. }
  1629. // jsonbTableFunction materializes a set-returning jsonb function as a relation.
  1630. // The returned types are the SQL type names used for result metadata.
  1631. func jsonbTableFunction(name string, value interface{}) (columns, types []string, rows [][]interface{}, err error) {
  1632. node, err := jsonbNodeFromArg(value)
  1633. if err != nil {
  1634. return nil, nil, nil, err
  1635. }
  1636. if value == nil {
  1637. switch strings.ToLower(name) {
  1638. case "jsonb_each":
  1639. return []string{"key", "value"}, []string{"TEXT", "JSONB"}, nil, nil
  1640. case "jsonb_each_text":
  1641. return []string{"key", "value"}, []string{"TEXT", "TEXT"}, nil, nil
  1642. case "jsonb_object_keys":
  1643. return []string{"jsonb_object_keys"}, []string{"TEXT"}, nil, nil
  1644. case "jsonb_array_elements_text":
  1645. return []string{"value"}, []string{"TEXT"}, nil, nil
  1646. default:
  1647. return []string{"value"}, []string{"JSONB"}, nil, nil
  1648. }
  1649. }
  1650. switch strings.ToLower(name) {
  1651. case "jsonb_each", "jsonb_each_text", "jsonb_object_keys":
  1652. object, ok := node.(map[string]interface{})
  1653. if !ok {
  1654. return nil, nil, nil, pgerror.InvalidParameter("cannot call %s() on a jsonb %s", strings.ToLower(name), jsonbNodeTypeName(node))
  1655. }
  1656. keys := make([]string, 0, len(object))
  1657. for key := range object {
  1658. keys = append(keys, key)
  1659. }
  1660. sort.Strings(keys)
  1661. if strings.EqualFold(name, "jsonb_object_keys") {
  1662. rows = make([][]interface{}, 0, len(keys))
  1663. for _, key := range keys {
  1664. rows = append(rows, []interface{}{key})
  1665. }
  1666. return []string{"jsonb_object_keys"}, []string{"TEXT"}, rows, nil
  1667. }
  1668. textValues := strings.EqualFold(name, "jsonb_each_text")
  1669. valueType := "JSONB"
  1670. if textValues {
  1671. valueType = "TEXT"
  1672. }
  1673. rows = make([][]interface{}, 0, len(keys))
  1674. for _, key := range keys {
  1675. var rendered interface{}
  1676. if textValues {
  1677. rendered, err = jsonbNodeToText(object[key])
  1678. } else {
  1679. rendered, err = encodeJSONB(object[key], false)
  1680. }
  1681. if err != nil {
  1682. return nil, nil, nil, err
  1683. }
  1684. rows = append(rows, []interface{}{key, rendered})
  1685. }
  1686. return []string{"key", "value"}, []string{"TEXT", valueType}, rows, nil
  1687. case "jsonb_array_elements", "jsonb_array_elements_text":
  1688. array, ok := node.([]interface{})
  1689. if !ok {
  1690. return nil, nil, nil, pgerror.InvalidParameter("cannot call %s() on a jsonb %s", strings.ToLower(name), jsonbNodeTypeName(node))
  1691. }
  1692. textValues := strings.EqualFold(name, "jsonb_array_elements_text")
  1693. valueType := "JSONB"
  1694. if textValues {
  1695. valueType = "TEXT"
  1696. }
  1697. rows = make([][]interface{}, 0, len(array))
  1698. for _, element := range array {
  1699. var rendered interface{}
  1700. if textValues {
  1701. rendered, err = jsonbNodeToText(element)
  1702. } else {
  1703. rendered, err = encodeJSONB(element, false)
  1704. }
  1705. if err != nil {
  1706. return nil, nil, nil, err
  1707. }
  1708. rows = append(rows, []interface{}{rendered})
  1709. }
  1710. return []string{"value"}, []string{valueType}, rows, nil
  1711. }
  1712. return nil, nil, nil, pgerror.Unsupported("table function %s() is not supported", name)
  1713. }
  1714. // normalizeJSONBRow canonicalizes every JSONB-typed column value before it is
  1715. // written, mirroring normalizeArrayRow. A value is canonicalized once, so a
  1716. // reload reads back the same bytes.
  1717. func (e *Executor) normalizeJSONBRow(schema *storage.Schema, row storage.Row) error {
  1718. if schema == nil {
  1719. return nil
  1720. }
  1721. for _, column := range schema.Columns {
  1722. if !strings.EqualFold(strings.TrimSpace(column.Type), "JSONB") {
  1723. continue
  1724. }
  1725. value, ok := lookupRowValue(row, column.Name)
  1726. if !ok || value == nil {
  1727. continue
  1728. }
  1729. text, isText := value.(string)
  1730. if !isText {
  1731. if jsonValue, isJSON := value.(jsonText); isJSON {
  1732. text = string(jsonValue)
  1733. } else {
  1734. return pgerror.InvalidText("column %q is %s and accepts JSON text, got %T", column.Name, column.Type, value)
  1735. }
  1736. }
  1737. canonical, err := CanonicalizeJSONB(text)
  1738. if err != nil {
  1739. return fmt.Errorf("column %q: %w", column.Name, err)
  1740. }
  1741. row[column.Name] = canonical
  1742. }
  1743. return nil
  1744. }
  1745. // canonicalJSONBDefault canonicalizes a constant DEFAULT for a JSONB column so
  1746. // the catalog and any ALTER TABLE backfill store the same bytes an INSERT would.
  1747. func canonicalJSONBDefault(typeName string, value interface{}, exprText string) (interface{}, string, error) {
  1748. if !strings.EqualFold(strings.TrimSpace(typeName), "JSONB") || exprText != "" || value == nil {
  1749. return value, exprText, nil
  1750. }
  1751. text, ok := value.(string)
  1752. if !ok {
  1753. if jsonValue, isJSON := value.(jsonText); isJSON {
  1754. text = string(jsonValue)
  1755. } else {
  1756. return nil, "", pgerror.InvalidText("DEFAULT for %s must be JSON text, got %T", typeName, value)
  1757. }
  1758. }
  1759. canonical, err := CanonicalizeJSONB(text)
  1760. if err != nil {
  1761. return nil, "", err
  1762. }
  1763. return canonical, "", nil
  1764. }