error in mysql code written for ruby on rails - mysql

while running the below mysql query in ruby on rails
cnt=Domainurl.find_by_sql["SELECT MAX(`count`) FROM domainurls WHERE `domaindetail_id` = ?", #domain.id]
puts cnt.count
I am getting below error:
"error is: wrong number of arguments (0 for 1)"
Can anybody tell where exactly am I wrong?

You either need to wrap the argument in parenthesis or add a space.
cnt=Domainurl.find_by_sql(["SELECT MAX(`count`) FROM domainurls WHERE `domaindetail_id` = ?", #domain.id])
or
cnt=Domainurl.find_by_sql ["SELECT MAX(`count`) FROM domainurls WHERE `domaindetail_id` = ?", #domain.id]

Related

Ruby Mysql2 Client not taking backslash while insert

We are using production and staging databases in our application.
Our requirement is to insert all the records to staging database when ever a record is added in production database, so that both the servers are consistent and same data.
I have used Mysql2 client pool to connect to staging server and insert the record that is added to production.
here is my code:
def create
#aperson = Person.new
#person = #aperson.save
if #person && Rails.env == "production"
#add_new_person_to_staging
client = Mysql2::Client.new(:host => dbconfig[:host], :username => dbconfig[:username], :password => dbconfig[:password], :database => dbconfig[:database])
#person_result = client.query('INSERT INTO user_types(user_name, regex, code) Values ("myname" , "\.myregex\." , "ns" );')
end
end
Here "#person_result" record is inserted to mysql table but the "regex" column eliminates "\" slashes.
like : user_name = myname, regex = .myregex., code = ns
when I manually execute the "Insert" query in mysql command line it inserts as it is along with \ slash. but not through "client.query"
Why does \ slash is eliminated. please help me here.
Thanks.
\ is likely being removed by the MySQL2 client as part of a SQL injection protection preprocessor.
Have you looked at trying either a double backslash or using the escape method to properly escape the string?
Try using this
#person_result = client.query('INSERT INTO user_types(user_name, regex, code) Values (myname , "\."+myregx+".\" , ns )')

Parallel mysql I/O in Ruby

Good day to you. I'm writing a cron job that hopefully will split a huge MySQL table to several threads and do some work on them. This is the minimal sample of what I have at the moment:
require 'mysql'
require 'parallel'
#db = Mysql.real_connect("localhost", "root", "", "database")
#threads = 10
Parallel.map(1..#threads, :in_processes => 8) do |i|
begin
#db.query("SELECT url FROM pages LIMIT 1 OFFSET #{i}")
rescue Mysql::Error => e
#db.reconnect()
puts "Error code: #{e.errno}"
puts "Error message: #{e.error}"
puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate")
end
end
#db.close
The threads don't need to return anything, they get their job share and they do it. Only they don't. Either connection to MySQL is lost during the query, or connection doesn't exist (MySQL server has gone away?!), or no _dump_data is defined for class Mysql::Result and then Parallel::DeadWorker.
How to do that right?
map method expects a result; I don't need a result, so I switched to each:
Parallel.each(1..#threads, :in_processes => 8) do |i|
Also this solves a problem with MySQL: I just needed to start the connection inside the parallel process. When using each loop, it's possible. Of course, connection should be closed inside the process also.

Storing a String saved as a Variable in a MySQL database?

In a ruby script that sends information to the TWILIO API, I have a string of characters of characters that their (Twilio's) API outputs. I then have the console output it so I can save it as a variable and reuse it later:
#client = Twilio::REST:Client.new account_sid, auth_token
call = #client.account.calls.create({:from => 'incoming', :to => 'outgoing', :url => 'url', :method => 'GET'})
puts call.sid
This part is functional, but now when I rename the variable (// #incoming_Cid=call.sid //) as to input it into a MySQL database, I bump into an issue. (The 34 character ID has numbers and letters, so I define the datatype as VARCHAR).
begin
dbh = DBI.connect("DBI:Mysql:db_name:localhost",
"user", "pass")
dbh.do ("INSERT INTO calls (column_name)" #//Select the column to insert
"VALUES (incoming_Cid)") #Insert the 34 character string.
dbh.commit
puts "Customer SID has been recorded"
rescue
puts "A database occurred"
puts "Error code: #{e.err}"
puts "Error message: #{e.errstr}"
ensure
dbh.disconnect if dbh
end
Right here at the dbh.do ("INSERT INTO calls " line if I put the incoming_Cid variable in the VALUES() instead of seeing a 34-char-string, like CA9321a83241035b4c3d3e7a4f7aa6970d, I literally see 'incoming_Cid' appear in the database when I execute select * in calls.
How can I resolve this issue?
You need to use string interpolation: "VALUES (#{#incoming_Cid})"

Failed to insert value into tables in Ruby Mysql

I am trying to use Ruby to insert values into MySQL on localhost. The value i want to insert is the result from Twitter search. My program can successfully write the result to a file, so now i want to insert the result to MySQL. Here is part of my code:
results = #search.perform("yahoo", 100)
client = Mysql2::Client.new(:host => "localhost", :username => "root", :password => "123", :database => "db1")
results.map do |status|
insert = client.query ("INSERT INTO table1 (fromuser, tweet) VALUES (#{status.from_user},#{status.text})")
end
The error is "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near " tweet " at line 1 (Mysql2::Error).
What caused the error?
Another problem i have found is that when i used following code to insert value to MySQL ,i got another error: "Unknown column 'a' in 'field list' (Mysql::ServerError::BadFieldError)"
require 'mysql'
require 'rubygems'
sql = Mysql.real_connect("localhost", "root", "123", "db1")
st1 = "a"
st2 = "b"
user_string = "(#{st1},#{st2})"
query="INSERT INTO table1 (fromuser, tweet) VALUES" + user_string
sql.query(query)
I want to insert "a" and "b" into table.
How to solve this?
Thanks in advance,
Like Andrew said, you definitely want to escape your data.
I think you also need to quote the values:
insert = client.query("INSERT INTO tweets (from_user, tweet_text)
VALUES ('#{client.escape(status.from_user)}',
'#{client.escape(status.text)}')")
You need to use CREATE TABLE to create a table in your database to insert the data into. At the moment you are saying you want to insert the data into the database name ("db1") itself.
Also, you must escape your data first:
insert = client.query("INSERT INTO tweets (from_user, tweet_text)
VALUES (#{client.escape(status.from_user)},
#{client.escape(status.text)})")

PGError syntax problem for named_scope

I have the following named_scope which works fine in MySQL and sqlite but bombs in Postgres:
course.rb
named_scope :current, :conditions => ['start < ? AND end > ? ', Time.now, Time.now], :order => 'start ASC'
Then I just call:
Course.current
I get the error:
PGError: ERROR: syntax error at or
near "end" LINE 1: ... WHERE (start <
'2010-03-17 14:03:24.995746' AND end >
'201...
^ : SELECT count(*) AS count_all FROM
"courses" WHERE (start <
'2010-03-17 14:03:24.995746' AND end >
'2010-03-17 14:03:24.995748' )
My google-fu is failing me so I'm hoping Stack Overflow won't. Any ideas on how to make that scope Postgres-friendly? Thanks,
Drew
END is a keyword, you have to use another name or place it between double quotes "end".
If you use double quotes around the columnname and use this code also for MySQL, tell MySQL to accept double quotes as object identifier by setting the correct SQL MODE: ANSI_QUOTES