Running Stored procedure giving error can't return a result set in the given context - mysql

I know this problem has been asked many times. But I tried the solutions and they didn't work for me. I have a web application built on rails 3.2.12 and ruby 1.9.2p180. I have a stored procedure in it which returns me data of a query having 5 inner joins. Multiple rows approximately 600 are returned in present case. On the local the stored procedure runs fine with no issues. But when I tried it on the server it is throwing:
ActiveRecord::StatementInvalid: Mysql2::Error: PROCEDURE test.sp_procedure can't return a result set in the given context: call sp_procedure('2015-02-14 00:00:00 -0500', '2015-03-03 23:59:00 -0500', 5, '13')
I have searched for this issue and found that I need to set CLIENT_MULTI_RESULTS flag when establishing connection to MySQL server. For this I have done monkey patching as said. Here is the file in initializers:
module ActiveRecord
class Base
def self.mysql2_connection(config)
config[:username] = 'deploy' if config[:username].nil?
if Mysql2::Client.const_defined? :FOUND_ROWS
config[:flags] = config[:flags] ? config[:flags] | Mysql2::Client::FOUND_ROWS : Mysql2::Client::FOUND_ROWS
end
client = Mysql2::Client.new(config.symbolize_keys)
options = [config[:host], config[:username], config[:password], config[:database], config[:port], config[:socket], 0]
ConnectionAdapters::Mysql2Adapter.new(client, logger, options, config)
end
def self.select_sp(sql, name = nil)
connection = ActiveRecord::Base.connection
begin
connection.select_all(sql, name)
rescue NoMethodError
ensure
connection.reconnect! unless connection.active?
end
end
end
end
In my database.yml I have added: flags: <%= 65536 | 131072 %> and also tried with flags: 131072. But it didn't work.
However using the following works:
client = Mysql2::Client.new(:host => "localhost", :username => "root", :flags => Mysql2::Client::MULTI_STATEMENTS )
result = client.query( 'CALL sp_procedure('2015-02-14 00:00:00 -0500', '2015-03-03 23:59:00 -0500', 5, '13')')
This worked on the server too. But each time the stored procedure will run it will create a new connection which I don't want.
And also one thing to note while I am doing this on local as soon as I call the stored procedure I have to execute this:
ActiveRecord::Base.connection.reconnect!
If I don't write this it throws an error:
ActiveRecord::StatementInvalid: Mysql2::Error: Commands out of sync; you can't run this command now
So this is also the same thing means it creates a new connection each time. So I am finding for a solution which saves me from doing this.
And if the monkey patching is correct then what am I missing. Please help.

Related

DBInterface.connect returns MySQL.Connection(disconnected)

I'm trying to connect to a MySQL database. In the Documentation its recommended to use DBInterface.connect with a Type MySQL.Connection Object. The Database im trying to connect to gets listed with the mysql> SHOW DATABASES; command so there should be no problem on the MySQL side of things.
For now I implemented:
module Database
using MySQL
using DBInterface
const HOST = "localhost"
const USER = "root"
const PASS = "#####"
const DB = "databank"
const CONN = DBInterface.connect(MySQL.Connection, HOST, USER, PASS, db=DB)
export CONN
disconnect() = DBInterface.close!(CONN)
# gets called for cleanup
atexit(disconnect)
end
But when I call CONN from the REPL I get:
julia> using Database
julia> CONN
MySQL.Connection(disconnected)
julia>
I already checked this Question for answeres, but my implementation should be the same.
Later down the line I was hoping to use DBInterface.execute(CONN, sql) but I get the error ERROR: mysql connection has been closed or disconnected

SphinxQL + sphinxsearch table doesn't exists

Today I was trying to use sphinxsearch with SphinxQL but something going bad =\
First I installed sphinxsearch then I configured it, after that I created index forum_index using indexer --all. All finished without errors.
Then I included SphinxQl to my project, typed host and port which is listening sphinx and tried to make a query like in ReadMe of SphinxQL:
// create a SphinxQL Connection object to use with SphinxQL
$conn = new Connection();
$conn->setParams(array('host' => 'localhost', 'port' => 9306))
;
But it caused a database access error:
access denied www-data#localhost password NO
After that I set parameters of username and password in SphinxQL using
mysqli::real_connect()
Previous errors disappeared
Then I tried to make a test query:
$query = SphinxQL::create($conn)->select('column_one', 'colume_two')
->from('forum_index');
$result = $query->execute();
But I get an error:
table forum_index doesn't exists
I have a feel that my SphinxQL doesn't see sphinx or sphinx config and tries to make a simple query.
Have you any idea what's going wrong?
Please go to command line use the following command
mysql -P9306 --protocol=tcp --prompt='sphinxQL> '
Once get sphinxQL prompt enter the following command
sphinxQL> show tables;
If you set up everything correctly you can see the forum_index table in the list. Else check your searchd configuration section in your sphinx.conf file for proper configuration. My configuration look like this
searchd {
listen = 9315
listen = 9306:mysql41
log = /Users/XXXX/projects/sphinx/data/searchd.log
query_log = /Users/XXXX/projects/sphinx/data/query.log
read_timeout = 5
max_children = 30
pid_file = /Users/XXXX/projects/sphinx/data/searchd.pid
max_matches = 1000
seamless_rotate = 1
preopen_indexes = 0
unlink_old = 1
workers = threads
thread_stack = 1024K
}
I solved my problem by setting host = '127.0.0.1' in SphinxQL params

Ruby: Catching Sequel::DatabaseConnectionError

I'm using Docker to run my Ruby app, with MySQL as a database. I need for my Ruby app to wait until MySQL has finished loading and a connection can be made.
I'm using the following code:
def connect_to_db
begin
puts "Trying to connect to Mysql"
Sequel::Model.db = Sequel.connect( // Connection stuff in here )
rescue Sequel::Error => e
puts "Mysql connection failed #{e.message}: Retrying."
retry
end
end
connect_to_db()
This runs once, then I get an error - Sequel::DatabaseConnectionError: Mysql2::Error: Unknown MySQL server host (25) - It doesn't go into the rescue block and doesn't retry.
I've tried rescue Sequel::DatabaseConnectionError but this gives the same result.
What do I need to rescue here?
Got it working with db.test_connection:
def connect_to_db_with_mysql_driver
begin
puts "Trying to connect to Mysql"
db = Sequel.connect(
// Connection stuff
)
if db.test_connection == true
Sequel::Model.db = db
else
raise "Mysql connection failed."
end
rescue => ex
puts ex
puts "Retrying..."
retry
end
end

CPU spikes observed when jruby tries to connect to database through jdbc/mysql driver

I am running a simple JRuby program which will fetch 2000 records from table using a jdbc/mysql driver.I am running the program on 3 core Ubuntu machine and with 4GB memory.
The database on same machine. When I try to execute the following program , I observe huge CPU spikes.
For the first few iterations CPU spikes between 150% to 200% and then gradually it comes down.I am using JRuby 1.7.3 for this and a oracle jdk6
Program:
require 'java'
require 'rubygems'
require 'jdbc/mysql'
Jdbc::MySQL.load_driver
module JavaLang
include_package "java.lang"
end
module JavaSql
include_package 'java.sql'
end
begin
loop do
com.mysql.jdbc.Driver.new
conn = JavaSql::DriverManager
.getConnection("jdbc:mysql://127.0.0.1:3306/db_name","root","password");
stmt = conn.createStatement
resultSet = stmt.executeQuery("select * from properties limit 2000")
end
resultSet.close
stmt.close
conn.close()
end
rescue JavaLang::ClassNotFoundException
puts "ClassNotFoundException"
rescue JavaSql::SQLException
puts "SQLException"
end
I have also tried to run similar code with ruby and mysql2 adapter and observed low CPU spike. Following is the ruby program
require 'mysql2'
client = Mysql2::Client.new(
host: "localhost",
username: "root",
password: "password",
database: "db_name",
)
loop do
results = client.query("SELECT * FROM properties limit 2000")
records = results.map do |row|
row
end
end
Try setting Xms and Xmx values to some max limit

500 Error in production adapter rails when starting new user session

I have been having this issue ever since I deployed and i can't figure it out.
I'll give some information and let me know if you need anything else! Thanks!
I, [2013-09-08T12:44:31.935143 #19456] INFO -- : Started POST "/sessions" for {IP ADDRESS} at 2013-09-08 12:44:31 -0700
I, [2013-09-08T12:44:31.937969 #19456] INFO -- : Processing by SessionsController#create as HTML
I, [2013-09-08T12:44:31.938102 #19456] INFO -- : Parameters: {"utf8"=>"✓", "authenticity_token"=>"{AUTHENTICITY TOKEN}", "email"=>"mike#test.com", "password"=>"[FILTERED]", "commit"=>"Log In"}
I, [2013-09-08T12:44:31.941064 #19456] INFO -- : Completed 500 Internal Server Error in 3ms
F, [2013-09-08T12:44:31.943631 #19456] FATAL -- :
ActiveRecord::StatementInvalid (Could not find table 'users'):
app/controllers/sessions_controller.rb:6:in `create'
Obviously it's telling me that the "users" table doesn't exist, but that BS, because it does. Perhaps it can't find the table? Which i ALSO think is wierd, because I created the table using Rails migrations.
Here is my production Adapter just for reference:
production:
adapter: mysql
database: {DATABASENAME}
username: {USERNAME}
password: {PASSWORD}
host: localhost
port: 3306
Here is my seeds file:
User.create([{ email: 'mike#test2.com' }, { password_digest: 'password' }])
And my user model:
class User < ActiveRecord::Base
has_secure_password
validates_uniqueness_of :email
end
And my sessions controller (handles the login):
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to root_url, notice: "Logged in!"
else
flash.now.alert = "Email or password is invalid"
render "new"
end
end
def destroy
session[:user_id] = nil
redirect_to root_url, notice: "Logged out!"
end
end
I created the user directly in the database, so the issue isn't that the user doesnt exist, the log file is saying the table 'users' doesnt exist, but that is false as well...i really don't know whats going on...
OH, BTW this all works in development. Login, user creation, everything. I was using sqlite3 for development and switched to mysql for production, just screwed everything up....
Any help is appreciated!
For future reference, this is the fix if anyone else is having an issue with their seeds not working:
This is what I was using:
User.create([{ email: 'mike#test2.com' }, { password_digest: 'password' }])
This is what it should be:
users =User.create!(:email 'mike#test2.com', :password 'password', :password_confirmation 'password')
users.save
Using
Create!
instead of just plain
Create
enables validation, and the seed will fail and explain the problem. In my case, it was that I was using password_digest, which is the column name, instead of password and password_confirmation.
Also, save the seed creation in a variable (users in my case), then save said variable by doing this:
users.save
Simple as that!
Hope this helps a fellow newbie in the future!