Slide 1

Slide 1 text

Refining Active Record Shugo Maeda Network Applied Communication Laboratory Ltd.

Slide 2

Slide 2 text

About me ▪ Shugo Maeda ▪ CEO at NaCl ▪ A Ruby committer ▪ An occasional Rails contributor

Slide 3

Slide 3 text

activerecord-refinements ▪ A gem written by Akira Matsuda ▪ Provides a DSL for where User.where { :name == "Matz" }

Slide 4

Slide 4 text

Warning in README And unfortunately, due to the Refinements’ spec change, this library does not work under Ruby 2.0.0 stable.

Slide 5

Slide 5 text

What are Refinements? ▪ A feature for local monkey patching

Slide 6

Slide 6 text

Define refinements module ExactDivision refine Integer do def /(other) = quo(other) end end

Slide 7

Slide 7 text

Use refinements p 1 / 2 #=> 0 using ExactDivision p 1 / 2 #=> (1/2)

Slide 8

Slide 8 text

Scope of refinements ▪ file-local ▪ class/module-local ▪ block-local

Slide 9

Slide 9 text

using at the top level p 1 / 2 #=> 0 using ExactDivision # activated only in the file p 1 / 2 #=> (1/2)

Slide 10

Slide 10 text

using in class/module class Foo p 1 / 2 #=> 0 using ExactDivision # activated only in the class p 1 / 2 #=> (1/2) def bar = 1 / 2 end p 1 / 2 #=> 0 p Foo.new.bar #=> (1/2)

Slide 11

Slide 11 text

Block-local refinement activation ▪ instance_eval and module_eval activated refinements in the given block ▪ Useful for DSLs

Slide 12

Slide 12 text

where in activerecord-refinements def where(opts = nil, *rest, &block) if block col, op, val = Module.new { using ActiveRecord::Refinements::WhereBlockSyntax }.module_eval &block ...

Slide 13

Slide 13 text

Removed in Ruby 2.0.0!

Slide 14

Slide 14 text

activerecord-refined ▪ A fork of activerecord-refinements ▪ Reimplemented with Proc#refined ▪ Added a number of DSL constructs ▪ activerecord-refinements supported only ==, !=, =~, >, >=, <, and <=

Slide 15

Slide 15 text

Proc#refined ▪ A new feature in Ruby 4.1 ▪ Returns a copy of the Proc with the given refinements activated

Slide 16

Slide 16 text

Example module StringExt refine String do def shout = upcase + "!" end end original = ->(s) { s.shout } refined = original.refined(StringExt) p refined.call("hello") # "HELLO!" p original.call("hello") # NoMethodError

Slide 17

Slide 17 text

where in activerecord-refined def where(opts = nil, *rest, &block) return super unless block super(to_arel_condition(evaluate_block(&block))) end def evaluate_block(&block) refined_block = block.refined(ActiveRecord::Refined::BlockSyntax) BlockContext.new(model).instance_exec(&refined_block) end

Slide 18

Slide 18 text

BlockSyntax ▪ Refinements for Symbol, Integer, String, … module BlockSyntax refine Symbol do def ==(other) = AST::Comparison.new(self, :==, other) end end

Slide 19

Slide 19 text

Refinements don’t leak class Post < ActiveRecord::Base def self.initial_state(author_role) # plain Symbol#== author_role == :admin ? "published" : "draft" end end Post.where { :state == Post.initial_state(:admin) } # WHERE "posts"."state" = 'published'

Slide 20

Slide 20 text

BlockContext ▪ self inside the block ▪ No method_missing class BlockContext def avg(column) = AST::Aggregate.new(column, :average) def count(column, distinct: false) = ... end

Slide 21

Slide 21 text

How it works Block AST Arel SQL Proc ActiveRecord::Refined::AST Arel::Nodes String Comparison Equality SELECT "users".* User.where { FROM "users" :name == "Matz" } WHERE "users"."name" column operator :name :== value left right "Matz" Attribute Casted "users"."name" 'Matz' = 'Matz'

Slide 22

Slide 22 text

Design policy ▪ SQL queries as Ruby expressions ▪ Columns are symbols ▪ Names come from SQL or Ruby ▪ One notation, one meaning

Slide 23

Slide 23 text

SQL queries as Ruby expressions ▪ No SQL in strings! ▪ Easy to read/write ▪ Automatic quoting

Slide 24

Slide 24 text

Why not Arel directly? ▪ Not a public API ▪ Verbose User.where(User.arel_table[:name].eq("Matz"))

Slide 25

Slide 25 text

Columns are symbols ▪ Bare names are ambiguous ▪ Column, local variable, or method? where { name == "Matz" } where { :name == "Matz" } # column? variable? method? # a column

Slide 26

Slide 26 text

Symbols are columns everywhere # Compares two columns where { :updated_at == :created_at } # ArgumentError if a symbol is not a column where { :status == :active } # An enum value is its string where { :status == "active" }

Slide 27

Slide 27 text

Names come from SQL or Ruby # SQL's names by default Author.select { avg(:age) } # not average Author.where { # not exist? exists?(Post.where { :posts[:author_id] == :authors[:id] }) } # Ruby's names when they fit better Doc.select { :meta.dig(:author, :name).as(:author) } Author.where { :name.start_with?("A") }

Slide 28

Slide 28 text

One notation, one meaning ▪ No overloading by SQL type ▪ + adds; concat concatenates ▪ & and | are AND and OR, never bitwise ▪ include? for substrings; member? for array elements

Slide 29

Slide 29 text

Supported RDBMSs ▪ SQLite ▪ PostgreSQL ▪ MySQL/MariaDB ▪ Oracle ▪ SQL Server

Slide 30

Slide 30 text

Dialect class hierarchy Dialect Sqlite Postgresql sqlite3 postgresql, postgis, pglite MysqlCompat Oracle SqlServer oracle_enhanced sqlserver Mysql Mariadb mysql2, trilogy mysql2, trilogy

Slide 31

Slide 31 text

Example: dig :meta.dig(:author, :name) -- SQLite "meta" -> '$.author.name' -- PostgreSQL "meta" #> '{"author","name"}' -- MySQL JSON_EXTRACT(`meta`, '$.author.name')

Slide 32

Slide 32 text

Example: filter count(:*).filter { :age < 50 } -- SQLite, PostgreSQL, and Oracle COUNT(*) FILTER (WHERE "age" < 50) -- MySQL, MariaDB, and SQL Server COUNT(CASE WHEN `age` < 50 THEN 1 END)

Slide 33

Slide 33 text

How to add a dialect class ExampleDialect < ActiveRecord::Refined::Dialect FUNCTIONS = { char_length: "LEN", rand: nil }.freeze def json_path(document, _dollar_path, steps, json_value, _model) Arel::Nodes::InfixOperation.new( json_value ? :"~>" : :"~>>", document, Arel::Nodes.build_quoted(steps)) end end ActiveRecord::Refined::Dialect.register("exampledb", ExampleDialect)

Slide 34

Slide 34 text

Performance benchmarks ▪ Query building only, no DB access ▪ Speed: queries built per second ▪ Memory: bytes per query built ▪ Simple case: :name == "alice"

Slide 35

Slide 35 text

Compared styles # hash User.where(name: "alice") # string User.where("name = ?", "alice") # Arel User.where(User.arel_table[:name].eq("alice")) # activerecord-refined User.where { :name == "alice" }

Slide 36

Slide 36 text

Queries built per second string 40.9k Arel 40.5k activerecord-refined 36.1k hash 31.5k ▪ Negligible compared with a DB round trip

Slide 37

Slide 37 text

Bytes per query built Arel 2,176 activerecord-refined 2,392 hash 2,576 string 2,976 ▪ Proc#refined: one ISeq copy per call site

Slide 38

Slide 38 text

Cost outside the block ▪ Global slowdown of Symbol#==: interpreter +18% YJIT +43%

Slide 39

Slide 39 text

A pitfall # "&" needs parentheses User.where { (:name == "Matz") & (:age > 50) } # Otherwise true & ... drops the condition User.where { :active == true & (:age > 50) } # WHERE "users"."active" = TRUE ▪ && can’t be redefined

Slide 40

Slide 40 text

Try it ▪ https://shugo.github.io/activerecord-refined/ ▪ ruby.wasm, SQLite, PGlite (via wasmify-rails)