Class: Og::MysqlAdapter

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

Overview

The MySQL adapter. This adapter communicates with an MySQL 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, join_table, parse_date, parse_timestamp, #props_for_insert, table

Constructor Details

#initializeMysqlAdapter

Returns a new instance of MysqlAdapter.



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

def initialize
	super
	@typemap.update({TrueClass => 'tinyint'})
end

Class Method Details

.date(date) ⇒ Object



34
35
36
37
# File 'lib/og/adapters/mysql.rb', line 34

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

.escape(str) ⇒ Object



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

def self.escape(str)
	return nil unless str
	return Mysql.quote(str)
end

.timestamp(time = Time.now) ⇒ Object



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

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



104
105
106
107
108
109
110
111
112
113
114
# File 'lib/og/adapters/mysql.rb', line 104

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

	for idx in (0...res.num_fields)
		meta.field_index[res.fetch_field.name] = idx
	end

ensure
	res.free if res
end

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



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

def create_db(database, user = nil, password = nil)
	`mysqladmin -f --user=#{user} --password=#{password} create #{database}`
	super
end

#create_table(klass, db) ⇒ Object



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
183
184
185
186
# File 'lib/og/adapters/mysql.rb', line 116

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

	fields = create_fields(klass)

	sql = "CREATE TABLE #{klass::DBTABLE} (#{fields.join(', ')}"
	
	conn.store.query_with_result = true 

	# Create table constrains
	
	if klass.__meta and constrains = klass.__meta[:sql_constrain]
		sql << ", #{constrains.join(', ')}"
	end
	
	sql << ');'
	
	begin
		conn.store.query(sql)
		Logger.info "Created table '#{klass::DBTABLE}'."
	rescue => ex
		if ex.errno == 1050 # table already exists.
			Logger.debug "Table already exists" if $DBG
			return 
		else
			raise
		end
	end
	
	# 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(/\(.*\)/, "")
			conn.store.query("CREATE #{pre_sql} INDEX #{klass::DBTABLE}_#{idxname}_idx #{post_sql} ON #{klass::DBTABLE} (#{idx})")
		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.query("CREATE TABLE #{join_table} ( key1 integer NOT NULL, key2 integer NOT NULL )")
				conn.store.query("CREATE INDEX #{join_table}_key1_idx ON #{join_table} (key1)")
				conn.store.query("CREATE INDEX #{join_table}_key2_idx ON #{join_table} (key2)")
			rescue => ex
				if ex.errno == 1050 # table already exists.
					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



80
81
82
83
# File 'lib/og/adapters/mysql.rb', line 80

def drop_db(database, user = nil, password = nil)
	`mysqladmin -f --user=#{user} --password=#{password} drop #{database}`
	super
end

#eval_og_oid(klass) ⇒ Object



188
189
190
191
192
# File 'lib/og/adapters/mysql.rb', line 188

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

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



85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/og/adapters/mysql.rb', line 85

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}
		conn.store.query_with_result = false
		conn.store.query "#{sql}"
		@oid = conn.store.insert_id()
		#{post_cb}
	}
end

#new_connection(db) ⇒ Object



100
101
102
# File 'lib/og/adapters/mysql.rb', line 100

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

#read_prop(p, idx) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/og/adapters/mysql.rb', line 57

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

#write_prop(p) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/og/adapters/mysql.rb', line 39

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} ? 1 : 0 \}"
	else 
		return %|#\{@#{p.symbol} ? "'#\{#{self.class}.escape(@#{p.symbol}.to_yaml)\}'" : "''"\}|
	end
end