Class: MYSQLSafe::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/MYSQLSafe/base.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#databaseObject

Returns the value of attribute database.



5
6
7
# File 'lib/MYSQLSafe/base.rb', line 5

def database
  @database
end

#encodingObject

Returns the value of attribute encoding.



5
6
7
# File 'lib/MYSQLSafe/base.rb', line 5

def encoding
  @encoding
end

#hostObject

Returns the value of attribute host.



5
6
7
# File 'lib/MYSQLSafe/base.rb', line 5

def host
  @host
end

#passwordObject

Returns the value of attribute password.



5
6
7
# File 'lib/MYSQLSafe/base.rb', line 5

def password
  @password
end

#userObject

Returns the value of attribute user.



5
6
7
# File 'lib/MYSQLSafe/base.rb', line 5

def user
  @user
end

Instance Method Details

#connect_safe(raw_sql) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/MYSQLSafe/base.rb', line 7

def connect_safe(raw_sql)
@mysql_array = []
@encoding ||= 'utf-8'
options = {}
self.instance_variables.map{|name| options = options.merge({ name.to_s.delete("@") => self.instance_variable_get(name) }) }
options.each do |k,v|
	options[k] = esc_enc_string(v)
end


sql = enc_string(raw_sql)
begin
	case
		when options["host"], options["user"], options["password"], options["database"]
			@cxtn = Mysql.new(options["host"], options["user"], options["password"], options["database"])
		when options["host"], options["user"], options["password"]
			@cxtn = Mysql.new(options["host"], options["user"], options["password"])
		when options["host"], options["user"]
			@cxtn = Mysql.new(options["host"], options["user"])
		else
			raise "MYSQLSafe error: In order to connect to MYSQL you must at least set the host and username. So far you have included #{options}."
	end
	
	table_names = get_table_names
	table_match = match_name(table_names, sql)
	
	if table_match
		column_names = get_column_names(table_match)
		column_match = match_name(column_names, sql)
		column_match = [] if !(sql.to_s.downcase.include?('where'))
	else
		raise 'MYSQLSafe error: no valid table name could be found in your SQL statement'
	end
	
	if column_match
		ticked_sql = tick_sql(sql, table_match, column_match)
	else
		raise 'MYSQLSafe error: no valid column name(s) could be found in your SQL statement'
	end
	
	mysql_object = @cxtn.query(ticked_sql)
	mysql_object.each { |row| @mysql_array.push(row) } if mysql_object
	unless @mysql_array.size > 0
		@mysql_array = ["Success, with 'nil' result"] 
	end
rescue Mysql::Error => msqle
	puts "Error! #{msqle}, #{@mysql_array}"
	@mysql_array.push(["MYSQL Error: #{msqle}"])
ensure
	@cxtn.close if @cxtn
end

return @mysql_array
	
end