From e36bc3e7cee5c2794262380bfe1687a2d87892b3 Mon Sep 17 00:00:00 2001 From: pengweiqhca Date: Thu, 3 Dec 2026 16:47:49 +0800 Subject: [PATCH] Add TempTableOptions with a TableNameProvider to the MySQL bulk update and upsert options The staging temp table of MySqlBulkUpdateOptions and MySqlBulkInsertOrUpdateOptions was always named by the ReusingTempTableNameProvider, which derives the name from the table of the entity. TableNameProvider of the options redirects the target table only, so a name that must not be used for a table, for example one that still contains a placeholder which is replaced for the target table only, failed with error 1146 on the first statement that referenced the staging table. The SQL Server and PostgreSQL options already expose the provider through TempTableOptions. MySqlBulkOperationTempTableOptions carries the ITempTableNameProvider. The executor leases the staging table name from it and falls back to the ReusingTempTableNameProvider when it is not set, so the default behaviour is unchanged. The provider is copied when options are initialized from another MySqlBulkUpdateOptions or MySqlBulkInsertOrUpdateOptions. --- .../MySqlBulkInsertOrUpdateOptions.cs | 10 ++++++ .../MySqlBulkOperationExecutor.cs | 8 +++-- .../MySqlBulkOperationTempTableOptions.cs | 25 +++++++++++++++ .../BulkOperations/MySqlBulkUpdateOptions.cs | 10 ++++++ .../BulkInsertOrUpdateAsync.cs | 25 +++++++++++++++ .../BulkUpdateAsync.cs | 29 +++++++++++++++++ .../RecordingTempTableNameProvider.cs | 31 +++++++++++++++++++ 7 files changed, 135 insertions(+), 3 deletions(-) create mode 100644 src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkOperationTempTableOptions.cs create mode 100644 tests/Thinktecture.EntityFrameworkCore.MySql.Tests/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutorTests/RecordingTempTableNameProvider.cs diff --git a/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkInsertOrUpdateOptions.cs b/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkInsertOrUpdateOptions.cs index dff210d5..8c824db0 100644 --- a/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkInsertOrUpdateOptions.cs +++ b/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkInsertOrUpdateOptions.cs @@ -49,6 +49,11 @@ public int? MaxParametersPerStatement /// public TimeSpan? CommandTimeout { get; set; } + /// + /// Options for the staging temp table. + /// + public MySqlBulkOperationTempTableOptions TempTableOptions { get; } + /// [Obsolete("Use 'TableNameProvider' instead: 'IBulkOperationTableNameProvider.ForRootEntityWithDefaultSchema(tableName)' when only 'TableName' is set, or 'IBulkOperationTableNameProvider.ForRootEntity(tableName, schema)' when 'Schema' is set as well. For a temp table entity use 'IBulkOperationTableNameProvider.ForRootEntity(tableName, schema)', because 'ForRootEntityWithDefaultSchema' throws for temp table entities.")] public string? TableName @@ -90,6 +95,11 @@ public MySqlBulkInsertOrUpdateOptions(IBulkInsertOrUpdateOptions? optionsToIniti { MaxParametersPerStatement = mySqlOptions.MaxParametersPerStatement; CommandTimeout = mySqlOptions.CommandTimeout; + TempTableOptions = new MySqlBulkOperationTempTableOptions(mySqlOptions.TempTableOptions); + } + else + { + TempTableOptions = new MySqlBulkOperationTempTableOptions(); } } } \ No newline at end of file diff --git a/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutor.cs b/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutor.cs index 9f086c50..ad6aa05f 100644 --- a/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutor.cs +++ b/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutor.cs @@ -239,7 +239,7 @@ public async Task BulkUpdateAsync(IEnumerable entities, IBulkUpdateOp var keys = ToPropertiesWithNavigations(keyProperties); var stagingProperties = keys.Concat(propertiesToSet).ToList(); - var staging = new StagingTable(entityType, table, keys, stagingProperties, mySqlOptions.MaxParametersPerStatement, mySqlOptions.CommandTimeout, false); + var staging = new StagingTable(entityType, table, keys, stagingProperties, mySqlOptions.MaxParametersPerStatement, mySqlOptions.CommandTimeout, mySqlOptions.TempTableOptions.TableNameProvider, false); return await ExecuteInTransactionAsync(token => ExecuteWithStagingTableAsync(staging, entities, @@ -276,7 +276,7 @@ public async Task BulkInsertOrUpdateAsync(IEnumerable entities, IBulk var propertiesToSet = propertiesToUpdate.Where(property => !keyProperties.Contains(property.Property) && !primaryKeyProperties.Contains(property.Property)).ToList(); var keys = ToPropertiesWithNavigations(keyProperties); var stagingProperties = keys.Concat(propertiesToInsert).Concat(propertiesToSet).Distinct().ToList(); - var staging = new StagingTable(entityType, table, keys, stagingProperties, mySqlOptions.MaxParametersPerStatement, mySqlOptions.CommandTimeout, true); + var staging = new StagingTable(entityType, table, keys, stagingProperties, mySqlOptions.MaxParametersPerStatement, mySqlOptions.CommandTimeout, mySqlOptions.TempTableOptions.TableNameProvider, true); return await ExecuteInTransactionAsync(token => ExecuteWithStagingTableAsync(staging, entities, @@ -922,7 +922,7 @@ private async Task ExecuteWithStagingTableAsync( try { - using var nameLease = ReusingTempTableNameProvider.Instance.LeaseName(_context, staging.EntityType); + using var nameLease = (staging.TableNameProvider ?? ReusingTempTableNameProvider.Instance).LeaseName(_context, staging.EntityType); var createStatement = CreateStagingTableStatement(staging, nameLease.Name); int result; @@ -1116,6 +1116,7 @@ private StringBuilder AppendKeyCondition(StringBuilder statement, IReadOnlyList< /// Staged properties; the keys come first. /// Parameter budget of the INSERT statements of the fill; null uses the registered value. /// Timeout of every statement. + /// Provides the name of the staging table; null derives the name from the table of the entity. /// Indication whether the operation is an upsert; an upsert stages a store-generated key without a key index. private sealed record StagingTable( IEntityType EntityType, @@ -1124,5 +1125,6 @@ private sealed record StagingTable( IReadOnlyList Properties, int? MaxParametersPerStatement, TimeSpan? CommandTimeout, + ITempTableNameProvider? TableNameProvider, bool IsUpsert); } diff --git a/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkOperationTempTableOptions.cs b/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkOperationTempTableOptions.cs new file mode 100644 index 00000000..d9c72fcf --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkOperationTempTableOptions.cs @@ -0,0 +1,25 @@ +using Thinktecture.EntityFrameworkCore.TempTables; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +/// +/// Options for the staging temp table of the MySQL bulk update and upsert operations. +/// +public sealed class MySqlBulkOperationTempTableOptions +{ + internal MySqlBulkOperationTempTableOptions(MySqlBulkOperationTempTableOptions? options = null) + { + TableNameProvider = options?.TableNameProvider; + } + + /// + /// Provides the name to create the staging temp table with. + /// The default is the , which derives the name from the table name of the entity. + /// + /// + /// The and redirect the target table only. + /// Use this provider if the name derived from the entity must not be used for the temp table, for example if the table name of the entity + /// contains a placeholder that is replaced for the target table only. + /// + public ITempTableNameProvider? TableNameProvider { get; set; } +} diff --git a/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkUpdateOptions.cs b/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkUpdateOptions.cs index df53793b..ec5da115 100644 --- a/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkUpdateOptions.cs +++ b/src/Thinktecture.EntityFrameworkCore.MySql/EntityFrameworkCore/BulkOperations/MySqlBulkUpdateOptions.cs @@ -40,6 +40,11 @@ public int? MaxParametersPerStatement /// public TimeSpan? CommandTimeout { get; set; } + /// + /// Options for the staging temp table. + /// + public MySqlBulkOperationTempTableOptions TempTableOptions { get; } + /// [Obsolete("Use 'TableNameProvider' instead: 'IBulkOperationTableNameProvider.ForRootEntityWithDefaultSchema(tableName)' when only 'TableName' is set, or 'IBulkOperationTableNameProvider.ForRootEntity(tableName, schema)' when 'Schema' is set as well. For a temp table entity use 'IBulkOperationTableNameProvider.ForRootEntity(tableName, schema)', because 'ForRootEntityWithDefaultSchema' throws for temp table entities.")] public string? TableName @@ -80,6 +85,11 @@ public MySqlBulkUpdateOptions(IBulkUpdateOptions? optionsToInitializeFrom = null { MaxParametersPerStatement = mySqlOptions.MaxParametersPerStatement; CommandTimeout = mySqlOptions.CommandTimeout; + TempTableOptions = new MySqlBulkOperationTempTableOptions(mySqlOptions.TempTableOptions); + } + else + { + TempTableOptions = new MySqlBulkOperationTempTableOptions(); } } } \ No newline at end of file diff --git a/tests/Thinktecture.EntityFrameworkCore.MySql.Tests/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutorTests/BulkInsertOrUpdateAsync.cs b/tests/Thinktecture.EntityFrameworkCore.MySql.Tests/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutorTests/BulkInsertOrUpdateAsync.cs index d2f15668..b2c33a74 100644 --- a/tests/Thinktecture.EntityFrameworkCore.MySql.Tests/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutorTests/BulkInsertOrUpdateAsync.cs +++ b/tests/Thinktecture.EntityFrameworkCore.MySql.Tests/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutorTests/BulkInsertOrUpdateAsync.cs @@ -1356,6 +1356,31 @@ public async Task Should_throw_if_an_existing_row_is_updated_to_reference_a_new_ loadedEntity.ParentId.Should().BeNull(); } + [Fact] + public async Task Should_name_the_staging_table_with_the_provider_of_the_TempTableOptions() + { + var entity = new TestEntity { Id = _TEST_ENTITY_ID, RequiredName = "RequiredName", Count = 42 }; + + var tableNameProvider = new RecordingTempTableNameProvider("custom_upsert_staging"); + var affectedRows = await SUT.BulkInsertOrUpdateAsync([entity], new MySqlBulkInsertOrUpdateOptions { TempTableOptions = { TableNameProvider = tableNameProvider } }); + + affectedRows.Should().Be(1); + ExecutedCommands.Should().ContainSingle(command => command.StartsWith("CREATE TEMPORARY TABLE `custom_upsert_staging`", StringComparison.Ordinal)); + ExecutedCommands.Should().Contain("DROP TEMPORARY TABLE IF EXISTS `custom_upsert_staging`;"); + tableNameProvider.LeasedCount.Should().Be(1); + tableNameProvider.DisposedCount.Should().Be(1); + (await AssertDbContext.TestEntities.SingleAsync()).Count.Should().Be(42); + } + + [Fact] + public void Should_keep_the_TempTableOptions_when_the_options_are_copied() + { + var tableNameProvider = new RecordingTempTableNameProvider("custom_upsert_staging"); + var options = new MySqlBulkInsertOrUpdateOptions { TempTableOptions = { TableNameProvider = tableNameProvider } }; + + new MySqlBulkInsertOrUpdateOptions(options).TempTableOptions.TableNameProvider.Should().BeSameAs(tableNameProvider); + } + [Fact] public async Task Should_drop_the_staging_table_if_the_upsert_fails() { diff --git a/tests/Thinktecture.EntityFrameworkCore.MySql.Tests/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutorTests/BulkUpdateAsync.cs b/tests/Thinktecture.EntityFrameworkCore.MySql.Tests/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutorTests/BulkUpdateAsync.cs index 10137bcf..d5415c31 100644 --- a/tests/Thinktecture.EntityFrameworkCore.MySql.Tests/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutorTests/BulkUpdateAsync.cs +++ b/tests/Thinktecture.EntityFrameworkCore.MySql.Tests/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutorTests/BulkUpdateAsync.cs @@ -1124,6 +1124,35 @@ public async Task Should_drop_the_staging_table_after_the_update() (await AssertDbContext.TestEntities.SingleAsync()).Count.Should().Be(43); } + [Fact] + public async Task Should_name_the_staging_table_with_the_provider_of_the_TempTableOptions() + { + var entity = new TestEntity { Id = _TEST_ENTITY_ID, RequiredName = "RequiredName" }; + ArrangeDbContext.Add(entity); + await ArrangeDbContext.SaveChangesAsync(); + + entity.Count = 42; + + var tableNameProvider = new RecordingTempTableNameProvider("custom_update_staging"); + var affectedRows = await SUT.BulkUpdateAsync([entity], new MySqlBulkUpdateOptions { TempTableOptions = { TableNameProvider = tableNameProvider } }); + + affectedRows.Should().Be(1); + ExecutedCommands.Should().ContainSingle(command => command.StartsWith("CREATE TEMPORARY TABLE `custom_update_staging`", StringComparison.Ordinal)); + ExecutedCommands.Should().Contain("DROP TEMPORARY TABLE IF EXISTS `custom_update_staging`;"); + tableNameProvider.LeasedCount.Should().Be(1); + tableNameProvider.DisposedCount.Should().Be(1); + (await AssertDbContext.TestEntities.SingleAsync()).Count.Should().Be(42); + } + + [Fact] + public void Should_keep_the_TempTableOptions_when_the_options_are_copied() + { + var tableNameProvider = new RecordingTempTableNameProvider("custom_update_staging"); + var options = new MySqlBulkUpdateOptions { TempTableOptions = { TableNameProvider = tableNameProvider } }; + + new MySqlBulkUpdateOptions(options).TempTableOptions.TableNameProvider.Should().BeSameAs(tableNameProvider); + } + [Fact] public async Task Should_drop_the_staging_table_if_the_update_fails() { diff --git a/tests/Thinktecture.EntityFrameworkCore.MySql.Tests/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutorTests/RecordingTempTableNameProvider.cs b/tests/Thinktecture.EntityFrameworkCore.MySql.Tests/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutorTests/RecordingTempTableNameProvider.cs new file mode 100644 index 00000000..44027897 --- /dev/null +++ b/tests/Thinktecture.EntityFrameworkCore.MySql.Tests/EntityFrameworkCore/BulkOperations/MySqlBulkOperationExecutorTests/RecordingTempTableNameProvider.cs @@ -0,0 +1,31 @@ +using Microsoft.EntityFrameworkCore.Metadata; +using Thinktecture.EntityFrameworkCore.TempTables; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations.MySqlBulkOperationExecutorTests; + +/// +/// Leases a fixed name and records how many leases were taken and disposed. +/// +internal sealed class RecordingTempTableNameProvider(string name) : ITempTableNameProvider +{ + public int LeasedCount { get; private set; } + + public int DisposedCount { get; private set; } + + public ITempTableNameLease LeaseName(DbContext ctx, IEntityType entityType) + { + LeasedCount++; + + return new Lease(name, () => DisposedCount++); + } + + private sealed class Lease(string name, Action onDispose) : ITempTableNameLease + { + public string Name { get; } = name; + + public void Dispose() + { + onDispose(); + } + } +}