Skip to content

Commit

Permalink
Treewalker: Allow passing a block with a single argument to walk!
Browse files Browse the repository at this point in the history
This simplifies the common use case of just working with the walked node
directly, which is now sufficient more often thanks to the addition of
Node#inner= streamling modification of Node objects without going to the
parent to replace them.
  • Loading branch information
lfittl committed Jan 3, 2024
1 parent f5e2066 commit cc7d11c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
19 changes: 16 additions & 3 deletions lib/pg_query/treewalker.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
module PgQuery
class ParserResult
def walk!
treewalker!(@tree) do |parent_node, parent_field, node, location|
yield(parent_node, parent_field, node, location)
# Walks the parse tree and calls the passed block for each contained node
#
# If you pass a block with 1 argument, you will get each node.
# If you pass a block with 4 arguments, you will get each parent_node, parent_field, node and location.
#
# Location uniquely identifies a given node within the parse tree. This is a stable identifier across
# multiple parser runs, assuming the same pg_query release and no modifications to the parse tree.
def walk!(&block)
if block.arity == 1
treewalker!(@tree) do |_, _, node, _|
yield(node)
end
else
treewalker!(@tree) do |parent_node, parent_field, node, location|
yield(parent_node, parent_field, node, location)
end
end
end

Expand Down
2 changes: 1 addition & 1 deletion spec/lib/treewalker_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@

it 'allows recursively replacing nodes' do
query = PgQuery.parse("SELECT * FROM tbl WHERE col::text = ANY(((ARRAY[$39, $40])::varchar[])::text[])")
query.walk! do |_parent_node, _parent_field, node, _location|
query.walk! do |node|
next unless node.is_a?(PgQuery::Node)
# Keep removing type casts until we hit a different class
node.inner = node.type_cast.arg.inner while node.node == :type_cast
Expand Down

0 comments on commit cc7d11c

Please sign in to comment.