Skip to content

Commit

Permalink
Merge pull request #47 from Sage/build-allow-nil-where
Browse files Browse the repository at this point in the history
Allow nil conditions in where for backward compatibility
  • Loading branch information
marianomms authored Feb 13, 2024
2 parents 25ced0a + fddc3b2 commit 737f098
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
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

0 comments on commit 737f098

Please sign in to comment.