/// <summary> /// Returns the underlying connection as a typed connection - this is used to unwrap the profiled mini profiler stuff /// </summary> /// <typeparam name="TConnection"></typeparam> /// <param name="connection"></param> /// <returns></returns> public static TConnection GetTypedConnection <TConnection>(IDbConnection connection) where TConnection : class, IDbConnection { IDbConnection?c = connection; for (; ;) { switch (c) { case TConnection ofType: return(ofType); case RetryDbConnection retry: c = retry.Inner; break; case ProfiledDbConnection profiled: c = profiled.WrappedConnection; break; default: throw new NotSupportedException(connection.GetType().FullName); } } }
public void ChangeOrSetDbConnection(IDbConnection dbConnection) { if (dbConnection is null) { throw new ArgumentNullException(nameof(dbConnection)); } DbConnection = dbConnection; }
public static MigrationBase Run(IDbConnectionFactory dbFactory, Type nextRun, Action <MigrationBase> migrateAction) { var sb = StringBuilderCache.Allocate(); var holdFilter = OrmLiteConfig.BeforeExecFilter; OrmLiteConfig.BeforeExecFilter = dbCmd => sb.AppendLine(dbCmd.GetDebugString()); var namedConnection = nextRun.FirstAttribute <NamedConnectionAttribute>()?.Name; IDbConnection? useDb = null; IDbTransaction?trans = null; var instance = nextRun.CreateInstance <MigrationBase>(); try { useDb = namedConnection == null ? dbFactory.OpenDbConnection() : dbFactory.OpenDbConnection(namedConnection); instance.DbFactory = dbFactory; instance.Db = useDb; trans = useDb.OpenTransaction(); instance.AfterOpen(); instance.Transaction = trans; instance.StartedAt = DateTime.UtcNow; // Run Migration migrateAction(instance); instance.CompletedDate = DateTime.UtcNow; instance.Log = sb.ToString(); instance.BeforeCommit(); trans.Commit(); trans.Dispose(); trans = null; } catch (Exception e) { instance.CompletedDate = DateTime.UtcNow; instance.Error = e; instance.Log = sb.ToString(); instance.BeforeRollback(); trans?.Rollback(); trans?.Dispose(); } finally { instance.Db = null; instance.Transaction = null; OrmLiteConfig.BeforeExecFilter = holdFilter; useDb?.Dispose(); StringBuilderCache.Free(sb); } return(instance); }
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private void AssertConnection(IDbConnection?connection) { if (connection == null || connection.State == ConnectionState.Closed || connection.State == ConnectionState.Broken) { throw new InvalidOperationException($"Connection is not opened. Use {nameof(OpenConnectionAsync)}"); } }
internal DataQueryElement(IDbConnection?connection, Func <QueryBuilderArgs <TTable>, SqlExpression <TTable> >?queryBuilder, string?onEmptyOrNullRaiseError, SelectType selectType, QuerySqlSelect?querySqlSelect) { _connection = connection; _queryBuilder = queryBuilder; _onEmptyOrNullRaiseError = onEmptyOrNullRaiseError; _selectType = selectType; _querySqlSelect = querySqlSelect; }
public IDbConnection GetOpenConnection() { if (_connection == null || _connection.State != ConnectionState.Open) { _connection = new NpgsqlConnection(_connectionString); _connection.Open(); } return(_connection); }
internal IDbConnection?CreateConnection() { IDbConnection?connection = this.DbProviderFactory?.CreateConnection(); if (connection != null) { connection !.ConnectionString = this.ConnectionString; } return(connection); }
public void TestDisposeFlagCloning([DataSources(false)] string context, [Values] bool dispose) { using (var db = new DataConnection(context)) { var cn = db.Connection; using (var testDb = new DataConnection(db.DataProvider, cn, dispose)) { Assert.AreEqual(ConnectionState.Open, cn.State); IDbConnection?clonedConnection = null; using (var clonedDb = (DataConnection)((IDataContext)testDb).Clone(true)) { clonedConnection = clonedDb.Connection; // fails in v2 for MARS-enabled connections, already fixed in v3 Assert.AreEqual(db.IsMarsEnabled, testDb.IsMarsEnabled); if (testDb.IsMarsEnabled) { // connection reused Assert.AreEqual(cn, clonedConnection); Assert.AreEqual(ConnectionState.Open, cn.State); } else { Assert.AreNotEqual(cn, clonedConnection); Assert.AreEqual(ConnectionState.Open, cn.State); Assert.AreEqual(ConnectionState.Open, clonedConnection.State); } } if (testDb.IsMarsEnabled) { // cloned DC doesn't dispose parent connection Assert.AreEqual(ConnectionState.Open, cn.State); } else { // cloned DC dispose own connection Assert.AreEqual(ConnectionState.Open, cn.State); try { Assert.AreEqual(ConnectionState.Closed, clonedConnection.State); } catch (ObjectDisposedException) { // API consistency FTW! } } } } }
/// <summary> /// Creates a database connection. If it has already been created, the existing one will be returned. /// </summary> /// <returns>A database connection.</returns> /// <remarks>The connection will not be opened as part of this operation.</remarks> public IDbConnection CreateConnection() { lock (_lock) { if (_connection != null) { return(_connection); } _connection = _connectionFactory.CreateConnection(); return(_connection); } }
void TestMssql() { bool flag = false; IDbConnection?connection = null; try { connection = new SqlConnection(ConnectString); flag = connection != null; } catch (Exception ex) { AppendLine(tb_Output, $"{ConnectString} New SqlConnection Handler Error {ex.Message}\r\n{ex}"); flag = false; } if (!flag) { return; } try { connection.Open(); flag = true; } catch (Exception ex) { AppendLine(tb_Output, $"{ConnectString} Open Handler Error {ex.Message}\r\n{ex}"); flag = false; } AppendLine(tb_Output, $"{ConnectString} Open {(flag ? "Success" : "Failed")}"); if (!flag) { return; } try { connection?.Close(); flag = true; } catch (Exception ex) { AppendLine(tb_Output, $"{ConnectString} Close Handler Error {ex.Message}\r\n{ex}"); flag = false; } AppendLine(tb_Output, $"{ConnectString} Close {(flag ? "Success" : "Failed")}"); }
public void ChangeOrSetDbConnection(string connectionString, DbTypes dbType) { if (connectionString.IsNullOrWhiteSpace()) { throw new ArgumentNullException(nameof(connectionString)); } DbConnection = dbType switch { DbTypes.MYSQL => new MySqlConnection(connectionString), //DbTypes.SQLSERVER => new MySqlConnection(connectionString), //DbTypes.ORACLE => new MySqlConnection(connectionString), _ => throw new NotImplementedException() }; }
public IDbConnection GetOpenConnection() { if (_connection == null) { _connection = new SqlConnection(_connectionString); _connection.Open(); } if (_connection.State == ConnectionState.Broken) { _connection.Close(); _connection.Open(); } return(_connection); }
/// <summary> /// RollbackAsync /// </summary> /// <param name="context"></param> /// <returns></returns> /// <exception cref="DatabaseException">Ignore.</exception> public async Task RollbackAsync(TransactionContext context, [CallerMemberName] string?callerMemberName = null, [CallerLineNumber] int callerLineNumber = 0) { //if (context == null || context.Transaction == null) //{ // throw new ArgumentNullException(nameof(context)); //} if (context.Status == TransactionStatus.Rollbacked || context.Status == TransactionStatus.Commited) { return; } if (context.Status != TransactionStatus.InTransaction) { throw Exceptions.TransactionError("AlreadyFinished", callerMemberName, callerLineNumber); } try { IDbConnection?conn = context.Transaction.Connection; await _databaseEngine.RollbackAsync(context.Transaction).ConfigureAwait(false); //context.Transaction.Rollback(); context.Transaction.Dispose(); if (conn != null && conn.State != ConnectionState.Closed) { conn.Dispose(); } context.Status = TransactionStatus.Rollbacked; } catch { context.Status = TransactionStatus.Failed; throw; } }
/// <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) { IDbConnection?unwrapped = connection; IDbConnection c; do { c = unwrapped; if (unwrapped is ProfiledDbConnection profiled) { unwrapped = profiled.WrappedConnection; } if (unwrapped is RetryDbConnection retrying) { unwrapped = retrying.Inner; } }while (c != unwrapped); return(unwrapped); }
/// <inheritdoc /> public void Dispose() { _connection?.Dispose(); _connection = null; if (_filterData == null) { return; } _filterData.LimitInfo = null; if (_filterData.OrderInfo != null) { _filterData.OrderInfo.Columns?.Clear(); _filterData.OrderInfo.Columns = null; _filterData.OrderInfo = null; } if (_filterData.SelectInfo != null) { _filterData.SelectInfo.Columns.Clear(); _filterData.SelectInfo = null; } _filterData = null; }
public void Configure(DatabaseSettings databaseSettings) { var connectionString = GetConnectionString(databaseSettings); connection = new SqlConnection(connectionString); }
internal DataQueryWriteBuilder(IDbConnection?connection) { _connection = connection; }
public FlowElementImpl(IDbConnection?connection, object mapAction, object writeAction) { _connection = connection; _mapAction = mapAction; _writeAction = writeAction; }
/// <summary> /// Constructor /// </summary> public ReadOnlyDapperRepository(IDbConnection connection, ISqlGenerator <TEntity> sqlGenerator) { _connection = connection; _filterData = new FilterData(); SqlGenerator = sqlGenerator; }
public DbStepBuilderImpl(IDbConnection?connection) { _connection = connection; }
public OrmLiteFlowElement(Func <OrmLiteFlowElementArgs, Task <object> > onExecute, Func <OrmLiteFlowElementArgs, Task <CanExecuteResult> > onCanExecute, IDbConnection?connection) { _onExecute = onExecute; _onCanExecute = onCanExecute; _connection = connection; }
public DataFlowElementBuilder SetConnection(IDbConnection connection) { _connection = connection; return(this); }
internal DataFlowElementBuilderRead(IDbConnection?connection) { _connection = connection; }
public DeleteQueryBuilder(IDbConnection?connection) { _connection = connection; }