Search code examples
sqljsonpostgresqlgogo-gorm

Search JSONB Data GORM & PostgreSQL


How to access JSONB data type and search a data that nested inside it using GORM?

Lets say the table products has info column that contain the JSONB type, like below:

{
 "ID": 1,
 "NAME": "Product A",
 "INFO": {
  "DESCRIPTION": "lorem ipsum",
  "BUYERS": [
   {
   "ID": 1,
   "NAME": "John Doe"
   },
   {
   "ID": 2,
   "NAME": "Jane Doe"
   }
  ]
 }
}

From the JSONB that stored in the PostgreSQL I want search the product by the buyers name if any of them are match.

So the PostgreSQL query that worked would be:

SELECT * FROM products WHERE info -> 'buyers' @> '[{"name": "Jane Doe"}]'

I have tried with GORM but it doesn't work:

result = db.Where("info-> 'buyers' @> '[{\"name\": ?}]'", request.body.name).Find(&products)

Where I got error and the SQL query output like below:

SELECT * FROM "products" WHERE info -> 'buyers' @> '[{"name": 'Jane Doe'}]'
ERROR: invalid input syntax for type json (SQLSTATE 22P02)

It seems the GORM query builder uses the string type with single quote instead of double quote so that cause the error of the JSONB search it should be "name": "Jane Doe" not "name": 'Jane Doe'

Therefore, how to change the single quote into double quote of the where clause value?


Solution

  • Build the json string inside the SQL?

    result = db.Where("info -> 'buyers' @> '[{\"name\": \"' || ? || '\"}]'", request.body.name).Find(&products)
    

    Which would create the SQL...

    SELECT * FROM products WHERE info -> 'buyers' @> '[{"name": "' || 'Jane Doe' || '"}]'