This repository has been archived by the owner on Dec 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.js
212 lines (183 loc) · 5.92 KB
/
main.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/**
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** Create new BQ tables and views in dataset **/
function setup() {
var views = loadViewQueries_();
buildBQTables_(CONFIG['cloudProjectID'], CONFIG['bqDatasetID'], CONFIG.baseSchema);
buildBQViews_(CONFIG['cloudProjectID'], CONFIG['bqDatasetID'], views);
}
/**
*This is the main function of the script
* the apps script scheduling trigger should
* call this one.
*/
function run() {
runExportQuery_(
CONFIG['cloudProjectID'], CONFIG['bqDatasetID'],
'SELECT * FROM ' + getTablePath_('Step8'), CONFIG['cloudStorageDest']);
}
/** Initializes a new sheet with the recommended data structure **/
function initSheet() {
var sheetFile = SpreadsheetApp.openByUrl(CONFIG['sheetUrl']);
CONFIG['baseSchema'].forEach(function(tableItem) {
var newSheet = sheetFile.getSheetByName(tableItem.id);
if (newSheet != null) {
throw Utilities.formatString(
'Sheet %s already exists. Update it manually, run init on an empty sheet only.',
tableItem.id);
} else {
newSheet = sheetFile.insertSheet();
newSheet.setName(tableItem.id);
var colNames = tableItem.fields.map(function(field) {
return field.name;
});
newSheet.getRange(1, 1, 1, colNames.length).setValues([colNames]);
newSheet.deleteColumns((colNames.length + 1), (26 - colNames.length));
}
});
}
/**
* Creates BQ Schema for the dataset based on the current sheet file data
* @param {object} sheetFile
* @param {string} Uri
* @return {object} tableSchema
*/
function generateBQSchema_(sheetFile, Uri) {
var sheet = sheetFile.getSheets()[0];
var columns = getSheetColumns_(sheet);
var tableFields = [];
columns[0].forEach(function(column) {
if (column.trim().length > 0) {
tableFields.push({name: column, type: 'STRING'});
}
});
return {id: sheet.getName(), fields: tableFields, sourceUri: Uri};
}
/**
* Connects a Google sheet with BQ as federated data source
* @param {string} cloudProjectId
* @param {string} bqDatasetId
* @param {string} tableSchema
*/
function connectSheetToBQ_(cloudProjectId, bqDatasetId, tableSchema) {
var job = {
tableReference: {
projectId: cloudProjectId,
datasetId: bqDatasetId,
tableId: tableSchema['id']
},
schema: {'fields': tableSchema['fields']},
externalDataConfiguration: {
'sourceUris': [tableSchema['sourceUri']],
'sourceFormat': 'GOOGLE_SHEETS',
'autodetect': true,
}
};
try {
BigQuery.Tables.insert(job, cloudProjectId, bqDatasetId);
Logger.log(
'Load job started. Check on the status of it here: ' +
'https://bigquery.cloud.google.com/jobs/%s',
cloudProjectId);
} catch (e) {
Logger.log(e);
}
}
/**
* Runs a query job on BQ and exports the results of the temp table
* into a cloud storage bucket.
*
* @param {string} projectId
* @param {string} dataSetId
* @param {string} targetQuery
* @param {string} cloudStorageDest
*/
function runExportQuery_(projectId, dataSetId, targetQuery, cloudStorageDest) {
var request = {
query: targetQuery,
useLegacySql: false,
destinationTable: {projectId: projectId, dataSetId: dataSetId}
};
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
// Check on status of the Query Job.
var sleepTimeMs = 500;
while (!queryResults.jobComplete) {
Utilities.sleep(sleepTimeMs);
sleepTimeMs *= 2;
queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId);
}
// Reference for the table create as a result of the query (24 hours TTL)
var tempTable =
BigQuery.Jobs.get(projectId, jobId).configuration.query.destinationTable;
// Export the temp table data into cloud storage
var extractJobRequest = BigQuery.Jobs.insert(
{
configuration: {
extract: {
destinationFormat: 'csv',
sourceTable: tempTable,
destinationUri: cloudStorageDest
}
}
},
projectId);
Logger.log(extractJobRequest.jobReference.jobId);
}
/**
* Creates all the BQ tables based on the config schema
*
* @param {string} cloudProjectId
* @param {string} bqDatasetId
* @param {array} schemaConfig
*/
function buildBQTables_(cloudProjectId, bqDatasetId, schemaConfig) {
schemaConfig.forEach(function(tableStructure) {
var sheet = SpreadsheetApp.openByUrl(tableStructure['driveUri']);
var tableSchema = generateBQSchema_(sheet, tableStructure['driveUri']);
connectSheetToBQ_(cloudProjectId, bqDatasetId, tableSchema);
});
}
/**
* Creates all the BQ views passed into BQ
* @param {string} cloudProjectId
* @param {string} bqDatasetId
* @param {object} views An object defining the queries for views
* key as name and value as an SQL query
*/
function buildBQViews_(cloudProjectId, bqDatasetId, views) {
for (var viewName in views) {
var viewSQL = views[viewName];
BigQuery.Tables.insert(
{
tableReference: {
projectId: cloudProjectId,
datasetId: bqDatasetId,
tableId: viewName
},
view: {query: viewSQL, useLegacySql: false}
},
cloudProjectId, bqDatasetId);
}
}
/**
* Extracts all column names from a target sheet
* @param {Object} sheet
* @return {Array} array of column values of the given sheet
*/
function getSheetColumns_(sheet) {
return sheet.getRange('1:1').getValues();
}