2020-11-14 01:38:56 +00:00
|
|
|
#!/usr/bin/node
|
|
|
|
const fs = require('fs-extra');
|
|
|
|
const mysql = require('mysql2/promise');
|
|
|
|
const ejs = require('ejs');
|
|
|
|
|
|
|
|
class Exporter {
|
|
|
|
constructor(objectName, callback) {
|
|
|
|
this.objectName = objectName;
|
|
|
|
this.callback = callback;
|
|
|
|
this.dstDir = `${objectName}s`;
|
|
|
|
|
2020-11-15 18:24:25 +00:00
|
|
|
const templateDir = `${__dirname}/templates/${objectName}`;
|
2020-11-14 01:38:56 +00:00
|
|
|
this.query = fs.readFileSync(`${templateDir}.sql`, 'utf8');
|
|
|
|
|
2020-11-15 18:24:25 +00:00
|
|
|
const templateFile = fs.readFileSync(`${templateDir}.ejs`, 'utf8');
|
2020-11-14 01:38:56 +00:00
|
|
|
this.template = ejs.compile(templateFile);
|
|
|
|
|
|
|
|
if (fs.existsSync(`${templateDir}.js`))
|
|
|
|
this.formatter = require(`${templateDir}.js`);
|
|
|
|
}
|
|
|
|
|
|
|
|
async export(conn, exportDir, schema) {
|
2020-11-15 18:24:25 +00:00
|
|
|
const res = await conn.execute(this.query, [schema]);
|
2020-11-14 01:38:56 +00:00
|
|
|
if (!res[0].length) return;
|
|
|
|
|
2020-11-15 18:24:25 +00:00
|
|
|
const routineDir = `${exportDir}/${schema}/${this.dstDir}`;
|
2020-11-14 01:38:56 +00:00
|
|
|
if (!fs.existsSync(routineDir))
|
|
|
|
fs.mkdirSync(routineDir);
|
|
|
|
|
|
|
|
for (let params of res[0]) {
|
|
|
|
if (this.formatter)
|
|
|
|
this.formatter(params, schema)
|
|
|
|
|
|
|
|
params.schema = schema;
|
|
|
|
let sql = this.template(params);
|
|
|
|
fs.writeFileSync(`${routineDir}/${params.name}.sql`, sql);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-15 18:24:25 +00:00
|
|
|
const exporters = [
|
2020-11-14 01:38:56 +00:00
|
|
|
new Exporter('function'),
|
|
|
|
new Exporter('procedure'),
|
|
|
|
new Exporter('view'),
|
|
|
|
new Exporter('trigger'),
|
|
|
|
new Exporter('event')
|
|
|
|
];
|
|
|
|
|
|
|
|
// Exports objects for all schemas
|
|
|
|
|
2020-11-15 18:24:25 +00:00
|
|
|
module.exports = async function main(opts, config, dbConf) {
|
|
|
|
const exportDir = `${opts.workdir}/routines`;
|
2020-11-14 01:38:56 +00:00
|
|
|
|
2020-11-15 18:24:25 +00:00
|
|
|
const conn = await mysql.createConnection(dbConf);
|
2020-11-14 01:38:56 +00:00
|
|
|
conn.queryFromFile = function(file, params) {
|
|
|
|
return this.execute(
|
|
|
|
fs.readFileSync(`${file}.sql`, 'utf8'),
|
|
|
|
params
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
if (fs.existsSync(exportDir))
|
|
|
|
fs.removeSync(exportDir, {recursive: true});
|
|
|
|
|
|
|
|
fs.mkdirSync(exportDir);
|
|
|
|
|
|
|
|
for (let schema of config.structure) {
|
|
|
|
let schemaDir = `${exportDir}/${schema}`;
|
|
|
|
|
|
|
|
if (!fs.existsSync(schemaDir))
|
|
|
|
fs.mkdirSync(schemaDir);
|
|
|
|
|
|
|
|
for (let exporter of exporters)
|
|
|
|
await exporter.export(conn, exportDir, schema);
|
|
|
|
}
|
|
|
|
} catch(err) {
|
|
|
|
console.error(err);
|
|
|
|
} finally {
|
|
|
|
await conn.end();
|
|
|
|
}
|
2020-11-15 18:24:25 +00:00
|
|
|
};
|