-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlexiReportService.cs
More file actions
76 lines (60 loc) · 2.57 KB
/
Copy pathFlexiReportService.cs
File metadata and controls
76 lines (60 loc) · 2.57 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
using FlexiReport.Dtos;
using Microsoft.EntityFrameworkCore;
using TS.Result;
namespace FlexiReport;
public sealed class FlexiReportService
{
public async Task<List<DatabaseSchemaDto>> GetDatabaseSchemaAsync(DbContext dbContext, CancellationToken cancellationToken = default)
{
using var connection = dbContext.Database.GetDbConnection();
await connection.OpenAsync();
var query = @"
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
ORDER BY TABLE_NAME, ORDINAL_POSITION";
var schema = new Dictionary<string, List<string>>();
using var command = connection.CreateCommand();
command.CommandText = query;
using var reader = await command.ExecuteReaderAsync(cancellationToken);
while (await reader.ReadAsync())
{
string tableName = reader.GetString(0);
string columnName = reader.GetString(1);
if (!schema.ContainsKey(tableName))
schema[tableName] = new List<string>();
schema[tableName].Add(columnName);
}
var respons = schema.Where(p => p.Key != "__EFMigrationsHistory").Select(s => new DatabaseSchemaDto(s.Key, s.Value)).ToList();
return respons;
}
public async Task<Result<object>> ExecuteQueryAsync(QueryRequestDto request, DbContext dbContext, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(request.SqlQuery))
return Result<object>.Failure("SQL query cannot be empty");
if (!request.SqlQuery.TrimStart().StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
return Result<object>.Failure("You can only use SELECT queries");
try
{
using var connection = dbContext.Database.GetDbConnection();
await connection.OpenAsync();
using var command = connection.CreateCommand();
command.CommandText = request.SqlQuery;
using var reader = await command.ExecuteReaderAsync();
var result = new List<Dictionary<string, object>>();
while (await reader.ReadAsync())
{
var row = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
row[reader.GetName(i)] = await reader.IsDBNullAsync(i) ? null : reader.GetValue(i);
}
result.Add(row);
}
return result;
}
catch (Exception ex)
{
return Result<object>.Failure(ex.Message);
}
}
}