nytai commented on a change in pull request #10745:
URL:
https://github.com/apache/incubator-superset/pull/10745#discussion_r483295743
##########
File path: superset-frontend/src/views/CRUD/hooks.ts
##########
@@ -168,6 +168,167 @@ export function useListViewResource<D extends object =
any>(
};
}
+// In the same vein as above, a hook for viewing a single instance of a
resource (given id)
+interface SingleViewResourceState<D extends object = any> {
+ loading: boolean;
+ resource: D | null;
+ permissions: string[];
+}
+
+export function useSingleViewResource<D extends object = any>(
+ resourceName: string,
+ resourceLabel: string, // resourceLabel for translations
+ handleErrorMsg: (errorMsg: string) => void,
+) {
+ const [state, setState] = useState<SingleViewResourceState<D>>({
+ loading: false,
+ resource: null,
+ permissions: [],
+ });
+
+ function updateState(update: Partial<SingleViewResourceState<D>>) {
+ setState(currentState => ({ ...currentState, ...update }));
+ }
+
+ useEffect(() => {
+ SupersetClient.get({
+ endpoint: `/api/v1/${resourceName}/_info`,
+ }).then(
+ ({ json: infoJson = {} }) => {
+ updateState({
+ permissions: infoJson.permissions,
+ });
+ },
+ createErrorHandler(errMsg =>
+ handleErrorMsg(
+ t(
+ 'An error occurred while fetching %ss info: %s',
+ resourceLabel,
+ errMsg,
+ ),
+ ),
+ ),
+ );
+ }, []);
+
+ function hasPerm(perm: string) {
+ if (!state.permissions.length) {
+ return false;
+ }
+
+ return Boolean(state.permissions.find(p => p === perm));
+ }
+
+ const fetchResource = useCallback((resourceID: number) => {
+ // Set loading state
+ updateState({
+ loading: true,
+ });
+
+ return SupersetClient.get({
+ endpoint: `/api/v1/${resourceName}/${resourceID}`,
+ })
+ .then(
+ ({ json = {} }) => {
+ updateState({
+ resource: json.result,
+ });
+ },
+ createErrorHandler(errMsg =>
+ handleErrorMsg(
+ t(
+ 'An error occurred while fetching %ss: %s',
+ resourceLabel,
+ errMsg,
+ ),
+ ),
+ ),
+ )
+ .finally(() => {
+ updateState({ loading: false });
+ });
+ }, []);
+
+ const createResource = useCallback((resource: D) => {
+ // Set loading state
+ updateState({
+ loading: true,
+ });
+
+ return SupersetClient.post({
+ endpoint: `/api/v1/${resourceName}/`,
+ body: JSON.stringify(resource),
+ headers: { 'Content-Type': 'application/json' },
+ })
+ .then(
+ ({ json = {} }) => {
+ updateState({
+ resource: json.result,
+ });
+ },
+ createErrorHandler(errMsg =>
+ handleErrorMsg(
+ t(
+ 'An error occurred while fetching %ss: %s',
+ resourceLabel,
+ errMsg,
+ ),
+ ),
+ ),
+ )
+ .finally(() => {
+ updateState({ loading: false });
+ });
+ }, []);
+
+ const updateResource = useCallback((resourceID: number, resource: D) => {
+ // Set loading state
+ updateState({
+ loading: true,
+ });
+
+ return SupersetClient.put({
+ endpoint: `/api/v1/${resourceName}/${resourceID}`,
+ body: JSON.stringify(resource),
+ headers: { 'Content-Type': 'application/json' },
+ })
+ .then(
+ ({ json = {} }) => {
+ updateState({
+ resource: json.result,
+ });
+ },
+ createErrorHandler(errMsg =>
+ handleErrorMsg(
+ t(
+ 'An error occurred while fetching %ss: %s',
+ resourceLabel,
+ errMsg,
+ ),
+ ),
+ ),
+ )
+ .finally(() => {
+ updateState({ loading: false });
+ });
+ }, []);
+
+ return {
+ state: {
+ loading: state.loading,
+ resource: state.resource,
Review comment:
Perhaps out of scope for this PR, but it just occurred to me that it
would be good to also include and error state in these hooks, something like `{
hasError: boolean, error: Error, errorMsg: string }`
##########
File path: superset-frontend/src/views/CRUD/hooks.ts
##########
@@ -168,6 +168,167 @@ export function useListViewResource<D extends object =
any>(
};
}
+// In the same vein as above, a hook for viewing a single instance of a
resource (given id)
+interface SingleViewResourceState<D extends object = any> {
+ loading: boolean;
+ resource: D | null;
+ permissions: string[];
+}
+
+export function useSingleViewResource<D extends object = any>(
+ resourceName: string,
+ resourceLabel: string, // resourceLabel for translations
+ handleErrorMsg: (errorMsg: string) => void,
+) {
+ const [state, setState] = useState<SingleViewResourceState<D>>({
+ loading: false,
+ resource: null,
+ permissions: [],
+ });
+
+ function updateState(update: Partial<SingleViewResourceState<D>>) {
+ setState(currentState => ({ ...currentState, ...update }));
+ }
+
+ useEffect(() => {
+ SupersetClient.get({
+ endpoint: `/api/v1/${resourceName}/_info`,
+ }).then(
+ ({ json: infoJson = {} }) => {
+ updateState({
+ permissions: infoJson.permissions,
+ });
+ },
+ createErrorHandler(errMsg =>
+ handleErrorMsg(
+ t(
+ 'An error occurred while fetching %ss info: %s',
+ resourceLabel,
+ errMsg,
+ ),
+ ),
+ ),
+ );
+ }, []);
+
+ function hasPerm(perm: string) {
+ if (!state.permissions.length) {
+ return false;
+ }
+
+ return Boolean(state.permissions.find(p => p === perm));
+ }
+
+ const fetchResource = useCallback((resourceID: number) => {
+ // Set loading state
+ updateState({
+ loading: true,
+ });
+
+ return SupersetClient.get({
+ endpoint: `/api/v1/${resourceName}/${resourceID}`,
+ })
+ .then(
+ ({ json = {} }) => {
+ updateState({
+ resource: json.result,
+ });
+ },
+ createErrorHandler(errMsg =>
+ handleErrorMsg(
+ t(
+ 'An error occurred while fetching %ss: %s',
+ resourceLabel,
+ errMsg,
+ ),
+ ),
+ ),
+ )
+ .finally(() => {
+ updateState({ loading: false });
+ });
+ }, []);
+
+ const createResource = useCallback((resource: D) => {
+ // Set loading state
+ updateState({
+ loading: true,
+ });
+
+ return SupersetClient.post({
+ endpoint: `/api/v1/${resourceName}/`,
+ body: JSON.stringify(resource),
+ headers: { 'Content-Type': 'application/json' },
+ })
+ .then(
+ ({ json = {} }) => {
+ updateState({
+ resource: json.result,
+ });
+ },
+ createErrorHandler(errMsg =>
+ handleErrorMsg(
+ t(
+ 'An error occurred while fetching %ss: %s',
+ resourceLabel,
+ errMsg,
+ ),
+ ),
+ ),
+ )
+ .finally(() => {
+ updateState({ loading: false });
+ });
+ }, []);
+
+ const updateResource = useCallback((resourceID: number, resource: D) => {
+ // Set loading state
+ updateState({
+ loading: true,
+ });
+
+ return SupersetClient.put({
+ endpoint: `/api/v1/${resourceName}/${resourceID}`,
+ body: JSON.stringify(resource),
+ headers: { 'Content-Type': 'application/json' },
+ })
+ .then(
+ ({ json = {} }) => {
+ updateState({
+ resource: json.result,
+ });
+ },
+ createErrorHandler(errMsg =>
+ handleErrorMsg(
+ t(
+ 'An error occurred while fetching %ss: %s',
+ resourceLabel,
+ errMsg,
+ ),
+ ),
+ ),
+ )
+ .finally(() => {
+ updateState({ loading: false });
+ });
+ }, []);
+
+ return {
+ state: {
+ loading: state.loading,
+ resource: state.resource,
+ },
+ setResource: (update: D) =>
+ updateState({
+ resource: update,
+ }),
+ hasPerm,
Review comment:
is this necessary? Looks like this method and the permissions state
isn't being consumed. If so, we should remove it as it is making a unnecessary
network request to the `_info` endpoint.
##########
File path: superset-frontend/src/views/CRUD/data/database/DatabaseModal.tsx
##########
@@ -82,53 +116,147 @@ const DatabaseModal:
FunctionComponent<DatabaseModalProps> = ({
show,
database = null,
}) => {
- // const [disableSave, setDisableSave] = useState(true);
- const [disableSave] = useState<boolean>(true);
- const [db, setDB] = useState<Partial<DatabaseObject> | null>(null);
+ const [disableSave, setDisableSave] = useState<boolean>(true);
+ const [db, setDB] = useState<DatabaseObject | null>(null);
const [isHidden, setIsHidden] = useState<boolean>(true);
+ const isEditMode = database !== null;
+
+ // Database fetch logic
+ const {
+ state: { loading: dbLoading, resource: dbFetched },
+ fetchResource,
+ createResource,
+ updateResource,
+ } = useSingleViewResource<DatabaseObject>(
+ 'database',
+ t('database'),
+ addDangerToast,
+ );
+
// Functions
const hide = () => {
setIsHidden(true);
onHide();
};
const onSave = () => {
- if (onDatabaseAdd) {
- onDatabaseAdd();
- }
+ if (isEditMode) {
+ // Edit
+ const update: DatabaseObject = {
+ database_name: db ? db.database_name : '',
+ sqlalchemy_uri: db ? db.sqlalchemy_uri : '',
+ ...db,
+ };
+
+ // Need to clean update object
+ if (update.id) {
+ delete update.id;
+ }
+
+ if (!update.cache_timeout) {
+ update.cache_timeout = '0';
+ }
- hide();
+ if (!update.encrypted_extra) {
+ update.encrypted_extra = '';
+ }
+
+ if (!update.force_ctas_schema) {
+ update.force_ctas_schema = '';
+ }
+
+ if (!update.server_cert) {
+ update.server_cert = '';
+ }
+
+ if (db && db.id) {
+ updateResource(db.id, update).then(() => {
+ if (onDatabaseAdd) {
+ onDatabaseAdd();
+ }
+
+ hide();
+ });
+ }
+ } else if (db) {
+ // Create
+ createResource(db).then(() => {
+ if (onDatabaseAdd) {
+ onDatabaseAdd();
+ }
+
+ hide();
+ });
+ }
};
const onInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const target = event.target;
const data = {
database_name: db ? db.database_name : '',
- uri: db ? db.uri : '',
+ sqlalchemy_uri: db ? db.sqlalchemy_uri : '',
...db,
};
- data[target.name] = target.value;
+ if (target.type === 'checkbox') {
+ data[target.name] = target.checked;
+ } else {
+ data[target.name] = target.value;
+ }
setDB(data);
};
- const isEditMode = database !== null;
+ const onTextChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
+ const target = event.target;
+ const data = {
+ database_name: db ? db.database_name : '',
+ sqlalchemy_uri: db ? db.sqlalchemy_uri : '',
+ ...db,
+ };
+
+ data[target.name] = target.value;
+ setDB(data);
+ };
+
+ const validate = () => {
+ if (
+ db &&
+ db.database_name.length &&
+ db.sqlalchemy_uri &&
+ db.sqlalchemy_uri.length
+ ) {
+ setDisableSave(false);
+ } else {
+ setDisableSave(true);
+ }
+ };
// Initialize
if (
isEditMode &&
(!db || !db.id || (database && database.id !== db.id) || (isHidden &&
show))
) {
- setDB(database);
+ if (database && database.id !== null && !dbLoading) {
+ const id = database.id || 0;
+
+ fetchResource(id).then(() => {
+ setDB(dbFetched);
+ });
+ }
} else if (!isEditMode && (!db || db.id || (isHidden && show))) {
setDB({
database_name: '',
- uri: '',
+ sqlalchemy_uri: '',
});
}
+ // Validation
+ useEffect(() => {
+ validate();
Review comment:
Do we really need to call this on every render? It's no an expensive
operation now, but it could become one. Would adding a dependency on `db` be a
sensible optimization?
##########
File path: superset-frontend/src/views/CRUD/data/database/DatabaseModal.tsx
##########
@@ -203,16 +332,322 @@ const DatabaseModal:
FunctionComponent<DatabaseModalProps> = ({
</StyledInputContainer>
</Tabs.TabPane>
<Tabs.TabPane tab={<span>{t('Performance')}</span>} key="2">
- Performance Form Data
+ <StyledInputContainer>
+ <div className="label">{t('Chart Cache Timeout')}</div>
+ <div className="input-container">
+ <input
+ type="number"
+ name="cache_timeout"
+ value={db ? db.cache_timeout || '' : ''}
+ placeholder={t('Chart Cache Timeout')}
+ onChange={onInputChange}
+ />
+ </div>
+ <div className="helper">
+ {t(
+ 'Duration (in seconds) of the caching timeout for charts of
this database.',
+ )}
+ {t(' A timeout of 0 indicates that the cache never expires.')}
+ {t(' Note this defaults to the global timeout if undefined.')}
+ </div>
+ </StyledInputContainer>
+ <StyledInputContainer>
+ <div className="input-container">
+ <IndeterminateCheckbox
+ id="allow_run_async"
+ indeterminate={false}
+ checked={db ? !!db.allow_run_async : false}
+ onChange={onInputChange}
+ />
+ <div>{t('Asynchronous Query Execution')}</div>
+ <InfoTooltipWithTrigger
+ label="aqe"
+ tooltip={
+ t(
+ 'Operate the database in asynchronous mode, meaning that
the queries ',
+ ) +
+ t(
+ 'are executed on remote workers as opposed to on the web
server itself. ',
+ ) +
+ t(
+ 'This assumes that you have a Celery worker setup as well
as a results ',
+ ) +
+ t(
+ 'backend. Refer to the installation docs for more
information.',
Review comment:
I'm not sure translations work like this. Each of these will be
extracted as separate strings and not all language adhere to the same grammar
rules. I think each of these sentences needs to be wrapped in a single `t` so
they're extracted as a single blob, I think something like
```js
t('............very long string ...............' +
'.............another long string ..........' +
...
)
```
should work.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]