Class: Momomoto::Database

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/momomoto/database.rb

Overview

Momomoto Connection class

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDatabase

:nodoc:



32
33
34
35
# File 'lib/momomoto/database.rb', line 32

def initialize # :nodoc:
  @config = {}
  @connection = nil
end

Class Method Details

.config(conf) ⇒ Object

Eases the use of #config.



28
29
30
# File 'lib/momomoto/database.rb', line 28

def self.config( conf )
  instance.config( conf )
end

.connectObject

Eases the use of #connect.

Momomoto::Database.config( :database=>:test, :username => 'test' )
Momomoto::Database.connect
# configure and connect


57
58
59
# File 'lib/momomoto/database.rb', line 57

def self.connect
  instance.connect
end

.escape_bytea(input) ⇒ Object

escapes the given binary data input



222
223
224
# File 'lib/momomoto/database.rb', line 222

def self.escape_bytea( input )
  PGconn.escape_bytea( input )
end

.escape_string(input) ⇒ Object

escapes the given string input



217
218
219
# File 'lib/momomoto/database.rb', line 217

def self.escape_string( input )
  PGconn.escape( input )
end

.quote(input) ⇒ Object

quotes and escapes the given string input



197
198
199
# File 'lib/momomoto/database.rb', line 197

def self.quote( input )
  PGconn.quote( input )
end

.quote_bytea(input) ⇒ Object

quotes and escapes the given string input



212
213
214
# File 'lib/momomoto/database.rb', line 212

def self.quote_bytea( input )
  "E'#{PGconn.escape_bytea(input)}'"
end

.quote_ident(input) ⇒ Object

escapes the given identifier input



207
208
209
# File 'lib/momomoto/database.rb', line 207

def self.quote_ident( input )
  PGconn.quote_ident( input.to_s )
end

.quote_string(input) ⇒ Object

quotes and escapes the given string input



202
203
204
# File 'lib/momomoto/database.rb', line 202

def self.quote_string( input )
  "E" + PGconn.quote( input )
end

Instance Method Details

#beginObject

begin a transaction



163
164
165
166
# File 'lib/momomoto/database.rb', line 163

def begin
  @transaction_active = true
  execute( "BEGIN;" )
end

#commitObject

commit the current transaction

Raises:



183
184
185
186
187
# File 'lib/momomoto/database.rb', line 183

def commit
  raise Error if not @transaction_active
  execute( "COMMIT;" )
  @transaction_active = false
end

#config(config) ⇒ Object

establish connection to the database expects a hash with the following keys: host, port, database, username, password, pgoptions and pgtty



17
18
19
20
21
22
23
24
25
# File 'lib/momomoto/database.rb', line 17

def config( config )
  config ||= {}
  # we also accept String keys in the config hash
  config.each do | key, value |
    config[key.to_sym] = value unless key.kind_of?( Symbol )
    config[key.to_sym] = value.to_s if value.kind_of?(Symbol)
  end
  @config = config
end

#connectObject

Connects to database

Momomoto::Database.config( :database=>:test, :username => 'test' )
Momomoto::Database.connect
# configure and connect


41
42
43
44
45
46
47
48
49
50
# File 'lib/momomoto/database.rb', line 41

def connect
  @connection.close if @connection
  @transaction_active = false
  PGconn.translate_results = true
  @connection = PGconn.connect( @config[:host], @config[:port], @config[:pgoptions],
                  @config[:pgtty], @config[:database], @config[:username],
                  @config[:password])
rescue => e
  raise CriticalError, "Connection to database failed: #{e}"
end

#disconnectObject

terminate this connection



62
63
64
65
66
# File 'lib/momomoto/database.rb', line 62

def disconnect
  @connection.close
  @connection = nil
  @transaction_active = false
end

#execute(sql) ⇒ Object

execute a query



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/momomoto/database.rb', line 69

def execute( sql ) # :nodoc:
  puts sql if Momomoto.debug
  @connection.query( sql )
 rescue => e
  if @connection.status == PGconn::CONNECTION_BAD
    begin
      connect
    rescue
    end
  end
  if Momomoto.verbose
    raise CriticalError.new( "#{e}: #{sql}", sql )
  else
    raise CriticalError.new( e.to_s, sql )
  end
  
end

#fetch_primary_keys(table_name, schema_name = nil) ⇒ Object

fetch columns which are primary key columns should work with any SQL2003 compliant DBMS



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/momomoto/database.rb', line 89

def fetch_primary_keys( table_name, schema_name = nil ) # :nodoc:
  pkeys = []
  conditions = {:table_name=>table_name, :constraint_type => 'PRIMARY KEY'}
  conditions[:table_schema] = schema_name if schema_name
  keys = Momomoto::Information_schema::Table_constraints.select( conditions )
  if keys.length != 0
    cols = Momomoto::Information_schema::Key_column_usage.select(
        { :table_name => keys[0].table_name,
          :table_schema => keys[0].table_schema,
          :constraint_name => keys[0].constraint_name,
          :constraint_schema => keys[0].constraint_schema } )
    cols.each do | key |
      pkeys << key.column_name.to_sym
    end
  end
  pkeys
end

#fetch_procedure_columns(procedure_name, schema_name = nil) ⇒ Object

fetches the result set columns of a stored procedure



152
153
154
155
156
157
158
159
160
# File 'lib/momomoto/database.rb', line 152

def fetch_procedure_columns( procedure_name, schema_name = nil ) # :nodoc:
  c = {}
  conditions = { :procedure_name => procedure_name }
  cols = Momomoto::Information_schema::Fetch_procedure_columns.call( conditions )
  cols.each do  | col |
    c[col.column_name.to_sym] = Momomoto::Datatype.const_get(col.data_type.gsub(' ','_').capitalize).new
  end
  c
end

#fetch_procedure_parameters(procedure_name, schema_name = nil) ⇒ Object

fetches parameters of a stored procedure



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/momomoto/database.rb', line 133

def fetch_procedure_parameters( procedure_name, schema_name = nil ) # :nodoc:
  p = []
  conditions = { :procedure_name => procedure_name }
  params = Momomoto::Information_schema::Fetch_procedure_parameters.call( conditions )
  params.each do  | param |
    p << { param.parameter_name.to_sym => Momomoto::Datatype.const_get(param.data_type.gsub(' ','_').capitalize).new }
  end
  # mark parameters of strict procedures as not null
  if Information_schema::Routines.select_single(:routine_name=>procedure_name).is_null_call == 'YES'
    p.each do | param |
      param[param.keys.first].instance_variable_set(:@not_null,true)
    end
  end
  p
 rescue => e
  raise Error, "Fetching procedure parameters for #{procedure_name} failed: #{e}"
end

#fetch_table_columns(table_name, schema_name = nil) ⇒ Object

fetch column definitions from database should work with any SQL2003 compliant DBMS

Raises:



120
121
122
123
124
125
126
127
128
129
130
# File 'lib/momomoto/database.rb', line 120

def fetch_table_columns( table_name, schema_name = nil ) # :nodoc:
  columns = {}
  conditions = { :table_name => table_name }
  conditions[:table_schema] = schema_name if schema_name
  cols = Momomoto::Information_schema::Columns.select( conditions )
  raise CriticalError, "Table without columns (#{table_name})" if cols.length < 1
  cols.each do  | col |
    columns[col.column_name.to_sym] = Momomoto::Datatype.const_get(col.data_type.gsub(' ','_').capitalize).new( col )
  end
  columns
end

#get_table_type(table_name, schema_name) ⇒ Object

get table type from database should work with any SQL2003 compliant DBMS



110
111
112
113
114
115
116
# File 'lib/momomoto/database.rb', line 110

def get_table_type( table_name, schema_name )
  begin
    Information_schema::Tables.select_single({:table_name=>table_name,:table_schema=>schema_name}).table_type
  rescue => e
    raise CriticalError, "Table #{table_name} does not exist. #{e.to_s}"
  end
end

#rollbackObject

roll the transaction back

Raises:



190
191
192
193
194
# File 'lib/momomoto/database.rb', line 190

def rollback
  raise Error if not @transaction_active
  execute( "ROLLBACK;" )
  @transaction_active = false
end

#transactionObject

executes the block and commits the transaction if a block is given otherwise simply starts a new transaction

Raises:



170
171
172
173
174
175
176
177
178
179
180
# File 'lib/momomoto/database.rb', line 170

def transaction
  raise Error, "Transaction active" if @transaction_active
  self.begin
  begin
    yield
  rescue Exception => e
    rollback
    raise e
  end
  commit
end