Class: Og::PsqlAdapter

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

Overview

The PostgreSQL adapter. This adapter communicates with an PostgreSQL rdbms. For extra documentation see lib/og/adapter.rb

Instance Attribute Summary

Attributes inherited from Adapter

#typemap

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Adapter

#create_fields, encode, #eval_og_insert, #eval_og_read, #eval_og_update, for_name, #initialize, join_table, parse_date, parse_timestamp, #props_for_insert, table

Constructor Details

This class inherits a constructor from Og::Adapter

Class Method Details

.date(date) ⇒ Object



29
30
31
32
# File 'lib/og/adapters/psql.rb', line 29

def self.date(date)
	return nil unless date
	return "#{date.year}-#{date.month}-#{date.mday}" 
end

.escape(str) ⇒ Object



19
20
21
22
# File 'lib/og/adapters/psql.rb', line 19

def self.escape(str)
	return nil unless str
	return PGconn.escape(str)
end

.timestamp(time = Time.now) ⇒ Object



24
25
26
27
# File 'lib/og/adapters/psql.rb', line 24

def self.timestamp(time = Time.now)
	return nil unless time
	return time.strftime("%Y-%m-%d %H:%M:%S")
end

Instance Method Details

#calc_field_index(klass, db) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
# File 'lib/og/adapters/psql.rb', line 100

def calc_field_index(klass, db)
	res = db.query "SELECT * FROM #{klass::DBTABLE} LIMIT 1"
	meta = db.managed_classes[klass]

	for field in res.fields
		meta.field_index[field] = res.fieldnum(field)
	end

ensure
	res.clear if res
end

#create_db(database, user = nil, password = nil) ⇒ Object



70
71
72
73
# File 'lib/og/adapters/psql.rb', line 70

def create_db(database, user = nil, password = nil)
	`createdb #{database} -U #{user}`
	super
end

#create_table(klass, db) ⇒ Object



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/og/adapters/psql.rb', line 112

def create_table(klass, db)
	conn = db.get_connection

	fields = create_fields(klass)

	sql = "CREATE TABLE #{klass::DBTABLE} (#{fields.join(', ')}"
	
	# Create table constrains
	
	if klass.__meta and constrains = klass.__meta[:sql_constrain]
		sql << ", #{constrains.join(', ')}"
	end
	
	sql << ") WITHOUT OIDS;"
	
	# Create indices
	
	if klass.__meta and indices = klass.__meta[:sql_index]
		for data in indices
			idx, options = *data
			idx = idx.to_s
			pre_sql, post_sql = options[:pre], options[:post]
			idxname = idx.gsub(/ /, "").gsub(/,/, "_").gsub(/\(.*\)/, "")
			sql << " CREATE #{pre_sql} INDEX #{klass::DBTABLE}_#{idxname}_idx #{post_sql} ON #{klass::DBTABLE} (#{idx});"  
		end
	end

	begin
		conn.store.exec(sql).clear
		Logger.info "Created table '#{klass::DBTABLE}'."
	rescue => ex
		# gmosx: any idea how to better test this?
		if ex.to_s =~ /relation .* already exists/i
			Logger.debug 'Table already exists' if $DBG
			return
		else
			raise
		end
	end

	# Create join tables if needed. Join tables are used in
	# 'many_to_many' relations.
	
	if klass.__meta and joins = klass.__meta[:sql_join] 
		for data in joins
			# the class to join to and some options.
			join_class, options = *data
			
			# gmosx: dont use DBTABLE here, perhaps the join class
			# is not managed yet.
			join_table = "#{self.class.join_table(klass, join_class)}"
			join_src = "#{self.class.encode(klass)}_oid"
			join_dst = "#{self.class.encode(join_class)}_oid"
			begin
				conn.store.exec("CREATE TABLE #{join_table} ( key1 integer NOT NULL, key2 integer NOT NULL )").clear
				conn.store.exec("CREATE INDEX #{join_table}_key1_idx ON #{join_table} (key1)").clear
				conn.store.exec("CREATE INDEX #{join_table}_key2_idx ON #{join_table} (key2)").clear
			rescue => ex
				# gmosx: any idea how to better test this?
				if ex.to_s =~ /relation .* already exists/i
					Logger.debug "Join table already exists" if $DBG
				else
					raise
				end
			end
		end
	end

ensure
	db.put_connection
end

#drop_db(database, user = nil, password = nil) ⇒ Object



75
76
77
78
# File 'lib/og/adapters/psql.rb', line 75

def drop_db(database, user = nil, password = nil)
	`dropdb #{database} -U #{user}`
	super
end

#drop_table(klass) ⇒ Object



184
185
186
187
# File 'lib/og/adapters/psql.rb', line 184

def drop_table(klass)
	super
	exec "DROP SEQUENCE #{klass::DBSEQ}"		
end

#eval_og_oid(klass) ⇒ Object

Generate the property for oid.



191
192
193
194
195
# File 'lib/og/adapters/psql.rb', line 191

def eval_og_oid(klass)
	klass.class_eval %{
		prop_accessor :oid, Fixnum, :sql => 'serial PRIMARY KEY'
	}
end

#insert_code(klass, db, pre_cb, post_cb) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/og/adapters/psql.rb', line 80

def insert_code(klass, db, pre_cb, post_cb)
	props = props_for_insert(klass)
	values = props.collect { |p| write_prop(p) }.join(',') 

	sql = "INSERT INTO #{klass::DBTABLE} (#{props.collect {|p| p.name}.join(',')}) VALUES (#{values})"

	%{
		#{pre_cb}
		res = conn.store.exec("SELECT nextval('#{klass::DBSEQ}')")
		@oid = res.getvalue(0, 0).to_i
		res.clear
		conn.exec "#{sql}"
		#{post_cb}
	}
end

#new_connection(db) ⇒ Object



96
97
98
# File 'lib/og/adapters/psql.rb', line 96

def new_connection(db)
	return Og::PsqlConnection.new(db)
end

#read_prop(p, idx) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/og/adapters/psql.rb', line 52

def read_prop(p, idx)
	if p.klass.ancestors.include?(Integer)
		return "res.getvalue(tuple, #{idx}).to_i()"
	elsif p.klass.ancestors.include?(Float)
		return "res.getvalue(tuple, #{idx}).to_f()"
	elsif p.klass.ancestors.include?(String)
		return "res.getvalue(tuple, #{idx})"
	elsif p.klass.ancestors.include?(Time)
		return "#{self.class}.parse_timestamp(res.getvalue(tuple, #{idx}))"
	elsif p.klass.ancestors.include?(Date)
		return "#{self.class}.parse_date(res.getvalue(tuple, #{idx}))"
	elsif p.klass.ancestors.include?(TrueClass)
		return %|('t' == res.getvalue(tuple, #{idx}))|
	else 
		return "YAML::load(res.getvalue(tuple, #{idx}))"
	end		
end

#write_prop(p) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/og/adapters/psql.rb', line 34

def write_prop(p)
	if p.klass.ancestors.include?(Integer)
		return "#\{@#{p.symbol} || 'NULL'\}"
	elsif p.klass.ancestors.include?(Float)
		return "#\{@#{p.symbol} || 'NULL'\}"		
	elsif p.klass.ancestors.include?(String)
		return "'#\{#{self.class}.escape(@#{p.symbol})\}'"
	elsif p.klass.ancestors.include?(Time)
		return %|#\{@#{p.symbol} ? "'#\{#{self.class}.timestamp(@#{p.symbol})\}'" : 'NULL'\}|
	elsif p.klass.ancestors.include?(Date)
		return %|#\{@#{p.symbol} ? "'#\{#{self.class}.date(@#{p.symbol})\}'" : 'NULL'\}|
	elsif p.klass.ancestors.include?(TrueClass)
		return "#\{@#{p.symbol} ? \"'t'\" : 'NULL' \}"
	else 
		return %|#\{@#{p.symbol} ? "'#\{#{self.class}.escape(@#{p.symbol}.to_yaml)\}'" : "''"\}|
	end
end