Your Name 817309ade9
Some checks failed
Lint / build (20) (push) Has been cancelled
Playwright Tests / test (push) Has been cancelled
feat: add sqlserver admin connection settings
2026-03-24 17:01:50 +08:00

67 lines
1.8 KiB
TypeScript

import "server-only";
import sql from "mssql";
import {
normalizeThirdPartySqlServerConfig,
type NormalizedThirdPartySqlServerConfig,
} from "@/lib/sqlserver/config";
function toSqlServerConnectionConfig(config: NormalizedThirdPartySqlServerConfig): sql.config {
return {
server: config.host,
port: config.port,
user: config.username,
password: config.password,
database: config.database,
options: {
encrypt: config.encrypt,
trustServerCertificate: config.trustServerCertificate,
},
connectionTimeout: config.connectionTimeoutMs,
requestTimeout: config.requestTimeoutMs,
pool: {
max: 1,
min: 0,
idleTimeoutMillis: 5000,
},
};
}
export async function testSqlServerConnection(configValue: unknown) {
const config = normalizeThirdPartySqlServerConfig(configValue);
if (!config.host) {
throw new Error("请填写 SQL Server 主机地址");
}
if (!config.database) {
throw new Error("请填写数据库名称");
}
if (!config.username) {
throw new Error("请填写数据库账号");
}
if (!config.password) {
throw new Error("请填写数据库密码");
}
const startedAt = Date.now();
const pool = new sql.ConnectionPool(toSqlServerConnectionConfig(config));
try {
await pool.connect();
const result = await pool
.request()
.query("SELECT @@SERVERNAME AS serverName, DB_NAME() AS databaseName, @@VERSION AS version");
const row = result.recordset?.[0] || {};
return {
latencyMs: Date.now() - startedAt,
serverName: String(row.serverName || config.host),
databaseName: String(row.databaseName || config.database),
version: String(row.version || "").trim(),
};
} finally {
await pool.close().catch(() => undefined);
}
}