Skip to content

Commit

Permalink
feat: support getTableListWithoutSession refs #199802
Browse files Browse the repository at this point in the history
  • Loading branch information
sandercage committed Apr 12, 2024
1 parent 2dc4c57 commit 6ddcb8f
Show file tree
Hide file tree
Showing 14 changed files with 149 additions and 102 deletions.
10 changes: 10 additions & 0 deletions src/common/network/table/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,16 @@ export async function getTableListByDatabaseName(
return ret?.data || [];
}

/**
* 不依赖session直接从元数据获取库下面的表列表
* @param databaseId 数据库ID
* @returns 数据库的表列表
*/
export async function getTableListWithoutSession(databaseId: number): Promise<ITable[]> {
const ret = await request.get(`/api/v2/table/listTables/${databaseId}`);
return ret?.data || [];
}

export async function batchGetDataModifySQL(
schemaName: string,
tableName: string,
Expand Down
44 changes: 21 additions & 23 deletions src/component/Task/ApplyTablePermission/CreateModal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ import { listProjects } from '@/common/network/project';
import { createTask } from '@/common/network/task';
import TableSelecter, {
TableSelecterRef,
flatTableByGroupedParams,
groupTableByDataBase,
} from '@/component/Task/component/TableSelecter';
import HelpDoc from '@/component/helpDoc';
import { IApplyTablePermissionTaskParams, TaskPageScope, TaskPageType, TaskType } from '@/d.ts';
import { TaskPageScope, TaskPageType, TaskType } from '@/d.ts';
import { TablePermissionType } from '@/d.ts/table';
import { openTasksPage } from '@/store/helper/page';
import type { ModalStore } from '@/store/modal';
Expand All @@ -48,6 +49,11 @@ const CheckboxGroup = Checkbox.Group;
const MAX_DATE = '9999-12-31 23:59:59';
const MAX_DATE_LABEL = '9999-12-31';

const defaultValue = {
tables: [],
expireTime: '7,days',
};

export const getExpireTime = (expireTime, customExpireTime, isCustomExpireTime) => {
if (isCustomExpireTime) {
return customExpireTime?.valueOf();
Expand Down Expand Up @@ -206,7 +212,7 @@ const CreateModal: React.FC<IProps> = (props) => {
handleCancel(false);
setConfirmLoading(false);
if (res) {
message.success('申请表权限成功');
message.success('工单创建成功');
openTasksPage(TaskPageType.APPLY_TABLE_PERMISSION, TaskPageScope.CREATED_BY_CURRENT_USER);
}
})
Expand All @@ -226,28 +232,22 @@ const CreateModal: React.FC<IProps> = (props) => {
},
executionStrategy,
} = task;
// 格式化成TableSelecter所需格式
const formatDbTables = (tables: IApplyTablePermissionTaskParams['tables']) => {
if (!tables) {
return [];
}
const map: { [databaseId: number]: string[] } = {};
tables.forEach(({ databaseId, tableName }) => {
if (map[databaseId]) {
map[databaseId].push(tableName);
} else {
map[databaseId] = [tableName];
}
});
return Object.keys(map).map((databaseId) => ({ databaseId, tableNames: map[databaseId] }));
};
const formData = {
...defaultValue,
projectId,
executionStrategy,
tables: formatDbTables(tables),
tables: flatTableByGroupedParams(tables),
types,
applyReason,
};
// 默认获取要申请权限的库下面的表,并且展开
// 目前一个工单只会关联一个库
const databaseId = tables?.[0]?.databaseId;
if (projectId && databaseId) {
tableSelecterRef.current?.loadTables(databaseId).then(() => {
tableSelecterRef.current?.expandTable(databaseId);
});
}
form.setFieldsValue(formData);
}, [applyTablePermissionData, form]);

Expand All @@ -256,15 +256,15 @@ const CreateModal: React.FC<IProps> = (props) => {
};

useEffect(() => {
const { projectId, databaseId, tableName, types } = applyTablePermissionData ?? {};
const { projectId, databaseId, tableNames, types } = applyTablePermissionData ?? {};
if (applyTablePermissionData?.task) {
loadEditData();
} else {
const initFormValues: any = {
projectId: projectId || props?.projectId,
databaseId,
// 格式化成TableSelecter value所需格式
tables: tableName ? [{ databaseId, tableName }] : [],
tables: flatTableByGroupedParams([{ databaseId, tableNames }]),
types,
};
if (projectId && databaseId) {
Expand Down Expand Up @@ -305,9 +305,7 @@ const CreateModal: React.FC<IProps> = (props) => {
>
<Form
name="basic"
initialValues={{
databases: [],
}}
initialValues={defaultValue}
layout="vertical"
requiredMark="optional"
form={form}
Expand Down
39 changes: 35 additions & 4 deletions src/component/Task/ApplyTablePermission/DetailContent/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@
* limitations under the License.
*/

import { getDataSourceStyleByConnectType } from '@/common/datasource';
import DisplayTable from '@/component/DisplayTable';
import { SimpleTextItem } from '@/component/Task/component/SimpleTextItem';
import type { IApplyTablePermissionTaskParams, TaskDetail } from '@/d.ts';
import { getFormatDateTime } from '@/util/utils';
import { Descriptions, Divider } from 'antd';
import { Descriptions, Divider, Space } from 'antd';
import { useMemo } from 'react';
import { getExpireTimeLabel, permissionOptionsMap } from '../';

const getConnectionColumns = () => {
Expand All @@ -28,6 +30,17 @@ const getConnectionColumns = () => {
title: '数据库',
ellipsis: true,
width: 240,
render(databaseName: string, { dataSourceType }) {
const Icon = dataSourceType
? getDataSourceStyleByConnectType(dataSourceType)?.dbIcon?.component
: null;
return (
<Space>
{Icon && <Icon />}
<span>{databaseName}</span>
</Space>
);
},
},
{
dataIndex: 'tableName',
Expand All @@ -48,7 +61,25 @@ interface IProps {
}
const TaskContent: React.FC<IProps> = (props) => {
const { task } = props;
const parameters = task?.parameters;
const { parameters, database } = task || {};
/**
* 数据处理成每个表一行
*/
const dataSource = useMemo(() => {
const tableList = [];
for (const table of parameters?.tables || []) {
const { tableNames, databaseName, dataSourceName } = table;
for (const tableName of tableNames) {
tableList.push({
tableName,
databaseName,
dataSourceName,
dataSourceType: database?.dataSource?.type,
});
}
}
return tableList;
}, [database?.dataSource?.type, parameters?.tables]);

return (
<>
Expand All @@ -68,9 +99,9 @@ const TaskContent: React.FC<IProps> = (props) => {
label="表"
content={
<DisplayTable
rowKey="tableId"
rowKey="tableName"
columns={getConnectionColumns()}
dataSource={parameters?.tables}
dataSource={dataSource}
scroll={null}
showQuickJumper={false}
showSizeChanger={false}
Expand Down
85 changes: 44 additions & 41 deletions src/component/Task/component/TableSelecter/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,25 @@
* limitations under the License.
*/

import { getDataSourceStyleByConnectType } from '@/common/datasource';
import { listDatabases } from '@/common/network/database';
import { generateDatabaseSidByDataBaseId } from '@/common/network/pathUtil';
import { getTableListWithoutSession } from '@/common/network/table';
import ExportCard from '@/component/ExportCard';
import DataBaseStatusIcon from '@/component/StatusIcon/DatabaseIcon';
import { IDatabase } from '@/d.ts/database';
import { TablePermissionType } from '@/d.ts/table';
import { SessionManagerStore } from '@/store/sessionManager';
import { ReactComponent as DatabaseSvg } from '@/svgr/database.svg';
import { ReactComponent as TableSvg } from '@/svgr/menuTable.svg';
import Icon, { DeleteOutlined } from '@ant-design/icons';
import { Checkbox, Empty, Popconfirm, Space, Spin, Tree, Typography } from 'antd';
import { DataNode, EventDataNode, TreeProps } from 'antd/lib/tree';
import classnames from 'classnames';
import { inject, observer } from 'mobx-react';
import React, { useCallback, useEffect, useImperativeHandle, useMemo, useState } from 'react';
import styles from './index.less';
import request from '@/util/request';

type TableItem = { databaseId: number; tableName: string };
export type TableItem = { databaseId: number; tableName: string };

type IProps = {
sessionManagerStore?: SessionManagerStore;
projectId: number;
value?: TableItem[];
stateId?: string;
onChange?: (newValue: TableItem[]) => void;
};

Expand Down Expand Up @@ -81,8 +75,7 @@ const parseDataBaseIdAndTableNamebByKey = (key: string): TableItem => {

/**
* 按库将表分组返回:
* 目前value格式和详情接口返回的格式保持了一致
* tips: 单个+批量提交时的参数类型可使用本方法获取
* 可用来获取:工单授权和用户授权的提交参数
* @param tables
* @returns
*/
Expand All @@ -102,6 +95,27 @@ export const groupTableByDataBase = (
tableNames: groupMap[databaseId],
}));
};
/**
* 和groupTableByDataBase配合使用
* 可将groupTableByDataBase按库分组后的值拍平为TableItem
* 就可以直接set到TableSeletor上了
* @param tables
* @returns
*/
export const flatTableByGroupedParams = (
tables: { databaseId: number; tableNames: string[] }[],
): TableItem[] => {
if (!tables) {
return [];
}
const result: TableItem[] = [];
tables.forEach(({ databaseId, tableNames }) => {
tableNames?.forEach((tableName) => {
tableName && result.push({ databaseId, tableName });
});
});
return result;
};
/**
* 将原始的IDataBaseWithTable数据转成TreeData格式
* 仅叶子节点可以选择
Expand Down Expand Up @@ -132,7 +146,7 @@ const getTreeData = (validTableList: IDataBaseWithTable[]) => {
</Space>
),
key: id,
icon: <DataBaseStatusIcon item={database} />,
icon: getDataSourceStyleByConnectType(dataSource.type).dbIcon.component,
checkable: false,
expandable: true,
children,
Expand All @@ -142,7 +156,7 @@ const getTreeData = (validTableList: IDataBaseWithTable[]) => {
};

const TableSelecter: React.ForwardRefRenderFunction<TableSelecterRef, IProps> = (
{ projectId, sessionManagerStore, value = [], onChange },
{ projectId, value = [], onChange },
ref,
) => {
const [isLoading, setIsLoading] = useState(false);
Expand All @@ -158,19 +172,17 @@ const TableSelecter: React.ForwardRefRenderFunction<TableSelecterRef, IProps> =
return value.map(generateKeyByDataBaseIdAndTableName);
}, [value]);
/**
* 获取项目下所有的库及其表
* 获取项目下所有的数据库
*/
const loadDatabases = useCallback(async () => {
setIsLoading(true);
try {
const res = await listDatabases(projectId, null, null, null, null, null, null, true, true);
if (res?.contents) {
const list: IDataBaseWithTable[] = res.contents
// .filter(({ authorizedPermissionTypes }) => authorizedPermissionTypes?.length)
.map((db) => ({
...db,
tableNames: [],
}));
const list: IDataBaseWithTable[] = res.contents.map((db) => ({
...db,
tableNames: [],
}));
setDataBaseWithTableList(list || []);
}
} catch (e) {
Expand Down Expand Up @@ -264,28 +276,18 @@ const TableSelecter: React.ForwardRefRenderFunction<TableSelecterRef, IProps> =
/**
* 加载库里包含的表
*/
const handleLoadTables = useCallback(
async (databaseId: number) => {
// TODO 由于此处依赖session, 后期会改成一个不依赖session的获取库下表列表的接口来做
const dbSession = await sessionManagerStore.createSession(null, databaseId, true);
if (dbSession && dbSession !== 'NotFound') {
const { sessionId } = dbSession;
await dbSession.database.getTableList();
const tables = dbSession.database.tables || [];
const tableNames = tables.map(({ info: { tableName } }) => tableName);
setDataBaseWithTableList((prevData) => {
for (const item of prevData) {
if (item.id === databaseId) {
item.tableNames = tableNames;
}
}
const handleLoadTables = useCallback(async (databaseId: number) => {
const tables = await getTableListWithoutSession(databaseId);
const tableNames = tables.map(({ tableName }) => tableName);
setDataBaseWithTableList((prevData) => {
for (const item of prevData) {
if (item.id === databaseId) {
item.tableNames = tableNames;
return [...prevData];
});
sessionManagerStore.destorySession(sessionId);
}
}
},
[sessionManagerStore],
);
});
}, []);
/**
* 所有选中的节点的Key
*/
Expand Down Expand Up @@ -422,6 +424,7 @@ const TableSelecter: React.ForwardRefRenderFunction<TableSelecterRef, IProps> =
>
{selectedTreeData?.length ? (
<Tree
blockNode
showIcon
autoExpandParent
defaultExpandAll
Expand Down Expand Up @@ -460,4 +463,4 @@ const TableSelecter: React.ForwardRefRenderFunction<TableSelecterRef, IProps> =
);
};

export default inject('sessionManagerStore')(observer(React.forwardRef(TableSelecter)));
export default React.forwardRef(TableSelecter);
11 changes: 6 additions & 5 deletions src/d.ts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2536,13 +2536,14 @@ export interface IApplyTablePermissionTaskParams {
id: number;
name?: string;
};
// 提交时databaseId、tableNames为必填项
// 详情返回时五个字段均有
tables: {
dataSourceId: number;
dataSourceName: string;
databaseId: number;
databaseName: string;
tableId: number;
tableName: string;
tableNames: string[];
dataSourceId?: number;
dataSourceName?: string;
databaseName?: string;
}[];
types: TablePermissionType[];
expireTime: number;
Expand Down
10 changes: 0 additions & 10 deletions src/page/Project/User/ManageModal/index.less
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,6 @@
> div {
height: 100%;
}
.layout {
> .sider {
flex: 0 0 80px;
width: 80px;
}
> .content {
display: flex;
flex-direction: column;
}
}
}
.ant-drawer-footer {
display: flex;
Expand Down
Loading

0 comments on commit 6ddcb8f

Please sign in to comment.