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); } }