Skip to content

View table support? #7197

Open

Description

@itaied246

Hello,

I'm using sequelize as my ORM for a small web app I'm writing as a hobby.
After modeling my data and creating the objects, I noticed that a view table can help me a lot querying data.
Searching the github repo, I found this question, and I wanted to know why isn't it possible to implement views on sequelize?

I have an offer model, which contains the following fields (uppercase name represents references for tables):

Offer
|--id
|--price
|__Game
|----name
|----platform
|____GiantGame
|--------image

All of my queries to offer will require the image, platform and name, so I need to execute a join (sequelize include).
I think a view here could make it much easier.
Is there another way to create the view and keep it consistent?

Activity

  1. dmlukichev commented on May 1, 2017

    @dmlukichev

    I have similar issue right now.

    Indeed, views are not supported.
    But you can still use them after defining view's model.
    The only problem would be schema sync and this can be avoided by overriding sync() and drop() methods.

    import Sequelize from 'sequelize';
    import { readFile } from 'fs';
    import { promisify } from 'bluebird';
    import { resolve as pathResolve } from 'path';
    
    export default function (sequelize) {
        return sequelize.define('GameOfferView', {
            id: {
                type: Sequelize.STRING(32),
                primaryKey: true
            },
            price: Sequelize.REAL,
            platform: Sequelize.ENUM(),
            /* other columns */
        }, {
            tableName: 'game_offer_view',
            classMethods: {
                async sync(options) {
                    const viewPath = pathResolve(__dirname, '/game-offer-view.sql');
                    const viewSource = await promisify(readFile)(path, { encoding: 'utf-8' });
    
                    await sequelize.query(viewSource, {
                        logging: options.logging,
                    });
                },
    
                async drop(options) {
                    return sequelize.query('DROP VIEW IF EXISTS game_offer_view', {
                        logging: options.logging,
                    });
                }
            }
        });
    }

    If you have multiple views you can even add some utility function that takes model and adds that methods. If you will, I would advise you also to override create(), update() and delete() methods with something that throws errors. And publish this mixin so I could use it too :)

  2. stale commented on Jun 30, 2017

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  3. phillippbertram commented on Apr 20, 2018

    @phillippbertram

    This is not working (anymore?) with sequelize v4.37.1 :/

    As the documentation says in Upgrade-To-v4, classMethods and instanceMethods are removed. So tried the new way to define or override those methods like they are describing:

    const Model = sequelize.define('Model', {
        ...
    });
    
    // Class Method
    Model.associate = function (models) {
        ...associate the models
    };
    
    // Instance Method
    Model.prototype.someMethod = function () {..}

    Here is what's my code looks like (simplified) in typesript

    model = return sequelize.define('GameOfferView', { ... });
    model.sync = async function (options?: Sequelize.SyncOptions) {
        const viewPath = pathResolve(__dirname, '../../../sql/script_to_create_view.sql');
        const viewSource = await promisify(readFile)(viewPath, { encoding: 'utf-8' });
        await sequelize.query(viewSource, {
          logging: options.logging
        });
        return this as any;
     };

    But I am not getting sync to be called, neither by using classMethods nor by using the model.sync = ... way if I run sequelize.sync({ force: true }).

    Maybe anyone else has a solution?

    Thanks in advance,
    Phillipp

  4. thehappycoder commented on Apr 24, 2018

    @thehappycoder

    I need this feature too.

  5. thehappycoder commented on Apr 24, 2018

    @thehappycoder

    @phillippbertram
    Try to get rid of async and do something like this:

    model.sync = (options: SyncOptions) => {
    ...
    }
    
  6. abelosorio commented on Jul 31, 2018

    @abelosorio
  7. LittleSaya commented on Sep 3, 2019

    @LittleSaya
    Contributor

    My choice is writing and wrapping raw queries to mock the functionality of view, though I still think it'd be better if there is an official support for it.

  8. papb commented on Sep 4, 2019

    @papb
    Member
  9. reopened this on Sep 4, 2019
  10. added
    type: feature
    on Sep 4, 2019
  11. LittleSaya commented on Sep 4, 2019

    @LittleSaya
    Contributor

    @papb I'm using MySQL and sequlize-views-support's doc says it only supports PostgreSQL so I didn't try it.

  12. papb commented on Sep 4, 2019

    @papb
    Member

    @LittleSaya Ah, I see! Ok.

  13. nichatr commented on Sep 22, 2019

    @nichatr

    My choice is writing and wrapping raw queries to mock the functionality of view, though I still think it'd be better if there is an official support for it.

    Could you elaborate how it is done?
    I'm using sequelize models for the tables and add associations, so the query for me is actually a findOne/findAll with the addition of "includes".

  14. amirh715 commented on Sep 27, 2020

    @amirh715

    Hello. Aren't views supported yet?

  15. paolocattani commented on Jan 18, 2021

    @paolocattani

    Any updates on views support?

  16. exos commented on Sep 4, 2021

    @exos

    I'm working to add views support in a project where I'm working, I'm thinking publish it like a decorator, but if there are interest in this feature, I can send a PR to the main project, but, I need more time.

  17. tonypee commented on Feb 17, 2022

    @tonypee

    @exos How did you go with this? Im interested in view support for mysql

  18. exos commented on Mar 1, 2022

    @exos

    @exos How did you go with this? Im interested in view support for mysql

    Yes! sorry the delay, I was very bussy this time. I just publish this:

    https://exoshtw.github.io/sequelize-view-support/

    I did prepared this docuementation in some hours, I'm aware that this documentation is plagued with typos errors and misspelled text, sorry for that, my primary language are not the english. I wold appreciate for PR's fixing docuementation.

    Thanks.

  19. added theissue type on Mar 9, 2025
  20. removed
    type: feature
    on Mar 9, 2025
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

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions