myt/myvc-push.js

596 lines
17 KiB
JavaScript
Raw Normal View History

2020-12-02 07:35:26 +00:00
2020-12-04 16:30:26 +00:00
const MyVC = require('./myvc');
2020-12-02 07:35:26 +00:00
const fs = require('fs-extra');
2020-12-04 10:53:11 +00:00
const nodegit = require('nodegit');
2022-02-02 04:05:31 +00:00
const ExporterEngine = require('./lib').ExporterEngine;
2020-12-04 09:15:29 +00:00
/**
* Pushes changes to remote.
*/
2020-12-02 07:35:26 +00:00
class Push {
get usage() {
return {
description: 'Apply changes into database',
params: {
force: 'Answer yes to all questions'
},
operand: 'remote'
};
}
get localOpts() {
2020-12-02 07:35:26 +00:00
return {
alias: {
force: 'f'
},
boolean: [
'force'
]
2020-12-02 07:35:26 +00:00
};
}
async run(myvc, opts) {
const conn = await myvc.dbConnect();
this.conn = conn;
// Obtain exclusive lock
const [[row]] = await conn.query(
`SELECT GET_LOCK('myvc_push', 30) getLock`);
if (!row.getLock) {
let isUsed = 0;
if (row.getLock == 0) {
const [[row]] = await conn.query(
`SELECT IS_USED_LOCK('myvc_push') isUsed`);
isUsed = row.isUsed;
}
throw new Error(`Cannot obtain exclusive lock, used by connection ${isUsed}`);
}
async function releaseLock() {
await conn.query(`DO RELEASE_LOCK('myvc_push')`);
}
try {
await this.push(myvc, opts, conn);
} catch(err) {
try {
await releaseLock();
} catch (e) {
console.error(e);
}
throw err;
}
await releaseLock();
}
async push(myvc, opts, conn) {
2022-02-02 04:05:31 +00:00
const pushConn = await myvc.createConnection();
// Get database version
2020-12-02 07:35:26 +00:00
const version = await myvc.fetchDbVersion() || {};
console.log(
`Database information:`
+ `\n -> Version: ${version.number}`
+ `\n -> Commit: ${version.gitCommit}`
);
if (!version.number)
version.number = String('0').padStart(opts.versionDigits, '0');
2020-12-05 21:50:45 +00:00
if (!/^[0-9]*$/.test(version.number))
throw new Error('Wrong database version');
2020-12-02 07:35:26 +00:00
// Prevent push to production by mistake
2020-12-04 16:30:26 +00:00
if (opts.remote == 'production') {
2020-12-02 07:35:26 +00:00
console.log(
'\n ( ( ) ( ( ) ) '
+ '\n )\\ ))\\ ) ( /( )\\ ) ( ))\\ ) ( /( ( /( '
+ '\n(()/(()/( )\\()|()/( ( )\\ ) /(()/( )\\()) )\\())'
+ '\n /(_))(_)|(_)\\ /(_)) )\\ (((_) ( )(_))(_)|(_)\\ ((_)\\ '
+ '\n(_))(_)) ((_|_))_ _ ((_))\\___(_(_()|__)) ((_) _((_)'
+ '\n| _ \\ _ \\ / _ \\| \\| | | ((/ __|_ _|_ _| / _ \\| \\| |'
+ '\n| _/ /| (_) | |) | |_| || (__ | | | | | (_) | . |'
+ '\n|_| |_|_\\ \\___/|___/ \\___/ \\___| |_| |___| \\___/|_|\\_|'
+ '\n'
);
if (!opts.force) {
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const answer = await new Promise(resolve => {
rl.question('Are you sure? (Default: no) [yes|no] ', resolve);
});
rl.close();
if (answer !== 'yes')
throw new Error('Changes aborted');
}
}
// Apply versions
2020-12-02 07:35:26 +00:00
console.log('Applying versions.');
let nChanges = 0;
let silent = true;
const versionsDir = `${opts.myvcDir}/versions`;
2020-12-02 07:35:26 +00:00
function logVersion(version, name, error) {
console.log('', version.bold, name);
}
function logScript(type, message, error) {
console.log(' ', type.bold, message);
2020-12-02 07:35:26 +00:00
}
function isUndoScript(script) {
return /\.undo\.sql$/.test(script);
}
2020-12-02 07:35:26 +00:00
if (await fs.pathExists(versionsDir)) {
const versionDirs = await fs.readdir(versionsDir);
for (const versionDir of versionDirs) {
if (versionDir == 'README.md')
continue;
const match = versionDir.match(/^([0-9]+)-([a-zA-Z0-9]+)?$/);
2020-12-02 07:35:26 +00:00
if (!match) {
logVersion('[?????]'.yellow, versionDir,
`Wrong directory name.`
);
2020-12-02 07:35:26 +00:00
continue;
}
const versionNumber = match[1];
2020-12-02 07:35:26 +00:00
const versionName = match[2];
if (versionNumber.length != version.number.length) {
logVersion('[*****]'.gray, versionDir,
`Bad version length, should have ${version.number.length} characters.`
);
2020-12-02 07:35:26 +00:00
continue;
}
const scriptsDir = `${versionsDir}/${versionDir}`;
const scripts = await fs.readdir(scriptsDir);
const [versionLog] = await conn.query(
`SELECT file FROM versionLog
WHERE code = ?
AND number = ?
AND errorNumber IS NULL`,
[opts.code, versionNumber]
);
for (const script of scripts)
if (!isUndoScript(script)
&& versionLog.findIndex(x => x.file == script) === -1) {
silent = false;
break;
}
if (silent) continue;
logVersion(`[${versionNumber}]`.cyan, versionName);
2020-12-02 07:35:26 +00:00
for (const script of scripts) {
if (!/^[0-9]{2}-[a-zA-Z0-9_]+(.undo)?\.sql$/.test(script)) {
logScript('[W]'.yellow, script, `Wrong file name.`);
2020-12-02 07:35:26 +00:00
continue;
}
if (isUndoScript(script))
continue;
2020-12-02 07:35:26 +00:00
const [[row]] = await conn.query(
`SELECT errorNumber FROM versionLog
WHERE code = ?
AND number = ?
AND file = ?`,
[
opts.code,
versionNumber,
script
]
);
const apply = !row || row.errorNumber;
const actionMsg = apply ? '[+]'.green : '[I]'.blue;
logScript(actionMsg, script);
if (!apply) continue;
let err;
try {
2022-02-02 04:05:31 +00:00
await this.queryFromFile(pushConn,
`${scriptsDir}/${script}`);
} catch (e) {
err = e;
}
await conn.query(
`INSERT INTO versionLog
SET code = ?,
number = ?,
file = ?,
user = USER(),
updated = NOW(),
errorNumber = ?,
errorMessage = ?
ON DUPLICATE KEY UPDATE
updated = VALUES(updated),
user = VALUES(user),
errorNumber = VALUES(errorNumber),
errorMessage = VALUES(errorMessage)`,
[
opts.code,
versionNumber,
script,
err && err.errno,
err && err.message
]
);
if (err) throw err;
2020-12-02 07:35:26 +00:00
nChanges++;
}
2022-02-07 14:54:24 +00:00
await this.updateVersion('number', versionNumber);
2020-12-02 07:35:26 +00:00
}
}
// Apply routines
2020-12-02 07:35:26 +00:00
console.log('Applying changed routines.');
2022-03-17 21:45:05 +00:00
const gitExists = await fs.pathExists(`${opts.workspace}/.git`);
2020-12-02 07:35:26 +00:00
let nRoutines = 0;
2022-03-17 21:45:05 +00:00
let changes = gitExists
2020-12-02 07:35:26 +00:00
? await myvc.changedRoutines(version.gitCommit)
: await myvc.cachedChanges();
2020-12-04 09:15:29 +00:00
changes = this.parseChanges(changes);
2020-12-02 07:35:26 +00:00
const routines = [];
for (const change of changes)
if (change.isRoutine)
2021-10-27 10:56:25 +00:00
routines.push([
change.schema,
change.name,
change.type.name
]);
2020-12-02 07:35:26 +00:00
if (routines.length) {
await conn.query(
`DROP TEMPORARY TABLE IF EXISTS tProcsPriv`
);
await conn.query(
`CREATE TEMPORARY TABLE tProcsPriv
ENGINE = MEMORY
SELECT * FROM mysql.procs_priv
2021-10-27 10:56:25 +00:00
WHERE (Db, Routine_name, Routine_type) IN (?)`,
2020-12-02 07:35:26 +00:00
[routines]
);
}
2022-02-02 04:05:31 +00:00
const engine = new ExporterEngine(conn, opts.myvcDir);
await engine.init();
async function finalize() {
await engine.saveShaSums();
if (routines.length) {
await conn.query('FLUSH PRIVILEGES');
await conn.query(`DROP TEMPORARY TABLE tProcsPriv`);
}
}
for (const change of changes)
try {
2022-02-02 04:05:31 +00:00
const schema = change.schema;
const name = change.name;
const type = change.type.name.toLowerCase();
const fullPath = `${opts.myvcDir}/routines/${change.path}.sql`;
2020-12-04 09:15:29 +00:00
const exists = await fs.pathExists(fullPath);
2022-02-02 04:05:31 +00:00
let newSql;
if (exists)
newSql = await fs.readFile(fullPath, 'utf8');
const oldSql = await engine.fetchRoutine(type, schema, name);
const isEqual = newSql == oldSql;
let actionMsg;
if ((exists && isEqual) || (!exists && !oldSql))
actionMsg = '[I]'.blue;
else if (exists)
actionMsg = '[+]'.green;
else
actionMsg = '[-]'.red;
2020-12-02 07:35:26 +00:00
const typeMsg = `[${change.type.abbr}]`[change.type.color];
console.log('', actionMsg.bold, typeMsg.bold, change.fullName);
if (!isEqual) {
2022-02-02 04:05:31 +00:00
const scapedSchema = pushConn.escapeId(schema, true);
if (exists) {
if (change.type.name === 'VIEW')
await pushConn.query(`USE ${scapedSchema}`);
await this.multiQuery(pushConn, newSql);
if (change.isRoutine) {
await conn.query(
`INSERT IGNORE INTO mysql.procs_priv
SELECT * FROM tProcsPriv
WHERE Db = ?
AND Routine_name = ?
AND Routine_type = ?`,
[schema, name, change.type.name]
);
}
await engine.fetchShaSum(type, schema, name);
} else {
const escapedName =
scapedSchema + '.' +
2022-02-02 04:05:31 +00:00
pushConn.escapeId(name, true);
const query = `DROP ${change.type.name} IF EXISTS ${escapedName}`;
await pushConn.query(query);
2022-02-02 04:05:31 +00:00
engine.deleteShaSum(type, schema, name);
}
nRoutines++;
2020-12-02 07:35:26 +00:00
}
} catch (err) {
try {
await finalize();
} catch (e) {
2022-03-30 11:20:58 +00:00
console.error(e);
}
throw err;
2020-12-02 07:35:26 +00:00
}
await finalize();
2020-12-02 07:35:26 +00:00
if (nRoutines > 0) {
console.log(` -> ${nRoutines} routines have changed.`);
} else
console.log(` -> No routines changed.`);
2021-10-16 06:44:19 +00:00
2022-03-17 21:45:05 +00:00
if (gitExists) {
const repo = await nodegit.Repository.open(this.opts.workspace);
const head = await repo.getHeadCommit();
2021-10-16 06:44:19 +00:00
2022-03-17 21:45:05 +00:00
if (version.gitCommit !== head.sha())
await this.updateVersion('gitCommit', head.sha());
}
// End
2022-02-02 04:05:31 +00:00
await pushConn.end();
2020-12-02 07:35:26 +00:00
}
2020-12-04 09:15:29 +00:00
parseChanges(changes) {
2020-12-02 07:35:26 +00:00
const routines = [];
2020-12-05 21:50:45 +00:00
if (changes)
for (const change of changes)
routines.push(new Routine(change));
2020-12-02 07:35:26 +00:00
return routines;
}
2022-02-07 14:54:24 +00:00
async updateVersion(column, value) {
2020-12-02 07:35:26 +00:00
column = this.conn.escapeId(column, true);
await this.conn.query(
`INSERT INTO version
SET code = ?,
${column} = ?,
updated = NOW()
ON DUPLICATE KEY UPDATE
${column} = VALUES(${column}),
updated = VALUES(updated)`,
[
2022-02-07 14:54:24 +00:00
this.opts.code,
value
]
);
2020-12-02 07:35:26 +00:00
}
/**
2022-02-02 04:05:31 +00:00
* Executes a multi-query string.
2020-12-02 07:35:26 +00:00
*
2022-02-02 04:05:31 +00:00
* @param {Connection} conn MySQL connection object
* @param {String} sql SQL multi-query string
2020-12-02 07:35:26 +00:00
* @returns {Array<Result>} The resultset
*/
2022-02-02 04:05:31 +00:00
async multiQuery(conn, sql) {
2020-12-02 07:35:26 +00:00
let results = [];
2022-02-02 04:05:31 +00:00
const stmts = this.querySplit(sql);
2020-12-02 07:35:26 +00:00
for (const stmt of stmts)
results = results.concat(await conn.query(stmt));
return results;
}
2022-02-02 04:05:31 +00:00
/**
* Executes an SQL script.
*
* @param {Connection} conn MySQL connection object
* @returns {Array<Result>} The resultset
*/
async queryFromFile(conn, file) {
const sql = await fs.readFile(file, 'utf8');
return await this.multiQuery(conn, sql);
}
2020-12-02 07:35:26 +00:00
/**
* Splits an SQL muti-query into a single-query array, it does an small
* parse to correctly handle the DELIMITER statement.
*
* @param {Array<String>} stmts The splitted SQL statements
*/
querySplit(sql) {
const stmts = [];
let i,
char,
token,
escaped,
stmtStart;
let delimiter = ';';
const delimiterRe = /\s*delimiter\s+(\S+)[^\S\r\n]*(?:\r?\n|\r|$)/yi;
2020-12-02 07:35:26 +00:00
function begins(str) {
let j;
for (j = 0; j < str.length; j++)
if (sql[i + j] != str[j])
return false;
i += j;
return true;
}
for (i = 0; i < sql.length;) {
stmtStart = i;
delimiterRe.lastIndex = i;
const match = sql.match(delimiterRe);
if (match) {
delimiter = match[1];
i += match[0].length;
continue;
}
while (i < sql.length) {
char = sql[i];
if (token) {
if (!escaped && begins(token.end))
token = null;
else {
escaped = !escaped && token.escape(char);
i++;
}
} else {
if (begins(delimiter)) break;
const tok = tokenIndex.get(char);
if (tok && begins(tok.start))
token = tok;
else
i++;
}
}
const len = i - stmtStart - delimiter.length;
const stmt = sql.substr(stmtStart, len);
2020-12-02 07:35:26 +00:00
if (!/^\s*$/.test(stmt))
stmts.push(stmt);
}
2020-12-02 07:35:26 +00:00
return stmts;
}
}
2020-12-04 09:15:29 +00:00
const typeMap = {
events: {
name: 'EVENT',
abbr: 'EVNT',
color: 'cyan'
},
functions: {
name: 'FUNCTION',
abbr: 'FUNC',
color: 'cyan'
},
procedures: {
name: 'PROCEDURE',
abbr: 'PROC',
color: 'yellow'
},
triggers: {
name: 'TRIGGER',
abbr: 'TRIG',
color: 'blue'
},
views: {
name: 'VIEW',
abbr: 'VIEW',
color: 'magenta'
},
};
const routineTypes = new Set([
'FUNCTION',
'PROCEDURE'
]);
2020-12-04 09:15:29 +00:00
class Routine {
constructor(change) {
const path = change.path;
const split = path.split('/');
const schema = split[0];
const type = typeMap[split[1]];
const name = split[2];
Object.assign(this, {
path,
mark: change.mark,
type,
schema,
name,
fullName: `${schema}.${name}`,
2021-10-27 10:56:25 +00:00
isRoutine: routineTypes.has(type.name)
2020-12-04 09:15:29 +00:00
});
}
}
const tokens = {
string: {
start: '\'',
end: '\'',
escape: char => char == '\'' || char == '\\'
},
quotedString: {
start: '"',
end: '"',
escape: char => char == '"' || char == '\\'
},
2020-12-04 09:15:29 +00:00
id: {
start: '`',
end: '`',
escape: char => char == '`'
},
multiComment: {
start: '/*',
end: '*/',
escape: () => false
},
singleComment: {
start: '-- ',
end: '\n',
escape: () => false
}
};
const tokenIndex = new Map();
for (const tokenId in tokens) {
const token = tokens[tokenId];
tokenIndex.set(token.start[0], token);
}
2020-12-02 07:35:26 +00:00
module.exports = Push;
if (require.main === module)
new MyVC().run(Push);