Skip to content

Commit

Permalink
Merge pull request #35 from Sage/commands-out-of-sync-fix
Browse files Browse the repository at this point in the history
Fix 'Commands out of sync' error
  • Loading branch information
ianoxley authored Dec 15, 2020
2 parents 1efa82c + fc71136 commit 4f329bb
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 3 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@
.idea/*
.idea
pkg
tags
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ version: '2.1'

services:
test-runner:
image: ruby:2.5
image: ruby:2.4
working_dir: /usr/src/app
container_name: test-runner
command: sh -c "while true; do echo 'Container is running..'; sleep 5; done"
Expand Down
13 changes: 11 additions & 2 deletions lib/mysql_framework/connector.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,19 @@ def with_client(provided = nil)
end

# This method is called to execute a prepared statement
#
# @note Ensure we close each statement, otherwise we can run into
# a 'Commands out of sync' error if multiple threads are running different
# queries at the same time.
def execute(query, provided_client = nil)
with_client(provided_client) do |client|
statement = client.prepare(query.sql)
statement.execute(*query.params)
begin
statement = client.prepare(query.sql)
result = statement.execute(*query.params)
result.to_a if result
ensure
statement.close if statement
end
end
end

Expand Down
27 changes: 27 additions & 0 deletions spec/lib/mysql_framework/connector_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,33 @@
expect(results.length).to eq(1)
expect(results[0][:id]).to eq(guid)
end

it 'does not raise a commands out of sync error' do
threads = []
threads << Thread.new do
350.times do
update_query = MysqlFramework::SqlQuery.new.update('gems')
.set(updated_at: Time.now)
expect { subject.execute(update_query) }.not_to raise_error
end
end

threads << Thread.new do
350.times do
select_query = MysqlFramework::SqlQuery.new.select('*').from('demo')
expect { subject.execute(select_query) }.not_to raise_error
end
end

threads << Thread.new do
350.times do
select_query = MysqlFramework::SqlQuery.new.select('*').from('test')
expect { subject.execute(select_query) }.not_to raise_error
end
end

threads.each(&:join)
end
end

describe '#query' do
Expand Down

0 comments on commit 4f329bb

Please sign in to comment.