@datatruck/cli 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/Action/BackupAction.d.ts +1 -0
  2. package/Action/BackupAction.js +4 -1
  3. package/Action/RestoreAction.d.ts +1 -0
  4. package/CHANGELOG.md +20 -0
  5. package/Command/BackupCommand.d.ts +1 -0
  6. package/Command/BackupCommand.js +8 -2
  7. package/Command/BackupSessionsCommand.js +1 -1
  8. package/Command/ConfigCommand.d.ts +1 -0
  9. package/Command/ConfigCommand.js +7 -1
  10. package/Command/InitCommand.js +1 -1
  11. package/Command/PruneCommand.js +2 -2
  12. package/Command/RestoreCommand.d.ts +1 -0
  13. package/Command/RestoreCommand.js +8 -2
  14. package/Command/RestoreSessionsCommand.js +1 -1
  15. package/Command/SnapshotsCommand.js +1 -1
  16. package/SessionDriver/ConsoleSessionDriver.d.ts +6 -2
  17. package/SessionDriver/ConsoleSessionDriver.js +19 -29
  18. package/SessionDriver/SessionDriverAbstract.d.ts +1 -1
  19. package/SessionDriver/SessionDriverAbstract.js +1 -1
  20. package/SessionManager/BackupSessionManager.d.ts +1 -1
  21. package/SessionManager/BackupSessionManager.js +2 -2
  22. package/Task/MysqlDumpTask.d.ts +1 -1
  23. package/Task/MysqlDumpTask.js +4 -2
  24. package/Task/PostgresqlDumpTask.d.ts +1 -1
  25. package/Task/PostgresqlDumpTask.js +2 -4
  26. package/Task/SqlDumpTaskAbstract.d.ts +1 -2
  27. package/Task/SqlDumpTaskAbstract.js +60 -17
  28. package/package.json +1 -1
  29. package/util/cli-util.d.ts +1 -0
  30. package/util/cli-util.js +13 -1
  31. package/util/datatruck/config-util.d.ts +1 -0
  32. package/util/datatruck/config-util.js +3 -0
  33. package/util/date-util.d.ts +4 -0
  34. package/util/date-util.js +17 -1
  35. package/util/process-util.js +2 -2
  36. package/util/string-util.d.ts +1 -0
  37. package/util/string-util.js +21 -1
@@ -10,6 +10,7 @@ export declare type BackupActionOptionsType = {
10
10
  repositoryNames?: string[];
11
11
  repositoryTypes?: string[];
12
12
  packageNames?: string[];
13
+ packageTaskNames?: string[];
13
14
  tags?: string[];
14
15
  dryRun?: boolean;
15
16
  verbose?: boolean;
@@ -21,6 +21,7 @@ class BackupAction {
21
21
  await session.initDrivers();
22
22
  let packages = (0, config_util_1.filterPackages)(this.config, {
23
23
  packageNames: this.options.packageNames,
24
+ packageTaskNames: this.options.packageTaskNames,
24
25
  repositoryNames: this.options.repositoryNames,
25
26
  repositoryTypes: this.options.repositoryTypes,
26
27
  sourceAction: "backup",
@@ -193,7 +194,9 @@ class BackupAction {
193
194
  error: error?.message,
194
195
  });
195
196
  }
196
- await session.endDrivers();
197
+ await session.endDrivers({
198
+ snapshotId: snapshot.id.slice(0, 8),
199
+ });
197
200
  return {
198
201
  total: total,
199
202
  errors: errors,
@@ -10,6 +10,7 @@ export declare type RestoreActionOptionsType = {
10
10
  snapshotId: string;
11
11
  tags?: string[];
12
12
  packageNames?: string[];
13
+ packageTaskNames?: string[];
13
14
  repositoryNames?: string[];
14
15
  repositoryTypes?: string[];
15
16
  verbose?: boolean;
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # @datatruck/cli
2
2
 
3
+ ## 0.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [`3b8d6da`](https://github.com/swordev/datatruck/commit/3b8d6da01495799aceb848a63b35b8c46a7d1b0e) Thanks [@juanrgm](https://github.com/juanrgm)! - Add `--package-task` cli option
8
+
9
+ * [`69b34a0`](https://github.com/swordev/datatruck/commit/69b34a02b9cade48df2b071a92a8f79d5cfec23e) Thanks [@juanrgm](https://github.com/juanrgm)! - Allow restore multiple backups over the same database
10
+
11
+ - [`69caf26`](https://github.com/swordev/datatruck/commit/69caf26881272331bd4c8d7d345b3b85d33e33ac) Thanks [@juanrgm](https://github.com/juanrgm)! - Add cli short option to `--tag`
12
+
13
+ * [`377f0de`](https://github.com/swordev/datatruck/commit/377f0de345c9c8f45c772ac47e4ded81e91725d7) Thanks [@juanrgm](https://github.com/juanrgm)! - Rename cli short option to `-rt`
14
+
15
+ ### Patch Changes
16
+
17
+ - [`c03200a`](https://github.com/swordev/datatruck/commit/c03200a6347d1e9f9fdad86dcb22df30bbefcab4) Thanks [@juanrgm](https://github.com/juanrgm)! - Fix `sql-dump` tasks
18
+
19
+ * [`f56a4bc`](https://github.com/swordev/datatruck/commit/f56a4bcb429a674c13f32de73985cd67eb1acc23) Thanks [@juanrgm](https://github.com/juanrgm)! - Show full error message
20
+
21
+ - [`4324422`](https://github.com/swordev/datatruck/commit/4324422550474619811a8d455af55bc6e3b08aeb) Thanks [@juanrgm](https://github.com/juanrgm)! - Use connection port in `mysql-dump` task
22
+
3
23
  ## 0.6.1
4
24
 
5
25
  ### Patch Changes
@@ -3,6 +3,7 @@ import { If } from "../util/ts-util";
3
3
  import { CommandAbstract } from "./CommandAbstract";
4
4
  export declare type BackupCommandOptionsType<TResolved = false> = {
5
5
  package?: If<TResolved, string[]>;
6
+ packageTask?: If<TResolved, string[]>;
6
7
  repository?: If<TResolved, string[]>;
7
8
  repositoryType?: If<TResolved, RepositoryConfigType["type"][]>;
8
9
  tag?: If<TResolved, string[]>;
@@ -21,6 +21,11 @@ class BackupCommand extends CommandAbstract_1.CommandAbstract {
21
21
  option: "-p,--package <values>",
22
22
  parser: string_util_1.parseStringList,
23
23
  },
24
+ packageTask: {
25
+ description: "Package task names",
26
+ option: "-pt,--package-task <values>",
27
+ parser: string_util_1.parseStringList,
28
+ },
24
29
  repository: {
25
30
  description: "Repository names",
26
31
  option: "-r,--repository <values>",
@@ -28,12 +33,12 @@ class BackupCommand extends CommandAbstract_1.CommandAbstract {
28
33
  },
29
34
  repositoryType: {
30
35
  description: "Repository types",
31
- option: "-t,--repository-type <values>",
36
+ option: "-rt,--repository-type <values>",
32
37
  parser: (v) => (0, string_util_1.parseStringList)(v),
33
38
  },
34
39
  tag: {
35
40
  description: "Tags",
36
- option: "--tag <values>",
41
+ option: "-t,--tag <values>",
37
42
  parser: string_util_1.parseStringList,
38
43
  },
39
44
  date: {
@@ -47,6 +52,7 @@ class BackupCommand extends CommandAbstract_1.CommandAbstract {
47
52
  const config = await ConfigAction_1.ConfigAction.fromGlobalOptions(this.globalOptions);
48
53
  const backup = new BackupAction_1.BackupAction(config, {
49
54
  packageNames: this.options.package,
55
+ packageTaskNames: this.options.packageTask,
50
56
  repositoryNames: this.options.repository,
51
57
  repositoryTypes: this.options.repositoryType,
52
58
  tags: this.options.tag,
@@ -24,7 +24,7 @@ class BackupSessionsCommand extends CommandAbstract_1.CommandAbstract {
24
24
  },
25
25
  tag: {
26
26
  description: "Tags",
27
- option: "--tag <values>",
27
+ option: "-t,--tag <values>",
28
28
  parser: string_util_1.parseStringList,
29
29
  },
30
30
  limit: {
@@ -3,6 +3,7 @@ import { If } from "../util/ts-util";
3
3
  import { CommandAbstract } from "./CommandAbstract";
4
4
  export declare type ConfigCommandOptionsType<TResolved = false> = {
5
5
  package?: If<TResolved, string[]>;
6
+ packageTask?: If<TResolved, string[]>;
6
7
  repository?: If<TResolved, string[]>;
7
8
  repositoryType?: If<TResolved, RepositoryConfigType["type"][]>;
8
9
  };
@@ -14,6 +14,11 @@ class ConfigCommand extends CommandAbstract_1.CommandAbstract {
14
14
  option: "-p,--package <values>",
15
15
  parser: string_util_1.parseStringList,
16
16
  },
17
+ packageTask: {
18
+ description: "Package task names",
19
+ option: "-pt,--package-task <values>",
20
+ parser: string_util_1.parseStringList,
21
+ },
17
22
  repository: {
18
23
  description: "Repository names",
19
24
  option: "-r,--repository <values>",
@@ -21,7 +26,7 @@ class ConfigCommand extends CommandAbstract_1.CommandAbstract {
21
26
  },
22
27
  repositoryType: {
23
28
  description: "Repository types",
24
- option: "-t,--repository-type <values>",
29
+ option: "-rt,--repository-type <values>",
25
30
  parser: (v) => (0, string_util_1.parseStringList)(v),
26
31
  },
27
32
  });
@@ -30,6 +35,7 @@ class ConfigCommand extends CommandAbstract_1.CommandAbstract {
30
35
  const config = await ConfigAction_1.ConfigAction.fromGlobalOptions(this.globalOptions);
31
36
  const packages = (0, config_util_1.filterPackages)(config, {
32
37
  packageNames: this.options.package,
38
+ packageTaskNames: this.options.packageTask,
33
39
  repositoryNames: this.options.repository,
34
40
  repositoryTypes: this.options.repositoryType,
35
41
  });
@@ -18,7 +18,7 @@ class InitCommand extends CommandAbstract_1.CommandAbstract {
18
18
  },
19
19
  repositoryType: {
20
20
  description: "Repository types",
21
- option: "-t,--repository-type <values>",
21
+ option: "-rt,--repository-type <values>",
22
22
  parser: (v) => (0, string_util_1.parseStringList)(v),
23
23
  },
24
24
  });
@@ -81,12 +81,12 @@ class PruneCommand extends CommandAbstract_1.CommandAbstract {
81
81
  },
82
82
  repositoryType: {
83
83
  description: "Repository types",
84
- option: "-t,--repositoryType <values>",
84
+ option: "-rt,--repository-type <values>",
85
85
  parser: (v) => (0, string_util_1.parseStringList)(v),
86
86
  },
87
87
  tag: {
88
88
  description: "Tags",
89
- option: "--tag <values>",
89
+ option: "-t,--tag <values>",
90
90
  parser: string_util_1.parseStringList,
91
91
  },
92
92
  showAll: {
@@ -4,6 +4,7 @@ import { CommandAbstract } from "./CommandAbstract";
4
4
  export declare type RestoreCommandOptionsType<TResolved = false> = {
5
5
  id: string;
6
6
  package?: If<TResolved, string[]>;
7
+ packageTask?: If<TResolved, string[]>;
7
8
  repository?: If<TResolved, string[]>;
8
9
  repositoryType?: If<TResolved, RepositoryConfigType["type"][]>;
9
10
  tag?: If<TResolved, string[]>;
@@ -21,6 +21,11 @@ class RestoreCommand extends CommandAbstract_1.CommandAbstract {
21
21
  option: "-p,--package <values>",
22
22
  parser: string_util_1.parseStringList,
23
23
  },
24
+ packageTask: {
25
+ description: "Package task names",
26
+ option: "-pt,--package-task <values>",
27
+ parser: string_util_1.parseStringList,
28
+ },
24
29
  repository: {
25
30
  description: "Repository names",
26
31
  option: "-r,--repository <values>",
@@ -28,12 +33,12 @@ class RestoreCommand extends CommandAbstract_1.CommandAbstract {
28
33
  },
29
34
  repositoryType: {
30
35
  description: "Repository types",
31
- option: "-t,--repository-type <values>",
36
+ option: "-rt,--repository-type <values>",
32
37
  parser: (v) => (0, string_util_1.parseStringList)(v),
33
38
  },
34
39
  tag: {
35
40
  description: "Tags",
36
- option: "--tag <values>",
41
+ option: "-t,--tag <values>",
37
42
  parser: string_util_1.parseStringList,
38
43
  },
39
44
  });
@@ -44,6 +49,7 @@ class RestoreCommand extends CommandAbstract_1.CommandAbstract {
44
49
  const restore = new RestoreAction_1.RestoreAction(config, {
45
50
  snapshotId: this.options.id,
46
51
  packageNames: this.options.package,
52
+ packageTaskNames: this.options.packageTask,
47
53
  repositoryNames: this.options.repository,
48
54
  repositoryTypes: this.options.repositoryType,
49
55
  tags: this.options.tag,
@@ -24,7 +24,7 @@ class RestoreSessionsCommand extends CommandAbstract_1.CommandAbstract {
24
24
  },
25
25
  tag: {
26
26
  description: "Tags",
27
- option: "--tag <values>",
27
+ option: "-t,--tag <values>",
28
28
  parser: string_util_1.parseStringList,
29
29
  },
30
30
  limit: {
@@ -76,7 +76,7 @@ class SnapshotsCommand extends CommandAbstract_1.CommandAbstract {
76
76
  },
77
77
  tag: {
78
78
  description: "Tags",
79
- option: "--tag <values>",
79
+ option: "-t,--tag <values>",
80
80
  parser: string_util_1.parseStringList,
81
81
  },
82
82
  });
@@ -26,10 +26,14 @@ export declare class ConsoleSessionDriver extends SessionDriverAbstract {
26
26
  protected rendering?: boolean;
27
27
  protected lastColumns?: number;
28
28
  protected startTime: number;
29
+ protected chron: {
30
+ start: () => number;
31
+ elapsed: (formatted?: boolean | undefined) => string | number;
32
+ };
29
33
  onInit(): Promise<void>;
30
- onEnd(): Promise<void>;
34
+ onEnd(data?: Record<string, any>): Promise<void>;
31
35
  onRead(): Promise<ReadResultType[]>;
32
- protected printMessage(message: MessageType): void;
36
+ protected printMessage(message: MessageType, endMessage: boolean): void;
33
37
  protected renderSpinner(text: string): string;
34
38
  protected renderMessage(message: MessageType): string;
35
39
  onWrite(data: WriteDataType): Promise<void>;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ConsoleSessionDriver = void 0;
4
4
  const AppError_1 = require("../Error/AppError");
5
5
  const cli_util_1 = require("../util/cli-util");
6
+ const date_util_1 = require("../util/date-util");
6
7
  const SessionDriverAbstract_1 = require("./SessionDriverAbstract");
7
8
  const chalk_1 = require("chalk");
8
9
  const sep = (0, chalk_1.grey)(`|`);
@@ -12,42 +13,28 @@ class ConsoleSessionDriver extends SessionDriverAbstract_1.SessionDriverAbstract
12
13
  constructor() {
13
14
  super(...arguments);
14
15
  this.prints = 0;
16
+ this.chron = (0, date_util_1.createChron)();
15
17
  }
16
18
  async onInit() {
17
- this.startTime = Date.now();
19
+ this.chron.start();
18
20
  this.renderInterval = setInterval(() => {
19
21
  if (this.lastMessage)
20
- this.printMessage(this.lastMessage);
22
+ this.printMessage(this.lastMessage, false);
21
23
  }, 100);
22
24
  }
23
- async onEnd() {
25
+ async onEnd(data) {
24
26
  clearInterval(this.renderInterval);
25
27
  if (!this.options.verbose)
26
28
  process.stdout.write(cli_util_1.showCursorCommand);
27
- const ellapsed = (Date.now() - this.startTime) / 1000;
28
- let ellapsedUnit;
29
- let ellapsedValue;
30
- if (ellapsed > 60 * 60) {
31
- ellapsedValue = ellapsed / 60 / 60;
32
- ellapsedUnit = `hour`;
33
- }
34
- else if (ellapsed > 60) {
35
- ellapsedValue = ellapsed / 60;
36
- ellapsedUnit = `minute`;
37
- }
38
- else {
39
- ellapsedValue = ellapsed;
40
- ellapsedUnit = `second`;
41
- }
42
- if (ellapsedValue !== 1)
43
- ellapsedUnit += `s`;
44
- const message = `Completed in ${ellapsedValue.toFixed(2)} ${ellapsedUnit}`;
45
- console.info(`\n${(0, chalk_1.grey)(message)}`);
29
+ (0, cli_util_1.logVars)({
30
+ ...data,
31
+ elapsed: this.chron.elapsed(true),
32
+ });
46
33
  }
47
34
  async onRead() {
48
35
  throw new AppError_1.AppError("Method not implemented");
49
36
  }
50
- printMessage(message) {
37
+ printMessage(message, endMessage) {
51
38
  const text = this.renderMessage(message);
52
39
  if (this.options.verbose && this.lastMessageText === text) {
53
40
  return;
@@ -58,8 +45,10 @@ class ConsoleSessionDriver extends SessionDriverAbstract_1.SessionDriverAbstract
58
45
  else {
59
46
  const columns = process.stdout.columns;
60
47
  const line = this.renderSpinner(text);
61
- const [truncatedLine, truncted] = (0, cli_util_1.truncate)(line, columns);
62
- if (this.lastColumns && columns !== this.lastColumns && truncted)
48
+ const [truncatedLine, truncated] = endMessage
49
+ ? [line, false]
50
+ : (0, cli_util_1.truncate)(line, columns);
51
+ if (this.lastColumns && columns !== this.lastColumns && truncated)
63
52
  process.stdout.write(`${cli_util_1.clearCommand}\n`);
64
53
  process.stdout.write(`${cli_util_1.clearCommand}${truncatedLine}${cli_util_1.hideCursorCommand}`);
65
54
  this.lastColumns = columns;
@@ -170,10 +159,11 @@ class ConsoleSessionDriver extends SessionDriverAbstract_1.SessionDriverAbstract
170
159
  if (isHeader && data.action === SessionDriverAbstract_1.ActionEnum.End) {
171
160
  return;
172
161
  }
173
- this.printMessage(message);
174
- if (!this.options.verbose)
175
- if (!hasProgress || data.action === SessionDriverAbstract_1.ActionEnum.End || isHeader)
176
- process.stdout.write("\n");
162
+ const endMessage = !this.options.verbose &&
163
+ (!hasProgress || data.action === SessionDriverAbstract_1.ActionEnum.End || isHeader);
164
+ this.printMessage(message, endMessage);
165
+ if (endMessage)
166
+ process.stdout.write("\n");
177
167
  }
178
168
  }
179
169
  exports.ConsoleSessionDriver = ConsoleSessionDriver;
@@ -73,6 +73,6 @@ export declare abstract class SessionDriverAbstract {
73
73
  });
74
74
  onInit(): Promise<void>;
75
75
  abstract onWrite(data: WriteDataType): Promise<void>;
76
- onEnd(): Promise<void>;
76
+ onEnd(data?: Record<string, any>): Promise<void>;
77
77
  abstract onRead(data: ReadDataType, entity: EntityEnum): Promise<ReadResultType[]>;
78
78
  }
@@ -22,6 +22,6 @@ class SessionDriverAbstract {
22
22
  this.options = options;
23
23
  }
24
24
  async onInit() { }
25
- async onEnd() { }
25
+ async onEnd(data) { }
26
26
  }
27
27
  exports.SessionDriverAbstract = SessionDriverAbstract;
@@ -27,7 +27,7 @@ export declare class BackupSessionManager {
27
27
  repositoryName: string;
28
28
  }): number;
29
29
  initDrivers(): Promise<void>;
30
- endDrivers(): Promise<void>;
30
+ endDrivers(data?: Record<string, any>): Promise<void>;
31
31
  protected alter(data: WriteDataType): Promise<number>;
32
32
  readAll(options: BackupSessionsActionOptionsType): Promise<import("../SessionDriver/SessionDriverAbstract").ReadResultType[]>;
33
33
  init(input: Pick<BackupSessionEntity, "packageName" | "snapshotId" | "tags">): Promise<number>;
@@ -27,10 +27,10 @@ class BackupSessionManager {
27
27
  await driver.onInit();
28
28
  }
29
29
  }
30
- async endDrivers() {
30
+ async endDrivers(data) {
31
31
  const drivers = [this.options.driver, ...(this.options.altDrivers ?? [])];
32
32
  for (const driver of drivers) {
33
- await driver.onEnd();
33
+ await driver.onEnd(data);
34
34
  }
35
35
  }
36
36
  async alter(data) {
@@ -8,7 +8,7 @@ export declare class MysqlDumpTask extends SqlDumpTaskAbstract<MysqlDumpTaskConf
8
8
  onDatabaseIsEmpty(name: string): Promise<boolean>;
9
9
  onCreateDatabase(database: TargetDatabaseType): Promise<void>;
10
10
  onExecQuery(query: string): Promise<import("../util/process-util").ExecResultType>;
11
- onFetchTableNames(): Promise<string[]>;
11
+ onFetchTableNames(database: string): Promise<string[]>;
12
12
  onExport(tableNames: string[], output: string): Promise<void>;
13
13
  onImport(path: string, database: string): Promise<void>;
14
14
  }
@@ -17,6 +17,7 @@ class MysqlDumpTask extends SqlDumpTaskAbstract_1.SqlDumpTaskAbstract {
17
17
  const password = await this.fetchPassword();
18
18
  return [
19
19
  `--host=${this.config.hostname}`,
20
+ ...(this.config.port ? [`--port=${this.config.port}`] : []),
20
21
  `--user=${this.config.username}`,
21
22
  `--password=${password ?? ""}`,
22
23
  ...(database && this.config.database ? [this.config.database] : []),
@@ -57,14 +58,14 @@ class MysqlDumpTask extends SqlDumpTaskAbstract_1.SqlDumpTaskAbstract {
57
58
  },
58
59
  });
59
60
  }
60
- async onFetchTableNames() {
61
+ async onFetchTableNames(database) {
61
62
  return await this.fetchValues(`
62
63
  SELECT
63
64
  table_name
64
65
  FROM
65
66
  information_schema.tables
66
67
  WHERE
67
- table_schema = '${this.config.database}'
68
+ table_schema = '${database}'
68
69
  `);
69
70
  }
70
71
  async onExport(tableNames, output) {
@@ -77,6 +78,7 @@ class MysqlDumpTask extends SqlDumpTaskAbstract_1.SqlDumpTaskAbstract {
77
78
  await (0, process_util_1.exec)("mysqldump", [
78
79
  ...(await this.buildConnectionArgs()),
79
80
  "--lock-tables=false",
81
+ "--skip-add-drop-table=false",
80
82
  ...tableNames,
81
83
  ], null, {
82
84
  pipe: { stream: stream },
@@ -8,7 +8,7 @@ export declare class PostgresqlDumpTask extends SqlDumpTaskAbstract<PostgresqlDu
8
8
  onDatabaseIsEmpty(name: string): Promise<boolean>;
9
9
  onCreateDatabase(database: TargetDatabaseType): Promise<void>;
10
10
  onExecQuery(query: string): Promise<import("../util/process-util").ExecResultType>;
11
- onFetchTableNames(): Promise<string[]>;
11
+ onFetchTableNames(database: string): Promise<string[]>;
12
12
  onExport(tableNames: string[], output: string): Promise<void>;
13
13
  onImport(path: string, database: string): Promise<void>;
14
14
  }
@@ -60,14 +60,14 @@ class PostgresqlDumpTask extends SqlDumpTaskAbstract_1.SqlDumpTaskAbstract {
60
60
  },
61
61
  });
62
62
  }
63
- async onFetchTableNames() {
63
+ async onFetchTableNames(database) {
64
64
  return await this.fetchValues(`
65
65
  SELECT
66
66
  CONCAT(table_schema, '.', table_name)
67
67
  FROM
68
68
  information_schema.tables
69
69
  WHERE
70
- table_catalog = '${this.config.database}' AND
70
+ table_catalog = '${database}' AND
71
71
  table_schema NOT IN ('pg_catalog', 'information_schema')
72
72
  `);
73
73
  }
@@ -80,8 +80,6 @@ class PostgresqlDumpTask extends SqlDumpTaskAbstract_1.SqlDumpTaskAbstract {
80
80
  }),
81
81
  (0, process_util_1.exec)("pg_dump", [
82
82
  ...(await this.buildConnectionArgs()),
83
- "--clean",
84
- "--if-exists",
85
83
  ...(tableNames?.flatMap((v) => ["-t", v]) ?? []),
86
84
  ], null, {
87
85
  pipe: { stream: stream },
@@ -26,11 +26,10 @@ export declare abstract class SqlDumpTaskAbstract<TConfig extends SqlDumpTaskCon
26
26
  fetchValues(query: string): Promise<string[]>;
27
27
  abstract onCreateDatabase(database: TargetDatabaseType): Promise<void>;
28
28
  abstract onDatabaseIsEmpty(databaseName: string): Promise<boolean>;
29
- abstract onFetchTableNames(): Promise<string[]>;
29
+ abstract onFetchTableNames(database: string): Promise<string[]>;
30
30
  abstract onExecQuery(query: string): ReturnType<typeof exec>;
31
31
  abstract onExport(tableNames: string[], output: string): Promise<void>;
32
32
  abstract onImport(path: string, database: string): Promise<void>;
33
- fetchTableNames(): Promise<string[]>;
34
33
  onBackup(data: BackupDataType): Promise<void>;
35
34
  onRestore(data: RestoreDataType): Promise<void>;
36
35
  }
@@ -49,6 +49,39 @@ exports.sqlDumpTaskDefinition = {
49
49
  oneFileByTable: { type: "boolean" },
50
50
  },
51
51
  };
52
+ function serializeSqlFile(input) {
53
+ if (input.database && input.table) {
54
+ return `${input.database}.${input.table}.table.sql`;
55
+ }
56
+ else if (input.database && !input.table) {
57
+ return `${input.database}.database.sql`;
58
+ }
59
+ else if (!input.database && input.table) {
60
+ return `${input.table}.table.sql`;
61
+ }
62
+ else {
63
+ throw new AppError_1.AppError(`Invalid sql file input: ${JSON.stringify(input)}`);
64
+ }
65
+ }
66
+ function parseSqlFile(fileName) {
67
+ if (!fileName.endsWith(".sql"))
68
+ return;
69
+ const regex = /^(.+)\.(table|database)\.sql$/;
70
+ const matches = regex.exec(fileName);
71
+ if (!matches)
72
+ return { fileName };
73
+ const [, name, type] = matches;
74
+ const lastName = name.split(".").pop();
75
+ if (type === "table") {
76
+ return { fileName, table: lastName };
77
+ }
78
+ else if (type === "database") {
79
+ return { fileName, database: lastName };
80
+ }
81
+ else {
82
+ throw new Error(`Invalid sql file type: ${type}`);
83
+ }
84
+ }
52
85
  class SqlDumpTaskAbstract extends TaskAbstract_1.TaskAbstract {
53
86
  async fetchPassword() {
54
87
  if (typeof this.config.password === "string")
@@ -66,26 +99,23 @@ class SqlDumpTaskAbstract extends TaskAbstract_1.TaskAbstract {
66
99
  return result;
67
100
  }, []);
68
101
  }
69
- async fetchTableNames() {
70
- const tableNames = await this.onFetchTableNames();
102
+ async onBackup(data) {
103
+ this.verbose = data.options.verbose;
71
104
  const config = this.config;
72
- return tableNames.filter((tableName) => {
105
+ const outputPath = data.package.path;
106
+ const allTableNames = await this.onFetchTableNames(this.config.database);
107
+ const tableNames = allTableNames.filter((tableName) => {
73
108
  if (config.includeTables && !(0, micromatch_1.isMatch)(tableName, config.includeTables))
74
109
  return false;
75
110
  if (config.excludeTables && (0, micromatch_1.isMatch)(tableName, config.excludeTables))
76
111
  return false;
77
112
  return true;
78
113
  });
79
- }
80
- async onBackup(data) {
81
- this.verbose = data.options.verbose;
82
- const outputPath = data.package.path;
83
- const tableNames = await this.fetchTableNames();
84
114
  (0, assert_1.ok)(typeof outputPath === "string");
85
115
  if (!(await (0, fs_util_1.checkDir)(outputPath)))
86
116
  await (0, promises_1.mkdir)(outputPath, { recursive: true });
87
117
  if (!this.config.oneFileByTable) {
88
- const outPath = (0, path_1.join)(outputPath, this.config.database) + ".database.sql";
118
+ const outPath = (0, path_1.join)(outputPath, serializeSqlFile({ database: this.config.database }));
89
119
  await this.onExport(tableNames, outPath);
90
120
  }
91
121
  else {
@@ -98,7 +128,7 @@ class SqlDumpTaskAbstract extends TaskAbstract_1.TaskAbstract {
98
128
  step: tableName,
99
129
  });
100
130
  current++;
101
- const outPath = (0, path_1.join)(outputPath, tableName) + ".table.sql";
131
+ const outPath = (0, path_1.join)(outputPath, serializeSqlFile({ table: tableName }));
102
132
  await this.onExport([tableName], outPath);
103
133
  }
104
134
  }
@@ -125,20 +155,33 @@ class SqlDumpTaskAbstract extends TaskAbstract_1.TaskAbstract {
125
155
  database: database.name,
126
156
  });
127
157
  }
128
- if (!(await this.onDatabaseIsEmpty(database.name)))
158
+ const items = (await (0, promises_1.readdir)(restorePath))
159
+ .map(parseSqlFile)
160
+ .filter((v) => !!v);
161
+ // Database check
162
+ const databaseItems = items.filter((v) => v.database);
163
+ if (databaseItems.length && !(await this.onDatabaseIsEmpty(database.name)))
129
164
  throw new AppError_1.AppError(`Target database is not empty: ${database.name}`);
165
+ // Table check
166
+ const restoreTables = items
167
+ .filter((v) => v.table)
168
+ .map((v) => v.table);
169
+ const serverTables = await this.onFetchTableNames(database.name);
170
+ const errorTables = restoreTables.filter((v) => serverTables.includes(v));
171
+ if (errorTables.length) {
172
+ throw new AppError_1.AppError(`Target table already exists: ${errorTables.join(", ")}`);
173
+ }
130
174
  await this.onCreateDatabase(database);
131
175
  if (this.verbose)
132
176
  (0, cli_util_1.logExec)("readdir", [restorePath]);
133
- const files = (await (0, promises_1.readdir)(restorePath)).filter((name) => /\.sql$/i.test(name));
134
177
  let current = 0;
135
- for (const file of files) {
136
- const path = (0, path_1.join)(restorePath, file);
178
+ for (const item of items) {
179
+ const path = (0, path_1.join)(restorePath, item.fileName);
137
180
  data.onProgress({
138
- total: files.length,
181
+ total: items.length,
139
182
  current: current,
140
- percent: (0, math_util_1.progressPercent)(files.length, current),
141
- step: file,
183
+ percent: (0, math_util_1.progressPercent)(items.length, current),
184
+ step: item.fileName,
142
185
  });
143
186
  current++;
144
187
  await this.onImport(path, database.name);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@datatruck/cli",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "dependencies": {
5
5
  "ajv": "^8.11.0",
6
6
  "async": "^3.2.4",
@@ -6,6 +6,7 @@ export declare const clearCommand = "\r\u001B[K";
6
6
  export declare const hideCursorCommand = "\u001B[?25l";
7
7
  export declare function renderSpinner(counter: number): string;
8
8
  export declare function renderProgressBar(progress: number, size?: number): string;
9
+ export declare function logVars(data: Record<string, any>): void;
9
10
  export declare function logExec(command: string, argv?: string[], env?: NodeJS.ProcessEnv, logToStderr?: boolean): void;
10
11
  export declare function resultColumn(error: Error | null | string, state?: "started" | "ended"): "❌" | " ? " | "✅";
11
12
  export declare function errorColumn(error: Error | null | string, verbose: number): string;
package/util/cli-util.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.confirm = exports.truncate = exports.parseOptions = exports.errorColumn = exports.resultColumn = exports.logExec = exports.renderProgressBar = exports.renderSpinner = exports.hideCursorCommand = exports.clearCommand = exports.showCursorCommand = exports.spinnerChars = exports.clearLastLine = void 0;
6
+ exports.confirm = exports.truncate = exports.parseOptions = exports.errorColumn = exports.resultColumn = exports.logExec = exports.logVars = exports.renderProgressBar = exports.renderSpinner = exports.hideCursorCommand = exports.clearCommand = exports.showCursorCommand = exports.spinnerChars = exports.clearLastLine = void 0;
7
7
  const chalk_1 = __importDefault(require("chalk"));
8
8
  const chalk_2 = require("chalk");
9
9
  const readline_1 = require("readline");
@@ -28,6 +28,18 @@ function renderProgressBar(progress, size = 10) {
28
28
  return completeChar.repeat(completedSize) + incompleteChar.repeat(restSize);
29
29
  }
30
30
  exports.renderProgressBar = renderProgressBar;
31
+ function logVars(data) {
32
+ let first = true;
33
+ for (const key in data) {
34
+ if (first) {
35
+ console.log();
36
+ first = false;
37
+ }
38
+ const value = data[key];
39
+ console.log(`${chalk_1.default.cyan(key)}${chalk_1.default.grey(":")} ${chalk_1.default.white(value ?? "")}`);
40
+ }
41
+ }
42
+ exports.logVars = logVars;
31
43
  function logExec(command, argv = [], env, logToStderr) {
32
44
  const envText = env
33
45
  ? Object.keys(env)
@@ -5,6 +5,7 @@ export declare function findRepositoryOrFail(config: ConfigType, repositoryName:
5
5
  export declare function filterRepository(repository: RepositoryConfigType, action?: RepositoryConfigEnabledActionType): boolean;
6
6
  export declare function filterPackages(config: ConfigType, options: {
7
7
  packageNames?: string[];
8
+ packageTaskNames?: string[];
8
9
  repositoryNames?: string[];
9
10
  repositoryTypes?: string[];
10
11
  sourceAction?: RepositoryConfigEnabledActionType;
@@ -22,6 +22,7 @@ function filterRepository(repository, action) {
22
22
  exports.filterRepository = filterRepository;
23
23
  function filterPackages(config, options) {
24
24
  const packagePatterns = (0, string_util_1.makePathPatterns)(options.packageNames);
25
+ const taskNamePatterns = (0, string_util_1.makePathPatterns)(options.packageTaskNames);
25
26
  return config.packages
26
27
  .map((pkg) => {
27
28
  pkg = Object.assign({}, pkg);
@@ -37,6 +38,8 @@ function filterPackages(config, options) {
37
38
  return pkg;
38
39
  })
39
40
  .filter((pkg) => {
41
+ if (taskNamePatterns && !(0, micromatch_1.isMatch)(pkg.task?.name ?? "", taskNamePatterns))
42
+ return false;
40
43
  return ((typeof pkg.enabled !== "boolean" || pkg.enabled) &&
41
44
  !!pkg.repositoryNames?.length &&
42
45
  (!packagePatterns || (0, micromatch_1.isMatch)(pkg.name, packagePatterns)));
@@ -10,3 +10,7 @@ export declare type FilterByLastOptionsType = {
10
10
  export declare function filterByLast<TItem extends {
11
11
  date: string;
12
12
  }>(items: TItem[], options: FilterByLastOptionsType, reasons?: Record<number, string[]>): TItem[];
13
+ export declare function createChron(): {
14
+ start: () => number;
15
+ elapsed: (formatted?: boolean | undefined) => string | number;
16
+ };
package/util/date-util.js CHANGED
@@ -3,7 +3,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.filterByLast = void 0;
6
+ exports.createChron = exports.filterByLast = void 0;
7
+ const string_util_1 = require("./string-util");
7
8
  const dayjs_1 = __importDefault(require("dayjs"));
8
9
  const advancedFormat_1 = __importDefault(require("dayjs/plugin/advancedFormat"));
9
10
  const isoWeek_1 = __importDefault(require("dayjs/plugin/isoWeek"));
@@ -72,3 +73,18 @@ function filterByLast(items, options, reasons) {
72
73
  return items.filter((item) => validItems.includes(item));
73
74
  }
74
75
  exports.filterByLast = filterByLast;
76
+ function createChron() {
77
+ let startTime;
78
+ return {
79
+ start: () => (startTime = Date.now()),
80
+ elapsed: (formatted) => {
81
+ if (!startTime)
82
+ throw new Error(`Chron was not started`);
83
+ const seconds = (Date.now() - startTime) / 1000;
84
+ if (formatted)
85
+ return (0, string_util_1.formatSeconds)(seconds);
86
+ return seconds;
87
+ },
88
+ };
89
+ }
90
+ exports.createChron = createChron;
@@ -68,10 +68,10 @@ async function exec(command, argv = [], options = null, settings = {}) {
68
68
  stderr: "",
69
69
  exitCode: 0,
70
70
  };
71
- let finishListens = pipe ? 2 : 1;
71
+ let finishListeners = pipe?.stream instanceof fs_1.WriteStream ? 2 : 1;
72
72
  let streamError;
73
73
  const tryFinish = () => {
74
- if (!--finishListens)
74
+ if (!--finishListeners)
75
75
  finish();
76
76
  };
77
77
  const finish = () => {
@@ -13,5 +13,6 @@ export declare type UriType = {
13
13
  path?: string;
14
14
  };
15
15
  export declare function formatUri(input: UriType, hidePassword?: boolean): string;
16
+ export declare function formatSeconds(seconds: number): string;
16
17
  export declare function makePathPatterns(values: string[] | undefined): string[] | undefined;
17
18
  export declare function formatDateTime(datetime: string): string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.formatDateTime = exports.makePathPatterns = exports.formatUri = exports.parseStringList = exports.render = exports.snakeCase = exports.lcfirst = exports.ucfirst = exports.serialize = void 0;
3
+ exports.formatDateTime = exports.makePathPatterns = exports.formatSeconds = exports.formatUri = exports.parseStringList = exports.render = exports.snakeCase = exports.lcfirst = exports.ucfirst = exports.serialize = void 0;
4
4
  const AppError_1 = require("../Error/AppError");
5
5
  function serialize(message, data) {
6
6
  if (data)
@@ -67,6 +67,26 @@ function formatUri(input, hidePassword) {
67
67
  return uri;
68
68
  }
69
69
  exports.formatUri = formatUri;
70
+ function formatSeconds(seconds) {
71
+ let unit;
72
+ let value;
73
+ if (seconds > 60 * 60) {
74
+ value = seconds / 60 / 60;
75
+ unit = `hour`;
76
+ }
77
+ else if (seconds > 60) {
78
+ value = seconds / 60;
79
+ unit = `minute`;
80
+ }
81
+ else {
82
+ value = seconds;
83
+ unit = `second`;
84
+ }
85
+ if (value !== 1)
86
+ unit += `s`;
87
+ return `${value.toFixed(2)} ${unit}`;
88
+ }
89
+ exports.formatSeconds = formatSeconds;
70
90
  function makePathPatterns(values) {
71
91
  return values?.flatMap((v) => [v, `${v}/**`]);
72
92
  }