Module: Stipa::Database

Defined in:
lib/stipa/database.rb

Overview

Database connection manager.

Usage:

require 'stipa/database'

Stipa::Database.connect!  # reads DATABASE_URL from environment
DB = Stipa::Database.connection

Environment variables:

DATABASE_URL      — connection string (required)
DATABASE_POOL     — max connections (default: 5)

Connection string examples:

postgres://user:pass@localhost:5432/myapp
mysql2://user:pass@localhost:3306/myapp
sqlite://db/development.db

Class Method Summary collapse

Class Method Details

.connect!Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/stipa/database.rb', line 26

def connect!
  return @connection if @connection

  @connection = Sequel.connect(
    ENV.fetch('DATABASE_URL'),
    max_connections: Integer(ENV.fetch('DATABASE_POOL', '5')),
    connect_timeout: 5,
    test: true,
    keep_reference: false,
    after_connect: lambda do |connection|
      connection.exec("SET TIME ZONE 'UTC'") if connection.respond_to?(:exec)
    end
  )

  configure_connection!
  Sequel::Model.db = @connection
  @connection
rescue KeyError => e
  raise "Missing database configuration: #{e.message}"
rescue ArgumentError => e
  raise "Invalid database configuration: #{e.message}"
end

.connected?Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/stipa/database.rb', line 53

def connected?
  !@connection.nil?
end

.connectionObject



49
50
51
# File 'lib/stipa/database.rb', line 49

def connection
  @connection || raise('Database.connect! must be called first')
end

.disconnect!Object



63
64
65
66
# File 'lib/stipa/database.rb', line 63

def disconnect!
  @connection&.disconnect
  @connection = nil
end

.healthy?Boolean

Returns:

  • (Boolean)


57
58
59
60
61
# File 'lib/stipa/database.rb', line 57

def healthy?
  connection.get(Sequel.lit('SELECT 1')) == 1
rescue Sequel::Error
  false
end

.transaction(&block) ⇒ Object



68
69
70
# File 'lib/stipa/database.rb', line 68

def transaction(&block)
  connection.transaction(&block)
end