SlideShare a Scribd company logo
1 of 16
ActiveRecordで
複雑なクエリを書くのは
間違っているのか
牧 俊男(@Kirika_K2)
ある日のこと
• 「Mysql2::Error: Lost connection to MySQL
server during query」というエラーが発生する。
• バッチサーバ(Resque)内で発生したエラーで
、コネクションがロストしたまま、他に何も出
なくなるという事象が発生。
Lost connectionが発生する理
由
• タイムアウトエラー
• 許容パケットの上限がサーバ設定値(
max_allowed_packet=4MB)を上回る
今回の原因はこっちだった。つまり4MBを超えるSQL文がある。
バッチ処理を止めるわけには
行かないので
max_allowed_packet
4MB → 16MB
エラーは出なくなり、バッチ処理は無事に再開された
あとで調査しようと思ってチケットだけ作った
その後事件は起こった
解決…したわけではなかった
• 別のタイミングで、全体の性能測定のため、ス
ロークエリをCloudWatchでの監視を開始
• すると、件の4MBを超えるSQL文がスロークエ
リログとして毎日CloudWatchに吐かれ始めた。
調査を開始
scope :job_sources, ->(process_at){
where(id: source_ids(process_at))
}
問題のSQLを生成している部分
• source_idsはクラスメソッドとして定義
• 大きく3つのクエリ(A、B、C)を投げて、pluckで
各クエリのIDを取得し、A + B - Cのidの配列を返す
• 問題はこのうちのAのクエリにあった
Aのクエリ
parent_ids =
Parent.where("schedule_at <= :process_hhmm AND
parent_id IS NULL", process_hhmm:
process_hhmm.to_i).pluck(:id)
children_ids =
Child.where(parent_id: parent_ids)
.where(is_disabled: false).pluck(:id)
Aのクエリ
parent_ids =
Parent.where("schedule_at <= :process_hhmm AND
parent_id IS NULL", process_hhmm:
process_hhmm.to_i).pluck(:id)
children_ids =
Child.where(parent_id: parent_ids)
.where(is_disabled: false).pluck(:id)
ここが数万件ある。しかも日々増殖している
その結果、parent_id IN (xxxxxx, xxxxxx, xxxxxx, …)
と数万件の文字列が並ぶことになり、SQL文が4MBを超える
どうしたか?
• A + B - C自体も、数が少ないとはいえ数百件の
IDを返すため1クエリで表現するSQL文を考える
。
• A + BをUNIONで、- CをNOT INの副問合せで表
現する。
最終的なSQL
SELECT m1.id from A m1
LEFT JOIN A m2 on m1.parent_id = m2.id
AND m2.is_disabled = 0
AND m2.deleted_at IS NULL
AND m2.type = "xxxxxxx"
WHERE m2.schedule_at <= 21180
AND m1.type = "X"
AND m1.`is_disabled` = 0
AND m1.deleted_at IS NULL
AND m1.id NOT IN (
SELECT m4.A_id from C m4
WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600)
UNION (
SELECT m3.id from A m3
WHERE m3.`deleted_at` IS NULL
AND ((m3.type = 'yyyyyyy'
AND m3.schedule_at <= 1531461195
AND truncate((m3.schedule_at + 32400) / 86400, 0) = 17725
AND m3.parent_id IS NOT NULL)
OR (m3.type = 'zzzzzzz'
AND m3.schedule_at <= 21180
AND m3.parent_id IS NULL)
OR (m3.type = 'xxxxxxxx'
AND m3.schedule_at <= 21180
AND m3.parent_id IS NOT NULL)
)
AND m3.is_disabled = 0
AND m3.id NOT IN (
SELECT m4.X_id from X m4
WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600)
)
Aのクエリ
Bのクエリ
Cのクエリ
Cのクエリ
問題はこのSQLを
ActiveRecordにどう書くか?
• find_by_sql
→ ActiveRecord::Relationが返らないのでNG
• JOINSの中にSQLをダイレクトに書いてしまう
→ 条件によってSQLが動的に変化するタイプのSQLを扱
うときは難しくなりそう
• Arel
→「RailsのPrivate APIだから使うな」との公式のご意見
もあるので、Railsのアップデートで引っかかる可能性も
高く、できれば避けたい…。
今回はArelで書きました
SELECT m1.id from A m1
LEFT JOIN A m2 on m1.parent_id = m2.id
AND m2.is_disabled = 0
AND m2.deleted_at IS NULL
AND m2.type = "xxxxxxx"
WHERE m2.schedule_at <= 21180
AND m1.type = "X"
AND m1.`is_disabled` = 0
AND m1.deleted_at IS NULL
AND m1.id NOT IN (
SELECT m4.A_id from C m4
WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600)
UNION (
SELECT m3.id from A m3
WHERE m3.`deleted_at` IS NULL
AND ((m3.type = 'yyyyyyy'
AND m3.schedule_at <= 1531461195
AND truncate((m3.schedule_at + 32400) / 86400, 0) = 17725
AND m3.parent_id IS NOT NULL)
OR (m3.type = 'zzzzzzz'
AND m3.schedule_at <= 21180
AND m3.parent_id IS NULL)
OR (m3.type = 'xxxxxxxx'
AND m3.schedule_at <= 21180
AND m3.parent_id IS NOT NULL)
)
AND m3.is_disabled = 0
AND m3.id NOT IN (
SELECT m4.X_id from X m4
WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600)
)
結合条件が複雑なので、Arel::Tableで各テーブルにエイリアスを用意
m1 = Arel::Table.new("A", as: "m1")
m2 = Arel::Table.new("A", as: "m2")
m3 = Arel::Table.new(“A", as: "m3")
m4 = Arel::Table.new("C", as: “m4”)
m1_m2 = m1.join(m2, Arel::InnerJoin).on(m1[:parent_id].eq(m2[:id]))
今回はArelで書きました
SELECT m1.id from A m1
LEFT JOIN A m2 on m1.parent_id = m2.id
AND m2.is_disabled = 0
AND m2.deleted_at IS NULL
AND m2.type = "xxxxxxx"
WHERE m2.schedule_at <= 21180
AND m1.type = "X"
AND m1.`is_disabled` = 0
AND m1.deleted_at IS NULL
AND m1.id NOT IN (
SELECT m4.A_id from C m4
WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600)
UNION (
SELECT m3.id from A m3
WHERE m3.`deleted_at` IS NULL
AND ((m3.type = 'yyyyyyy'
AND m3.schedule_at <= 1531461195
AND truncate((m3.schedule_at + 32400) / 86400, 0) = 17725
AND m3.parent_id IS NOT NULL)
OR (m3.type = 'zzzzzzz'
AND m3.schedule_at <= 21180
AND m3.parent_id IS NULL)
OR (m3.type = 'xxxxxxxx'
AND m3.schedule_at <= 21180
AND m3.parent_id IS NOT NULL)
)
AND m3.is_disabled = 0
AND m3.id NOT IN (
SELECT m4.X_id from X m4
WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600)
)
結合条件が複雑なので、Arel::Tableで各テーブルにエイリアスを用意
m1 = Arel::Table.new("A", as: "m1")
m2 = Arel::Table.new("A", as: "m2")
m3 = Arel::Table.new(“A", as: "m3")
m4 = Arel::Table.new("C", as: “m4”)
m1_m2 = m1.join(m2, Arel::InnerJoin).on(m1[:parent_id].eq(m2[:id]))
SQLの関数はArel::Nodes::NamedFunctionで、SQL内での演算は
Arel::Nodes::InfixOperationで実現可能。
op1 = Arel::Nodes::InfixOperation.new(‘+’, m3[:schedule_at], 32400)
op2 = Arel::Nodes::InfixOperation.new(‘/’,
Arel::Nodes::Grouping.new((op1), 86400)
Arel::Nodes::NamedFunction.new(‘truncate’, op2, 0)
今回はArelで書きました
SELECT m1.id from A m1
LEFT JOIN A m2 on m1.parent_id = m2.id
AND m2.is_disabled = 0
AND m2.deleted_at IS NULL
AND m2.type = "xxxxxxx"
WHERE m2.schedule_at <= 21180
AND m1.type = "X"
AND m1.`is_disabled` = 0
AND m1.deleted_at IS NULL
AND m1.id NOT IN (
SELECT m4.A_id from C m4
WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600)
UNION (
SELECT m3.id from A m3
WHERE m3.`deleted_at` IS NULL
AND ((m3.type = 'yyyyyyy'
AND m3.schedule_at <= 1531461195
AND truncate((m3.schedule_at + 32400) / 86400, 0) = 17725
AND m3.parent_id IS NOT NULL)
OR (m3.type = 'zzzzzzz'
AND m3.schedule_at <= 21180
AND m3.parent_id IS NULL)
OR (m3.type = 'xxxxxxxx'
AND m3.schedule_at <= 21180
AND m3.parent_id IS NOT NULL)
)
AND m3.is_disabled = 0
AND m3.id NOT IN (
SELECT m4.X_id from X m4
WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600)
)
結合条件が複雑なので、Arel::Tableで各テーブルにエイリアスを用意
m1 = Arel::Table.new("A", as: "m1")
m2 = Arel::Table.new("A", as: "m2")
m3 = Arel::Table.new(“A", as: "m3")
m4 = Arel::Table.new("C", as: “m4”)
m1_m2 = m1.join(m2, Arel::InnerJoin).on(m1[:parent_id].eq(m2[:id]))
SQLの関数はArel::Nodes::NamedFunctionで、SQL内での演算は
Arel::Nodes::InfixOperationで実現可能。
op1 = Arel::Nodes::InfixOperation.new(‘+’, m3[:schedule_at], 32400)
op2 = Arel::Nodes::InfixOperation.new(‘/’,
Arel::Nodes::Grouping.new((op1), 86400)
Arel::Nodes::NamedFunction.new(‘truncate’, op2, 0)
最後にActiveRecord::Relation#joinsでArelオブジェクトを渡して結合
original_table = OriginalTable.arel_table
picked_ids = Arel::Nodes::TableAlias.new(m1_m2.union(m3_m4), "picked_ids")
joins(original_table.join(picked_ids, Arel::Nodes::InnerJoin).
on(original_table[:id].eq(picked_uuids[:id])).join_sources)
まとめ
• where文に他のクエリで作った配列を突っ込むときは
、IN句で展開されるため、件数に注意しましょう。
• 書いたArelについては、メンバーからは「読めない」
というコメントも貰ったので、Arelに傾倒するのも厳
しい。
• SQL文自体が変化しないのであれば、JOINS(“SQL文
”)が一番いいかも。他にご意見あればお話したいです
。

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

ActiveRecordで複雑なクエリを書くのは間違っているのか

  • 2. ある日のこと • 「Mysql2::Error: Lost connection to MySQL server during query」というエラーが発生する。 • バッチサーバ(Resque)内で発生したエラーで 、コネクションがロストしたまま、他に何も出 なくなるという事象が発生。
  • 3. Lost connectionが発生する理 由 • タイムアウトエラー • 許容パケットの上限がサーバ設定値( max_allowed_packet=4MB)を上回る 今回の原因はこっちだった。つまり4MBを超えるSQL文がある。
  • 7. 調査を開始 scope :job_sources, ->(process_at){ where(id: source_ids(process_at)) } 問題のSQLを生成している部分 • source_idsはクラスメソッドとして定義 • 大きく3つのクエリ(A、B、C)を投げて、pluckで 各クエリのIDを取得し、A + B - Cのidの配列を返す • 問題はこのうちのAのクエリにあった
  • 8. Aのクエリ parent_ids = Parent.where("schedule_at <= :process_hhmm AND parent_id IS NULL", process_hhmm: process_hhmm.to_i).pluck(:id) children_ids = Child.where(parent_id: parent_ids) .where(is_disabled: false).pluck(:id)
  • 9. Aのクエリ parent_ids = Parent.where("schedule_at <= :process_hhmm AND parent_id IS NULL", process_hhmm: process_hhmm.to_i).pluck(:id) children_ids = Child.where(parent_id: parent_ids) .where(is_disabled: false).pluck(:id) ここが数万件ある。しかも日々増殖している その結果、parent_id IN (xxxxxx, xxxxxx, xxxxxx, …) と数万件の文字列が並ぶことになり、SQL文が4MBを超える
  • 10. どうしたか? • A + B - C自体も、数が少ないとはいえ数百件の IDを返すため1クエリで表現するSQL文を考える 。 • A + BをUNIONで、- CをNOT INの副問合せで表 現する。
  • 11. 最終的なSQL SELECT m1.id from A m1 LEFT JOIN A m2 on m1.parent_id = m2.id AND m2.is_disabled = 0 AND m2.deleted_at IS NULL AND m2.type = "xxxxxxx" WHERE m2.schedule_at <= 21180 AND m1.type = "X" AND m1.`is_disabled` = 0 AND m1.deleted_at IS NULL AND m1.id NOT IN ( SELECT m4.A_id from C m4 WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600) UNION ( SELECT m3.id from A m3 WHERE m3.`deleted_at` IS NULL AND ((m3.type = 'yyyyyyy' AND m3.schedule_at <= 1531461195 AND truncate((m3.schedule_at + 32400) / 86400, 0) = 17725 AND m3.parent_id IS NOT NULL) OR (m3.type = 'zzzzzzz' AND m3.schedule_at <= 21180 AND m3.parent_id IS NULL) OR (m3.type = 'xxxxxxxx' AND m3.schedule_at <= 21180 AND m3.parent_id IS NOT NULL) ) AND m3.is_disabled = 0 AND m3.id NOT IN ( SELECT m4.X_id from X m4 WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600) ) Aのクエリ Bのクエリ Cのクエリ Cのクエリ
  • 12. 問題はこのSQLを ActiveRecordにどう書くか? • find_by_sql → ActiveRecord::Relationが返らないのでNG • JOINSの中にSQLをダイレクトに書いてしまう → 条件によってSQLが動的に変化するタイプのSQLを扱 うときは難しくなりそう • Arel →「RailsのPrivate APIだから使うな」との公式のご意見 もあるので、Railsのアップデートで引っかかる可能性も 高く、できれば避けたい…。
  • 13. 今回はArelで書きました SELECT m1.id from A m1 LEFT JOIN A m2 on m1.parent_id = m2.id AND m2.is_disabled = 0 AND m2.deleted_at IS NULL AND m2.type = "xxxxxxx" WHERE m2.schedule_at <= 21180 AND m1.type = "X" AND m1.`is_disabled` = 0 AND m1.deleted_at IS NULL AND m1.id NOT IN ( SELECT m4.A_id from C m4 WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600) UNION ( SELECT m3.id from A m3 WHERE m3.`deleted_at` IS NULL AND ((m3.type = 'yyyyyyy' AND m3.schedule_at <= 1531461195 AND truncate((m3.schedule_at + 32400) / 86400, 0) = 17725 AND m3.parent_id IS NOT NULL) OR (m3.type = 'zzzzzzz' AND m3.schedule_at <= 21180 AND m3.parent_id IS NULL) OR (m3.type = 'xxxxxxxx' AND m3.schedule_at <= 21180 AND m3.parent_id IS NOT NULL) ) AND m3.is_disabled = 0 AND m3.id NOT IN ( SELECT m4.X_id from X m4 WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600) ) 結合条件が複雑なので、Arel::Tableで各テーブルにエイリアスを用意 m1 = Arel::Table.new("A", as: "m1") m2 = Arel::Table.new("A", as: "m2") m3 = Arel::Table.new(“A", as: "m3") m4 = Arel::Table.new("C", as: “m4”) m1_m2 = m1.join(m2, Arel::InnerJoin).on(m1[:parent_id].eq(m2[:id]))
  • 14. 今回はArelで書きました SELECT m1.id from A m1 LEFT JOIN A m2 on m1.parent_id = m2.id AND m2.is_disabled = 0 AND m2.deleted_at IS NULL AND m2.type = "xxxxxxx" WHERE m2.schedule_at <= 21180 AND m1.type = "X" AND m1.`is_disabled` = 0 AND m1.deleted_at IS NULL AND m1.id NOT IN ( SELECT m4.A_id from C m4 WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600) UNION ( SELECT m3.id from A m3 WHERE m3.`deleted_at` IS NULL AND ((m3.type = 'yyyyyyy' AND m3.schedule_at <= 1531461195 AND truncate((m3.schedule_at + 32400) / 86400, 0) = 17725 AND m3.parent_id IS NOT NULL) OR (m3.type = 'zzzzzzz' AND m3.schedule_at <= 21180 AND m3.parent_id IS NULL) OR (m3.type = 'xxxxxxxx' AND m3.schedule_at <= 21180 AND m3.parent_id IS NOT NULL) ) AND m3.is_disabled = 0 AND m3.id NOT IN ( SELECT m4.X_id from X m4 WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600) ) 結合条件が複雑なので、Arel::Tableで各テーブルにエイリアスを用意 m1 = Arel::Table.new("A", as: "m1") m2 = Arel::Table.new("A", as: "m2") m3 = Arel::Table.new(“A", as: "m3") m4 = Arel::Table.new("C", as: “m4”) m1_m2 = m1.join(m2, Arel::InnerJoin).on(m1[:parent_id].eq(m2[:id])) SQLの関数はArel::Nodes::NamedFunctionで、SQL内での演算は Arel::Nodes::InfixOperationで実現可能。 op1 = Arel::Nodes::InfixOperation.new(‘+’, m3[:schedule_at], 32400) op2 = Arel::Nodes::InfixOperation.new(‘/’, Arel::Nodes::Grouping.new((op1), 86400) Arel::Nodes::NamedFunction.new(‘truncate’, op2, 0)
  • 15. 今回はArelで書きました SELECT m1.id from A m1 LEFT JOIN A m2 on m1.parent_id = m2.id AND m2.is_disabled = 0 AND m2.deleted_at IS NULL AND m2.type = "xxxxxxx" WHERE m2.schedule_at <= 21180 AND m1.type = "X" AND m1.`is_disabled` = 0 AND m1.deleted_at IS NULL AND m1.id NOT IN ( SELECT m4.A_id from C m4 WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600) UNION ( SELECT m3.id from A m3 WHERE m3.`deleted_at` IS NULL AND ((m3.type = 'yyyyyyy' AND m3.schedule_at <= 1531461195 AND truncate((m3.schedule_at + 32400) / 86400, 0) = 17725 AND m3.parent_id IS NOT NULL) OR (m3.type = 'zzzzzzz' AND m3.schedule_at <= 21180 AND m3.parent_id IS NULL) OR (m3.type = 'xxxxxxxx' AND m3.schedule_at <= 21180 AND m3.parent_id IS NOT NULL) ) AND m3.is_disabled = 0 AND m3.id NOT IN ( SELECT m4.X_id from X m4 WHERE m4.`deleted_at` IS NULL AND m4.`process_on` = 1531407600) ) 結合条件が複雑なので、Arel::Tableで各テーブルにエイリアスを用意 m1 = Arel::Table.new("A", as: "m1") m2 = Arel::Table.new("A", as: "m2") m3 = Arel::Table.new(“A", as: "m3") m4 = Arel::Table.new("C", as: “m4”) m1_m2 = m1.join(m2, Arel::InnerJoin).on(m1[:parent_id].eq(m2[:id])) SQLの関数はArel::Nodes::NamedFunctionで、SQL内での演算は Arel::Nodes::InfixOperationで実現可能。 op1 = Arel::Nodes::InfixOperation.new(‘+’, m3[:schedule_at], 32400) op2 = Arel::Nodes::InfixOperation.new(‘/’, Arel::Nodes::Grouping.new((op1), 86400) Arel::Nodes::NamedFunction.new(‘truncate’, op2, 0) 最後にActiveRecord::Relation#joinsでArelオブジェクトを渡して結合 original_table = OriginalTable.arel_table picked_ids = Arel::Nodes::TableAlias.new(m1_m2.union(m3_m4), "picked_ids") joins(original_table.join(picked_ids, Arel::Nodes::InnerJoin). on(original_table[:id].eq(picked_uuids[:id])).join_sources)