Class: Pod4::PgInterface

Inherits:
Interface show all
Includes:
SQLHelper
Defined in:
lib/pod4/pg_interface.rb

Overview

Pod4 Interface for requests on a SQL table via pg, the PostgresQL adapter.

If your DB table is one-one with your model, you shouldn’t need to override anything. Example:

class CustomerInterface < SwingShift::PgInterface
  set_schema :public    # optional
  set_table  :customer
  set_id_fld :id, autoincrement: true
end

Constant Summary

Constants inherited from Interface

Interface::ACTIONS

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from SQLHelper

#quoted_table

Methods included from Metaxing

#define_class_method, #metaclass

Constructor Details

#initialize(arg) ⇒ PgInterface

Initialise the interface by passing it a Pg connection hash, or a Pod4::ConnectionPool object.



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/pod4/pg_interface.rb', line 83

def initialize(arg)
  case arg
    when Hash
      @connection = ConnectionPool.new(interface: self.class)
      @connection.data_layer_options = arg

    when ConnectionPool
      @connection = arg

    else
      raise ArgumentError, "Bad argument"
  end

rescue => e
  handle_error(e)
end

Instance Attribute Details

#id_fldObject (readonly)

Returns the value of attribute id_fld.



30
31
32
# File 'lib/pod4/pg_interface.rb', line 30

def id_fld
  @id_fld
end

Class Method Details

.id_aiObject

Raises:



73
74
75
# File 'lib/pod4/pg_interface.rb', line 73

def id_ai
  raise Pod4Error, "You need to use set_id_fld to set the ID column"
end

.id_fldObject

Raises:



69
70
71
# File 'lib/pod4/pg_interface.rb', line 69

def id_fld
  raise Pod4Error, "You need to use set_id_fld to set the ID column"
end

.schemaObject



45
# File 'lib/pod4/pg_interface.rb', line 45

def schema; nil; end

.set_id_fld(idFld, opts = {}) ⇒ Object

Set the name of the column that holds the unique id for the table.



63
64
65
66
67
# File 'lib/pod4/pg_interface.rb', line 63

def set_id_fld(idFld, opts={})
  ai = opts.fetch(:autoincrement) { true }
  define_class_method(:id_fld) {idFld.to_s.to_sym}
  define_class_method(:id_ai)  {!!ai}
end

.set_schema(schema) ⇒ Object

Set the name of the schema. This is optional.



41
42
43
# File 'lib/pod4/pg_interface.rb', line 41

def set_schema(schema) 
  define_class_method(:schema) {schema.to_s.to_sym}
end

.set_table(table) ⇒ Object

Set the name of the database table



51
52
53
# File 'lib/pod4/pg_interface.rb', line 51

def set_table(table)
  define_class_method(:table) {table.to_s.to_sym}
end

.tableObject

Raises:



55
56
57
# File 'lib/pod4/pg_interface.rb', line 55

def table
  raise Pod4Error, "You need to use set_table to set the table name"
end

Instance Method Details

#_connectionObject

Expose @connection, for testing only.



335
336
337
# File 'lib/pod4/pg_interface.rb', line 335

def _connection
  @connection
end

#close_connection(conn) ⇒ Object

Close the connection to the database.

Pod4 itself doesn’t use this(?)



324
325
326
327
328
329
330
# File 'lib/pod4/pg_interface.rb', line 324

def close_connection(conn)
  Pod4.logger.info(__FILE__){ "Closing connection to DB" }
  conn.finish unless conn.nil?

rescue => e
  handle_error(e)
end

#create(record) ⇒ Object

Record is a hash or octothorpe of field: value

By a happy coincidence, insert returns the unique ID for the record, which is just what we want to do, too.



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/pod4/pg_interface.rb', line 122

def create(record)
  raise Octothorpe::BadHash if record.nil?
  ot = Octothorpe.new(record)

  if id_ai
    ot = ot.reject{|k,_| k == id_fld}
  else
    raise(ArgumentError, "ID field missing from record") if ot[id_fld].nil?
  end

  sql, vals = sql_insert(ot) 
  x = selectp(sql, *vals)
  x.first[id_fld]

rescue Octothorpe::BadHash
  raise ArgumentError, "Bad type for record parameter"
rescue
  handle_error $!
end

#delete(id) ⇒ Object

ID is whatever you set in the interface using set_id_fld



183
184
185
186
187
188
189
190
191
192
193
# File 'lib/pod4/pg_interface.rb', line 183

def delete(id)
  read_or_die(id)

  sql, vals = sql_delete(id_fld => id)
  executep(sql, *vals)

  self

rescue => e
  handle_error(e)
end

#execute(sql) ⇒ Object

Run SQL code on the server; return true or false for success or failure



274
275
276
277
278
279
280
281
282
283
# File 'lib/pod4/pg_interface.rb', line 274

def execute(sql)
  raise(ArgumentError, "Bad SQL parameter") unless sql.kind_of?(String)

  client = ensure_connection
  Pod4.logger.debug(__FILE__){ "execute: #{sql}" }
  client.exec(sql)

rescue => e
  handle_error(e)
end

#executep(sql, *vals) ⇒ Object

Run SQL code on the server as per execute() but with parameter insertion.

Placeholders in the SQL string should all be %s as per sql_helper methods. Values should be as returned by sql_helper methods.



291
292
293
294
295
296
297
298
299
300
# File 'lib/pod4/pg_interface.rb', line 291

def executep(sql, *vals)
  raise(ArgumentError, "Bad SQL parameter") unless sql.kind_of?(String)

  client = ensure_connection
  Pod4.logger.debug(__FILE__){ "parameterised execute: #{sql}" }
  client.exec_params( *parse_for_params(sql, vals) )

rescue => e
  handle_error(e)
end

#id_aiObject



103
# File 'lib/pod4/pg_interface.rb', line 103

def id_ai;  self.class.id_ai;  end

#list(selection = nil) ⇒ Object



105
106
107
108
109
110
111
112
113
114
# File 'lib/pod4/pg_interface.rb', line 105

def list(selection=nil)
  raise(ArgumentError, 'selection parameter is not a hash') \
    unless selection.nil? || selection.respond_to?(:keys)

  sql, vals = sql_select(nil, selection)
  selectp(sql, *vals) {|r| Octothorpe.new(r) }

rescue => e
  handle_error(e)
end

#new_connection(params) ⇒ Object

Open the connection to the database.

This is called from a Connection Object.



307
308
309
310
311
312
313
314
315
316
317
# File 'lib/pod4/pg_interface.rb', line 307

def new_connection(params)
  Pod4.logger.info(__FILE__){ "Connecting to DB" }

  client = PG.connect(params)
  raise DataBaseError, "Bad Connection" unless client.status == PG::CONNECTION_OK

  client

rescue => e
  handle_error(e)
end

#read(id) ⇒ Object

ID corresponds to whatever you set in set_id_fld



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/pod4/pg_interface.rb', line 145

def read(id)
  raise(ArgumentError, "ID parameter is nil") if id.nil?

  sql, vals = sql_select(nil, id_fld => id) 
  rows = selectp(sql, *vals)
  Octothorpe.new(rows.first)

rescue => e
  # Select has already wrapped the error in a Pod4Error, but in this case we want to catch
  # something. Ruby 2.0 doesn't define Exception.cause, but in that case, we do on Pod4Error.
  raise CantContinue, "That doesn't look like an ID" \
    if e.respond_to?(:cause) && e.cause.class == PG::InvalidTextRepresentation

  handle_error(e)
end

#schemaObject



100
# File 'lib/pod4/pg_interface.rb', line 100

def schema; self.class.schema; end

#select(sql) ⇒ Object

Run SQL code on the server. Return the results.

Will return an array of records, or you can use it in block mode, like this:

select("select * from customer") do |r|
  # r is a single record
end

The returned results will be an array of hashes (or if you passed a block, of whatever you returned from the block).



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/pod4/pg_interface.rb', line 207

def select(sql)
  raise(ArgumentError, "Bad SQL parameter") unless sql.kind_of?(String)

  client = ensure_connection
  Pod4.logger.debug(__FILE__){ "select: #{sql}" }

  rows = []
  client.exec(sql) do |query|
    oids = make_oid_hash(query)

    query.each do |r| 
      row = cast_row_fudge(r, oids)

      if block_given? 
        rows << yield(row)
      else
        rows << row
      end

    end
  end

  client.cancel 
  rows

rescue => e
  handle_error(e)
end

#selectp(sql, *vals) ⇒ Object

Run SQL code on the server as per select() but with parameter insertion.

Placeholders in the SQL string should all be %s as per sql_helper methods. Values should be as returned by sql_helper methods.



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/pod4/pg_interface.rb', line 242

def selectp(sql, *vals)
  raise(ArgumentError, "Bad SQL parameter") unless sql.kind_of?(String)

  client = ensure_connection
  Pod4.logger.debug(__FILE__){ "select: #{sql} #{vals.inspect}" }

  rows = []
  client.exec_params( *parse_for_params(sql, vals) ) do |query|
    oids = make_oid_hash(query)

    query.each do |r| 
      row = cast_row_fudge(r, oids)

      if block_given? 
        rows << yield(row)
      else
        rows << row
      end

    end
  end

  client.cancel 
  rows

rescue => e
  handle_error(e)
end

#tableObject



101
# File 'lib/pod4/pg_interface.rb', line 101

def table;  self.class.table;  end

#update(id, record) ⇒ Object

ID is whatever you set in the interface using set_id_fld; record should be a Hash or Octothorpe.



165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/pod4/pg_interface.rb', line 165

def update(id, record)
  raise(ArgumentError, "Bad type for record parameter") \
    unless record.kind_of?(Hash) || record.kind_of?(Octothorpe)

  read_or_die(id)

  sql, vals = sql_update(record, id_fld => id)
  executep(sql, *vals)

  self

rescue => e
  handle_error(e)
end