-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathsqlExport.ts
More file actions
66 lines (56 loc) · 1.68 KB
/
sqlExport.ts
File metadata and controls
66 lines (56 loc) · 1.68 KB
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
import dayjs from 'dayjs'
export type SQLExportFormat = 'csv' | 'json'
export interface SQLExportData {
columns: string[]
rows: any[][]
}
/**
* 将 SQL 结果格式化为 CSV
*/
export function formatAsCSV(data: SQLExportData): string {
const header = data.columns.join(',')
const rows = data.rows.map((row) =>
row.map((cell) => (cell === null ? '' : `"${String(cell).replace(/"/g, '""')}"`)).join(',')
)
return [header, ...rows].join('\n')
}
/**
* 将 SQL 结果格式化为 JSON(数组对象形式)
*/
export function formatAsJSON(data: SQLExportData): string {
const jsonData = data.rows.map((row) => {
const obj: Record<string, unknown> = {}
data.columns.forEach((col, idx) => {
obj[col] = row[idx]
})
return obj
})
return JSON.stringify(jsonData, null, 2)
}
/**
* 导出 SQL 结果到文件
*/
export async function exportSQLResult(
data: SQLExportData,
format: SQLExportFormat
): Promise<{ success: boolean; filePath?: string; error?: string }> {
if (data.rows.length === 0) {
return { success: false, error: 'No data to export' }
}
const timestamp = dayjs().format('YYYYMMDD_HHmmss')
const filename = `sql_result_${timestamp}.${format}`
let content: string
let mimeType: string
if (format === 'json') {
content = formatAsJSON(data)
mimeType = 'application/json'
} else {
content = formatAsCSV(data)
mimeType = 'text/csv'
}
// 转换为 data URL 并保存
const dataUrl = `data:${mimeType};charset=utf-8,${encodeURIComponent(content)}`
const { useCacheService } = await import('@/services/cache/service')
const result = await useCacheService().saveToDownloads(filename, dataUrl)
return result
}