-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathsql-translate.ts
More file actions
83 lines (74 loc) · 2.73 KB
/
sql-translate.ts
File metadata and controls
83 lines (74 loc) · 2.73 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import z from "zod"
import { Tool } from "../../tool/tool"
import { Dispatcher } from "../native"
import type { SqlTranslateResult } from "../native/types"
export const SqlTranslateTool = Tool.define("sql_translate", {
description:
"Translate SQL from one database dialect to another (e.g., Snowflake to PostgreSQL, BigQuery to Snowflake, MySQL to PostgreSQL). Supports all major dialects: snowflake, bigquery, postgres, mysql, tsql, hive, spark, databricks, redshift, duckdb, and more.",
parameters: z.object({
sql: z.string().describe("SQL query to translate"),
source_dialect: z
.string()
.describe("Source SQL dialect (e.g., snowflake, bigquery, postgres, mysql, tsql, redshift, duckdb)"),
target_dialect: z
.string()
.describe("Target SQL dialect (e.g., snowflake, bigquery, postgres, mysql, tsql, redshift, duckdb)"),
}),
async execute(args, ctx) {
try {
const result = await Dispatcher.call("sql.translate", {
sql: args.sql,
source_dialect: args.source_dialect,
target_dialect: args.target_dialect,
})
return {
title: `Translate: ${args.source_dialect} → ${args.target_dialect} [${result.success ? "OK" : "FAIL"}]`,
metadata: {
success: result.success,
source_dialect: result.source_dialect,
target_dialect: result.target_dialect,
warningCount: (result.warnings ?? []).length,
...(result.error && { error: result.error }),
},
output: formatTranslation(result, args.sql),
}
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
return {
title: `Translate: ERROR`,
metadata: {
success: false,
source_dialect: args.source_dialect,
target_dialect: args.target_dialect,
warningCount: 0,
error: msg,
},
output: `Failed to translate SQL: ${msg}\n\nCheck your connection configuration and try again.`,
}
}
},
})
function formatTranslation(result: SqlTranslateResult, originalSql: string): string {
if (!result.success) {
return `Translation failed: ${result.error ?? "Unknown error"}`
}
const lines: string[] = []
lines.push(`Source dialect: ${result.source_dialect}`)
lines.push(`Target dialect: ${result.target_dialect}`)
lines.push("")
lines.push("--- Original SQL ---")
lines.push(originalSql.trim())
lines.push("")
lines.push("--- Translated SQL ---")
lines.push(result.translated_sql ?? "")
lines.push("")
const warnings = result.warnings ?? []
if (warnings.length > 0) {
lines.push("--- Warnings ---")
for (const warning of warnings) {
lines.push(` ! ${warning}`)
}
lines.push("")
}
return lines.join("\n")
}