Search code examples
sqlnode.jspostgresqlsequelize.jsquoted-identifier

SQL query to PostgeSQL tables


I have a problem.

SELECT * 
FROM posts CROSS JOIN public."postReactions" AS reactions
WHERE posts.userId = '423abb9e-a00d-4045-9e88-4a85897f67e4'

But the response from DB is like 'ERROR: column posts.userid doesn't exist. LINE 3: WHERE posts.userId = '423abb9e-a00d-4045-9e88-4a85897f67e4'.

Result of CROSS JOIN below:

enter image description here

    • Posts table
    • PostReactions table

Sequelize models below:

 export default models => {
  const {
    User,
    Post,
    PostReaction,
    PostNegativeReaction,
    Comment,
    Image
  } = models;


  User.hasMany(Post);
  User.hasMany(PostReaction);

  Post.belongsTo(User);
  Post.hasMany(PostReaction);

  PostReaction.belongsTo(Post);
  PostReaction.belongsTo(User);
};

This is my associations:

export default {
  up: (queryInterface, Sequelize) => queryInterface.sequelize
    .transaction(transaction => Promise.all([     
      queryInterface.addColumn('posts', 'userId', {
        type: Sequelize.UUID,
        references: {
          model: 'users',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL'
      }, { transaction }),
      queryInterface.addColumn('postReactions', 'userId', {
        type: Sequelize.UUID,
        references: {
          model: 'users',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL'
      }, { transaction }),
      queryInterface.addColumn('postReactions', 'postId', {
        type: Sequelize.UUID,
        references: {
          model: 'posts',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL'
      }, { transaction }),     
    ])),

  down: queryInterface => queryInterface.sequelize
    .transaction(transaction => Promise.all([
      queryInterface.removeColumn('posts', 'userId', { transaction }),
      queryInterface.removeColumn('postReactions', 'userId', { transaction }),
      queryInterface.removeColumn('postReactions', 'postId', { transaction })
    ]))
};

MERN stack. Main problem: how to do a request to db that will receive the response with POSTS body (only liked by the current user).


Solution

  • This would be possible if the table were created using escaped column names . . . "postId" rather than postId.

    I suspect that is the problem. The best solution is to recreate the table and not escape any identifiers, ever. Alternatively, you can use the escaped column name.