-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathNpgsqlUpdateSqlGenerator.cs
More file actions
323 lines (269 loc) · 14.9 KB
/
NpgsqlUpdateSqlGenerator.cs
File metadata and controls
323 lines (269 loc) · 14.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
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
using System.Data;
using System.Text;
using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping;
namespace Npgsql.EntityFrameworkCore.PostgreSQL.Update.Internal;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class NpgsqlUpdateSqlGenerator : UpdateSqlGenerator
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public NpgsqlUpdateSqlGenerator(UpdateSqlGeneratorDependencies dependencies)
: base(dependencies)
{
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override ResultSetMapping AppendInsertOperation(
StringBuilder commandStringBuilder,
IReadOnlyModificationCommand command,
int commandPosition,
out bool requiresTransaction)
=> AppendInsertOperation(commandStringBuilder, command, commandPosition, overridingSystemValue: false, out requiresTransaction);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual ResultSetMapping AppendInsertOperation(
StringBuilder commandStringBuilder,
IReadOnlyModificationCommand command,
int commandPosition,
bool overridingSystemValue,
out bool requiresTransaction)
{
var name = command.TableName;
var schema = command.Schema;
var operations = command.ColumnModifications;
var writeOperations = operations.Where(o => o.IsWrite).ToList();
var readOperations = operations.Where(o => o.IsRead).ToList();
AppendInsertCommand(commandStringBuilder, name, schema, writeOperations, readOperations, overridingSystemValue);
requiresTransaction = false;
return readOperations.Count > 0 ? ResultSetMapping.LastInResultSet : ResultSetMapping.NoResults;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected virtual void AppendInsertCommand(
StringBuilder commandStringBuilder,
string name,
string? schema,
IReadOnlyList<IColumnModification> writeOperations,
IReadOnlyList<IColumnModification> readOperations,
bool overridingSystemValue)
{
AppendInsertCommandHeader(commandStringBuilder, name, schema, writeOperations);
if (overridingSystemValue)
{
commandStringBuilder.AppendLine().Append("OVERRIDING SYSTEM VALUE");
}
AppendValuesHeader(commandStringBuilder, writeOperations);
AppendValues(commandStringBuilder, name, schema, writeOperations);
AppendReturningClause(commandStringBuilder, readOperations);
commandStringBuilder.AppendLine(SqlGenerationHelper.StatementTerminator);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override ResultSetMapping AppendUpdateOperation(
StringBuilder commandStringBuilder,
IReadOnlyModificationCommand command,
int commandPosition,
out bool requiresTransaction)
{
// The default implementation adds RETURNING 1 to do concurrency check (was the row actually updated), but in PostgreSQL we check
// the per-statement row-affected value exposed by Npgsql in the batch; so no need for RETURNING 1.
var name = command.TableName;
var schema = command.Schema;
var operations = command.ColumnModifications;
var writeOperations = operations.Where(o => o.IsWrite).ToList();
var conditionOperations = operations.Where(o => o.IsCondition).ToList();
var readOperations = operations.Where(o => o.IsRead).ToList();
requiresTransaction = false;
AppendUpdateCommand(commandStringBuilder, name, schema, writeOperations, readOperations, conditionOperations);
return readOperations.Count > 0 ? ResultSetMapping.LastInResultSet : ResultSetMapping.NoResults;
}
/// <inheritdoc />
protected override void AppendUpdateColumnValue(
ISqlGenerationHelper updateSqlGeneratorHelper,
IColumnModification columnModification,
StringBuilder stringBuilder,
string name,
string? schema)
{
if (columnModification.JsonPath is null or { IsRoot: true })
{
base.AppendUpdateColumnValue(updateSqlGeneratorHelper, columnModification, stringBuilder, name, schema);
return;
}
{
Check.DebugAssert(
columnModification.TypeMapping is NpgsqlStructuralJsonTypeMapping,
"ColumnModification with JsonPath but non-NpgsqlOwnedJsonTypeMapping");
if (columnModification.TypeMapping.StoreType is "json")
{
throw new NotSupportedException(
"Cannot perform partial update because the PostgreSQL 'json' type has no json_set method. Use 'jsonb' instead.");
}
Check.DebugAssert(columnModification.TypeMapping.StoreType is "jsonb", "Non-jsonb type mapping in JSON partial update");
var jsonPath = columnModification.JsonPath;
// TODO: Lax or not?
stringBuilder
.Append("jsonb_set(")
.Append(updateSqlGeneratorHelper.DelimitIdentifier(columnModification.ColumnName))
.Append(", '{");
// PG's jsonb_set requires the path as an array, so we iterate over the structured JsonPath segments.
var ordinalIndex = 0;
var needsComma = false;
foreach (var segment in jsonPath.Segments)
{
if (needsComma)
{
stringBuilder.Append(',');
}
if (segment.IsArray)
{
stringBuilder.Append(jsonPath.Ordinals[ordinalIndex++]);
}
else
{
stringBuilder.Append(segment.PropertyName);
}
needsComma = true;
}
stringBuilder.Append("}', ");
// TODO: Hack around
if (columnModification.Value is null)
{
_columnModificationValueField ??= typeof(ColumnModification).GetField(
"_value", BindingFlags.Instance | BindingFlags.NonPublic)!;
_columnModificationValueField.SetValue(columnModification, "null");
}
base.AppendUpdateColumnValue(updateSqlGeneratorHelper, columnModification, stringBuilder, name, schema);
stringBuilder.Append(")");
}
}
private FieldInfo? _columnModificationValueField;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override ResultSetMapping AppendDeleteOperation(
StringBuilder commandStringBuilder,
IReadOnlyModificationCommand command,
int commandPosition,
out bool requiresTransaction)
{
// The default implementation adds RETURNING 1 to do concurrency check (was the row actually deleted), but in PostgreSQL we check
// the per-statement row-affected value exposed by Npgsql in the batch; so no need for RETURNING 1.
var name = command.TableName;
var schema = command.Schema;
var conditionOperations = command.ColumnModifications.Where(o => o.IsCondition).ToList();
requiresTransaction = false;
AppendDeleteCommand(commandStringBuilder, name, schema, [], conditionOperations);
return ResultSetMapping.NoResults;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override ResultSetMapping AppendStoredProcedureCall(
StringBuilder commandStringBuilder,
IReadOnlyModificationCommand command,
int commandPosition,
out bool requiresTransaction)
{
Check.DebugAssert(command.StoreStoredProcedure is not null, "command.StoreStoredProcedure is not null");
var storedProcedure = command.StoreStoredProcedure;
Check.DebugAssert(
storedProcedure.Parameters.Any() || storedProcedure.ResultColumns.Any(),
"Stored procedure call with neither parameters nor result columns");
var resultSetMapping = ResultSetMapping.NoResults;
commandStringBuilder.Append("CALL ");
// PostgreSQL supports neither a return value nor a result set with stored procedures, only output parameters.
Check.DebugAssert(storedProcedure.ReturnValue is null, "storedProcedure.Return is null");
Check.DebugAssert(!storedProcedure.ResultColumns.Any(), "!storedProcedure.ResultColumns.Any()");
SqlGenerationHelper.DelimitIdentifier(commandStringBuilder, storedProcedure.Name, storedProcedure.Schema);
commandStringBuilder.Append('(');
var first = true;
// Only positional parameter style supported for now, see https://github.com/dotnet/efcore/issues/28439
// Note: the column modifications are already ordered according to the sproc parameter ordering
// (see ModificationCommand.GenerateColumnModifications)
for (var i = 0; i < command.ColumnModifications.Count; i++)
{
var columnModification = command.ColumnModifications[i];
var parameter = (IStoreStoredProcedureParameter)columnModification.Column!;
if (first)
{
first = false;
}
else
{
commandStringBuilder.Append(", ");
}
Check.DebugAssert(columnModification.UseParameter, "Column modification matched a parameter, but UseParameter is false");
if (parameter.Direction == ParameterDirection.Output)
{
// Recommended PG practice is to pass NULL for output parameters
commandStringBuilder.Append("NULL");
}
else
{
SqlGenerationHelper.GenerateParameterNamePlaceholder(
commandStringBuilder, columnModification.UseOriginalValueParameter
? columnModification.OriginalParameterName!
: columnModification.ParameterName!);
}
// PostgreSQL stored procedures cannot return a regular result set, and output parameter values are simply sent back as the
// result set; this is very different from SQL Server, where output parameter values can be sent back in addition to result
// sets.
if (parameter.Direction.HasFlag(ParameterDirection.Output))
{
// The distinction between having only a rows affected output parameter and having other non-rows affected parameters
// is important later on (i.e. whether we need to propagate or not).
resultSetMapping = parameter == command.RowsAffectedColumn && resultSetMapping == ResultSetMapping.NoResults
? ResultSetMapping.ResultSetWithRowsAffectedOnly
: ResultSetMapping.LastInResultSet;
}
}
commandStringBuilder.Append(')');
commandStringBuilder.AppendLine(SqlGenerationHelper.StatementTerminator);
requiresTransaction = true;
return resultSetMapping;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override void AppendObtainNextSequenceValueOperation(StringBuilder commandStringBuilder, string name, string? schema)
{
commandStringBuilder.Append("nextval('");
SqlGenerationHelper.DelimitIdentifier(commandStringBuilder, Check.NotNull(name, nameof(name)), schema);
commandStringBuilder.Append("')");
}
}