Skip to content

Commit

Permalink
Correctly handle column names that need escaping in INSERT and UPDATE…
Browse files Browse the repository at this point in the history
… statements (#164)

Examples:

INSERT INTO "x" ("user") VALUES ('abc')
UPDATE "x" SET "user" = 'MEK'
  • Loading branch information
emin100 authored Dec 27, 2020
1 parent 234043b commit c8f74aa
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/pg_query/deparse.rb
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ def deparse_restarget(node, context)
if context == :select
[deparse_item(node['val']), deparse_identifier(node['name'])].compact.join(' AS ')
elsif context == :update
[node['name'], deparse_item(node['val'])].compact.join(' = ')
[deparse_identifier(node['name']), deparse_item(node['val'])].compact.join(' = ')
elsif node['val'].nil?
node['name']
else
Expand Down Expand Up @@ -1202,7 +1202,7 @@ def deparse_insert_into(node)

if node['cols']
output << '(' + node['cols'].map do |column|
deparse_item(column)
deparse_item(column, :select)
end.join(', ') + ')'
end

Expand Down
12 changes: 12 additions & 0 deletions spec/lib/pg_query/deparse_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,12 @@
it { is_expected.to eq query }
end

context 'special column name' do
let(:query) { 'INSERT INTO "x" ("user") VALUES (\'abc\')' }

it { is_expected.to eq query }
end

context 'with RETURNING' do
let(:query) { 'INSERT INTO "x" (y, z) VALUES (1, \'abc\') RETURNING "id"' }

Expand Down Expand Up @@ -770,6 +776,12 @@

it { is_expected.to eq oneline_query }
end

context 'special column name' do
let(:query) { "UPDATE \"x\" SET \"user\" = 'emin'" }

it { is_expected.to eq query }
end
end

context 'DELETE' do
Expand Down

0 comments on commit c8f74aa

Please sign in to comment.