-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathService.cs
More file actions
104 lines (91 loc) · 2.9 KB
/
Service.cs
File metadata and controls
104 lines (91 loc) · 2.9 KB
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
98
99
100
101
102
103
104
using Azure;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Logging;
namespace Tyc_studio.Plugin.Database;
public interface IDatabaseService
{
DatabaseContext GetContext();
Task<IEnumerable<T>> QueryAsync<T>(string sql, object? parameters = null);
Task<int> ExecuteAsync(string sql, object? parameters = null);
Task<bool> TestConnectionAsync();
}
public class DatabaseService : IDatabaseService, IDisposable
{
private readonly DatabaseContext _context;
private readonly SqlConnection _connection;
private readonly ILogger<DatabaseService> _logger;
public DatabaseContext GetContext() => _context;
public DatabaseService(
DatabaseContext context,
ILogger<DatabaseService> logger)
{
_context = context;
_logger = logger;
if (string.IsNullOrWhiteSpace(_context.ConnectionString))
{
throw new ArgumentException("Connection string is required");
}
_connection = new SqlConnection(_context.ConnectionString);
_logger.LogDebug("DatabaseService created.");
}
public async Task<bool> TestConnectionAsync()
{
try
{
await using var connection = new SqlConnection(_context.ConnectionString);
await connection.OpenAsync();
await connection.CloseAsync();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Database connection test failed");
throw new RequestFailedException(ex.Message, ex);
}
}
public async Task<IEnumerable<T>> QueryAsync<T>(string sql, object? parameters)
{
if (string.IsNullOrWhiteSpace(sql))
{
_logger.LogWarning("QueryAsync called with empty SQL.");
return [];
}
try
{
await using var connection = new SqlConnection(_context.ConnectionString);
await connection.OpenAsync();
var result = await connection.QueryAsync<T>(sql, parameters);
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "QueryAsync failed. SQL: {Sql}", sql);
return [];
}
}
public async Task<int> ExecuteAsync(string sql, object? parameters)
{
if (string.IsNullOrWhiteSpace(sql))
{
_logger.LogWarning("ExecuteAsync called with empty SQL.");
return -1;
}
try
{
await using var connection = new SqlConnection(_context.ConnectionString);
await connection.OpenAsync();
var affected = await connection.ExecuteAsync(sql, parameters);
return affected;
}
catch (Exception ex)
{
_logger.LogError(ex, "ExecuteAsync failed. SQL: {Sql}", sql);
return -1;
}
}
public void Dispose()
{
_connection.Dispose();
}
}