module ElasticAPM::Spies::SequelSpy::Ext

def log_connection_yield(sql, connection, args = nil, &block)

rubocop:disable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity
def log_connection_yield(sql, connection, args = nil, &block)
  unless ElasticAPM.current_transaction
    return super(sql, connection, args, &block)
  end
  subtype = database_type.to_s
  name =
    ElasticAPM::Spies::SequelSpy.summarizer.summarize sql
  context = ElasticAPM::Span::Context.new(
    db: { statement: sql, type: 'sql', user: opts[:user] },
    destination: { service: { name: subtype, resource: subtype, type: TYPE } }
  )
  span = ElasticAPM.start_span(
    name,
    TYPE,
    subtype: subtype,
    action: ACTION,
    context: context
  )
  super(sql, connection, args, &block).tap do |result|
    if /^(UPDATE|DELETE)/.match?(name)
      if connection.respond_to?(:changes)
        span.context.db.rows_affected = connection.changes
      elsif result.is_a?(Integer)
        span.context.db.rows_affected = result
      end
    end
  end
rescue
  span&.outcome = Span::Outcome::FAILURE
  raise
ensure
  span&.outcome ||= Span::Outcome::SUCCESS
  ElasticAPM.end_span
end