Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ public int? MaxParametersPerStatement
/// </summary>
public TimeSpan? CommandTimeout { get; set; }

/// <summary>
/// Options for the staging temp table.
/// </summary>
public MySqlBulkOperationTempTableOptions TempTableOptions { get; }

/// <inheritdoc />
[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
Expand Down Expand Up @@ -90,6 +95,11 @@ public MySqlBulkInsertOrUpdateOptions(IBulkInsertOrUpdateOptions? optionsToIniti
{
MaxParametersPerStatement = mySqlOptions.MaxParametersPerStatement;
CommandTimeout = mySqlOptions.CommandTimeout;
TempTableOptions = new MySqlBulkOperationTempTableOptions(mySqlOptions.TempTableOptions);
}
else
{
TempTableOptions = new MySqlBulkOperationTempTableOptions();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ public async Task<int> BulkUpdateAsync<T>(IEnumerable<T> 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,
Expand Down Expand Up @@ -276,7 +276,7 @@ public async Task<int> BulkInsertOrUpdateAsync<T>(IEnumerable<T> 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,
Expand Down Expand Up @@ -922,7 +922,7 @@ private async Task<int> ExecuteWithStagingTableAsync<T>(

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;

Expand Down Expand Up @@ -1116,6 +1116,7 @@ private StringBuilder AppendKeyCondition(StringBuilder statement, IReadOnlyList<
/// <param name="Properties">Staged properties; the keys come first.</param>
/// <param name="MaxParametersPerStatement">Parameter budget of the INSERT statements of the fill; <c>null</c> uses the registered value.</param>
/// <param name="CommandTimeout">Timeout of every statement.</param>
/// <param name="TableNameProvider">Provides the name of the staging table; <c>null</c> derives the name from the table of the entity.</param>
/// <param name="IsUpsert">Indication whether the operation is an upsert; an upsert stages a store-generated key without a key index.</param>
private sealed record StagingTable(
IEntityType EntityType,
Expand All @@ -1124,5 +1125,6 @@ private sealed record StagingTable(
IReadOnlyList<PropertyWithNavigations> Properties,
int? MaxParametersPerStatement,
TimeSpan? CommandTimeout,
ITempTableNameProvider? TableNameProvider,
bool IsUpsert);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Thinktecture.EntityFrameworkCore.TempTables;

namespace Thinktecture.EntityFrameworkCore.BulkOperations;

/// <summary>
/// Options for the staging temp table of the MySQL bulk update and upsert operations.
/// </summary>
public sealed class MySqlBulkOperationTempTableOptions
{
internal MySqlBulkOperationTempTableOptions(MySqlBulkOperationTempTableOptions? options = null)
{
TableNameProvider = options?.TableNameProvider;
}

/// <summary>
/// Provides the name to create the staging temp table with.
/// The default is the <see cref="ReusingTempTableNameProvider"/>, which derives the name from the table name of the entity.
/// </summary>
/// <remarks>
/// The <see cref="IBulkUpdateOptions.TableNameProvider"/> and <see cref="IBulkInsertOrUpdateOptions.TableNameProvider"/> 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.
/// </remarks>
public ITempTableNameProvider? TableNameProvider { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ public int? MaxParametersPerStatement
/// </summary>
public TimeSpan? CommandTimeout { get; set; }

/// <summary>
/// Options for the staging temp table.
/// </summary>
public MySqlBulkOperationTempTableOptions TempTableOptions { get; }

/// <inheritdoc />
[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
Expand Down Expand Up @@ -80,6 +85,11 @@ public MySqlBulkUpdateOptions(IBulkUpdateOptions? optionsToInitializeFrom = null
{
MaxParametersPerStatement = mySqlOptions.MaxParametersPerStatement;
CommandTimeout = mySqlOptions.CommandTimeout;
TempTableOptions = new MySqlBulkOperationTempTableOptions(mySqlOptions.TempTableOptions);
}
else
{
TempTableOptions = new MySqlBulkOperationTempTableOptions();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Microsoft.EntityFrameworkCore.Metadata;
using Thinktecture.EntityFrameworkCore.TempTables;

namespace Thinktecture.EntityFrameworkCore.BulkOperations.MySqlBulkOperationExecutorTests;

/// <summary>
/// Leases a fixed name and records how many leases were taken and disposed.
/// </summary>
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();
}
}
}
Loading