Skip to content

Commit

Permalink
新增数据源配置:可以直接执行sql,支持MySQL,PG数据库
Browse files Browse the repository at this point in the history
  • Loading branch information
silencezhang7 committed Oct 18, 2024
1 parent 4aaf9bf commit e84d5eb
Show file tree
Hide file tree
Showing 6 changed files with 838 additions and 1 deletion.
3 changes: 3 additions & 0 deletions packages/plugins/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
"version": "1.0.0",
"type": "module",
"dependencies": {
"@types/pg": "^8.6.6",
"axios": "^1.5.1",
"duck-duck-scrape": "^2.2.5",
"echarts": "5.4.1",
"expr-eval": "^2.0.2",
"lodash": "^4.17.21",
"mysql2": "^3.11.3",
"pg": "^8.10.0",
"wikijs": "^6.4.1"
},
"devDependencies": {
Expand Down
3 changes: 2 additions & 1 deletion packages/plugins/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ const packagePluginList = [
'duckduckgo/searchVideo',
'drawing',
'drawing/baseChart',
'wiki'
'wiki',
'databaseConnection'
];

export const list = [...staticPluginList, ...packagePluginList];
Expand Down
71 changes: 71 additions & 0 deletions packages/plugins/src/databaseConnection/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { Client as PgClient } from 'pg'; // PostgreSQL 客户端
import mysql from 'mysql2/promise'; // MySQL 客户端

type Props = {
databaseType: string;
host: string;
port: string;
databaseName: string;
user: string;
password: string;
sql: string;
};

type Response = Promise<{
result: any; // 根据你的 SQL 查询结果类型调整
}>;

const main = async ({
databaseType,
host,
port,
databaseName,
user,
password,
sql
}: Props): Response => {
let result;

try {
if (databaseType === 'PostgreSQL') {
const client = new PgClient({
host,
port: parseInt(port, 10),
database: databaseName,
user,
password
});

await client.connect();
const res = await client.query(sql);
result = res.rows;
await client.end();
} else if (databaseType === 'MySQL') {
const connection = await mysql.createConnection({
host,
port: parseInt(port, 10),
database: databaseName,
user,
password
});

const [rows] = await connection.execute(sql);
result = rows;
await connection.end();
}
return {
result
};
} catch (error: unknown) {
// 使用类型断言来处理错误
if (error instanceof Error) {
console.error('Database query error:', error.message);
throw new Error(error.message);
} else {
console.error('Database query error:', error);
throw new Error('An unknown error occurred');
}
}
};

export default main;
Loading

0 comments on commit e84d5eb

Please sign in to comment.