simplest_sql_parser 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: dee7f0482eb748f492eece192b3f3cc2d36b4a1122887482c3358c49c6ff0846
4
+ data.tar.gz: 393453ac8a26300b12fefdb307dc98f56825b6e5c605576c34ba933f60cc268b
5
+ SHA512:
6
+ metadata.gz: 8d913cdd3c0cc486d02465818d570bf8859fb3d8d9dc9d0f0d14929c665d68ed530629c953c2ad9cff7190711a03e075a79e49b8479f2c1d46fbe448179dedc8
7
+ data.tar.gz: 9c05af53d6558d1eb3efe8cb9d60c17f9d776d43e2e46f53415d3b05c5250a810a5e74eb3e71f4669177f2cbb8d94cec2a6c0a5fa12c77d0a188332abc338302
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-06-21
4
+
5
+ - Initial release
@@ -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 heyjudejudejude1968@gmail.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/Gemfile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in simplest_sql_parser.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.21"
13
+
14
+ gem "rexical", "~> 1.0"
15
+
16
+ gem "racc", "~> 1.7"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 kudojp
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/Makefile ADDED
@@ -0,0 +1,12 @@
1
+ .PHONY: spec
2
+ spec: rex racc
3
+
4
+ .PHONY: rex
5
+ rex:
6
+ bundle exec rex lib/simplest_sql_parser/lexical_scanner.rex
7
+ bundle exec rspec spec/lexical_scanner_spec.rb
8
+
9
+ .PHONY: racc
10
+ racc:
11
+ bundle exec racc lib/simplest_sql_parser/parser.racc &&\
12
+ bundle exec rspec spec/parser_spec.rb
data/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # SimplestSqlParser
2
+
3
+ SimplestSqlParser is a toy SQL parser written in Ruby.
4
+ Currently it can parse queries composed only of `SELECT`, `FROM`, and `WHERE` clauses.
5
+
6
+ - `SELECT name, address, age FROM table WHERE id = 12` (SELECT multiple columns)
7
+ - `SELECT * FROM table WHERE id = 12` (SELECT all columns)
8
+ - `SELECT COUNT(*) FROM table WHERE id = 12` (COUNT function)
9
+
10
+ ## Installation
11
+
12
+ Add this line to your application's Gemfile:
13
+
14
+ ```ruby
15
+ gem 'simplest_sql_parser'
16
+ ```
17
+
18
+ And then execute:
19
+
20
+ ```
21
+ $ bundle install
22
+ ```
23
+
24
+ Or install it yourself as:
25
+
26
+ ```
27
+ $ gem install simplest_sql_parser
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ ```rb
33
+ ast = SimplestSqlParser.parse("Select name FROM table")
34
+ # And do something creative with ast!
35
+ ```
36
+
37
+ ## Development
38
+
39
+ To update the lex scanner `SimplestSQLParser::LexicalScanner`,
40
+ 1. Update `lib/simplest_sql_parser/lexical_scanner.rex`
41
+ 2. Run $`bundle exec rex lib/simplest_sql_parser/lexical_scanner.rex`
42
+ 3. Test your implementation with `bundle exec rspec spec/lexical_scanner_spec.rb`
43
+
44
+
45
+ To update the parser `SimplestSQLParser::Parser`,
46
+ 1. Update `lib/simplest_sql_parser/parser.racc`
47
+ 2. Run $`bundle exec racc lib/simplest_sql_parser/parser.rex`
48
+ 3. Test your implementation with `bundle exec rspec spec/parser_spec.rb`
49
+
50
+ ## Contributing
51
+
52
+ Bug reports and pull requests are welcome on GitHub at https://github.com/kudojp/simplest_sql_parser. 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/[USERNAME]/simplest_sql_parser/blob/master/CODE_OF_CONDUCT.md).
53
+
54
+ ## License
55
+
56
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
57
+
58
+ ## Code of Conduct
59
+
60
+ Everyone interacting in the SimplestSqlParser project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/simplest_sql_parser/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,21 @@
1
+ require_relative "node"
2
+
3
+ module AST
4
+ class ColumnNode < Node
5
+ class UnsupportedTypeError < StandardError; end
6
+
7
+ TYPES = [:single_col, :asterisk].freeze
8
+ attr_reader :type, :name
9
+
10
+ def initialize(name:, type: :single_col)
11
+ raise UnsupportedTypeError unless TYPES.include? type
12
+
13
+ @type = type # single_col
14
+ @name = name # nil when type == :asterisk
15
+ end
16
+
17
+ def list_attributes_without_child
18
+ [:type, :name]
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,27 @@
1
+ require_relative "node"
2
+
3
+ module AST
4
+ class ConditionNode < Node
5
+ class UnsupportedOperatorError < StandardError; end
6
+
7
+ OPERATORS = [:equals, :larger_than].freeze # TODO: add more operators
8
+
9
+ attr_reader :operator, :left, :right
10
+
11
+ def initialize(operator:, left:, right:)
12
+ raise UnsupportedOperatorError unless OPERATORS.include? operator
13
+
14
+ @operator = operator
15
+ @left = left
16
+ @right = right
17
+ end
18
+
19
+ def list_attributes_without_child
20
+ [:operator]
21
+ end
22
+
23
+ def list_attributes_of_single_child_node
24
+ [:left, :right]
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,15 @@
1
+ require_relative "node"
2
+
3
+ module AST
4
+ class ExpressionNode < Node
5
+ attr_reader :value
6
+
7
+ def initialize(value:)
8
+ @value = value
9
+ end
10
+
11
+ def list_attributes_without_child
12
+ [:value]
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,15 @@
1
+ require_relative "node"
2
+
3
+ module AST
4
+ class FromClauseNode < Node
5
+ attr_reader :table
6
+
7
+ def initialize(table:)
8
+ @table = table
9
+ end
10
+
11
+ def list_attributes_of_single_child_node
12
+ [:table]
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,25 @@
1
+ require_relative "node"
2
+
3
+ module AST
4
+ class FunctionNode < Node
5
+ class UnsupportedTypeError; end
6
+
7
+ TYPES = [:count] # TODO: add other types (:max, etc)
8
+ attr_reader :type, :args
9
+
10
+ def initialize(type:, args: [])
11
+ raise UnsupportedTypeError unless TYPES.include? type
12
+
13
+ @type = type
14
+ @args = args
15
+ end
16
+
17
+ def list_attributes_without_child
18
+ [:type]
19
+ end
20
+
21
+ def list_attributes_of_multiple_child_nodes
22
+ [:args]
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,80 @@
1
+ module AST
2
+ class Node # used as an abstract class
3
+ # This should be overwritten in each node if necessary.
4
+ def list_attributes_without_child
5
+ []
6
+ # ["attr1", "attr2"]
7
+ end
8
+
9
+ # This should be overwritten in each node if necessary.
10
+ def list_attributes_of_single_child_node
11
+ []
12
+ # [:attr3, attr4]
13
+ end
14
+
15
+ # This should be overwritten in each node if necessary.
16
+ def list_attributes_of_multiple_child_nodes
17
+ []
18
+ # [:attr5, attr6]
19
+ end
20
+
21
+ # used for debugging.
22
+ def self_and_descendants
23
+ attributes = list_attributes_without_child.map { |attr_sym| "#{attr_sym}=#{send(attr_sym)}" }.join ","
24
+
25
+ descendants = {}
26
+
27
+ list_attributes_of_single_child_node.each do |attr_sym|
28
+ descendants[attr_sym.to_s] = send(attr_sym)&.self_and_descendants
29
+ end
30
+
31
+ list_attributes_of_multiple_child_nodes.each do |attr_sym|
32
+ descendants[attr_sym.to_s] = send(attr_sym)&.map { |attribute| attribute.self_and_descendants }
33
+ end
34
+
35
+ { "#{self.class}(#{attributes})" => descendants }
36
+ end
37
+ end
38
+ end
39
+
40
+ =begin
41
+ QueryNode.new
42
+ @select: SelectClauseNode.new
43
+ @columns: Array.new
44
+ - SelectedColumnNode.new # name
45
+ @alias_name: String.new
46
+ @col_def: ColumnNode.new
47
+ @type: :single_col
48
+ @name: "name"
49
+ - SelectedColumnNode.new # *
50
+ @alias_name: String.new
51
+ @col_def: ColumnNode.new
52
+ @type: :asterisk
53
+ @name: nil
54
+ - SelectedColumnNode.new # COUNT(name)
55
+ @alias_name: String.new
56
+ @col_def: FunctionNode.new
57
+ @type: :count
58
+ @args: Array.new
59
+ - ColumnNode.new
60
+ @type: :single_col
61
+ @name: "name"
62
+ @from: FromClauseNode.new
63
+ @table: TableNode.new
64
+ @table_def: ExpressionNode.new
65
+ @alias_name: String.new
66
+ @where: WhereClauseNode.new
67
+ @predicate: Array.new
68
+ - ConditionNode.new
69
+ @operator: :equals
70
+ @left: ExpressionNode.new
71
+ @right: ExpressionNode.new
72
+ - EqualsConditionNode.new
73
+ @operator: :larger_than
74
+ @left: ExpressionNode.new
75
+ @right: ExpressionNode.new
76
+
77
+ Maybe,,
78
+ - I should create separate classes for each ExpressionNode depending on where it is used??
79
+ - I should create a parent class `ClauseNode` for SelectClauseNode, FromClauseNode, and WhereClauseNode.
80
+ =end
@@ -0,0 +1,17 @@
1
+ require_relative "node"
2
+
3
+ module AST
4
+ class QueryNode < Node
5
+ attr_reader :select_clause, :from_clause, :where_clause
6
+
7
+ def initialize(select_clause: nil, from_clause: nil, where_clause: nil)
8
+ @select_clause = select_clause
9
+ @from_clause = from_clause
10
+ @where_clause = where_clause
11
+ end
12
+
13
+ def list_attributes_of_single_child_node
14
+ [:select_clause, :from_clause, :where_clause]
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,15 @@
1
+ require_relative "node"
2
+
3
+ module AST
4
+ class SelectClauseNode < Node
5
+ attr_reader :selected_columns
6
+
7
+ def initialize(selected_columns:)
8
+ @selected_columns = selected_columns # array of ColumnNode instances
9
+ end
10
+
11
+ def list_attributes_of_multiple_child_nodes
12
+ [:selected_columns]
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,20 @@
1
+ require_relative "node"
2
+
3
+ module AST
4
+ class SelectedColumnNode < Node
5
+ attr_reader :alias_name, :col_def
6
+
7
+ def initialize(col_def:, alias_name: nil)
8
+ @col_def = col_def
9
+ @alias_name = alias_name
10
+ end
11
+
12
+ def list_attributes_without_child
13
+ [:alias_name]
14
+ end
15
+
16
+ def list_attributes_of_single_child_node
17
+ [:col_def]
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,20 @@
1
+ require_relative "node"
2
+
3
+ module AST
4
+ class TableNode < Node
5
+ attr_reader :table_def, :alias_name
6
+
7
+ def initialize(table_def:, alias_name: nil)
8
+ @table_def = table_def # For now, this is ExpressionNode
9
+ @alias_name = alias_name
10
+ end
11
+
12
+ def list_attributes_without_child
13
+ [:alias_name]
14
+ end
15
+
16
+ def list_attributes_of_single_child_node
17
+ [:table_def]
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,15 @@
1
+ require_relative "node"
2
+
3
+ module AST
4
+ class WhereClauseNode < Node
5
+ attr_reader :predicate
6
+
7
+ def initialize(predicate:)
8
+ @predicate = predicate # array of ConditionNode instances
9
+ end
10
+
11
+ def list_attributes_of_multiple_child_nodes
12
+ [:predicate]
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,37 @@
1
+ # ref. https://github.com/tenderlove/rexical/blob/master/DOCUMENTATION.ja.rdoc
2
+
3
+ class SimplestSqlParser::LexicalScanner
4
+ option
5
+ ignorecase
6
+ macro
7
+ BLANK \s+
8
+ WORD [a-zA-Z]\w*
9
+ NUMBER \d+(\.\d+)?
10
+
11
+ rule
12
+ # Each line should be formatted as:
13
+ # `start_state pattern { action }
14
+ #
15
+ # - In action should return [:TOKEN_SYMBOL, value] (ref. https://docs.ruby-lang.org/en/3.2/Racc/Parser.html#method-i-next_token)
16
+
17
+ {BLANK} # do nothing
18
+
19
+ # keywords
20
+ ## keyword of statements
21
+ SELECT { [:SELECT, text] }
22
+ FROM { [:FROM, text] }
23
+ WHERE { [:WHERE, text] }
24
+
25
+ ## keyword of functions
26
+ COUNT { [:COUNT, text] }
27
+
28
+ # tokens
29
+ , { [:COMMA, text] }
30
+ \* { [:ASTERISK, text] }
31
+ = {[:EQUALS, text]}
32
+ \( {[:PARENTHESIS_LEFT, text]}
33
+ \) {[:PARENTHESIS_RIGHT, text]}
34
+
35
+ # identifiers
36
+ {WORD} { [:IDENTIFIER, text] }
37
+ {NUMBER} {[:IDENTIFIER, text.to_f]}
@@ -0,0 +1,110 @@
1
+ #--
2
+ # DO NOT MODIFY!!!!
3
+ # This file is automatically generated by rex 1.0.7
4
+ # from lexical definition file "lib/simplest_sql_parser/lexical_scanner.rex".
5
+ #++
6
+
7
+ require 'racc/parser'
8
+ # ref. https://github.com/tenderlove/rexical/blob/master/DOCUMENTATION.ja.rdoc
9
+
10
+ class SimplestSqlParser::LexicalScanner < Racc::Parser
11
+ require 'strscan'
12
+
13
+ class ScanError < StandardError ; end
14
+
15
+ attr_reader :lineno
16
+ attr_reader :filename
17
+ attr_accessor :state
18
+
19
+ def scan_setup(str)
20
+ @ss = StringScanner.new(str)
21
+ @lineno = 1
22
+ @state = nil
23
+ end
24
+
25
+ def action
26
+ yield
27
+ end
28
+
29
+ def scan_str(str)
30
+ scan_setup(str)
31
+ do_parse
32
+ end
33
+ alias :scan :scan_str
34
+
35
+ def load_file( filename )
36
+ @filename = filename
37
+ File.open(filename, "r") do |f|
38
+ scan_setup(f.read)
39
+ end
40
+ end
41
+
42
+ def scan_file( filename )
43
+ load_file(filename)
44
+ do_parse
45
+ end
46
+
47
+
48
+ def next_token
49
+ return if @ss.eos?
50
+
51
+ # skips empty actions
52
+ until token = _next_token or @ss.eos?; end
53
+ token
54
+ end
55
+
56
+ def _next_token
57
+ text = @ss.peek(1)
58
+ @lineno += 1 if text == "\n"
59
+ token = case @state
60
+ when nil
61
+ case
62
+ when (text = @ss.scan(/\s+/i))
63
+ ;
64
+
65
+ when (text = @ss.scan(/SELECT/i))
66
+ action { [:SELECT, text] }
67
+
68
+ when (text = @ss.scan(/FROM/i))
69
+ action { [:FROM, text] }
70
+
71
+ when (text = @ss.scan(/WHERE/i))
72
+ action { [:WHERE, text] }
73
+
74
+ when (text = @ss.scan(/COUNT/i))
75
+ action { [:COUNT, text] }
76
+
77
+ when (text = @ss.scan(/,/i))
78
+ action { [:COMMA, text] }
79
+
80
+ when (text = @ss.scan(/\*/i))
81
+ action { [:ASTERISK, text] }
82
+
83
+ when (text = @ss.scan(/=/i))
84
+ action {[:EQUALS, text]}
85
+
86
+ when (text = @ss.scan(/\(/i))
87
+ action {[:PARENTHESIS_LEFT, text]}
88
+
89
+ when (text = @ss.scan(/\)/i))
90
+ action {[:PARENTHESIS_RIGHT, text]}
91
+
92
+ when (text = @ss.scan(/[a-zA-Z]\w*/i))
93
+ action { [:IDENTIFIER, text] }
94
+
95
+ when (text = @ss.scan(/\d+(\.\d+)?/i))
96
+ action {[:IDENTIFIER, text.to_f]}
97
+
98
+
99
+ else
100
+ text = @ss.string[@ss.pos .. -1]
101
+ raise ScanError, "can not match: '" + text + "'"
102
+ end # if
103
+
104
+ else
105
+ raise ScanError, "undefined state: '" + state.to_s + "'"
106
+ end # case state
107
+ token
108
+ end # def _next_token
109
+
110
+ end # class
@@ -0,0 +1,65 @@
1
+ class SimplestSqlParser::Parser
2
+
3
+ # ref. https://i.loveruby.net/ja/projects/racc/doc/grammar.html
4
+ rule
5
+ # Each line should be formatted as:
6
+ # `target : pattern1 | pattern2 { action_block }`
7
+ #
8
+ # - pattern should be a composed of (`next_token[0]`, another target)
9
+ # - In action, substitute the generated AST node into `result` with `val[0] = next_token[1]`
10
+
11
+ # MEMO: The first line in the rule has a special meaning.only the program has to be finally reduced down into the first line.
12
+ # Every rule has to be reduced down to this target.
13
+ query : select_clause {result = AST::QueryNode.new(select_clause: val[0])}
14
+ | select_clause from_clause {result = AST::QueryNode.new(select_clause: val[0], from_clause: val[1])} # TODO: accept from, where, etc.
15
+ | select_clause from_clause where_clause {result = AST::QueryNode.new(select_clause: val[0], from_clause: val[1], where_clause: val[2])} # TODO: accept from, where, etc.
16
+
17
+ select_clause : SELECT selected_columns { result = AST::SelectClauseNode.new(selected_columns: val[1])} # TODO: accept multiple columns
18
+
19
+ selected_columns: selected_column { result = [val[0]] }
20
+ | selected_columns COMMA selected_column { result = val[0] + [val[2]] }
21
+
22
+ selected_column : column_node { result = AST::SelectedColumnNode.new(col_def: val[0]) }
23
+ | function_node { result = AST::SelectedColumnNode.new(col_def: val[0]) }
24
+
25
+ column_node : IDENTIFIER { result = AST::ColumnNode.new(type: :single_col, name: val[0])}
26
+ | ASTERISK { result = AST::ColumnNode.new(type: :asterisk, name: nil) }
27
+
28
+ function_node : COUNT PARENTHESIS_LEFT arg_node PARENTHESIS_RIGHT { result = AST::FunctionNode.new(type: :count, args: [val[2]])}
29
+ # | MAX PARENTHESIS_LEFT IDENTIFIER PARENTHESIS_RIGHT {}
30
+
31
+ arg_node : column_node
32
+ | function_node
33
+
34
+ from_clause : FROM expression { result = AST::FromClauseNode.new(table: AST::TableNode.new(table_def: val[1])) }
35
+
36
+ where_clause : WHERE predicate { result = AST::WhereClauseNode.new(predicate: val[1])}
37
+
38
+ predicate : condition { result = [val[0]] }
39
+ # | predicate AND condition {}
40
+
41
+ condition : selected_column EQUALS expression { result = AST::ConditionNode.new(operator: :equals, left: val[0], right: val[2]) }
42
+ # | selected_column LARGER_THAN expression { result = AST::ConditionNode.new(operator: :equals, left: val[0], right: val[2]) }
43
+
44
+ expression : IDENTIFIER {result = AST::ExpressionNode.new(value: val[0])}
45
+
46
+ ---- header
47
+ Dir[File.join(File.dirname(__FILE__), "ast/*.rb")].each {|file| require file }
48
+
49
+ ---- inner
50
+ # innerの内容はそのまま生成されたparser.tab.rbファイル内のParserクラス内でmodule_evalされる。
51
+ # ref. https://i.loveruby.net/ja/projects/racc/doc/parser.html#Racc%3a%3aParser-yyparse
52
+
53
+ def initialize(query)
54
+ @scanner = SimplestSqlParser::LexicalScanner.new
55
+ @scanner.scan_setup(query)
56
+ end
57
+
58
+ # #next_token はここで必ず実装する必要がある。
59
+ def next_token
60
+ @scanner.next_token
61
+ end
62
+
63
+ ---- footer
64
+ # footerの内容はそのまま生成されたparser.tab.rbファイルの下にコピーされる。
65
+ # ruby parser.tab.rb で直にファイルを実行する際に Parserクラスを使って何かをするときなどに使える。
@@ -0,0 +1,289 @@
1
+ #
2
+ # DO NOT MODIFY!!!!
3
+ # This file is automatically generated by Racc 1.7.1
4
+ # from Racc grammar file "".
5
+ #
6
+
7
+ require 'racc/parser.rb'
8
+
9
+ Dir[File.join(File.dirname(__FILE__), "ast/*.rb")].each {|file| require file }
10
+
11
+ module SimplestSqlParser
12
+ class Parser < Racc::Parser
13
+
14
+ module_eval(<<'...end parser.racc/module_eval...', 'parser.racc', 50)
15
+ # innerの内容はそのまま生成されたparser.tab.rbファイル内のParserクラス内でmodule_evalされる。
16
+ # ref. https://i.loveruby.net/ja/projects/racc/doc/parser.html#Racc%3a%3aParser-yyparse
17
+
18
+ def initialize(query)
19
+ @scanner = SimplestSqlParser::LexicalScanner.new
20
+ @scanner.scan_setup(query)
21
+ end
22
+
23
+ # #next_token はここで必ず実装する必要がある。
24
+ def next_token
25
+ @scanner.next_token
26
+ end
27
+
28
+ ...end parser.racc/module_eval...
29
+ ##### State transition tables begin ###
30
+
31
+ racc_action_table = [
32
+ 11, 12, 13, 11, 12, 13, 11, 12, 13, 11,
33
+ 12, 13, 3, 4, 6, 14, 16, 18, 19, 20,
34
+ 28, 29, 18 ]
35
+
36
+ racc_action_check = [
37
+ 3, 3, 3, 16, 16, 16, 19, 19, 19, 20,
38
+ 20, 20, 0, 1, 2, 4, 5, 6, 7, 13,
39
+ 23, 25, 28 ]
40
+
41
+ racc_action_pointer = [
42
+ 10, 13, 5, -4, 15, 6, 13, 15, nil, nil,
43
+ nil, nil, nil, 12, nil, nil, -1, nil, nil, 2,
44
+ 5, nil, nil, 9, nil, 13, nil, nil, 18, nil,
45
+ nil ]
46
+
47
+ racc_action_default = [
48
+ -19, -19, -1, -19, -19, -2, -19, -4, -5, -7,
49
+ -8, -9, -10, -19, 31, -3, -19, -14, -18, -19,
50
+ -19, -15, -16, -19, -6, -19, -12, -13, -19, -11,
51
+ -17 ]
52
+
53
+ racc_goto_table = [
54
+ 17, 8, 1, 2, 5, 15, 7, 26, 27, 25,
55
+ 21, 22, nil, nil, 23, nil, nil, 24, nil, nil,
56
+ nil, nil, 30 ]
57
+
58
+ racc_goto_check = [
59
+ 10, 6, 1, 2, 3, 4, 5, 7, 8, 9,
60
+ 11, 12, nil, nil, 6, nil, nil, 6, nil, nil,
61
+ nil, nil, 10 ]
62
+
63
+ racc_goto_pointer = [
64
+ nil, 2, 3, 2, 0, 3, -2, -13, -12, -11,
65
+ -6, -6, -5 ]
66
+
67
+ racc_goto_default = [
68
+ nil, nil, nil, nil, nil, nil, nil, 9, 10, nil,
69
+ nil, nil, nil ]
70
+
71
+ racc_reduce_table = [
72
+ 0, 0, :racc_error,
73
+ 1, 13, :_reduce_1,
74
+ 2, 13, :_reduce_2,
75
+ 3, 13, :_reduce_3,
76
+ 2, 14, :_reduce_4,
77
+ 1, 17, :_reduce_5,
78
+ 3, 17, :_reduce_6,
79
+ 1, 18, :_reduce_7,
80
+ 1, 18, :_reduce_8,
81
+ 1, 19, :_reduce_9,
82
+ 1, 19, :_reduce_10,
83
+ 4, 20, :_reduce_11,
84
+ 1, 21, :_reduce_none,
85
+ 1, 21, :_reduce_none,
86
+ 2, 15, :_reduce_14,
87
+ 2, 16, :_reduce_15,
88
+ 1, 23, :_reduce_16,
89
+ 3, 24, :_reduce_17,
90
+ 1, 22, :_reduce_18 ]
91
+
92
+ racc_reduce_n = 19
93
+
94
+ racc_shift_n = 31
95
+
96
+ racc_token_table = {
97
+ false => 0,
98
+ :error => 1,
99
+ :SELECT => 2,
100
+ :COMMA => 3,
101
+ :IDENTIFIER => 4,
102
+ :ASTERISK => 5,
103
+ :COUNT => 6,
104
+ :PARENTHESIS_LEFT => 7,
105
+ :PARENTHESIS_RIGHT => 8,
106
+ :FROM => 9,
107
+ :WHERE => 10,
108
+ :EQUALS => 11 }
109
+
110
+ racc_nt_base = 12
111
+
112
+ racc_use_result_var = true
113
+
114
+ Racc_arg = [
115
+ racc_action_table,
116
+ racc_action_check,
117
+ racc_action_default,
118
+ racc_action_pointer,
119
+ racc_goto_table,
120
+ racc_goto_check,
121
+ racc_goto_default,
122
+ racc_goto_pointer,
123
+ racc_nt_base,
124
+ racc_reduce_table,
125
+ racc_token_table,
126
+ racc_shift_n,
127
+ racc_reduce_n,
128
+ racc_use_result_var ]
129
+ Ractor.make_shareable(Racc_arg) if defined?(Ractor)
130
+
131
+ Racc_token_to_s_table = [
132
+ "$end",
133
+ "error",
134
+ "SELECT",
135
+ "COMMA",
136
+ "IDENTIFIER",
137
+ "ASTERISK",
138
+ "COUNT",
139
+ "PARENTHESIS_LEFT",
140
+ "PARENTHESIS_RIGHT",
141
+ "FROM",
142
+ "WHERE",
143
+ "EQUALS",
144
+ "$start",
145
+ "query",
146
+ "select_clause",
147
+ "from_clause",
148
+ "where_clause",
149
+ "selected_columns",
150
+ "selected_column",
151
+ "column_node",
152
+ "function_node",
153
+ "arg_node",
154
+ "expression",
155
+ "predicate",
156
+ "condition" ]
157
+ Ractor.make_shareable(Racc_token_to_s_table) if defined?(Ractor)
158
+
159
+ Racc_debug_parser = false
160
+
161
+ ##### State transition tables end #####
162
+
163
+ # reduce 0 omitted
164
+
165
+ module_eval(<<'.,.,', 'parser.racc', 12)
166
+ def _reduce_1(val, _values, result)
167
+ result = AST::QueryNode.new(select_clause: val[0])
168
+ result
169
+ end
170
+ .,.,
171
+
172
+ module_eval(<<'.,.,', 'parser.racc', 13)
173
+ def _reduce_2(val, _values, result)
174
+ result = AST::QueryNode.new(select_clause: val[0], from_clause: val[1])
175
+ result
176
+ end
177
+ .,.,
178
+
179
+ module_eval(<<'.,.,', 'parser.racc', 14)
180
+ def _reduce_3(val, _values, result)
181
+ result = AST::QueryNode.new(select_clause: val[0], from_clause: val[1], where_clause: val[2])
182
+ result
183
+ end
184
+ .,.,
185
+
186
+ module_eval(<<'.,.,', 'parser.racc', 16)
187
+ def _reduce_4(val, _values, result)
188
+ result = AST::SelectClauseNode.new(selected_columns: val[1])
189
+ result
190
+ end
191
+ .,.,
192
+
193
+ module_eval(<<'.,.,', 'parser.racc', 18)
194
+ def _reduce_5(val, _values, result)
195
+ result = [val[0]]
196
+ result
197
+ end
198
+ .,.,
199
+
200
+ module_eval(<<'.,.,', 'parser.racc', 19)
201
+ def _reduce_6(val, _values, result)
202
+ result = val[0] + [val[2]]
203
+ result
204
+ end
205
+ .,.,
206
+
207
+ module_eval(<<'.,.,', 'parser.racc', 21)
208
+ def _reduce_7(val, _values, result)
209
+ result = AST::SelectedColumnNode.new(col_def: val[0])
210
+ result
211
+ end
212
+ .,.,
213
+
214
+ module_eval(<<'.,.,', 'parser.racc', 22)
215
+ def _reduce_8(val, _values, result)
216
+ result = AST::SelectedColumnNode.new(col_def: val[0])
217
+ result
218
+ end
219
+ .,.,
220
+
221
+ module_eval(<<'.,.,', 'parser.racc', 24)
222
+ def _reduce_9(val, _values, result)
223
+ result = AST::ColumnNode.new(type: :single_col, name: val[0])
224
+ result
225
+ end
226
+ .,.,
227
+
228
+ module_eval(<<'.,.,', 'parser.racc', 25)
229
+ def _reduce_10(val, _values, result)
230
+ result = AST::ColumnNode.new(type: :asterisk, name: nil)
231
+ result
232
+ end
233
+ .,.,
234
+
235
+ module_eval(<<'.,.,', 'parser.racc', 27)
236
+ def _reduce_11(val, _values, result)
237
+ result = AST::FunctionNode.new(type: :count, args: [val[2]])
238
+ result
239
+ end
240
+ .,.,
241
+
242
+ # reduce 12 omitted
243
+
244
+ # reduce 13 omitted
245
+
246
+ module_eval(<<'.,.,', 'parser.racc', 33)
247
+ def _reduce_14(val, _values, result)
248
+ result = AST::FromClauseNode.new(table: AST::TableNode.new(table_def: val[1]))
249
+ result
250
+ end
251
+ .,.,
252
+
253
+ module_eval(<<'.,.,', 'parser.racc', 35)
254
+ def _reduce_15(val, _values, result)
255
+ result = AST::WhereClauseNode.new(predicate: val[1])
256
+ result
257
+ end
258
+ .,.,
259
+
260
+ module_eval(<<'.,.,', 'parser.racc', 37)
261
+ def _reduce_16(val, _values, result)
262
+ result = [val[0]]
263
+ result
264
+ end
265
+ .,.,
266
+
267
+ module_eval(<<'.,.,', 'parser.racc', 40)
268
+ def _reduce_17(val, _values, result)
269
+ result = AST::ConditionNode.new(operator: :equals, left: val[0], right: val[2])
270
+ result
271
+ end
272
+ .,.,
273
+
274
+ module_eval(<<'.,.,', 'parser.racc', 43)
275
+ def _reduce_18(val, _values, result)
276
+ result = AST::ExpressionNode.new(value: val[0])
277
+ result
278
+ end
279
+ .,.,
280
+
281
+ def _reduce_none(val, _values, result)
282
+ val[0]
283
+ end
284
+
285
+ end # class Parser
286
+ end # module SimplestSqlParser
287
+
288
+ # footerの内容はそのまま生成されたparser.tab.rbファイルの下にコピーされる。
289
+ # ruby parser.tab.rb で直にファイルを実行する際に Parserクラスを使って何かをするときなどに使える。
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimplestSqlParser
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "simplest_sql_parser/version"
4
+ require_relative "simplest_sql_parser/lexical_scanner.rex"
5
+ require_relative "simplest_sql_parser/parser.tab"
6
+
7
+ module SimplestSqlParser
8
+ class << self
9
+ def parse(query)
10
+ Parser.new(query).do_parse
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,4 @@
1
+ module SimplestSqlParser
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/simplest_sql_parser/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "simplest_sql_parser"
7
+ spec.version = SimplestSqlParser::VERSION
8
+ spec.authors = ["kudojp"]
9
+ spec.email = ["heyjudejudejude1968@gmail.com"]
10
+
11
+ spec.summary = "My first SQL query parser"
12
+ spec.description = "This parser parses very simple SQL query and generates AST."
13
+ spec.homepage = "https://github.com/kudojp/simplest_sql_parser"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 2.6.0"
16
+
17
+ # spec.metadata["allowed_push_host"] = "TODO: Set to your gem server 'https://example.com'"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = "https://github.com/kudojp/simplest_sql_parser"
21
+ spec.metadata["changelog_uri"] = "https://github.com/kudojp/simplest_sql_parser/blob/main/CHANGELOG.md"
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject do |f|
27
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
28
+ end
29
+ end
30
+ spec.bindir = "exe"
31
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
32
+ spec.require_paths = ["lib"]
33
+
34
+ # Uncomment to register a new dependency of your gem
35
+ # spec.add_dependency "example-gem", "~> 1.0"
36
+
37
+ # For more information and examples about making a new gem, check out our
38
+ # guide at: https://bundler.io/guides/creating_gem.html
39
+ end
metadata ADDED
@@ -0,0 +1,74 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: simplest_sql_parser
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - kudojp
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-06-23 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: This parser parses very simple SQL query and generates AST.
14
+ email:
15
+ - heyjudejudejude1968@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".rspec"
21
+ - ".rubocop.yml"
22
+ - CHANGELOG.md
23
+ - CODE_OF_CONDUCT.md
24
+ - Gemfile
25
+ - LICENSE.txt
26
+ - Makefile
27
+ - README.md
28
+ - Rakefile
29
+ - lib/simplest_sql_parser.rb
30
+ - lib/simplest_sql_parser/ast/column_node.rb
31
+ - lib/simplest_sql_parser/ast/condition_node.rb
32
+ - lib/simplest_sql_parser/ast/expression_node.rb
33
+ - lib/simplest_sql_parser/ast/from_clause_node.rb
34
+ - lib/simplest_sql_parser/ast/function_node.rb
35
+ - lib/simplest_sql_parser/ast/node.rb
36
+ - lib/simplest_sql_parser/ast/query_node.rb
37
+ - lib/simplest_sql_parser/ast/select_clause_node.rb
38
+ - lib/simplest_sql_parser/ast/selected_column_node.rb
39
+ - lib/simplest_sql_parser/ast/table_node.rb
40
+ - lib/simplest_sql_parser/ast/where_clause_node.rb
41
+ - lib/simplest_sql_parser/lexical_scanner.rex
42
+ - lib/simplest_sql_parser/lexical_scanner.rex.rb
43
+ - lib/simplest_sql_parser/parser.racc
44
+ - lib/simplest_sql_parser/parser.tab.rb
45
+ - lib/simplest_sql_parser/version.rb
46
+ - sig/simplest_sql_parser.rbs
47
+ - simplest_sql_parser.gemspec
48
+ homepage: https://github.com/kudojp/simplest_sql_parser
49
+ licenses:
50
+ - MIT
51
+ metadata:
52
+ homepage_uri: https://github.com/kudojp/simplest_sql_parser
53
+ source_code_uri: https://github.com/kudojp/simplest_sql_parser
54
+ changelog_uri: https://github.com/kudojp/simplest_sql_parser/blob/main/CHANGELOG.md
55
+ post_install_message:
56
+ rdoc_options: []
57
+ require_paths:
58
+ - lib
59
+ required_ruby_version: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: 2.6.0
64
+ required_rubygems_version: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ requirements: []
70
+ rubygems_version: 3.3.8
71
+ signing_key:
72
+ specification_version: 4
73
+ summary: My first SQL query parser
74
+ test_files: []