You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.6 KiB
C#

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
{
/// <summary>
/// 运维API
/// </summary>
public class MaintenanceController : ApiController
{
readonly ISqlSugarClient sugarClient;
/// <summary>
/// 初始化
/// </summary>
/// <param name="sugarClient"></param>
public MaintenanceController(ISqlSugarClient sugarClient)
{
this.sugarClient = sugarClient;
}
/// <summary>
/// 运行SQL脚本
/// </summary>
/// <param name="script">SQL脚本</param>
/// <param name="dbNames">运行的数据库,为空时执行全部租户库</param>
/// <returns></returns>
[HttpPost, Route("RunScript"), AllowAnonymous]
public async Task<IActionResult> RunScriptAsync([FromForm] string script, [FromQuery] params string[] dbNames)
{
bool hasError = default;
var linkList = await sugarClient.Queryable<SysTenantLink>().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();
}
}
}