-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoogle_bigquery.js
More file actions
512 lines (437 loc) · 18.1 KB
/
google_bigquery.js
File metadata and controls
512 lines (437 loc) · 18.1 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
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
/**
* @fileoverview BigQuery Audit Module - GA4 Export Monitoring
* @version 1.0
*/
// =================================================================
// MODULE CONSTANTS AND CONFIGURATION
// =================================================================
const BQ_DATASETS_HEADERS = [
'Project ID', 'Dataset ID', 'Location', 'Created Date', 'Last Modified',
'Default Expiration (Days)', 'Description', 'Is GA4 Export', 'Sync Date'
];
const BQ_GA4_TABLES_HEADERS = [
'Project ID', 'Dataset ID', 'Table ID', 'Table Type', 'Row Count',
'Size (GB)', 'Created Date', 'Last Modified', 'Partition Type', 'Clustering Fields', 'Sync Date'
];
const BQ_GA4_EXPORT_LINKS_HEADERS = [
'GA4 Property ID', 'GA4 Property Name', 'BigQuery Project', 'BigQuery Dataset',
'Daily Export Enabled', 'Streaming Export Enabled', 'Fresh Daily Export Enabled',
'Excluded Events', 'Link Created Date', 'Export Status', 'Sync Date'
];
// =================================================================
// SYNCHRONIZATION FUNCTIONS (EXECUTABLE FROM MENU)
// =================================================================
/**
* Main function to synchronize BigQuery data.
* Supports incremental sync by filtering datasets modified since last sync.
* @param {Object} options - Options object {forceFullAudit, incrementalEnabled}
* @returns {Object} Sync status, record count, and sync mode.
*/
function syncBigQueryCore(options = {}) {
const startTime = Date.now();
const serviceName = 'bigquery';
const results = { datasets: 0, ga4Tables: 0, exportLinks: 0 };
const forceFullAudit = options.forceFullAudit || false;
const incrementalEnabled = options.incrementalEnabled !== false;
try {
const config = getUserConfig();
const auth = getAuthConfig(serviceName);
logSyncStart('BigQuery_Sync', auth.authUser);
// Get GCP Project ID from config
const projectId = config.bqProjectId;
if (!projectId) {
logWarning('BigQuery', 'No BigQuery Project ID configured. Skipping BigQuery audit.');
return {
records: 0,
status: 'SKIPPED',
duration: Date.now() - startTime,
syncMode: 'SKIPPED',
error: 'No BigQuery Project ID configured'
};
}
// Determine audit mode (FULL vs INCREMENTAL)
const auditMode = getAuditMode('BigQuery', 'Datasets', forceFullAudit);
const isIncremental = incrementalEnabled && auditMode === 'INCREMENTAL';
const lastSyncTime = isIncremental ? new Date(getSyncState('BigQuery', 'Datasets')?.lastSyncTimestamp || 0) : null;
logEvent('BigQuery', `Phase 1: Scanning project ${projectId}... (Mode: ${auditMode})`);
// 1. LIST ALL DATASETS
let datasets = listBigQueryDatasets(projectId);
// Filter datasets if incremental and we have a last sync time
if (isIncremental && lastSyncTime) {
const originalCount = datasets.length;
datasets = datasets.filter(d => {
const lastModified = new Date(d['Last Modified'] || 0);
return lastModified > lastSyncTime;
});
logEvent('BigQuery', `Incremental datasets: ${datasets.length} modified since last sync (from ${originalCount} total)`);
}
results.datasets = datasets.length;
if (datasets.length > 0 || !isIncremental) {
writeBQDatasetsToSheet(datasets);
}
// 2. GET GA4 EXPORT TABLES
const ga4Datasets = datasets.filter(d => d['Is GA4 Export'] === 'Yes');
logEvent('BigQuery', `Found ${ga4Datasets.length} GA4 export datasets`);
const allGa4Tables = [];
for (const dataset of ga4Datasets) {
try {
const tables = listGA4ExportTables(dataset['Project ID'], dataset['Dataset ID']);
allGa4Tables.push(...tables);
} catch (e) {
logWarning('BigQuery', `Could not get tables for ${dataset['Dataset ID']}: ${e.message}`);
}
Utilities.sleep(100);
}
results.ga4Tables = allGa4Tables.length;
if (allGa4Tables.length > 0 || !isIncremental) {
writeBQGA4TablesToSheet(allGa4Tables);
}
// 3. GET GA4 EXPORT LINKS
logEvent('BigQuery', 'Phase 2: Checking GA4 BigQuery export links...');
const exportLinks = getGA4ExportLinks();
results.exportLinks = exportLinks.length;
writeBQExportLinksToSheet(exportLinks, datasets);
// Record sync state for each resource type
recordSyncState('BigQuery', 'Datasets', results.datasets, 'SUCCESS', auditMode);
recordSyncState('BigQuery', 'GA4Tables', results.ga4Tables, 'SUCCESS', auditMode);
recordSyncState('BigQuery', 'ExportLinks', results.exportLinks, 'SUCCESS', auditMode);
const totalElements = results.datasets + results.ga4Tables + results.exportLinks;
const duration = Date.now() - startTime;
logSyncEnd('BigQuery_Sync', totalElements, duration, 'SUCCESS');
return {
records: totalElements,
status: 'SUCCESS',
duration: duration,
syncMode: auditMode,
details: results
};
} catch (error) {
const duration = Date.now() - startTime;
logSyncEnd('BigQuery_Sync', 0, duration, 'ERROR');
logError('BigQuery', `Synchronization failed: ${error.message}`);
// Report error in the primary sheet
writeDataToSheet('BQ_DATASETS', BQ_DATASETS_HEADERS, null, 'BigQuery', error.message);
return {
records: 0,
status: 'ERROR',
duration: duration,
syncMode: 'ERROR',
error: error.message
};
}
}
/**
* Entry point for UI calls.
*/
function syncBigQueryWithUI() {
showLoadingNotification('Syncing BigQuery datasets and GA4 exports...');
const result = syncBigQueryCore();
const ui = SpreadsheetApp.getUi();
if (result.status === 'SUCCESS') {
const details = result.details;
const body = `Datasets: ${details.datasets} | GA4 Tables: ${details.ga4Tables} | Export Links: ${details.exportLinks}\n\n` +
`Total: ${result.records} elements | Time: ${Math.round(result.duration / 1000)}s\n\n` +
`Data written to BQ_DATASETS, BQ_GA4_TABLES, BQ_GA4_EXPORT_LINKS.`;
ui.alert('BigQuery Synchronized', body, ui.ButtonSet.OK);
} else if (result.status === 'SKIPPED') {
const body = `BigQuery audit requires a GCP Project ID to be configured.\n\n` +
`Action: Go to "Configure Addocu" > Advanced Settings and enter your GCP Project ID to enable BigQuery auditing.\n\n` +
`Details: Check LOGS sheet for more information.`;
ui.alert('BigQuery Skipped', body, ui.ButtonSet.OK);
} else {
const body = `Synchronization failed: ${result.error}\n\n` +
`Action: Verify that your GCP Project ID is correctly configured and that you have BigQuery API access.\n\n` +
`Details: Check LOGS sheet for more information.`;
ui.alert('BigQuery Error', body, ui.ButtonSet.OK);
}
}
// =================================================================
// DATA EXTRACTION HELPERS
// =================================================================
/**
* Lists all BigQuery datasets in a project.
* @param {string} projectId - GCP Project ID
* @returns {Array<Object>} Array of dataset objects.
*/
function listBigQueryDatasets(projectId) {
const auth = getAuthConfig('bigquery');
const url = `https://bigquery.googleapis.com/bigquery/v2/projects/${projectId}/datasets`;
const options = { method: 'GET', headers: auth.headers, muteHttpExceptions: true };
const response = fetchWithRetry(url, options, 'BQ-Datasets');
if (!response || !response.datasets) return [];
return response.datasets.map(ds => {
const datasetRef = ds.datasetReference;
const isGA4 = datasetRef.datasetId.startsWith('analytics_') ? 'Yes' : 'No';
// Convert expiration from milliseconds to days
const expirationDays = ds.defaultTableExpirationMs
? Math.round(ds.defaultTableExpirationMs / (1000 * 60 * 60 * 24))
: 'None';
return {
'Project ID': datasetRef.projectId,
'Dataset ID': datasetRef.datasetId,
'Location': ds.location || 'N/A',
'Created Date': ds.creationTime ? formatTimestamp(ds.creationTime) : 'N/A',
'Last Modified': ds.lastModifiedTime ? formatTimestamp(ds.lastModifiedTime) : 'N/A',
'Default Expiration (Days)': expirationDays,
'Description': ds.friendlyName || 'N/A',
'Is GA4 Export': isGA4
};
});
}
/**
* Lists GA4 export tables in a dataset.
* Implements date range filtering to avoid timeout issues.
* @param {string} projectId - GCP Project ID
* @param {string} datasetId - Dataset ID
* @returns {Array<Object>} Array of table objects.
*/
function listGA4ExportTables(projectId, datasetId) {
const auth = getAuthConfig('bigquery');
const url = `https://bigquery.googleapis.com/bigquery/v2/projects/${projectId}/datasets/${datasetId}/tables`;
const options = { method: 'GET', headers: auth.headers, muteHttpExceptions: true };
const response = fetchWithRetry(url, options, `BQ-Tables-${datasetId}`);
if (!response || !response.tables) return [];
// Get date range filter from user config (default: 30 days)
const dateRangeDays = getBigQueryTableDateRange();
// Filter tables by date before fetching metadata (critical optimization)
const filteredTables = filterTablesByDateRange(response.tables, dateRangeDays);
logEvent('BigQuery', `Dataset ${datasetId}: ${response.tables.length} total tables, ${filteredTables.length} within ${dateRangeDays}-day range`);
// Get detailed metadata only for filtered tables
return filteredTables.map(t => {
const tableRef = t.tableReference;
return getTableMetadata(projectId, datasetId, tableRef.tableId);
}).filter(t => t !== null);
}
/**
* Gets the BigQuery table date range from user config.
* @returns {number} Number of days to look back (default: 30)
*/
function getBigQueryTableDateRange() {
try {
const userProperties = PropertiesService.getUserProperties();
const range = userProperties.getProperty('ADDOCU_BQ_TABLE_DATE_RANGE');
if (range === 'all') return -1; // -1 means no filtering
const days = parseInt(range);
return days > 0 ? days : 30; // Default: 30 days
} catch (e) {
return 30; // Default if error
}
}
/**
* Filters tables by date range to reduce API calls.
* Only GA4 daily export tables (events_YYYYMMDD) are filtered.
* Streaming, intraday, and other tables are always included.
* @param {Array} tables - Array of table objects from BigQuery API
* @param {number} daysBack - Number of days to look back (-1 = all)
* @returns {Array} Filtered array of tables
*/
function filterTablesByDateRange(tables, daysBack) {
// If daysBack is -1, return all tables (no filtering)
if (daysBack < 0) {
logEvent('BigQuery', 'Date range filter disabled (processing all tables)');
return tables;
}
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - daysBack);
cutoffDate.setHours(0, 0, 0, 0);
return tables.filter(table => {
const tableId = table.tableReference.tableId;
// Match GA4 daily export tables: events_YYYYMMDD
const dailyMatch = tableId.match(/^events_(\d{8})$/);
if (dailyMatch) {
const dateStr = dailyMatch[1];
const year = parseInt(dateStr.substring(0, 4));
const month = parseInt(dateStr.substring(4, 6)) - 1; // 0-indexed
const day = parseInt(dateStr.substring(6, 8));
const tableDate = new Date(year, month, day);
// Only include if within date range
return tableDate >= cutoffDate;
}
// Always include non-daily tables (streaming, intraday, custom)
return true;
});
}
/**
* Gets detailed metadata for a specific table.
* @param {string} projectId - GCP Project ID
* @param {string} datasetId - Dataset ID
* @param {string} tableId - Table ID
* @returns {Object} Table metadata.
*/
function getTableMetadata(projectId, datasetId, tableId) {
try {
const auth = getAuthConfig('bigquery');
const url = `https://bigquery.googleapis.com/bigquery/v2/projects/${projectId}/datasets/${datasetId}/tables/${tableId}`;
const options = { method: 'GET', headers: auth.headers, muteHttpExceptions: true };
const table = fetchWithRetry(url, options, `BQ-Table-${tableId}`);
if (!table) return null;
// Determine table type from name pattern
let tableType = 'Other';
if (tableId.match(/^events_\d{8}$/)) tableType = 'Daily';
else if (tableId.startsWith('events_intraday_')) tableType = 'Intraday';
else if (tableId.startsWith('events_streaming_')) tableType = 'Streaming';
// Get size in GB
const sizeGB = table.numBytes ? (parseFloat(table.numBytes) / 1073741824).toFixed(2) : '0';
// Get partition and clustering info
const partitionType = table.timePartitioning ? table.timePartitioning.type : 'None';
const clusteringFields = table.clustering
? table.clustering.fields.join(', ')
: 'None';
return {
'Project ID': projectId,
'Dataset ID': datasetId,
'Table ID': tableId,
'Table Type': tableType,
'Row Count': table.numRows || '0',
'Size (GB)': sizeGB,
'Created Date': table.creationTime ? formatTimestamp(table.creationTime) : 'N/A',
'Last Modified': table.lastModifiedTime ? formatTimestamp(table.lastModifiedTime) : 'N/A',
'Partition Type': partitionType,
'Clustering Fields': clusteringFields
};
} catch (e) {
logWarning('BigQuery', `Could not get metadata for table ${tableId}: ${e.message}`);
return null;
}
}
/**
* Gets GA4 BigQuery export links from all GA4 properties.
* @returns {Array<Object>} Array of export link objects.
*/
function getGA4ExportLinks() {
try {
// Get all GA4 properties from the GA4_PROPERTIES sheet
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ga4Sheet = ss.getSheetByName('GA4_PROPERTIES');
if (!ga4Sheet || ga4Sheet.getLastRow() <= 1) {
logWarning('BigQuery', 'No GA4 properties found. Run GA4 audit first.');
return [];
}
const data = ga4Sheet.getDataRange().getValues();
const headers = data[0];
const propertyIdIndex = headers.indexOf('Property ID');
const propertyNameIndex = headers.indexOf('Display Name');
if (propertyIdIndex === -1) {
logWarning('BigQuery', 'Could not find Property ID column in GA4_PROPERTIES sheet');
return [];
}
const exportLinks = [];
// Skip header row
for (let i = 1; i < data.length; i++) {
const propertyId = data[i][propertyIdIndex];
const propertyName = data[i][propertyNameIndex] || 'N/A';
if (!propertyId) continue;
try {
const links = listBigQueryLinksForProperty(propertyId, propertyName);
exportLinks.push(...links);
} catch (e) {
logWarning('BigQuery', `Could not get BQ links for property ${propertyId}: ${e.message}`);
}
Utilities.sleep(100);
}
return exportLinks;
} catch (e) {
logError('BigQuery', `Error getting GA4 export links: ${e.message}`);
return [];
}
}
/**
* Lists BigQuery links for a specific GA4 property.
* @param {string} propertyId - GA4 Property ID (e.g., "123456789")
* @param {string} propertyName - GA4 Property Name
* @returns {Array<Object>} Array of BigQuery link objects.
*/
function listBigQueryLinksForProperty(propertyId, propertyName) {
const auth = getAuthConfig('ga4');
const url = `https://analyticsadmin.googleapis.com/v1alpha/properties/${propertyId}/bigQueryLinks`;
const options = { method: 'GET', headers: auth.headers, muteHttpExceptions: true };
const response = fetchWithRetry(url, options, `GA4-BQLinks-${propertyId}`);
if (!response || !response.bigQueryLinks) return [];
return response.bigQueryLinks.map(link => ({
'GA4 Property ID': propertyId,
'GA4 Property Name': propertyName,
'BigQuery Project': link.project || 'N/A',
'BigQuery Dataset': `analytics_${propertyId}`,
'Daily Export Enabled': link.dailyExportEnabled ? 'Yes' : 'No',
'Streaming Export Enabled': link.streamingExportEnabled ? 'Yes' : 'No',
'Fresh Daily Export Enabled': link.freshDailyExportEnabled ? 'Yes' : 'No',
'Excluded Events': link.excludedEvents ? link.excludedEvents.join(', ') : 'None',
'Link Created Date': link.createTime || 'N/A'
}));
}
// =================================================================
// SHEET WRITING HELPERS
// =================================================================
function writeBQDatasetsToSheet(datasets) {
const syncDate = formatDate(new Date());
const data = datasets.map(d => [
d['Project ID'],
d['Dataset ID'],
d['Location'],
d['Created Date'],
d['Last Modified'],
d['Default Expiration (Days)'],
d['Description'],
d['Is GA4 Export'],
syncDate
]);
writeDataToSheet('BQ_DATASETS', BQ_DATASETS_HEADERS, data, 'BigQuery');
}
function writeBQGA4TablesToSheet(tables) {
const syncDate = formatDate(new Date());
const data = tables.map(t => [
t['Project ID'],
t['Dataset ID'],
t['Table ID'],
t['Table Type'],
t['Row Count'],
t['Size (GB)'],
t['Created Date'],
t['Last Modified'],
t['Partition Type'],
t['Clustering Fields'],
syncDate
]);
writeDataToSheet('BQ_GA4_TABLES', BQ_GA4_TABLES_HEADERS, data, 'BigQuery');
}
function writeBQExportLinksToSheet(links, datasets) {
const syncDate = formatDate(new Date());
const data = links.map(link => {
// Check if the dataset actually exists in BigQuery
const datasetExists = datasets.some(d =>
d['Dataset ID'] === link['BigQuery Dataset'] &&
d['Project ID'] === link['BigQuery Project']
);
const exportStatus = datasetExists ? 'Active' : 'Missing Dataset';
return [
link['GA4 Property ID'],
link['GA4 Property Name'],
link['BigQuery Project'],
link['BigQuery Dataset'],
link['Daily Export Enabled'],
link['Streaming Export Enabled'],
link['Fresh Daily Export Enabled'],
link['Excluded Events'],
link['Link Created Date'],
exportStatus,
syncDate
];
});
writeDataToSheet('BQ_GA4_EXPORT_LINKS', BQ_GA4_EXPORT_LINKS_HEADERS, data, 'BigQuery');
}
// =================================================================
// UTILITY HELPERS
// =================================================================
/**
* Formats a BigQuery timestamp (milliseconds) to a readable date.
* @param {string} timestamp - Timestamp in milliseconds
* @returns {string} Formatted date string
*/
function formatTimestamp(timestamp) {
try {
const date = new Date(parseInt(timestamp));
return formatDate(date);
} catch (e) {
return 'N/A';
}
}