Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow nil conditions in where for backward compatibility #47

Merged
merged 1 commit into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/mysql_framework/sql_query.rb
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def where(*conditions)
@sql += " (#{conditions.join(' AND ')}) "

conditions.each do |condition|
next if condition.value.nil?
next if condition.value.nil? && !skip_nil_validation?
if condition.value.is_a?(Enumerable)
@params.concat(condition.value)
else
Expand Down Expand Up @@ -263,5 +263,11 @@ def on_duplicate(update_values = {})

self
end

private

def skip_nil_validation?
ENV.fetch('MYSQL_FRAMEWORK_SKIP_NIL_VALUE_VALIDATION', 'false').downcase == 'true'
end
end
end
27 changes: 27 additions & 0 deletions spec/lib/mysql_framework/sql_query_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,33 @@
expect(subject.sql).to eq('WHERE (`gems`.`author` = ? AND `gems`.`created_at` > ?) AND (`gems`.`name` IN (?, ?))')
end
end

context 'when condition is nil' do
context 'when MYSQL_FRAMEWORK_SKIP_NIL_VALUE_VALIDATION is not present' do
it 'concats the parameter collections' do
expect { subject.where(gems[:created_at].eq(nil)) }.to raise_error ArgumentError
end
end

context 'when MYSQL_FRAMEWORK_SKIP_NIL_VALUE_VALIDATION is present' do
after(:each) { ENV.delete('MYSQL_FRAMEWORK_SKIP_NIL_VALUE_VALIDATION') }

context 'when value is false' do
it 'concats the parameter collections' do
ENV['MYSQL_FRAMEWORK_SKIP_NIL_VALUE_VALIDATION'] = 'false'
expect { subject.where(gems[:created_at].eq(nil)) }.to raise_error ArgumentError
end
end

context 'when value is true' do
it 'concats the parameter collections' do
ENV['MYSQL_FRAMEWORK_SKIP_NIL_VALUE_VALIDATION'] = 'true'
query = subject.where(gems[:updated_at].eq(nil))
expect(query.params).to eq ['sage', '2018-01-01 00:00:00', nil]
end
end
end
end
end

describe '#and' do
Expand Down
Loading