You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by di...@apache.org on 2025/06/12 12:38:23 UTC
(superset) branch master updated: feat(DatasourceEditor): Format sql shortcut and bigger table (#33709)
This is an automated email from the ASF dual-hosted git repository.
diegopucci pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new e6af4ea126 feat(DatasourceEditor): Format sql shortcut and bigger table (#33709)
e6af4ea126 is described below
commit e6af4ea126058052506e5437cbe90f9c5f2192d0
Author: Mehmet Salih Yavuz <sa...@proton.me>
AuthorDate: Thu Jun 12 15:38:17 2025 +0300
feat(DatasourceEditor): Format sql shortcut and bigger table (#33709)
---
.../src/components/Datasource/DatasourceEditor.jsx | 95 ++++++++++++++++++++--
.../src/components/Icons/AntdEnhanced.tsx | 2 +
superset-frontend/src/database/actions.ts | 22 ++++-
superset-frontend/src/database/reducers.ts | 7 ++
.../components/controls/TextAreaControl.jsx | 12 +++
5 files changed, 132 insertions(+), 6 deletions(-)
diff --git a/superset-frontend/src/components/Datasource/DatasourceEditor.jsx b/superset-frontend/src/components/Datasource/DatasourceEditor.jsx
index 9723e82587..4556b178d7 100644
--- a/superset-frontend/src/components/Datasource/DatasourceEditor.jsx
+++ b/superset-frontend/src/components/Datasource/DatasourceEditor.jsx
@@ -54,8 +54,13 @@ import SpatialControl from 'src/explore/components/controls/SpatialControl';
import withToasts from 'src/components/MessageToasts/withToasts';
import { Icons } from 'src/components/Icons';
import CurrencyControl from 'src/explore/components/controls/CurrencyControl';
-import { executeQuery, resetDatabaseState } from 'src/database/actions';
+import {
+ executeQuery,
+ formatQuery,
+ resetDatabaseState,
+} from 'src/database/actions';
import { connect } from 'react-redux';
+import Mousetrap from 'mousetrap';
import CollectionTable from './CollectionTable';
import Fieldset from './Fieldset';
import Field from './Field';
@@ -640,6 +645,7 @@ class DatasourceEditor extends PureComponent {
this.setColumns = this.setColumns.bind(this);
this.validateAndChange = this.validateAndChange.bind(this);
this.handleTabSelect = this.handleTabSelect.bind(this);
+ this.formatSql = this.formatSql.bind(this);
this.currencies = ensureIsArray(props.currencies).map(currencyCode => ({
value: currencyCode,
label: `${getCurrencySymbol({
@@ -715,6 +721,27 @@ class DatasourceEditor extends PureComponent {
});
}
+ async onQueryFormat() {
+ const { datasource } = this.state;
+ if (!datasource.sql || !this.state.isEditMode) {
+ return;
+ }
+
+ try {
+ const response = await this.props.formatQuery(datasource.sql);
+ this.onDatasourcePropChange('sql', response.json.result);
+ this.props.addSuccessToast(t('SQL was formatted'));
+ } catch (error) {
+ const { error: clientError, statusText } =
+ await getClientErrorObject(error);
+ this.props.addDangerToast(
+ clientError ||
+ statusText ||
+ t('An error occurred while formatting SQL'),
+ );
+ }
+ }
+
getSQLLabUrl() {
const queryParams = new URLSearchParams({
dbid: this.state.datasource.database.id,
@@ -738,6 +765,31 @@ class DatasourceEditor extends PureComponent {
});
}
+ async formatSql() {
+ const { datasource } = this.state;
+ if (!datasource.sql) {
+ return;
+ }
+
+ try {
+ const response = await SupersetClient.post({
+ endpoint: '/api/v1/sql/format',
+ body: JSON.stringify({ sql: datasource.sql }),
+ headers: { 'Content-Type': 'application/json' },
+ });
+ this.onDatasourcePropChange('sql', response.json.result);
+ this.props.addSuccessToast(t('SQL was formatted'));
+ } catch (error) {
+ const { error: clientError, statusText } =
+ await getClientErrorObject(error);
+ this.props.addDangerToast(
+ clientError ||
+ statusText ||
+ t('An error occurred while formatting SQL'),
+ );
+ }
+ }
+
async syncMetadata() {
const { datasource } = this.state;
this.setState({ metadataLoading: true });
@@ -1187,6 +1239,16 @@ class DatasourceEditor extends PureComponent {
<>
{this.renderSqlEditorOverlay()}
<TextAreaControl
+ hotkeys={[
+ {
+ name: 'formatQuery',
+ key: 'ctrl+shift+f',
+ descr: t('Format SQL query'),
+ func: () => {
+ this.onQueryFormat();
+ },
+ },
+ ]}
language="sql"
offerEditInModal={false}
minLines={10}
@@ -1197,6 +1259,16 @@ class DatasourceEditor extends PureComponent {
</>
) : (
<TextAreaControl
+ hotkeys={[
+ {
+ name: 'formatQuery',
+ key: 'ctrl+shift+f',
+ descr: t('Format SQL query'),
+ func: () => {
+ this.onQueryFormat();
+ },
+ },
+ ]}
language="sql"
offerEditInModal={false}
minLines={10}
@@ -1213,6 +1285,7 @@ class DatasourceEditor extends PureComponent {
right: 0;
top: 0;
z-index: 2;
+ display: flex;
`}
>
<Button
@@ -1220,15 +1293,15 @@ class DatasourceEditor extends PureComponent {
tooltip={t('Open SQL Lab in a new tab')}
css={floatingButtonCss}
size="small"
+ onClick={() => {
+ this.openOnSqlLab();
+ }}
>
<Icons.ExportOutlined
iconSize="s"
css={theme => ({
color: theme.colors.primary.dark1,
})}
- onClick={() => {
- this.openOnSqlLab();
- }}
/>
</Button>
<Button
@@ -1287,10 +1360,10 @@ class DatasourceEditor extends PureComponent {
orderedColumnKeys={this.props.database?.queryResult.columns.map(
col => col.column_name,
)}
- height={100}
expandedColumns={
this.props.database?.queryResult.expandedColumns
}
+ height={300}
allowHTML
/>
</>
@@ -1676,7 +1749,18 @@ class DatasourceEditor extends PureComponent {
);
}
+ componentDidMount() {
+ Mousetrap.bind('ctrl+shift+f', e => {
+ e.preventDefault();
+ if (this.state.isEditMode) {
+ this.onQueryFormat();
+ }
+ return false;
+ });
+ }
+
componentWillUnmount() {
+ Mousetrap.unbind('ctrl+shift+f');
this.props.resetQuery();
}
}
@@ -1689,6 +1773,7 @@ const DataSourceComponent = withTheme(DatasourceEditor);
const mapDispatchToProps = dispatch => ({
runQuery: payload => dispatch(executeQuery(payload)),
resetQuery: () => dispatch(resetDatabaseState()),
+ formatQuery: sql => dispatch(formatQuery(sql)),
});
const mapStateToProps = state => ({
database: state?.database,
diff --git a/superset-frontend/src/components/Icons/AntdEnhanced.tsx b/superset-frontend/src/components/Icons/AntdEnhanced.tsx
index 43eb75b426..ee081ac97c 100644
--- a/superset-frontend/src/components/Icons/AntdEnhanced.tsx
+++ b/superset-frontend/src/components/Icons/AntdEnhanced.tsx
@@ -73,6 +73,7 @@ import {
FullscreenOutlined,
FundProjectionScreenOutlined,
FunctionOutlined,
+ HighlightOutlined,
InfoCircleOutlined,
InfoCircleFilled,
InsertRowAboveOutlined,
@@ -179,6 +180,7 @@ const AntdIcons = {
FullscreenOutlined,
FundProjectionScreenOutlined,
FunctionOutlined,
+ HighlightOutlined,
InfoCircleOutlined,
InfoCircleFilled,
InsertRowAboveOutlined,
diff --git a/superset-frontend/src/database/actions.ts b/superset-frontend/src/database/actions.ts
index ba98d0cd49..556d0b014e 100644
--- a/superset-frontend/src/database/actions.ts
+++ b/superset-frontend/src/database/actions.ts
@@ -17,7 +17,7 @@
* under the License.
*/
-import { makeApi } from '@superset-ui/core';
+import { SupersetClient, makeApi } from '@superset-ui/core';
import { ThunkDispatch } from 'redux-thunk';
import { AnyAction } from 'redux';
import { QueryExecutePayload, QueryExecuteResponse } from './types';
@@ -30,6 +30,13 @@ export const executeQueryApi = makeApi<
endpoint: '/api/v1/sqllab/execute',
});
+export function setQuery(query: string) {
+ return {
+ type: 'SET_QUERY',
+ payload: query,
+ };
+}
+
export function setQueryIsLoading(isLoading: boolean) {
return {
type: 'SET_QUERY_IS_LOADING',
@@ -66,3 +73,16 @@ export function executeQuery(payload: QueryExecutePayload) {
}
};
}
+
+export function formatQuery(sql: string) {
+ return function (dispatch: ThunkDispatch<any, undefined, AnyAction>) {
+ return SupersetClient.post({
+ endpoint: `/api/v1/sqllab/format_sql/`,
+ body: JSON.stringify({ sql }),
+ headers: { 'Content-Type': 'application/json' },
+ }).then(response => {
+ dispatch(setQuery(response.json.result));
+ return response;
+ });
+ };
+}
diff --git a/superset-frontend/src/database/reducers.ts b/superset-frontend/src/database/reducers.ts
index 7541494b83..ace2afed1c 100644
--- a/superset-frontend/src/database/reducers.ts
+++ b/superset-frontend/src/database/reducers.ts
@@ -31,6 +31,13 @@ export default function databaseReducer(
action: any,
): QueryAdhocState {
switch (action.type) {
+ case 'SET_QUERY':
+ return {
+ ...state,
+ sql: action.payload ?? '',
+ queryResult: null,
+ error: null,
+ };
case 'SET_QUERY_IS_LOADING':
return {
...state,
diff --git a/superset-frontend/src/explore/components/controls/TextAreaControl.jsx b/superset-frontend/src/explore/components/controls/TextAreaControl.jsx
index 605d495218..d48b06396e 100644
--- a/superset-frontend/src/explore/components/controls/TextAreaControl.jsx
+++ b/superset-frontend/src/explore/components/controls/TextAreaControl.jsx
@@ -57,6 +57,7 @@ const propTypes = {
]),
textAreaStyles: PropTypes.object,
tooltipOptions: PropTypes.oneOf([null, TooltipProps]),
+ hotkeys: PropTypes.array,
};
const defaultProps = {
@@ -70,6 +71,7 @@ const defaultProps = {
resize: null,
textAreaStyles: {},
tooltipOptions: {},
+ hotkeys: [],
};
class TextAreaControl extends Component {
@@ -97,6 +99,15 @@ class TextAreaControl extends Component {
if (this.props.readOnly) {
style.backgroundColor = '#f2f2f2';
}
+ const onEditorLoad = editor => {
+ this.props.hotkeys.forEach(keyConfig => {
+ editor.commands.addCommand({
+ name: keyConfig.name,
+ bindKey: { win: keyConfig.key, mac: keyConfig.key },
+ exec: keyConfig.func,
+ });
+ });
+ };
const codeEditor = (
<div>
<TextAreaEditor
@@ -105,6 +116,7 @@ class TextAreaControl extends Component {
minLines={minLines}
maxLines={inModal ? 1000 : this.props.maxLines}
editorProps={{ $blockScrolling: true }}
+ onLoad={onEditorLoad}
defaultValue={this.props.initialValue}
readOnly={this.props.readOnly}
key={this.props.name}