-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDapperPartialExtensions.cs
More file actions
258 lines (210 loc) · 9.21 KB
/
DapperPartialExtensions.cs
File metadata and controls
258 lines (210 loc) · 9.21 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
using System.Collections.Concurrent;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Reflection;
using Dapper;
namespace Dapper.PartialUpdate;
public static class DapperPartialExtensions
{
private sealed record PartialProp(
string Name,
PropertyInfo Prop,
PropertyInfo IsSetProp,
PropertyInfo ValueProp
);
private sealed record EntityPlan(
string QualifiedTableName,
PropertyInfo KeyProp,
string KeyColumnName,
IReadOnlyList<PartialProp> PartialProps
);
private static readonly ConcurrentDictionary<Type, EntityPlan> PlanCache = new();
public static int UpdatePartials<T>(
this IDbConnection connection,
T entity,
IDbTransaction? transaction = null,
int? commandTimeout = null)
where T : class
{
if (connection is null) throw new ArgumentNullException(nameof(connection));
if (entity is null) throw new ArgumentNullException(nameof(entity));
var plan = PlanCache.GetOrAdd(typeof(T), BuildPlan);
var keyValue = plan.KeyProp.GetValue(entity)
?? throw new InvalidOperationException("Key value cannot be null.");
var setClauses = new List<string>();
var parameters = new DynamicParameters();
parameters.Add("__key", keyValue);
foreach (var partial in plan.PartialProps)
{
if (!TryReadSetValue(partial, entity, out var value))
continue;
var paramName = $"p_{partial.Name}";
var columnName = GetColumnName(partial.Prop) ?? partial.Name;
setClauses.Add($"{QuoteIdentifier(columnName)} = @{paramName}");
parameters.Add(paramName, value);
}
if (setClauses.Count == 0)
return 0;
var sql = $"UPDATE {plan.QualifiedTableName} SET {string.Join(", ", setClauses)} WHERE {QuoteIdentifier(plan.KeyColumnName)} = @__key;";
return connection.Execute(sql, parameters, transaction, commandTimeout);
}
public static Task<int> UpdatePartialsAsync<T>(
this IDbConnection connection,
T entity,
IDbTransaction? transaction = null,
int? commandTimeout = null)
where T : class
{
if (connection is null) throw new ArgumentNullException(nameof(connection));
if (entity is null) throw new ArgumentNullException(nameof(entity));
var plan = PlanCache.GetOrAdd(typeof(T), BuildPlan);
var keyValue = plan.KeyProp.GetValue(entity)
?? throw new InvalidOperationException("Key value cannot be null.");
var setClauses = new List<string>();
var parameters = new DynamicParameters();
parameters.Add("__key", keyValue);
foreach (var partial in plan.PartialProps)
{
if (!TryReadSetValue(partial, entity, out var value))
continue;
var paramName = $"p_{partial.Name}";
var columnName = GetColumnName(partial.Prop) ?? partial.Name;
setClauses.Add($"{QuoteIdentifier(columnName)} = @{paramName}");
parameters.Add(paramName, value);
}
if (setClauses.Count == 0)
return Task.FromResult(0);
var sql = $"UPDATE {plan.QualifiedTableName} SET {string.Join(", ", setClauses)} WHERE {QuoteIdentifier(plan.KeyColumnName)} = @__key;";
return connection.ExecuteAsync(sql, parameters, transaction, commandTimeout);
}
public static int InsertPartials<T>(
this IDbConnection connection,
T entity,
IDbTransaction? transaction = null,
int? commandTimeout = null)
where T : class
{
if (connection is null) throw new ArgumentNullException(nameof(connection));
if (entity is null) throw new ArgumentNullException(nameof(entity));
var plan = PlanCache.GetOrAdd(typeof(T), BuildPlan);
var parameters = new DynamicParameters();
var columns = new List<string>();
var valueParams = new List<string>();
foreach (var partial in plan.PartialProps)
{
if (!TryReadSetValue(partial, entity, out var value))
continue;
var paramName = $"p_{partial.Name}";
var columnName = GetColumnName(partial.Prop) ?? partial.Name;
columns.Add(QuoteIdentifier(columnName));
valueParams.Add($"@{paramName}");
parameters.Add(paramName, value);
}
string sql;
if (columns.Count == 0)
{
sql = $"INSERT INTO {plan.QualifiedTableName} DEFAULT VALUES;";
}
else
{
sql = $"INSERT INTO {plan.QualifiedTableName} ({string.Join(", ", columns)}) VALUES ({string.Join(", ", valueParams)});";
}
return connection.Execute(sql, parameters, transaction, commandTimeout);
}
public static Task<int> InsertPartialsAsync<T>(
this IDbConnection connection,
T entity,
IDbTransaction? transaction = null,
int? commandTimeout = null)
where T : class
{
if (connection is null) throw new ArgumentNullException(nameof(connection));
if (entity is null) throw new ArgumentNullException(nameof(entity));
var plan = PlanCache.GetOrAdd(typeof(T), BuildPlan);
var parameters = new DynamicParameters();
var columns = new List<string>();
var valueParams = new List<string>();
foreach (var partial in plan.PartialProps)
{
if (!TryReadSetValue(partial, entity, out var value))
continue;
var paramName = $"p_{partial.Name}";
var columnName = GetColumnName(partial.Prop) ?? partial.Name;
columns.Add(QuoteIdentifier(columnName));
valueParams.Add($"@{paramName}");
parameters.Add(paramName, value);
}
string sql;
if (columns.Count == 0)
{
sql = $"INSERT INTO {plan.QualifiedTableName} DEFAULT VALUES;";
}
else
{
sql = $"INSERT INTO {plan.QualifiedTableName} ({string.Join(", ", columns)}) VALUES ({string.Join(", ", valueParams)});";
}
return connection.ExecuteAsync(sql, parameters, transaction, commandTimeout);
}
private static EntityPlan BuildPlan(Type entityType)
{
var props = entityType.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => p.GetMethod is not null && p.SetMethod is not null)
.ToArray();
var keyProp = props.FirstOrDefault(p => p.GetCustomAttribute<KeyAttribute>() is not null)
?? props.FirstOrDefault(p => string.Equals(p.Name, "Id", StringComparison.OrdinalIgnoreCase))
?? props.FirstOrDefault(p => string.Equals(p.Name, entityType.Name + "Id", StringComparison.OrdinalIgnoreCase))
?? throw new InvalidOperationException($"No key property found on {entityType.Name}. Add [Key] or a conventional Id property.");
var tableAttr = entityType.GetCustomAttribute<TableAttribute>();
var tableName = tableAttr?.Name ?? entityType.Name;
var schema = tableAttr?.Schema;
var qualifiedTableName = BuildQualifiedTableName(tableName, schema);
var keyColumnName = GetColumnName(keyProp) ?? keyProp.Name;
var partialProps = new List<PartialProp>();
foreach (var prop in props)
{
if (prop == keyProp)
continue;
if (!IsPartialType(prop.PropertyType, out var isSetProp, out var valueProp))
continue;
partialProps.Add(new PartialProp(prop.Name, prop, isSetProp, valueProp));
}
return new EntityPlan(qualifiedTableName, keyProp, keyColumnName, partialProps);
}
private static bool IsPartialType(Type type, out PropertyInfo isSetProp, out PropertyInfo valueProp)
{
isSetProp = null!;
valueProp = null!;
if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Partial<>))
return false;
isSetProp = type.GetProperty(nameof(Partial<int>.IsSet))!;
valueProp = type.GetProperty(nameof(Partial<int>.Value))!;
return isSetProp is not null && valueProp is not null;
}
private static bool TryReadSetValue<T>(PartialProp partial, T entity, out object? value)
where T : class
{
value = null;
var partialObj = partial.Prop.GetValue(entity);
if (partialObj is null)
return false;
var isSet = (bool?)partial.IsSetProp.GetValue(partialObj);
if (isSet != true)
return false;
value = partial.ValueProp.GetValue(partialObj);
return true;
}
private static string? GetColumnName(PropertyInfo property)
=> property.GetCustomAttribute<ColumnAttribute>()?.Name;
private static string BuildQualifiedTableName(string tableName, string? schema)
{
if (string.IsNullOrWhiteSpace(schema))
return QuoteIdentifier(tableName);
return $"{QuoteIdentifier(schema)}.{QuoteIdentifier(tableName)}";
}
private static string QuoteIdentifier(string identifier)
{
var clean = identifier.Replace("]", "]]", StringComparison.Ordinal);
return $"[{clean}]";
}
}