66 lines
2.9 KiB
TypeScript
66 lines
2.9 KiB
TypeScript
|
||
import { GoogleGenAI } from "@google/genai";
|
||
import { SqlGenerationRequest } from "../types";
|
||
|
||
const generateSqlPrompt = (data: SqlGenerationRequest): string => {
|
||
return `
|
||
你是一名世界级的数据库架构师和SQL专家。请根据以下提供的信息,编写一个精确、高效的 SQL 查询语句。
|
||
|
||
### 1. 目标数据库类型
|
||
**${data.databaseType}**
|
||
(请严格遵守该数据库的方言规范,包括引号使用、函数名称、分页语法、字符串连接方式等)
|
||
|
||
### 2. 业务表结构与字段说明
|
||
${data.tableStructure}
|
||
|
||
### 3. 字典表信息 (用于代码转义)
|
||
${data.dictionaryData}
|
||
|
||
### 4. 查询需求
|
||
${data.requirement}
|
||
|
||
### 任务要求:
|
||
1. **自动关联**:根据表结构和字典表,自动构建 JOIN 语句。
|
||
2. **字典翻译**:需求中提到的字段如果需要字典翻译(例如:政治面貌、国籍等),请务必关联字典表,取出对应的中文名称(Label/Value)。
|
||
3. **输出格式**:只返回一段纯净的 SQL 代码,不需要 markdown 标记(如 \`\`\`sql),不需要解释文字。
|
||
4. **命名规范**:使用清晰的表别名(Alias),例如 main_table 为 t1, dict_table 为 d1 等。
|
||
5. **语法兼容**:针对 **${data.databaseType}** 进行优化。例如:
|
||
- 如果是 Oracle,请注意字段通常大写,使用双引号处理特殊列名,日期处理使用 TO_DATE/TO_CHAR。
|
||
- 如果是 MySQL,使用反引号 (\`) 处理列名。
|
||
- 如果是 SQL Server,使用 [] 处理列名,注意 TOP 语法。
|
||
`;
|
||
};
|
||
|
||
export const generateSql = async (requestData: SqlGenerationRequest): Promise<string> => {
|
||
try {
|
||
// Prioritize the user-provided key, fallback to the environment variable
|
||
const apiKey = requestData.apiKey || process.env.API_KEY;
|
||
|
||
if (!apiKey) {
|
||
throw new Error("未配置 API Key。请点击右上角设置按钮输入您的 Google Gemini API Key,或联系管理员配置环境变量。");
|
||
}
|
||
|
||
const ai = new GoogleGenAI({ apiKey: apiKey });
|
||
|
||
// Using gemini-2.5-flash for speed and good reasoning capabilities on coding tasks
|
||
const response = await ai.models.generateContent({
|
||
model: 'gemini-2.5-flash',
|
||
contents: generateSqlPrompt(requestData),
|
||
config: {
|
||
thinkingConfig: { thinkingBudget: 0 }, // Disable thinking for faster direct response
|
||
temperature: 0.2, // Lower temperature for more deterministic code generation
|
||
}
|
||
});
|
||
|
||
let sql = response.text || '';
|
||
|
||
// Clean up potential markdown formatting if the model adds it despite instructions
|
||
sql = sql.replace(/^```sql\n/, '').replace(/^```\n/, '').replace(/\n```$/, '');
|
||
|
||
return sql.trim();
|
||
} catch (error: any) {
|
||
console.error("Error generating SQL:", error);
|
||
// Pass through the specific error message if possible
|
||
throw new Error(error.message || "生成 SQL 失败,请检查 API Key 或网络连接。");
|
||
}
|
||
}; |