在Node环境中导入SQL转储

我想要一个npm脚本来创build/configuration/ etc。 最后导入一个SQL转储。 整个创build,configuration等都在工作,但是,我无法导入工作。 数据永远不会被插入。 这就是我所拥有的(永远不要嵌套的callback,因为他们将变成承诺):

connection.query(`DROP DATABASE IF EXISTS ${config.database};`, err => { connection.query(`CREATE DATABASE IF NOT EXISTS ${config.database};`, err => { connection.query('use DATABASENAME', err => { const sqlDumpPath = path.join(__dirname, 'sql-dump/sql-dump.sql'); connection.query(`SOURCE ${sqlDumpPath}`, err => { connection.end(err => resolve()); }); }) }); }); 

我也试过以下的Sequelize(ORM):

 return new Promise(resolve => { const sqlDumpPath = path.join(__dirname, 'sql-dump/sql-dump.sql'); fs.readFile('./sql/dump.sql', 'utf-8', (err, data) => { sequelize .query(data) .then(resolve) .catch(console.error); }); }); 

以下是我如何使用迁移框架设置我的初始Sequelized导入。 这里有很多,但总之我:

  1. 在migrations文件夹中find最新的sql-dump
  2. fs读取文件
  3. 将文本分割成查询
  4. 检查是否有有效的查询,如果是这样,应用一些清洁,我的数据所需( 见相关的职位 )
  5. 推一个充满了查询的数组 – 我首先通过调用this.down确保数据库是干净的
  6. 运行一切作为承诺( 这里build议)使用mapSeries不是 map

使用sequelize-cli你可以在你的shell中创build一个迁移,通过编写:

 sequelize migration:create 

而且你会自动把文件放在你input下面的代码的地方。 为了执行迁移,你只需写:

 sequelize db:migrate 
 "use strict"; const promise = require("bluebird"); const fs = require("fs"); const path = require("path"); const assert = require("assert"); const db = require("../api/models"); // To be able to run raw queries const debug = require("debug")("my_new_api"); // I needed this in order to get some encoding issues straight const Aring = new RegExp(String.fromCharCode(65533) + "\\" + String.fromCharCode(46) + "{1,3}", "g"); const Auml = new RegExp(String.fromCharCode(65533) + String.fromCharCode(44) + "{1,3}", "g"); const Ouml = new RegExp(String.fromCharCode(65533) + String.fromCharCode(45) + "{1,3}", "g"); module.exports = { up: function (queryInterface, Sequelize) { // The following section allows me to have multiple sql-files and only use the last dump var last_sql; for (let fn of fs.readdirSync(__dirname)){ if (fn.match(/\.sql$/)){ fn = path.join(__dirname, fn); var stats = fs.statSync(fn); if (typeof last_sql === "undefined" || last_sql.stats.mtime < stats.mtime){ last_sql = { filename: fn, stats: stats }; } } } assert(typeof last_sql !== "undefined", "Could not find any valid sql files in " + __dirname); // Split file into queries var queries = fs.readFileSync(last_sql.filename).toString().split(/;\n/); var actions = [{ query: "Running the down section", exec: this.down }]; // Clean database by calling the down first for (let i in queries){ // Skip empty queries and the character set information in the 40101 section // as this would most likely require a multi-query set-up if (queries[i].trim().length == 0 || queries[i].match(new RegExp("/\\*!40101 .+ \\*/"))){ continue; } // The manual fixing of encoding let clean_query = queries[i] .replace(Aring, "Å") .replace(Ouml, "Ö") .replace(Auml, "Ä"); actions.push({ query: clean_query.substring(0, 200), // We save a short section of the query only for debugging purposes exec: () => db.sequelize.query(clean_query) }); } // The Series is important as the order isn't retained with just map return promise.mapSeries(actions, function(item) { debug(item.query); return item.exec(); }, { concurrency: 1 }); }, down: function (queryInterface, Sequelize) { var tables_2_drop = [ "items", "users", "usertypes" ]; var actions = []; for (let tbl of tables_2_drop){ actions.push({ // The created should be created_at exec: () => db.sequelize.query("DROP TABLE IF EXISTS `" + tbl +"`") }); } return promise.map(actions, function(item) { return item.exec(); }, { concurrency: 1 });/**/ } };