Skip to content

Commit 395cede

Browse files
committed
Normalize backtick SQL for PostgreSQL
1 parent 5adbd36 commit 395cede

6 files changed

Lines changed: 132 additions & 3 deletions

File tree

‎gems/mysql_genius-core/lib/mysql_genius/core/query_explainer.rb‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def explain(sql, skip_validation: false)
3232
raise QueryRunner::Rejected, error if error
3333
end
3434

35-
clean_sql = sql.gsub(/;\s*\z/, "")
35+
clean_sql = SqlValidator.normalize_identifier_quotes(sql, @connection).gsub(/;\s*\z/, "")
3636

3737
unless looks_complete?(clean_sql)
3838
raise Truncated, "This query appears to be truncated and cannot be explained."

‎gems/mysql_genius-core/lib/mysql_genius/core/query_runner.rb‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ def run(sql, row_limit:)
3535
)
3636
raise Rejected, validation_error if validation_error
3737

38-
limited = SqlValidator.apply_row_limit(sql, row_limit)
38+
normalized = SqlValidator.normalize_identifier_quotes(sql, @connection)
39+
limited = SqlValidator.apply_row_limit(normalized, row_limit)
3940
timed = apply_timeout_hint(limited)
4041

4142
start = Process.clock_gettime(Process::CLOCK_MONOTONIC)

‎gems/mysql_genius-core/lib/mysql_genius/core/sql_validator.rb‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,13 +54,87 @@ def apply_row_limit(sql, limit)
5454
end
5555
end
5656

57+
def normalize_identifier_quotes(sql, connection)
58+
quote = connection.quote_table_name("mysql_genius_identifier_probe")[0]
59+
return sql if quote == "`" || !sql.include?("`")
60+
61+
rewrite_backtick_identifiers(sql, connection)
62+
end
63+
5764
def masked_column?(column_name, patterns)
5865
patterns.any? { |pattern| column_name.downcase.include?(pattern) }
5966
end
6067

6168
def unquote_identifier(parts)
6269
(parts.find { |part| part && !part.empty? } || "").gsub('""', '"')
6370
end
71+
72+
def rewrite_backtick_identifiers(sql, connection)
73+
output = +""
74+
i = 0
75+
76+
while i < sql.length
77+
char = sql[i]
78+
79+
if char == "'"
80+
literal, i = read_single_quoted_literal(sql, i)
81+
output << literal
82+
elsif char == "`"
83+
identifier, i = read_backtick_identifier(sql, i)
84+
output << connection.quote_table_name(identifier)
85+
else
86+
output << char
87+
i += 1
88+
end
89+
end
90+
91+
output
92+
end
93+
94+
def read_single_quoted_literal(sql, index)
95+
output = +"'"
96+
i = index + 1
97+
98+
while i < sql.length
99+
output << sql[i]
100+
if sql[i] == "'"
101+
if sql[i + 1] == "'"
102+
output << sql[i + 1]
103+
i += 2
104+
next
105+
end
106+
107+
i += 1
108+
break
109+
end
110+
i += 1
111+
end
112+
113+
[output, i]
114+
end
115+
116+
def read_backtick_identifier(sql, index)
117+
output = +""
118+
i = index + 1
119+
120+
while i < sql.length
121+
if sql[i] == "`"
122+
if sql[i + 1] == "`"
123+
output << "`"
124+
i += 2
125+
next
126+
end
127+
128+
i += 1
129+
break
130+
end
131+
132+
output << sql[i]
133+
i += 1
134+
end
135+
136+
[output, i]
137+
end
64138
end
65139
end
66140
end

‎gems/mysql_genius-core/spec/mysql_genius/core/query_explainer_spec.rb‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,5 +85,19 @@
8585
explainer.explain("SELECT id FROM users;")
8686
expect(captured_sql).to(eq("EXPLAIN SELECT id FROM users"))
8787
end
88+
89+
it "rewrites backtick identifiers when the connection uses double quotes" do
90+
captured_sql = nil
91+
allow(connection).to(receive(:quote_table_name) { |name| %("#{name}") })
92+
connection.stub_query(/EXPLAIN/, columns: ["id"], rows: [[1]])
93+
allow(connection).to(receive(:exec_query).and_wrap_original do |original, sql, **kwargs|
94+
captured_sql = sql
95+
original.call(sql, **kwargs)
96+
end)
97+
98+
explainer.explain("SELECT `id` FROM `users`")
99+
100+
expect(captured_sql).to(eq(%(EXPLAIN SELECT "id" FROM "users")))
101+
end
88102
end
89103
end

‎gems/mysql_genius-core/spec/mysql_genius/core/query_runner_spec.rb‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,20 @@
6363
expect(captured_sql).to(match(/LIMIT 25/))
6464
end
6565

66+
it "rewrites backtick identifiers when the connection uses double quotes" do
67+
captured_sql = nil
68+
allow(connection).to(receive(:quote_table_name) { |name| %("#{name}") })
69+
connection.stub_query(/SELECT/, columns: ["id"], rows: [[1]])
70+
allow(connection).to(receive(:exec_query).and_wrap_original do |original, sql, **kwargs|
71+
captured_sql = sql
72+
original.call(sql, **kwargs)
73+
end)
74+
75+
runner.run("SELECT `id` FROM `users`", row_limit: 25)
76+
77+
expect(captured_sql).to(include(%("id" FROM "users")))
78+
end
79+
6680
it "masks columns matching configured patterns with [REDACTED]" do
6781
connection.stub_query(
6882
/SELECT/,

‎gems/mysql_genius-core/spec/mysql_genius/core/sql_validator_spec.rb‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
let(:blocked_tables) { ["sessions", "authentication_tokens"] }
55
let(:all_tables) { ["users", "posts", "sessions", "authentication_tokens"] }
66
let(:connection) do
7-
double("connection", tables: all_tables)
7+
double("connection", tables: all_tables, quote_table_name: "`mysql_genius_identifier_probe`")
88
end
99

1010
def validate(sql)
@@ -116,6 +116,32 @@ def validate(sql)
116116
end
117117
end
118118

119+
describe ".normalize_identifier_quotes" do
120+
it "leaves backticks intact for backtick-quoting adapters" do
121+
sql = "SELECT `id` FROM `users` WHERE `name` = 'has `backtick` text'"
122+
123+
expect(described_class.normalize_identifier_quotes(sql, connection)).to(eq(sql))
124+
end
125+
126+
it "rewrites backtick identifiers for double-quote adapters" do
127+
pg_connection = double("connection")
128+
allow(pg_connection).to(receive(:quote_table_name) { |name| %("#{name.gsub('"', '""')}") })
129+
130+
sql = "SELECT `id`, `title` FROM `users` WHERE `name` = 'has `backtick` text'"
131+
132+
expect(described_class.normalize_identifier_quotes(sql, pg_connection))
133+
.to(eq(%(SELECT "id", "title" FROM "users" WHERE "name" = 'has `backtick` text')))
134+
end
135+
136+
it "unescapes doubled backticks before adapter quoting" do
137+
pg_connection = double("connection")
138+
allow(pg_connection).to(receive(:quote_table_name) { |name| %("#{name.gsub('"', '""')}") })
139+
140+
expect(described_class.normalize_identifier_quotes("SELECT `weird``name` FROM `users`", pg_connection))
141+
.to(eq(%(SELECT "weird`name" FROM "users")))
142+
end
143+
end
144+
119145
describe ".masked_column?" do
120146
let(:patterns) { ["password", "secret", "digest", "token"] }
121147

0 commit comments

Comments
 (0)