Beispiel #1
0
            public bool MoveNext()
            {
                try
                {
                    using (_relationalQueryContext.ConcurrencyDetector.EnterCriticalSection())
                    {
                        if (_dataReader == null)
                        {
                            if (_executionStrategy == null)
                            {
                                _executionStrategy = _relationalQueryContext.ExecutionStrategyFactory.Create();
                            }

                            _executionStrategy.Execute(true, InitializeReader, null);
                        }

                        var hasNext = _resultCoordinator.HasNext ?? _dataReader.Read();
                        Current = default;

                        if (hasNext)
                        {
                            while (true)
                            {
                                _resultCoordinator.ResultReady = true;
                                _resultCoordinator.HasNext     = null;
                                Current = _shaper(
                                    _relationalQueryContext, _dataReader.DbDataReader,
                                    _resultCoordinator.ResultContext, _indexMap, _resultCoordinator);
                                if (_resultCoordinator.ResultReady)
                                {
                                    // We generated a result so null out previously stored values
                                    _resultCoordinator.ResultContext.Values = null;
                                    break;
                                }

                                if (!_dataReader.Read())
                                {
                                    _resultCoordinator.HasNext = false;
                                    // Enumeration has ended, materialize last element
                                    _resultCoordinator.ResultReady = true;
                                    Current = _shaper(
                                        _relationalQueryContext, _dataReader.DbDataReader,
                                        _resultCoordinator.ResultContext, _indexMap, _resultCoordinator);

                                    break;
                                }
                            }
                        }

                        return(hasNext);
                    }
                }
                catch (Exception exception)
                {
                    _logger.QueryIterationFailed(_contextType, exception);

                    throw;
                }
            }
Beispiel #2
0
            private bool BufferlessMoveNext(DbContext _, bool buffer)
            {
                if (_dataReader == null)
                {
                    _relationalQueryContext.Connection.Open();

                    try
                    {
                        var relationalCommand
                            = _shaperCommandContext
                              .GetRelationalCommand(_relationalQueryContext.ParameterValues, _relationalQueryContext);

                        _relationalQueryContext.Connection.RegisterBufferable(this);

                        _dataReader
                            = relationalCommand.ExecuteReader(
                                  _relationalQueryContext.Connection,
                                  _relationalQueryContext.ParameterValues,
                                  _relationalQueryContext.CommandLogger);
                    }
                    catch
                    {
                        // If failure happens creating the data reader, then it won't be available to
                        // handle closing the connection, so do it explicitly here to preserve ref counting.
                        _relationalQueryContext.Connection.Close();

                        throw;
                    }

                    _dbDataReader = _dataReader.DbDataReader;
                    _shaperCommandContext.NotifyReaderCreated(_dbDataReader);
                    _valueBufferFactory = _shaperCommandContext.ValueBufferFactory;
                }

                var hasNext = _dataReader.Read();

                Current
                    = hasNext
                        ? _shaper.Shape(_relationalQueryContext, _valueBufferFactory.Create(_dbDataReader))
                        : default;

                if (buffer)
                {
                    BufferAll();
                }

                return(hasNext);
            }
        /// <summary>
        ///     Consumes the data reader created by <see cref="ReaderModificationCommandBatch.Execute" />,
        ///     propagating values back into the <see cref="ModificationCommand" />.
        /// </summary>
        /// <param name="commandIndex"> The ordinal of the command being consumed. </param>
        /// <param name="reader"> The data reader. </param>
        /// <returns> The ordinal of the next command that must be consumed. </returns>
        protected virtual int ConsumeResultSetWithPropagation(int commandIndex, RelationalDataReader reader)
        {
            var rowsAffected = 0;

            do
            {
                var tableModification = ModificationCommands[commandIndex];
                Check.DebugAssert(tableModification.RequiresResultPropagation, "RequiresResultPropagation is false");

                if (!reader.Read())
                {
                    var expectedRowsAffected = rowsAffected + 1;
                    while (++commandIndex < CommandResultSet.Count &&
                           CommandResultSet[commandIndex - 1] == ResultSetMapping.NotLastInResultSet)
                    {
                        expectedRowsAffected++;
                    }

                    ThrowAggregateUpdateConcurrencyException(commandIndex, expectedRowsAffected, rowsAffected);
                }

                var valueBufferFactory = CreateValueBufferFactory(tableModification.ColumnModifications);

                tableModification.PropagateResults(valueBufferFactory.Create(reader.DbDataReader));
                rowsAffected++;
            }while (++commandIndex < CommandResultSet.Count &&
                    CommandResultSet[commandIndex - 1] == ResultSetMapping.NotLastInResultSet);

            return(commandIndex);
        }
        /// <summary>
        ///     Consumes the data reader created by <see cref="ReaderModificationCommandBatch.Execute" />
        ///     without propagating values back into the <see cref="ModificationCommand" />.
        /// </summary>
        /// <param name="commandIndex"> The ordinal of the command being consumed. </param>
        /// <param name="reader"> The data reader. </param>
        /// <returns> The ordinal of the next command that must be consumed. </returns>
        protected virtual int ConsumeResultSetWithoutPropagation(int commandIndex, RelationalDataReader reader)
        {
            var expectedRowsAffected = 1;

            while (++commandIndex < CommandResultSet.Count &&
                   CommandResultSet[commandIndex - 1] == ResultSetMapping.NotLastInResultSet)
            {
                Check.DebugAssert(!ModificationCommands[commandIndex].RequiresResultPropagation, "RequiresResultPropagation is true");

                expectedRowsAffected++;
            }

            if (reader.Read())
            {
                var rowsAffected = reader.DbDataReader.GetInt32(0);
                if (rowsAffected != expectedRowsAffected)
                {
                    ThrowAggregateUpdateConcurrencyException(commandIndex, expectedRowsAffected, rowsAffected);
                }
            }
            else
            {
                ThrowAggregateUpdateConcurrencyException(commandIndex, 1, 0);
            }

            return(commandIndex);
        }
            public bool MoveNext()
            {
                try
                {
                    using (_relationalQueryContext.ConcurrencyDetector.EnterCriticalSection())
                    {
                        if (_dataReader == null)
                        {
                            _relationalQueryContext.ExecutionStrategyFactory.Create()
                            .Execute(true, InitializeReader, null);
                        }

                        var hasNext = _dataReader.Read();

                        Current = hasNext
                            ? _shaper(_relationalQueryContext, _dataReader.DbDataReader, _indexMap)
                            : default;

                        return(hasNext);
                    }
                }
                catch (Exception exception)
                {
                    _queryLogger.QueryIterationFailed(_contextType, exception);

                    throw;
                }
            }
        protected override void Consume(RelationalDataReader relationalReader)
        {
            if (relationalReader == null)
            {
                throw new ArgumentNullException(nameof(relationalReader));
            }

            var dataReader   = (FbDataReader)relationalReader.DbDataReader;
            var commandIndex = 0;

            try
            {
                for (; ;)
                {
                    while (commandIndex < CommandResultSet.Count && CommandResultSet[commandIndex] == ResultSetMapping.NoResultSet)
                    {
                        commandIndex++;
                    }

                    var propragation = commandIndex;
                    while (propragation < ModificationCommands.Count && !ModificationCommands[propragation].RequiresResultPropagation)
                    {
                        propragation++;
                    }

                    while (commandIndex < propragation)
                    {
                        commandIndex++;
                        if (!dataReader.Read())
                        {
                            throw new DbUpdateConcurrencyException(RelationalStrings.UpdateConcurrencyException(1, 0), ModificationCommands[commandIndex].Entries);
                        }
                    }
                    //check if you've gone through all notifications
                    if (propragation == ModificationCommands.Count)
                    {
                        break;
                    }

                    var modifications = ModificationCommands[commandIndex];
                    if (!relationalReader.Read())
                    {
                        throw new DbUpdateConcurrencyException(RelationalStrings.UpdateConcurrencyException(1, 0), modifications.Entries);
                    }

                    var bufferFactory = CreateValueBufferFactory(modifications.ColumnModifications);
                    modifications.PropagateResults(bufferFactory.Create(dataReader));
                    dataReader.NextResult();
                    commandIndex++;
                }
            }
            catch (DbUpdateException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new DbUpdateException(RelationalStrings.UpdateStoreException, ex, ModificationCommands[commandIndex].Entries);
            }
        }
Beispiel #7
0
    /// <summary>
    ///     Consumes the data reader created by <see cref="ReaderModificationCommandBatch.Execute" />,
    ///     propagating values back into the <see cref="ModificationCommand" />.
    /// </summary>
    /// <param name="startResultSetIndex">The ordinal of the first result set being consumed.</param>
    /// <param name="reader">The data reader.</param>
    /// <returns>The ordinal of the next result set that must be consumed.</returns>
    protected virtual int ConsumeResultSetWithPropagation(int startResultSetIndex, RelationalDataReader reader)
    {
        var resultSetIndex = startResultSetIndex;
        var rowsAffected   = 0;

        do
        {
            if (!reader.Read())
            {
                var expectedRowsAffected = rowsAffected + 1;
                while (++resultSetIndex < CommandResultSet.Count &&
                       CommandResultSet[resultSetIndex - 1] == ResultSetMapping.NotLastInResultSet)
                {
                    expectedRowsAffected++;
                }

                ThrowAggregateUpdateConcurrencyException(resultSetIndex, expectedRowsAffected, rowsAffected);
            }

            var tableModification = ModificationCommands[
                ResultsPositionalMappingEnabled?.Length > resultSetIndex && ResultsPositionalMappingEnabled[resultSetIndex]
                    ? startResultSetIndex + reader.DbDataReader.GetInt32(reader.DbDataReader.FieldCount - 1)
                    : resultSetIndex];

            Check.DebugAssert(tableModification.RequiresResultPropagation, "RequiresResultPropagation is false");

            var valueBufferFactory = CreateValueBufferFactory(tableModification.ColumnModifications);

            tableModification.PropagateResults(valueBufferFactory.Create(reader.DbDataReader));
            rowsAffected++;
        }while (++resultSetIndex < CommandResultSet.Count &&
                CommandResultSet[resultSetIndex - 1] == ResultSetMapping.NotLastInResultSet);

        return(resultSetIndex);
    }
            private bool BufferlessMoveNext(bool buffer)
            {
                try
                {
                    if (_dataReader == null)
                    {
                        _relationalQueryContext.Connection.Open();

                        var relationalCommand
                            = _shaperCommandContext
                              .GetRelationalCommand(_relationalQueryContext.ParameterValues);

                        _relationalQueryContext.Connection.RegisterBufferable(this);

                        _dataReader
                            = relationalCommand.ExecuteReader(
                                  _relationalQueryContext.Connection,
                                  _relationalQueryContext.ParameterValues);

                        _dbDataReader = _dataReader.DbDataReader;
                        _shaperCommandContext.NotifyReaderCreated(_dbDataReader);
                        _valueBufferFactory = _shaperCommandContext.ValueBufferFactory;
                    }

                    var hasNext = _dataReader.Read();

                    Current
                        = hasNext
                            ? _shaper.Shape(_relationalQueryContext, _valueBufferFactory.Create(_dbDataReader))
                            : default(T);

                    if (buffer)
                    {
                        BufferAll();
                    }

                    return(hasNext);
                }
                catch (Exception)
                {
                    _dataReader   = null;
                    _dbDataReader = null;

                    throw;
                }
            }
Beispiel #9
0
        protected override void Consume(RelationalDataReader reader)
        {
            var clickHouseReader = (ClickHouseDataReader)reader.DbDataReader;
            var commandIndex     = 0;

            try
            {
                while (true)
                {
                    // Find the next propagating command, if any
                    int nextPropagating;
                    for (nextPropagating = commandIndex;
                         nextPropagating < ModificationCommands.Count &&
                         !ModificationCommands[nextPropagating].RequiresResultPropagation;
                         nextPropagating++)
                    {
                        ;
                    }

                    if (nextPropagating == ModificationCommands.Count)
                    {
                        Debug.Assert(!clickHouseReader.NextResult(), "Expected less resultsets");
                        break;
                    }

                    // Propagate to results from the reader to the ModificationCommand

                    var modificationCommand = ModificationCommands[commandIndex++];

                    if (!reader.Read())
                    {
                        throw new DbUpdateConcurrencyException(
                                  RelationalStrings.UpdateConcurrencyException(1, 0),
                                  modificationCommand.Entries);
                    }

                    var valueBufferFactory = CreateValueBufferFactory(modificationCommand.ColumnModifications);
                    modificationCommand.PropagateResults(valueBufferFactory.Create(clickHouseReader));

                    clickHouseReader.NextResult();
                }
            }
            catch (DbUpdateException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new DbUpdateException(
                          RelationalStrings.UpdateStoreException,
                          ex,
                          ModificationCommands[commandIndex].Entries);
            }
        }
Beispiel #10
0
                public bool MoveNext()
                {
                    try
                    {
                        if (_dataReader == null)
                        {
                            _relationalQueryContext.Connection.Open();

                            try
                            {
                                var selectExpression = new ParameterValueBasedSelectExpressionOptimizer(
                                    _sqlExpressionFactory,
                                    _parameterNameGeneratorFactory)
                                                       .Optimize(_selectExpression, _relationalQueryContext.ParameterValues);

                                var relationalCommand = _querySqlGeneratorFactory.Create().GetCommand(selectExpression);

                                _dataReader
                                    = relationalCommand.ExecuteReader(
                                          _relationalQueryContext.Connection,
                                          _relationalQueryContext.ParameterValues,
                                          _relationalQueryContext.CommandLogger);

                                _resultCoordinator = new ResultCoordinator();
                            }
                            catch (Exception)
                            {
                                // If failure happens creating the data reader, then it won't be available to
                                // handle closing the connection, so do it explicitly here to preserve ref counting.
                                _relationalQueryContext.Connection.Close();

                                throw;
                            }
                        }

                        var hasNext = _resultCoordinator.HasNext ?? _dataReader.Read();
                        _resultCoordinator.HasNext = null;

                        Current
                            = hasNext
                                ? _shaper(_relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator)
                                : default;

                        return(hasNext);
                    }
                    catch (Exception exception)
                    {
                        _logger.QueryIterationFailed(_contextType, exception);

                        throw;
                    }
                }
                public bool MoveNext()
                {
                    if (_dataReader == null)
                    {
                        _relationalQueryContext.Connection.Open();

                        try
                        {
                            var relationalCommand = _querySqlGenerator
                                                    .GetCommand(
                                _selectExpression,
                                _relationalQueryContext.ParameterValues,
                                _relationalQueryContext.CommandLogger);

                            _dataReader
                                = relationalCommand.ExecuteReader(
                                      _relationalQueryContext.Connection,
                                      _relationalQueryContext.ParameterValues,
                                      _relationalQueryContext.CommandLogger);
                        }
                        catch (Exception exception)
                        {
                            _logger.QueryIterationFailed(_contextType, exception);
                            // If failure happens creating the data reader, then it won't be available to
                            // handle closing the connection, so do it explicitly here to preserve ref counting.
                            _relationalQueryContext.Connection.Close();

                            throw;
                        }
                    }

                    try
                    {
                        var hasNext = _dataReader.Read();

                        Current
                            = hasNext
                            ? _shaper(_relationalQueryContext, _dataReader.DbDataReader)
                            : default;

                        return(hasNext);
                    }
                    catch (Exception exception)
                    {
                        _logger.QueryIterationFailed(_contextType, exception);

                        throw;
                    }
                }
            public void BufferAll()
            {
                if (_buffer == null &&
                    _dataReader != null)
                {
                    _buffer = new Queue <ValueBuffer>();

                    using (_dataReader)
                    {
                        while (_dataReader.Read())
                        {
                            _buffer.Enqueue(_valueBufferFactory.Create(_dbDataReader));
                        }
                    }

                    _relationalQueryContext.Connection?.Close();

                    _dataReader   = null;
                    _dbDataReader = null;
                }
            }
            public bool MoveNext()
            {
                try
                {
                    using (_relationalQueryContext.ConcurrencyDetector.EnterCriticalSection())
                    {
                        if (_dataReader == null)
                        {
                            if (_executionStrategy == null)
                            {
                                _executionStrategy = _relationalQueryContext.ExecutionStrategyFactory.Create();
                            }

                            _executionStrategy.Execute(true, InitializeReader, null);
                        }

                        var hasNext = _dataReader.Read();
                        Current = default;

                        if (hasNext)
                        {
                            _resultCoordinator.ResultContext.Values = null;
                            _shaper(
                                _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _resultCoordinator);
                            _relatedDataLoaders?.Invoke(_relationalQueryContext, _executionStrategy, _resultCoordinator);
                            Current = _shaper(
                                _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _resultCoordinator);
                        }

                        return(hasNext);
                    }
                }
                catch (Exception exception)
                {
                    _queryLogger.QueryIterationFailed(_contextType, exception);

                    throw;
                }
            }
Beispiel #14
0
        protected override async Task ConsumeAsync(
            RelationalDataReader relationalReader, CancellationToken cancellationToken = default)
        {
            var commandPosition = 0;
            int rowsAffected;

            try
            {
                do
                {
                    while (commandPosition < CommandResultSet.Count &&
                           CommandResultSet[commandPosition] == ResultSetMapping.NoResultSet)
                    {
                        commandPosition++;
                    }

                    if (commandPosition < CommandResultSet.Count)
                    {
                        if (ModificationCommands[commandPosition].RequiresResultPropagation)
                        {
                            rowsAffected = 0;
                            do
                            {
                                var tableModification = ModificationCommands[commandPosition];
                                if (!await relationalReader.ReadAsync(cancellationToken))
                                {
                                    throw new DbUpdateConcurrencyException(
                                              RelationalStrings.UpdateConcurrencyException(
                                                  ModificationCommands.Count(m => m.RequiresResultPropagation), rowsAffected),
                                              ModificationCommands[commandPosition].Entries);
                                }

                                var valueBufferFactory = CreateValueBufferFactory(tableModification.ColumnModifications);
                                tableModification.PropagateResults(valueBufferFactory.Create(relationalReader.DbDataReader));
                                rowsAffected++;
                            }while (++commandPosition < CommandResultSet.Count &&
                                    CommandResultSet[commandPosition - 1] == ResultSetMapping.NotLastInResultSet);
                        }
                        else
                        {
                            var expectedRowsAffected = 1;
                            while (++commandPosition < CommandResultSet.Count &&
                                   CommandResultSet[commandPosition - 1] == ResultSetMapping.NotLastInResultSet)
                            {
                                expectedRowsAffected++;
                            }

                            if (relationalReader.Read())
                            {
                                rowsAffected = relationalReader.DbDataReader.GetInt32(0);
                                if (rowsAffected != expectedRowsAffected)
                                {
                                    throw new DbUpdateConcurrencyException(
                                              RelationalStrings.UpdateConcurrencyException(expectedRowsAffected, rowsAffected),
                                              ModificationCommands[commandPosition - 1].Entries);
                                }
                            }
                            else
                            {
                                throw new DbUpdateConcurrencyException(
                                          RelationalStrings.UpdateConcurrencyException(1, 0),
                                          ModificationCommands[commandPosition - 1].Entries);
                            }
                        }
                    }
                }while (commandPosition < CommandResultSet.Count &&
                        await relationalReader.DbDataReader.NextResultAsync(cancellationToken));
            }
            catch (DbUpdateException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new DbUpdateException(
                          RelationalStrings.UpdateStoreException,
                          ex, ModificationCommands[commandPosition].Entries);
            }
        }
    protected override void Consume(RelationalDataReader reader)
    {
        var npgsqlReader = (NpgsqlDataReader)reader.DbDataReader;

#pragma warning disable 618
        Debug.Assert(npgsqlReader.Statements.Count == ModificationCommands.Count, $"Reader has {npgsqlReader.Statements.Count} statements, expected {ModificationCommands.Count}");
#pragma warning restore 618

        var commandIndex = 0;

        try
        {
            while (true)
            {
                // Find the next propagating command, if any
                int nextPropagating;
                for (nextPropagating = commandIndex;
                     nextPropagating < ModificationCommands.Count &&
                     !ModificationCommands[nextPropagating].RequiresResultPropagation;
                     nextPropagating++)
                {
                }

                // Go over all non-propagating commands before the next propagating one,
                // make sure they executed
                for (; commandIndex < nextPropagating; commandIndex++)
                {
#pragma warning disable 618
                    if (npgsqlReader.Statements[commandIndex].Rows == 0)
                    {
                        throw new DbUpdateConcurrencyException(
                                  RelationalStrings.UpdateConcurrencyException(1, 0),
                                  ModificationCommands[commandIndex].Entries
                                  );
                    }
#pragma warning restore 618
                }

                if (nextPropagating == ModificationCommands.Count)
                {
                    Debug.Assert(!npgsqlReader.NextResult(), "Expected less resultsets");
                    break;
                }

                // Propagate to results from the reader to the ModificationCommand

                var modificationCommand = ModificationCommands[commandIndex++];

                if (!reader.Read())
                {
                    throw new DbUpdateConcurrencyException(
                              RelationalStrings.UpdateConcurrencyException(1, 0),
                              modificationCommand.Entries);
                }

                var valueBufferFactory = CreateValueBufferFactory(modificationCommand.ColumnModifications);
                modificationCommand.PropagateResults(valueBufferFactory.Create(npgsqlReader));

                npgsqlReader.NextResult();
            }
        }
        catch (DbUpdateException)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw new DbUpdateException(
                      RelationalStrings.UpdateStoreException,
                      ex,
                      ModificationCommands[commandIndex].Entries);
        }
    }
                public bool MoveNext()
                {
                    try
                    {
                        using (_relationalQueryContext.ConcurrencyDetector.EnterCriticalSection())
                        {
                            if (_dataReader == null)
                            {
                                var relationalCommand = _relationalCommandCache.GetRelationalCommand(
                                    _relationalQueryContext.ParameterValues);

                                _dataReader
                                    = relationalCommand.ExecuteReader(
                                          new RelationalCommandParameterObject(
                                              _relationalQueryContext.Connection,
                                              _relationalQueryContext.ParameterValues,
                                              _relationalQueryContext.Context,
                                              _relationalQueryContext.CommandLogger));

                                // Non-Composed FromSql
                                if (_columnNames != null)
                                {
                                    var readerColumns = Enumerable.Range(0, _dataReader.DbDataReader.FieldCount)
                                                        .ToDictionary(i => _dataReader.DbDataReader.GetName(i), i => i, StringComparer.OrdinalIgnoreCase);

                                    _indexMap = new int[_columnNames.Count];
                                    for (var i = 0; i < _columnNames.Count; i++)
                                    {
                                        var columnName = _columnNames[i];
                                        if (!readerColumns.TryGetValue(columnName, out var ordinal))
                                        {
                                            throw new InvalidOperationException(RelationalStrings.FromSqlMissingColumn(columnName));
                                        }

                                        _indexMap[i] = ordinal;
                                    }
                                }
                                else
                                {
                                    _indexMap = null;
                                }

                                _resultCoordinator = new ResultCoordinator();
                            }

                            var hasNext = _resultCoordinator.HasNext ?? _dataReader.Read();
                            Current = default;

                            if (hasNext)
                            {
                                while (true)
                                {
                                    _resultCoordinator.ResultReady = true;
                                    _resultCoordinator.HasNext     = null;
                                    Current = _shaper(
                                        _relationalQueryContext, _dataReader.DbDataReader,
                                        _resultCoordinator.ResultContext, _indexMap, _resultCoordinator);
                                    if (_resultCoordinator.ResultReady)
                                    {
                                        // We generated a result so null out previously stored values
                                        _resultCoordinator.ResultContext.Values = null;
                                        break;
                                    }

                                    if (!_dataReader.Read())
                                    {
                                        _resultCoordinator.HasNext = false;
                                        // Enumeration has ended, materialize last element
                                        _resultCoordinator.ResultReady = true;
                                        Current = _shaper(
                                            _relationalQueryContext, _dataReader.DbDataReader,
                                            _resultCoordinator.ResultContext, _indexMap, _resultCoordinator);

                                        break;
                                    }
                                }
                            }

                            return(hasNext);
                        }
                    }
                    catch (Exception exception)
                    {
                        _logger.QueryIterationFailed(_contextType, exception);

                        throw;
                    }
                }
Beispiel #17
0
        /// <summary>
        /// 恢复
        /// </summary>
        /// <param name="relationalReader">关系DataReader</param>
        protected override void Consume(RelationalDataReader relationalReader)
        {
            int commandPosition = 0;
            int rowsAffected    = 0;

            try
            {
                if (Check.IsTraceEnabled(m_oracleLogger?.Logger))
                {
                    Trace <DbLoggerCategory.Update> .Write(m_oracleLogger, LogLevel.Trace, OracleTraceTag.Entry, OracleTraceClassName.OracleModificationCommandBatch, OracleTraceFuncName.Consume);
                }

                while (true)
                {
                    if (commandPosition < CommandResultSet.Count && CommandResultSet[commandPosition] == ResultSetMapping.NoResultSet)
                    {
                        commandPosition++;
                    }
                    else
                    {
                        if (commandPosition < CommandResultSet.Count)
                        {
                            if (ModificationCommands[commandPosition].RequiresResultPropagation)
                            {
                                rowsAffected = 0;
                                do
                                {
                                    ModificationCommand modificationCommand = ModificationCommands[commandPosition];
                                    if (!relationalReader.Read())
                                    {
                                        throw new DbUpdateConcurrencyException(RelationalStrings.UpdateConcurrencyException(ModificationCommands.Count((ModificationCommand m) => m.RequiresResultPropagation), rowsAffected), ModificationCommands[commandPosition].Entries);
                                    }
                                    IRelationalValueBufferFactory relationalValueBufferFactory = CreateValueBufferFactory(modificationCommand.ColumnModifications);
                                    modificationCommand.PropagateResults(relationalValueBufferFactory.Create(relationalReader.DbDataReader));
                                    rowsAffected++;
                                    foreach (ColumnModification columnModification in modificationCommand.ColumnModifications)
                                    {
                                        if (Check.IsTraceEnabled(m_oracleLogger?.Logger))
                                        {
                                            Trace <DbLoggerCategory.Update> .Write(m_oracleLogger, LogLevel.Trace, OracleTraceTag.SQL, OracleTraceClassName.OracleModificationCommandBatch, OracleTraceFuncName.Consume, $"Column Name: {columnModification.ColumnName}");
                                        }
                                    }
                                }while (++commandPosition < CommandResultSet.Count && CommandResultSet[commandPosition - 1] == ResultSetMapping.NotLastInResultSet);
                            }
                            else
                            {
                                int expectedRowsAffected = 1;
                                while (++commandPosition < CommandResultSet.Count && CommandResultSet[commandPosition - 1] == ResultSetMapping.NotLastInResultSet)
                                {
                                    expectedRowsAffected++;
                                }
                                if (!relationalReader.Read())
                                {
                                    break;
                                }
                                rowsAffected = relationalReader.DbDataReader.GetInt32(0);
                                if (rowsAffected != expectedRowsAffected)
                                {
                                    throw new DbUpdateConcurrencyException(RelationalStrings.UpdateConcurrencyException(expectedRowsAffected, rowsAffected), ModificationCommands[commandPosition - 1].Entries);
                                }
                            }
                        }
                        if (commandPosition >= CommandResultSet.Count || !relationalReader.DbDataReader.NextResult())
                        {
                            return;
                        }
                    }
                }
                throw new DbUpdateConcurrencyException(RelationalStrings.UpdateConcurrencyException(1, 0), ModificationCommands[commandPosition - 1].Entries);
            }
            catch (DbUpdateException dbEx)
            {
                if (Check.IsErrorEnabled(m_oracleLogger?.Logger))
                {
                    Trace <DbLoggerCategory.Update> .Write(m_oracleLogger, LogLevel.Error, OracleTraceTag.Error, OracleTraceClassName.OracleModificationCommandBatch, OracleTraceFuncName.Consume, dbEx.ToString());
                }
                throw;
            }
            catch (Exception ex)
            {
                if (Check.IsErrorEnabled(m_oracleLogger?.Logger))
                {
                    Trace <DbLoggerCategory.Update> .Write(m_oracleLogger, LogLevel.Error, OracleTraceTag.Error, OracleTraceClassName.OracleModificationCommandBatch, OracleTraceFuncName.Consume, ex.ToString());
                }
                throw new DbUpdateException(RelationalStrings.UpdateStoreException, ex, ModificationCommands[commandPosition - 1].Entries);
            }
        }
Beispiel #18
0
        /// <summary>
        /// 异步恢复
        /// </summary>
        /// <param name="relationalReader">关系DataReader</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        protected override async Task ConsumeAsync(RelationalDataReader relationalReader, CancellationToken cancellationToken = default(CancellationToken))
        {
            int commandPosition = 0;

            try
            {
                if (Check.IsTraceEnabled(m_oracleLogger?.Logger))
                {
                    Trace <DbLoggerCategory.Update> .Write(m_oracleLogger, LogLevel.Trace, OracleTraceTag.Entry, OracleTraceClassName.OracleModificationCommandBatch, OracleTraceFuncName.ConsumeAsync);
                }

                while (true)
                {
                    if (commandPosition < CommandResultSet.Count && CommandResultSet[commandPosition] == ResultSetMapping.NoResultSet)
                    {
                        commandPosition++;
                    }
                    else
                    {
                        if (commandPosition < CommandResultSet.Count)
                        {
                            if (ModificationCommands[commandPosition].RequiresResultPropagation)
                            {
                                int rowsAffected = 0;
                                int num          = 0;
                                do
                                {
                                    ModificationCommand tableModification = ModificationCommands[commandPosition];
                                    if (!(await relationalReader.ReadAsync(cancellationToken)))
                                    {
                                        throw new DbUpdateConcurrencyException(RelationalStrings.UpdateConcurrencyException(ModificationCommands.Count((ModificationCommand m) => m.RequiresResultPropagation), rowsAffected), ModificationCommands[commandPosition].Entries);
                                    }
                                    IRelationalValueBufferFactory relationalValueBufferFactory = CreateValueBufferFactory(tableModification.ColumnModifications);
                                    tableModification.PropagateResults(relationalValueBufferFactory.Create(relationalReader.DbDataReader));
                                    rowsAffected++;
                                    num             = commandPosition + 1;
                                    commandPosition = num;
                                }while (num < CommandResultSet.Count && CommandResultSet[commandPosition - 1] == ResultSetMapping.NotLastInResultSet);
                            }
                            else
                            {
                                int expectedRowsAffected = 1;
                                while (true)
                                {
                                    int num = commandPosition + 1;
                                    commandPosition = num;
                                    if (num >= CommandResultSet.Count || CommandResultSet[commandPosition - 1] != ResultSetMapping.NotLastInResultSet)
                                    {
                                        break;
                                    }
                                    expectedRowsAffected++;
                                }
                                if (!relationalReader.Read())
                                {
                                    break;
                                }
                                int rowsAffected = relationalReader.DbDataReader.GetInt32(0);
                                if (rowsAffected != expectedRowsAffected)
                                {
                                    throw new DbUpdateConcurrencyException(RelationalStrings.UpdateConcurrencyException(expectedRowsAffected, rowsAffected), ModificationCommands[commandPosition - 1].Entries);
                                }
                            }
                        }
                        bool flag = commandPosition < CommandResultSet.Count;
                        if (flag)
                        {
                            flag = await relationalReader.DbDataReader.NextResultAsync(cancellationToken);
                        }
                        if (!flag)
                        {
                            return;
                        }
                    }
                }
                throw new DbUpdateConcurrencyException(RelationalStrings.UpdateConcurrencyException(1, 0), ModificationCommands[commandPosition - 1].Entries);
            }
            catch (DbUpdateException dbEx)
            {
                if (Check.IsErrorEnabled(m_oracleLogger?.Logger))
                {
                    Trace <DbLoggerCategory.Update> .Write(m_oracleLogger, LogLevel.Error, OracleTraceTag.Error, OracleTraceClassName.OracleModificationCommandBatch, OracleTraceFuncName.ConsumeAsync, dbEx.ToString());
                }
                throw;
            }
            catch (Exception ex)
            {
                if (Check.IsErrorEnabled(m_oracleLogger?.Logger))
                {
                    Trace <DbLoggerCategory.Update> .Write(m_oracleLogger, LogLevel.Error, OracleTraceTag.Error, OracleTraceClassName.OracleModificationCommandBatch, OracleTraceFuncName.ConsumeAsync, ex.ToString());
                }
                throw new DbUpdateException(RelationalStrings.UpdateStoreException, ex, ModificationCommands[commandPosition].Entries);
            }
        }
Beispiel #19
0
                public bool MoveNext()
                {
                    try
                    {
                        if (_dataReader == null)
                        {
                            var selectExpression = new ParameterValueBasedSelectExpressionOptimizer(
                                _sqlExpressionFactory,
                                _parameterNameGeneratorFactory)
                                                   .Optimize(_selectExpression, _relationalQueryContext.ParameterValues);

                            var relationalCommand = _querySqlGeneratorFactory.Create().GetCommand(selectExpression);

                            _dataReader
                                = relationalCommand.ExecuteReader(
                                      new RelationalCommandParameterObject(
                                          _relationalQueryContext.Connection,
                                          _relationalQueryContext.ParameterValues,
                                          _relationalQueryContext.Context,
                                          _relationalQueryContext.CommandLogger));

                            if (selectExpression.IsNonComposedFromSql())
                            {
                                var projection    = _selectExpression.Projection.ToList();
                                var readerColumns = Enumerable.Range(0, _dataReader.DbDataReader.FieldCount)
                                                    .ToDictionary(i => _dataReader.DbDataReader.GetName(i), i => i, StringComparer.OrdinalIgnoreCase);

                                _indexMap = new int[projection.Count];
                                for (var i = 0; i < projection.Count; i++)
                                {
                                    if (projection[i].Expression is ColumnExpression columnExpression)
                                    {
                                        var columnName = columnExpression.Name;
                                        if (columnName != null)
                                        {
                                            if (!readerColumns.TryGetValue(columnName, out var ordinal))
                                            {
                                                throw new InvalidOperationException(RelationalStrings.FromSqlMissingColumn(columnName));
                                            }

                                            _indexMap[i] = ordinal;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                _indexMap = null;
                            }

                            _resultCoordinator = new ResultCoordinator();
                        }

                        var hasNext = _resultCoordinator.HasNext ?? _dataReader.Read();
                        Current = default;

                        if (hasNext)
                        {
                            while (true)
                            {
                                _resultCoordinator.ResultReady = true;
                                _resultCoordinator.HasNext     = null;
                                Current = _shaper(_relationalQueryContext, _dataReader.DbDataReader, Current, _indexMap, _resultCoordinator);
                                if (_resultCoordinator.ResultReady)
                                {
                                    break;
                                }

                                if (!_dataReader.Read())
                                {
                                    _resultCoordinator.HasNext = false;

                                    break;
                                }
                            }
                        }

                        return(hasNext);
                    }
                    catch (Exception exception)
                    {
                        _logger.QueryIterationFailed(_contextType, exception);

                        throw;
                    }
                }
                public bool MoveNext()
                {
                    try
                    {
                        if (_dataReader == null)
                        {
                            _relationalQueryContext.Connection.Open();

                            try
                            {
                                var projection = _selectExpression.Projection.ToList();

                                var selectExpression = new ParameterValueBasedSelectExpressionOptimizer(
                                    _sqlExpressionFactory,
                                    _parameterNameGeneratorFactory)
                                                       .Optimize(_selectExpression, _relationalQueryContext.ParameterValues);

                                var relationalCommand = _querySqlGeneratorFactory.Create().GetCommand(selectExpression);

                                _dataReader
                                    = relationalCommand.ExecuteReader(
                                          _relationalQueryContext.Connection,
                                          _relationalQueryContext.ParameterValues,
                                          _relationalQueryContext.CommandLogger);

                                var readerColumns = Enumerable.Range(0, _dataReader.DbDataReader.FieldCount)
                                                    .Select(
                                    i => new
                                {
                                    Name    = _dataReader.DbDataReader.GetName(i),
                                    Ordinal = i
                                }).ToList();

                                _indexMap = new int[projection.Count];

                                for (var i = 0; i < projection.Count; i++)
                                {
                                    if (projection[i].Expression is ColumnExpression columnExpression)
                                    {
                                        var columnName = columnExpression.Name;

                                        if (columnName != null)
                                        {
                                            var readerColumn
                                                = readerColumns.SingleOrDefault(
                                                      c =>
                                                      string.Equals(columnName, c.Name, StringComparison.OrdinalIgnoreCase));

                                            if (readerColumn == null)
                                            {
                                                throw new InvalidOperationException(RelationalStrings.FromSqlMissingColumn(columnName));
                                            }

                                            _indexMap[i] = readerColumn.Ordinal;
                                        }
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                // If failure happens creating the data reader, then it won't be available to
                                // handle closing the connection, so do it explicitly here to preserve ref counting.
                                _relationalQueryContext.Connection.Close();

                                throw;
                            }
                        }

                        var hasNext = _dataReader.Read();

                        Current
                            = hasNext
                                ? _shaper(_relationalQueryContext, _dataReader.DbDataReader, _indexMap)
                                : default;

                        return(hasNext);
                    }
                    catch (Exception exception)
                    {
                        _logger.QueryIterationFailed(_contextType, exception);

                        throw;
                    }
                }