简体   繁体   English

Sequelize Js - 如果不存在则创建新数据库

[英]Sequelize Js - Create new database if its not exists

I am using ( SequelizeJs + NodeJs + Mysql ) in my project我在我的项目中使用( SequelizeJs + NodeJs + Mysql )
Whenever I start the project I want to check the database exists or not and then if it's not there I want to create a new one.每当我开始项目时,我都想检查数据库是否存在,然后如果它不存在,我想创建一个新的。
I tried this:我试过这个:

const mysql        = require('mysql2');

let mysqlCon = mysql.createConnection({
    host    :config.host,
    user    :config.username,
    password:config.password
});

mysqlCon.connect(function(err) {

    //Check Database
    mysqlCon.query('SHOW DATABASES LIKE ' + config.database,
        function(err, result) {
            if(err) {

                //Create new Database
                mysqlCon.query(
                    'CREATE DATABASE ' + config.database,
                    function(err, result) {
                        if(!err){

                            //Sync sequelize js model files
                            models.sequelize.sync().then(() => {
                                console.log('Database connected successfully!');
                            }).catch((err) => {
                                console.log(err, 'Something went wrong with the Database!');
                            });

                        }
                    });
            }
        });
    if(err) {
        console.log(err.message);

    } else {
        console.log('Connected!');
    }
});

I am getting this error:我收到此错误:

sqlMessage: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'pixljobs\' at line 1' } undefined

使用以下命令创建“CREATE DATABASE IF NOT EXISTS DBName;”

Perhaps, a different approach would be to use Sequelize migrations.也许,另一种方法是使用 Sequelize 迁移。

Check out the docs here: https://sequelize.org/master/manual/migrations.html在此处查看文档: https : //sequelize.org/master/manual/migrations.html

Once you have installed sequelize-cli, you init the project, add the migrations to initialise the DB schema (tables, indexes, etc) and then run the command db:create , and after it run db:migrate .安装 sequelize-cli 后,您初始化项目,添加迁移以初始化数据库架构(表、索引等),然后运行命令db:create ,然后运行db:migrate

A migration file consist of two parts: the "up" function, is what you are applying to the DB, and the "down" function, what you need to rollback.迁移文件由两部分组成:“up”功能,是您应用到数据库的功能,以及“down”功能,您需要回滚的功能。 It looks something like this:它看起来像这样:

module.exports = {
  up: (queryInterface, Sequelize) => {
    // logic for transforming into the new state
  },
  down: (queryInterface, Sequelize) => {
    // logic for reverting the changes
  }
}

The advantage of this approach is that you have a way to initialise different environments in an automated, scalable way.这种方法的优点是您可以以自动化、可扩展的方式初始化不同的环境。

Finally, to answer your question, you just need to make sure you run sequelize-cli db:create and sequelize-cli db:migrate on every environment you want to run your project to make sure the DB has the right schema.最后,要回答您的问题,您只需要确保在要运行项目的每个环境中运行sequelize-cli db:createsequelize-cli db:migrate以确保数据库具有正确的架构。 If you are using sequelize-cli > v5.2.0, db:create will create the DB if it does not exist, and will use an existing DB if it was already created (behind the scenes it run the command Kumaresan showed you).如果您使用 sequelize-cli > v5.2.0, db:create将创建不存在的数据库,如果它已经创建,将使用现有的数据库(在幕后运行 Kumaresan 向您展示的命令)。

Hope this helps!希望这可以帮助!

In 2021 Sequelize hasn't implemented db:create for mariadb if you're facing the same issue, the workaround I've found was osifo's answer here: https://stackoverflow.com/a/46694727/11940283 . 2021 年,Sequelize 还没有为 mariadb 实现 db:create,如果您遇到同样的问题,我发现的解决方法是 osifo 的答案: https ://stackoverflow.com/a/46694727/11940283。

In my case I just created another file called create-database.js and I run this file with node create-database.js before running the migrations like: create-node database.js && npx sequelize-cli db:migrate but I think a better solution is to place this code in the first migration file before the actual migration code and just run the migrations normally.就我而言,我刚刚创建了另一个名为 create-database.js 的文件,并在运行迁移之前使用node create-database.js运行此文件,例如: create-node database.js && npx sequelize-cli db:migrate但我认为更好的解决方案是将此代码放在实际迁移代码之前的第一个迁移文件中,然后正常运行迁移。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM