Module: IMW::Schemes::SQL::Base

Defined in:
lib/imw/schemes/sql.rb

Overview

A base implementation of a connection to a relational database.

The Base#extended method will examine the scheme of an object extended with this module and choose a more specific database adaptor module to extend with as well.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(obj) ⇒ Object

When an IMW::Resource is extended use URI’s scheme to choose which other module inside IMW::Schemes::SQL to extend with.



26
27
28
29
30
31
32
# File 'lib/imw/schemes/sql.rb', line 26

def self.extended obj
  case obj.scheme
  when 'mysql'      then obj.extend(IMW::Schemes::SQL::MySQL)
  when 'postgresql' then obj.extend(IMW::Schemes::SQL::PostgreSQL)
  else raise IMW::ArgumentError.new("Unknown database type: #{obj.scheme}")
  end
end

Instance Method Details

#connectionDBI::DatabaseHandle

The (cached) database connection for this resource.

Returns:

  • (DBI::DatabaseHandle)


52
53
54
# File 'lib/imw/schemes/sql.rb', line 52

def connection
  @connection ||= DBI.connect("#{dbi_module}:#{database}:#{host}", user, password)
end

#databaseString

For an SQL connection the database will be the same as the path.

Returns:



38
39
40
# File 'lib/imw/schemes/sql.rb', line 38

def database
  @database ||= path.tr('/','')
end

#execute(*query_string_parts) {|DBI::Row| ... } ⇒ DBI::StatementHandle

Execute the (joined) query_string_parts using this resource’s cached connection.

If passed a block, yield each row of the result set to the block.

Parameters:

Yields:

  • (DBI::Row)

Returns:

  • (DBI::StatementHandle)


84
85
86
87
88
89
# File 'lib/imw/schemes/sql.rb', line 84

def execute *query_string_parts, &block
  query = query_string_parts.join(' ')
  IMW.announce_if_verbose "Querying #{self}: #{query}"
  statement = connection.execute(query)
  block_given? ? statement.fetch(&block) : statement
end

#passwordString

Return the password associated with user’s account on the given database.

Returns:



60
61
62
# File 'lib/imw/schemes/sql.rb', line 60

def password
  @password ||= resource_options[:password]
end

#tablesArray<String>

Return an array of the table names in the current database.

Returns:



67
68
69
70
71
72
73
# File 'lib/imw/schemes/sql.rb', line 67

def tables
  returning([]) do |table_names|
    execute("SHOW TABLES") do |row|
      table_names << row.first
    end
  end
end