Ruby предлагает несколько способов подключения к реляционным СУБД. Рассмотрим основные подходы и лучшие практики.
require 'pg'
begin
conn = PG.connect(
dbname: 'myapp_production',
user: 'app_user',
password: ENV['DB_PASSWORD'],
host: 'localhost',
port: 5432
)
# Выполнение запроса
result = conn.exec('SELECT * FROM users LIMIT 5')
result.each do |row|
puts row['email']
end
rescue PG::Error => e
puts "Ошибка подключения: #{e.message}"
ensure
conn&.close
end
require 'mysql2'
client = Mysql2::Client.new(
host: 'localhost',
username: 'root',
password: ENV['DB_PASSWORD'],
database: 'myapp_development',
reconnect: true # Автоматическое переподключение
)
results = client.query('SELECT * FROM products')
require 'active_record'
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: 'localhost',
database: 'myapp_dev',
username: 'dev_user',
password: 'password',
pool: 5,
timeout: 5000
)
class User < ActiveRecord::Base
end
User.all.each { |user| puts user.name }
require 'connection_pool'
require 'pg'
# Создаем пул из 5 соединений
DB_POOL = ConnectionPool.new(size: 5) do
PG.connect(dbname: 'myapp')
end
# Использование в потоке
DB_POOL.with do |conn|
conn.exec('UPDATE counters SET value = value + 1')
end
# PostgreSQL
ActiveRecord::Base.establish_connection(
'postgresql://user:password@localhost:5432/dbname?pool=5'
)
# MySQL
client = Mysql2::Client.new(
'mysql2://root:password@127.0.0.1:3306/dbname?reconnect=true'
)
development:
adapter: postgresql
encoding: unicode
database: myapp_development
pool: 5
username: dev_user
password: <%= ENV['DB_PASSWORD'] %>
host: localhost
require 'yaml'
db_config = YAML.load_file('config/database.yml')[ENV['RACK_ENV'] || 'development']
ActiveRecord::Base.establish_connection(db_config)
def with_db_connection(retries: 3)
attempts = 0
begin
yield
rescue PG::ConnectionBad, Mysql2::Error => e
attempts += 1
if attempts <= retries
sleep(2**attempts) # Exponential backoff
retry
end
raise "DB connection failed after #{retries} attempts: #{e.message}"
end
end
with_db_connection do
User.where(active: true).count
end
# Для PostgreSQL
conn.exec('SELECT 1')
# Для ActiveRecord
ActiveRecord::Base.connection.execute('SELECT 1')
begin
ActiveRecord::Base.connection.migration_context.current_version
true
rescue
false
end
class PrimaryDB < ActiveRecord::Base
self.abstract_class = true
establish_connection(:primary)
end
class ReplicaDB < ActiveRecord::Base
self.abstract_class = true
establish_connection(:replica)
end
class User < PrimaryDB; end
class ReadonlyUser < ReplicaDB; end
Для подключения к реляционным БД в Ruby доступны:
Основные рекомендации:
Для сложных сценариев рассмотрите: