-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
Copy pathview.js
517 lines (437 loc) · 14.1 KB
/
view.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
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
513
514
515
516
517
import { pick, some, find, minBy, map, intersection, isArray, isObject } from 'lodash';
import { SCHEMA_NOT_SUPPORTED, SCHEMA_LOAD_ERROR } from '@/services/data-source';
import getTags from '@/services/getTags';
import template from './query.html';
const DEFAULT_TAB = 'table';
function QueryViewCtrl(
$scope,
Events,
$route,
$routeParams,
$location,
$window,
$q,
KeyboardShortcuts,
Title,
AlertDialog,
Notifications,
clientConfig,
toastr,
$uibModal,
currentUser,
Policy,
Query,
DataSource,
Visualization,
) {
function getQueryResult(maxAge) {
if (maxAge === undefined) {
maxAge = $location.search().maxAge;
}
if (maxAge === undefined) {
maxAge = -1;
}
$scope.showLog = false;
$scope.queryResult = $scope.query.getQueryResult(maxAge);
}
function getDataSourceId() {
// Try to get the query's data source id
let dataSourceId = $scope.query.data_source_id;
// If there is no source yet, then parse what we have in localStorage
// e.g. `null` -> `NaN`, malformed data -> `NaN`, "1" -> 1
if (dataSourceId === undefined) {
dataSourceId = parseInt(localStorage.lastSelectedDataSourceId, 10);
}
// If we had an invalid value in localStorage (e.g. nothing, deleted source),
// then use the first data source
const isValidDataSourceId = !isNaN(dataSourceId) && some($scope.dataSources, ds => ds.id === dataSourceId);
if (!isValidDataSourceId) {
dataSourceId = $scope.dataSources[0].id;
}
// Return our data source id
return dataSourceId;
}
function getSchema(refresh = undefined) {
// TODO: is it possible this will be called before dataSource is set?
$scope.schema = [];
$scope.dataSource.getSchema(refresh).then((data) => {
if (data.schema) {
$scope.schema = data.schema;
$scope.schema.forEach((table) => {
table.collapsed = true;
});
} else if (data.error.code === SCHEMA_NOT_SUPPORTED) {
$scope.schema = undefined;
} else if (data.error.code === SCHEMA_LOAD_ERROR) {
toastr.error('Schema refresh failed. Please try again later.');
} else {
toastr.error('Schema refresh failed. Please try again later.');
}
});
}
$scope.refreshSchema = () => getSchema(true);
function updateDataSources(dataSources) {
// Filter out data sources the user can't query (or used by current query):
function canUseDataSource(dataSource) {
return !dataSource.view_only || dataSource.id === $scope.query.data_source_id;
}
$scope.dataSources = dataSources.filter(canUseDataSource);
if ($scope.dataSources.length === 0) {
$scope.noDataSources = true;
return;
}
if ($scope.query.isNew()) {
$scope.query.data_source_id = getDataSourceId();
}
$scope.dataSource = find(dataSources, ds => ds.id === $scope.query.data_source_id);
$scope.canCreateQuery = some(dataSources, ds => !ds.view_only);
getSchema();
}
$scope.executeQuery = () => {
if (!$scope.canExecuteQuery()) {
return;
}
if (!$scope.query.query) {
return;
}
getQueryResult(0);
$scope.lockButton(true);
$scope.cancelling = false;
Events.record('execute', 'query', $scope.query.id);
Notifications.getPermissions();
};
$scope.selectedTab = DEFAULT_TAB;
$scope.currentUser = currentUser;
$scope.dataSource = {};
$scope.query = $route.current.locals.query;
$scope.showPermissionsControl = clientConfig.showPermissionsControl;
const shortcuts = {
'mod+enter': $scope.executeQuery,
};
KeyboardShortcuts.bind(shortcuts);
$scope.$on('$destroy', () => {
KeyboardShortcuts.unbind(shortcuts);
});
if ($scope.query.hasResult() || $scope.query.paramsRequired()) {
getQueryResult();
}
$scope.queryExecuting = false;
$scope.isQueryOwner = currentUser.id === $scope.query.user.id || currentUser.hasPermission('admin');
$scope.canEdit = currentUser.canEdit($scope.query) || $scope.query.can_edit;
$scope.canViewSource = currentUser.hasPermission('view_source');
$scope.canExecuteQuery = () => currentUser.hasPermission('execute_query') && !$scope.dataSource.view_only;
$scope.canForkQuery = () => currentUser.hasPermission('edit_query') && !$scope.dataSource.view_only;
$scope.canScheduleQuery = currentUser.hasPermission('schedule_query');
if ($route.current.locals.dataSources) {
$scope.dataSources = $route.current.locals.dataSources;
updateDataSources($route.current.locals.dataSources);
} else {
$scope.dataSources = DataSource.query(updateDataSources);
}
// in view mode, latest dataset is always visible
// source mode changes this behavior
$scope.showDataset = true;
$scope.showLog = false;
$scope.lockButton = (lock) => {
$scope.queryExecuting = lock;
};
$scope.showApiKey = () => {
$uibModal.open({
component: 'apiKeyDialog',
resolve: {
query: $scope.query,
},
});
};
$scope.duplicateQuery = () => {
// To prevent opening the same tab, name must be unique for each browser
const tabName = 'duplicatedQueryTab' + Math.random().toString();
$window.open('', tabName);
Query.fork({ id: $scope.query.id }, (newQuery) => {
const queryUrl = newQuery.getUrl(true);
$window.open(queryUrl, tabName);
});
};
$scope.saveTags = (tags) => {
$scope.query.tags = tags;
$scope.saveQuery({}, { tags: $scope.query.tags });
};
$scope.loadTags = () => getTags('api/queries/tags').then(tags => map(tags, t => t.name));
$scope.saveQuery = (customOptions, data) => {
let request = data;
if (request) {
// Don't save new query with partial data
if ($scope.query.isNew()) {
return $q.reject();
}
request.id = $scope.query.id;
request.version = $scope.query.version;
} else {
request = pick($scope.query, [
'schedule',
'query',
'id',
'description',
'name',
'data_source_id',
'options',
'latest_query_data_id',
'version',
'is_draft',
]);
}
const options = Object.assign(
{},
{
successMessage: 'Query saved',
errorMessage: 'Query could not be saved',
},
customOptions,
);
return Query.save(
request,
(updatedQuery) => {
toastr.success(options.successMessage);
$scope.query.version = updatedQuery.version;
},
(error) => {
if (error.status === 409) {
toastr.error(
'It seems like the query has been modified by another user. ' +
'Please copy/backup your changes and reload this page.',
{ autoDismiss: false },
);
} else {
toastr.error(options.errorMessage);
}
},
).$promise;
};
$scope.togglePublished = () => {
Events.record('toggle_published', 'query', $scope.query.id);
$scope.query.is_draft = !$scope.query.is_draft;
$scope.saveQuery(undefined, { is_draft: $scope.query.is_draft });
};
$scope.saveDescription = (desc) => {
$scope.query.description = desc;
Events.record('edit_description', 'query', $scope.query.id);
$scope.saveQuery(undefined, { description: $scope.query.description });
};
$scope.saveName = (name) => {
$scope.query.name = name;
Events.record('edit_name', 'query', $scope.query.id);
if ($scope.query.is_draft && clientConfig.autoPublishNamedQueries && $scope.query.name !== 'New Query') {
$scope.query.is_draft = false;
}
$scope.saveQuery(undefined, { name: $scope.query.name, is_draft: $scope.query.is_draft });
};
$scope.cancelExecution = () => {
$scope.cancelling = true;
$scope.queryResult.cancelExecution();
Events.record('cancel_execute', 'query', $scope.query.id);
};
$scope.archiveQuery = () => {
function archive() {
Query.delete(
{ id: $scope.query.id },
() => {
$scope.query.is_archived = true;
$scope.query.schedule = null;
},
() => {
toastr.error('Query could not be archived.');
},
);
}
const title = 'Archive Query';
const message =
'Are you sure you want to archive this query?<br/> All alerts and dashboard widgets created with its visualizations will be deleted.';
const confirm = { class: 'btn-warning', title: 'Archive' };
AlertDialog.open(title, message, confirm).then(archive);
};
$scope.updateDataSource = () => {
Events.record('update_data_source', 'query', $scope.query.id);
localStorage.lastSelectedDataSourceId = $scope.query.data_source_id;
$scope.query.latest_query_data = null;
$scope.query.latest_query_data_id = null;
if ($scope.query.id) {
Query.save(
{
id: $scope.query.id,
data_source_id: $scope.query.data_source_id,
latest_query_data_id: null,
},
(updatedQuery) => {
$scope.query.version = updatedQuery.version;
},
);
}
$scope.dataSource = find($scope.dataSources, ds => ds.id === $scope.query.data_source_id);
getSchema();
$scope.executeQuery();
};
$scope.setVisualizationTab = (visualization) => {
$scope.selectedTab = visualization.id;
$location.hash(visualization.id);
};
$scope.deleteVisualization = ($e, vis) => {
$e.preventDefault();
const title = undefined;
const message = `Are you sure you want to delete ${vis.name} ?`;
const confirm = { class: 'btn-danger', title: 'Delete' };
AlertDialog.open(title, message, confirm).then(() => {
Visualization.delete(
{ id: vis.id },
() => {
if ($scope.selectedTab === String(vis.id)) {
$scope.selectedTab = DEFAULT_TAB;
$location.hash($scope.selectedTab);
}
$scope.query.visualizations = $scope.query.visualizations.filter(v => vis.id !== v.id);
},
() => {
toastr.error("Error deleting visualization. Maybe it's used in a dashboard?");
},
);
});
};
$scope.$watch('query.name', () => {
Title.set($scope.query.name);
});
$scope.$watch('queryResult && queryResult.getData()', (data) => {
if (!data) {
return;
}
$scope.filters = $scope.queryResult.getFilters();
});
$scope.$watch('queryResult && queryResult.getStatus()', (status) => {
if (!status) {
return;
}
if (status === 'done') {
$scope.query.latest_query_data_id = $scope.queryResult.getId();
$scope.query.queryResult = $scope.queryResult;
Notifications.showNotification('Redash', `${$scope.query.name} updated.`);
} else if (status === 'failed') {
Notifications.showNotification('Redash', `${$scope.query.name} failed to run: ${$scope.queryResult.getError()}`);
}
if (status === 'done' || status === 'failed') {
$scope.lockButton(false);
}
if ($scope.queryResult.getLog() != null) {
$scope.showLog = true;
}
});
function getVisualization(visId) {
// eslint-disable-next-line eqeqeq
return find($scope.query.visualizations, item => item.id == visId);
}
$scope.openVisualizationEditor = (visId) => {
const visualization = getVisualization(visId);
function openModal() {
$uibModal.open({
windowClass: 'modal-xl',
component: 'editVisualizationDialog',
resolve: {
query: $scope.query,
visualization,
queryResult: $scope.queryResult,
onNewSuccess: () => $scope.setVisualizationTab,
},
});
}
if ($scope.query.isNew()) {
$scope.saveQuery().then((query) => {
// Because we have a path change, we need to "signal" the next page to
// open the visualization editor.
$location.path(query.getSourceLink()).hash('add');
});
} else {
openModal();
}
};
if ($location.hash() === 'add') {
$location.hash(null);
$scope.openVisualizationEditor();
}
const intervals = clientConfig.queryRefreshIntervals;
const allowedIntervals = Policy.getQueryRefreshIntervals();
$scope.refreshOptions = isArray(allowedIntervals) ? intersection(intervals, allowedIntervals) : intervals;
$scope.updateQueryMetadata = changes =>
$scope.$apply(() => {
$scope.query = Object.assign($scope.query, changes);
$scope.saveQuery();
});
$scope.showScheduleForm = false;
$scope.openScheduleForm = () => {
if (!$scope.canEdit || !$scope.canScheduleQuery) {
return;
}
$scope.showScheduleForm = true;
};
$scope.closeScheduleForm = () => {
$scope.$apply(() => {
$scope.showScheduleForm = false;
});
};
$scope.openAddToDashboardForm = (visId) => {
const visualization = getVisualization(visId);
$uibModal.open({
component: 'addToDashboardDialog',
size: 'sm',
resolve: {
query: $scope.query,
vis: visualization,
},
});
};
$scope.showEmbedDialog = (query, visId) => {
const visualization = getVisualization(visId);
$uibModal.open({
component: 'embedCodeDialog',
resolve: {
query,
visualization,
},
});
};
$scope.$watch(
() => $location.hash(),
(hash) => {
// eslint-disable-next-line eqeqeq
const exists = find($scope.query.visualizations, item => item.id == hash);
let visualization = minBy($scope.query.visualizations, viz => viz.id);
if (!isObject(visualization)) {
visualization = {};
}
$scope.selectedTab = (exists ? hash : visualization.id) || DEFAULT_TAB;
},
);
$scope.showManagePermissionsModal = () => {
$uibModal.open({
component: 'permissionsEditor',
resolve: {
aclUrl: { url: `api/queries/${$routeParams.queryId}/acl` },
owner: $scope.query.user,
},
});
};
}
export default function init(ngModule) {
ngModule.controller('QueryViewCtrl', QueryViewCtrl);
return {
'/queries/:queryId': {
template,
layout: 'fixed',
controller: 'QueryViewCtrl',
reloadOnSearch: false,
resolve: {
query: (Query, $route) => {
'ngInject';
return Query.get({ id: $route.current.params.queryId }).$promise;
},
},
},
};
}
init.init = true;