David
David

Reputation: 1356

Where clause using included relation in `OR` statement

I'm moving a project from MySQL to Postgres using Sequelize, and there is one thing that has failed straight away. It looks to be due to the fact that 'User' isn't included anywhere.

Edit: the error message is 'missing FROM-clause entry for table users'.

The code for sequelize is:

List.model.findOne({
  where: {
    id: listId,
    $or: [
      { open: true },
      ['Users.id = ?', [userId]], // <-- the line I think is breaking this.
    ],
  },
  include: [{
    model: db.models.User
  }],
});

I think this is due to User not being included in the FROM clause. But, I'm not sure how to make Sequelize do the right thing.

The query generated by Sequelize is:

SELECT "List"."id",
   "List"."name",
   "List"."image",
   "List"."slug",
   "List"."open",
   "List"."password",
   "List"."createdAt",
   "List"."updatedAt",
   "List"."OwnerId",
   "Users"."id" AS "Users.id",
   "Users"."firstName" AS "Users.firstName",
   "Users"."lastName" AS "Users.lastName",
   "Users"."email" AS "Users.email",
   "Users"."password" AS "Users.password",
   "Users"."image" AS "Users.image",
   "Users"."facebookId" AS "Users.facebookId",
   "Users"."googleId" AS "Users.googleId",
   "Users"."createdAt" AS "Users.createdAt",
   "Users"."updatedAt" AS "Users.updatedAt",
   "Users.UserList"."createdAt" AS "Users.UserList.createdAt",
   "Users.UserList"."updatedAt" AS "Users.UserList.updatedAt",
   "Users.UserList"."ListId" AS "Users.UserList.ListId",
   "Users.UserList"."UserId" AS "Users.UserList.UserId"
FROM "Lists" AS "List"
LEFT OUTER JOIN ("UserList" AS "Users.UserList"
             INNER JOIN "Users" AS "Users" ON "Users"."id" =     "Users.UserList"."UserId") ON "List"."id" = "Users.UserList"."ListId"
WHERE "List"."id" = 13
  AND ("List"."open" = TRUE
   OR (Users.id = 1234));

Upvotes: 0

Views: 95

Answers (1)

icuken
icuken

Reputation: 1356

Try to wrap Users.id with double quotes like "Users"."id", because in PostgreSQL all unquoted identifiers (table names, fields) will be folded to lowercase and PostgreSQL is case-sensitive: https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS

Quoting an identifier also makes it case-sensitive, whereas unquoted names are always folded to lower case. For example, the identifiers FOO, foo, and "foo" are considered the same by PostgreSQL, but "Foo" and "FOO" are different from these three and each other. (The folding of unquoted names to lower case in PostgreSQL is incompatible with the SQL standard, which says that unquoted names should be folded to upper case. Thus, foo should be equivalent to "FOO" not "foo" according to the standard. If you want to write portable applications you are advised to always quote a particular name or never quote it.)

Upvotes: 4

Related Questions