-
Notifications
You must be signed in to change notification settings - Fork 935
/
Copy pathSqlUpdateBuilder.cs
367 lines (320 loc) · 11.4 KB
/
SqlUpdateBuilder.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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Engine;
using NHibernate.SqlTypes;
using NHibernate.Type;
using NHibernate.Util;
namespace NHibernate.SqlCommand
{
/// <summary>
/// A class that builds an <c>UPDATE</c> sql statement.
/// </summary>
public class SqlUpdateBuilder : SqlBaseBuilder, ISqlStringBuilder
{
private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(SqlUpdateBuilder));
private string tableName;
private string comment;
// columns-> (ColumnName, Value) or (ColumnName, SqlType) for parametrized column
private readonly LinkedHashMap<string, object> columns = new LinkedHashMap<string, object>();
private List<SqlString> whereStrings = new List<SqlString>();
private readonly List<SqlType> whereParameterTypes = new List<SqlType>();
private SqlString assignments;
public SqlUpdateBuilder(Dialect.Dialect dialect, IMapping mapping)
: base(dialect, mapping) {}
public SqlUpdateBuilder SetTableName(string tableName)
{
this.tableName = tableName;
return this;
}
public SqlUpdateBuilder SetComment(string comment)
{
this.comment = comment;
return this;
}
/// <summary>
/// Add a column with a specific value to the UPDATE sql
/// </summary>
/// <param name="columnName">The name of the Column to add.</param>
/// <param name="val">The value to set for the column.</param>
/// <param name="literalType">The NHibernateType to use to convert the value to a sql string.</param>
/// <returns>The SqlUpdateBuilder.</returns>
// Since v5.6
[Obsolete("This method is unsafe and has no more usages. Use the overload with a property type and use a parameterized query.")]
public SqlUpdateBuilder AddColumn(string columnName, object val, ILiteralType literalType)
{
return AddColumn(columnName, literalType.ObjectToSQLString(val, Dialect));
}
/// <summary>
/// Add a column with a specific value to the UPDATE sql
/// </summary>
/// <param name="columnName">The name of the Column to add.</param>
/// <param name="val">A valid sql string to set as the value of the column.</param>
/// <returns>The SqlUpdateBuilder.</returns>
public SqlUpdateBuilder AddColumn(string columnName, string val)
{
AddColumnWithValueOrType(columnName, val);
return this;
}
/// <summary>
/// Adds columns with a specific value to the UPDATE sql
/// </summary>
/// <param name="columnsName">The names of the Columns to add.</param>
/// <param name="val">A valid sql string to set as the value of the column. This value is assigned to each column.</param>
/// <returns>The SqlUpdateBuilder.</returns>
public SqlUpdateBuilder AddColumns(string[] columnsName, string val)
{
foreach (string columnName in columnsName)
AddColumnWithValueOrType(columnName, val);
return this;
}
public virtual SqlUpdateBuilder AddColumn(string columnName, IType propertyType)
{
SqlType[] sqlTypes = propertyType.SqlTypes(Mapping);
if (sqlTypes.Length > 1)
throw new AssertionFailure("Adding one column for a composed IType.");
AddColumnWithValueOrType(columnName, sqlTypes[0]);
return this;
}
/// <summary>
/// Adds the Property's columns to the UPDATE sql
/// </summary>
/// <param name="columnNames">An array of the column names for the Property</param>
/// <param name="propertyType">The IType of the property.</param>
/// <returns>The SqlUpdateBuilder.</returns>
public SqlUpdateBuilder AddColumns(string[] columnNames, IType propertyType)
{
return AddColumns(columnNames, null, propertyType);
}
/// <summary>
/// Adds the Property's updatable columns to the UPDATE sql
/// </summary>
/// <param name="columnNames">An array of the column names for the Property</param>
/// <param name="updateable">An array of updatable column flags. If this array is <c>null</c>, all supplied columns are considered updatable.</param>
/// <param name="propertyType">The IType of the property.</param>
/// <returns>The SqlUpdateBuilder.</returns>
public SqlUpdateBuilder AddColumns(string[] columnNames, bool[] updateable, IType propertyType)
{
SqlType[] sqlTypes = propertyType.SqlTypes(Mapping);
for (int i = 0; i < columnNames.Length; i++)
{
if (updateable == null || updateable[i])
{
if (i >= sqlTypes.Length)
throw new AssertionFailure("Different columns and it's IType.");
AddColumnWithValueOrType(columnNames[i], sqlTypes[i]);
}
}
return this;
}
private void AddColumnWithValueOrType(string columnName, object valueOrType)
{
if (columns.ContainsKey(columnName))
throw new ArgumentException(
$"The column '{columnName}' has already been added in this SQL builder",
nameof(columnName));
columns.Add(columnName, valueOrType);
}
public SqlUpdateBuilder AppendAssignmentFragment(SqlString fragment)
{
// SqlString is immutable
assignments = assignments == null ? fragment : assignments.Append(", ", fragment);
return this;
}
// Since v5.2
[Obsolete("This method has no more usage.")]
public SqlUpdateBuilder SetJoin(string joinTableName, string[] keyColumnNames, IType identityType, string[] lhsColumnNames, string[] rhsColumnNames)
{
var sqlBuilder = new SqlStringBuilder()
.Add("EXISTS (SELECT * FROM ")
.Add(joinTableName)
.Add(" WHERE ")
.Add(ToWhereString(joinTableName, keyColumnNames));
for (int columnIndex = 0; columnIndex < lhsColumnNames.Length; columnIndex++)
{
sqlBuilder.Add(" AND ")
.Add(tableName)
.Add(StringHelper.Dot.ToString())
.Add(lhsColumnNames[columnIndex])
.Add("=")
.Add(joinTableName)
.Add(StringHelper.Dot.ToString())
.Add(rhsColumnNames[columnIndex]);
}
sqlBuilder.Add(")");
whereStrings.Add(sqlBuilder.ToSqlString());
whereParameterTypes.AddRange(identityType.SqlTypes(Mapping));
return this;
}
public SqlUpdateBuilder SetWhere(string whereSql)
{
if (StringHelper.IsNotEmpty(whereSql))
{
whereStrings = new List<SqlString>(new[] { new SqlString(whereSql) });
}
return this;
}
/// <summary>
/// Sets the IdentityColumn for the <c>UPDATE</c> sql to use.
/// </summary>
/// <param name="columnNames">An array of the column names for the Property</param>
/// <param name="identityType">The IType of the Identity Property.</param>
/// <returns>The SqlUpdateBuilder.</returns>
public SqlUpdateBuilder SetIdentityColumn(string[] columnNames, IType identityType)
{
whereStrings.Add(ToWhereString(columnNames));
whereParameterTypes.AddRange(identityType.SqlTypes(Mapping));
return this;
}
/// <summary>
/// Sets the VersionColumn for the <c>UPDATE</c> sql to use.
/// </summary>
/// <param name="columnNames">An array of the column names for the Property</param>
/// <param name="versionType">The IVersionType of the Version Property.</param>
/// <returns>The SqlUpdateBuilder.</returns>
public SqlUpdateBuilder SetVersionColumn(string[] columnNames, IVersionType versionType)
{
whereStrings.Add(ToWhereString(columnNames));
whereParameterTypes.AddRange(versionType.SqlTypes(Mapping));
return this;
}
/// <summary>
/// Adds the columns for the Type to the WhereFragment
/// </summary>
/// <param name="columnNames">The names of the columns to add.</param>
/// <param name="type">The IType of the property.</param>
/// <param name="op">The operator to put between the column name and value.</param>
/// <returns>The SqlUpdateBuilder</returns>
public SqlUpdateBuilder AddWhereFragment(string[] columnNames, IType type, string op)
{
if (columnNames.Length > 0)
{
// Don't add empty conditions - we get extra ANDs
whereStrings.Add(ToWhereString(columnNames, op));
whereParameterTypes.AddRange(type.SqlTypes(Mapping));
}
return this;
}
public SqlUpdateBuilder AddWhereFragment(string[] columnNames, SqlType[] types, string op)
{
if (columnNames.Length > 0)
{
// Don't add empty conditions - we get extra ANDs
whereStrings.Add(ToWhereString(columnNames, op));
whereParameterTypes.AddRange(types);
}
return this;
}
public SqlUpdateBuilder AddWhereFragment(string columnName, SqlType type, string op)
{
if (!string.IsNullOrEmpty(columnName))
{
whereStrings.Add(ToWhereString(columnName, op));
whereParameterTypes.Add(type);
}
return this;
}
/// <summary>
/// Adds a string to the WhereFragment
/// </summary>
/// <param name="whereSql">A well formed sql string with no parameters.</param>
/// <returns>The SqlUpdateBuilder</returns>
public SqlUpdateBuilder AddWhereFragment(string whereSql)
{
// Don't add empty conditions - we get extra ANDs
if (!string.IsNullOrEmpty(whereSql))
{
whereStrings.Add(new SqlString(whereSql));
}
return this;
}
#region ISqlStringBuilder Members
/// <summary></summary>
public SqlString ToSqlString()
{
// 3 = "UPDATE", tableName, "SET"
int initialCapacity = 3;
// will have a comma for all but the first column, and then for each column
// will have a name, " = ", value so multiply by 3
if (columns.Count > 0)
{
initialCapacity += (columns.Count - 1) + (columns.Count * 3);
}
// 1 = "WHERE"
initialCapacity++;
// the "AND" before all but the first whereString
if (whereStrings.Count > 0)
{
initialCapacity += (whereStrings.Count - 1);
initialCapacity += whereStrings.Sum(x => x.Count);
}
if (!string.IsNullOrEmpty(comment))
initialCapacity++;
var sqlBuilder = new SqlStringBuilder(initialCapacity + 2);
if (!string.IsNullOrEmpty(comment))
sqlBuilder.Add("/* " + comment + " */ ");
sqlBuilder.Add("UPDATE ")
.Add(tableName)
.Add(" SET ");
bool assignmentsAppended = false;
bool commaNeeded = false;
foreach (KeyValuePair<string, object> valuePair in columns)
{
if (commaNeeded)
sqlBuilder.Add(StringHelper.CommaSpace);
commaNeeded = true;
sqlBuilder.Add(valuePair.Key)
.Add(" = ");
SqlType param = valuePair.Value as SqlType;
if (param != null)
sqlBuilder.Add(Parameter.Placeholder);
else
sqlBuilder.Add((string) valuePair.Value);
assignmentsAppended = true;
}
if (assignments != null)
{
if (assignmentsAppended)
{
sqlBuilder.Add(", ");
}
sqlBuilder.Add(assignments);
}
sqlBuilder.Add(" WHERE ");
bool andNeeded = false;
foreach (SqlString whereString in whereStrings)
{
if (andNeeded)
sqlBuilder.Add(" AND ");
andNeeded = true;
sqlBuilder.Add(whereString);
}
if (log.IsDebugEnabled())
{
if (initialCapacity < sqlBuilder.Count)
{
log.Debug("The initial capacity was set too low at: {0} for the UpdateSqlBuilder that needed a capacity of: {1} for the table {2}",
initialCapacity,
sqlBuilder.Count,
tableName);
}
else if (initialCapacity > 16 && ((float) initialCapacity / sqlBuilder.Count) > 1.2)
{
log.Debug("The initial capacity was set too high at: {0} for the UpdateSqlBuilder that needed a capacity of: {1} for the table {2}",
initialCapacity,
sqlBuilder.Count,
tableName);
}
}
return sqlBuilder.ToSqlString();
}
#endregion
public SqlCommandInfo ToSqlCommandInfo()
{
SqlString text = ToSqlString();
var parameterTypes = columns.Values.OfType<SqlType>().ToList();
parameterTypes.AddRange(whereParameterTypes);
return new SqlCommandInfo(text, parameterTypes.ToArray());
}
}
}