-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryBase.cs
More file actions
189 lines (157 loc) · 6.01 KB
/
QueryBase.cs
File metadata and controls
189 lines (157 loc) · 6.01 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
using StilettoSQL.Query;
using System.Data;
using System.Data.Common;
using System.Text;
namespace StilettoSQL.Internal;
public class QueryBase {
internal List<object?>? positionParms;
protected TimeSpan? _Timeout { get; set; }
protected void ConsumeParmsFrom(QueryBase other) {
if (other.positionParms == null) return;
positionParms ??= new();
positionParms.AddRange(other.positionParms);
other.positionParms = null;
}
protected void AddPosParm(object? data) {
(positionParms ??= new()).Add(data);
}
protected void AddPosParms(params object?[] list) {
if (list.Length == 0) return;
(positionParms ??= new()).AddRange(list);
}
public string ReplacePlaceholders(string sql, StProfile profile) {
if (positionParms == null) return sql;
StringBuilder? sb = null;
int i_from = 0;
int count = 0;
int i = 0;
while (i < sql.Length - 1) {
// skip strings
if (sql[i] == '\'') {
i++;
for (; i < sql.Length - 1; i++) {
//if (sql[i] == '\\' && sql[i+1] == '\'') {
// i += 2 ;
// continue;
//}
if (sql[i] == '\'') {
i++;
break;
}
}
continue;
}
if (sql[i] == '?' && sql[i + 1] == '?') {
sb ??= new(sql.Length + positionParms.Count);
sb.Append(sql, i_from, i - i_from);
if (profile.ProviderSQL == StProviderSQL.PostgreSQL) {
sb.Append('$');
sb.Append(++count);
} else if (profile.ProviderSQL == StProviderSQL.MySQL) {
sb.Append('?');
} else {
throw new NotSupportedException();
}
i += 2;
i_from = i;
} else {
i++;
}
}
if (sb == null) {
// ok user can use native ($1, $2, ...) or (?, ?, ...)
return sql;
}
sb.Append(sql, i_from, sql.Length - i_from);
if (count != positionParms.Count)
throw new Exception($"Excepted {count} parms. Have: {positionParms.Count}");
var res = sb.ToString();
return res;
}
class ActionCtx : IDisposable {
public DbConnection? con;
public DbCommand? cmd;
public AutoTransaction? transact;
public bool need_dispose_con = true;
public void Dispose() {
if (transact != null) transact.commandsCount--;
if(need_dispose_con) con?.Dispose();
cmd?.Dispose();
}
}
async Task<ActionCtx> NewCommandCtx(string sql) {
var ctx = new ActionCtx();
try {
var profile = StProfile.CurrentProfile;
var transact = StProfile.CurrentTransaction_.Value;
if (transact == null) {
// как обычно, делаем новое подключение
ctx.con = profile.CreateConnection();
await ctx.con.OpenAsync();
ctx.cmd = ctx.con.CreateCommand();
} else {
// коннектимся к транзакции
ctx.need_dispose_con = false; // не владеем
if (transact.Connection != null) {
ctx.con = transact.Connection;
} else {
// первое подключение
ctx.con = transact.Connection = profile.CreateConnection();
await ctx.con.OpenAsync();
transact.transact = await ctx.con.BeginTransactionAsync();
}
if (transact.commandsCount != 0) {
throw new Exception("Other command still in progress for transaction connection");
}
transact.commandsCount++;
ctx.transact = transact;
ctx.cmd = ctx.con.CreateCommand();
ctx.cmd.Transaction = transact.transact;
}
var cmd = ctx.cmd;
cmd.CommandText = ReplacePlaceholders(sql, profile);
if (_Timeout != null) {
cmd.CommandTimeout = (int)_Timeout.Value.TotalSeconds;
}
if (positionParms != null) {
foreach (var item in positionParms) {
var p = cmd.CreateParameter();
if (item == null) p.Value = DBNull.Value;
else {
if (profile.DataConverter?.ToDb(item, p) != true) {
// стандартный конверт
p.Value = item;
}
}
cmd.Parameters.Add(p);
}
}
return ctx;
} catch (Exception) {
ctx.Dispose(); // чистка
throw;
}
}
protected async IAsyncEnumerable<DbDataReader> ExecuteReader(string sql) {
using var ctx = await NewCommandCtx(sql);
using var rdr = await ctx.cmd.ExecuteReaderAsync();
while (await rdr.ReadAsync()) {
yield return rdr;
}
}
async protected Task<object?> ExecuteScalar(string sql) {
using var ctx = await NewCommandCtx(sql);
return ctx.cmd.ExecuteScalar();
}
async protected Task<T?> ExecuteScalar<T>(string sql) {
using var ctx = await NewCommandCtx(sql);
// Use reader for auto-conversion.
using var rdr = await ctx.cmd.ExecuteReaderAsync();
if (!await rdr.ReadAsync()) return StProfile.ConvertToNull<T>();
return StProfile.CurrentProfile.ConvertFromDb<T>(rdr, 0);
}
async protected Task<int> ExecuteNonQuery(string sql) {
using var ctx = await NewCommandCtx(sql);
return await ctx.cmd.ExecuteNonQueryAsync();
}
}