/
connection.cr
39 lines (36 loc) · 1.58 KB
/
connection.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
module Marten
module DB
abstract class Model
module Connection
macro included
extend Marten::DB::Model::Connection::ClassMethods
end
module ClassMethods
# Returns the database connection to use for the considered model.
def connection
DB::Connection.for(db_table)
end
# Allows to run the underlying block in a database transaction.
#
# A optional database alias can be specified in order to define the database connection to use in the context
# of the transaction (otherwise it defaults to the default connection). If the passed database alias doesn't
# correspond to any defined connections, a `Marten::DB::Errors::UnknownConnection` error will be raised.
def transaction(using : Nil | String | Symbol = nil, &)
conn = using.nil? ? connection : DB::Connection.get(using.to_s)
conn.transaction do
yield
end
end
end
# Allows to run the underlying block in a database transaction.
#
# A optional database alias can be specified in order to define the database connection to use in the context of
# the transaction (otherwise it defaults to the default connection). If the passed database alias doesn't
# correspond to any defined connections, a `Marten::DB::Errors::UnknownConnection` error will be raised.
def transaction(using : Nil | String | Symbol = nil, &block)
self.class.transaction(using, &block)
end
end
end
end
end