@pittica/google-business-intelligence-helpers 1.14.0 → 1.15.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.
@@ -0,0 +1,111 @@
1
+ // Copyright 2024-2026 Pittica S.r.l.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ const {
16
+ getBucket
17
+ } = require("@pittica/google-cloud-storage-helpers");
18
+ const {
19
+ getDataset,
20
+ jobDone
21
+ } = require("@pittica/google-bigquery-helpers");
22
+ const log = require("@pittica/logger-helpers");
23
+ const {
24
+ format
25
+ } = require("date-and-time");
26
+
27
+ /**
28
+ * Creates a backup for a BigQuery dataset to Google Cloud Storage bucket.
29
+ *
30
+ * @param {string} id BigQuery dataset ID.
31
+ * @param {string} bucket Bucket name.
32
+ * @param {string} projectId Google Cloud project ID.
33
+ * @param {string} dateFormat Date format string.
34
+ * @returns {boolean} A value indicating whehter the job has been done.
35
+ */
36
+ exports.backup = async (id, bucket, projectId, dateFormat = "YYYY-MM-DD") => {
37
+ const dataset = await getDataset(id, {
38
+ projectId
39
+ });
40
+ const [tables] = await dataset.getTables();
41
+ const date = format(new Date(), dateFormat);
42
+ return await exports.extract(bucket, date, tables, 0);
43
+ };
44
+
45
+ /**
46
+ * Extracts a table from BigQuery to Google Cloud Storage.
47
+ *
48
+ * @param {string} bucket Bucket name.
49
+ * @param {string} date Date in format YYYY-MM-DD.
50
+ * @param {Array} tables An array of BigQuery tables.
51
+ * @param {number} index Array index.
52
+ * @returns {boolean} A value indicating whehter the job has been done.
53
+ */
54
+ exports.extract = async (bucket, date, tables, index) => {
55
+ if (index < tables.length) {
56
+ const table = tables[index];
57
+ return await table.extract(getBucket(bucket).file(`${date}/${table.id}-*.json`), {
58
+ location: "us-central1",
59
+ format: "json",
60
+ gzip: false
61
+ }).then(async response => {
62
+ if (jobDone(response)) {
63
+ const [job] = response;
64
+ log.success(`Job backup "${job.id}" for table "${table.id}" done.`);
65
+ return await exports.extract(date, tables, index + 1);
66
+ } else {
67
+ return false;
68
+ }
69
+ }).catch(errors => {
70
+ log.error(errors);
71
+ return false;
72
+ });
73
+ } else {
74
+ return true;
75
+ }
76
+ };
77
+
78
+ /**
79
+ * Rollback data using backup.
80
+ *
81
+ * @param {string} date Date to download in format "YYYY-MM-DD".
82
+ * @param {string} id BigQuery dataset ID.
83
+ * @param {string} projectId Google Cloud project ID.
84
+ * @param {string} sourceBucket Bucket name.
85
+ * @param {string} destinationDataset BigQuery dataset ID.
86
+ */
87
+ exports.rollback = async (date, id, projectId, sourceBucket, destinationDataset) => {
88
+ const dataset = await getDataset(id, {
89
+ projectId
90
+ });
91
+ const bucket = getBucket(sourceBucket);
92
+ const [response] = await bucket.getFiles({
93
+ prefix: `${date}/`
94
+ });
95
+ const files = groupJson(response.map(file => file.name.substring(11)));
96
+ log.info(`Begin rollback "${date}".`);
97
+ Object.keys(files).forEach(async key => {
98
+ const [table] = await dataset.table(key).get();
99
+ files[key].forEach(filename => bigquery.dataset(destinationDataset, {
100
+ location: dataset.metadata.location,
101
+ projectId
102
+ }).table(key).load(bucket.file(`${date}/${filename}`), {
103
+ sourceFormat: "NEWLINE_DELIMITED_JSON",
104
+ schema: table.metadata.schema,
105
+ timePartitioning: table.metadata.timePartitioning,
106
+ location: table.metadata.location,
107
+ tableConstraints: table.metadata.tableConstraints,
108
+ partitionDefinition: table.metadata.partitionDefinition
109
+ }));
110
+ });
111
+ };
@@ -14,6 +14,9 @@
14
14
 
15
15
  const fs = require("fs");
16
16
  const path = require("path");
17
+ const {
18
+ getTables
19
+ } = require("@pittica/google-bigquery-helpers");
17
20
 
18
21
  /**
19
22
  * Maps and imports the contents of the given folder.
@@ -38,7 +41,7 @@ exports.getSchemas = folder => {
38
41
  * @returns {object} The content related to the given name.
39
42
  */
40
43
  exports.getSchema = (name, folder) => {
41
- const contents = this.getSchemas(folder);
44
+ const contents = exports.getSchemas(folder);
42
45
  return Object.keys(contents).includes(name) ? contents[name] : null;
43
46
  };
44
47
 
@@ -57,4 +60,39 @@ exports.getSchemaKeys = folder => fs.readdirSync(folder).map(file => file.split(
57
60
  * @param {string} folder Path of the folder to scan.
58
61
  * @returns {boolean} A value indicating whether the given name has an associated content.
59
62
  */
60
- exports.hasSchema = (name, folder) => this.getSchemaKeys(folder).includes(name);
63
+ exports.hasSchema = (name, folder) => exports.getSchemaKeys(folder).includes(name);
64
+
65
+ /**
66
+ * Downloads the schemas of a dataset.
67
+ *
68
+ * @param {string} output Path to save files.
69
+ * @param {string} id The dataset name from which to download schemas.
70
+ * @param {string} projectId The project ID to which the dataset belongs.
71
+ */
72
+ exports.downloadSchemas = async (output, id, projectId = null) => {
73
+ const tables = await getTables(id, {
74
+ projectId
75
+ });
76
+ tables.forEach(async ({
77
+ dataset,
78
+ metadata: {
79
+ tableReference: {
80
+ tableId
81
+ }
82
+ }
83
+ }) => {
84
+ const [table] = await dataset.table(tableId).get();
85
+ const {
86
+ schema,
87
+ timePartitioning,
88
+ tableConstraints,
89
+ partitionDefinition
90
+ } = table.metadata;
91
+ fs.writeFileSync(path.join(output, `${tableId}.json`), JSON.stringify({
92
+ schema,
93
+ timePartitioning,
94
+ tableConstraints,
95
+ partitionDefinition
96
+ }), "utf8");
97
+ });
98
+ };
@@ -13,11 +13,18 @@
13
13
  // limitations under the License.
14
14
 
15
15
  const {
16
- getFiles
16
+ getFiles,
17
+ downloadFolder,
18
+ groupJson,
19
+ getBucket
17
20
  } = require("@pittica/google-cloud-storage-helpers");
21
+ const log = require("@pittica/logger-helpers");
18
22
  const {
19
- format
23
+ format,
24
+ parse
20
25
  } = require("date-and-time");
26
+ const path = require("path");
27
+ const fs = require("fs");
21
28
  const {
22
29
  getSchemaKeys
23
30
  } = require("./schema");
@@ -63,7 +70,7 @@ exports.mapStorageResponse = (response, schemas = "") => {
63
70
  */
64
71
  exports.extractStorageResponse = (response, schemas = "", dateFormat = "YYYY-MM-DD") => {
65
72
  const days = {};
66
- const files = this.mapStorageResponse(response, schemas);
73
+ const files = exports.mapStorageResponse(response, schemas);
67
74
  files.forEach(file => {
68
75
  const date = format(file.date, dateFormat);
69
76
  if (typeof days[date] === "undefined") {
@@ -104,4 +111,67 @@ exports.getSafeFilename = (storage, bucket, filename, folder = "") => getFiles(s
104
111
  exports.getSafeFilenameFromBucket = ({
105
112
  storage,
106
113
  name
107
- }, filename, folder = "") => this.getSafeFilename(storage, name, filename, folder);
114
+ }, filename, folder = "") => exports.getSafeFilename(storage, name, filename, folder);
115
+
116
+ /**
117
+ * Merges the files from a date and saves them in a local folder.
118
+ *
119
+ * @param {string} date Date to download in given format.
120
+ * @param {string} output Path to save files.
121
+ * @param {string} bucket Bucket name.
122
+ * @param {string} dateFormat Date format string.
123
+ */
124
+ exports.implode = async (date, output, bucket, dateFormat = "YYYY-MM-DD") => {
125
+ const folder = format(parse(date, dateFormat), dateFormat);
126
+ const destination = path.join(output, ".tmp");
127
+ const temporary = path.join(destination, folder);
128
+ await downloadFolder(folder, bucket, destination).then(() => log.info(`Downloaded "gs://${bucket}/${folder}" to "${destination}".`)).catch(log.error);
129
+ const files = groupJson(fs.readdirSync(temporary));
130
+ Object.keys(files).forEach(table => {
131
+ const json = [];
132
+ files[table].forEach(current => {
133
+ const content = [];
134
+ fs.readFileSync(path.join(temporary, current), {
135
+ encoding: "utf8"
136
+ }).split("\n").forEach(line => {
137
+ if (line) {
138
+ const result = JSON.parse(`[${line}]`);
139
+ return content.push(result[0]);
140
+ }
141
+ });
142
+ json.push(content);
143
+ });
144
+ fs.writeFileSync(path.join(output, `${table}.json`), JSON.stringify(json.flat(1)), "utf8");
145
+ });
146
+ fs.rmSync(destination, {
147
+ recursive: true,
148
+ force: true
149
+ });
150
+ log.success(`JSON files created in "${output}".`);
151
+ };
152
+
153
+ /**
154
+ * Erases the bucket.
155
+ *
156
+ * @param {string} bucket Bucket name.
157
+ * @param {number} days Number of days to keep.
158
+ * @returns {boolean} A value indicating whehter the job has been done.
159
+ */
160
+ exports.erase = async (bucket, days = process.env.BACKUP_KEEP_DAYS || 3) => {
161
+ const b = getBucket(bucket);
162
+ const [files] = await b.getFiles();
163
+ const result = {};
164
+ files.forEach(({
165
+ id
166
+ }) => {
167
+ const split = id.split(/^(\d{4})\-(\d{2})\-(\d{2})/gis);
168
+ result[`${split[1]}-${split[2]}-${split[3]}`] = null;
169
+ });
170
+ const folders = Object.keys(result).sort();
171
+ const blacklist = folders.slice(0, folders.length - parseInt(days));
172
+ blacklist.forEach(async prefix => await b.deleteFiles({
173
+ prefix
174
+ }));
175
+ log.success("Backup bucket erased.");
176
+ return true;
177
+ };
package/dist/index.js CHANGED
@@ -12,11 +12,16 @@
12
12
  // See the License for the specific language governing permissions and
13
13
  // limitations under the License.
14
14
 
15
+ const {
16
+ backup,
17
+ rollback
18
+ } = require("./contents/backup");
15
19
  const {
16
20
  getSchemas,
17
21
  getSchema,
18
22
  getSchemaKeys,
19
- hasSchema
23
+ hasSchema,
24
+ downloadSchemas
20
25
  } = require("./contents/schema");
21
26
  const {
22
27
  getSqlFilePath
@@ -25,7 +30,9 @@ const {
25
30
  mapStorageResponse,
26
31
  extractStorageResponse,
27
32
  getSafeFilename,
28
- getSafeFilenameFromBucket
33
+ getSafeFilenameFromBucket,
34
+ implode,
35
+ erase
29
36
  } = require("./contents/storage");
30
37
  const {
31
38
  getTemporaryTableName,
@@ -63,15 +70,32 @@ const {
63
70
  const {
64
71
  scriptUnlistened
65
72
  } = require("./scripts/unlistened");
73
+ const {
74
+ scriptDownloadSchemas
75
+ } = require("./scripts/schema");
76
+ const {
77
+ scriptImplode,
78
+ scriptErase
79
+ } = require("./scripts/storage");
80
+ const {
81
+ scriptBackup,
82
+ scriptBackupErase,
83
+ scriptRollback
84
+ } = require("./scripts/backup");
85
+ exports.backup = backup;
86
+ exports.rollback = rollback;
66
87
  exports.getSchemas = getSchemas;
67
88
  exports.getSchema = getSchema;
68
89
  exports.getSchemaKeys = getSchemaKeys;
69
90
  exports.hasSchema = hasSchema;
91
+ exports.downloadSchemas = downloadSchemas;
70
92
  exports.getSqlFilePath = getSqlFilePath;
71
93
  exports.mapStorageResponse = mapStorageResponse;
72
94
  exports.extractStorageResponse = extractStorageResponse;
73
95
  exports.getSafeFilename = getSafeFilename;
74
96
  exports.getSafeFilenameFromBucket = getSafeFilenameFromBucket;
97
+ exports.implode = implode;
98
+ exports.erase = erase;
75
99
  exports.getTemporaryTableName = getTemporaryTableName;
76
100
  exports.getTemporaryTableSuffix = getTemporaryTableSuffix;
77
101
  exports.partsToDate = partsToDate;
@@ -94,5 +118,11 @@ exports.splitName = splitName;
94
118
  exports.splitIdByKeys = splitIdByKeys;
95
119
  exports.scripts = {
96
120
  comparison: scriptComparison,
97
- unlistened: scriptUnlistened
121
+ unlistened: scriptUnlistened,
122
+ downloadSchemas: scriptDownloadSchemas,
123
+ implode: scriptImplode,
124
+ erase: scriptErase,
125
+ backup: scriptBackup,
126
+ backupErase: scriptBackupErase,
127
+ rollback: scriptRollback
98
128
  };
@@ -35,4 +35,4 @@ exports.getTemporaryTableName = ({
35
35
  date,
36
36
  name,
37
37
  version
38
- }, prefix) => prefix + name + "-" + version + "-" + this.getTemporaryTableSuffix(date);
38
+ }, prefix) => prefix + name + "-" + version + "-" + exports.getTemporaryTableSuffix(date);
@@ -41,7 +41,7 @@ exports.partsToDateUTC = parts => new Date(Date.UTC(parseInt(parts[1]), parseInt
41
41
  exports.stringToDate = date => {
42
42
  const split = date.split(/^(\d{4})\-(\d{2})\-(\d{2})$/gis);
43
43
  if (split.length === 5) {
44
- return this.partsToDate(split);
44
+ return exports.partsToDate(split);
45
45
  }
46
46
  return null;
47
47
  };
@@ -55,7 +55,7 @@ exports.stringToDate = date => {
55
55
  exports.stringToDateUTC = date => {
56
56
  const split = date.split(/^(\d{4})\-(\d{2})\-(\d{2})$/gis);
57
57
  if (split.length === 5) {
58
- return this.partsToDateUTC(split);
58
+ return exports.partsToDateUTC(split);
59
59
  }
60
60
  return null;
61
61
  };
@@ -66,7 +66,7 @@ exports.stringToDateUTC = date => {
66
66
  * @param {string} dateFormat Format string.
67
67
  * @returns {string} The current date in the given format.
68
68
  */
69
- exports.getNow = (dateFormat = "YYYY-MM-DD") => this.formatDate(new Date(), dateFormat);
69
+ exports.getNow = (dateFormat = "YYYY-MM-DD") => exports.formatDate(new Date(), dateFormat);
70
70
 
71
71
  /**
72
72
  * Gets the given date in the given format.
@@ -98,7 +98,7 @@ exports.getDatesUntil = (until = new Date(), dateFormat = "YYYY-MM-DD") => {
98
98
  const year = until.getUTCFullYear();
99
99
  let current = new Date(Date.UTC(year, 0, 1));
100
100
  while (current <= until && current.getUTCFullYear() === year) {
101
- dates.push(this.formatDateUTC(current, dateFormat));
101
+ dates.push(exports.formatDateUTC(current, dateFormat));
102
102
  current.setUTCDate(current.getUTCDate() + 1);
103
103
  }
104
104
  return dates;
@@ -113,10 +113,10 @@ exports.getDatesUntil = (until = new Date(), dateFormat = "YYYY-MM-DD") => {
113
113
  */
114
114
  exports.getFormattedDate = (date = null, dateFormat = "YYYY-MM-DD") => {
115
115
  if (date != null) {
116
- return this.formatDate(typeof date === "string" ? this.stringToDate(date) : date, dateFormat);
116
+ return exports.formatDate(typeof date === "string" ? exports.stringToDateUTC(date) : date, dateFormat);
117
117
  } else {
118
- const now = this.stringToDate(this.getNow());
119
- now.setDate(now.getDate() - 1);
120
- return this.formatDate(now, dateFormat);
118
+ const now = exports.stringToDateUTC(exports.getNow());
119
+ now.setDate(now.getDate());
120
+ return exports.formatDate(now, dateFormat);
121
121
  }
122
122
  };
@@ -85,4 +85,4 @@ exports.mergeFiledata = ({
85
85
  name,
86
86
  extension,
87
87
  version
88
- }, increment = false) => this.mergeFilename(date, name, extension, increment ? typeof version !== "undefined" ? version + 1 : 1 : version);
88
+ }, increment = false) => exports.mergeFilename(date, name, extension, increment ? typeof version !== "undefined" ? version + 1 : 1 : version);
@@ -0,0 +1,51 @@
1
+ // Copyright 2024-2026 Pittica S.r.l.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ const {
16
+ backup,
17
+ rollback
18
+ } = require("../contents/backup");
19
+ const {
20
+ erase
21
+ } = require("../contents/storage");
22
+
23
+ /**
24
+ * Creates a backup for a BigQuery dataset to Google Cloud Storage bucket.
25
+ *
26
+ * @param {string} id BigQuery dataset ID.
27
+ * @param {string} bucket Bucket name.
28
+ * @param {string} projectId Google Cloud project ID.
29
+ * @param {string} dateFormat Date format string.
30
+ * @returns {boolean} A value indicating whehter the job has been done.
31
+ */
32
+ exports.scriptBackup = backup;
33
+
34
+ /**
35
+ * Creates a backup and erases the bucket.
36
+ *
37
+ * @param {number} days Number of days to keep.
38
+ * @returns {boolean} A value indicating whehter the job has been done.
39
+ */
40
+ exports.scriptBackupErase = async days => await backup().then(async () => await erase(days));
41
+
42
+ /**
43
+ * Rollback data using backup.
44
+ *
45
+ * @param {string} date Date to download in format "YYYY-MM-DD".
46
+ * @param {string} id BigQuery dataset ID.
47
+ * @param {string} projectId Google Cloud project ID.
48
+ * @param {string} sourceBucket Bucket name.
49
+ * @param {string} destinationDataset BigQuery dataset ID.
50
+ */
51
+ exports.scriptRollback = rollback;
@@ -0,0 +1,26 @@
1
+ // Copyright 2024-2026 Pittica S.r.l.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ const {
16
+ downloadSchemas
17
+ } = require("../contents/schema");
18
+
19
+ /**
20
+ * Downloads the schemas of a dataset.
21
+ *
22
+ * @param {string} output Path to save files.
23
+ * @param {string} id The dataset name from which to download schemas.
24
+ * @param {string} projectId The project ID to which the dataset belongs.
25
+ */
26
+ exports.scriptDownloadSchemas = downloadSchemas;
@@ -0,0 +1,36 @@
1
+ // Copyright 2024-2026 Pittica S.r.l.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ const {
16
+ implode,
17
+ erase
18
+ } = require("../contents/storage");
19
+
20
+ /**
21
+ * Merges the files from a date and saves them in a local folder.
22
+ *
23
+ * @param {string} date Date to download in given format.
24
+ * @param {string} output Path to save files.
25
+ * @param {string} bucket Bucket name.
26
+ * @param {string} dateFormat Date format string.
27
+ */
28
+ exports.scriptImplode = implode;
29
+ /**
30
+ * Erases the bucket.
31
+ *
32
+ * @param {string} bucket Bucket name.
33
+ * @param {number} days Number of days to keep.
34
+ * @returns {boolean} A value indicating whehter the job has been done.
35
+ */
36
+ exports.scriptErase = erase;
package/package.json CHANGED
@@ -1,14 +1,20 @@
1
1
  {
2
2
  "name": "@pittica/google-business-intelligence-helpers",
3
3
  "private": false,
4
- "version": "1.14.0",
4
+ "version": "1.15.0",
5
5
  "description": "Helpers for business intelligence for Google Cloud.",
6
6
  "main": "dist/index.js",
7
7
  "scripts": {
8
8
  "build": "rimraf ./dist && mkdirp ./dist && babel src --out-dir dist --copy-files",
9
9
  "test": "echo \"Error: no test specified\" && exit 1",
10
10
  "unlistened": "npm run build && run-func ./dist/scripts/unlistened.js scriptUnlistened",
11
- "comparison": "npm run build && run-func ./dist/scripts/comparison.js scriptComparison"
11
+ "comparison": "npm run build && run-func ./dist/scripts/comparison.js scriptComparison",
12
+ "download-schema": "npm run build && run-func ./dist/scripts/schema.js scriptDownloadSchemas",
13
+ "implode": "npm run build && run-func ./dist/scripts/storage.js scriptImplode",
14
+ "erase": "npm run build && run-func ./dist/scripts/storage.js scriptErase",
15
+ "backup": "npm run build && run-func ./dist/scripts/backup.js scriptBackup",
16
+ "backup-erase": "npm run build && run-func ./dist/scripts/backup.js scriptBackupErase",
17
+ "rollback": "npm run build && run-func ./dist/scripts/backup.js scriptRollback"
12
18
  },
13
19
  "repository": {
14
20
  "type": "git",
@@ -30,8 +36,10 @@
30
36
  "node": ">=24.11.0"
31
37
  },
32
38
  "dependencies": {
39
+ "@pittica/google-bigquery-helpers": "^1.6.1",
33
40
  "@pittica/google-cloud-storage-helpers": "^1.5.0",
34
- "date-and-time": "^4.6.0"
41
+ "@pittica/logger-helpers": "^1.2.2",
42
+ "date-and-time": "^4.7.0"
35
43
  },
36
44
  "devDependencies": {
37
45
  "@babel/cli": "^8.0.6",