7

I have a project which is using Sequelize to manage a set of MySQL databases. Thus far I've been able to run simple queries to create new databases, insert parameters into a table, and select data... however, I have a very long .sql file (+1,700 lines) which when executed will set up a database with a specific schema (ie. tables, views, etc.). The problem is that I can not figure out how to execute a script like this using sequelize. I know the script works on a new database because I can execute the sql file from MySQL Workbench, however I do not know how to execute the script from javascript file using sequelize. I've searched forums but can't seem to find any resources either. Can this be done?

andyopayne
  • 1,348
  • 3
  • 24
  • 49
  • it is a bit tricky see https://stackoverflow.com/a/49741899/5193536 – nbk Aug 25 '20 at 20:28
  • Hmm. thanks for the link. I'll look into this (although it seems like it _should_ be easier than that :) – andyopayne Aug 25 '20 at 20:33
  • i don't think so, all link in SO point that way, this was onöly the "easiest" with out much changes to do, but the qiestion is young – nbk Aug 25 '20 at 20:36

1 Answers1

8

You can run raw query by Sequelize using sequelize.query(sql_string) and you can use fs or fs-extra to read the sql file;

Just mind that you need to set the multiline statement option true in order to run this sql text:

var sql_string = fs.readFileSync('path to file', 'utf8');
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */,
  dialectOptions: {
    multipleStatements: true
  }
});

sequelize.query(sql_string);

Edit 1:

To better understanding of Sequelize class take a look at this

  • Thanks. This looks promising. However, this answer assumes that the database already exists. I'm creating a new database and then want to run the schema script on the newly created database. Do I need to create two instances of 'sequelize' where one creates the new database and then other executes the sql_string sequence you provided? Or is there a cleaner way to do that? – andyopayne Aug 25 '20 at 21:05
  • actually it will run your entire sql file, `database` is just an initial config of Sequelize which you can be skipped and you are able to build every thing from scratch and just make a connection to your Database instance, I will update the answer in few seconds BTW. hope it help you – MohamadrezaRahimianGolkhandani Aug 25 '20 at 21:10