Skip to content

Querying Postgres jsonb column contaning non-text type of fields cause "operator does not exist" exception #3824

Closed

Description

@xwk

Suppose model Store has a column called 'jsonb' which has type jsonb. Query like

Store.find({
      where: {
        jsonb: {
          enabled: true
        }
      }

will cause SequelizeDatabaseError: operator does not exist: text = boolean exception.

The reason for that is Sequelize will translate the query into following SQL

SELECT "id", "jsonb", "createdAt", "updatedAt" FROM "stores" AS "store" WHERE ("store"."jsonb"#>>'{enabled}') = true LIMIT 1.

Notice #>> operator is used, which converts the jsonb type to text. The correct SQL should be

SELECT "id", "jsonb", "createdAt", "updatedAt" FROM "stores" AS "store" WHERE ("store"."jsonb"#>'{enabled}') = 'true'::jsonb LIMIT 1;

Full sample code as below

var Sequelize, Store, configs, sequelize;

Sequelize = require("sequelize");

configs = require("../configs");

sequelize = new Sequelize(configs.DB_NAME, configs.DB_USERNAME, configs.DB_PASSWORD, {
  host: configs.DB_HOSTNAME,
  dialect: 'postgres'
});

Store = sequelize.define('store', {
  jsonb: Sequelize.JSONB
});

Store.sync({
  force: true
}).then(function() {
  return Store.create({
    jsonb: {
      name: 'test store',
      enabled: true,
      grade: 3
    }
  }).then(function() {
    return Store.find({
      where: {
        jsonb: {
          enabled: true
        }
      }
    });
  })

Activity

  1. mickhansen commented on May 29, 2015

    @mickhansen
    Contributor

    ("store"."jsonb"#>'{enabled}')::boolean = true might work aswell? That's the technique we use for numbers

  2. added
    type: bug
    on May 29, 2015
  3. added a commit that references this issue on Sep 18, 2017
    0af0406
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    staletype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions