Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creates a full backup of all SQL Server, PostgreSQL and MySQL databases in JScript/JavaScript.
Backup = {
shell: WScript.CreateObject("WScript.Shell"),
base: "C:/BACKUP/",
username: "USERNAME",
hostname: "HOST",
password: "PASSWORD",
type: {
postgreSQL: function(){
var shell = Backup.shell;
var path = "c:/program files/postgresql/9.6/bin/";
var cmd = shell.Exec("\"" + path + "psql.exe\" --command=\"SELECT datname FROM pg_database WHERE datistemplate = false\" --username=" + Backup.username + " --host=" + Backup.hostname + " --no-password postgres");
var input = cmd.StdOut.ReadAll().split(/[\r\n\s]+/).slice(2, -2);
for(var i = input.length; i--; )
shell.Exec("\"" + path + "pg_dump.exe\" --file=" + Backup.base + "postgre-sql/" + input[i] + ".sql --clean --no-owner --host=" + Backup.hostname + " --username=" + Backup.username + " --no-password " + input[i]);
},
sqlServer: function(){
var shell = Backup.shell;
var path = "c:/program files/microsoft sql server/client sdk/odbc/110/tools/binn/";
var sql = "USE MASTER\n\
DECLARE @lvchNomeBanco VARCHAR(200)\n\
DECLARE @lintErros INTEGER\n\
DECLARE @lintCont INTEGER\n\
DECLARE @strSQL VARCHAR(2000)\n\
DECLARE @lvchDiretorio VARCHAR(200)\n\
SET @lvchDiretorio = '" + Backup.base + "sql-server/'\n\
SET @lintCont = 0\n\
SET @lintErros = 0\n\
DECLARE curBancos CURSOR FAST_FORWARD\n\
FOR SELECT NAME FROM SYSDATABASES WHERE DBID > 6\n\
OPEN curBancos\n\
FETCH NEXT FROM curBancos\n\
INTO @lvchNomeBanco\n\
WHILE @@FETCH_STATUS = 0\n\
BEGIN\n\
SET @strSQL = 'BACKUP DATABASE [' + @lvchNomeBanco + '] TO DISK=N''' + @lvchDiretorio + @lvchNomeBanco + '.bak'' WITH INIT , NOUNLOAD , NAME = N''' + @lvchNomeBanco + '.bak'', SKIP , STATS = 10, NOFORMAT'\n\
EXEC(@strSQL)\n\
IF @@ERROR <> 0\n\
SET @lintErros = @lintErros + 1\n\
SET @lintCont = @lintCont + 1\n\
FETCH NEXT FROM curBancos INTO @lvchNomeBanco\n\
END\n\
CLOSE curBancos\n\
DEALLOCATE curBancos\n\
GO\n\
QUIT\n";
var cmd = shell.Exec("\"" + path + "sqlcmd.exe\"");
cmd.StdIn.Write(sql.split("\n").join("\r\n"));
},
mySQL: function(){
var shell = Backup.shell;
var path = "c:/program Files/mysql/mysql server 5.7/bin/";
var cmd = shell.Exec("\"" + path + "mysql.exe\" --execute=\"SHOW DATABASES\" --user=" + Backup.username + " --host=" + Backup.hostname + " --password=" + Backup.password);
var input = cmd.StdOut.ReadAll().split(/[\r\n\s]+/).slice(1);
for(var i = input.length; i--; )
if(!input[i].match(/^(?:mysql|information_schema)$/))
shell.Exec("\"" + path + "mysqldump.exe\" --disable-keys --extended-insert --host=" + Backup.hostname + " --password=" + Backup.password + " --result-file=" + Backup.base + "/mysql/" + input[i] + ".sql --user=" + Backup.username + " " + input[i]);
}
},
run: function(){
for(var n in this.type)
this.type[n]();
}
};
Backup.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment