BotSharp/src/Plugins/BotSharp.Plugin.SqlDriver/Functions/SqlSelect.cs

74 lines
2.3 KiB
C#
Raw Normal View History

2024-02-19 22:55:41 +00:00
using BotSharp.Plugin.SqlDriver.Models;
2024-09-17 11:32:11 +00:00
using Microsoft.Data.SqlClient;
2024-02-19 22:55:41 +00:00
using MySqlConnector;
using static Dapper.SqlMapper;
namespace BotSharp.Plugin.SqlDriver.Functions;
public class SqlSelect : IFunctionCallback
{
public string Name => "sql_select";
private readonly IServiceProvider _services;
public SqlSelect(IServiceProvider services)
{
_services = services;
}
public async Task<bool> Execute(RoleDialogModel message)
{
var args = JsonSerializer.Deserialize<SqlStatement>(message.FunctionArgs);
2024-09-10 22:12:17 +00:00
if (args.GeneratedWithoutTableDefinition)
{
message.Content = $"Get the table definition first.";
return false;
}
2024-02-21 04:31:09 +00:00
2024-02-19 22:55:41 +00:00
// check if need to instantely
2024-09-10 22:12:17 +00:00
var settings = _services.GetRequiredService<SqlDriverSetting>();
2024-09-17 11:32:11 +00:00
var result = settings.DatabaseType switch
2024-02-19 22:55:41 +00:00
{
2024-09-17 11:32:11 +00:00
"MySql" => RunQueryInMySql(args),
"SqlServer" => RunQueryInSqlServer(args),
_ => throw new NotImplementedException($"Database type {settings.DatabaseType} is not supported.")
};
2024-02-19 22:55:41 +00:00
2024-09-10 22:12:17 +00:00
if (result == null)
{
message.Content = "Record not found";
2024-02-19 22:55:41 +00:00
}
else
{
2024-09-10 22:12:17 +00:00
message.Content = JsonSerializer.Serialize(result);
args.Return.Value = message.Content;
2024-02-19 22:55:41 +00:00
}
2024-09-10 22:12:17 +00:00
2024-02-19 22:55:41 +00:00
return true;
}
2024-09-17 11:32:11 +00:00
private IEnumerable<dynamic> RunQueryInMySql(SqlStatement args)
{
var settings = _services.GetRequiredService<SqlDriverSetting>();
using var connection = new MySqlConnection(settings.MySqlExecutionConnectionString);
var dictionary = new Dictionary<string, object>();
foreach (var p in args.Parameters)
{
dictionary["@" + p.Name] = p.Value;
}
return connection.Query(args.Statement, dictionary);
}
private IEnumerable<dynamic> RunQueryInSqlServer(SqlStatement args)
{
var settings = _services.GetRequiredService<SqlDriverSetting>();
using var connection = new SqlConnection(settings.SqlServerExecutionConnectionString ?? settings.SqlServerConnectionString);
var dictionary = new Dictionary<string, object>();
foreach (var p in args.Parameters)
{
dictionary["@" + p.Name] = p.Value;
}
return connection.Query(args.Statement, dictionary);
}
2024-02-19 22:55:41 +00:00
}