Class: Og::PsqlConnection

Inherits:
Connection show all
Defined in:
lib/og/adapters/psql.rb

Overview

The PostgreSQL connection.

Instance Attribute Summary

Attributes inherited from Connection

#db, #store

Instance Method Summary collapse

Methods inherited from Connection

#close, #commit, #count, #create_table, #delete, #drop_table, #insert, #load, #load_all, #load_by_name, #load_by_oid, #prepare, #rollback, #save, #select, #select_one, #start, #transaction, #update, #update_properties

Constructor Details

#initialize(db) ⇒ PsqlConnection

Returns a new instance of PsqlConnection.



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/og/adapters/psql.rb', line 203

def initialize(db)
	super

	config = db.config

	begin
		@store = PGconn.connect(
			config[:address], 
			config[:port], 
			nil, 
			nil, 
			config[:database], 
			config[:user].to_s, 
			config[:password].to_s
		)
	rescue => ex
		# gmosx: any idea how to better test this?
		if ex.to_s =~ /database .* does not exist/i
			Logger.info "Database '#{config[:database]}' not found!"
			@db.adapter.create_db(config[:database], config[:user])
			retry
		end
		raise
	end
end

Instance Method Details

#exec(sql) ⇒ Object



240
241
242
243
244
245
246
247
248
# File 'lib/og/adapters/psql.rb', line 240

def exec(sql)
	Logger.debug sql if $DBG
	begin
		@store.exec(sql).clear
	rescue => ex
		Logger.error "DB error #{ex}, [#{sql}]"
		Logger.error ex.backtrace.join("\n")
	end
end

#query(sql) ⇒ Object



229
230
231
232
233
234
235
236
237
238
# File 'lib/og/adapters/psql.rb', line 229

def query(sql)
	Logger.debug sql if $DBG
	begin
		return @store.exec(sql)
	rescue => ex
		Logger.error "DB error #{ex}, [#{sql}]"
		Logger.error ex.backtrace.join("\n")
		return nil
	end
end

#read_all(res, klass) ⇒ Object



264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/og/adapters/psql.rb', line 264

def read_all(res, klass)
	return [] unless valid_res?(res)
	objects = []

	for tuple in (0...res.num_tuples)
		obj = klass.new
		obj.og_read(res, tuple)
		objects << obj
	end
	
	res.clear
	return objects
end

#read_int(res, idx = 0) ⇒ Object



278
279
280
281
282
# File 'lib/og/adapters/psql.rb', line 278

def read_int(res, idx = 0)
	val = res.getvalue(0, idx).to_i
	res.clear
	return val
end

#read_one(res, klass) ⇒ Object



254
255
256
257
258
259
260
261
262
# File 'lib/og/adapters/psql.rb', line 254

def read_one(res, klass)
	return nil unless valid_res?(res)

	obj = klass.new
	obj.og_read(res, 0)

	res.clear
	return obj
end

#valid_res?(res) ⇒ Boolean

Returns:

  • (Boolean)


250
251
252
# File 'lib/og/adapters/psql.rb', line 250

def valid_res?(res)
	return !(res.nil? or 0 == res.num_tuples)
end