初始化项目;更新至 v0.1.0_20251209 版本
This commit is contained in:
58
services/gemini.ts
Normal file
58
services/gemini.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
|
||||
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 {
|
||||
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
|
||||
|
||||
// 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) {
|
||||
console.error("Error generating SQL:", error);
|
||||
throw new Error("生成 SQL 失败,请检查 API Key 或网络连接。");
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user