sql_tools 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/LICENSE.txt +21 -0
- data/README.md +52 -0
- data/Rakefile +15 -0
- data/exe/install_tree_sitter_sql +64 -0
- data/lib/sql_tools/common_table_expression.rb +17 -0
- data/lib/sql_tools/inner_join.rb +3 -0
- data/lib/sql_tools/left_join.rb +3 -0
- data/lib/sql_tools/predicate.rb +45 -0
- data/lib/sql_tools/predicate_filter.rb +35 -0
- data/lib/sql_tools/predicate_visitor.rb +26 -0
- data/lib/sql_tools/query.rb +123 -0
- data/lib/sql_tools/query_visitor.rb +28 -0
- data/lib/sql_tools/relation.rb +7 -0
- data/lib/sql_tools/selection.rb +7 -0
- data/lib/sql_tools/version.rb +5 -0
- data/lib/sql_tools.rb +24 -0
- data/rakelib/treesitter.rake +11 -0
- metadata +94 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: b2ba309601d1b52dd6da36b4a8bb360a36d626887c422670c8ab9baeac3613b1
|
4
|
+
data.tar.gz: aed2136db1548ecebf953dade273f0827eaebc5f9669b3739fae7a4f243e53f3
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 5659b85ea66765857217a48c74c115e24e30a57d292fa035c45f51565b7a0a478ce76e7750785ad11b1643eda23a40a05f683a83051b105eeaab14dbc133927d
|
7
|
+
data.tar.gz: 12b1b67b6273fb448ed28eeb74d4a755cab78edaa026cefe617426367b1a53657cc355dbbee1c012febded7c2b562879e01e5ef482e8620ab279053090604c73
|
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,84 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
6
|
+
|
7
|
+
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
8
|
+
|
9
|
+
## Our Standards
|
10
|
+
|
11
|
+
Examples of behavior that contributes to a positive environment for our community include:
|
12
|
+
|
13
|
+
* Demonstrating empathy and kindness toward other people
|
14
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
15
|
+
* Giving and gracefully accepting constructive feedback
|
16
|
+
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
17
|
+
* Focusing on what is best not just for us as individuals, but for the overall community
|
18
|
+
|
19
|
+
Examples of unacceptable behavior include:
|
20
|
+
|
21
|
+
* The use of sexualized language or imagery, and sexual attention or
|
22
|
+
advances of any kind
|
23
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
24
|
+
* Public or private harassment
|
25
|
+
* Publishing others' private information, such as a physical or email
|
26
|
+
address, without their explicit permission
|
27
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
28
|
+
professional setting
|
29
|
+
|
30
|
+
## Enforcement Responsibilities
|
31
|
+
|
32
|
+
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
33
|
+
|
34
|
+
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
35
|
+
|
36
|
+
## Scope
|
37
|
+
|
38
|
+
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
39
|
+
|
40
|
+
## Enforcement
|
41
|
+
|
42
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at derek.stride@shopify.com. All complaints will be reviewed and investigated promptly and fairly.
|
43
|
+
|
44
|
+
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
45
|
+
|
46
|
+
## Enforcement Guidelines
|
47
|
+
|
48
|
+
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
49
|
+
|
50
|
+
### 1. Correction
|
51
|
+
|
52
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
53
|
+
|
54
|
+
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
55
|
+
|
56
|
+
### 2. Warning
|
57
|
+
|
58
|
+
**Community Impact**: A violation through a single incident or series of actions.
|
59
|
+
|
60
|
+
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
61
|
+
|
62
|
+
### 3. Temporary Ban
|
63
|
+
|
64
|
+
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
65
|
+
|
66
|
+
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
67
|
+
|
68
|
+
### 4. Permanent Ban
|
69
|
+
|
70
|
+
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
71
|
+
|
72
|
+
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
73
|
+
|
74
|
+
## Attribution
|
75
|
+
|
76
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
|
77
|
+
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
78
|
+
|
79
|
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
|
80
|
+
|
81
|
+
[homepage]: https://www.contributor-covenant.org
|
82
|
+
|
83
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
84
|
+
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2024 derekstride
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,52 @@
|
|
1
|
+
# SqlTools
|
2
|
+
|
3
|
+
SqlTools is a collection of tools for working with SQL ASTs. It's the intersection of
|
4
|
+
[ruby_tree_sitter](https://github.com/faveod/ruby-tree-sitter/) &
|
5
|
+
[tree-sitter-sql](https://github.com/derekstride/tree-sitter-sql), letting you parse SQL queries and transform them into
|
6
|
+
semantic Ruby objects.
|
7
|
+
|
8
|
+
## Installation
|
9
|
+
|
10
|
+
If you're having trouble installing `ruby_tree_sitter` try installing the libraries for the latest supported version of
|
11
|
+
libtree-sitter.
|
12
|
+
|
13
|
+
```bash
|
14
|
+
git clone https://github.com/tree-sitter/tree-sitter
|
15
|
+
cd tree-sitter
|
16
|
+
git checkout tags/v0.22.6
|
17
|
+
make
|
18
|
+
sudo make install
|
19
|
+
```
|
20
|
+
|
21
|
+
To install the SQL parser run the rake task.
|
22
|
+
|
23
|
+
```bash
|
24
|
+
bundle exec rake treesitter:install
|
25
|
+
```
|
26
|
+
|
27
|
+
## Usage
|
28
|
+
|
29
|
+
```ruby
|
30
|
+
SqlTools.query_from_sql(<<~SQL)
|
31
|
+
SELECT id, name
|
32
|
+
FROM table_a
|
33
|
+
WHERE id > 10
|
34
|
+
AND id < 20
|
35
|
+
SQL
|
36
|
+
```
|
37
|
+
|
38
|
+
## Development
|
39
|
+
|
40
|
+
After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
41
|
+
|
42
|
+
## Contributing
|
43
|
+
|
44
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/DerekStride/sql_tools. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/DerekStride/sql_tools/blob/main/CODE_OF_CONDUCT.md).
|
45
|
+
|
46
|
+
## License
|
47
|
+
|
48
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
49
|
+
|
50
|
+
## Code of Conduct
|
51
|
+
|
52
|
+
Everyone interacting in the SqlTools project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/DerekStride/sql_tools/blob/main/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
@@ -0,0 +1,15 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "bundler/gem_tasks"
|
4
|
+
require "rake/testtask"
|
5
|
+
require "debug"
|
6
|
+
|
7
|
+
Rake::TestTask.new(:test) do |t|
|
8
|
+
t.libs << "test"
|
9
|
+
t.libs << "lib"
|
10
|
+
t.deps << "treesitter:install"
|
11
|
+
t.test_files = FileList["test/**/*_test.rb"]
|
12
|
+
end
|
13
|
+
|
14
|
+
|
15
|
+
task default: %i[test]
|
@@ -0,0 +1,64 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
|
3
|
+
require "fileutils"
|
4
|
+
require "optparse"
|
5
|
+
require "pathname"
|
6
|
+
|
7
|
+
app_root = if File.basename(__dir__) == "exe"
|
8
|
+
File.expand_path("..", __dir__)
|
9
|
+
else
|
10
|
+
File.expand_path(__dir__)
|
11
|
+
end
|
12
|
+
out = File.join(app_root, "treesitter")
|
13
|
+
|
14
|
+
options = {
|
15
|
+
revision: "cdb7cde9bf70b194ab8beb5069fbbc3c9640284e",
|
16
|
+
out:,
|
17
|
+
}
|
18
|
+
|
19
|
+
OptionParser.new do |o|
|
20
|
+
HELP = o
|
21
|
+
o.banner = "usage: install_tree_sitter_sql [options]"
|
22
|
+
o.on("--revision SHA", "The version of the repo to clone")
|
23
|
+
o.on("-o OUTDIR", "--out OUTDIR", "The destination directory for the parser library") do |dir|
|
24
|
+
Pathname.new(File.expand_path(dir))
|
25
|
+
end
|
26
|
+
o.on_tail("-h", "--help") { puts o; exit(1) }
|
27
|
+
end.parse!(ARGV, into: options)
|
28
|
+
|
29
|
+
target = if RbConfig::CONFIG["host_os"] =~ /mac|darwin/
|
30
|
+
File.join(options[:out], "sql.dylib")
|
31
|
+
else
|
32
|
+
File.join(options[:out], "sql.so")
|
33
|
+
end
|
34
|
+
|
35
|
+
return if File.exist?(target)
|
36
|
+
|
37
|
+
# Create the target directory if it doesn't exist
|
38
|
+
FileUtils.mkdir_p(options[:out]) unless File.exist?(options[:out])
|
39
|
+
|
40
|
+
def system!(*args)
|
41
|
+
system(*args) || abort("\n== Command #{args} failed ==\n#{HELP}")
|
42
|
+
end
|
43
|
+
|
44
|
+
FileUtils.chdir(File.join("/", "tmp")) do
|
45
|
+
repo_dir = "tree-sitter-sql-#{options[:revision]}"
|
46
|
+
unless File.exist?(repo_dir)
|
47
|
+
system! "git clone --depth=1 https://github.com/derekstride/tree-sitter-sql.git #{repo_dir}"
|
48
|
+
end
|
49
|
+
|
50
|
+
FileUtils.chdir(repo_dir) do
|
51
|
+
unless File.exist?("parser.so")
|
52
|
+
system! "git fetch origin #{options[:revision]}"
|
53
|
+
system! "git checkout #{options[:revision]}"
|
54
|
+
|
55
|
+
puts "Compiling..."
|
56
|
+
system! "cc -shared -fPIC -I./src src/parser.c src/scanner.c -o parser.so"
|
57
|
+
end
|
58
|
+
|
59
|
+
return if File.exist?(target)
|
60
|
+
|
61
|
+
puts "Copying parser.so to #{target}"
|
62
|
+
FileUtils.cp("parser.so", target)
|
63
|
+
end
|
64
|
+
end
|
@@ -0,0 +1,17 @@
|
|
1
|
+
module SqlTools
|
2
|
+
class CommonTableExpression
|
3
|
+
attr_reader :node
|
4
|
+
|
5
|
+
def initialize(node)
|
6
|
+
@node = node
|
7
|
+
end
|
8
|
+
|
9
|
+
def name = node.children.first.text.delete('`')
|
10
|
+
|
11
|
+
def view
|
12
|
+
@view ||= ViewVisitor.new(node.children[-2]).visit.view
|
13
|
+
end
|
14
|
+
|
15
|
+
def inspect = "#<class CommonTableExpression name=#{name.inspect}>"
|
16
|
+
end
|
17
|
+
end
|
@@ -0,0 +1,45 @@
|
|
1
|
+
module SqlTools
|
2
|
+
class Predicate
|
3
|
+
Binary = Struct.new(:left, :operator, :right) do
|
4
|
+
def to_s = "(#{left} #{operator} #{right})"
|
5
|
+
def inspect = to_s
|
6
|
+
end
|
7
|
+
|
8
|
+
class Builder
|
9
|
+
def initialize(query)
|
10
|
+
@query = query
|
11
|
+
end
|
12
|
+
|
13
|
+
def build(predicate)
|
14
|
+
case predicate
|
15
|
+
when Predicate::Binary
|
16
|
+
predicate.left = build(predicate.left)
|
17
|
+
predicate.right = build(predicate.right)
|
18
|
+
predicate
|
19
|
+
when TreeStand::Node
|
20
|
+
type_from_node(predicate)
|
21
|
+
else
|
22
|
+
raise "Unknown predicate: #{predicate}"
|
23
|
+
end
|
24
|
+
end
|
25
|
+
|
26
|
+
private
|
27
|
+
|
28
|
+
def type_from_node(node)
|
29
|
+
case node.type
|
30
|
+
when :field
|
31
|
+
table = if table_alias = node.find_node("(field (object_reference name: (identifier) @table_alias))")&.text
|
32
|
+
@query.object_alias_map.fetch(table_alias)
|
33
|
+
elsif @query.objects.size == 1
|
34
|
+
@query.objects.first
|
35
|
+
end
|
36
|
+
Column.new(table, node.name.text)
|
37
|
+
when :literal
|
38
|
+
node.text
|
39
|
+
else
|
40
|
+
raise "Unknown node type: #{node.type}"
|
41
|
+
end
|
42
|
+
end
|
43
|
+
end
|
44
|
+
end
|
45
|
+
end
|
@@ -0,0 +1,35 @@
|
|
1
|
+
module SqlTools
|
2
|
+
class PredicateFilter
|
3
|
+
def initialize(query)
|
4
|
+
@query = query
|
5
|
+
end
|
6
|
+
|
7
|
+
def filter(object)
|
8
|
+
@stack = []
|
9
|
+
filter_recursive(object, @query.predicate)
|
10
|
+
|
11
|
+
right = @stack.pop
|
12
|
+
|
13
|
+
while left = @stack.pop
|
14
|
+
predicate = Predicate::Binary.new(left, "AND", right)
|
15
|
+
right = predicate
|
16
|
+
end
|
17
|
+
|
18
|
+
right
|
19
|
+
end
|
20
|
+
|
21
|
+
private
|
22
|
+
|
23
|
+
def filter_recursive(object, predicate)
|
24
|
+
case predicate
|
25
|
+
when Predicate::Binary
|
26
|
+
@stack << predicate if filter_recursive(object, predicate.left) || filter_recursive(object, predicate.right)
|
27
|
+
false
|
28
|
+
when SqlTools::Column
|
29
|
+
predicate.table == object
|
30
|
+
else
|
31
|
+
raise "Unknown predicate type: #{predicate}"
|
32
|
+
end
|
33
|
+
end
|
34
|
+
end
|
35
|
+
end
|
@@ -0,0 +1,26 @@
|
|
1
|
+
module SqlTools
|
2
|
+
class PredicateVisitor < TreeStand::Visitor
|
3
|
+
attr_reader :stack
|
4
|
+
def initialize(node)
|
5
|
+
super(node)
|
6
|
+
@stack = []
|
7
|
+
end
|
8
|
+
|
9
|
+
def around_binary_expression(node)
|
10
|
+
@stack << Predicate::Binary.new(nil, node.operator.text, nil)
|
11
|
+
yield
|
12
|
+
@stack[-3].right = @stack.pop
|
13
|
+
@stack[-2].left = @stack.pop
|
14
|
+
end
|
15
|
+
|
16
|
+
def on_field(node)
|
17
|
+
parent = node.parent
|
18
|
+
# Case JOIN ON v.is_not_deleted
|
19
|
+
@stack << node if parent.type == :join || parent.type == :where
|
20
|
+
# Case JOIN ON _ AND v.is_not_deleted
|
21
|
+
@stack << node if parent.type == :binary_expression
|
22
|
+
end
|
23
|
+
|
24
|
+
def on_literal(node) = on_field(node)
|
25
|
+
end
|
26
|
+
end
|
@@ -0,0 +1,123 @@
|
|
1
|
+
module SqlTools
|
2
|
+
class Query
|
3
|
+
attr_accessor :select, :from, :join_nodes
|
4
|
+
attr_reader :common_table_expressions
|
5
|
+
|
6
|
+
def initialize
|
7
|
+
@common_table_expressions = {}
|
8
|
+
@join_nodes = []
|
9
|
+
end
|
10
|
+
|
11
|
+
def selections
|
12
|
+
terms = select.query(<<~QUERY)
|
13
|
+
(select_expression
|
14
|
+
(term
|
15
|
+
value: [
|
16
|
+
(field
|
17
|
+
(object_reference name: (identifier) @table_alias)?
|
18
|
+
name: (identifier) @column_name)
|
19
|
+
(invocation) @invocation
|
20
|
+
(all_fields
|
21
|
+
(object_reference name: (identifier) @table_alias)?) @all_fields
|
22
|
+
]
|
23
|
+
alias: (identifier)? @selection_name))
|
24
|
+
QUERY
|
25
|
+
terms.map! do |captures|
|
26
|
+
selection_name = captures["selection_name"]&.text || captures["column_name"]&.text
|
27
|
+
|
28
|
+
if captures["all_fields"]
|
29
|
+
table = if table_alias = captures["table_alias"]
|
30
|
+
object_alias_map[table_alias.text]
|
31
|
+
elsif objects.size == 1
|
32
|
+
objects.first
|
33
|
+
end
|
34
|
+
Selection::AllFields.new(table)
|
35
|
+
elsif table_alias = captures["table_alias"]
|
36
|
+
table = object_alias_map[table_alias.text]
|
37
|
+
column_name = captures["column_name"].text
|
38
|
+
Selection::Column.new(selection_name, Column.new(table, column_name))
|
39
|
+
elsif (column_name = captures["column_name"]&.text) && objects.size == 1
|
40
|
+
table = objects.first
|
41
|
+
Selection::Column.new(selection_name, Column.new(table, column_name))
|
42
|
+
elsif invocation = captures["invocation"]
|
43
|
+
Selection::Invocation.new(selection_name, invocation)
|
44
|
+
else
|
45
|
+
raise "Unknown selection type"
|
46
|
+
end
|
47
|
+
end
|
48
|
+
end
|
49
|
+
|
50
|
+
def joins
|
51
|
+
join_nodes.map do |join_node|
|
52
|
+
object_name = join_node.find_node(<<~QUERY).text
|
53
|
+
(join
|
54
|
+
(relation
|
55
|
+
(object_reference name: (identifier) @object_name)))
|
56
|
+
QUERY
|
57
|
+
|
58
|
+
filter = PredicateFilter.new(self)
|
59
|
+
object = object_alias_map[object_name]
|
60
|
+
predicate = filter.filter(object)
|
61
|
+
|
62
|
+
if join_node.children.any? { |child| child.type == :keyword_left }
|
63
|
+
LeftJoin.new(object, predicate)
|
64
|
+
else
|
65
|
+
InnerJoin.new(object, predicate)
|
66
|
+
end
|
67
|
+
end
|
68
|
+
end
|
69
|
+
|
70
|
+
def relations
|
71
|
+
objects.each_with_object({}) do |object, map|
|
72
|
+
map[object] ||= []
|
73
|
+
map[object] << predicates.select do |p|
|
74
|
+
(p.left.is_a?(Column) && p.left.table == object) ||
|
75
|
+
(p.right.is_a?(Column) && p.right.table == object)
|
76
|
+
end
|
77
|
+
end
|
78
|
+
end
|
79
|
+
|
80
|
+
def predicate
|
81
|
+
@predicate ||= begin
|
82
|
+
nodes = from.query(<<~QUERY).map { |captures| captures["predicate"] }
|
83
|
+
(from
|
84
|
+
(join
|
85
|
+
predicate: (_) @predicate))
|
86
|
+
(where
|
87
|
+
predicate: (_) @predicate)
|
88
|
+
QUERY
|
89
|
+
|
90
|
+
builder = Predicate::Builder.new(self)
|
91
|
+
predicates = nodes.flat_map do |predicate|
|
92
|
+
visitor = PredicateVisitor.new(predicate).visit
|
93
|
+
binding.b unless visitor.stack.size == 1
|
94
|
+
builder.build(visitor.stack.last)
|
95
|
+
end
|
96
|
+
|
97
|
+
right = predicates.pop
|
98
|
+
|
99
|
+
# This needs to pluck the left & right from binary expressions & rebuild the tree.
|
100
|
+
# TODO: maybe this is the rotate algorithm, TBD
|
101
|
+
while left = predicates.pop
|
102
|
+
predicate = Predicate::Binary.new(left, "AND", right)
|
103
|
+
right = predicate
|
104
|
+
end
|
105
|
+
|
106
|
+
right
|
107
|
+
end
|
108
|
+
end
|
109
|
+
|
110
|
+
def objects = object_alias_map.values.to_set
|
111
|
+
|
112
|
+
def object_alias_map
|
113
|
+
@table_alias_map ||= @from.query("(relation) @relation").each_with_object({}) do |captures, map|
|
114
|
+
relation = captures["relation"]
|
115
|
+
relation_name = relation.children.first.name.text
|
116
|
+
relation_alias = relation.respond_to?(:alias) ? relation.alias.text : relation_name
|
117
|
+
|
118
|
+
map[relation_alias] = common_table_expressions[relation_name] || Table.new(relation_name, relation_alias)
|
119
|
+
map[relation_name] = map[relation_alias]
|
120
|
+
end
|
121
|
+
end
|
122
|
+
end
|
123
|
+
end
|
@@ -0,0 +1,28 @@
|
|
1
|
+
module SqlTools
|
2
|
+
class QueryVisitor < TreeStand::Visitor
|
3
|
+
attr_reader :query
|
4
|
+
|
5
|
+
def initialize(node)
|
6
|
+
super(node)
|
7
|
+
@ctes = {}
|
8
|
+
@query = Query.new
|
9
|
+
end
|
10
|
+
|
11
|
+
def on_cte(node)
|
12
|
+
cte = CommonTableExpression.new(node)
|
13
|
+
@query.common_table_expressions[cte.name] = cte
|
14
|
+
end
|
15
|
+
|
16
|
+
def on_select(node)
|
17
|
+
@query.select = node
|
18
|
+
end
|
19
|
+
|
20
|
+
def on_from(node)
|
21
|
+
@query.from = node
|
22
|
+
end
|
23
|
+
|
24
|
+
def on_join(node)
|
25
|
+
@query.join_nodes << node
|
26
|
+
end
|
27
|
+
end
|
28
|
+
end
|
data/lib/sql_tools.rb
ADDED
@@ -0,0 +1,24 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "tree_stand"
|
4
|
+
require "zeitwerk"
|
5
|
+
|
6
|
+
loader = Zeitwerk::Loader.for_gem
|
7
|
+
loader.setup
|
8
|
+
|
9
|
+
module SqlTools
|
10
|
+
class Error < StandardError; end
|
11
|
+
|
12
|
+
class << self
|
13
|
+
def query_from_sql(sql) = query_from_tree(tree_from_sql(sql))
|
14
|
+
def query_from_tree(tree) = SqlTools::QueryVisitor.new(tree.root_node).visit.query
|
15
|
+
def tree_from_sql(sql) = parser.parse_string(sql)
|
16
|
+
def parser = @parser ||= TreeStand::Parser.new("sql")
|
17
|
+
end
|
18
|
+
|
19
|
+
Table = Data.define(:name, :alias)
|
20
|
+
Column = Data.define(:table, :name) do
|
21
|
+
def to_s = "#{table.name}.#{name}"
|
22
|
+
def inspect = to_s
|
23
|
+
end
|
24
|
+
end
|
@@ -0,0 +1,11 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "fileutils"
|
4
|
+
|
5
|
+
namespace :treesitter do
|
6
|
+
task :install do
|
7
|
+
app_root = File.expand_path("..", __dir__)
|
8
|
+
exe = File.join(app_root, "exe", "install_tree_sitter_sql")
|
9
|
+
system(exe) || abort("\n== Command #{exe} failed ==")
|
10
|
+
end
|
11
|
+
end
|
metadata
ADDED
@@ -0,0 +1,94 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: sql_tools
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- derekstride
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
11
|
+
date: 2024-07-03 00:00:00.000000000 Z
|
12
|
+
dependencies:
|
13
|
+
- !ruby/object:Gem::Dependency
|
14
|
+
name: ruby_tree_sitter
|
15
|
+
requirement: !ruby/object:Gem::Requirement
|
16
|
+
requirements:
|
17
|
+
- - "~>"
|
18
|
+
- !ruby/object:Gem::Version
|
19
|
+
version: '1.0'
|
20
|
+
type: :runtime
|
21
|
+
prerelease: false
|
22
|
+
version_requirements: !ruby/object:Gem::Requirement
|
23
|
+
requirements:
|
24
|
+
- - "~>"
|
25
|
+
- !ruby/object:Gem::Version
|
26
|
+
version: '1.0'
|
27
|
+
- !ruby/object:Gem::Dependency
|
28
|
+
name: zeitwerk
|
29
|
+
requirement: !ruby/object:Gem::Requirement
|
30
|
+
requirements:
|
31
|
+
- - ">="
|
32
|
+
- !ruby/object:Gem::Version
|
33
|
+
version: '0'
|
34
|
+
type: :runtime
|
35
|
+
prerelease: false
|
36
|
+
version_requirements: !ruby/object:Gem::Requirement
|
37
|
+
requirements:
|
38
|
+
- - ">="
|
39
|
+
- !ruby/object:Gem::Version
|
40
|
+
version: '0'
|
41
|
+
description:
|
42
|
+
email:
|
43
|
+
- derek@stride.host
|
44
|
+
executables:
|
45
|
+
- install_tree_sitter_sql
|
46
|
+
extensions: []
|
47
|
+
extra_rdoc_files: []
|
48
|
+
files:
|
49
|
+
- CODE_OF_CONDUCT.md
|
50
|
+
- LICENSE.txt
|
51
|
+
- README.md
|
52
|
+
- Rakefile
|
53
|
+
- exe/install_tree_sitter_sql
|
54
|
+
- lib/sql_tools.rb
|
55
|
+
- lib/sql_tools/common_table_expression.rb
|
56
|
+
- lib/sql_tools/inner_join.rb
|
57
|
+
- lib/sql_tools/left_join.rb
|
58
|
+
- lib/sql_tools/predicate.rb
|
59
|
+
- lib/sql_tools/predicate_filter.rb
|
60
|
+
- lib/sql_tools/predicate_visitor.rb
|
61
|
+
- lib/sql_tools/query.rb
|
62
|
+
- lib/sql_tools/query_visitor.rb
|
63
|
+
- lib/sql_tools/relation.rb
|
64
|
+
- lib/sql_tools/selection.rb
|
65
|
+
- lib/sql_tools/version.rb
|
66
|
+
- rakelib/treesitter.rake
|
67
|
+
homepage: https://github.com/derekstride/sql_tools
|
68
|
+
licenses:
|
69
|
+
- MIT
|
70
|
+
metadata:
|
71
|
+
allowed_push_host: https://rubygems.org
|
72
|
+
homepage_uri: https://github.com/derekstride/sql_tools
|
73
|
+
source_code_uri: https://github.com/derekstride/sql_tools
|
74
|
+
changelog_uri: https://github.com/derekstride/sql_tools
|
75
|
+
post_install_message:
|
76
|
+
rdoc_options: []
|
77
|
+
require_paths:
|
78
|
+
- lib
|
79
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
80
|
+
requirements:
|
81
|
+
- - ">="
|
82
|
+
- !ruby/object:Gem::Version
|
83
|
+
version: '3.2'
|
84
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
85
|
+
requirements:
|
86
|
+
- - ">="
|
87
|
+
- !ruby/object:Gem::Version
|
88
|
+
version: '0'
|
89
|
+
requirements: []
|
90
|
+
rubygems_version: 3.5.11
|
91
|
+
signing_key:
|
92
|
+
specification_version: 4
|
93
|
+
summary: Collection of tools for working with SQL ASTs.
|
94
|
+
test_files: []
|