From e521a4de095a1c63d2f0336bab91ec15b493564e Mon Sep 17 00:00:00 2001 From: Bilal Catic Date: Fri, 31 Jan 2020 17:44:12 +0100 Subject: [PATCH] raise error on unknown column; add complex query test --- spec/query_generator_spec.rb | 27 ++++++++++++++++++++++++++- text_to_sql_query.rb | 4 +++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/spec/query_generator_spec.rb b/spec/query_generator_spec.rb index 0ee9ba4..bd617af 100644 --- a/spec/query_generator_spec.rb +++ b/spec/query_generator_spec.rb @@ -17,7 +17,7 @@ class SqlGeneratorTester it 'tests simple search term with unknown column name and without quotes' do @query = TextToSqlQuery.new('unknown:ab', [:'players.title', :'players.tag', :'players.device_id'], :'players.device_id') - expect(@query.where_clause).to eq ['players.device_id ILIKE ?', '%ab%'] + expect { @query.where_clause }.to raise_error(RuntimeError, "Unknown field 'unknown'") end it 'tests simple search term without column name and with quotes' do @@ -97,5 +97,30 @@ class SqlGeneratorTester expect(@query.where_clause).to eq ['tags.name ILIKE ?', '%h1-r%'] end + + it 'tests complex query' do + text = '(device_id:"with space" tags:mta no-quotes-id-123)'\ + 'or "id with quotes-5" and ( ("id with q 10" or "id with q 20")'\ + 'and ("id with Q 30" "id with Q 40") and not id-without-Q-50)' + + fields = [:'players.title', :'players.name', :'players.device_id'] + default_field = :'players.device_id' + fields_mappings = { tags: 'tags.name' } + + @query = TextToSqlQuery.new(text, fields, default_field, fields_mappings) + + result_expression = '((players.device_id ILIKE ? OR (tags.name ILIKE ? OR players.device_id ILIKE ?)) OR (players.device_id ILIKE ? AND (((players.device_id ILIKE ? OR players.device_id ILIKE ?) AND (players.device_id ILIKE ? OR players.device_id ILIKE ?)) AND NOT players.device_id ILIKE ?)))' + result_params = ['%with space%', + '%mta%', + '%no-quotes-id-123%', + '%id with quotes-5%', + '%id with q 10%', + '%id with q 20%', + '%id with Q 30%', + '%id with Q 40%', + '%id-without-Q-50%'] + + expect(@query.where_clause).to eq [result_expression, result_params].flatten + end end end \ No newline at end of file diff --git a/text_to_sql_query.rb b/text_to_sql_query.rb index fb4bd6b..4fbefa8 100644 --- a/text_to_sql_query.rb +++ b/text_to_sql_query.rb @@ -48,7 +48,9 @@ class TextToSqlQuery escaped_node_value = handle_special_chars node_value mapping = @fields_mappings[first_key.to_sym] if mapping.nil? - ["#{@default_field.to_s} ILIKE ?", "%#{escaped_node_value}%"] + # ["#{@default_field.to_s} ILIKE ?", "%#{escaped_node_value}%"] + #['', ''] + raise "Unknown field '#{first_key.to_s}'" # "Unknown field '#{first_key.to_s}' in query " else ["#{mapping.to_s} ILIKE ?", "%#{escaped_node_value}%"] end