require 'sequelizer'

DB = Object.new.extend(Sequelizer).db unless defined?(DB)
DB.run("use #{DB.opts[:database]}") if DB.opts[:adapter] =~ /(impala|hive)/


if %w(omopv4 omopv4_plus).include?(ENV['DATA_MODEL']) && !DB.table_exists?(:source_to_concept_map)
  $stderr.puts <<END
The source_to_concept_map table doesn't exist in this database,
so it appears this doesn't include the necessary OMOP vocabulary
data. Please review the README for how to setup the test database
with the vocabulary, which needs to be done before running tests.
END
  exit 1
end


require 'sequelizer'

DB = Object.new.extend(Sequelizer).db unless defined?(DB)
if DB.database_type == :impala
  # Make sure to issue USE statement for every new connection
  ac = DB.pool.after_connect
  DB.pool.after_connect = proc do |conn|
    DB.send(:log_connection_execute, conn, "USE #{DB.opts[:database]}")
    ac.call(conn) if ac
  end

  # Remove existing connnections, so that the next query will use a new connection
  # that the USE statement has been executed on
  DB.disconnect
end

if %w(omopv4 omopv4_plus).include?(ENV['DATA_MODEL']) && !DB.table_exists?(:source_to_concept_map)
  $stderr.puts <<END
The source_to_concept_map table doesn't exist in this database,
so it appears this doesn't include the necessary OMOP vocabulary
data. Please review the README for how to setup the test database
with the vocabulary, which needs to be done before running tests.
END
  exit 1
end


Fix USE statement execution when testing on impala/hive
Fix USE statement execution when testing on impala/hive

Issuing the USE query once via Datase#run only works if only one
connection is ever created.  While that may be true for the current
tests, this will bite us later if we ever have multithreaded access
in the tests or there is an accidental disconnect during testing.

Also, instead of checking for an adapter via a regexp, just check
the database_type.

This code does not handle Sequel's sharding support for
after_connect (where the proc takes a second argument).
