You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi, I'm implementing a simple version system, and I have designed a draft EER diagram(part of it):
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.
@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.
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.
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...
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...
'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 "
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
})
})
]);
}
};
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 :)
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";constsequelize=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 willauto delete the model on syncmigrations file no mvw just vw name, add the s to the end for proper grammarvwLoginsListsex:20200102010201-vwloginslists_create_view_delete_model_table.jsconst view_name = 'vwloginslists';models file no s, s will automatically be addedvwLoginsLists will automatically be addedex:vwloginslist.jsmodule.exports = sequelize.define("vwloginslist",vwloginslist.jsnow on your routes you can use the vw model file to do a findAllex:loginsroles-routes.jsconst 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 */constview_name="vwloginslists";constoriginal_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("");constnew_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){returnPromise.all([]);},down: function(database,Sequelize){returnPromise.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=>{returnresult;});}),]);},};
Go to your route file and here's is how you can now findAll
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 :)
Reacted by syouro, Import3r and João Marcos M. A. Mruk
Reacted by KOT, Allan Jiang, Bartłomiej Ryba, Pallav Sharma, Harsh Tenguriya, tehtea, Mike B, Vaulstein Rodrigues, Fabio Zapata, Kripesh Dhakal and 4 more
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
Reacted by Mike B, Jason Woodlee, Kripesh Dhakal, roca and Luke Chen Shui
For those using sequelize-typescript I resolved like this:
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})exportclassMyViewextendsModel<MyView>{
@Column({primaryKey: true,autoIncrement: true})id!: number
@Column({allowNull: false})myViewColumn!: number
@Column({allowNull: false})mySecondViewColumn!: string}
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})exportclassMyViewextendsModel<MyView>{
@Column({primaryKey: true,autoIncrement: true})id!: number
@Column({allowNull: false})myViewColumn!: number
@Column({allowNull: false})mySecondViewColumn!: stringstaticasyncsync(options: SyncOptions): Promise<any>{if(options.force){awaitthis.sequelize?.query(`DROP VIEW IF EXISTS "${this.tableName}"`)}}}
Create the view in your entry point code after the Sequelize initialization:
... restofyourentrypointconstsequelize=awaitcreateSequelizeInstance(configuration)try{awaitsequelize.authenticate()console.log('Connection has been established successfully.')}catch(error){console.error('Unable to connect to the database:',error)process.exit(-1)}awaitsequelize.query(getMyViewCreateQuery(MyView.tableName))...restofyourentrypoint
Query your view:
MyView.findAll({where: {myViewColumn: 1}})
Reacted by Coinhexa, João Marcos M. A. Mruk and LyokoJeremie
Activity
janmeier commentedon Feb 9, 2015
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:
Just remember not to
.syncthe schema_content modelneekey commentedon Feb 9, 2015
@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 useSchemaContent.create( { .. } );and then do something like updating attributes and saving it.janmeier commentedon Feb 9, 2015
I'm not at all familiar with updating a parent table through a view, so can't help you there.
neekey commentedon Feb 9, 2015
So may be the easiest way to do this is just add a
versioncolumn toschema_core, and update it wheneverschema_versionupdates ? Any better idea?neekey commentedon Feb 9, 2015
@janmeier Thank you for your sharing : )
janmeier commentedon Feb 13, 2015
@neekey That sounds reasonable, I dont have any better ideas
drkstr101 commentedon Jan 14, 2018
const MyView = sequelize.define('my_view', {});Attempting to define a model from an existing view throws the above error. Sequelize 4.24.0 & Maria DB 10.2.10
abelosorio commentedon Jul 31, 2018
See #7197 (comment)
mariusa commentedon Aug 25, 2020
Hi, with one model, would it be possible to READ from a view, and have write operations to the table, as usual?
soonsam123 commentedon Aug 28, 2020
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.jsWhen reading data I pass the name of the view as a parameter
When writing data I just leave the default, which is the name of the table
KeyOnTech commentedon Nov 16, 2020
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,
}
);
KeyOnTech commentedon Nov 16, 2020
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 "
const new_query = "SELECT "
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
})
})
]);
}
};
KeyOnTech commentedon Nov 16, 2020
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...
KeyOnTech commentedon Nov 16, 2020
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 :)
RomanShabanov commentedon Dec 7, 2020
To whomever is struggling to read @KeyOnTech's tutorials:
npm run startto auto create all the models and tablesnpx sequelize db:migratenow 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 :)
KeyOnTech commentedon Dec 10, 2020
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
vaulstein commentedon Oct 20, 2021
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?it-nalon commentedon Aug 24, 2022
For those using
sequelize-typescriptI resolved like this:primaryKeycolumn and disablecreatedAtandupdatedAtcolumns:sync()function implementation in your model, doing so will skip the table creation when you runsequelize.sync()during the initialization: