-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSQLServerPlugin.cs
97 lines (88 loc) · 3.42 KB
/
SQLServerPlugin.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.ComponentModel;
using Microsoft.Data.SqlClient;
using Microsoft.SemanticKernel;
namespace SQLMultiAgent
{
public class SQLServerPlugin
{
private string _connectionString;
private SQLMultiAgentRunner? _multiAgent;
public string ConnectionString
{
get { return _connectionString; }
set { _connectionString = value; }
}
//A constructor that takes in no arguments that sets the connection string to the database called AdventureWorks on SQL Server Express on localhost
public SQLServerPlugin(SQLMultiAgentRunner multiAgent)
{
_multiAgent = multiAgent;
_connectionString = "Server=localhost\\SQLEXPRESS;Database=AdventureWorks;Trusted_Connection=True;TrustServerCertificate=True;";
}
public SQLServerPlugin()
{
_connectionString = "Server=localhost\\SQLEXPRESS;Database=AdventureWorks;Trusted_Connection=True;TrustServerCertificate=True;";
}
public string executeSqlQuerySchema = @"
{
""$schema"": ""http://json-schema.org/draft-07/schema#"",
""title"": ""AssistantExecuteSqlQuery"",
""description"": ""Executes a SQL query on the attached database."",
""type"": ""object"",
""properties"": {
""query"": {
""type"": ""string"",
""description"": ""The SQL query to execute""
}
},
""required"": [""query""],
""additionalProperties"": false
}";
/// <summary>
/// An SK function for an Assistant that executes a SQL query on the attached database.
///
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
[KernelFunction("AssistantExecuteSqlQuery")]
[Description("Executes a SQL query on the attached database.")]
[return: Description("The result of the SQL query")]
public string AssistantExecuteSqlQuery(string query)
{
return ExecuteSqlQuery(query).Result;
}
public async Task<string> ExecuteSqlQuery(string query)
{
try
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
var result = "";
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
result += reader.GetValue(i) + "\t";
}
result += Environment.NewLine;
}
_multiAgent.EmitResponse("SQL Runner", "Ran query " + query);
Console.WriteLine("Ran query " + query);
Console.WriteLine(result);
return result;
}
}
}
}
catch (Exception ex)
{
return $"Error: {ex.Message}";
}
}
}
}