Files
Umbraco-CMS/src/Umbraco.Infrastructure/Persistence/DbConnectionExtensions.cs

74 lines
2.2 KiB
C#
Raw Normal View History

using System;
using System.Data;
using System.Data.Common;
using Microsoft.Extensions.Logging;
2018-05-30 16:40:25 +02:00
using StackExchange.Profiling.Data;
using Umbraco.Cms.Core;
using Umbraco.Cms.Infrastructure.Persistence.FaultHandling;
namespace Umbraco.Extensions
{
public static class DbConnectionExtensions
{
public static bool IsConnectionAvailable(string connectionString, DbProviderFactory factory)
{
var connection = factory?.CreateConnection();
2016-04-12 19:55:50 +02:00
if (connection == null)
2019-12-12 08:11:23 +01:00
throw new InvalidOperationException($"Could not create a connection for provider \"{factory}\".");
2016-04-12 19:55:50 +02:00
connection.ConnectionString = connectionString;
using (connection)
{
return connection.IsAvailable();
}
}
public static bool IsAvailable(this IDbConnection connection)
{
try
{
connection.Open();
connection.Close();
}
2016-04-12 19:55:50 +02:00
catch (DbException e)
{
// Don't swallow this error, the exception is super handy for knowing "why" its not available
StaticApplicationLogging.Logger.LogWarning(e, "Configured database is reporting as not being available.");
return false;
}
return true;
}
2016-12-14 14:06:30 +01:00
/// <summary>
/// Unwraps a database connection.
/// </summary>
/// <remarks>UmbracoDatabase wraps the original database connection in various layers (see
/// OnConnectionOpened); this unwraps and returns the original database connection.</remarks>
internal static IDbConnection UnwrapUmbraco(this IDbConnection connection)
{
2018-05-30 16:40:25 +02:00
var unwrapped = connection;
2018-05-30 16:40:25 +02:00
IDbConnection c;
2016-12-14 14:06:30 +01:00
do
{
2018-05-30 16:40:25 +02:00
c = unwrapped;
2016-12-14 14:06:30 +01:00
if (unwrapped is ProfiledDbConnection profiled)
{
unwrapped = profiled.WrappedConnection;
}
if (unwrapped is RetryDbConnection retrying)
{
unwrapped = retrying.Inner;
}
}
while (c != unwrapped);
2016-12-14 14:06:30 +01:00
return unwrapped;
}
}
}