Skip to content

can i use VIEW with sequelize ? #3078

Closed

Description

@neekey

Hi, I'm implementing a simple version system, and I have designed a draft EER diagram(part of it):

image

As this diagram tells, besides schema_core, there are also schema_content and schema_mock attached to schema_core, and each of them need to have a version whenever updated. schema_version is just a set of references to schema_content and schema_mock, and combine two versions into one "schema version".

Now I want to use VIEW to get me the latest "schema version" and combine with schema_core.

Activity

  1. janmeier commented on Feb 9, 2015

    @janmeier
    Member

    There is no way to create views on sequelize, but you can create the view manually and query it like a regular sequelize model.

    So you use a raw query to create the view, and query the table using a regular sequelize model:

    sequelize.define('schema_content', {
      ...
    });

    Just remember not to .sync the schema_content model

  2. neekey commented on Feb 9, 2015

    @neekey
    Author

    @janmeier Thank you for sharing your idea. But since I generally use sequelize.sync() to sync all the models, it's a little risky. And what came to my mind suddenly is that there seems lots of restrictions when you try to update a view. So event if I imply your idea, I guess it will not be easy to just use SchemaContent.create( { .. } ); and then do something like updating attributes and saving it.

  3. janmeier commented on Feb 9, 2015

    @janmeier
    Member

    I'm not at all familiar with updating a parent table through a view, so can't help you there.

  4. neekey commented on Feb 9, 2015

    @neekey
    Author

    So may be the easiest way to do this is just add a version column to schema_core, and update it whenever schema_version updates ? Any better idea?

  5. neekey commented on Feb 9, 2015

    @neekey
    Author

    @janmeier Thank you for your sharing : )

  6. janmeier commented on Feb 13, 2015

    @janmeier
    Member

    @neekey That sounds reasonable, I dont have any better ideas

  7. drkstr101 commented on Jan 14, 2018

    @drkstr101

    const MyView = sequelize.define('my_view', {});

    Error: Table 'mydb.my_view' doesn't exist

    Attempting to define a model from an existing view throws the above error. Sequelize 4.24.0 & Maria DB 10.2.10

  8. abelosorio commented on Jul 31, 2018

    @abelosorio
  9. mariusa commented on Aug 25, 2020

    @mariusa

    Hi, with one model, would it be possible to READ from a view, and have write operations to the table, as usual?

  10. soonsam123 commented on Aug 28, 2020

    @soonsam123

    Hi, with one model, would it be possible to READ from a view, and have write operations to the table, as usual?

    In my case I need to set the name of the database at runtime and also I need to write to the table and read from the view. For that I changed my model to get those fields at runtime.

    models/liberacoes.js

    module.exports = (sequelize, DataTypes, nomeTable = "liberacoes") => {
      class Liberacoes extends Model {}
      Liberacoes.init(
        {
          horario: DataTypes.DATEONLY,
          ....
        },
        {
          sequelize,
          modelName: nomeTable,
          timestamps: false,
        }
      );
      return Liberacoes;
    };
    
    

    When reading data I pass the name of the view as a parameter

          const liberacoes = await Liberacoes(
            sequelize,
            Sequelize.DataTypes,
            'view_liberacao'
          ).findAll();
    

    When writing data I just leave the default, which is the name of the table

          const liberacao = await Liberacoes(sequelize, Sequelize.DataTypes).create(...);
    
  11. KeyOnTech commented on Nov 16, 2020

    @KeyOnTech

    Hi saw this thread and figured it out if this is still an issue for anybody...
    going to try and explain best i can
    first create a model file with the fields you need from your view, in this model there has to be a primary index...

    sequelize/model/view_model_vwloginslist.js

    const Sequelize = require('sequelize');
    const sequelize = require('../database/connection');
    module.exports = sequelize.define("vwloginslist",
    {
    loginid: {
    field: 'id',
    type: Sequelize.INTEGER,
    allowNull: false,
    autoIncrement: true,
    primaryKey: true,
    },
    name: {
    type: Sequelize.STRING(255),
    },
    login: {
    type: Sequelize.STRING(255),
    },
    roledescription: {
    type: Sequelize.STRING(255),
    },
    },
    {
    timestamps: false,
    }
    );

  12. KeyOnTech commented on Nov 16, 2020

    @KeyOnTech

    next make a migration file, the special thing about this file is you will delete the table model auto created by sequelize then create or replace the view with the same name. Once this is done you will be able to do a findAll against the model because it will call the view

    The code below keeps auto formating.... but. you get the jest of what i'm doing and i cant paste it without the bullets that are actually */ or the bullets that are actually + " so here you go...

    20200102010201-vwloginslists_create_view_delete_model_table.js

    'use strict';
    const sequelize = require("../database/connection");
    /***
    if you are using views make sure you add the s to the end of the name below in proper grammer format and this way you will
    auto delete the model on sync

    migrations file no mvw just vw name, add the s to the end for proper grammar
    vwLoginsLists
    ex:
    20200102010201-vwloginslists_create_view_delete_model_table.js
    const view_name = 'vwloginslists';

    models file no s, s will automatically be added
    vwLoginsList
    s will automatically be added
    ex:
    vwloginslist.js
    module.exports = sequelize.define("vwloginslist",
    vwloginslist.js

    now on your routes you can use the vw model file to do a findAll
    ex:
    loginsroles-routes.js
    const vwLoginsList = require('../sequelize/models/vwloginslist');
    await vwLoginsList.count()
    return vwLoginsList.findAll(
    whereCondition
    )

    /
    /
    ** this is only used for views if this is not related to a view delete these sections --- start /
    const auto_created_model_table_name = 'vwloginslists';
    /
    ** this is only used for views if this is not related to a view delete these sections --- end */
    const view_name = 'vwloginslists';
    const original_query = "SELECT "

    • " logins.id, logins.name, logins.login, logins.loginenabled, logins.role, "
    • " CASE "
    • " WHEN logins.loginenabled = 0 THEN 'DISABLED' "
    • " WHEN logins.loginenabled = 1 THEN 'ENABLED' "
    • " END AS loginenableddescription, "
    • " loginroles.description AS roledescription "
    • " FROM logins "
    • " LEFT JOIN loginroles "
    • " ON loginroles.id = logins.role "

    const new_query = "SELECT "

    • " logins.id, logins.name, logins.login, logins.loginenabled, logins.role, "
    • " CASE "
    • " WHEN logins.loginenabled = 0 THEN 'DISABLED' "
    • " WHEN logins.loginenabled = 1 THEN 'ENABLED' "
    • " END AS loginenableddescription, "
    • " loginroles.description AS roledescription "
    • " FROM logins "
    • " LEFT JOIN loginroles "
    • " ON loginroles.id = logins.role "

    module.exports = {
    up: function (database, Sequelize) {
    return Promise.all([
    /*** this is only used for views if this is not related to a view delete these sections --- start /
    sequelize.query(DROP TABLE IF EXISTS ${auto_created_model_table_name})
    .then(result => {
    /
    ** this is only used for views if this is not related to a view delete these sections --- end /
    sequelize.query(CREATE OR REPLACE VIEW ${view_name} AS ${new_query})
    .then(result => {
    return result
    })
    /
    ** this is only used for views if this is not related to a view delete these sections --- start /
    })
    /
    ** this is only used for views if this is not related to a view delete these sections --- end */

    ]);
    

    },
    down: function (database, Sequelize) {
    return Promise.all([
    sequelize.query(DROP TABLE IF EXISTS ${auto_created_model_table_name})
    .then(result => {
    sequelize.query(CREATE OR REPLACE VIEW ${view_name} AS ${new_query})
    .then(result => {
    return result
    })
    })
    ]);
    }
    };

  13. KeyOnTech commented on Nov 16, 2020

    @KeyOnTech

    next step go to your route file and here's is how you can now findAll

    const vwLoginsList = require('../sequelize/models/view_model_vwloginslist');
    await vwLoginsList.count(
    whereConditionCount
    )

    or
    return vwLoginsList.findAll(
    whereCondition
    )

    or etc...

  14. KeyOnTech commented on Nov 16, 2020

    @KeyOnTech

    next npm run start to auto create all the models and tables
    stop the node server
    next run sequelize migration to clean up the auto created tables and create your view for you
    npx sequelize db:migrate

    now start your server again npm run start and your findAll should work great

    hope this helps the next person or myself in the future

    Note to future self... your awesome and its all gonna be worth it one day :)

  15. RomanShabanov commented on Dec 7, 2020

    @RomanShabanov

    To whomever is struggling to read @KeyOnTech's tutorials:

    1. Create a model file with the fields you need from your view, in this model there has to be a primary index.
    // sequelize/model/view_model_vwloginslist.js;
    
    const Sequelize = require("sequelize");
    const sequelize = require("../database/connection");
    module.exports = sequelize.define(
      "vwloginslist",
      {
        loginid: {
          field: "id",
          type: Sequelize.INTEGER,
          allowNull: false,
          autoIncrement: true,
          primaryKey: true,
        },
        name: {
          type: Sequelize.STRING(255),
        },
        login: {
          type: Sequelize.STRING(255),
        },
        roledescription: {
          type: Sequelize.STRING(255),
        },
      },
      {
        timestamps: false,
      }
    );
    1. Next make a migration file. The special thing about this file is you will delete the table model auto created by sequelize then create or replace the view with the same name. Once this is done you will be able to do a findAll against the model because it will call the view.
    // 20200102010201-vwloginslists_create_view_delete_model_table.js
    
    "use strict";
    const sequelize = require("../database/connection");
    /***
    if you are using views make sure you add the s to the end of the name below in proper grammer format and this way you will
    auto delete the model on sync
    
    migrations file no mvw just vw name, add the s to the end for proper grammar
    vwLoginsLists
    ex:
    20200102010201-vwloginslists_create_view_delete_model_table.js
    const view_name = 'vwloginslists';
    
    models file no s, s will automatically be added
    vwLoginsList
    s will automatically be added
    ex:
    vwloginslist.js
    module.exports = sequelize.define("vwloginslist",
    vwloginslist.js
    
    now on your routes you can use the vw model file to do a findAll
    ex:
    loginsroles-routes.js
    const vwLoginsList = require('../sequelize/models/vwloginslist');
    await vwLoginsList.count()
    return vwLoginsList.findAll(
    whereCondition
    )
    
    /
    /** this is only used for views if this is not related to a view delete these sections --- start /
    const auto_created_model_table_name = 'vwloginslists';
    /** this is only used for views if this is not related to a view delete these sections --- end */
    
    const view_name = "vwloginslists";
    const original_query = [
      "SELECT ",
      " logins.id, logins.name, logins.login, logins.loginenabled, logins.role, ",
      " CASE ",
      " WHEN logins.loginenabled = 0 THEN 'DISABLED' ",
      " WHEN logins.loginenabled = 1 THEN 'ENABLED' ",
      " END AS loginenableddescription, ",
      " loginroles.description AS roledescription ",
      " FROM logins ",
      " LEFT JOIN loginroles ",
      " ON loginroles.id = logins.role ",
    ].join("");
    
    const new_query = [
      "SELECT ",
      " logins.id, logins.name, logins.login, logins.loginenabled, logins.role, ",
      " CASE ",
      " WHEN logins.loginenabled = 0 THEN 'DISABLED' ",
      " WHEN logins.loginenabled = 1 THEN 'ENABLED' ",
      " END AS loginenableddescription, ",
      " loginroles.description AS roledescription ",
      " FROM logins ",
      " LEFT JOIN loginroles ",
      " ON loginroles.id = logins.role ",
    ].join("");
    
    module.exports = {
      up: function(database, Sequelize) {
        return Promise.all([]);
      },
      down: function(database, Sequelize) {
        return Promise.all([
          sequelize.query(`DROP TABLE IF EXISTS ${auto_created_model_table_name}`).then(result => {
            sequelize.query(`CREATE OR REPLACE VIEW ${view_name} AS ${new_query}`).then(result => {
              return result;
            });
          }),
        ]);
      },
    };
    1. Go to your route file and here's is how you can now findAll
    const vwLoginsList = require("../sequelize/models/view_model_vwloginslist");
    await vwLoginsList.count(whereConditionCount);
    
    // or;
    return vwLoginsList.findAll(whereCondition);
    • next npm run start to auto create all the models and tables
    • stop the node server
    • next run sequelize migration to clean up the auto created tables and create your view for you npx sequelize db:migrate

    now start your server again npm run start and your findAll should work great

    hope this helps the next person or myself in the future

    Note to future self... your awesome and its all gonna be worth it one day :)

  16. KeyOnTech commented on Dec 10, 2020

    @KeyOnTech

    Thank you for rewriting this I had so much trouble posting it wouldn't format right for me and I was super tired after figuring it all out I just wanted to go to bed

    I just wanted to get the message out that it can work

    you showed it like I was trying LoL and great explanation of the steps. Thanks

  17. vaulstein commented on Oct 20, 2021

    @vaulstein
    original_query

    What is the use of original_query here? Don't see it being used.

    Also if I am not using sync() will I have to add the migration?

  18. it-nalon commented on Aug 24, 2022

    @it-nalon

    For those using sequelize-typescript I resolved like this:

    1. create your model as usual, add a primaryKey column and disable createdAt and updatedAt columns:
    import { Column, Model, Table } from 'sequelize-typescript'
    
    @Table({ createdAt: false, updatedAt: false })
    export class MyView extends Model<MyView> {
      @Column({ primaryKey: true, autoIncrement: true })
      id!: number
    
      @Column({ allowNull: false })
      myViewColumn!: number
    
      @Column({ allowNull: false })
      mySecondViewColumn!: string
    }
    1. add the sync() function implementation in your model, doing so will skip the table creation when you run sequelize.sync() during the initialization:
    import { Column, Model, Table } from 'sequelize-typescript'
    import { SyncOptions } from 'sequelize' // <- import SyncOptions
    
    @Table({ createdAt: false, updatedAt: false })
    export class MyView extends Model<MyView> {
      @Column({ primaryKey: true, autoIncrement: true })
      id!: number
    
      @Column({ allowNull: false })
      myViewColumn!: number
    
      @Column({ allowNull: false })
      mySecondViewColumn!: string
    
      static async sync(options: SyncOptions): Promise<any> {
        if (options.force) {
          await this.sequelize?.query(`DROP VIEW IF EXISTS "${this.tableName}"`)
        }
      }
    }
    1. Create the view in your entry point code after the Sequelize initialization:
     ... rest of your entry point
    
      const sequelize = await createSequelizeInstance(configuration)
    
      try {
        await sequelize.authenticate()
        console.log('Connection has been established successfully.')
      } catch (error) {
        console.error('Unable to connect to the database:', error)
        process.exit(-1)
      }
    
      await sequelize.query(getMyViewCreateQuery(MyView.tableName))
    
    ... rest of your entry point
    1. Query your view:
    MyView.findAll({where: { myViewColumn: 1 }})
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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions