Class: Sqlyzer::Db

Inherits:
Object
  • Object
show all
Defined in:
lib/sqlyzer/db.rb

Overview

Static class assuming connectivity and traffic to remote database server. It’s a pure ruby interface to Ruby DBI Api, offering some usage improvements.

Class Method Summary collapse

Class Method Details

.connect(api, hostname, database, username, password) ⇒ Object

This method will try to establish the connexion to remote database server from given api, hostname, database, username and password. Method call will assign handle class attribute.

Throws Sqlyzer::ConnexionError.



62
63
64
65
66
67
68
69
70
# File 'lib/sqlyzer/db.rb', line 62

def   Db.connect(api, hostname, database, username, password)
  begin
    @@handle = DBI.connect("DBI:#{api}:#{database}:#{hostname}", username, password)
  rescue DBI::Error
    raise Sqlyzer::ConnexionError, "#{username}@DBI:#{api}:#{database}:#{hostname}"
  else  
    true
  end
end

.do(request) ⇒ Object

Send given request to the database, doesn’t expect any return value. Mostly used with CREATE, ALTER, INSERT, UPDATE or DELETE Sql commands.



88
89
90
91
92
# File 'lib/sqlyzer/db.rb', line 88

def   Db.do(request)
  Db::_safe_request(request) { |r|
    @@handle.do r
  }
end

.query(request, &block) ⇒ Object

Alias to query_hash.



135
136
137
# File 'lib/sqlyzer/db.rb', line 135

def   Db.query(request, &block)
  query_hash(request, &block)
end

.query_array(request) ⇒ Object

Send given request to the database and expect a return value as an array from the remote server. Each tupple will be passed through a yield call, enabling user to process a request result just like Array#each. Mostly used with SELECT Sql command.

If no block is given, return do call value.



102
103
104
105
106
107
108
109
110
111
# File 'lib/sqlyzer/db.rb', line 102

def   Db.query_array(request)
  return Db::do(request) unless block_given?
  Db::_safe_request(request) { |r|
    sth = @@handle.execute r
    while row = sth.fetch
      yield row
    end
    sth.finish
  }
end

.query_hash(request) ⇒ Object

Send given request to the database and expect a return value as a Hash from the remote server. Each tupple will be passed through a yield call, enabling user to process a request result just like Hash#each. Mostly used with SELECT Sql command.

If no block is given, return do call value.



121
122
123
124
125
126
127
128
129
130
# File 'lib/sqlyzer/db.rb', line 121

def   Db.query_hash(request)
  return Db::do(request) unless block_given?
  Db::_safe_request(request) { |r|
    sth = @@handle.execute r
    while row = sth.fetch_hash
      yield row
    end
    sth.finish
  }
end

.tablesObject

Retreive the Array containing the table list in current database.

Throws Sqlyzer::NotConnectedError.



79
80
81
82
# File 'lib/sqlyzer/db.rb', line 79

def   Db.tables
  raise Sqlyzer::NotConnectedError unless @@handle
  @@handle.tables
end