2024-08-22 15:15:05 +00:00
|
|
|
using MySqlConnector;
|
|
|
|
|
using static Dapper.SqlMapper;
|
|
|
|
|
|
|
|
|
|
namespace BotSharp.Plugin.SqlDriver.Functions;
|
|
|
|
|
|
|
|
|
|
public class GetTableDefinitionFn : IFunctionCallback
|
|
|
|
|
{
|
|
|
|
|
public string Name => "get_table_definition";
|
|
|
|
|
private readonly IServiceProvider _services;
|
|
|
|
|
|
|
|
|
|
public GetTableDefinitionFn(IServiceProvider services)
|
|
|
|
|
{
|
|
|
|
|
_services = services;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<bool> Execute(RoleDialogModel message)
|
|
|
|
|
{
|
|
|
|
|
var agentService = _services.GetRequiredService<IAgentService>();
|
|
|
|
|
var sqlDriver = _services.GetRequiredService<SqlDriverService>();
|
|
|
|
|
var settings = _services.GetRequiredService<SqlDriverSetting>();
|
2024-08-30 21:12:20 +00:00
|
|
|
|
|
|
|
|
// Get table DDL from database
|
2024-08-22 15:15:05 +00:00
|
|
|
using var connection = new MySqlConnection(settings.MySqlConnectionString);
|
|
|
|
|
var dictionary = new Dictionary<string, object>();
|
2024-08-30 21:12:20 +00:00
|
|
|
var tableDdls = new List<string>();
|
2024-08-22 15:15:05 +00:00
|
|
|
|
|
|
|
|
foreach (var p in (List<string>)message.Data)
|
|
|
|
|
{
|
|
|
|
|
var escapedTableName = MySqlHelper.EscapeString(p);
|
2024-08-30 21:12:20 +00:00
|
|
|
dictionary["@" + "table_name"] = p;
|
2024-08-22 15:15:05 +00:00
|
|
|
dictionary["table_name"] = escapedTableName;
|
|
|
|
|
|
2024-08-30 21:12:20 +00:00
|
|
|
var sql = $"select * from information_schema.tables where table_name ='{escapedTableName}'";
|
2024-08-22 15:15:05 +00:00
|
|
|
var result = connection.QueryFirstOrDefault(sql: sql, dictionary);
|
2024-08-30 21:12:20 +00:00
|
|
|
if (result == null) continue;
|
|
|
|
|
|
|
|
|
|
sql = $"SHOW CREATE TABLE `{escapedTableName}`";
|
|
|
|
|
result = connection.QueryFirstOrDefault(sql: sql, dictionary);
|
|
|
|
|
tableDdls.Add(result);
|
2024-08-22 15:15:05 +00:00
|
|
|
}
|
|
|
|
|
|
2024-08-30 21:12:20 +00:00
|
|
|
message.Content = string.Join("\r\n", tableDdls);
|
2024-08-22 15:15:05 +00:00
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
}
|