rails: PG::SyntaxError on query serialize in Rails 7.2

Description

Problem with serialization sql query with string condition and nil bind value with PostgreSQL adapter (it does work with sqlite3)

Steps to reproduce

# frozen_string_literal: true

require 'bundler/inline'

gemfile(true) do
  source 'https://rubygems.org'

  gem 'rails'
  # If you want to test against edge Rails replace the previous line with this:
  # gem "rails", github: "rails/rails", branch: "main"

  gem 'pg'
end

require 'active_record'
require 'minitest/autorun'
require 'logger'

db_config = { adapter: 'postgresql', database: 'test', host: 'localhost' }
ActiveRecord::Tasks::DatabaseTasks.create(db_config)

# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'postgresql', database: 'test')
ActiveRecord::Base.logger = Logger.new($stdout)

ActiveRecord::Schema.define do
  create_table :users, force: true do |t|
    t.string :name
  end
end

class User < ActiveRecord::Base
end

class BugTest < Minitest::Test
  def test_association_stuff
    user1 = User.create!(name: 'John Doe')
    user2 = User.create!

    assert_equal user1, User.find_by('LOWER(name) = ?', 'john doe')
    assert_equal nil, User.find_by('LOWER(name) = ?', 'jane doe')
    assert_equal user2, User.find_by('LOWER(name) IS ?', nil)
  end
end

Expected behavior

Serialize query with LOWER(name) IS NULL condition

Actual behavior

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near "$1"
LINE 1: ...LECT "users".* FROM "users" WHERE (LOWER(name) IS $1) LIMIT ...

System configuration

Rails version: Rails 7.2.0 Ruby version: ruby 3.3.4 (2024-07-09 revision be1089c8ec) [arm64-darwin23]

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 15 (9 by maintainers)

Commits related to this issue

Most upvoted comments

For anyone who also had this issue: I was able to get around it by using Arel.sql("NULL") in place of nil` in the params, so if I’m using a where statement, it looks like:

User.where('LOWER(name) IS ?', Arel.sql("NULL"))

Note that using a string "NULL" (instead of the Arel statement) will not avoid the issue.

TIL

open up an app to injection attacks?

No.