myt/myvc-pull.js

81 lines
2.3 KiB
JavaScript
Raw Normal View History

2020-11-16 13:23:28 +00:00
2020-11-14 01:38:56 +00:00
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`;
const templateDir = `${__dirname}/exporters/${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
module.exports = async function main(workspace, schemas, dbConf) {
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 {
const exportDir = `${workspace}/routines`;
2020-11-14 01:38:56 +00:00
if (fs.existsSync(exportDir))
fs.removeSync(exportDir, {recursive: true});
fs.mkdirSync(exportDir);
2020-11-16 13:23:28 +00:00
for (let schema of schemas) {
2020-11-14 01:38:56 +00:00
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
};