ruby sql 19 lines · 3 tabs

SQL injection prevention with unsafe and safe query patterns

Kai Nakamura Apr 2026
3 tabs
# Vulnerable: user input is concatenated directly into SQL.
email = params[:email]
password = params[:password]

sql = "SELECT * FROM users WHERE email = '#{email}' AND password_hash = '#{password}'"
user = ActiveRecord::Base.connection.execute(sql).first
3 files · ruby, sql Explain with highlit

I teach SQL injection by showing the vulnerable pattern first and then replacing it with parameterized queries. The important point is that escaping is not a strategy and string interpolation is not acceptable anywhere user input reaches SQL. I also prefer narrow database roles so a missed injection path cannot become a full database compromise.


Related snips

ruby
RegistrationSchema = Dry::Schema.Params do
  required(:email).filled(:string, format?: URI::MailTo::EMAIL_REGEXP)
  required(:password).filled(:string, min_size?: 12)
  optional(:marketing_opt_in).filled(:bool)
  optional(:country).filled(:string, included_in?: %w[US CA GB AU])
end

Input validation with allowlists and explicit schemas

input-validation schemas secure-coding
by Kai Nakamura 1 tab
sql
-- EXPLAIN ANALYZE (actual execution statistics)
EXPLAIN ANALYZE
SELECT u.username, COUNT(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at >= '2024-01-01'

Advanced query optimization techniques

database optimization query-performance
by Maria Garcia 2 tabs
python
from django.db.models import Count, Avg, Sum, Q, F
from django.views.generic import TemplateView
from products.models import Product, Order, OrderItem


class DashboardView(TemplateView):

Django aggregation with annotate for statistics

django python database
by Priya Sharma 1 tab
ruby
raw_token = SecureRandom.urlsafe_base64(32)
token_digest = Digest::SHA256.hexdigest(raw_token)

PasswordReset.create!(
  user: user,
  token_digest: token_digest,

Secure random token generation for sessions and recovery flows

randomness tokens authentication
by Kai Nakamura 1 tab
python
import psycopg

with psycopg.connect(conninfo) as connection:
    with connection.cursor() as cursor:
        cursor.execute(
            'SELECT id, email FROM users WHERE email = %s',

Parameterized queries in Python with psycopg

python sql-injection psycopg
by Kai Nakamura 1 tab
ruby
class ReportQuery
  SQL = <<~SQL.freeze
    SELECT date_trunc('day', events.created_at) AS day,
           count(*) AS total,
           count(*) FILTER (WHERE events.kind = 'purchase') AS purchases
    FROM events

Safe Raw SQL with exec_query + Binds

rails activerecord sql
by codesnips 2 tabs

Share this code

Here's the card — post it anywhere.

SQL injection prevention with unsafe and safe query patterns — share card
Link copied