-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdatabase.ts
More file actions
50 lines (44 loc) · 1.63 KB
/
Copy pathdatabase.ts
File metadata and controls
50 lines (44 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import mysqldump from 'mysqldump';
import { getOctoberCmsConfig, octoberDir } from './get-config';
import { execSync } from 'child_process';
import { resolve } from 'path';
import { writeFileSync } from 'fs';
const config = getOctoberCmsConfig();
export const backupDatabase = (dumpToFile: string) => {
if (config.database.default !== 'mysql' || config.database.connections.mysql.driver !== 'mysql') {
throw new Error(
`The backup script supports only mysql as database but you are using "${config.database.default}" in OctoberCMS.`,
);
}
const mysqlConf = config.database.connections.mysql;
return mysqldump({
connection: {
host: mysqlConf.host,
user: mysqlConf.username,
password: mysqlConf.password,
database: mysqlConf.database,
charset: mysqlConf.charset,
port: mysqlConf.port || 3306,
},
dumpToFile,
});
};
export const restoreDatabase = (dir: string) => {
const { username, password, database } = config.database.connections.mysql;
const filePath = resolve(octoberDir, 'backups', dir, 'database.sql');
try {
execSync(`mysql -u ${username} -p${password} ${database} < ${filePath}`, { encoding: 'utf8'});
} catch (error: any) {
if (typeof error?.message === 'string') {
if (error.stdout) {
error.message += `\nstdout: ${error.stdout}`;
}
if (error.stderr) {
error.message += `\nstderr: ${error.stderr}`;
}
}
throw error;
}
// Mark the fresh backup as the current one.
writeFileSync(resolve(octoberDir, 'backups', '.current.database'), dir);
};