why_query 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 02cb599669704dcfaae94307fc9ad94d8e5a89f953523c642d342132c124fcc2
4
+ data.tar.gz: b37df34ce1fafc9b75d91004cdea4f4c6b0ec165b70ffa37ecdd9fdbae235d54
5
+ SHA512:
6
+ metadata.gz: eaca64f9fc625d3949813da60dd25d103f60e98a63e42dc6928eee4e1b1f6840ce2fc0c450e2e1c003fc6102bf72a2696cb0c420ceb6fce82c74e9469c36306e
7
+ data.tar.gz: 07da22bc6e4e612f94415f4e650f71715d73cfacc8835c2de7ea80506c7097399966bb1dbf5cfa2a056edc4f237e9a18457b743de0fc4abc8dc36c723cb29e5f
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,9 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-04-16
4
+
5
+ - Initial release of `why_query`
6
+ - Logs file + line number for every SQL query via ActiveRecord
7
+ - Configurable output via `WhyQuery.configure`
8
+ - Support for `Rails.root` filtering (`app_only: true`)
9
+ - Fully tested with Minitest
@@ -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 lahiru.lahirumadusanka@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 why_query.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "minitest", "~> 5.0"
11
+
12
+ gem "rubocop", "~> 1.21"
data/LICENSE.md ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2025 Lahiru Himesh
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # 🔍 why_query
2
+
3
+ **Find out exactly where your SQL queries come from.**
4
+ No more grepping logs or blaming ActiveRecord. `why_query` prints the file and line of code that triggered every query in development.
5
+
6
+ ```ruby
7
+ User.where(active: true).first
8
+ # => ↳ Called from: app/controllers/users_controller.rb:12
9
+ ```
10
+
11
+ ---
12
+
13
+ ## ✨ Features
14
+
15
+ - 📍 Logs **where each SQL query was called from**
16
+ - 🧠 Filters to **your app code only** (no gems, no noise)
17
+ - 🛠 Simple configuration (log anywhere, toggle anytime)
18
+ - 🧪 Great for debugging N+1s and finding rogue queries
19
+
20
+ ---
21
+
22
+ ## 🚀 Installation
23
+
24
+ Add it to your Gemfile:
25
+
26
+ ```ruby
27
+ gem "why_query", group: :development
28
+ ```
29
+
30
+ Then run:
31
+
32
+ ```bash
33
+ bundle install
34
+ ```
35
+
36
+ ---
37
+
38
+ ## ⚙️ Configuration
39
+
40
+ Create an initializer in your Rails app:
41
+
42
+ ```ruby
43
+ # config/initializers/why_query.rb
44
+
45
+ WhyQuery.configure do |config|
46
+ config.enabled = Rails.env.development? # Toggle globally
47
+ config.app_only = true # Only log queries from your app files
48
+ config.logger = ->(msg) { Rails.logger.debug("[WHY_QUERY] #{msg}") } # Custom logger
49
+ end
50
+ ```
51
+
52
+ You can also toggle at runtime:
53
+
54
+ ```ruby
55
+ WhyQuery.config.enabled = false
56
+ ```
57
+
58
+ ---
59
+
60
+ ## 💡 Output Examples
61
+
62
+ In logs or console:
63
+
64
+ ```sql
65
+ SELECT "users".* FROM "users" WHERE "users"."active" = TRUE
66
+ ↳ Called from: app/services/users/fetcher.rb:7
67
+ ```
68
+
69
+ ---
70
+
71
+ ## ❓ Why Use This?
72
+
73
+ - “Where did this query come from?”
74
+ - “Who’s loading all users in a loop?”
75
+ - “Why is my controller generating 20 queries?”
76
+
77
+ Now you’ll know. Instantly.
78
+
79
+ ---
80
+
81
+ ## 🧠 Tips
82
+
83
+ Want to log stack traces? Set `app_only = false`:
84
+
85
+ ```ruby
86
+ WhyQuery.configure do |config|
87
+ config.app_only = false
88
+ end
89
+ ```
90
+
91
+ You’ll get:
92
+
93
+ ```
94
+ ↳ Called from: app/models/post.rb:18
95
+ ↳ Called from: app/controllers/posts_controller.rb:42
96
+ ```
97
+
98
+ ---
99
+
100
+ ## 🙏 Acknowledgements
101
+
102
+ Inspired by hours of wondering “Where the heck is this query coming from?”
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "rubocop/rake_task"
13
+
14
+ RuboCop::RakeTask.new
15
+
16
+ task default: %i[test rubocop]
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WhyQuery
4
+ class Config
5
+ attr_accessor :enabled, :app_only, :logger
6
+
7
+ def initialize
8
+ @enabled = true
9
+ @app_only = true
10
+ @logger = ->(msg) { puts msg }
11
+ end
12
+ end
13
+ end
14
+
@@ -0,0 +1,10 @@
1
+ module WhyQuery
2
+ class Railtie < ::Rails::Railtie
3
+ initializer "why_query.initialize" do
4
+ ActiveSupport.on_load(:active_record) do
5
+ require "why_query"
6
+ end
7
+ end
8
+ end
9
+ end
10
+
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WhyQuery
4
+ VERSION = "0.1.0"
5
+ end
data/lib/why_query.rb ADDED
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "why_query/version"
4
+ require_relative "why_query/config"
5
+ require "active_support/notifications"
6
+ require "active_record"
7
+ require "rails" if defined?(Rails)
8
+ require "why_query/railtie" if defined?(Rails)
9
+
10
+ module WhyQuery
11
+ class << self
12
+ attr_accessor :config
13
+
14
+ def configure
15
+ yield(config)
16
+ end
17
+
18
+ def config
19
+ @config ||= Config.new
20
+ end
21
+
22
+ def enabled?
23
+ config.enabled
24
+ end
25
+
26
+ def log_origin
27
+ stack = caller_locations(3, 10)
28
+
29
+ location = stack.find do |loc|
30
+ path = loc.path
31
+ path.start_with?(Rails.root.to_s) && !path.include?("/gems/")
32
+ end if config.app_only
33
+
34
+ location ||= stack[0] # fallback to any top stack
35
+
36
+ if location
37
+ config.logger.call("↳ Called from: #{location.path.sub(Rails.root.to_s + "/", "")}:#{location.lineno}")
38
+ end
39
+ end
40
+ end
41
+ end
42
+
43
+ ActiveSupport::Notifications.subscribe("sql.active_record") do |_, _, _, _, payload|
44
+ next unless WhyQuery.enabled?
45
+
46
+ SKIPPED_NAMES = ["SCHEMA", "TRANSACTION"]
47
+
48
+ next if SKIPPED_NAMES.include?(payload[:name])
49
+
50
+ WhyQuery.log_origin
51
+ end
data/sig/why_query.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module WhyQuery
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
data/why_query.gemspec ADDED
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/why_query/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "why_query"
7
+ spec.version = WhyQuery::VERSION
8
+ spec.authors = ["Lahiru Himesh Madusanka"]
9
+ spec.email = ["lahiru.lahirumadusanka@gmail.com"]
10
+
11
+ spec.summary = "Log the origin of every ActiveRecord query."
12
+ spec.description = "WhyQuery helps you trace where each SQL query in your Rails app comes from by logging the Ruby file and line that triggered it. Great for debugging N+1s and rogue queries in development."
13
+
14
+ spec.homepage = "https://github.com/sdglhm/why_query"
15
+ spec.required_ruby_version = ">= 2.6.0"
16
+
17
+ spec.files = Dir["lib/**/*.rb", "README.md", "LICENSE.txt"]
18
+ spec.require_paths = ["lib"]
19
+
20
+ spec.metadata["homepage_uri"] = spec.homepage
21
+ spec.metadata["source_code_uri"] = "https://github.com/sdglhm/why_query"
22
+ spec.metadata["changelog_uri"] = "https://github.com/sdglhm/why_query/blob/main/CHANGELOG.md"
23
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
24
+
25
+
26
+ # Specify which files should be added to the gem when it is released.
27
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
28
+ spec.files = Dir.chdir(__dir__) do
29
+ `git ls-files -z`.split("\x0").reject do |f|
30
+ (File.expand_path(f) == __FILE__) || f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor])
31
+ end
32
+ end
33
+ spec.bindir = "exe"
34
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
35
+ spec.require_paths = ["lib"]
36
+
37
+ # Uncomment to register a new dependency of your gem
38
+ # spec.add_dependency "example-gem", "~> 1.0"
39
+
40
+ # For more information and examples about making a new gem, check out our
41
+ # guide at: https://bundler.io/guides/creating_gem.html
42
+ end
metadata ADDED
@@ -0,0 +1,61 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: why_query
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Lahiru Himesh Madusanka
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-04-16 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: WhyQuery helps you trace where each SQL query in your Rails app comes
14
+ from by logging the Ruby file and line that triggered it. Great for debugging N+1s
15
+ and rogue queries in development.
16
+ email:
17
+ - lahiru.lahirumadusanka@gmail.com
18
+ executables: []
19
+ extensions: []
20
+ extra_rdoc_files: []
21
+ files:
22
+ - ".rubocop.yml"
23
+ - CHANGELOG.md
24
+ - CODE_OF_CONDUCT.md
25
+ - Gemfile
26
+ - LICENSE.md
27
+ - README.md
28
+ - Rakefile
29
+ - lib/why_query.rb
30
+ - lib/why_query/config.rb
31
+ - lib/why_query/railtile.rb
32
+ - lib/why_query/version.rb
33
+ - sig/why_query.rbs
34
+ - why_query.gemspec
35
+ homepage: https://github.com/sdglhm/why_query
36
+ licenses: []
37
+ metadata:
38
+ homepage_uri: https://github.com/sdglhm/why_query
39
+ source_code_uri: https://github.com/sdglhm/why_query
40
+ changelog_uri: https://github.com/sdglhm/why_query/blob/main/CHANGELOG.md
41
+ allowed_push_host: https://rubygems.org
42
+ post_install_message:
43
+ rdoc_options: []
44
+ require_paths:
45
+ - lib
46
+ required_ruby_version: !ruby/object:Gem::Requirement
47
+ requirements:
48
+ - - ">="
49
+ - !ruby/object:Gem::Version
50
+ version: 2.6.0
51
+ required_rubygems_version: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - ">="
54
+ - !ruby/object:Gem::Version
55
+ version: '0'
56
+ requirements: []
57
+ rubygems_version: 3.4.10
58
+ signing_key:
59
+ specification_version: 4
60
+ summary: Log the origin of every ActiveRecord query.
61
+ test_files: []