query_rule_engine 0.1.0.beta

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: d428caaf6d25e1f4d59a3e313989a5e161e1493b0f0953e16455a094343a35db
4
+ data.tar.gz: 98e8480d007a6c9d42a973c27675856dd651d8bdc1b94bc722e86ca79ed7342a
5
+ SHA512:
6
+ metadata.gz: d4833614a76bdbd7c37d1762eab7d972b2a706a4d1bdba10b12382f36f96a29bdc049160671e79c3b2d9e70c3db21cf8e6aa24fd47fd1a74937f0f9c290b9566
7
+ data.tar.gz: d588e2f602ac8c07951694b70fcb6e33a8638f9203c374103e69f09c0be831bdf579ef1ee95aa3bba1f1f3f0fe754fd8cc5d26391db42db31500d4b2fdf6c2a6
@@ -0,0 +1,18 @@
1
+ name: Ruby
2
+
3
+ on: [push,pull_request]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v2
10
+ - name: Set up Ruby
11
+ uses: ruby/setup-ruby@v1
12
+ with:
13
+ ruby-version: 2.4.1
14
+ - name: Run the default task
15
+ run: |
16
+ gem install bundler -v 2.2.3
17
+ bundle install
18
+ bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,10 @@
1
+ Style/StringLiterals:
2
+ Enabled: true
3
+ EnforcedStyle: double_quotes
4
+
5
+ Style/StringLiteralsInInterpolation:
6
+ Enabled: true
7
+ EnforcedStyle: double_quotes
8
+
9
+ Layout/LineLength:
10
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,2 @@
1
+ # Change Log
2
+ All notable changes to this project will be documented in this file.
@@ -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 striker.aryu56@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,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in query_rule_engine.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 0.80"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 strikeraryu
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,43 @@
1
+ # QueryRuleEngine
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/query_rule_engine`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'query_rule_engine'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install query_rule_engine
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/query_rule_engine. 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]/query_rule_engine/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the QueryRuleEngine project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/query_rule_engine/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]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "query_rule_engine"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module QueryRuleEngine
4
+ class Analysis
5
+ # Module to define methods related to dynamic message
6
+ module DynamicMessage
7
+ private
8
+
9
+ LISTED_VAR = %w[amount column impact table tag value].freeze
10
+
11
+ # to pretty print the analysis with warnings and suggestions
12
+ # @param opts [Hash] opts to get specifc dyanmic message
13
+ # eg. {"table" => "users", "column" => "select_type", "tag" => "SIMPLE", "type" => "message"}
14
+ # @return [String]
15
+ def dynamic_message(opts)
16
+ table, column, tag, type = opts.values_at("table", "column", "tag", "type")
17
+ message = self.tables.dig(table, "analysis", column, "tags", tag, type) || ""
18
+
19
+ variables = message.scan(/\$(\w+)/).uniq.map { |var| var[0] }
20
+ variables.each do |var|
21
+ value = dynamic_value_of(var, opts)
22
+
23
+ message.gsub!(/\$#{var}/, value.to_s) if value.present?
24
+ end
25
+
26
+ message
27
+ end
28
+
29
+ def dynamic_value_of(var, opts)
30
+ LISTED_VAR.include?(var) ? send(var, opts) : relative_value_of(var, opts.dig("table"))
31
+ end
32
+
33
+ def relative_value_of(var, table)
34
+ value_type = var.match(/amount_/).present? ? "amount" : "value"
35
+ self.tables.dig(table, "analysis", var.gsub(/amount_/, ""), value_type)
36
+ end
37
+
38
+ # dynamic variable methods
39
+ def amount(opts)
40
+ table, column = opts.values_at("table", "column")
41
+
42
+ self.tables.dig(table, "analysis", column, "amount")
43
+ end
44
+
45
+ def column(opts)
46
+ opts.dig("column")
47
+ end
48
+
49
+ def impact(opts)
50
+ table, column, tag = opts.values_at("table", "column", "tag")
51
+
52
+ impact = self.tables.dig(table, "analysis", column, "tags", tag, "impact")
53
+
54
+ opts.dig("colours").present? ? impact.send(IMPACTS[impact].colour) : impact
55
+ end
56
+
57
+ def table(opts)
58
+ opts.dig("table")
59
+ end
60
+
61
+ def tag(opts)
62
+ opts.dig("tag")
63
+ end
64
+
65
+ def value(opts)
66
+ table, column = opts.values_at("table", "column")
67
+
68
+ self.tables.dig(table, "analysis", column, "value")
69
+ end
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,155 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'analysis/dynamic_message'
4
+
5
+ module QueryRuleEngine
6
+ # This class is used to store analysis of a query and provide methods over them
7
+ class Analysis
8
+ include DynamicMessage
9
+
10
+ IMPACTS = {
11
+ "negative" => { "colour" => "red" },
12
+ "positive" => { "colour" => "green" },
13
+ "caution" => { "colour" => "yellow" }
14
+ }.freeze
15
+
16
+ # initialize analysis object
17
+ # tables [Array] Array of table analysis
18
+ # Eg.
19
+ # {
20
+ # "users" => {
21
+ # "id"=>1,
22
+ # "name"=>"users",
23
+ # "analysis"=>{
24
+ # "type"=>{
25
+ # "value" => "all",
26
+ # "tags" => {
27
+ # "all" => {
28
+ # "impact"=>"negative",
29
+ # "warning"=>"warning to represent the issue",
30
+ # "suggestions"=>"some follow up suggestions"
31
+ # }
32
+ # }
33
+ # }
34
+ # }
35
+ # }
36
+ # }
37
+ # summary [Hash] hash of analysis summary
38
+ # Eg.
39
+ # {
40
+ # "cardinality"=>{
41
+ # "amount"=>10,
42
+ # "warning"=>"warning to represent the issue",
43
+ # "suggestions"=>"some follow up suggestions"
44
+ # }
45
+ # }
46
+ def initialize
47
+ @table_count = 0
48
+ @tables = {}
49
+ @summary = {}
50
+ end
51
+
52
+ attr_accessor :tables, :table_count, :summary
53
+
54
+ # register a table analysis in analysis object
55
+ # @param name [String] name of the table
56
+ # @param table_analysis [Hash] analysis of a table
57
+ # Eg.
58
+ # {
59
+ # "id"=>1,
60
+ # "name"=>"users",
61
+ # "analysis"=>{
62
+ # "type"=>[
63
+ # {
64
+ # "tag"=>"all",
65
+ # "impact"=>"negative",
66
+ # "warning"=>"warning to represent the issue",
67
+ # "suggestions"=>"some follow up suggestions"
68
+ # }
69
+ # ]
70
+ # }
71
+ # }
72
+ def register_table(name, table_analysis)
73
+ self.table_count += 1
74
+ self.tables.merge!(
75
+ {
76
+ name => {
77
+ "id" => self.table_count,
78
+ "name" => name,
79
+ "analysis" => table_analysis
80
+ }
81
+ }
82
+ )
83
+ end
84
+
85
+ # register summary based in different attributes
86
+ # @param summary [Hash] hash of summary of analysis
87
+ def register_summary(summary)
88
+ self.summary.merge!(summary)
89
+ end
90
+
91
+ # to get analysis in pretty format with warnings and suggestions
92
+ # @param opts [Hash] - possible options [positive: <boolean>, negative: <boolean>, caution: <boolean>]
93
+ # @return [String] pretty analysis
94
+ def pretty_analysis(opts)
95
+ final_message = ""
96
+
97
+ opts.slice(*IMPACTS.keys).each do |impact, value|
98
+ final_message += pretty_analysis_for(impact) if value.present?
99
+ end
100
+
101
+ final_message
102
+ end
103
+
104
+ # to get analysis in pretty format with warnings and suggestions for a impact
105
+ # @param impact [String]
106
+ # @return [String] pretty analysis
107
+ def pretty_analysis_for(impact)
108
+ final_message = ""
109
+
110
+ self.tables.keys.each do |table|
111
+ table_message = table_pretty_analysis(table, {impact => true})
112
+
113
+ final_message += "table: #{table}\n#{table_message}\n" if table_message.present?
114
+ end
115
+
116
+ final_message
117
+ end
118
+
119
+ # to get analysis in pretty format with warnings and suggestions for a table
120
+ # @param table [String] - table name
121
+ # @param opts [Hash] - possible options [positive: <boolean>, negative: <boolean>, caution: <boolean>]
122
+ # @return [String] pretty analysis
123
+ def table_pretty_analysis(table, opts)
124
+ table_message = ""
125
+
126
+ self.tables.dig(table, "analysis").each do |column, column_analysis|
127
+ tags_message = ""
128
+ column_analysis.dig("tags").each do |tag, tag_analysis|
129
+ next unless opts.dig(tag_analysis.dig("impact")).present?
130
+
131
+ tags_message += tag_pretty_analysis(table, column, tag)
132
+ end
133
+
134
+ table_message += "column: #{column}\n#{tags_message}" if tags_message.present?
135
+ end
136
+
137
+ table_message
138
+ end
139
+
140
+ private
141
+
142
+ def tag_pretty_analysis(table, column, tag)
143
+ tag_message = ""
144
+
145
+ opts = { "table" => table, "column" => column, "tag" => tag }
146
+ message = dynamic_message(opts.merge({ "type" => "message" }))
147
+ suggestion = dynamic_message(opts.merge({ "type" => "suggestion" }))
148
+ tag_message += "impact: #{impact(opts.merge({ "colours" => true }))}\n"
149
+ tag_message += "message: #{message}\n"
150
+ tag_message += "suggestion: #{suggestion}\n" if suggestion.present?
151
+
152
+ tag_message
153
+ end
154
+ end
155
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module QueryRuleEngine
4
+ # This class is used for configuration of query rule engine
5
+ class Config
6
+ def initialize(detailed, rules_path)
7
+ @detailed = detailed
8
+ @rules_path = rules_path
9
+ end
10
+
11
+ def detailed?
12
+ @detailed.present?
13
+ end
14
+
15
+ attr_accessor :detailed, :rules_path
16
+ end
17
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module QueryRuleEngine
4
+ module Constants
5
+ DEFAULT_COLUMN_RULES = {
6
+ "value_type" => "string"
7
+ }.freeze
8
+ DEFAULT_DETAILED = true
9
+ DEFAULT_LOGGER_CONFIG = {
10
+ "negative" => true
11
+ }.freeze
12
+ DEFAULT_RULES_PATH = File.join(File.dirname(__FILE__), "rules.json")
13
+ end
14
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "helper"
4
+
5
+ module QueryRuleEngine
6
+ # This module provides tools to explain queries and ActiveRecord::Relation
7
+ module Explain
8
+ # to get explain result in parsable format
9
+ # @param relation [ActiveRecord::Relation, String] active record relation or raw sql query
10
+ # @return [Array] parsed_result - array of hashes representing EXPLAIN result for each row
11
+ def full_explain(relation, detailed = true)
12
+ explain_result = explain(relation)
13
+ return explain_result unless detailed
14
+
15
+ detailed_explain_result = detailed_explain(relation)
16
+
17
+ [*explain_result.keys, *detailed_explain_result.keys].uniq.map do |key|
18
+ (
19
+ explain_result.dig(key)&.merge(
20
+ detailed_explain_result.dig(key) || {}
21
+ ) || detailed_explain_result.dig(key)
22
+ )
23
+ end
24
+ end
25
+
26
+ # to get explain result in parsable format using "EXPLAIN <query>"
27
+ # @param relation [ActiveRecord::Relation, String] active record relation or raw sql query
28
+ # @return [Array] parsed_result - array of hashes representing EXPLAIN result for each row
29
+ def explain(relation)
30
+ query = load_query(relation)
31
+ explain_result = ActiveRecord::Base.connection.execute("EXPLAIN #{query}")
32
+ parsed_result = {}
33
+
34
+ explain_result.each(as: :json) do |ele|
35
+ parsed_result[ele.dig("table")] = ele
36
+ end
37
+
38
+ parsed_result
39
+ end
40
+
41
+ # to get detailed explain result in parsable format using "EXPLAIN format=JSON <query>"
42
+ # @param relation [ActiveRecord::Relation, String] active record relation or raw sql query
43
+ # @param prefix [String] prefix to append before each key "prefix#<key>"
44
+ # @return [Array] parsed_result - array of flatten hashes representing EXPLAIN result for each row
45
+ def detailed_explain(relation, prefix = "detailed")
46
+ query = load_query(relation)
47
+ explain_result = ActiveRecord::Base.connection.execute("EXPLAIN format=json #{query}")
48
+ explain_result = parse_detailed_explain(explain_result)
49
+
50
+ explain_result.map { |ele| [ele.dig("table_name"), Helper.flatten_hash(ele, prefix)] }.to_h
51
+ end
52
+
53
+ class << self
54
+ private
55
+
56
+ def load_query(relation)
57
+ relation.class.name == "ActiveRecord::Relation" ? relation.to_sql : relation
58
+ end
59
+
60
+ def parse_detailed_explain(explain_result)
61
+ parsed_result = JSON.parse(explain_result&.first&.first || "{}").dig("query_block")
62
+ return parsed_result.dig("nested_loop").map { |e| e.dig("table") } if parsed_result.key?("nested_loop")
63
+
64
+ parsed_result.key?("table") ? [parsed_result.dig("table")] : []
65
+ end
66
+ end
67
+
68
+ module_function :full_explain, :explain, :detailed_explain
69
+ end
70
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module QueryRuleEngine
4
+ # This module define helper methods for query rule engine
5
+ module Helper
6
+ def flatten_hash(hash, prefix_key = "")
7
+ flat_hash = {}
8
+
9
+ hash.each do |key, value|
10
+ key = prefix_key.present? ? "#{prefix_key}##{key}" : key.to_s
11
+
12
+ flat_hash.merge!(value.is_a?(Hash) ? flatten_hash(value, key) : { key => value })
13
+ end
14
+
15
+ flat_hash
16
+ end
17
+
18
+ def logger(message, type="info")
19
+ if defined?(Rails) && Rails.logger
20
+ Rails.logger.send(type, message)
21
+ else
22
+ puts "#{type.upcase}: #{message}"
23
+ end
24
+ end
25
+
26
+ def load_config(rules_path)
27
+ unless File.exists?(rules_path)
28
+ raise Error.new(
29
+ "Failed to load the rule file from '#{rules_path}'. " \
30
+ "The file may be missing or there is a problem with the path. " \
31
+ "Please ensure that the file exists and the path is correct."
32
+ )
33
+ end
34
+
35
+ rules_config = JSON.parse(File.read(rules_path))
36
+
37
+ rules_config
38
+ end
39
+
40
+ module_function :flatten_hash, :logger, :load_config
41
+ end
42
+
43
+ private_constant :Helper
44
+ end
@@ -0,0 +1,171 @@
1
+ {
2
+ "select_type": {
3
+ "description": "Type of select used in the table.",
4
+ "value_type": "string",
5
+ "rules": {
6
+ "SIMPLE": {
7
+ "impact": "positive",
8
+ "message": "A simple query without subqueries or unions.",
9
+ "suggestion": ""
10
+ }
11
+ }
12
+ },
13
+ "type": {
14
+ "description": "Join used in the query for a specific table.",
15
+ "value_type": "string",
16
+ "rules": {
17
+ "system": {
18
+ "impact": "positive",
19
+ "message": "Table has zero or one row, no change required.",
20
+ "suggestion": ""
21
+ },
22
+ "const": {
23
+ "impact": "positive",
24
+ "message": "Table has only one indexed matching row, fastest join type.",
25
+ "suggestion": ""
26
+ },
27
+ "eq_ref": {
28
+ "impact": "positive",
29
+ "message": "All index parts used in join and index is primary_key or unique not null.",
30
+ "suggestion": ""
31
+ },
32
+ "ref": {
33
+ "impact": "caution",
34
+ "message": "All matching rows of an indexed column read for each combination of rows from previous table.",
35
+ "suggestion": "Ensure the referenced column is indexed and look for null values, dupilcates. Upgrade to eq_ref join type if possible.\nYou can acheive eq_ref by adding unique and not null to the index - $key used in $table table table."
36
+ },
37
+ "fulltext": {
38
+ "impact": "caution",
39
+ "message": "Join uses table FULLTEXT index, index key used - $key.",
40
+ "suggestion": "Should only be used for text heavy columns."
41
+ },
42
+ "ref_or_null": {
43
+ "impact": "caution",
44
+ "message": "Using ref index with Null value in $table table.",
45
+ "suggestion": "Please check if you can upgrade to eq_ref, you can acheive eq_ref by adding unique and not null to the index - $key used in $table table."
46
+ },
47
+ "index_merge": {
48
+ "impact": "caution",
49
+ "message": "Join uses list of indexes, keys used: $key.",
50
+ "suggestion": "Slow if the indexes are not well-chosen or if there are too many indexes being used."
51
+ },
52
+ "range": {
53
+ "impact": "caution",
54
+ "message": "Index used to find matching rows in specific range.",
55
+ "suggestion": "Please check the range it should not be too broad."
56
+ },
57
+ "index": {
58
+ "impact": "caution",
59
+ "message": "Entire index tree scanned to find matching rows.",
60
+ "suggestion": "Can be slow for large indexes(Your key length: $key_len), use carefully."
61
+ },
62
+ "ALL": {
63
+ "impact": "negative",
64
+ "message": "Entire $table table is scanned to find matching rows, you have $amount_possible_keys possible keys to use.",
65
+ "suggestion": "Use index here. You can use index from possible key: $possible_keys or add new one to $table table as per the requirements."
66
+ }
67
+ }
68
+ },
69
+ "rows": {
70
+ "description": "Estimated number of rows scanned to find matching rows.",
71
+ "value_type": "number",
72
+ "rules": {
73
+ "threshold": {
74
+ "amount": 100,
75
+ "impact": "negative",
76
+ "message": "$value rows are being scanned per join for $table table.",
77
+ "suggestion": "Please see if it is possible to use index from $possible_keys or add new one to $table table as per the requirements to reduce the number of rows scanned."
78
+ }
79
+ }
80
+ },
81
+ "possible_keys": {
82
+ "description": "Index keys possible for a specifc table",
83
+ "value_type": "array",
84
+ "delimiter": ",",
85
+ "rules": {
86
+ "absent": {
87
+ "impact": "negative",
88
+ "message": "There are no possible keys for $table table to be used, can result into full scan",
89
+ "suggestion": "Please add index keys for $table table"
90
+ },
91
+ "threshold": {
92
+ "amount": 5,
93
+ "impact": "negative",
94
+ "message": "There are $amount possible keys for $table table, having too many index keys can be unoptimal",
95
+ "suggestion": "Please check if there are extra indexes in $table table."
96
+ }
97
+ }
98
+ },
99
+ "key": {
100
+ "description": "",
101
+ "value_type": "string",
102
+ "rules": {
103
+ "absent": {
104
+ "impact": "negative",
105
+ "message": "There is no index key used for $table table, and can result into full scan of the $table table",
106
+ "suggestion": "Please use index from possible_keys: $possible_keys or add new one to $table table as per the requirements."
107
+ }
108
+ }
109
+ },
110
+ "key_len": {
111
+ "description": "Length of the key index used",
112
+ "value_type": "number",
113
+ "rules": {}
114
+ },
115
+ "filtered": {
116
+ "description": "Indicates percentage of rows appearing from the total.",
117
+ "value_type": "number",
118
+ "rules": {}
119
+ },
120
+ "extra": {
121
+ "description": "Additional information about the plan",
122
+ "value_type": "array",
123
+ "delimiter": ";",
124
+ "rules": {
125
+ "Using temporary": {
126
+ "impact": "",
127
+ "message": "",
128
+ "suggestion": ""
129
+ },
130
+ "Using filesort": {
131
+ "impact": "negative",
132
+ "message": "A file-based algorithm in being applied over your result, This can be inefficient and result into long query time.",
133
+ "suggestion": "Please ensure either result set is small or use proper index."
134
+ },
135
+ "Using join buffer": {
136
+ "impact": "",
137
+ "message": "",
138
+ "suggestion": ""
139
+ },
140
+ "Using index condition": {
141
+ "impact": "",
142
+ "message": "",
143
+ "suggestion": ""
144
+ }
145
+ }
146
+ },
147
+ "detailed#used_columns": {
148
+ "description": "",
149
+ "value_type": "array",
150
+ "rules": {
151
+ "threshold": {
152
+ "amount": 7,
153
+ "impact": "negative",
154
+ "message": "You have selected $amount columns, You should not select too many columns.",
155
+ "suggestion": "Please only select required columns."
156
+ }
157
+ }
158
+ },
159
+ "cardinality": {
160
+ "description": "",
161
+ "value_type": "number",
162
+ "rules": {
163
+ "threshold": {
164
+ "amount": 100,
165
+ "impact": "negative",
166
+ "message": "The cardinality of table is $amount, and its too high.",
167
+ "suggestion": "Please use proper index, query only requried data and ensure you are using proper joins."
168
+ }
169
+ }
170
+ }
171
+ }
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module QueryRuleEngine
4
+ VERSION = "0.1.0.beta"
5
+ end
@@ -0,0 +1,163 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_record"
4
+ require "active_support/notifications"
5
+ require "active_support/core_ext"
6
+ require "json"
7
+ require "forwardable"
8
+
9
+ require_relative "query_rule_engine/analysis"
10
+ require_relative "query_rule_engine/constants"
11
+ require_relative "query_rule_engine/config"
12
+ require_relative "query_rule_engine/explain"
13
+ require_relative "query_rule_engine/helper"
14
+ require_relative "query_rule_engine/version"
15
+
16
+ # This module provides tools to analyse your queries based on custom rules
17
+ module QueryRuleEngine
18
+ extend Forwardable
19
+
20
+ class Error < StandardError; end
21
+
22
+ @config = Config.new(
23
+ Constants::DEFAULT_DETAILED, Constants::DEFAULT_RULES_PATH
24
+ )
25
+
26
+ CONFIG_METHODS = %i[
27
+ detailed detailed? detailed= rules_path rules_path=
28
+ ].freeze
29
+
30
+ def_delegators :config, *CONFIG_METHODS
31
+
32
+ # to create analysis for ActiveRecord::Relation or a query string
33
+ # @param relation [ActiveRecord::Relation, String]
34
+ # @return [QueryRuleEngine::Analysis] analysis - contains the analysis of the query
35
+ def analyse(relation)
36
+ rules_config = Helper.load_config(config.rules_path)
37
+ analysis = Analysis.new
38
+ summary = {}
39
+
40
+ query_plan = Explain.full_explain(relation, config.detailed?)
41
+
42
+ query_plan.each do |table|
43
+ table_analysis, summary = analyse_table(table, summary, rules_config)
44
+
45
+ analysis.register_table(table.dig("table"), table_analysis)
46
+ end
47
+
48
+ analysis.register_summary(generate_summary_analysis(rules_config, summary))
49
+
50
+ analysis
51
+ end
52
+
53
+ # to add a logger to print analysis after each query
54
+ # @param silent [Boolean] silent errors for logger
55
+ # @param logger_config [Hash] possible options [positive: <boolean>, negative: <boolean>, caution: <boolean>]
56
+ def subscribe_logger(silent: false, logger_config: Constants::DEFAULT_LOGGER_CONFIG)
57
+ ActiveSupport::Notifications.subscribe("sql.active_record") do |_, _, _, _, payload|
58
+ begin
59
+ if !payload[:exception].present? && payload[:name] =~ /.* Load/
60
+ analysis = analyse(payload[:sql])
61
+
62
+ Helper.logger(analysis.pretty_analysis(logger_config))
63
+ end
64
+ rescue => error
65
+ if silent.present?
66
+ Helper.logger("#{error.class}: #{error.message}", "error")
67
+ else
68
+ raise error
69
+ end
70
+ end
71
+ end
72
+ end
73
+
74
+ class << self
75
+ attr_accessor :config
76
+
77
+ private
78
+
79
+ def add_summary(summary, column_name, value)
80
+ summary["cardinality"] = (summary.dig("cardinality") || 1) + value.to_f if column_name.eql?("rows")
81
+
82
+ summary
83
+ end
84
+
85
+ def analyse_table(table, summary, rules_config)
86
+ table_analysis = {}
87
+
88
+ table.each do |column, value|
89
+ summary = add_summary(summary, column, value)
90
+ next unless rules_config.dig(column).present?
91
+
92
+ table_analysis.merge!({ column => apply_rules(rules_config.dig(column), value) })
93
+ end
94
+
95
+ [table_analysis, summary]
96
+ end
97
+
98
+ def apply_rules(column_rules, value)
99
+ column_rules = Constants::DEFAULT_COLUMN_RULES.merge(column_rules)
100
+ value = transform_value(value, column_rules)
101
+ amount = transform_amount(value, column_rules)
102
+
103
+ column_analyse = { "value" => value, "amount" => amount, "tags" => {} }
104
+
105
+ [*value].each do |tag|
106
+ tag_rule = column_rules.dig("rules", tag)
107
+ next unless tag_rule.present?
108
+
109
+ column_analyse["tags"].merge!({ tag => transform_tag_rule(tag_rule) })
110
+ end
111
+
112
+ column_analyse["tags"].merge!(apply_threshold_rule(column_rules, amount))
113
+
114
+ column_analyse
115
+ end
116
+
117
+ def apply_threshold_rule(column_rules, amount)
118
+ threshold_rule = column_rules.dig("rules", "threshold")
119
+
120
+ if threshold_rule.present? && amount >= threshold_rule.dig("amount")
121
+ return {
122
+ "threshold" => transform_tag_rule(threshold_rule).merge(
123
+ { "amount" => amount }
124
+ )
125
+ }
126
+ end
127
+
128
+ {}
129
+ end
130
+
131
+ def generate_summary_analysis(rules_config, summary)
132
+ summary_analysis = {}
133
+
134
+ summary.each do |column, value|
135
+ next unless rules_config.dig(column).present?
136
+
137
+ summary_analysis.merge!({ column => apply_rules(rules_config.dig(column), value) })
138
+ end
139
+
140
+ summary_analysis
141
+ end
142
+
143
+ def transform_amount(value, column_rules)
144
+ column_rules.dig("value_type").eql?("number") ? value.to_f : value.size
145
+ end
146
+
147
+ def transform_tag_rule(tag_rule)
148
+ tag_rule.slice("impact", "suggestion", "message")
149
+ end
150
+
151
+ def transform_value(value, column_rules)
152
+ value ||= "absent"
153
+
154
+ if column_rules.dig("value_type").eql?("array") && column_rules.dig("delimiter").present?
155
+ value = value.split(column_rules.dig("delimiter")).map(&:strip)
156
+ end
157
+
158
+ value
159
+ end
160
+ end
161
+
162
+ module_function :analyse, :subscribe_logger, *CONFIG_METHODS
163
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path('lib', __dir__)
4
+ $LOAD_PATH.unshift lib unless $LOAD_PATH.include?(lib)
5
+
6
+ require_relative "lib/query_rule_engine/version"
7
+
8
+ Gem::Specification.new do |spec|
9
+ spec.name = "query_rule_engine"
10
+ spec.version = QueryRuleEngine::VERSION
11
+ spec.authors = ["strikeraryu"]
12
+ spec.email = ["striker.aryu56@gmail.com"]
13
+
14
+ spec.summary = "This gem provides tools to analyze your queries based on custom rules."
15
+ spec.homepage = "https://github.com/strikeraryu/query_rule_engine.git"
16
+ spec.license = "MIT"
17
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
18
+ spec.required_rubygems_version = Gem::Requirement.new(">= 3.2.3")
19
+
20
+ spec.metadata["homepage_uri"] = spec.homepage
21
+ spec.metadata["source_code_uri"] = "https://github.com/strikeraryu/query_rule_engine.git"
22
+ spec.metadata["changelog_uri"] = "https://github.com/strikeraryu/tree/master/CHANGELOG.md"
23
+
24
+ # Specify which files should be added to the gem when it is released.
25
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
26
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
27
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
28
+ end
29
+ spec.bindir = "exe"
30
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
31
+ spec.require_paths = ["lib"]
32
+
33
+ # Uncomment to register a new dependency of your gem
34
+ spec.add_runtime_dependency "activesupport", ">= 3.0.0", "< 6.0.0"
35
+ spec.add_runtime_dependency "activerecord", ">= 3.0.0", "< 6.0.0"
36
+
37
+ # For more information and examples about making a new gem, checkout our
38
+ # guide at: https://bundler.io/guides/creating_gem.html
39
+ end
metadata ADDED
@@ -0,0 +1,108 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: query_rule_engine
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0.beta
5
+ platform: ruby
6
+ authors:
7
+ - strikeraryu
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-04-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 3.0.0
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: 6.0.0
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: 3.0.0
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: 6.0.0
33
+ - !ruby/object:Gem::Dependency
34
+ name: activerecord
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: 3.0.0
40
+ - - "<"
41
+ - !ruby/object:Gem::Version
42
+ version: 6.0.0
43
+ type: :runtime
44
+ prerelease: false
45
+ version_requirements: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: 3.0.0
50
+ - - "<"
51
+ - !ruby/object:Gem::Version
52
+ version: 6.0.0
53
+ description:
54
+ email:
55
+ - striker.aryu56@gmail.com
56
+ executables: []
57
+ extensions: []
58
+ extra_rdoc_files: []
59
+ files:
60
+ - ".github/workflows/main.yml"
61
+ - ".gitignore"
62
+ - ".rspec"
63
+ - ".rubocop.yml"
64
+ - CHANGELOG.md
65
+ - CODE_OF_CONDUCT.md
66
+ - Gemfile
67
+ - LICENSE.txt
68
+ - README.md
69
+ - Rakefile
70
+ - bin/console
71
+ - bin/setup
72
+ - lib/query_rule_engine.rb
73
+ - lib/query_rule_engine/analysis.rb
74
+ - lib/query_rule_engine/analysis/dynamic_message.rb
75
+ - lib/query_rule_engine/config.rb
76
+ - lib/query_rule_engine/constants.rb
77
+ - lib/query_rule_engine/explain.rb
78
+ - lib/query_rule_engine/helper.rb
79
+ - lib/query_rule_engine/rules.json
80
+ - lib/query_rule_engine/version.rb
81
+ - query_rule_engine.gemspec
82
+ homepage: https://github.com/strikeraryu/query_rule_engine.git
83
+ licenses:
84
+ - MIT
85
+ metadata:
86
+ homepage_uri: https://github.com/strikeraryu/query_rule_engine.git
87
+ source_code_uri: https://github.com/strikeraryu/query_rule_engine.git
88
+ changelog_uri: https://github.com/strikeraryu/tree/master/CHANGELOG.md
89
+ post_install_message:
90
+ rdoc_options: []
91
+ require_paths:
92
+ - lib
93
+ required_ruby_version: !ruby/object:Gem::Requirement
94
+ requirements:
95
+ - - ">="
96
+ - !ruby/object:Gem::Version
97
+ version: 2.3.0
98
+ required_rubygems_version: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - ">="
101
+ - !ruby/object:Gem::Version
102
+ version: 3.2.3
103
+ requirements: []
104
+ rubygems_version: 3.2.3
105
+ signing_key:
106
+ specification_version: 4
107
+ summary: This gem provides tools to analyze your queries based on custom rules.
108
+ test_files: []