在 Node 环境中导入 SQL 转储

Det*_*ned 6 sql node.js sequelize.js

我想要一个 npm 脚本来创建/配置/等。最后导入一个 SQL 转储。整个创建、配置等都在工作,但是,我无法让导入工作。永远不会插入数据。这是我所拥有的(不要介意嵌套的回调,因为它们会变成承诺):

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());
      });
    })
  });
});
Run Code Online (Sandbox Code Playgroud)

我还使用 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);
  });
}); 
Run Code Online (Sandbox Code Playgroud)

Max*_*don 4

以下是我如何使用迁移框架设置初始Sequelized导入。这里发生了很多事情,但简而言之,我:

\n\n
    \n
  1. 在migrations文件夹中找到最新的sql-dump
  2. \n
  3. 使用读取文件fs
  4. \n
  5. 将文本拆分为查询
  6. \n
  7. 检查它是否是有效的查询,如果是,则应用我的数据所需的一些清理(请参阅相关帖子
  8. \n
  9. this.down推送一个充满查询的数组 - 我首先通过调用第一个来确保数据库是干净的
  10. \n
  11. 使用(而不是)将所有内容作为承诺运行(如此处建议的那样mapSeriesmap
  12. \n
\n\n

您可以sequelize-cli在 shell 中通过编写以下内容来创建迁移:

\n\n
sequelize migration:create\n
Run Code Online (Sandbox Code Playgroud)\n\n

您将自动获得在其中输入以下代码的文件。为了执行迁移,您只需编写:

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