Class: Infrastructure::Storage::SQL

Inherits:
Object
  • Object
show all
Defined in:
lib/podrb/infrastructure/storage/sql.rb

Instance Method Summary collapse

Constructor Details

#initialize(db:) ⇒ SQL

Returns a new instance of SQL.



9
10
11
12
13
# File 'lib/podrb/infrastructure/storage/sql.rb', line 9

def initialize(db:)
  @conn = SQLite3::Database.new(db)
rescue SQLite3::CantOpenException
  raise Exceptions::CantStartConnection
end

Instance Method Details

#execute(sql) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/podrb/infrastructure/storage/sql.rb', line 15

def execute(sql)
  result = @conn.execute(sql)

  # SQLite3 #execute always return an Array when the
  # statement was successfully executed, and sometimes,
  # the array will be empty, which isn't useful for us.
  result.empty? ? true : result
rescue SQLite3::SQLException => exc
  raise Exceptions::WrongSyntax, exc.message
rescue SQLite3::ConstraintException => exc
  raise Exceptions::ConstraintViolation, exc.message
end

#query(sql) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/podrb/infrastructure/storage/sql.rb', line 28

def query(sql)
  parsed_result = []

  @conn.query(sql) do |result|
    result.each_hash do |row|
      parsed_result << Infrastructure::DTO.new(row.transform_keys(&:to_sym))
    end
  end

  parsed_result
rescue SQLite3::SQLException => exc
  raise Exceptions::WrongSyntax, exc.message
end

#transaction(mode = :deferred, &block) ⇒ Object



44
45
46
# File 'lib/podrb/infrastructure/storage/sql.rb', line 44

def transaction(mode = :deferred, &block)
  @conn.transaction(mode, &block)
end