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
  db_name = ''
  # postgresql shows current database
  db_name = connection&.db.to_s if connection.respond_to?(:db)
  # sqlite may expose a filename
  db_name = connection&.filename.to_s if db_name == '' && connection.respond_to?(:filename)
  # fall back to adapter class name
  db_name = connection.class.to_s if db_name == ''
  context = ElasticAPM::Span::Context.new(
    db: { statement: sql, type: 'sql', user: opts[:user] },
    service: {target: {type: subtype, name: db_name }},
    destination: { service: { resource: subtype } }
  )
  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