Skip to content

Commit

Permalink
compiler: Improve validation of ORDER BY clause with column number
Browse files Browse the repository at this point in the history
Only targets in the SELECT target list can be referenced by column
number in the ORDER BY clause, not auxiliary targets added to compute
the GROUP BY clause.
  • Loading branch information
dnicolodi committed Jun 17, 2024
1 parent 5625b83 commit a17023a
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions beanquery/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,10 +219,6 @@ def _compile_order_by(self, order_by, c_targets):
if not order_by:
return [], None

new_targets = c_targets[:]
c_target_expressions = [c_target.c_expr for c_target in c_targets]
order_spec = []

# Compile order-by expressions and resolve them to their targets if
# possible. A ORDER-BY column may be one of the following:
#
Expand All @@ -232,7 +228,16 @@ def _compile_order_by(self, order_by, c_targets):
#
# References by name are converted to indexes. New expressions are
# inserted into the list of targets as invisible targets.
targets_name_map = {target.name: index for index, target in enumerate(c_targets)}

new_targets = c_targets[:]
c_target_expressions = [c_target.c_expr for c_target in c_targets]
targets_name_map = {target.name: idx for idx, target in enumerate(c_targets) if target.name is not None}
# Only targets appearing in the SELECT targets list can be
# referenced by index. These are guaranteed to have a valid name.
n_targets = len(targets_name_map)

order_spec = []

for spec in order_by:
column = spec.column
descending = spec.ordering
Expand All @@ -241,7 +246,7 @@ def _compile_order_by(self, order_by, c_targets):
# Process target references by index.
if isinstance(column, int):
index = column - 1
if not 0 <= index < len(c_targets):
if not 0 <= index < n_targets:
raise CompilationError(f'invalid ORDER-BY column index {column}')

else:
Expand Down

0 comments on commit a17023a

Please sign in to comment.