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)


64
65
66
# File 'lib/imw/schemes/sql.rb', line 64

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:

  • (String)


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:

  • query_string_parts (Array<String>)

Yields:

  • (DBI::Row)

Returns:

  • (DBI::StatementHandle)


96
97
98
99
100
101
# File 'lib/imw/schemes/sql.rb', line 96

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

#external_summaryHash

Return a summary of this database.

Purposefully does not call super.

Returns:

  • (Hash)


54
55
56
57
58
59
# File 'lib/imw/schemes/sql.rb', line 54

def external_summary
  {
    :uri      => uri.to_s,
    :database => database
  }
end

#passwordString

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

Returns:

  • (String)


72
73
74
# File 'lib/imw/schemes/sql.rb', line 72

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

#tablesArray<String>

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

Returns:

  • (Array<String>)


79
80
81
82
83
84
85
# File 'lib/imw/schemes/sql.rb', line 79

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