jsonb.go 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861
  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. // Array @> and <@ compare arrays element-wise and must not fall into the
  472. // jsonb path, which would reject an array operand with a jsonb type error.
  473. if (op == lexer.TokenAtArrow || op == lexer.TokenLtAt) && !leftJSONB && !rightJSONB {
  474. if arrayType, ok := e.arrayContainmentType(leftExpr, rightExpr); ok {
  475. value, err := e.arrayContainment(op, arrayType, leftExpr, rightExpr, left, right)
  476. return value, true, err
  477. }
  478. }
  479. if isComparisonOp(op) && (leftJSONB || rightJSONB) {
  480. if left == nil || right == nil {
  481. return nil, true, nil
  482. }
  483. if (leftJSONB && !jsonbComparisonValue(right)) || (rightJSONB && !jsonbComparisonValue(left)) {
  484. return nil, true, pgerror.DatatypeMismatch("jsonb comparison requires jsonb or text operands")
  485. }
  486. // jsonb equality and ordering compare the exact canonical bytes. Using
  487. // the engine's numeric-aware compare here would round through float64 and
  488. // report 1 = 1.0000000000000000001 or collapse integers above 2^53.
  489. leftText, err := CanonicalizeJSONB(toString(left))
  490. if err != nil {
  491. return nil, true, err
  492. }
  493. rightText, err := CanonicalizeJSONB(toString(right))
  494. if err != nil {
  495. return nil, true, err
  496. }
  497. result, err := comparisonOperatorResult(op, strings.Compare(leftText, rightText))
  498. return result, true, err
  499. }
  500. switch op {
  501. case lexer.TokenArrow, lexer.TokenArrowText:
  502. if !leftJSONB {
  503. return nil, false, nil
  504. }
  505. value, err := jsonbArrowExtract(left, right, op == lexer.TokenArrowText)
  506. return value, true, err
  507. case lexer.TokenHashArrow, lexer.TokenHashArrowText:
  508. value, err := jsonbPathExtract(left, right, op == lexer.TokenHashArrowText)
  509. return value, true, err
  510. case lexer.TokenHashMinus:
  511. value, err := jsonbPathDelete(left, right)
  512. return value, true, err
  513. case lexer.TokenAtArrow, lexer.TokenLtAt:
  514. value, err := e.jsonbContainment(op, leftExpr, rightExpr, left, right)
  515. return value, true, err
  516. case lexer.TokenQuestion:
  517. value, err := jsonbKeyExists(left, right)
  518. return value, true, err
  519. case lexer.TokenQuestionPipe, lexer.TokenQuestionAmp:
  520. value, err := jsonbAnyKeysExist(op, left, right)
  521. return value, true, err
  522. case lexer.TokenConcat:
  523. if !leftJSONB && !rightJSONB {
  524. return nil, false, nil
  525. }
  526. if left == nil || right == nil {
  527. return nil, true, nil
  528. }
  529. leftNode, err := jsonbNodeFromArg(left)
  530. if err != nil {
  531. return nil, true, err
  532. }
  533. rightNode, err := jsonbNodeFromArg(right)
  534. if err != nil {
  535. return nil, true, err
  536. }
  537. text, err := encodeJSONB(jsonbConcatNodes(leftNode, rightNode), false)
  538. return text, true, err
  539. case lexer.TokenMinus:
  540. if !leftJSONB {
  541. if rightJSONB {
  542. return nil, true, pgerror.DatatypeMismatch("cannot subtract a jsonb value from a non-jsonb value")
  543. }
  544. return nil, false, nil
  545. }
  546. if left == nil || right == nil {
  547. return nil, true, nil
  548. }
  549. value, err := e.jsonbDeleteValue(leftExpr, rightExpr, left, right)
  550. return value, true, err
  551. case lexer.TokenPlus, lexer.TokenStar, lexer.TokenSlash, lexer.TokenPercent:
  552. if leftJSONB || rightJSONB {
  553. return nil, true, pgerror.DatatypeMismatch("arithmetic operator %s requires numeric operands, got jsonb", op.String())
  554. }
  555. }
  556. return nil, false, nil
  557. }
  558. // jsonbComparisonValue reports whether a runtime value can be read as a jsonb
  559. // document on the other side of a comparison. SQL numbers and booleans are not
  560. // silently reinterpreted as JSON (PostgreSQL has no jsonb = integer operator).
  561. func jsonbComparisonValue(value interface{}) bool {
  562. switch value.(type) {
  563. case string, jsonText, []byte:
  564. return true
  565. default:
  566. return false
  567. }
  568. }
  569. // canonicalizeJSONBReadValue canonicalizes a JSONB-typed value on read so a
  570. // legacy row written before native JSONB still presents canonical text to
  571. // projections, DISTINCT, GROUP BY, and ORDER BY.
  572. func canonicalizeJSONBReadValue(typeName string, value interface{}) (interface{}, error) {
  573. if value == nil || !strings.EqualFold(strings.TrimSpace(typeName), "JSONB") {
  574. return value, nil
  575. }
  576. text, ok := value.(string)
  577. if !ok {
  578. if jsonValue, isJSON := value.(jsonText); isJSON {
  579. text = string(jsonValue)
  580. } else {
  581. return value, nil
  582. }
  583. }
  584. return CanonicalizeJSONB(text)
  585. }
  586. // canonicalizeJSONBColumnValue applies read canonicalization to a column
  587. // reference. It is a no-op for columns whose declared type is not JSONB.
  588. func (e *Executor) canonicalizeJSONBColumnValue(ref *parser.ColumnRef, value interface{}) (interface{}, error) {
  589. if ref == nil || value == nil {
  590. return value, nil
  591. }
  592. typeName, ok := e.resolveColumnType(ref.Table, ref.Column)
  593. if !ok {
  594. return value, nil
  595. }
  596. return canonicalizeJSONBReadValue(typeName, value)
  597. }
  598. // jsonbArrowPath resolves the right operand of -> and ->> for a jsonb document.
  599. // A $ path is validated like every other jsonb path, so wildcards and slices
  600. // are rejected with 0A000 rather than misinterpreted as member names.
  601. func jsonbArrowPath(key interface{}) ([]jsonPathSeg, error) {
  602. switch typed := key.(type) {
  603. case string:
  604. if strings.HasPrefix(strings.TrimSpace(typed), "$") {
  605. return parseJSONBJSONPath(typed)
  606. }
  607. return jsonArrowPath(key)
  608. case jsonText:
  609. if strings.HasPrefix(strings.TrimSpace(string(typed)), "$") {
  610. return parseJSONBJSONPath(string(typed))
  611. }
  612. return jsonArrowPath(key)
  613. default:
  614. return jsonArrowPath(key)
  615. }
  616. }
  617. // jsonbArrowExtract evaluates -> and ->> against a jsonb document. A missing
  618. // path is SQL NULL; a JSON null member is the jsonb value "null" for -> and SQL
  619. // NULL for ->>.
  620. func jsonbArrowExtract(document, key interface{}, scalar bool) (interface{}, error) {
  621. if document == nil || key == nil {
  622. return nil, nil
  623. }
  624. node, err := jsonbNodeFromArg(document)
  625. if err != nil {
  626. return nil, err
  627. }
  628. segs, err := jsonbArrowPath(key)
  629. if err != nil {
  630. return nil, err
  631. }
  632. found, ok := jsonLookup(node, segs)
  633. if !ok {
  634. return nil, nil
  635. }
  636. if scalar {
  637. return jsonbNodeToText(found)
  638. }
  639. return encodeJSONB(found, false)
  640. }
  641. // jsonbPathExtract evaluates #> and #>>. The path operand is a PostgreSQL
  642. // text[] (canonical array text) or a $ path.
  643. func jsonbPathExtract(document, path interface{}, scalar bool) (interface{}, error) {
  644. if document == nil || path == nil {
  645. return nil, nil
  646. }
  647. node, err := jsonbNodeFromArg(document)
  648. if err != nil {
  649. return nil, err
  650. }
  651. segs, err := jsonbPathArg(path)
  652. if err != nil {
  653. return nil, err
  654. }
  655. found, ok, err := jsonLookupE(node, segs)
  656. if err != nil {
  657. return nil, err
  658. }
  659. if !ok {
  660. return nil, nil
  661. }
  662. if scalar {
  663. return jsonbNodeToText(found)
  664. }
  665. return encodeJSONB(found, false)
  666. }
  667. // jsonbPathDelete evaluates #-. A missing path leaves the document unchanged.
  668. func jsonbPathDelete(document, path interface{}) (interface{}, error) {
  669. if document == nil || path == nil {
  670. return nil, nil
  671. }
  672. node, err := jsonbNodeFromArg(document)
  673. if err != nil {
  674. return nil, err
  675. }
  676. segs, err := jsonbPathArg(path)
  677. if err != nil {
  678. return nil, err
  679. }
  680. updated, err := jsonRemove(node, segs)
  681. if err != nil {
  682. return nil, err
  683. }
  684. return encodeJSONB(updated, false)
  685. }
  686. // jsonbContainment evaluates @> and <@. The jsonb operand must be present on at
  687. // least one side so a text-only comparison is not silently reinterpreted.
  688. func (e *Executor) jsonbContainment(op lexer.TokenType, leftExpr, rightExpr parser.Expr, left, right interface{}) (interface{}, error) {
  689. leftJSONB := e.isJSONBExpr(leftExpr)
  690. rightJSONB := e.isJSONBExpr(rightExpr)
  691. if !leftJSONB && !rightJSONB {
  692. return nil, pgerror.DatatypeMismatch("jsonb containment requires a jsonb operand; cast one side with ::jsonb")
  693. }
  694. if left == nil || right == nil {
  695. return nil, nil
  696. }
  697. leftNode, err := jsonbNodeFromArg(left)
  698. if err != nil {
  699. return nil, err
  700. }
  701. rightNode, err := jsonbNodeFromArg(right)
  702. if err != nil {
  703. return nil, err
  704. }
  705. switch op {
  706. case lexer.TokenAtArrow:
  707. return jsonbContains(leftNode, rightNode), nil
  708. case lexer.TokenLtAt:
  709. return jsonbContains(rightNode, leftNode), nil
  710. }
  711. return nil, pgerror.InvalidParameter("unsupported jsonb containment operator")
  712. }
  713. // jsonbKeyExists evaluates the ? operator: an object key or a top-level string
  714. // array element.
  715. func jsonbKeyExists(left, right interface{}) (interface{}, error) {
  716. if left == nil || right == nil {
  717. return nil, nil
  718. }
  719. node, err := jsonbNodeFromArg(left)
  720. if err != nil {
  721. return nil, err
  722. }
  723. key := toString(right)
  724. switch value := node.(type) {
  725. case map[string]interface{}:
  726. _, exists := value[key]
  727. return exists, nil
  728. case []interface{}:
  729. for _, element := range value {
  730. if text, ok := element.(string); ok && text == key {
  731. return true, nil
  732. }
  733. }
  734. return false, nil
  735. default:
  736. // Scalar strings never match: jsonb_exists only looks at object keys and
  737. // top-level string array elements.
  738. return false, nil
  739. }
  740. }
  741. // jsonbAnyKeysExist evaluates ?| and ?& against a text[] of keys.
  742. func jsonbAnyKeysExist(op lexer.TokenType, left, right interface{}) (interface{}, error) {
  743. if left == nil || right == nil {
  744. return nil, nil
  745. }
  746. node, err := jsonbNodeFromArg(left)
  747. if err != nil {
  748. return nil, err
  749. }
  750. keys, err := jsonbKeyListArg(right)
  751. if err != nil {
  752. return nil, err
  753. }
  754. matches := 0
  755. switch value := node.(type) {
  756. case map[string]interface{}:
  757. for _, key := range keys {
  758. if _, exists := value[key]; exists {
  759. matches++
  760. }
  761. }
  762. case []interface{}:
  763. for _, key := range keys {
  764. for _, element := range value {
  765. if text, ok := element.(string); ok && text == key {
  766. matches++
  767. break
  768. }
  769. }
  770. }
  771. default:
  772. return false, nil
  773. }
  774. if op == lexer.TokenQuestionAmp {
  775. return matches == len(keys), nil
  776. }
  777. return matches > 0, nil
  778. }
  779. // jsonbDeleteValue evaluates jsonb - text, jsonb - integer, and jsonb - text[].
  780. func (e *Executor) jsonbDeleteValue(leftExpr, rightExpr parser.Expr, left, right interface{}) (interface{}, error) {
  781. if e.isJSONBExpr(rightExpr) {
  782. return nil, pgerror.DatatypeMismatch("jsonb deletion requires a text key, integer index, or text[] path, not a jsonb operand")
  783. }
  784. node, err := jsonbNodeFromArg(left)
  785. if err != nil {
  786. return nil, err
  787. }
  788. if _, isArray := e.arrayTypeOf(rightExpr); isArray {
  789. elements, parseErr := parseArrayLiteral(toString(right))
  790. if parseErr != nil {
  791. return nil, parseErr
  792. }
  793. keys := make([]string, 0, len(elements))
  794. for _, element := range elements {
  795. if element == nil {
  796. return nil, pgerror.InvalidParameter("jsonb delete path contains a NULL element")
  797. }
  798. keys = append(keys, *element)
  799. }
  800. return encodeJSONB(jsonbDeleteKeys(node, keys), false)
  801. }
  802. switch value := right.(type) {
  803. case int64:
  804. array, ok := node.([]interface{})
  805. if !ok {
  806. if _, isObject := node.(map[string]interface{}); isObject {
  807. return nil, pgerror.InvalidParameter("cannot delete from object using integer index")
  808. }
  809. return nil, pgerror.InvalidParameter("cannot delete an array element from a jsonb %s", jsonbNodeTypeName(node))
  810. }
  811. return encodeJSONB(jsonbDeleteIndex(array, int(value)), false)
  812. case int:
  813. return e.jsonbDeleteValue(leftExpr, rightExpr, left, int64(value))
  814. case string, jsonText:
  815. // jsonb - text deletes an object key, or every string element equal to
  816. // the text when the document is an array.
  817. key := toString(value)
  818. return encodeJSONB(jsonbDeleteKeys(node, []string{key}), false)
  819. default:
  820. return nil, pgerror.DatatypeMismatch("cannot delete %T from jsonb", right)
  821. }
  822. }
  823. func jsonbDeleteKeys(node interface{}, keys []string) interface{} {
  824. switch container := node.(type) {
  825. case map[string]interface{}:
  826. out := make(map[string]interface{}, len(container))
  827. for key, value := range container {
  828. out[key] = value
  829. }
  830. for _, key := range keys {
  831. delete(out, key)
  832. }
  833. return out
  834. case []interface{}:
  835. out := make([]interface{}, 0, len(container))
  836. for _, element := range container {
  837. remove := false
  838. if text, ok := element.(string); ok {
  839. for _, key := range keys {
  840. if text == key {
  841. remove = true
  842. break
  843. }
  844. }
  845. }
  846. if !remove {
  847. out = append(out, element)
  848. }
  849. }
  850. return out
  851. default:
  852. return node
  853. }
  854. }
  855. func jsonbDeleteIndex(array []interface{}, index int) []interface{} {
  856. if index < 0 {
  857. index += len(array)
  858. }
  859. if index < 0 || index >= len(array) {
  860. return array
  861. }
  862. out := make([]interface{}, 0, len(array)-1)
  863. out = append(out, array[:index]...)
  864. out = append(out, array[index+1:]...)
  865. return out
  866. }
  867. // jsonbConcatNodes implements jsonb || jsonb: objects merge right-wins, arrays
  868. // concatenate, and any non-array operand becomes a single-element array.
  869. func jsonbConcatNodes(left, right interface{}) interface{} {
  870. leftObject, leftIsObject := left.(map[string]interface{})
  871. rightObject, rightIsObject := right.(map[string]interface{})
  872. if leftIsObject && rightIsObject {
  873. out := make(map[string]interface{}, len(leftObject)+len(rightObject))
  874. for key, value := range leftObject {
  875. out[key] = value
  876. }
  877. for key, value := range rightObject {
  878. out[key] = value
  879. }
  880. return out
  881. }
  882. asArray := func(node interface{}) []interface{} {
  883. if array, ok := node.([]interface{}); ok {
  884. return array
  885. }
  886. return []interface{}{node}
  887. }
  888. out := append([]interface{}{}, asArray(left)...)
  889. return append(out, asArray(right)...)
  890. }
  891. // jsonbContains implements jsonb containment: object keys/values recurse, array
  892. // elements are order-independent, top-level arrays contain scalars, and scalars
  893. // compare by type.
  894. func jsonbContains(container, candidate interface{}) bool {
  895. // A top-level array contains a scalar candidate when any element does.
  896. switch candidate.(type) {
  897. case nil, bool, string, json.Number:
  898. if containerArray, ok := container.([]interface{}); ok {
  899. for _, element := range containerArray {
  900. if jsonbContains(element, candidate) {
  901. return true
  902. }
  903. }
  904. return false
  905. }
  906. }
  907. switch candidateValue := candidate.(type) {
  908. case map[string]interface{}:
  909. containerObject, ok := container.(map[string]interface{})
  910. if !ok {
  911. return false
  912. }
  913. for key, value := range candidateValue {
  914. other, exists := containerObject[key]
  915. if !exists || !jsonbContains(other, value) {
  916. return false
  917. }
  918. }
  919. return true
  920. case []interface{}:
  921. containerArray, ok := container.([]interface{})
  922. if ok {
  923. // PostgreSQL array containment does not require multiplicity: each
  924. // candidate element only needs some container element, and duplicates
  925. // may match the same element.
  926. for _, candidateElement := range candidateValue {
  927. matched := false
  928. for _, containerElement := range containerArray {
  929. if jsonbContains(containerElement, candidateElement) {
  930. matched = true
  931. break
  932. }
  933. }
  934. if !matched {
  935. return false
  936. }
  937. }
  938. return true
  939. }
  940. // A non-array container can still contain a nested empty array? No.
  941. return false
  942. case nil:
  943. return container == nil
  944. case bool:
  945. other, ok := container.(bool)
  946. return ok && other == candidateValue
  947. case string:
  948. other, ok := container.(string)
  949. return ok && other == candidateValue
  950. case json.Number:
  951. candidateText, err := canonicalJSONBNumber(candidateValue)
  952. if err != nil {
  953. return false
  954. }
  955. other, ok := container.(json.Number)
  956. if !ok {
  957. return false
  958. }
  959. containerText, err := canonicalJSONBNumber(other)
  960. if err != nil {
  961. return false
  962. }
  963. return containerText == candidateText
  964. }
  965. return false
  966. }
  967. // jsonbNodeTypeName returns the PostgreSQL jsonb type name.
  968. func jsonbNodeTypeName(node interface{}) string {
  969. switch node.(type) {
  970. case nil:
  971. return "null"
  972. case bool:
  973. return "boolean"
  974. case json.Number:
  975. return "number"
  976. case string:
  977. return "string"
  978. case []interface{}:
  979. return "array"
  980. case map[string]interface{}:
  981. return "object"
  982. default:
  983. return "unknown"
  984. }
  985. }
  986. // jsonbPathArg resolves a path operand to path steps. A text[] value (canonical
  987. // array text) is PostgreSQL's path form; a $string is the JSON1 path form this
  988. // engine already uses for -> and json_extract.
  989. func jsonbPathArg(value interface{}) ([]jsonPathSeg, error) {
  990. text := strings.TrimSpace(toString(value))
  991. switch {
  992. case strings.HasPrefix(text, "{"):
  993. return parseJSONBArrayPath(text)
  994. case strings.HasPrefix(text, "$"):
  995. return parseJSONBJSONPath(text)
  996. default:
  997. return nil, pgerror.InvalidParameter("jsonb path must be a text[] array literal such as '{a,0}' or a $ path, got %q", text)
  998. }
  999. }
  1000. // jsonbKeyListArg parses a text[] of object keys. Unlike a path, every element
  1001. // is a key: a numeric-looking key such as "1" must not become an array index.
  1002. func jsonbKeyListArg(value interface{}) ([]string, error) {
  1003. text := strings.TrimSpace(toString(value))
  1004. if !strings.HasPrefix(text, "{") {
  1005. return nil, pgerror.InvalidParameter("jsonb key list must be a text[] array literal, got %q", text)
  1006. }
  1007. elements, err := parseArrayLiteral(text)
  1008. if err != nil {
  1009. return nil, err
  1010. }
  1011. keys := make([]string, 0, len(elements))
  1012. for _, element := range elements {
  1013. if element == nil {
  1014. return nil, pgerror.InvalidParameter("jsonb key list element must not be NULL")
  1015. }
  1016. keys = append(keys, *element)
  1017. }
  1018. return keys, nil
  1019. }
  1020. // parseJSONBArrayPath parses PostgreSQL text[] path text into steps. A path
  1021. // element is kept as raw text because its meaning depends on the container it
  1022. // is applied to: an object key, or an integer array index. Numeric-looking
  1023. // object keys such as "1", "01", "-1", and "1.5" therefore stay keys when the
  1024. // container is an object.
  1025. func parseJSONBArrayPath(text string) ([]jsonPathSeg, error) {
  1026. elements, err := parseArrayLiteral(text)
  1027. if err != nil {
  1028. return nil, err
  1029. }
  1030. segs := make([]jsonPathSeg, 0, len(elements))
  1031. for _, element := range elements {
  1032. if element == nil {
  1033. return nil, pgerror.InvalidParameter("jsonb path element must not be NULL")
  1034. }
  1035. segs = append(segs, jsonPathSeg{dynamic: true, element: *element})
  1036. }
  1037. return segs, nil
  1038. }
  1039. // resolveJSONBPathSegment converts a PostgreSQL path element into a concrete
  1040. // object key or array index for the container it is applied to. Concrete steps
  1041. // (JSON1 $ paths and index/key steps) pass through unchanged. resolved is false
  1042. // when container is a scalar or missing; callers decide whether that is a
  1043. // not-found, an unchanged target, or an error. strict selects whether a
  1044. // non-integer element on an array is an error (jsonb path mutation and #-) or a
  1045. // non-match (jsonb #>).
  1046. func resolveJSONBPathSegment(seg jsonPathSeg, container interface{}, strict bool) (jsonPathSeg, bool, error) {
  1047. if !seg.dynamic {
  1048. return seg, true, nil
  1049. }
  1050. switch container.(type) {
  1051. case map[string]interface{}:
  1052. return jsonPathSeg{key: seg.element}, true, nil
  1053. case []interface{}:
  1054. index, err := strconv.Atoi(seg.element)
  1055. if err != nil {
  1056. if strict {
  1057. return seg, false, pgerror.InvalidText("path element %q is not an integer", seg.element)
  1058. }
  1059. return seg, false, nil
  1060. }
  1061. return jsonPathSeg{isIndex: true, index: index, fromEnd: index < 0}, true, nil
  1062. default:
  1063. return seg, false, nil
  1064. }
  1065. }
  1066. // parseJSONBJSONPath parses a JSON1 $ path for jsonb use and rejects the
  1067. // jsonpath shapes the engine cannot execute (wildcards, slices, unbounded
  1068. // expansion) with SQLSTATE 0A000.
  1069. func parseJSONBJSONPath(path string) ([]jsonPathSeg, error) {
  1070. if unsupportedJSONPathShape(path) {
  1071. return nil, pgerror.Unsupported("jsonpath wildcards, slices, and unbounded expansion are not supported; pass an explicit path")
  1072. }
  1073. segs, err := parseJSONPath(path)
  1074. if err != nil {
  1075. return nil, err
  1076. }
  1077. for _, segment := range segs {
  1078. if !segment.isIndex && (segment.key == "*" || strings.HasPrefix(segment.key, "**")) {
  1079. return nil, pgerror.Unsupported("jsonpath wildcards and unbounded expansion are not supported; pass an explicit path")
  1080. }
  1081. }
  1082. return segs, nil
  1083. }
  1084. // unsupportedJSONPathShape reports whether path text contains a jsonpath
  1085. // wildcard, slice, or deep-expansion marker inside brackets or as a bare member.
  1086. func unsupportedJSONPathShape(path string) bool {
  1087. for i := 0; i < len(path); i++ {
  1088. if path[i] != '[' {
  1089. continue
  1090. }
  1091. end := strings.IndexByte(path[i:], ']')
  1092. if end < 0 {
  1093. return false
  1094. }
  1095. inner := path[i+1 : i+end]
  1096. if strings.ContainsAny(inner, "*:") {
  1097. return true
  1098. }
  1099. i += end
  1100. }
  1101. return false
  1102. }
  1103. // jsonbSetPG implements PostgreSQL's jsonb_set path semantics. An empty path
  1104. // leaves the target unchanged. All steps except the last must exist and be
  1105. // containers; missing keys or a scalar on the way leave the target unchanged. A
  1106. // missing array position at the last step is appended when create is true, and
  1107. // an index before the start is clamped to the first position.
  1108. func jsonbSetPG(node interface{}, segs []jsonPathSeg, value interface{}, create bool) (interface{}, error) {
  1109. if len(segs) == 0 {
  1110. return node, nil
  1111. }
  1112. segment, resolved, err := resolveJSONBPathSegment(segs[0], node, true)
  1113. if err != nil {
  1114. return nil, err
  1115. }
  1116. if !resolved {
  1117. return nil, pgerror.InvalidParameter("cannot set path in scalar")
  1118. }
  1119. if len(segs) > 1 {
  1120. child, exists, err := jsonbPathChild(node, segment)
  1121. if err != nil {
  1122. return nil, err
  1123. }
  1124. if !exists {
  1125. return node, nil
  1126. }
  1127. switch child.(type) {
  1128. case map[string]interface{}, []interface{}:
  1129. default:
  1130. // PostgreSQL leaves the target unchanged when an intermediate step
  1131. // names a scalar rather than a container.
  1132. return node, nil
  1133. }
  1134. updated, err := jsonbSetPG(child, segs[1:], value, create)
  1135. if err != nil {
  1136. return nil, err
  1137. }
  1138. return jsonbReplaceChild(node, segment, updated)
  1139. }
  1140. switch container := node.(type) {
  1141. case map[string]interface{}:
  1142. if segment.isIndex {
  1143. return nil, pgerror.InvalidText("path element is not an object key")
  1144. }
  1145. if _, exists := container[segment.key]; !exists && !create {
  1146. return node, nil
  1147. }
  1148. out := make(map[string]interface{}, len(container)+1)
  1149. for key, item := range container {
  1150. out[key] = item
  1151. }
  1152. out[segment.key] = value
  1153. return out, nil
  1154. case []interface{}:
  1155. if !segment.isIndex {
  1156. return nil, pgerror.InvalidText("path element %q is not an integer", segment.key)
  1157. }
  1158. index := segment.index
  1159. if index < 0 {
  1160. index += len(container)
  1161. }
  1162. if index < 0 {
  1163. if !create {
  1164. return node, nil
  1165. }
  1166. out := make([]interface{}, 0, len(container)+1)
  1167. out = append(out, value)
  1168. return append(out, container...), nil
  1169. }
  1170. if index >= len(container) {
  1171. if !create {
  1172. return node, nil
  1173. }
  1174. out := append([]interface{}{}, container...)
  1175. return append(out, value), nil
  1176. }
  1177. out := append([]interface{}{}, container...)
  1178. out[index] = value
  1179. return out, nil
  1180. default:
  1181. return nil, pgerror.InvalidParameter("cannot set path in scalar")
  1182. }
  1183. }
  1184. // jsonbInsertPG implements PostgreSQL's jsonb_insert path semantics: array
  1185. // elements are inserted before or after an index (clamped into range), and an
  1186. // object key is inserted only when it is absent. An existing object key is an
  1187. // error, matching PostgreSQL.
  1188. func jsonbInsertPG(node interface{}, segs []jsonPathSeg, value interface{}, after bool) (interface{}, error) {
  1189. if len(segs) == 0 {
  1190. return node, nil
  1191. }
  1192. segment, resolved, err := resolveJSONBPathSegment(segs[0], node, true)
  1193. if err != nil {
  1194. return nil, err
  1195. }
  1196. if !resolved {
  1197. return nil, pgerror.InvalidParameter("cannot set path in scalar")
  1198. }
  1199. if len(segs) > 1 {
  1200. child, exists, err := jsonbPathChild(node, segment)
  1201. if err != nil {
  1202. return nil, err
  1203. }
  1204. if !exists {
  1205. return node, nil
  1206. }
  1207. switch child.(type) {
  1208. case map[string]interface{}, []interface{}:
  1209. default:
  1210. return node, nil
  1211. }
  1212. updated, err := jsonbInsertPG(child, segs[1:], value, after)
  1213. if err != nil {
  1214. return nil, err
  1215. }
  1216. return jsonbReplaceChild(node, segment, updated)
  1217. }
  1218. switch container := node.(type) {
  1219. case map[string]interface{}:
  1220. if segment.isIndex {
  1221. return nil, pgerror.InvalidText("path element is not an object key")
  1222. }
  1223. if _, exists := container[segment.key]; exists {
  1224. return nil, pgerror.InvalidParameter("cannot replace existing key")
  1225. }
  1226. out := make(map[string]interface{}, len(container)+1)
  1227. for key, item := range container {
  1228. out[key] = item
  1229. }
  1230. out[segment.key] = value
  1231. return out, nil
  1232. case []interface{}:
  1233. if !segment.isIndex {
  1234. return nil, pgerror.InvalidText("path element %q is not an integer", segment.key)
  1235. }
  1236. index := segment.index
  1237. if index < 0 {
  1238. index += len(container)
  1239. }
  1240. if index < 0 {
  1241. index = 0
  1242. }
  1243. if index > len(container) {
  1244. index = len(container)
  1245. }
  1246. if after {
  1247. index++
  1248. }
  1249. if index > len(container) {
  1250. index = len(container)
  1251. }
  1252. out := make([]interface{}, 0, len(container)+1)
  1253. out = append(out, container[:index]...)
  1254. out = append(out, value)
  1255. out = append(out, container[index:]...)
  1256. return out, nil
  1257. default:
  1258. return nil, pgerror.InvalidParameter("cannot set path in scalar")
  1259. }
  1260. }
  1261. // jsonbPathChild resolves one non-final path step to an existing child.
  1262. func jsonbPathChild(node interface{}, segment jsonPathSeg) (interface{}, bool, error) {
  1263. switch container := node.(type) {
  1264. case map[string]interface{}:
  1265. if segment.isIndex {
  1266. return nil, false, pgerror.InvalidParameter("jsonb path element %d does not identify an object key", segment.index)
  1267. }
  1268. child, exists := container[segment.key]
  1269. return child, exists, nil
  1270. case []interface{}:
  1271. if !segment.isIndex {
  1272. return nil, false, pgerror.InvalidParameter("jsonb path element %q does not identify an array index", segment.key)
  1273. }
  1274. index := segment.index
  1275. if index < 0 {
  1276. index += len(container)
  1277. }
  1278. if index < 0 || index >= len(container) {
  1279. return nil, false, nil
  1280. }
  1281. return container[index], true, nil
  1282. default:
  1283. return nil, false, pgerror.InvalidParameter("cannot walk a jsonb path through a %s", jsonbNodeTypeName(node))
  1284. }
  1285. }
  1286. // jsonbReplaceChild writes an updated child back into its container.
  1287. func jsonbReplaceChild(node interface{}, segment jsonPathSeg, child interface{}) (interface{}, error) {
  1288. switch container := node.(type) {
  1289. case map[string]interface{}:
  1290. if segment.isIndex {
  1291. return nil, pgerror.InvalidParameter("jsonb path element %d does not identify an object key", segment.index)
  1292. }
  1293. out := make(map[string]interface{}, len(container)+1)
  1294. for key, item := range container {
  1295. out[key] = item
  1296. }
  1297. out[segment.key] = child
  1298. return out, nil
  1299. case []interface{}:
  1300. if !segment.isIndex {
  1301. return nil, pgerror.InvalidParameter("jsonb path element %q does not identify an array index", segment.key)
  1302. }
  1303. index := segment.index
  1304. if index < 0 {
  1305. index += len(container)
  1306. }
  1307. if index < 0 || index >= len(container) {
  1308. return nil, pgerror.InvalidParameter("jsonb path array index %d is out of range", segment.index)
  1309. }
  1310. out := append([]interface{}{}, container...)
  1311. out[index] = child
  1312. return out, nil
  1313. default:
  1314. return nil, pgerror.InvalidParameter("cannot write a jsonb path through a %s", jsonbNodeTypeName(node))
  1315. }
  1316. }
  1317. // jsonbStripNulls removes object members whose value is JSON null. Array
  1318. // elements are kept, matching jsonb_strip_nulls.
  1319. func jsonbStripNulls(node interface{}) interface{} {
  1320. switch value := node.(type) {
  1321. case map[string]interface{}:
  1322. out := make(map[string]interface{}, len(value))
  1323. for key, item := range value {
  1324. if item == nil {
  1325. continue
  1326. }
  1327. out[key] = jsonbStripNulls(item)
  1328. }
  1329. return out
  1330. case []interface{}:
  1331. out := make([]interface{}, len(value))
  1332. for i, item := range value {
  1333. out[i] = jsonbStripNulls(item)
  1334. }
  1335. return out
  1336. default:
  1337. return node
  1338. }
  1339. }
  1340. // jsonbEncodeNode canonicalizes a tree that has already been validated.
  1341. func jsonbEncodeNode(node interface{}) (string, error) {
  1342. return encodeJSONB(node, false)
  1343. }
  1344. // evalJSONBFunction evaluates a native jsonb scalar function. handled is false
  1345. // for names it does not own, keeping the JSON1 surface untouched.
  1346. func (e *Executor) evalJSONBFunction(name string, fn *parser.FunctionCall, args []interface{}) (interface{}, bool, error) {
  1347. upper := strings.ToUpper(name)
  1348. switch upper {
  1349. case "TO_JSONB":
  1350. if len(args) != 1 {
  1351. return nil, true, pgerror.InvalidParameter("to_jsonb() requires exactly one argument")
  1352. }
  1353. if args[0] == nil {
  1354. return nil, true, nil
  1355. }
  1356. node, err := e.toJSONBNode(firstFunctionArg(fn), args[0])
  1357. if err != nil {
  1358. return nil, true, err
  1359. }
  1360. text, err := jsonbEncodeNode(node)
  1361. return text, true, err
  1362. case "JSONB_TYPEOF":
  1363. if len(args) != 1 {
  1364. return nil, true, pgerror.InvalidParameter("jsonb_typeof() requires exactly one argument")
  1365. }
  1366. node, err := jsonbNodeFromArg(args[0])
  1367. if err != nil {
  1368. return nil, true, err
  1369. }
  1370. if node == nil && args[0] == nil {
  1371. return nil, true, nil
  1372. }
  1373. return jsonbNodeTypeName(node), true, nil
  1374. case "JSONB_ARRAY_LENGTH":
  1375. if len(args) != 1 {
  1376. return nil, true, pgerror.InvalidParameter("jsonb_array_length() requires exactly one argument")
  1377. }
  1378. node, err := jsonbNodeFromArg(args[0])
  1379. if err != nil {
  1380. return nil, true, err
  1381. }
  1382. if node == nil && args[0] == nil {
  1383. return nil, true, nil
  1384. }
  1385. array, ok := node.([]interface{})
  1386. if !ok {
  1387. return nil, true, pgerror.InvalidParameter("cannot get array length of a jsonb %s", jsonbNodeTypeName(node))
  1388. }
  1389. return int64(len(array)), true, nil
  1390. case "JSONB_PRETTY":
  1391. if len(args) != 1 {
  1392. return nil, true, pgerror.InvalidParameter("jsonb_pretty() requires exactly one argument")
  1393. }
  1394. if args[0] == nil {
  1395. return nil, true, nil
  1396. }
  1397. node, err := jsonbNodeFromArg(args[0])
  1398. if err != nil {
  1399. return nil, true, err
  1400. }
  1401. text, err := encodeJSONB(node, true)
  1402. return text, true, err
  1403. case "JSONB_STRIP_NULLS":
  1404. if len(args) != 1 {
  1405. return nil, true, pgerror.InvalidParameter("jsonb_strip_nulls() requires exactly one argument")
  1406. }
  1407. if args[0] == nil {
  1408. return nil, true, nil
  1409. }
  1410. node, err := jsonbNodeFromArg(args[0])
  1411. if err != nil {
  1412. return nil, true, err
  1413. }
  1414. text, err := jsonbEncodeNode(jsonbStripNulls(node))
  1415. return text, true, err
  1416. case "JSONB_BUILD_ARRAY":
  1417. values := make([]interface{}, len(args))
  1418. for i, arg := range args {
  1419. node, err := e.toJSONBNode(functionArgAt(fn, i), arg)
  1420. if err != nil {
  1421. return nil, true, err
  1422. }
  1423. values[i] = node
  1424. }
  1425. text, err := jsonbEncodeNode(values)
  1426. return text, true, err
  1427. case "JSONB_BUILD_OBJECT":
  1428. if len(args)%2 != 0 {
  1429. return nil, true, pgerror.InvalidParameter("jsonb_build_object() argument list must have an even number of elements")
  1430. }
  1431. object := make(map[string]interface{}, len(args)/2)
  1432. for i := 0; i+1 < len(args); i += 2 {
  1433. if args[i] == nil {
  1434. return nil, true, pgerror.InvalidParameter("jsonb_build_object() argument %d: key must not be null", i+1)
  1435. }
  1436. key := toString(args[i])
  1437. node, err := e.toJSONBNode(functionArgAt(fn, i+1), args[i+1])
  1438. if err != nil {
  1439. return nil, true, err
  1440. }
  1441. object[key] = node
  1442. }
  1443. text, err := jsonbEncodeNode(object)
  1444. return text, true, err
  1445. case "JSONB_SET", "JSONB_INSERT", "JSONB_REPLACE", "JSONB_REMOVE":
  1446. value, err := e.evalJSONBPatch(upper, fn, args)
  1447. return value, true, err
  1448. case "JSONB_EACH", "JSONB_EACH_TEXT", "JSONB_ARRAY_ELEMENTS", "JSONB_ARRAY_ELEMENTS_TEXT", "JSONB_OBJECT_KEYS":
  1449. 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))
  1450. case "JSONB_PATH_EXISTS", "JSONB_PATH_EXISTS_TZ", "JSONB_PATH_MATCH", "JSONB_PATH_MATCH_TZ",
  1451. "JSONB_PATH_QUERY", "JSONB_PATH_QUERY_TZ", "JSONB_PATH_QUERY_ARRAY", "JSONB_PATH_QUERY_ARRAY_TZ",
  1452. "JSONB_PATH_QUERY_FIRST", "JSONB_PATH_QUERY_FIRST_TZ":
  1453. return nil, true, pgerror.Unsupported("jsonpath (%s) is not supported", strings.ToLower(name))
  1454. }
  1455. return nil, false, nil
  1456. }
  1457. // firstFunctionArg returns the first argument expression of a call, or nil when
  1458. // the call has no arguments.
  1459. func firstFunctionArg(fn *parser.FunctionCall) parser.Expr {
  1460. if fn == nil || len(fn.Args) == 0 {
  1461. return nil
  1462. }
  1463. return fn.Args[0]
  1464. }
  1465. func functionArgAt(fn *parser.FunctionCall, index int) parser.Expr {
  1466. if fn == nil || index < 0 || index >= len(fn.Args) {
  1467. return nil
  1468. }
  1469. return fn.Args[index]
  1470. }
  1471. // toJSONBNode converts a SQL value to a JSON tree node, decoding arrays into
  1472. // JSON arrays so to_jsonb(jsonb_build_array(...)) and to_jsonb(array_column)
  1473. // keep their element types.
  1474. func (e *Executor) toJSONBNode(expr parser.Expr, value interface{}) (interface{}, error) {
  1475. if value == nil {
  1476. return nil, nil
  1477. }
  1478. // to_jsonb(jsonb) is the identity: a jsonb argument is embedded as its
  1479. // document, not as a JSON string.
  1480. if e.isJSONBExpr(expr) {
  1481. return jsonbNodeFromArg(value)
  1482. }
  1483. if typeName, ok := e.arrayTypeOf(expr); ok {
  1484. elements, err := parseArrayLiteral(toString(value))
  1485. if err != nil {
  1486. return nil, err
  1487. }
  1488. elementType, _ := arrayElementType(typeName)
  1489. nodes := make([]interface{}, len(elements))
  1490. for i, element := range elements {
  1491. typed, valueErr := arrayElementValue(element, elementType)
  1492. if valueErr != nil {
  1493. return nil, valueErr
  1494. }
  1495. node, nodeErr := jsonbNodeFromSQLValue(typed)
  1496. if nodeErr != nil {
  1497. return nil, nodeErr
  1498. }
  1499. nodes[i] = node
  1500. }
  1501. return nodes, nil
  1502. }
  1503. return jsonbNodeFromSQLValue(value)
  1504. }
  1505. // jsonbPatchNode converts a JSON1 $ path patch value to a JSON tree node. A
  1506. // float64 must become a json.Number before it reaches the encoder, and NaN and
  1507. // infinity are rejected instead of producing invalid JSON.
  1508. func jsonbPatchNode(value interface{}) (interface{}, error) {
  1509. switch typed := value.(type) {
  1510. case jsonText:
  1511. if node, err := jsonDecode(string(typed)); err == nil {
  1512. return node, nil
  1513. }
  1514. return string(typed), nil
  1515. case nil, bool, int, int8, int16, int32, int64,
  1516. uint, uint32, uint64, float32, float64, string, []byte:
  1517. return jsonbNodeFromSQLValue(value)
  1518. default:
  1519. return jsonArgToNode(value), nil
  1520. }
  1521. }
  1522. // evalJSONBPatch evaluates the jsonb_set/jsonb_insert/jsonb_replace/
  1523. // jsonb_remove family. A $ path keeps the JSON1 semantics the engine already
  1524. // exposed; a PostgreSQL text[] path uses PostgreSQL's jsonb_set/jsonb_insert
  1525. // rules and accepts the optional boolean fourth argument.
  1526. func (e *Executor) evalJSONBPatch(name string, fn *parser.FunctionCall, args []interface{}) (interface{}, error) {
  1527. minArgs := 2
  1528. if name != "JSONB_REMOVE" {
  1529. minArgs = 3
  1530. }
  1531. if len(args) < minArgs {
  1532. return nil, pgerror.InvalidParameter("%s() requires at least %d arguments", strings.ToLower(name), minArgs)
  1533. }
  1534. if args[0] == nil || args[1] == nil {
  1535. return nil, nil
  1536. }
  1537. node, err := jsonbNodeFromArg(args[0])
  1538. if err != nil {
  1539. return nil, err
  1540. }
  1541. if name == "JSONB_REMOVE" {
  1542. for _, path := range args[1:] {
  1543. if path == nil {
  1544. return nil, nil
  1545. }
  1546. segs, pathErr := jsonbPathArg(path)
  1547. if pathErr != nil {
  1548. return nil, pathErr
  1549. }
  1550. node, err = jsonRemove(node, segs)
  1551. if err != nil {
  1552. return nil, err
  1553. }
  1554. }
  1555. return jsonbEncodeNode(node)
  1556. }
  1557. // JSON1 multi-path form: jsonb_set(doc, path, value, path, value, ...).
  1558. // PostgreSQL's form has exactly three or four arguments.
  1559. pathText := strings.TrimSpace(toString(args[1]))
  1560. pgPath := strings.HasPrefix(pathText, "{")
  1561. if pgPath && len(args) > 4 {
  1562. return nil, pgerror.InvalidParameter("%s() with a PostgreSQL path accepts at most four arguments", strings.ToLower(name))
  1563. }
  1564. if len(args) == 4 && !pgPath {
  1565. 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))
  1566. }
  1567. flag := false
  1568. if len(args) == 4 {
  1569. if args[3] == nil {
  1570. return nil, nil
  1571. }
  1572. flag = toBool(args[3])
  1573. }
  1574. if !pgPath {
  1575. // JSON1 form: every path/value pair is applied in order. A plain SQL
  1576. // string becomes a JSON string, which is the behavior this engine exposed
  1577. // before JSONB became native; a jsonb-typed value embeds its document.
  1578. mode := "set"
  1579. switch name {
  1580. case "JSONB_INSERT":
  1581. mode = "insert"
  1582. case "JSONB_REPLACE":
  1583. mode = "replace"
  1584. }
  1585. for i := 1; i+1 < len(args); i += 2 {
  1586. if args[i] == nil || args[i+1] == nil {
  1587. return nil, nil
  1588. }
  1589. segs, pathErr := jsonbPathArg(args[i])
  1590. if pathErr != nil {
  1591. return nil, pathErr
  1592. }
  1593. var patchValue interface{}
  1594. if e.isJSONBExpr(functionArgAt(fn, i+1)) {
  1595. patchValue, err = jsonbNodeFromArg(args[i+1])
  1596. } else {
  1597. patchValue, err = jsonbPatchNode(args[i+1])
  1598. }
  1599. if err != nil {
  1600. return nil, err
  1601. }
  1602. node, err = jsonApplyPatch(node, segs, patchValue, mode)
  1603. if err != nil {
  1604. return nil, err
  1605. }
  1606. }
  1607. return jsonbEncodeNode(node)
  1608. }
  1609. if args[2] == nil {
  1610. return nil, nil
  1611. }
  1612. newValueNode, err := jsonbNodeFromArg(args[2])
  1613. if err != nil {
  1614. return nil, err
  1615. }
  1616. segs, err := jsonbPathArg(args[1])
  1617. if err != nil {
  1618. return nil, err
  1619. }
  1620. switch name {
  1621. case "JSONB_SET":
  1622. create := true
  1623. if len(args) == 4 {
  1624. create = flag
  1625. }
  1626. node, err = jsonbSetPG(node, segs, newValueNode, create)
  1627. case "JSONB_INSERT":
  1628. node, err = jsonbInsertPG(node, segs, newValueNode, flag)
  1629. case "JSONB_REPLACE":
  1630. return nil, pgerror.Unsupported("jsonb_replace() with a PostgreSQL path is not supported; use jsonb_set or the JSON1 $ path form")
  1631. }
  1632. if err != nil {
  1633. return nil, err
  1634. }
  1635. return jsonbEncodeNode(node)
  1636. }
  1637. // jsonbTableFunction materializes a set-returning jsonb function as a relation.
  1638. // The returned types are the SQL type names used for result metadata.
  1639. func jsonbTableFunction(name string, value interface{}) (columns, types []string, rows [][]interface{}, err error) {
  1640. node, err := jsonbNodeFromArg(value)
  1641. if err != nil {
  1642. return nil, nil, nil, err
  1643. }
  1644. if value == nil {
  1645. switch strings.ToLower(name) {
  1646. case "jsonb_each":
  1647. return []string{"key", "value"}, []string{"TEXT", "JSONB"}, nil, nil
  1648. case "jsonb_each_text":
  1649. return []string{"key", "value"}, []string{"TEXT", "TEXT"}, nil, nil
  1650. case "jsonb_object_keys":
  1651. return []string{"jsonb_object_keys"}, []string{"TEXT"}, nil, nil
  1652. case "jsonb_array_elements_text":
  1653. return []string{"value"}, []string{"TEXT"}, nil, nil
  1654. default:
  1655. return []string{"value"}, []string{"JSONB"}, nil, nil
  1656. }
  1657. }
  1658. switch strings.ToLower(name) {
  1659. case "jsonb_each", "jsonb_each_text", "jsonb_object_keys":
  1660. object, ok := node.(map[string]interface{})
  1661. if !ok {
  1662. return nil, nil, nil, pgerror.InvalidParameter("cannot call %s() on a jsonb %s", strings.ToLower(name), jsonbNodeTypeName(node))
  1663. }
  1664. keys := make([]string, 0, len(object))
  1665. for key := range object {
  1666. keys = append(keys, key)
  1667. }
  1668. sort.Strings(keys)
  1669. if strings.EqualFold(name, "jsonb_object_keys") {
  1670. rows = make([][]interface{}, 0, len(keys))
  1671. for _, key := range keys {
  1672. rows = append(rows, []interface{}{key})
  1673. }
  1674. return []string{"jsonb_object_keys"}, []string{"TEXT"}, rows, nil
  1675. }
  1676. textValues := strings.EqualFold(name, "jsonb_each_text")
  1677. valueType := "JSONB"
  1678. if textValues {
  1679. valueType = "TEXT"
  1680. }
  1681. rows = make([][]interface{}, 0, len(keys))
  1682. for _, key := range keys {
  1683. var rendered interface{}
  1684. if textValues {
  1685. rendered, err = jsonbNodeToText(object[key])
  1686. } else {
  1687. rendered, err = encodeJSONB(object[key], false)
  1688. }
  1689. if err != nil {
  1690. return nil, nil, nil, err
  1691. }
  1692. rows = append(rows, []interface{}{key, rendered})
  1693. }
  1694. return []string{"key", "value"}, []string{"TEXT", valueType}, rows, nil
  1695. case "jsonb_array_elements", "jsonb_array_elements_text":
  1696. array, ok := node.([]interface{})
  1697. if !ok {
  1698. return nil, nil, nil, pgerror.InvalidParameter("cannot call %s() on a jsonb %s", strings.ToLower(name), jsonbNodeTypeName(node))
  1699. }
  1700. textValues := strings.EqualFold(name, "jsonb_array_elements_text")
  1701. valueType := "JSONB"
  1702. if textValues {
  1703. valueType = "TEXT"
  1704. }
  1705. rows = make([][]interface{}, 0, len(array))
  1706. for _, element := range array {
  1707. var rendered interface{}
  1708. if textValues {
  1709. rendered, err = jsonbNodeToText(element)
  1710. } else {
  1711. rendered, err = encodeJSONB(element, false)
  1712. }
  1713. if err != nil {
  1714. return nil, nil, nil, err
  1715. }
  1716. rows = append(rows, []interface{}{rendered})
  1717. }
  1718. return []string{"value"}, []string{valueType}, rows, nil
  1719. }
  1720. return nil, nil, nil, pgerror.Unsupported("table function %s() is not supported", name)
  1721. }
  1722. // normalizeJSONBRow canonicalizes every JSONB-typed column value before it is
  1723. // written, mirroring normalizeArrayRow. A value is canonicalized once, so a
  1724. // reload reads back the same bytes.
  1725. func (e *Executor) normalizeJSONBRow(schema *storage.Schema, row storage.Row) error {
  1726. if schema == nil {
  1727. return nil
  1728. }
  1729. for _, column := range schema.Columns {
  1730. if !strings.EqualFold(strings.TrimSpace(column.Type), "JSONB") {
  1731. continue
  1732. }
  1733. value, ok := lookupRowValue(row, column.Name)
  1734. if !ok || value == nil {
  1735. continue
  1736. }
  1737. text, isText := value.(string)
  1738. if !isText {
  1739. if jsonValue, isJSON := value.(jsonText); isJSON {
  1740. text = string(jsonValue)
  1741. } else {
  1742. return pgerror.InvalidText("column %q is %s and accepts JSON text, got %T", column.Name, column.Type, value)
  1743. }
  1744. }
  1745. canonical, err := CanonicalizeJSONB(text)
  1746. if err != nil {
  1747. return fmt.Errorf("column %q: %w", column.Name, err)
  1748. }
  1749. row[column.Name] = canonical
  1750. }
  1751. return nil
  1752. }
  1753. // canonicalJSONBDefault canonicalizes a constant DEFAULT for a JSONB column so
  1754. // the catalog and any ALTER TABLE backfill store the same bytes an INSERT would.
  1755. func canonicalJSONBDefault(typeName string, value interface{}, exprText string) (interface{}, string, error) {
  1756. if !strings.EqualFold(strings.TrimSpace(typeName), "JSONB") || exprText != "" || value == nil {
  1757. return value, exprText, nil
  1758. }
  1759. text, ok := value.(string)
  1760. if !ok {
  1761. if jsonValue, isJSON := value.(jsonText); isJSON {
  1762. text = string(jsonValue)
  1763. } else {
  1764. return nil, "", pgerror.InvalidText("DEFAULT for %s must be JSON text, got %T", typeName, value)
  1765. }
  1766. }
  1767. canonical, err := CanonicalizeJSONB(text)
  1768. if err != nil {
  1769. return nil, "", err
  1770. }
  1771. return canonical, "", nil
  1772. }