feat(external-sql): 完善外部 SQL 目录文件管理

- 新增外部 SQL 文件的新建、重命名、删除和目录管理接口

- 后端限制 SQL 目录只加载 .sql 文件并补充目录操作测试

- 前端补齐 Wails 类型、浏览器 mock 和外部 SQL 树过滤逻辑

- 支持从外部 SQL 文件标签定位到侧栏目录节点
This commit is contained in:
Syngnat
2026-06-02 11:15:30 +08:00
parent bf3e21f15c
commit e6dd986115
10 changed files with 696 additions and 37 deletions

View File

@@ -215,6 +215,12 @@ if (typeof window !== 'undefined' && !(window as any).go) {
SelectSQLDirectory: async (currentPath: string) => ({ success: false, message: currentPath ? '已取消' : '已取消' }),
ListSQLDirectory: async () => ({ success: true, data: [] }),
ReadSQLFile: async () => ({ success: false, message: '已取消' }),
CreateSQLFile: async (_directoryPath: string, _name: string) => ({ success: true, data: { filePath: '', name: _name } }),
CreateSQLDirectory: async (directoryPath: string, name: string) => ({ success: true, data: { directoryPath: `${directoryPath}/${name}`, name } }),
DeleteSQLFile: async (_filePath: string) => ({ success: true }),
DeleteSQLDirectory: async (_directoryPath: string) => ({ success: true }),
RenameSQLFile: async (_filePath: string, name: string) => ({ success: true, data: { filePath: _filePath, name } }),
RenameSQLDirectory: async (directoryPath: string, name: string) => ({ success: true, data: { directoryPath: `${directoryPath.replace(/[\\/][^\\/]*$/, '')}/${name}`, name } }),
WriteSQLFile: async (_filePath: string, _content: string) => ({ success: true }),
ExportSQLFile: async (_defaultName: string, _content: string) => ({ success: false, message: '浏览器 mock 不支持 SQL 文件导出' }),
InstallUpdateAndRestart: async () => ({ success: false }),
@@ -302,4 +308,3 @@ ReactDOM.createRoot(rootNode).render(
{rootComponent}
</React.StrictMode>,
)

View File

@@ -472,8 +472,8 @@ export interface ExternalSQLDirectory {
id: string;
name: string;
path: string;
connectionId: string;
dbName: string;
connectionId?: string;
dbName?: string;
createdAt: number;
}

View File

@@ -10,8 +10,6 @@ describe('externalSqlTree helpers', () => {
id: 'dir-1',
name: 'scripts',
path: 'D:/sql/scripts',
connectionId: 'conn-1',
dbName: 'demo',
createdAt: 1,
},
];
@@ -33,14 +31,12 @@ describe('externalSqlTree helpers', () => {
};
const node = buildExternalSQLRootNode({
dbNodeKey: 'conn-1-demo',
connectionId: 'conn-1',
dbName: 'demo',
directories,
directoryTrees: trees,
});
expect(node.type).toBe('external-sql-root');
expect(node.key).toBe('external-sql-root');
expect(node.title).toBe('外部 SQL 目录 (1)');
expect(node.children).toHaveLength(1);
expect(node.children?.[0]).toMatchObject({
@@ -65,4 +61,77 @@ describe('externalSqlTree helpers', () => {
expect(first).toContain('demo');
expect(first).not.toBe(second);
});
it('filters non-sql file entries even when the backend returns them', () => {
const directories: ExternalSQLDirectory[] = [
{
id: 'dir-1',
name: 'scripts',
path: 'D:/sql/scripts',
createdAt: 1,
},
];
const trees: Record<string, ExternalSQLTreeEntry[]> = {
'dir-1': [
{
name: 'readme.md',
path: 'D:/sql/scripts/readme.md',
isDir: false,
},
{
name: 'nested',
path: 'D:/sql/scripts/nested',
isDir: true,
children: [
{
name: 'notes.txt',
path: 'D:/sql/scripts/nested/notes.txt',
isDir: false,
},
{
name: 'report.SQL',
path: 'D:/sql/scripts/nested/report.SQL',
isDir: false,
},
],
},
{
name: 'docs',
path: 'D:/sql/scripts/docs',
isDir: true,
children: [
{
name: 'manual.md',
path: 'D:/sql/scripts/docs/manual.md',
isDir: false,
},
],
},
],
};
const node = buildExternalSQLRootNode({
directories,
directoryTrees: trees,
});
const folderChildren = node.children?.[0].children || [];
const docsFolder = folderChildren.find((child) => child.title === 'docs');
const nestedFolder = folderChildren.find((child) => child.title === 'nested');
expect(folderChildren).toHaveLength(2);
expect(docsFolder).toMatchObject({
title: 'docs',
type: 'external-sql-folder',
});
expect(docsFolder?.children).toBeUndefined();
expect(nestedFolder).toMatchObject({
title: 'nested',
type: 'external-sql-folder',
});
expect(nestedFolder?.children).toHaveLength(1);
expect(nestedFolder?.children?.[0]).toMatchObject({
title: 'report.SQL',
type: 'external-sql-file',
});
});
});

View File

@@ -16,9 +16,9 @@ export interface ExternalSQLTreeNode {
}
type BuildExternalSQLRootNodeParams = {
dbNodeKey: string;
connectionId: string;
dbName: string;
dbNodeKey?: string;
connectionId?: string;
dbName?: string;
directories: ExternalSQLDirectory[];
directoryTrees: Record<string, ExternalSQLTreeEntry[]>;
};
@@ -35,7 +35,7 @@ const resolveDirectoryDisplayName = (directory: ExternalSQLDirectory): string =>
};
export const buildExternalSQLDirectoryId = (connectionId: string, dbName: string, directoryPath: string): string =>
`external-sql-dir:${String(connectionId || '').trim()}:${String(dbName || '').trim()}:${normalizeExternalSQLPath(directoryPath)}`;
`external-sql-dir:${normalizeExternalSQLPath(directoryPath)}`;
export const buildExternalSQLTabId = (connectionId: string, dbName: string, filePath: string): string =>
`external-sql-tab:${String(connectionId || '').trim()}:${String(dbName || '').trim()}:${normalizeExternalSQLPath(filePath)}`;
@@ -43,14 +43,20 @@ export const buildExternalSQLTabId = (connectionId: string, dbName: string, file
const buildExternalSQLNodeKey = (type: ExternalSQLNodeType, base: string): string =>
`${type}:${normalizeExternalSQLPath(base)}`;
const isExternalSQLFileEntry = (entry: ExternalSQLTreeEntry): boolean => {
const name = String(entry.name || '').trim();
const path = normalizeExternalSQLPath(entry.path);
return /\.sql$/i.test(name) || /\.sql$/i.test(path);
};
const mapExternalSQLTreeEntries = (
entries: ExternalSQLTreeEntry[],
context: { connectionId: string; dbName: string; dbNodeKey: string; directoryId: string },
): ExternalSQLTreeNode[] => entries.map((entry) => {
): ExternalSQLTreeNode[] => entries.flatMap((entry): ExternalSQLTreeNode[] => {
const entryPath = normalizeExternalSQLPath(entry.path);
if (entry.isDir) {
const children = mapExternalSQLTreeEntries(entry.children || [], context);
return {
return [{
title: entry.name,
key: buildExternalSQLNodeKey('external-sql-folder', entryPath),
type: 'external-sql-folder',
@@ -64,10 +70,14 @@ const mapExternalSQLTreeEntries = (
path: entry.path,
name: entry.name,
},
};
}];
}
return {
if (!isExternalSQLFileEntry(entry)) {
return [];
}
return [{
title: entry.name,
key: buildExternalSQLNodeKey('external-sql-file', entryPath),
type: 'external-sql-file',
@@ -80,13 +90,13 @@ const mapExternalSQLTreeEntries = (
path: entry.path,
name: entry.name,
},
};
}];
});
export const buildExternalSQLRootNode = ({
dbNodeKey,
connectionId,
dbName,
dbNodeKey = 'external-sql-root',
connectionId = '',
dbName = '',
directories,
directoryTrees,
}: BuildExternalSQLRootNodeParams): ExternalSQLTreeNode => {
@@ -118,7 +128,7 @@ export const buildExternalSQLRootNode = ({
return {
title: children.length > 0 ? `外部 SQL 目录 (${children.length})` : '外部 SQL 目录',
key: `${dbNodeKey}-external-sql`,
key: dbNodeKey === 'external-sql-root' ? 'external-sql-root' : `${dbNodeKey}-external-sql`,
type: 'external-sql-root',
isLeaf: children.length === 0,
children: children.length > 0 ? children : undefined,

View File

@@ -122,6 +122,29 @@ describe('sidebarLocate', () => {
});
});
it('builds and resolves locate requests from external SQL file query tabs', () => {
const request = normalizeSidebarLocateObjectRequestFromTab({
id: 'external-sql-tab:conn-1:main:/Users/me/sql/report.sql',
type: 'query',
connectionId: 'conn-1',
dbName: 'main',
filePath: '/Users/me/sql/report.sql',
});
expect(request).toMatchObject({
connectionId: 'conn-1',
dbName: 'main',
filePath: '/Users/me/sql/report.sql',
objectGroup: 'externalSqlFiles',
});
expect(resolveSidebarLocateTarget(request!, { groupBySchema: false })).toMatchObject({
objectGroupKey: 'external-sql-root',
expectedAncestorKeys: ['external-sql-root'],
filePath: '/Users/me/sql/report.sql',
});
});
it('keeps StarRocks materialized view tabs on the materialized views branch', () => {
const request = normalizeSidebarLocateObjectRequestFromTab({
id: 'view-def-conn-1-main-sales.mv_daily',
@@ -285,4 +308,38 @@ describe('sidebarLocate', () => {
'conn-1-main-routine-reporting.refresh_stats',
]);
});
it('finds external SQL file paths from loaded tree data', () => {
const target = resolveSidebarLocateTarget({
filePath: 'C:\\Users\\me\\sql\\report.sql',
objectGroup: 'externalSqlFiles',
}, { groupBySchema: false });
const tree = [
{
key: 'external-sql-root',
type: 'external-sql-root',
children: [
{
key: 'external-sql-directory:C:/Users/me/sql',
type: 'external-sql-directory',
dataRef: { path: 'C:/Users/me/sql' },
children: [
{
key: 'external-sql-file:C:/Users/me/sql/report.sql',
type: 'external-sql-file',
dataRef: { path: 'C:/Users/me/sql/report.sql' },
},
],
},
],
},
];
expect(findSidebarNodePathForLocate(tree, target)).toEqual([
'external-sql-root',
'external-sql-directory:C:/Users/me/sql',
'external-sql-file:C:/Users/me/sql/report.sql',
]);
});
});

View File

@@ -1,14 +1,26 @@
export type SidebarLocateObjectGroup = 'tables' | 'views' | 'materializedViews' | 'triggers' | 'routines';
export type SidebarLocateObjectGroup = 'tables' | 'views' | 'materializedViews' | 'triggers' | 'routines' | 'externalSqlFiles';
export type SidebarLocateDatabaseObjectGroup = Exclude<SidebarLocateObjectGroup, 'externalSqlFiles'>;
export interface SidebarLocateObjectRequest {
export interface SidebarLocateDatabaseObjectRequest {
tabId?: string;
connectionId: string;
dbName: string;
tableName: string;
schemaName?: string;
objectGroup: SidebarLocateObjectGroup;
objectGroup: SidebarLocateDatabaseObjectGroup;
}
export interface SidebarLocateExternalSQLFileRequest {
tabId?: string;
connectionId?: string;
dbName?: string;
filePath: string;
fileName?: string;
objectGroup: 'externalSqlFiles';
}
export type SidebarLocateObjectRequest = SidebarLocateDatabaseObjectRequest | SidebarLocateExternalSQLFileRequest;
export interface SidebarLocateTarget {
connectionKey: string;
databaseKey: string;
@@ -21,6 +33,7 @@ export interface SidebarLocateTarget {
dbName: string;
tableName: string;
schemaName: string;
filePath?: string;
}
export interface SidebarLocateTreeNodeLike {
@@ -40,10 +53,13 @@ export interface SidebarLocateTabLike {
viewKind?: string;
triggerName?: string;
routineName?: string;
filePath?: string;
}
const toTrimmedString = (value: unknown): string => String(value ?? '').trim();
const normalizeExternalSQLLocatePath = (value: unknown): string => toTrimmedString(value).replace(/\\/g, '/');
export const splitSidebarQualifiedName = (qualifiedName: string): { schemaName: string; objectName: string } => {
const raw = toTrimmedString(qualifiedName);
if (!raw) return { schemaName: '', objectName: '' };
@@ -55,7 +71,7 @@ export const splitSidebarQualifiedName = (qualifiedName: string): { schemaName:
};
};
const inferObjectGroup = (detail: Record<string, unknown>, connectionId: string, dbName: string): SidebarLocateObjectGroup => {
const inferObjectGroup = (detail: Record<string, unknown>, connectionId: string, dbName: string): SidebarLocateDatabaseObjectGroup => {
const explicitGroup = toTrimmedString(detail.objectGroup);
if (explicitGroup === 'views' || explicitGroup === 'view') return 'views';
if (explicitGroup === 'materializedViews' || explicitGroup === 'materialized-view') return 'materializedViews';
@@ -80,6 +96,18 @@ const inferObjectGroup = (detail: Record<string, unknown>, connectionId: string,
export const normalizeSidebarLocateObjectRequest = (detail: unknown): SidebarLocateObjectRequest | null => {
const raw = (detail || {}) as Record<string, unknown>;
const filePath = normalizeExternalSQLLocatePath(raw.filePath);
if (filePath) {
return {
tabId: toTrimmedString(raw.tabId) || undefined,
connectionId: toTrimmedString(raw.connectionId) || undefined,
dbName: toTrimmedString(raw.dbName) || undefined,
filePath,
fileName: toTrimmedString(raw.fileName || raw.title) || undefined,
objectGroup: 'externalSqlFiles',
};
}
const connectionId = toTrimmedString(raw.connectionId);
const dbName = toTrimmedString(raw.dbName);
const tableName = toTrimmedString(raw.tableName || raw.objectName || raw.viewName || raw.triggerName || raw.routineName);
@@ -103,6 +131,17 @@ export const normalizeSidebarLocateObjectRequest = (detail: unknown): SidebarLoc
export const normalizeSidebarLocateObjectRequestFromTab = (tab: SidebarLocateTabLike | null | undefined): SidebarLocateObjectRequest | null => {
if (!tab) return null;
const filePath = normalizeExternalSQLLocatePath(tab.filePath);
if (tab.type === 'query' && filePath) {
return normalizeSidebarLocateObjectRequest({
tabId: tab.id,
connectionId: tab.connectionId,
dbName: tab.dbName,
filePath,
fileName: tab.id,
});
}
const objectName = tab.type === 'view-def'
? toTrimmedString(tab.viewName || tab.tableName)
: tab.type === 'trigger'
@@ -129,6 +168,23 @@ export const resolveSidebarLocateTarget = (
request: SidebarLocateObjectRequest,
options: { groupBySchema: boolean },
): SidebarLocateTarget => {
if (request.objectGroup === 'externalSqlFiles') {
const filePath = normalizeExternalSQLLocatePath(request.filePath);
return {
connectionKey: toTrimmedString(request.connectionId),
databaseKey: request.connectionId && request.dbName ? `${request.connectionId}-${request.dbName}` : '',
targetKey: request.tabId || filePath,
objectGroup: 'externalSqlFiles',
objectGroupKey: 'external-sql-root',
expectedAncestorKeys: ['external-sql-root'],
connectionId: toTrimmedString(request.connectionId),
dbName: toTrimmedString(request.dbName),
tableName: request.fileName || filePath.split('/').filter(Boolean).pop() || filePath,
schemaName: '',
filePath,
};
}
const connectionKey = request.connectionId;
const databaseKey = `${request.connectionId}-${request.dbName}`;
const fallbackTargetKey = request.objectGroup === 'materializedViews'
@@ -205,6 +261,12 @@ const matchesLocateObjectName = (target: SidebarLocateTarget, nodeObjectName: st
const matchesLocateObjectNode = (node: SidebarLocateTreeNodeLike, target: SidebarLocateTarget): boolean => {
const dataRef = node.dataRef || {};
if (target.objectGroup === 'externalSqlFiles') {
return node.type === 'external-sql-file'
&& normalizeExternalSQLLocatePath(dataRef.path) === normalizeExternalSQLLocatePath(target.filePath);
}
const nodeConnectionId = toTrimmedString(dataRef.id || dataRef.connectionId);
const nodeDbName = toTrimmedString(dataRef.dbName);

View File

@@ -28,6 +28,10 @@ export function ConfigureGlobalProxy(arg1:boolean,arg2:connection.ProxyConfig):P
export function CreateDatabase(arg1:connection.ConnectionConfig,arg2:string):Promise<connection.QueryResult>;
export function CreateSQLDirectory(arg1:string,arg2:string):Promise<connection.QueryResult>;
export function CreateSQLFile(arg1:string,arg2:string):Promise<connection.QueryResult>;
export function CreateSchema(arg1:connection.ConnectionConfig,arg2:string,arg3:string):Promise<connection.QueryResult>;
export function DBConnect(arg1:connection.ConnectionConfig):Promise<connection.QueryResult>;
@@ -64,6 +68,10 @@ export function DataSyncPreview(arg1:sync.SyncConfig,arg2:string,arg3:number):Pr
export function DeleteConnection(arg1:string):Promise<void>;
export function DeleteSQLDirectory(arg1:string):Promise<connection.QueryResult>;
export function DeleteSQLFile(arg1:string):Promise<connection.QueryResult>;
export function DismissSecurityUpdateReminder():Promise<app.SecurityUpdateStatus>;
export function DownloadDriverPackage(arg1:string,arg2:string,arg3:string,arg4:string):Promise<connection.QueryResult>;
@@ -246,6 +254,10 @@ export function RemoveDriverPackage(arg1:string,arg2:string):Promise<connection.
export function RenameDatabase(arg1:connection.ConnectionConfig,arg2:string,arg3:string):Promise<connection.QueryResult>;
export function RenameSQLDirectory(arg1:string,arg2:string):Promise<connection.QueryResult>;
export function RenameSQLFile(arg1:string,arg2:string):Promise<connection.QueryResult>;
export function RenameTable(arg1:connection.ConnectionConfig,arg2:string,arg3:string,arg4:string):Promise<connection.QueryResult>;
export function RenameView(arg1:connection.ConnectionConfig,arg2:string,arg3:string,arg4:string):Promise<connection.QueryResult>;

View File

@@ -46,6 +46,14 @@ export function CreateDatabase(arg1, arg2) {
return window['go']['app']['App']['CreateDatabase'](arg1, arg2);
}
export function CreateSQLDirectory(arg1, arg2) {
return window['go']['app']['App']['CreateSQLDirectory'](arg1, arg2);
}
export function CreateSQLFile(arg1, arg2) {
return window['go']['app']['App']['CreateSQLFile'](arg1, arg2);
}
export function CreateSchema(arg1, arg2, arg3) {
return window['go']['app']['App']['CreateSchema'](arg1, arg2, arg3);
}
@@ -118,6 +126,14 @@ export function DeleteConnection(arg1) {
return window['go']['app']['App']['DeleteConnection'](arg1);
}
export function DeleteSQLDirectory(arg1) {
return window['go']['app']['App']['DeleteSQLDirectory'](arg1);
}
export function DeleteSQLFile(arg1) {
return window['go']['app']['App']['DeleteSQLFile'](arg1);
}
export function DismissSecurityUpdateReminder() {
return window['go']['app']['App']['DismissSecurityUpdateReminder']();
}
@@ -482,6 +498,14 @@ export function RenameDatabase(arg1, arg2, arg3) {
return window['go']['app']['App']['RenameDatabase'](arg1, arg2, arg3);
}
export function RenameSQLDirectory(arg1, arg2) {
return window['go']['app']['App']['RenameSQLDirectory'](arg1, arg2);
}
export function RenameSQLFile(arg1, arg2) {
return window['go']['app']['App']['RenameSQLFile'](arg1, arg2);
}
export function RenameTable(arg1, arg2, arg3, arg4) {
return window['go']['app']['App']['RenameTable'](arg1, arg2, arg3, arg4);
}