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
1 change: 1 addition & 0 deletions Dependencies.targets
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<PackageReference Update="Microsoft.EntityFrameworkCore" Version="$(EFCoreVersion)" />

<PackageReference Update="MySqlConnector" Version="2.3.1" />
<PackageReference Update="MySqlConnector.DependencyInjection" Version="2.3.1" />

<PackageReference Update="NetTopologySuite" Version="2.5.0" />
<PackageReference Update="System.Text.Json" Version="8.0.0" />
Expand Down
1 change: 1 addition & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
<EfCoreTargetFramework>net8.0</EfCoreTargetFramework>
<EfCoreTestTargetFramework>net8.0</EfCoreTestTargetFramework>
<MySqlConnectorTargetFramework>net8.0</MySqlConnectorTargetFramework>
<MySqlConnectorDependencyInjectionTargetFramework>net7.0</MySqlConnectorDependencyInjectionTargetFramework>
</PropertyGroup>

<PropertyGroup>
Expand Down
32 changes: 32 additions & 0 deletions src/EFCore.MySql/Extensions/MySqlDatabaseFacadeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@
// Licensed under the MIT. See LICENSE in the project root for license information.

using System;
using System.Data.Common;
using System.Reflection;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Pomelo.EntityFrameworkCore.MySql.Storage.Internal;

//ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore
Expand All @@ -32,5 +36,33 @@ public static bool IsMySql([NotNull] this DatabaseFacade database)
=> database.ProviderName.Equals(
typeof(MySqlOptionsExtension).GetTypeInfo().Assembly.GetName().Name,
StringComparison.Ordinal);

/// <summary>
/// Uses a <see cref="DbDataSource" /> for this <see cref="DbContext" /> as the underlying database provider.
/// </summary>
/// <remarks>
/// <para>
/// It may not be possible to change the data source if an existing connection is open.
/// </para>
/// <para>
/// See <see href="https://aka.ms/efcore-docs-connections">Connections and connection strings</see> for more information and examples.
/// </para>
/// </remarks>
/// <param name="databaseFacade">The <see cref="DatabaseFacade" /> for the context.</param>
/// <param name="dataSource">The data source.</param>
public static void SetDbDataSource(this DatabaseFacade databaseFacade, DbDataSource dataSource)
=> ((MySqlRelationalConnection)GetFacadeDependencies(databaseFacade).RelationalConnection).DbDataSource = dataSource;

private static IRelationalDatabaseFacadeDependencies GetFacadeDependencies(DatabaseFacade databaseFacade)
{
var dependencies = ((IDatabaseFacadeDependenciesAccessor)databaseFacade).Dependencies;

if (dependencies is IRelationalDatabaseFacadeDependencies relationalDependencies)
{
return relationalDependencies;
}

throw new InvalidOperationException(RelationalStrings.RelationalNotInUse);
}
}
}
108 changes: 72 additions & 36 deletions src/EFCore.MySql/Extensions/MySqlDbContextOptionsBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
using MySqlConnector;

// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore
Expand Down Expand Up @@ -98,17 +96,6 @@ public static DbContextOptionsBuilder UseMySql(
Check.NotNull(optionsBuilder, nameof(optionsBuilder));
Check.NullButNotEmpty(connectionString, nameof(connectionString));

if (connectionString is not null)
{
var resolvedConnectionString = new NamedConnectionStringResolver(optionsBuilder.Options)
.ResolveConnectionString(connectionString);

// TODO: Move to MySqlRelationalConnection.
var csb = new MySqlConnectionStringBuilder(resolvedConnectionString) { AllowUserVariables = true, UseAffectedRows = false };

connectionString = csb.ConnectionString;
}

var extension = (MySqlOptionsExtension)GetOrCreateExtension(optionsBuilder)
.WithServerVersion(serverVersion)
.WithConnectionString(connectionString);
Expand Down Expand Up @@ -155,35 +142,52 @@ public static DbContextOptionsBuilder UseMySql(
Check.NotNull(optionsBuilder, nameof(optionsBuilder));
Check.NotNull(connection, nameof(connection));

var resolvedConnectionString = connection.ConnectionString is not null
? new NamedConnectionStringResolver(optionsBuilder.Options)
.ResolveConnectionString(connection.ConnectionString)
: null;
var extension = (MySqlOptionsExtension)GetOrCreateExtension(optionsBuilder)
.WithServerVersion(serverVersion)
.WithConnection(connection);

// TODO: Move to MySqlRelationalConnection.
var csb = new MySqlConnectionStringBuilder(resolvedConnectionString);
((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension);
ConfigureWarnings(optionsBuilder);
mySqlOptionsAction?.Invoke(new MySqlDbContextOptionsBuilder(optionsBuilder));

if (!csb.AllowUserVariables ||
csb.UseAffectedRows)
{
try
{
csb.AllowUserVariables = true;
csb.UseAffectedRows = false;
return optionsBuilder;
}

connection.ConnectionString = csb.ConnectionString;
}
catch (Exception e)
{
throw new InvalidOperationException(
@"The connection string of a connection used by Pomelo.EntityFrameworkCore.MySql must contain ""AllowUserVariables=true;UseAffectedRows=false"".",
e);
}
}

/// <summary>
/// Configures the context to connect to a MySQL compatible database.
/// </summary>
/// <param name="optionsBuilder"> The builder being used to configure the context. </param>
/// <param name="dataSource"> A <see cref="DbDataSource" /> which will be used to get database connections. </param>
/// <param name="serverVersion">
/// <para>
/// The version of the database server.
/// </para>
/// <para>
/// Create an object for this parameter by calling the static method
/// <see cref="ServerVersion.Create(System.Version,ServerType)"/>,
/// by calling the static method <see cref="ServerVersion.AutoDetect(string)"/> (which retrieves the server version directly
/// from the database server),
/// by parsing a version string using the static methods
/// <see cref="ServerVersion.Parse(string)"/> or <see cref="ServerVersion.TryParse(string,out ServerVersion)"/>,
/// or by directly instantiating an object from the <see cref="MySqlServerVersion"/> (for MySQL) or
/// <see cref="MariaDbServerVersion"/> (for MariaDB) classes.
/// </para>
/// </param>
/// <param name="mySqlOptionsAction"> An optional action to allow additional MySQL specific configuration. </param>
/// <returns> The options builder so that further configuration can be chained. </returns>
public static DbContextOptionsBuilder UseMySql(
this DbContextOptionsBuilder optionsBuilder,
DbDataSource dataSource,
[NotNull] ServerVersion serverVersion,
Action<MySqlDbContextOptionsBuilder> mySqlOptionsAction = null)
{
Check.NotNull(optionsBuilder, nameof(optionsBuilder));
Check.NotNull(dataSource, nameof(dataSource));

var extension = (MySqlOptionsExtension)GetOrCreateExtension(optionsBuilder)
.WithServerVersion(serverVersion)
.WithConnection(connection);
.WithDataSource(dataSource);

((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension);
ConfigureWarnings(optionsBuilder);
Expand Down Expand Up @@ -298,6 +302,38 @@ public static DbContextOptionsBuilder<TContext> UseMySql<TContext>(
=> (DbContextOptionsBuilder<TContext>)UseMySql(
(DbContextOptionsBuilder)optionsBuilder, connection, serverVersion, mySqlOptionsAction);

/// <summary>
/// Configures the context to connect to a MySQL compatible database.
/// </summary>
/// <param name="optionsBuilder"> The builder being used to configure the context. </param>
/// <param name="dataSource"> A <see cref="DbDataSource" /> which will be used to get database connections. </param>
/// <typeparam name="TContext"> The type of context to be configured. </typeparam>
/// <param name="serverVersion">
/// <para>
/// The version of the database server.
/// </para>
/// <para>
/// Create an object for this parameter by calling the static method
/// <see cref="ServerVersion.Create(System.Version,ServerType)"/>,
/// by calling the static method <see cref="ServerVersion.AutoDetect(string)"/> (which retrieves the server version directly
/// from the database server),
/// by parsing a version string using the static methods
/// <see cref="ServerVersion.Parse(string)"/> or <see cref="ServerVersion.TryParse(string,out ServerVersion)"/>,
/// or by directly instantiating an object from the <see cref="MySqlServerVersion"/> (for MySQL) or
/// <see cref="MariaDbServerVersion"/> (for MariaDB) classes.
/// </para>
/// </param>
/// <param name="mySqlOptionsAction"> An optional action to allow additional MySQL specific configuration. </param>
/// <returns> The options builder so that further configuration can be chained. </returns>
public static DbContextOptionsBuilder<TContext> UseMySql<TContext>(
[NotNull] this DbContextOptionsBuilder<TContext> optionsBuilder,
[NotNull] DbDataSource dataSource,
[NotNull] ServerVersion serverVersion,
[CanBeNull] Action<MySqlDbContextOptionsBuilder> mySqlOptionsAction = null)
where TContext : DbContext
=> (DbContextOptionsBuilder<TContext>)UseMySql(
(DbContextOptionsBuilder)optionsBuilder, dataSource, serverVersion, mySqlOptionsAction);

private static MySqlOptionsExtension GetOrCreateExtension(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.Options.FindExtension<MySqlOptionsExtension>()
?? new MySqlOptionsExtension();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
using Pomelo.EntityFrameworkCore.MySql.Migrations;
using Pomelo.EntityFrameworkCore.MySql.Query.ExpressionVisitors.Internal;
using Pomelo.EntityFrameworkCore.MySql.Query.Internal;
using Pomelo.EntityFrameworkCore.MySql.Storage;

// ReSharper disable once CheckNamespace
namespace Microsoft.Extensions.DependencyInjection
Expand Down Expand Up @@ -111,7 +110,7 @@ public static IServiceCollection AddEntityFrameworkMySql([NotNull] this IService
.TryAdd<IModificationCommandFactory, MySqlModificationCommandFactory>()
.TryAdd<IModificationCommandBatchFactory, MySqlModificationCommandBatchFactory>()
.TryAdd<IValueGeneratorSelector, MySqlValueGeneratorSelector>()
.TryAdd<IRelationalConnection>(p => p.GetService<IMySqlRelationalConnection>())
.TryAdd<IRelationalConnection>(p => p.GetRequiredService<IMySqlRelationalConnection>())
.TryAdd<IMigrationsSqlGenerator, MySqlMigrationsSqlGenerator>()
.TryAdd<IRelationalDatabaseCreator, MySqlDatabaseCreator>()
.TryAdd<IHistoryRepository, MySqlHistoryRepository>()
Expand All @@ -126,7 +125,7 @@ public static IServiceCollection AddEntityFrameworkMySql([NotNull] this IService
.TryAdd<IRelationalSqlTranslatingExpressionVisitorFactory, MySqlSqlTranslatingExpressionVisitorFactory>()
.TryAdd<IRelationalParameterBasedSqlProcessorFactory, MySqlParameterBasedSqlProcessorFactory>()
.TryAdd<ISqlExpressionFactory, MySqlSqlExpressionFactory>()
.TryAdd<ISingletonOptions, IMySqlOptions>(p => p.GetService<IMySqlOptions>())
.TryAdd<ISingletonOptions, IMySqlOptions>(p => p.GetRequiredService<IMySqlOptions>())
//.TryAdd<IValueConverterSelector, MySqlValueConverterSelector>()
.TryAdd<IQueryCompilationContextFactory, MySqlQueryCompilationContextFactory>()
.TryAdd<IQueryTranslationPostprocessorFactory, MySqlQueryTranslationPostprocessorFactory>()
Expand All @@ -141,6 +140,7 @@ public static IServiceCollection AddEntityFrameworkMySql([NotNull] this IService
.TryAddProviderSpecificServices(m => m
//.TryAddSingleton<IMySqlValueGeneratorCache, MySqlValueGeneratorCache>()
.TryAddSingleton<IMySqlOptions, MySqlOptions>()
.TryAddSingleton<IMySqlConnectionStringOptionsValidator, MySqlConnectionStringOptionsValidator>()
//.TryAddScoped<IMySqlSequenceValueGeneratorFactory, MySqlSequenceValueGeneratorFactory>()
.TryAddScoped<IMySqlUpdateSqlGenerator, MySqlUpdateSqlGenerator>()
.TryAddScoped<IMySqlRelationalConnection, MySqlRelationalConnection>());
Expand Down
7 changes: 7 additions & 0 deletions src/EFCore.MySql/Infrastructure/Internal/IMySqlOptions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Pomelo Foundation. All rights reserved.
// Licensed under the MIT. See LICENSE in the project root for license information.

using System.Data.Common;
using Microsoft.EntityFrameworkCore;
using Pomelo.EntityFrameworkCore.MySql.Storage.Internal;
using Microsoft.EntityFrameworkCore.Infrastructure;
Expand All @@ -10,6 +11,12 @@ namespace Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal
public interface IMySqlOptions : ISingletonOptions
{
MySqlConnectionSettings ConnectionSettings { get; }

/// <remarks>
/// If null, there might still be a `DbDataSource` in the ApplicationServiceProvider.
/// </remarks>>
DbDataSource DataSource { get; }

ServerVersion ServerVersion { get; }
CharSet DefaultCharSet { get; }
CharSet NationalCharSet { get; }
Expand Down
41 changes: 41 additions & 0 deletions src/EFCore.MySql/Infrastructure/Internal/MySqlOptionsExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Data.Common;
using System.Globalization;
using Microsoft.EntityFrameworkCore;
using MySqlConnector;
using Pomelo.EntityFrameworkCore.MySql.Storage.Internal;

namespace Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal
{
Expand All @@ -29,6 +32,7 @@ public MySqlOptionsExtension()
public MySqlOptionsExtension([NotNull] MySqlOptionsExtension copyFrom)
: base(copyFrom)
{
DataSource = copyFrom.DataSource;
ServerVersion = copyFrom.ServerVersion;
NoBackslashEscapes = copyFrom.NoBackslashEscapes;
UpdateSqlModeOnOpen = copyFrom.UpdateSqlModeOnOpen;
Expand All @@ -53,6 +57,12 @@ public override DbContextOptionsExtensionInfo Info
protected override RelationalOptionsExtension Clone()
=> new MySqlOptionsExtension(this);

/// <summary>
/// The <see cref="DbDataSource" />, or <see langword="null" /> if a connection string or <see cref="DbConnection" /> was used
/// instead of a <see cref="DbDataSource" />.
/// </summary>
public virtual DbDataSource DataSource { get; private set; }

/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
Expand Down Expand Up @@ -82,6 +92,35 @@ protected override RelationalOptionsExtension Clone()
public virtual bool StringComparisonTranslations { get; private set; }
public virtual bool PrimitiveCollectionsSupport { get; private set; }

/// <summary>
/// Creates a new instance with all options the same as for this instance, but with the given option changed.
/// It is unusual to call this method directly. Instead use <see cref="DbContextOptionsBuilder" />.
/// </summary>
/// <param name="dataSource">The option to change.</param>
/// <returns>A new instance with the option changed.</returns>
public virtual RelationalOptionsExtension WithDataSource(DbDataSource dataSource)
{
var clone = (MySqlOptionsExtension)Clone();
clone.DataSource = dataSource;
return clone;
}

/// <inheritdoc />
public override RelationalOptionsExtension WithConnectionString(string connectionString)
{
var clone = (MySqlOptionsExtension)base.WithConnectionString(connectionString);
clone.DataSource = null;
return clone;
}

/// <inheritdoc />
public override RelationalOptionsExtension WithConnection(DbConnection connection)
{
var clone = (MySqlOptionsExtension)base.WithConnection(connection);
clone.DataSource = null;
return clone;
}

/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
Expand Down Expand Up @@ -230,6 +269,7 @@ public override int GetServiceProviderHashCode()
{
var hashCode = new HashCode();
hashCode.Add(base.GetServiceProviderHashCode());
hashCode.Add(Extension.DataSource?.ConnectionString);
hashCode.Add(Extension.ServerVersion);
hashCode.Add(Extension.NoBackslashEscapes);
hashCode.Add(Extension.UpdateSqlModeOnOpen);
Expand All @@ -251,6 +291,7 @@ public override int GetServiceProviderHashCode()
public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other)
=> other is ExtensionInfo otherInfo &&
base.ShouldUseSameServiceProvider(other) &&
ReferenceEquals(Extension.DataSource, otherInfo.Extension.DataSource) &&
Equals(Extension.ServerVersion, otherInfo.Extension.ServerVersion) &&
Extension.NoBackslashEscapes == otherInfo.Extension.NoBackslashEscapes &&
Extension.UpdateSqlModeOnOpen == otherInfo.Extension.UpdateSqlModeOnOpen &&
Expand Down
Loading