-
Notifications
You must be signed in to change notification settings - Fork 14.1k
/
DatasourceEditor.jsx
999 lines (951 loc) · 31.1 KB
/
DatasourceEditor.jsx
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
*
* http://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.
*/
import React from 'react';
import PropTypes from 'prop-types';
import { Alert, Badge, Col, Radio, Well } from 'react-bootstrap';
import shortid from 'shortid';
import { styled, SupersetClient, t } from '@superset-ui/core';
import Tabs from 'src/common/components/Tabs';
import Button from 'src/components/Button';
import CertifiedIconWithTooltip from 'src/components/CertifiedIconWithTooltip';
import DatabaseSelector from 'src/components/DatabaseSelector';
import Label from 'src/components/Label';
import Loading from 'src/components/Loading';
import TableSelector from 'src/components/TableSelector';
import EditableTitle from 'src/components/EditableTitle';
import getClientErrorObject from 'src/utils/getClientErrorObject';
import CheckboxControl from 'src/explore/components/controls/CheckboxControl';
import TextControl from 'src/explore/components/controls/TextControl';
import SelectControl from 'src/explore/components/controls/SelectControl';
import TextAreaControl from 'src/explore/components/controls/TextAreaControl';
import SelectAsyncControl from 'src/explore/components/controls/SelectAsyncControl';
import SpatialControl from 'src/explore/components/controls/SpatialControl';
import CollectionTable from 'src/CRUD/CollectionTable';
import Fieldset from 'src/CRUD/Fieldset';
import Field from 'src/CRUD/Field';
import withToasts from 'src/messageToasts/enhancers/withToasts';
const DatasourceContainer = styled.div`
.change-warning {
margin: 16px 10px 0;
color: ${({ theme }) => theme.colors.warning.base};
}
.change-warning .bold {
font-weight: ${({ theme }) => theme.typography.weights.bold};
}
`;
const FlexRowContainer = styled.div`
align-items: center;
display: flex;
> svg {
margin-right: ${({ theme }) => theme.gridUnit}px;
}
`;
const checkboxGenerator = (d, onChange) => (
<CheckboxControl value={d} onChange={onChange} />
);
const DATA_TYPES = ['STRING', 'NUMERIC', 'DATETIME'];
const DATASOURCE_TYPES_ARR = [
{ key: 'physical', label: t('Physical (table or view)') },
{ key: 'virtual', label: t('Virtual (SQL)') },
];
const DATASOURCE_TYPES = {};
DATASOURCE_TYPES_ARR.forEach(o => {
DATASOURCE_TYPES[o.key] = o;
});
function CollectionTabTitle({ title, collection }) {
return (
<div data-test={`collection-tab-${title}`}>
{title} <Badge>{collection ? collection.length : 0}</Badge>
</div>
);
}
CollectionTabTitle.propTypes = {
title: PropTypes.string,
collection: PropTypes.array,
};
function ColumnCollectionTable({
columns,
onChange,
editableColumnName,
showExpression,
allowAddItem,
allowEditDataType,
itemGenerator,
}) {
return (
<CollectionTable
collection={columns}
tableColumns={['column_name', 'type', 'is_dttm', 'filterable', 'groupby']}
allowDeletes
allowAddItem={allowAddItem}
itemGenerator={itemGenerator}
expandFieldset={
<FormContainer>
<Fieldset compact>
{showExpression && (
<Field
fieldKey="expression"
label={t('SQL Expression')}
control={
<TextAreaControl
language="markdown"
offerEditInModal={false}
/>
}
/>
)}
<Field
fieldKey="verbose_name"
label={t('Label')}
control={
<TextControl
controlId="verbose_name"
placeholder={t('Label')}
/>
}
/>
<Field
fieldKey="description"
label={t('Description')}
control={
<TextControl
controlId="description"
placeholder={t('Description')}
/>
}
/>
{allowEditDataType && (
<Field
fieldKey="type"
label={t('Data Type')}
control={
<SelectControl choices={DATA_TYPES} name="type" freeForm />
}
/>
)}
<Field
fieldKey="python_date_format"
label={t('Datetime Format')}
description={
/* Note the fragmented translations may not work. */
<div>
{t('The pattern of timestamp format. For strings use ')}
<a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior">
{t('python datetime string pattern')}
</a>
{t(' expression which needs to adhere to the ')}
<a href="https://en.wikipedia.org/wiki/ISO_8601">
{t('ISO 8601')}
</a>
{t(` standard to ensure that the lexicographical ordering
coincides with the chronological ordering. If the
timestamp format does not adhere to the ISO 8601 standard
you will need to define an expression and type for
transforming the string into a date or timestamp. Note
currently time zones are not supported. If time is stored
in epoch format, put \`epoch_s\` or \`epoch_ms\`. If no pattern
is specified we fall back to using the optional defaults on a per
database/column name level via the extra parameter.`)}
</div>
}
control={
<TextControl
controlId="python_date_format"
placeholder="%Y/%m/%d"
/>
}
/>
</Fieldset>
</FormContainer>
}
columnLabels={{
column_name: t('Column'),
type: t('Data Type'),
groupby: t('Is Dimension'),
is_dttm: t('Is Temporal'),
filterable: t('Is Filterable'),
}}
onChange={onChange}
itemRenderers={{
column_name: (v, onItemChange) =>
editableColumnName ? (
<EditableTitle canEdit title={v} onSaveTitle={onItemChange} />
) : (
v
),
type: d => <Label>{d}</Label>,
is_dttm: checkboxGenerator,
filterable: checkboxGenerator,
groupby: checkboxGenerator,
}}
/>
);
}
ColumnCollectionTable.propTypes = {
columns: PropTypes.array.isRequired,
onChange: PropTypes.func.isRequired,
editableColumnName: PropTypes.bool,
showExpression: PropTypes.bool,
allowAddItem: PropTypes.bool,
allowEditDataType: PropTypes.bool,
itemGenerator: PropTypes.func,
};
ColumnCollectionTable.defaultProps = {
editableColumnName: false,
showExpression: false,
allowAddItem: false,
allowEditDataType: false,
itemGenerator: () => ({
column_name: '<new column>',
filterable: true,
groupby: true,
}),
};
function StackedField({ label, formElement }) {
return (
<div>
<div>
<strong>{label}</strong>
</div>
<div>{formElement}</div>
</div>
);
}
StackedField.propTypes = {
label: PropTypes.string,
formElement: PropTypes.node,
};
function FormContainer({ children }) {
return <Well style={{ marginTop: 20 }}>{children}</Well>;
}
FormContainer.propTypes = {
children: PropTypes.node,
};
const propTypes = {
datasource: PropTypes.object.isRequired,
onChange: PropTypes.func,
addSuccessToast: PropTypes.func.isRequired,
addDangerToast: PropTypes.func.isRequired,
};
const defaultProps = {
onChange: () => {},
};
class DatasourceEditor extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
datasource: props.datasource,
errors: [],
isDruid:
props.datasource.type === 'druid' ||
props.datasource.datasource_type === 'druid',
isSqla:
props.datasource.datasource_type === 'table' ||
props.datasource.type === 'table',
databaseColumns: props.datasource.columns.filter(col => !col.expression),
calculatedColumns: props.datasource.columns.filter(
col => !!col.expression,
),
metadataLoading: false,
activeTabKey: 0,
datasourceType: props.datasource.sql
? DATASOURCE_TYPES.virtual.key
: DATASOURCE_TYPES.physical.key,
};
this.onChange = this.onChange.bind(this);
this.onDatasourcePropChange = this.onDatasourcePropChange.bind(this);
this.onDatasourceChange = this.onDatasourceChange.bind(this);
this.syncMetadata = this.syncMetadata.bind(this);
this.setColumns = this.setColumns.bind(this);
this.validateAndChange = this.validateAndChange.bind(this);
this.handleTabSelect = this.handleTabSelect.bind(this);
}
onChange() {
// Emptying SQL if "Physical" radio button is selected
// Currently the logic to know whether the source is
// physical or virtual is based on whether SQL is empty or not.
const { datasourceType, datasource } = this.state;
const sql =
datasourceType === DATASOURCE_TYPES.physical.key ? '' : datasource.sql;
const newDatasource = {
...this.state.datasource,
sql,
columns: [...this.state.databaseColumns, ...this.state.calculatedColumns],
};
this.props.onChange(newDatasource, this.state.errors);
}
onDatasourceChange(datasource) {
this.setState({ datasource }, this.validateAndChange);
}
onDatasourcePropChange(attr, value) {
const datasource = { ...this.state.datasource, [attr]: value };
this.setState(
prevState => ({ datasource: { ...prevState.datasource, [attr]: value } }),
this.onDatasourceChange(datasource),
);
}
onDatasourceTypeChange(datasourceType) {
this.setState({ datasourceType });
}
setColumns(obj) {
this.setState(obj, this.validateAndChange);
}
validateAndChange() {
this.validate(this.onChange);
}
updateColumns(cols) {
const { databaseColumns } = this.state;
const databaseColumnNames = cols.map(col => col.name);
const currentCols = databaseColumns.reduce(
(agg, col) => ({
...agg,
[col.column_name]: col,
}),
{},
);
const finalColumns = [];
const results = {
added: [],
modified: [],
removed: databaseColumns
.map(col => col.column_name)
.filter(col => !databaseColumnNames.includes(col)),
};
cols.forEach(col => {
const currentCol = currentCols[col.name];
if (!currentCol) {
// new column
finalColumns.push({
id: shortid.generate(),
column_name: col.name,
type: col.type,
groupby: true,
filterable: true,
});
results.added.push(col.name);
} else if (currentCol.type !== col.type) {
// modified column
finalColumns.push({
...currentCol,
type: col.type,
});
results.modified.push(col.name);
} else {
// unchanged
finalColumns.push(currentCol);
}
});
if (
results.added.length ||
results.modified.length ||
results.removed.length
) {
this.setColumns({ databaseColumns: finalColumns });
}
return results;
}
syncMetadata() {
const { datasource } = this.state;
const endpoint = `/datasource/external_metadata/${
datasource.type || datasource.datasource_type
}/${datasource.id}/`;
this.setState({ metadataLoading: true });
SupersetClient.get({ endpoint })
.then(({ json }) => {
const results = this.updateColumns(json);
if (results.modified.length)
this.props.addSuccessToast(
t('Modified columns: %s', results.modified.join(', ')),
);
if (results.removed.length)
this.props.addSuccessToast(
t('Removed columns: %s', results.removed.join(', ')),
);
if (results.added.length)
this.props.addSuccessToast(
t('New columns added: %s', results.added.join(', ')),
);
this.props.addSuccessToast(t('Metadata has been synced'));
this.setState({ metadataLoading: false });
})
.catch(response =>
getClientErrorObject(response).then(({ error, statusText }) => {
this.props.addDangerToast(
error || statusText || t('An error has occurred'),
);
this.setState({ metadataLoading: false });
}),
);
}
findDuplicates(arr, accessor) {
const seen = {};
const dups = [];
arr.forEach(obj => {
const item = accessor(obj);
if (item in seen) {
dups.push(item);
} else {
seen[item] = null;
}
});
return dups;
}
validate(callback) {
let errors = [];
let dups;
const { datasource } = this.state;
// Looking for duplicate column_name
dups = this.findDuplicates(datasource.columns, obj => obj.column_name);
errors = errors.concat(
dups.map(name => t('Column name [%s] is duplicated', name)),
);
// Looking for duplicate metric_name
dups = this.findDuplicates(datasource.metrics, obj => obj.metric_name);
errors = errors.concat(
dups.map(name => t('Metric name [%s] is duplicated', name)),
);
// Making sure calculatedColumns have an expression defined
const noFilterCalcCols = this.state.calculatedColumns.filter(
col => !col.expression && !col.json,
);
errors = errors.concat(
noFilterCalcCols.map(col =>
t('Calculated column [%s] requires an expression', col.column_name),
),
);
this.setState({ errors }, callback);
}
handleTabSelect(activeTabKey) {
this.setState({ activeTabKey });
}
renderSettingsFieldset() {
const { datasource } = this.state;
return (
<Fieldset
title={t('Basic')}
item={datasource}
onChange={this.onDatasourceChange}
>
<Field
fieldKey="description"
label={t('Description')}
control={
<TextAreaControl language="markdown" offerEditInModal={false} />
}
/>
<Field
fieldKey="default_endpoint"
label={t('Default URL')}
description={t(
'Default URL to redirect to when accessing from the dataset list page',
)}
control={<TextControl controlId="default_endpoint" />}
/>
<Field
fieldKey="filter_select_enabled"
label={t('Autocomplete filters')}
description={t('Whether to populate autocomplete filters options')}
control={<CheckboxControl />}
/>
{this.state.isSqla && (
<Field
fieldKey="fetch_values_predicate"
label={t('Autocomplete Query Predicate')}
description={t(
'When using "Autocomplete filters", this can be used to improve performance ' +
'of the query fetching the values. Use this option to apply a ' +
'predicate (WHERE clause) to the query selecting the distinct ' +
'values from the table. Typically the intent would be to limit the scan ' +
'by applying a relative time filter on a partitioned or indexed time-related field.',
)}
control={<TextControl controlId="fetch_values_predicate" />}
/>
)}
{this.state.isSqla && (
<Field
fieldKey="extra"
label={t('Extra')}
description={t(
'Extra data to specify table metadata. Currently supports ' +
'certification data of the format: `{ "certification": { "certified_by": ' +
'"Data Platform Team", "details": "This table is the source of truth." ' +
'} }`.',
)}
control={
<TextAreaControl
controlId="extra"
language="json"
offerEditInModal={false}
/>
}
/>
)}
<Field
fieldKey="owners"
label={t('Owners')}
description={t('Owners of the dataset')}
control={
<SelectAsyncControl
dataEndpoint="api/v1/dataset/related/owners"
multi
mutator={data =>
data.result.map(pk => ({
value: pk.value,
label: `${pk.text}`,
}))
}
/>
}
controlProps={{}}
/>
</Fieldset>
);
}
renderAdvancedFieldset() {
const { datasource } = this.state;
return (
<Fieldset
title={t('Advanced')}
item={datasource}
onChange={this.onDatasourceChange}
>
<Field
fieldKey="cache_timeout"
label={t('Cache Timeout')}
description={t(
'The duration of time in seconds before the cache is invalidated',
)}
control={<TextControl controlId="cache_timeout" />}
/>
<Field
fieldKey="offset"
label={t('Hours offset')}
control={<TextControl controlId="offset" />}
/>
{this.state.isSqla && (
<Field
fieldKey="template_params"
label={t('Template parameters')}
description={t(
'A set of parameters that become available in the query using Jinja templating syntax',
)}
control={<TextControl controlId="template_params" />}
/>
)}
</Fieldset>
);
}
renderSpatialTab() {
const { datasource } = this.state;
const { spatials, all_cols: allCols } = datasource;
return (
<Tabs.TabPane
tab={<CollectionTabTitle collection={spatials} title={t('Spatial')} />}
key={4}
>
<CollectionTable
tableColumns={['name', 'config']}
onChange={this.onDatasourcePropChange.bind(this, 'spatials')}
itemGenerator={() => ({
name: '<new spatial>',
type: '<no type>',
config: null,
})}
collection={spatials}
allowDeletes
itemRenderers={{
name: (d, onChange) => (
<EditableTitle canEdit title={d} onSaveTitle={onChange} />
),
config: (v, onChange) => (
<SpatialControl value={v} onChange={onChange} choices={allCols} />
),
}}
/>
</Tabs.TabPane>
);
}
renderSourceFieldset() {
const { datasource } = this.state;
return (
<div>
<div className="m-l-10 m-t-20 m-b-10">
{DATASOURCE_TYPES_ARR.map(type => (
<Radio
key={type.key}
value={type.key}
inline
onChange={this.onDatasourceTypeChange.bind(this, type.key)}
checked={this.state.datasourceType === type.key}
>
{type.label}
</Radio>
))}
</div>
<hr />
<Fieldset item={datasource} onChange={this.onDatasourceChange} compact>
{this.state.datasourceType === DATASOURCE_TYPES.virtual.key && (
<div>
{this.state.isSqla && (
<>
<Field
fieldKey="databaseSelector"
label={t('virtual')}
control={
<DatabaseSelector
dbId={datasource.database.id}
schema={datasource.schema}
onSchemaChange={schema =>
this.onDatasourcePropChange('schema', schema)
}
onDbChange={database =>
this.onDatasourcePropChange('database', database)
}
formMode={false}
handleError={this.props.addDangerToast}
/>
}
/>
<Field
fieldKey="table_name"
label={t('dataset name')}
control={
<TextControl
controlId="table_name"
onChange={table => {
this.onDatasourcePropChange('table_name', table);
}}
placeholder={t('dataset name')}
/>
}
/>
<Field
fieldKey="sql"
label={t('SQL')}
description={t(
'When specifying SQL, the datasource acts as a view. ' +
'Superset will use this statement as a subquery while grouping and filtering ' +
'on the generated parent queries.',
)}
control={
<TextAreaControl
language="sql"
offerEditInModal={false}
minLines={25}
maxLines={25}
/>
}
/>
</>
)}
{this.state.isDruid && (
<Field
fieldKey="json"
label={t('JSON')}
description={
<div>
{t('The JSON metric or post aggregation definition.')}
</div>
}
control={
<TextAreaControl language="json" offerEditInModal={false} />
}
/>
)}
</div>
)}
{this.state.datasourceType === DATASOURCE_TYPES.physical.key && (
<Col md={6}>
{this.state.isSqla && (
<Field
fieldKey="tableSelector"
label={t('Physical')}
control={
<TableSelector
clearable={false}
dbId={datasource.database.id}
handleError={this.props.addDangerToast}
schema={datasource.schema}
sqlLabMode={false}
tableName={datasource.table_name}
onSchemaChange={schema =>
this.onDatasourcePropChange('schema', schema)
}
onDbChange={database =>
this.onDatasourcePropChange('database', database)
}
onTableChange={table => {
this.onDatasourcePropChange('table_name', table);
}}
isDatabaseSelectEnabled={false}
/>
}
description={t(
'The pointer to a physical table (or view). Keep in mind that the chart is ' +
'associated to this Superset logical table, and this logical table points ' +
'the physical table referenced here.',
)}
/>
)}
</Col>
)}
</Fieldset>
</div>
);
}
renderErrors() {
if (this.state.errors.length > 0) {
return (
<Alert bsStyle="danger">
{this.state.errors.map(err => (
<div key={err}>{err}</div>
))}
</Alert>
);
}
return null;
}
renderMetricCollection() {
return (
<CollectionTable
tableColumns={['metric_name', 'verbose_name', 'expression']}
columnLabels={{
metric_name: t('Metric'),
verbose_name: t('Label'),
expression: t('SQL Expression'),
}}
expandFieldset={
<FormContainer>
<Fieldset compact>
<Field
fieldKey="verbose_name"
label={t('Label')}
control={<TextControl controlId="verbose_name" />}
/>
<Field
fieldKey="description"
label={t('Description')}
control={
<TextControl
controlId="description"
placeholder={t('Description')}
/>
}
/>
<Field
fieldKey="d3format"
label={t('D3 Format')}
control={
<TextControl controlId="d3format" placeholder="%y/%m/%d" />
}
/>
<Field
label={t('Warning Message')}
fieldKey="warning_text"
description={t(
'Warning message to display in the metric selector',
)}
control={
<TextControl
controlId="warning_text"
placeholder={t('Warning Message')}
/>
}
/>
<Field
label={t('Certified By')}
fieldKey="certified_by"
description={t(
'Person or group that has certified this metric',
)}
control={
<TextControl
controlId="certified_by"
placeholder={t('Certified By')}
/>
}
/>
<Field
label={t('Certification Details')}
fieldKey="certification_details"
description={t('Details of the certification')}
control={
<TextControl
controlId="certification_details"
placeholder={t('Certification Details')}
/>
}
/>
</Fieldset>
</FormContainer>
}
collection={this.state.datasource.metrics}
allowAddItem
onChange={this.onDatasourcePropChange.bind(this, 'metrics')}
itemGenerator={() => ({
metric_name: '<new metric>',
verbose_name: '',
expression: '',
})}
itemRenderers={{
metric_name: (v, onChange, _, record) => (
<FlexRowContainer>
{record.is_certified && (
<CertifiedIconWithTooltip
certifiedBy={record.certified_by}
details={record.certification_details}
/>
)}
<EditableTitle canEdit title={v} onSaveTitle={onChange} />
</FlexRowContainer>
),
verbose_name: (v, onChange) => (
<EditableTitle canEdit title={v} onSaveTitle={onChange} />
),
expression: (v, onChange) => (
<EditableTitle
canEdit
title={v}
onSaveTitle={onChange}
extraClasses={['datasource-sql-expression']}
multiLine
/>
),
description: (v, onChange, label) => (
<StackedField
label={label}
formElement={<TextControl value={v} onChange={onChange} />}
/>
),
d3format: (v, onChange, label) => (
<StackedField
label={label}
formElement={<TextControl value={v} onChange={onChange} />}
/>
),
}}
allowDeletes
/>
);
}
render() {
const { datasource, activeTabKey } = this.state;
return (
<DatasourceContainer>
{this.renderErrors()}
<div className="m-t-10">
<Alert bsStyle="warning">
<strong>{t('Be careful.')} </strong>
{t(
'Changing these settings will affect all charts using this dataset, including charts owned by other people.',
)}
</Alert>
</div>
<Tabs
fullWidth={false}
id="table-tabs"
data-test="edit-dataset-tabs"
onChange={this.handleTabSelect}
defaultActiveKey={activeTabKey}
>
<Tabs.TabPane key={0} tab={t('Source')}>
{this.renderSourceFieldset()}
</Tabs.TabPane>
<Tabs.TabPane
tab={
<CollectionTabTitle
collection={datasource.metrics}
title={t('Metrics')}
/>
}
key={1}
>
{this.renderMetricCollection()}
</Tabs.TabPane>
<Tabs.TabPane
tab={
<CollectionTabTitle
collection={this.state.databaseColumns}
title={t('Columns')}
/>
}
key={2}
>
<div>
<ColumnCollectionTable
columns={this.state.databaseColumns}
onChange={databaseColumns =>
this.setColumns({ databaseColumns })
}
/>
<Button
buttonStyle="primary"
onClick={this.syncMetadata}
className="sync-from-source"
>
{t('Sync columns from source')}
</Button>
{this.state.metadataLoading && <Loading />}
</div>
</Tabs.TabPane>
<Tabs.TabPane
tab={
<CollectionTabTitle
collection={this.state.calculatedColumns}
title={t('Calculated Columns')}
/>
}
key={3}
>
<ColumnCollectionTable
columns={this.state.calculatedColumns}
onChange={calculatedColumns =>
this.setColumns({ calculatedColumns })
}
editableColumnName
showExpression
allowAddItem
allowEditDataType
itemGenerator={() => ({
column_name: '<new column>',
filterable: true,
groupby: true,
expression: '<enter SQL expression here>',
__expanded: true,
})}
/>
</Tabs.TabPane>
<Tabs.TabPane key={4} tab={t('Settings')}>
<div>
<Col md={6}>
<FormContainer>{this.renderSettingsFieldset()}</FormContainer>
</Col>
<Col md={6}>
<FormContainer>{this.renderAdvancedFieldset()}</FormContainer>
</Col>
</div>
</Tabs.TabPane>
</Tabs>
</DatasourceContainer>
);
}
}
DatasourceEditor.defaultProps = defaultProps;
DatasourceEditor.propTypes = propTypes;
export default withToasts(DatasourceEditor);