public SqlConnection CreateConnection(Session session)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXCreatingConnection, session.ToStringSafely());
            }

            SqlConnection connection;

            try {
                connection = underlyingDriver.CreateConnection();
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }

            var sessionConfiguration = GetConfiguration(session);

            if (sessionConfiguration.ConnectionInfo != null)
            {
                connection.ConnectionInfo = sessionConfiguration.ConnectionInfo;
            }
            connection.CommandTimeout = sessionConfiguration.DefaultCommandTimeout;

            if (!string.IsNullOrEmpty(configuration.ConnectionInitializationSql))
            {
                SetInitializationSql(connection, configuration.ConnectionInitializationSql);
            }

            return(connection);
        }
        public void OpenConnection(Session session, SqlConnection connection)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXOpeningConnectionY, session.ToStringSafely(), connection.ConnectionInfo);
            }

            var extension = connection.Extensions.Get <InitializationSqlExtension>();

            var script = extension?.Script;

            try {
                if (!string.IsNullOrEmpty(script))
                {
                    connection.OpenAndInitialize(extension.Script);
                }
                else
                {
                    connection.Open();
                }
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        private async Task <TResult> ExecuteCommandAsync <TResult>(Session session, DbCommand command, CancellationToken cancellationToken, Func <DbCommand, CancellationToken, Task <TResult> > action)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXQueryY, session.ToStringSafely(), command.ToHumanReadableString());
            }

            cancellationToken.ThrowIfCancellationRequested();
            session?.Events.NotifyDbCommandExecuting(command);

            TResult result;

            try {
                result = await action(command, cancellationToken).ConfigureAwait(false);
            }
            catch (OperationCanceledException) {
                throw;
            }
            catch (Exception exception) {
                var wrapped = ExceptionBuilder.BuildException(exception, command.ToHumanReadableString());
                session?.Events.NotifyDbCommandExecuted(command, wrapped);
                throw wrapped;
            }

            session?.Events.NotifyDbCommandExecuted(command);

            return(result);
        }
        public async Task OpenConnectionAsync(Session session, SqlConnection connection, CancellationToken cancellationToken)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXOpeningConnectionY, session.ToStringSafely(), connection.ConnectionInfo);
            }

            var extension = connection.Extensions.Get <InitializationSqlExtension>();

            try {
                if (!string.IsNullOrEmpty(extension?.Script))
                {
                    await connection.OpenAndInitializeAsync(extension.Script, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException) {
                throw;
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
Example #5
0
 private void LogStatements(IEnumerable <string> statements)
 {
     SqlLog.Info(
         Strings.LogSessionXSchemaUpgradeScriptY,
         session.ToStringSafely(),
         driver.BuildBatch(statements.ToArray()).Trim());
 }
        private TResult ExecuteCommand <TResult>(
            Session session, DbCommand command, CommandBehavior commandBehavior, Func <DbCommand, CommandBehavior, TResult> action)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXQueryY, session.ToStringSafely(), command.ToHumanReadableString());
            }

            session?.Events.NotifyDbCommandExecuting(command);

            TResult result;

            try {
                result = action.Invoke(command, commandBehavior);
            }
            catch (Exception exception) {
                var wrapped = ExceptionBuilder.BuildException(exception, command.ToHumanReadableString());
                session?.Events.NotifyDbCommandExecuted(command, wrapped);
                throw wrapped;
            }

            session?.Events.NotifyDbCommandExecuted(command);

            return(result);
        }
 private void EnsureConnectionIsAlive(ref SqlServerConnection connection, string query)
 {
     try {
         using (var command = connection.CreateCommand()) {
             command.CommandText = query;
             command.ExecuteNonQuery();
         }
     }
     catch (Exception exception) {
         if (SqlHelper.ShouldRetryOn(exception))
         {
             SqlLog.Warning(exception, Strings.LogGivenConnectionIsCorruptedTryingToRestoreTheConnection);
             if (!TryReconnect(ref connection, query))
             {
                 SqlLog.Error(exception, Strings.LogConnectionRestoreFailed);
                 throw;
             }
             SqlLog.Info(Strings.LogConnectionSuccessfullyRestored);
         }
         else
         {
             throw;
         }
     }
 }
        public void DisposeConnection(Session session, SqlConnection connection)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXDisposingConnection, session.ToStringSafely());
            }

            try {
                connection.Dispose();
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public void RollbackTransaction(Session session, SqlConnection connection)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXRollbackTransaction, session.ToStringSafely());
            }

            try {
                connection.Rollback();
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public void ReleaseSavepoint(Session session, SqlConnection connection, string name)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXReleaseSavepointY, session.ToStringSafely(), name);
            }

            try {
                connection.ReleaseSavepoint(name);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public async Task DisposeConnectionAsync(Session session, SqlConnection connection)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXDisposingConnection, session.ToStringSafely());
            }

            try {
                await connection.DisposeAsync().ConfigureAwait(false);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public void SqlLogTest()
        {
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            SqlLog.Debug("Test message", null);
            SqlLog.Debug("Test message with parameter {0}", new object[] { 1 });
            SqlLog.Debug(new Exception("Some exception"), "Test message with parameter {0}", new object[] { 1 });
            SqlLog.Debug("Test message", new object[] { 1 });
            SqlLog.Debug("Test message {0}", null);
            SqlLog.Debug(new Exception("Some exeption"));
            SqlLog.Debug(null, new object[] { 1 });

            SqlLog.Info("Test message", null);
            SqlLog.Info("Test message with parameter {0}", new object[] { 1 });
            SqlLog.Info(new Exception("Some exception"), "Test message with parameter {0}", new object[] { 1 });
            SqlLog.Info("Test message", new object[] { 1 });
            SqlLog.Info("Test message {0}", null);
            SqlLog.Info(new Exception("Some exeption"));
            SqlLog.Info(null, new object[] { 1 });

            SqlLog.Warning("Test message", null);
            SqlLog.Warning("Test message with parameter {0}", new object[] { 1 });
            SqlLog.Warning(new Exception("Some exception"), "Test message with parameter {0}", new object[] { 1 });
            SqlLog.Warning("Test message", new object[] { 1 });
            SqlLog.Warning("Test message {0}", null);
            SqlLog.Warning(new Exception("Some exeption"));
            SqlLog.Warning(null, new object[] { 1 });

            SqlLog.Error("Test message", null);
            SqlLog.Error("Test message with parameter {0}", new object[] { 1 });
            SqlLog.Error(new Exception("Some exception"), "Test message with parameter {0}", new object[] { 1 });
            SqlLog.Error("Test message", new object[] { 1 });
            SqlLog.Error("Test message {0}", null);
            SqlLog.Error(new Exception("Some exeption"));
            SqlLog.Error(null, new object[] { 1 });

            SqlLog.FatalError("Test message", null);
            SqlLog.FatalError("Test message with parameter {0}", new object[] { 1 });
            SqlLog.FatalError(new Exception("Some exception"), "Test message with parameter {0}", new object[] { 1 });
            SqlLog.FatalError("Test message", new object[] { 1 });
            SqlLog.FatalError("Test message {0}", null);
            SqlLog.FatalError(new Exception("Some exeption"));
            SqlLog.FatalError(null, new object[] { 1 });

            Assert.IsTrue(File.Exists(filePath));
            Assert.AreEqual(File.ReadAllLines(filePath).Count(), 35);
        }
        public async ValueTask ReleaseSavepointAsync(
            Session session, SqlConnection connection, string name, CancellationToken token = default)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXReleaseSavepointY, session.ToStringSafely(), name);
            }

            try {
                await connection.ReleaseSavepointAsync(name, token).ConfigureAwait(false);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public async ValueTask RollbackTransactionAsync(
            Session session, SqlConnection connection, CancellationToken token = default)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXRollbackTransaction, session.ToStringSafely());
            }

            try {
                await connection.RollbackAsync(token).ConfigureAwait(false);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public void BeginTransaction(Session session, SqlConnection connection, IsolationLevel?isolationLevel)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXBeginningTransactionWithYIsolationLevel, session.ToStringSafely(),
                            isolationLevel);
            }

            isolationLevel ??= IsolationLevelConverter.Convert(GetConfiguration(session).DefaultIsolationLevel);

            try {
                connection.BeginTransaction(isolationLevel.Value);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public async ValueTask BeginTransactionAsync(
            Session session, SqlConnection connection, IsolationLevel?isolationLevel, CancellationToken token = default)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXBeginningTransactionWithYIsolationLevel, session.ToStringSafely(),
                            isolationLevel);
            }

            isolationLevel ??= IsolationLevelConverter.Convert(GetConfiguration(session).DefaultIsolationLevel);

            try {
                await connection.BeginTransactionAsync(isolationLevel.Value, token).ConfigureAwait(false);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public void MakeSavepoint(Session session, SqlConnection connection, string name)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXMakeSavepointY, session.ToStringSafely(), name);
            }

            if (!hasSavepoints)
            {
                return; // Driver does not support savepoints, so let's fail later (on rollback)
            }
            try {
                connection.MakeSavepoint(name);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public void CloseConnection(Session session, SqlConnection connection)
        {
            if (connection.State != ConnectionState.Open)
            {
                return;
            }

            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXClosingConnectionY, session.ToStringSafely(), connection.ConnectionInfo);
            }

            try {
                connection.Close();
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public async Task CloseConnectionAsync(Session session, SqlConnection connection)
        {
            if (connection.State != ConnectionState.Open)
            {
                return;
            }

            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXClosingConnectionY, session.ToStringSafely(), connection.ConnectionInfo);
            }

            try {
                await connection.CloseAsync().ConfigureAwait(false);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public void RollbackToSavepoint(Session session, SqlConnection connection, string name)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXRollbackToSavepointY, session.ToStringSafely(), name);
            }

            if (!hasSavepoints)
            {
                throw new NotSupportedException(Strings.ExCurrentStorageProviderDoesNotSupportSavepoints);
            }

            try {
                connection.RollbackToSavepoint(name);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public async ValueTask MakeSavepointAsync(
            Session session, SqlConnection connection, string name, CancellationToken token = default)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXMakeSavepointY, session.ToStringSafely(), name);
            }

            if (!hasSavepoints)
            {
                return; // Driver does not support save points, so let's fail later (on rollback)
            }

            try {
                await connection.MakeSavepointAsync(name, token).ConfigureAwait(false);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public async ValueTask RollbackToSavepointAsync(
            Session session, SqlConnection connection, string name, CancellationToken token = default)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXRollbackToSavepointY, session.ToStringSafely(), name);
            }

            if (!hasSavepoints)
            {
                throw new NotSupportedException(Strings.ExCurrentStorageProviderDoesNotSupportSavepoints);
            }

            try {
                await connection.RollbackToSavepointAsync(name, token).ConfigureAwait(false);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public SqlConnection CreateConnection(Session session)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXCreatingConnection, session.ToStringSafely());
            }

            SqlConnection connection;

            try {
                connection = underlyingDriver.CreateConnection();
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }

            if (connectionAccessorFactories != null)
            {
                connection.AssignConnectionAccessors(
                    CreateConnectionAccessorsFast(configuration.Types.DbConnectionAccessors));
            }

            var sessionConfiguration = GetConfiguration(session);

            connection.CommandTimeout = sessionConfiguration.DefaultCommandTimeout;
            var connectionInfo = GetConnectionInfo(session) ?? sessionConfiguration.ConnectionInfo;

            if (connectionInfo != null)
            {
                connection.ConnectionInfo = connectionInfo;
            }

            var connectionInitializationSql = GetInitializationSql(session) ?? configuration.ConnectionInitializationSql;

            if (!string.IsNullOrEmpty(connectionInitializationSql))
            {
                SetInitializationSql(connection, connectionInitializationSql);
            }

            return(connection);
        }
        public void OpenConnection(Session session, SqlConnection connection)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXOpeningConnectionY, session.ToStringSafely(), connection.ConnectionInfo);
            }

            try {
                connection.Open();
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }

            var extension = connection.Extensions.Get <InitializationSqlExtension>();

            if (!string.IsNullOrEmpty(extension?.Script))
            {
                using (var command = connection.CreateCommand(extension.Script))
                    ExecuteNonQuery(session, command);
            }
        }