Sequelize Create Database

前端 未结 4 1140
耶瑟儿~
耶瑟儿~ 2021-02-05 01:42

Is there a way to have sequelize create the database I\'m trying to connect to if it doesn\'t exist?

I have a raw MySQL instance and I get this error back:



        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 02:12

    I didn't have this problem with Postgresql but I did have with mysql. Solution was creating a pre-migrate script and trigger it before the sequelize migration, here's part of my package.json :

    "db:pre-migrate": "node scripts/createDB.js",
    "db:migrate": "npm run db:pre-migrate && node_modules/.bin/sequelize db:migrate",
    

    and similarly to what was proposed in some answer here, you could create this createDB.js using modules like node-postgres or mysql(or any other that connects to mysql with raw queries):

    const mysql = require('mysql2/promise');
    
    const dbName = process.env.DB_SCHEMAS || "YOUR_DB";
    
    mysql.createConnection({
        host: process.env.DB_HOST || "127.0.0.1",
        port: process.env.DB_PORT || "3306",
        user     : process.env.DB_USER || "root",
        password : process.env.DB_PASSWORD || "root",
    }).then( connection => {
        connection.query(`CREATE DATABASE IF NOT EXISTS ${dbName};`).then((res) => {
            console.info("Database create or successfully checked");
            process.exit(0);
        })
    })
    

提交回复
热议问题