`rails dbrunner`: the db equivalent of `rails runner`
I recently realized how often I'm trekking into psql just to copy-paste the not-very-ActiveRecord-able queries from my local editor.
bin/rails dbrunner "SELECT name, email FROM users WHERE created_at > '2026-01-01' LIMIT 5"
Bad example. Here's a better one:
SELECT
users.email,
users.created_at AS signed_up,
last_activity.last_seen,
DATE_PART('day', NOW() - last_activity.last_seen) AS days_inactive,
plan_changes.previous_plan,
plan_changes.current_plan,
plan_changes.changed_at AS downgraded_at
FROM users
JOIN LATERAL (
SELECT MAX(events.created_at) AS last_seen
FROM events
WHERE events.user_id = users.id
) last_activity ON true
JOIN LATERAL (
SELECT
LAG(subscriptions.plan) OVER (ORDER BY subscriptions.created_at) AS previous_plan,
subscriptions.plan AS current_plan,
subscriptions.created_at AS changed_at
FROM subscriptions
WHERE subscriptions.user_id = users.id
ORDER BY subscriptions.created_at DESC
LIMIT 1
) plan_changes ON true
WHERE plan_changes.previous_plan IS NOT NULL
AND plan_changes.current_plan < plan_changes.previous_plan
AND last_activity.last_seen < NOW() - INTERVAL '14 days'
ORDER BY days_inactive DESC
bundle add dbrunner and you're off to hell.
Find it here: https://github.com/joshmn/dbrunner
It respects your database.yml, works with multi-db setups, and outputs as table (default), JSON, or CSV.
bin/rails dbrunner query.sql # from a file
echo "SELECT 1" | bin/rails dbrunner - # from stdin
bin/rails dbrunner "SELECT ..." -f json # as JSON
bin/rails dbrunner "SELECT ..." --db secondary # hit a different db
No dependencies that your Rails app doesn't already ship with.
This is one of those it-works-for-me things and not battle-tested, so please hit the github's issues controller with bugs when github itself not 500ing.
Posted Apr 6, 2026, 1:14 PM UTC
1715