Module: Desiru::Persistence::Database

Defined in:
lib/desiru/persistence/database.rb

Overview

Database connection and migration management

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.connectionObject (readonly)

Returns the value of attribute connection.



11
12
13
# File 'lib/desiru/persistence/database.rb', line 11

def connection
  @connection
end

Class Method Details

.connect(database_url = nil) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/desiru/persistence/database.rb', line 13

def connect(database_url = nil)
  url = database_url || Persistence.database_url

  @connection = Sequel.connect(
    url,
    logger: logger,
    max_connections: max_connections
  )

  # Enable foreign keys for SQLite
  @connection.run('PRAGMA foreign_keys = ON') if sqlite?

  @connection
end

.disconnectObject



28
29
30
31
# File 'lib/desiru/persistence/database.rb', line 28

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

.migrate!Object



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/desiru/persistence/database.rb', line 33

def migrate!
  raise 'Not connected to database' unless @connection

  Sequel.extension :migration
  migrations_path = File.expand_path('../../../db/migrations', __dir__)
  Sequel::Migrator.run(@connection, migrations_path)

  # Initialize persistence layer after migrations
  require_relative 'setup'
  Setup.initialize!(@connection)
end

.transactionObject



45
46
47
48
49
# File 'lib/desiru/persistence/database.rb', line 45

def transaction(&)
  raise 'Not connected to database' unless @connection

  @connection.transaction(&)
end