using System.Data.Common;
using DS.Module.SqlSugar;
using DS.WMS.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
namespace DS.WMS.MainApi.Controllers
{
///
/// 运维API
///
public class MaintenanceController : ApiController
{
readonly ISqlSugarClient sugarClient;
///
/// 初始化
///
///
public MaintenanceController(ISqlSugarClient sugarClient)
{
this.sugarClient = sugarClient;
}
///
/// 运行SQL脚本
///
/// SQL脚本
/// 运行的数据库,为空时执行全部租户库
///
[HttpPost, Route("RunScript"), AllowAnonymous]
public async Task RunScriptAsync([FromForm] string script, [FromQuery] params string[] dbNames)
{
bool hasError = default;
var linkList = await sugarClient.Queryable().ToListAsync();
DbConnection? connection = null;
try
{
foreach (var item in linkList)
{
var paramArr = item.Connection.Split(';', StringSplitOptions.RemoveEmptyEntries);
if (dbNames != null && dbNames.Length > 0) //指定了数据库名
{
var seg = Array.Find(paramArr, x => x.StartsWith("database", StringComparison.OrdinalIgnoreCase));
if (seg == null)
continue;
string dbName = seg.Split('=')[1];
if (!dbNames.Contains(dbName, StringComparer.OrdinalIgnoreCase))
continue;
}
var fac = DbProviderFactories.GetFactory(sugarClient.Ado.Connection as DbConnection);
connection = fac!.CreateConnection();
connection.ConnectionString = item.Connection;
var cmd = connection.CreateCommand();
cmd.CommandText = script;
await connection.OpenAsync();
await cmd.ExecuteNonQueryAsync();
}
}
catch (Exception ex)
{
await ex.LogAsync(sugarClient);
hasError = true;
}
finally
{
connection?.Dispose();
}
return hasError ? StatusCode(500) : Ok();
}
}
}