| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- using System.Data.Common;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using SqlSugar;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform;
- /// <summary>
- /// 把本环境已注册的 t8_v5 连接抄进 mdp_source。只填 db_host 为空的行,不把口令写入迁移脚本或日志。
- /// </summary>
- public sealed class MdpSourceConnectionImportService : IHostedService
- {
- private readonly ISqlSugarClient _db;
- private readonly ILogger<MdpSourceConnectionImportService> _logger;
- public MdpSourceConnectionImportService(ISqlSugarClient db, ILogger<MdpSourceConnectionImportService> logger)
- {
- _db = db;
- _logger = logger;
- }
- public async Task StartAsync(CancellationToken cancellationToken)
- {
- try
- {
- if (!_db.AsTenant().IsAnyConnection("t8_v5"))
- return;
- var conn = _db.AsTenant().GetConnectionScope("t8_v5").CurrentConnectionConfig.ConnectionString;
- if (string.IsNullOrWhiteSpace(conn))
- return;
- var builder = new DbConnectionStringBuilder { ConnectionString = conn };
- string? Host() => First(builder, "Server", "Data Source", "Host");
- var hostRaw = Host() ?? "";
- var host = hostRaw;
- int? port = null;
- var comma = hostRaw.LastIndexOf(',');
- if (comma > 0 && int.TryParse(hostRaw[(comma + 1)..], out var p))
- {
- host = hostRaw[..comma];
- port = p;
- }
- var dbName = First(builder, "Database", "Initial Catalog");
- var user = First(builder, "User Id", "Uid", "User ID");
- var password = First(builder, "Password", "Pwd") ?? "";
- if (string.IsNullOrWhiteSpace(host) || string.IsNullOrWhiteSpace(dbName) || string.IsNullOrWhiteSpace(user))
- return;
- var n = await _db.Ado.ExecuteCommandAsync(
- """
- UPDATE mdp_source
- SET db_type='SQLSERVER', db_host=@host, db_port=@port, db_name=@name,
- db_user=@user, db_password_enc=@pwd, conn_mode='EXTERNAL'
- WHERE source_code='T8_V5_SQLSERVER' AND IFNULL(db_host,'')=''
- """,
- new List<SugarParameter>
- {
- new("@host", host),
- new("@port", port),
- new("@name", dbName),
- new("@user", user),
- new("@pwd", password)
- });
- if (n > 0)
- _logger.LogInformation("已从已注册连接导入来源 T8_V5_SQLSERVER 的连接(口令已写入)");
- }
- catch (Exception ex)
- {
- _logger.LogWarning("来源连接导入跳过:{Message}", ex.Message);
- }
- }
- public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
- private static string? First(DbConnectionStringBuilder builder, params string[] keys)
- {
- foreach (var key in keys)
- {
- if (builder.TryGetValue(key, out var value) && value is string s && !string.IsNullOrWhiteSpace(s))
- return s;
- }
- return null;
- }
- }
|