| | | 1 | | using System.Linq.Expressions; |
| | | 2 | | using System.Text; |
| | | 3 | | using Microsoft.EntityFrameworkCore; |
| | | 4 | | using Microsoft.EntityFrameworkCore.Infrastructure; |
| | | 5 | | using Microsoft.EntityFrameworkCore.Metadata; |
| | | 6 | | using Microsoft.EntityFrameworkCore.Storage; |
| | | 7 | | |
| | | 8 | | // ReSharper disable once CheckNamespace |
| | | 9 | | namespace Elsa.Persistence.EFCore.Extensions; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Provides extension methods to perform bulk upsert operations for entities |
| | | 13 | | /// in an Entity Framework Core context, supporting multiple database providers. |
| | | 14 | | /// </summary> |
| | | 15 | | public static class BulkUpsertExtensions |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Performs a bulk upsert operation on a list of entities in the specified database context using a key selector. |
| | | 19 | | /// </summary> |
| | | 20 | | /// <typeparam name="TDbContext">The type of the database context.</typeparam> |
| | | 21 | | /// <typeparam name="TEntity">The type of the entity being upserted.</typeparam> |
| | | 22 | | /// <param name="dbContext">The database context where the bulk upsert operation will be executed.</param> |
| | | 23 | | /// <param name="entities">The list of entities to be upserted.</param> |
| | | 24 | | /// <param name="keySelector">An expression used to determine the key for upsert operations.</param> |
| | | 25 | | /// <param name="cancellationToken">A token to observe while waiting for the operation to complete.</param> |
| | | 26 | | public static async Task BulkUpsertAsync<TDbContext, TEntity>( |
| | | 27 | | this TDbContext dbContext, |
| | | 28 | | IList<TEntity> entities, |
| | | 29 | | Expression<Func<TEntity, string>> keySelector, |
| | | 30 | | CancellationToken cancellationToken = default) |
| | | 31 | | where TDbContext : DbContext |
| | | 32 | | where TEntity : class, new() |
| | | 33 | | { |
| | 3186 | 34 | | await BulkUpsertAsync(dbContext, entities, keySelector, 50, cancellationToken); |
| | 3186 | 35 | | } |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// Performs a bulk upsert operation on a list of entities in the specified database context using a key selector an |
| | | 39 | | /// </summary> |
| | | 40 | | /// <typeparam name="TDbContext">The type of the database context.</typeparam> |
| | | 41 | | /// <typeparam name="TEntity">The type of the entity being upserted.</typeparam> |
| | | 42 | | /// <param name="dbContext">The database context where the bulk upsert operation will be executed.</param> |
| | | 43 | | /// <param name="entities">The list of entities to be upserted.</param> |
| | | 44 | | /// <param name="keySelector">An expression used to determine the key for upsert operations.</param> |
| | | 45 | | /// <param name="batchSize">The size of each batch for processing the upsert operation. Defaults to 50.</param> |
| | | 46 | | /// <param name="cancellationToken">A token to observe while waiting for the operation to complete.</param> |
| | | 47 | | /// <exception cref="NotSupportedException">Thrown if the database provider for the context is not supported.</excep |
| | | 48 | | public static async Task BulkUpsertAsync<TDbContext, TEntity>( |
| | | 49 | | this TDbContext dbContext, |
| | | 50 | | IList<TEntity> entities, |
| | | 51 | | Expression<Func<TEntity, string>> keySelector, |
| | | 52 | | int batchSize = 50, |
| | | 53 | | CancellationToken cancellationToken = default) |
| | | 54 | | where TDbContext : DbContext |
| | | 55 | | where TEntity : class, new() |
| | | 56 | | { |
| | 3186 | 57 | | if (entities.Count == 0) |
| | 0 | 58 | | return; |
| | | 59 | | |
| | | 60 | | // Identify the current provider (e.g., "Microsoft.EntityFrameworkCore.SqlServer") |
| | 3186 | 61 | | var providerName = dbContext.Database.ProviderName?.ToLowerInvariant() ?? string.Empty; |
| | | 62 | | |
| | | 63 | | // Determine the method for generating SQL based on the provider |
| | 3186 | 64 | | Func<DbContext, IList<TEntity>, Expression<Func<TEntity, string>>, (string, object[])> generateSql = providerNam |
| | 3186 | 65 | | { |
| | 6372 | 66 | | var pn when pn.Contains("sqlserver") => GenerateSqlServerUpsert, |
| | 0 | 67 | | var pn when pn.Contains("sqlite") => GenerateSqliteUpsert, |
| | 0 | 68 | | var pn when pn.Contains("postgres") => GeneratePostgresUpsert, |
| | 0 | 69 | | var pn when pn.Contains("mysql") => GenerateMySqlUpsert, |
| | 0 | 70 | | var pn when pn.Contains("oracle") => GenerateOracleUpsert, |
| | 0 | 71 | | _ => throw new NotSupportedException($"Provider '{providerName}' is not supported.") |
| | 3186 | 72 | | }; |
| | | 73 | | |
| | | 74 | | // Loop through batched entities |
| | 12744 | 75 | | foreach (var batch in entities.Chunk(batchSize)) |
| | | 76 | | { |
| | | 77 | | // Generate SQL and parameters |
| | 3186 | 78 | | var (sql, parameters) = generateSql(dbContext, batch, keySelector); |
| | | 79 | | |
| | 3186 | 80 | | await dbContext.Database.ExecuteSqlRawAsync(sql, parameters, cancellationToken); |
| | | 81 | | } |
| | 3186 | 82 | | } |
| | | 83 | | |
| | | 84 | | private static (string, object[]) GenerateSqlServerUpsert<TEntity>( |
| | | 85 | | DbContext dbContext, |
| | | 86 | | IList<TEntity> entities, |
| | | 87 | | Expression<Func<TEntity, string>> keySelector) |
| | | 88 | | where TEntity : class |
| | | 89 | | { |
| | 3186 | 90 | | var entityType = dbContext.Model.FindEntityType(typeof(TEntity))!; |
| | 3186 | 91 | | var tableName = $"[{entityType.GetSchema()}].[{entityType.GetTableName()}]"; |
| | 3186 | 92 | | var storeObject = StoreObjectIdentifier.Table(entityType.GetTableName()!, entityType.GetSchema()); |
| | 3186 | 93 | | var props = entityType.GetProperties().ToList(); |
| | 3186 | 94 | | var keyProp = entityType.FindProperty(keySelector.GetMemberAccess().Name)!; |
| | 3186 | 95 | | var keyColumnName = $"[{keyProp.GetColumnName(storeObject)}]"; |
| | 3186 | 96 | | var columnNames = props |
| | 64224 | 97 | | .Select(p => $"[{p.GetColumnName(storeObject)}]") |
| | 3186 | 98 | | .ToList(); |
| | | 99 | | |
| | 3186 | 100 | | var mergeSql = new StringBuilder(); |
| | 3186 | 101 | | mergeSql.AppendLine($"MERGE {tableName} AS Target"); |
| | 3186 | 102 | | mergeSql.AppendLine("USING (VALUES"); |
| | | 103 | | |
| | 3186 | 104 | | var parameters = new List<object>(); |
| | 3186 | 105 | | var parameterCount = 0; |
| | | 106 | | |
| | 17466 | 107 | | for (var i = 0; i < entities.Count; i++) |
| | | 108 | | { |
| | 5547 | 109 | | var entity = entities[i]; |
| | 5547 | 110 | | var values = new List<string>(); |
| | | 111 | | |
| | 252470 | 112 | | foreach (var property in props) |
| | | 113 | | { |
| | 120688 | 114 | | var paramName = $"{{{parameterCount++}}}"; |
| | | 115 | | |
| | | 116 | | // If it's a shadow property, retrieve value via Entry(..).Property(..) |
| | 120688 | 117 | | var value = property.IsShadowProperty() |
| | 120688 | 118 | | ? dbContext.Entry(entity).Property(property.Name).CurrentValue |
| | 120688 | 119 | | : property.PropertyInfo?.GetValue(entity); |
| | | 120 | | |
| | 120688 | 121 | | var converter = property.GetTypeMapping().Converter; |
| | 120688 | 122 | | if (converter != null) |
| | 5451 | 123 | | value = converter.ConvertToProvider(value)!; |
| | | 124 | | |
| | | 125 | | // Explicitly cast null values for varbinary columns |
| | 120688 | 126 | | if (property.GetColumnType().StartsWith("varbinary", StringComparison.OrdinalIgnoreCase) && value is nul |
| | 2726 | 127 | | values.Add("CAST(NULL AS varbinary(max))"); // Explicitly cast null |
| | | 128 | | else |
| | 117962 | 129 | | values.Add(paramName); |
| | | 130 | | |
| | 120688 | 131 | | parameters.Add(value!); |
| | | 132 | | } |
| | | 133 | | |
| | 5547 | 134 | | var line = $"({string.Join(", ", values)}){(i < entities.Count - 1 ? "," : string.Empty)}"; |
| | 5547 | 135 | | mergeSql.AppendLine(line); |
| | | 136 | | } |
| | | 137 | | |
| | 3186 | 138 | | mergeSql.AppendLine($") AS Source ({string.Join(", ", columnNames)})"); |
| | 3186 | 139 | | mergeSql.AppendLine($"ON Target.{keyColumnName} = Source.{keyColumnName}"); |
| | 3186 | 140 | | mergeSql.AppendLine("WHEN MATCHED THEN"); |
| | 128448 | 141 | | mergeSql.AppendLine($" UPDATE SET {string.Join(", ", columnNames.Where(c => c != keyColumnName).Select(c => $ |
| | 3186 | 142 | | mergeSql.AppendLine("WHEN NOT MATCHED THEN"); |
| | 3186 | 143 | | mergeSql.AppendLine($" INSERT ({string.Join(", ", columnNames)})"); |
| | 67410 | 144 | | mergeSql.AppendLine($" VALUES ({string.Join(", ", columnNames.Select(c => $"Source.{c}"))});"); |
| | | 145 | | |
| | 3186 | 146 | | return (mergeSql.ToString(), parameters.ToArray()); |
| | | 147 | | } |
| | | 148 | | |
| | | 149 | | private static (string, object[]) GenerateSqliteUpsert<TEntity>( |
| | | 150 | | DbContext dbContext, |
| | | 151 | | IList<TEntity> entities, |
| | | 152 | | Expression<Func<TEntity, string>> keySelector) |
| | | 153 | | where TEntity : class |
| | | 154 | | { |
| | 0 | 155 | | var entityType = dbContext.Model.FindEntityType(typeof(TEntity))!; |
| | 0 | 156 | | var tableName = entityType.GetTableName(); |
| | 0 | 157 | | var storeObject = StoreObjectIdentifier.Table(tableName!, entityType.GetSchema()); |
| | 0 | 158 | | var props = entityType.GetProperties().ToList(); |
| | 0 | 159 | | var keyProp = entityType.FindProperty(keySelector.GetMemberAccess().Name)!; |
| | 0 | 160 | | var keyColumnName = keyProp.GetColumnName(storeObject); |
| | 0 | 161 | | var columnNames = props |
| | 0 | 162 | | .Select(p => p.GetColumnName(storeObject)!) |
| | 0 | 163 | | .ToList(); |
| | | 164 | | |
| | 0 | 165 | | var sb = new StringBuilder(); |
| | 0 | 166 | | var parameters = new List<object>(); |
| | 0 | 167 | | var parameterCount = 0; |
| | | 168 | | |
| | 0 | 169 | | sb.Append($"INSERT INTO \"{tableName}\" ({string.Join(", ", columnNames.Select(c => $"\"{c}\""))}) VALUES "); |
| | | 170 | | |
| | 0 | 171 | | for (var i = 0; i < entities.Count; i++) |
| | | 172 | | { |
| | 0 | 173 | | var entity = entities[i]; |
| | 0 | 174 | | var placeholders = new List<string>(); |
| | | 175 | | |
| | 0 | 176 | | foreach (var property in props) |
| | | 177 | | { |
| | 0 | 178 | | var paramName = $"{{{parameterCount++}}}"; |
| | | 179 | | |
| | 0 | 180 | | var value = property.IsShadowProperty() |
| | 0 | 181 | | ? dbContext.Entry(entity).Property(property.Name).CurrentValue |
| | 0 | 182 | | : property.PropertyInfo?.GetValue(entity); |
| | | 183 | | |
| | 0 | 184 | | var converter = property.GetTypeMapping().Converter; |
| | 0 | 185 | | if (converter != null) |
| | 0 | 186 | | value = converter.ConvertToProvider(value); |
| | | 187 | | |
| | 0 | 188 | | placeholders.Add(paramName); |
| | 0 | 189 | | parameters.Add(value!); |
| | | 190 | | } |
| | | 191 | | |
| | 0 | 192 | | sb.Append($"({string.Join(", ", placeholders)})"); |
| | 0 | 193 | | if (i < entities.Count - 1) |
| | 0 | 194 | | sb.Append(", "); |
| | | 195 | | } |
| | | 196 | | |
| | 0 | 197 | | sb.AppendLine(); |
| | 0 | 198 | | sb.AppendLine($"ON CONFLICT(\"{keyColumnName}\") DO UPDATE SET"); |
| | | 199 | | |
| | 0 | 200 | | var updateAssignments = columnNames |
| | 0 | 201 | | .Where(c => c != keyColumnName) |
| | 0 | 202 | | .Select(c => $"\"{c}\"=excluded.\"{c}\""); |
| | | 203 | | |
| | 0 | 204 | | sb.AppendLine(string.Join(", ", updateAssignments) + ";"); |
| | | 205 | | |
| | 0 | 206 | | return (sb.ToString(), parameters.ToArray()); |
| | | 207 | | } |
| | | 208 | | |
| | | 209 | | private static (string, object[]) GeneratePostgresUpsert<TEntity>( |
| | | 210 | | DbContext dbContext, |
| | | 211 | | IList<TEntity> entities, |
| | | 212 | | Expression<Func<TEntity, string>> keySelector) |
| | | 213 | | where TEntity : class |
| | | 214 | | { |
| | 0 | 215 | | var entityType = dbContext.Model.FindEntityType(typeof(TEntity))!; |
| | 0 | 216 | | var tableName = entityType.GetTableName(); |
| | 0 | 217 | | var storeObject = StoreObjectIdentifier.Table(tableName!, entityType.GetSchema()); |
| | | 218 | | |
| | 0 | 219 | | var props = entityType.GetProperties().ToList(); |
| | | 220 | | |
| | 0 | 221 | | var keyProp = entityType.FindProperty(keySelector.GetMemberAccess().Name)!; |
| | 0 | 222 | | var keyColumnName = keyProp.GetColumnName(storeObject); |
| | 0 | 223 | | var columnNames = props |
| | 0 | 224 | | .Select(p => p.GetColumnName(storeObject)!) |
| | 0 | 225 | | .ToList(); |
| | | 226 | | |
| | 0 | 227 | | var sb = new StringBuilder(); |
| | 0 | 228 | | var parameters = new List<object>(); |
| | 0 | 229 | | var parameterCount = 0; |
| | | 230 | | |
| | 0 | 231 | | sb.Append($"INSERT INTO \"{storeObject.Schema}\".\"{storeObject.Name}\" ({string.Join(", ", columnNames.Select(c |
| | | 232 | | |
| | 0 | 233 | | for (var i = 0; i < entities.Count; i++) |
| | | 234 | | { |
| | 0 | 235 | | var entity = entities[i]; |
| | 0 | 236 | | var placeholders = new List<string>(); |
| | | 237 | | |
| | 0 | 238 | | foreach (var property in props) |
| | | 239 | | { |
| | 0 | 240 | | var paramName = $"{{{parameterCount++}}}"; |
| | | 241 | | |
| | 0 | 242 | | var value = property.IsShadowProperty() |
| | 0 | 243 | | ? dbContext.Entry(entity).Property(property.Name).CurrentValue |
| | 0 | 244 | | : property.PropertyInfo?.GetValue(entity); |
| | | 245 | | |
| | 0 | 246 | | var converter = property.GetTypeMapping().Converter; |
| | 0 | 247 | | if (converter != null) |
| | 0 | 248 | | value = converter.ConvertToProvider(value); |
| | | 249 | | |
| | | 250 | | // Detect json/jsonb column types and cast the parameter so PostgreSQL accepts it. |
| | 0 | 251 | | var columnType = property.GetColumnType(); |
| | 0 | 252 | | if (columnType.StartsWith("jsonb", StringComparison.OrdinalIgnoreCase)) |
| | 0 | 253 | | placeholders.Add($"CAST({paramName} AS jsonb)"); |
| | 0 | 254 | | else if (columnType.StartsWith("json", StringComparison.OrdinalIgnoreCase)) |
| | 0 | 255 | | placeholders.Add($"CAST({paramName} AS json)"); |
| | | 256 | | else |
| | 0 | 257 | | placeholders.Add(paramName); |
| | | 258 | | |
| | 0 | 259 | | parameters.Add(value!); |
| | | 260 | | } |
| | | 261 | | |
| | 0 | 262 | | sb.Append($"({string.Join(", ", placeholders)})"); |
| | 0 | 263 | | if (i < entities.Count - 1) |
| | 0 | 264 | | sb.Append(", "); |
| | | 265 | | } |
| | | 266 | | |
| | 0 | 267 | | sb.AppendLine(); |
| | 0 | 268 | | sb.AppendLine($"ON CONFLICT (\"{keyColumnName}\") DO UPDATE SET"); |
| | | 269 | | |
| | 0 | 270 | | var updateAssignments = columnNames |
| | 0 | 271 | | .Where(c => c != keyColumnName) |
| | 0 | 272 | | .Select(c => $"\"{c}\" = EXCLUDED.\"{c}\""); |
| | | 273 | | |
| | 0 | 274 | | sb.AppendLine(string.Join(", ", updateAssignments) + ";"); |
| | | 275 | | |
| | 0 | 276 | | return (sb.ToString(), parameters.ToArray()); |
| | | 277 | | } |
| | | 278 | | |
| | | 279 | | private static (string, object[]) GenerateMySqlUpsert<TEntity>( |
| | | 280 | | DbContext dbContext, |
| | | 281 | | IList<TEntity> entities, |
| | | 282 | | Expression<Func<TEntity, string>> keySelector) |
| | | 283 | | where TEntity : class |
| | | 284 | | { |
| | 0 | 285 | | var entityType = dbContext.Model.FindEntityType(typeof(TEntity))!; |
| | 0 | 286 | | var tableName = entityType.GetTableName(); |
| | 0 | 287 | | var storeObject = StoreObjectIdentifier.Table(tableName!, entityType.GetSchema()); |
| | | 288 | | |
| | 0 | 289 | | var props = entityType.GetProperties().ToList(); |
| | | 290 | | |
| | 0 | 291 | | var keyProp = entityType.FindProperty(keySelector.GetMemberAccess().Name)!; |
| | 0 | 292 | | var keyColumnName = keyProp.GetColumnName(storeObject); |
| | 0 | 293 | | var columnNames = props |
| | 0 | 294 | | .Select(p => p.GetColumnName(storeObject)!) |
| | 0 | 295 | | .ToList(); |
| | | 296 | | |
| | 0 | 297 | | var sb = new StringBuilder(); |
| | 0 | 298 | | var parameters = new List<object>(); |
| | 0 | 299 | | var parameterCount = 0; |
| | | 300 | | |
| | 0 | 301 | | sb.Append($"INSERT INTO `{tableName}` ({string.Join(", ", columnNames.Select(c => $"`{c}`"))}) VALUES "); |
| | | 302 | | |
| | 0 | 303 | | for (var i = 0; i < entities.Count; i++) |
| | | 304 | | { |
| | 0 | 305 | | var entity = entities[i]; |
| | 0 | 306 | | var placeholders = new List<string>(); |
| | | 307 | | |
| | 0 | 308 | | foreach (var property in props) |
| | | 309 | | { |
| | 0 | 310 | | var paramName = $"{{{parameterCount++}}}"; |
| | | 311 | | |
| | 0 | 312 | | var value = property.IsShadowProperty() |
| | 0 | 313 | | ? dbContext.Entry(entity).Property(property.Name).CurrentValue |
| | 0 | 314 | | : property.PropertyInfo?.GetValue(entity); |
| | | 315 | | |
| | 0 | 316 | | var converter = property.GetTypeMapping().Converter; |
| | 0 | 317 | | if (converter != null) |
| | 0 | 318 | | value = converter.ConvertToProvider(value); |
| | | 319 | | |
| | 0 | 320 | | placeholders.Add(paramName); |
| | 0 | 321 | | parameters.Add(value!); |
| | | 322 | | } |
| | | 323 | | |
| | 0 | 324 | | sb.Append($"({string.Join(", ", placeholders)})"); |
| | 0 | 325 | | if (i < entities.Count - 1) |
| | 0 | 326 | | sb.Append(", "); |
| | | 327 | | } |
| | | 328 | | |
| | 0 | 329 | | sb.AppendLine(); |
| | 0 | 330 | | sb.AppendLine("ON DUPLICATE KEY UPDATE"); |
| | | 331 | | |
| | 0 | 332 | | var updateAssignments = columnNames |
| | 0 | 333 | | .Where(c => c != keyColumnName) |
| | 0 | 334 | | .Select(c => $"`{c}` = VALUES(`{c}`)"); |
| | | 335 | | |
| | 0 | 336 | | sb.AppendLine(string.Join(", ", updateAssignments) + ";"); |
| | | 337 | | |
| | 0 | 338 | | return (sb.ToString(), parameters.ToArray()); |
| | | 339 | | } |
| | | 340 | | |
| | | 341 | | internal static (string, object[]) GenerateOracleUpsert<TEntity>( |
| | | 342 | | DbContext dbContext, |
| | | 343 | | IList<TEntity> entities, |
| | | 344 | | Expression<Func<TEntity, string>> keySelector) |
| | | 345 | | where TEntity : class |
| | | 346 | | { |
| | 0 | 347 | | var entityType = dbContext.Model.FindEntityType(typeof(TEntity))!; |
| | 0 | 348 | | var schema = entityType.GetSchema(); |
| | 0 | 349 | | var tableName = entityType.GetTableName()!; |
| | 0 | 350 | | var storeObject = StoreObjectIdentifier.Table(tableName, schema); |
| | 0 | 351 | | var sqlGenerationHelper = dbContext.GetService<ISqlGenerationHelper>(); |
| | 0 | 352 | | var fullName = sqlGenerationHelper.DelimitIdentifier(tableName, schema); |
| | | 353 | | |
| | 0 | 354 | | var props = entityType.GetProperties().ToList(); |
| | | 355 | | |
| | 0 | 356 | | var keyProp = entityType.FindProperty(keySelector.GetMemberAccess().Name)!; |
| | 0 | 357 | | var keyColumnName = keyProp.GetColumnName(storeObject)!; |
| | | 358 | | |
| | | 359 | | // Pre-build quoted column names once and reuse throughout all clauses. |
| | 0 | 360 | | var quotedColumnNames = props |
| | 0 | 361 | | .Select(p => sqlGenerationHelper.DelimitIdentifier(p.GetColumnName(storeObject)!)) |
| | 0 | 362 | | .ToList(); |
| | 0 | 363 | | var quotedKeyColumnName = sqlGenerationHelper.DelimitIdentifier(keyColumnName); |
| | | 364 | | |
| | 0 | 365 | | var sb = new StringBuilder(); |
| | 0 | 366 | | var parameters = new List<object>(); |
| | 0 | 367 | | var parameterCount = 0; |
| | | 368 | | |
| | 0 | 369 | | sb.AppendLine($"MERGE INTO {fullName} Target"); |
| | 0 | 370 | | sb.AppendLine("USING (SELECT"); |
| | | 371 | | |
| | 0 | 372 | | for (var i = 0; i < entities.Count; i++) |
| | | 373 | | { |
| | 0 | 374 | | var entity = entities[i]; |
| | 0 | 375 | | var lineParts = new List<string>(); |
| | | 376 | | |
| | 0 | 377 | | foreach (var property in props) |
| | | 378 | | { |
| | 0 | 379 | | var paramName = $"{{{parameterCount++}}}"; |
| | | 380 | | |
| | 0 | 381 | | var value = property.IsShadowProperty() |
| | 0 | 382 | | ? dbContext.Entry(entity).Property(property.Name).CurrentValue |
| | 0 | 383 | | : property.PropertyInfo?.GetValue(entity); |
| | | 384 | | |
| | 0 | 385 | | var converter = property.GetTypeMapping().Converter; |
| | 0 | 386 | | if (converter != null) |
| | 0 | 387 | | value = converter.ConvertToProvider(value); |
| | | 388 | | |
| | 0 | 389 | | parameters.Add(value!); |
| | | 390 | | |
| | | 391 | | // Aliases must be quoted so Oracle preserves their case, matching |
| | | 392 | | // the quoted references in ON, UPDATE SET, and INSERT/VALUES below. |
| | 0 | 393 | | var quotedAlias = sqlGenerationHelper.DelimitIdentifier(property.GetColumnName(storeObject)!); |
| | | 394 | | |
| | | 395 | | // In a SELECT … FROM DUAL subquery, ODP.NET has no target column to |
| | | 396 | | // derive bind parameter types from and defaults to VARCHAR2 for .NET |
| | | 397 | | // strings. Elsa's Oracle migrations define string columns as NVARCHAR2, |
| | | 398 | | // so an explicit CAST is required to avoid a datatype mismatch error. |
| | | 399 | | // The full EF Core column type string (e.g. "NVARCHAR2(450)") is |
| | | 400 | | // used directly in the CAST so all Oracle type variants are handled |
| | | 401 | | // correctly without any string parsing. |
| | 0 | 402 | | var columnType = property.GetColumnType() ?? string.Empty; |
| | 0 | 403 | | var expr = columnType.StartsWith("NVARCHAR2", StringComparison.OrdinalIgnoreCase) |
| | 0 | 404 | | ? $"CAST({paramName} AS {columnType})" |
| | 0 | 405 | | : paramName; |
| | | 406 | | |
| | 0 | 407 | | lineParts.Add($"{expr} AS {quotedAlias}"); |
| | | 408 | | } |
| | | 409 | | |
| | 0 | 410 | | var suffix = i < entities.Count - 1 ? " FROM DUAL UNION ALL SELECT" : " FROM DUAL"; |
| | 0 | 411 | | sb.AppendLine(string.Join(", ", lineParts) + suffix); |
| | | 412 | | } |
| | | 413 | | |
| | 0 | 414 | | sb.AppendLine($") Source ON (Target.{quotedKeyColumnName} = Source.{quotedKeyColumnName})"); |
| | 0 | 415 | | sb.AppendLine("WHEN MATCHED THEN UPDATE SET"); |
| | 0 | 416 | | sb.AppendLine(string.Join(", ", quotedColumnNames |
| | 0 | 417 | | .Where(c => c != quotedKeyColumnName) |
| | 0 | 418 | | .Select(c => $"Target.{c} = Source.{c}"))); |
| | 0 | 419 | | sb.AppendLine("WHEN NOT MATCHED THEN"); |
| | 0 | 420 | | sb.AppendLine($"INSERT ({string.Join(", ", quotedColumnNames)})"); |
| | 0 | 421 | | sb.AppendLine($"VALUES ({string.Join(", ", quotedColumnNames.Select(c => $"Source.{c}"))});"); |
| | | 422 | | |
| | 0 | 423 | | return (sb.ToString(), parameters.ToArray()); |
| | | 424 | | } |
| | | 425 | | } |