コンソールでローカルに正常に動作するRailsfind_by_sql
メソッドとPostgresqlで直接ステートメントを使用していますが、ActiveRecord::StatementInvalid
Herokuにデプロイするとステートメントがエラーを引き起こします。
Postgresql バージョン 9.0.3 をローカルで実行し、Heroku の Cedar スタックで共有データベースを使用しています。
私が得ているエラーは次のとおりです。
PG::Error: ERROR: syntax error at or near "WITH normal_items" LINE 1: WITH normal_items AS (SELECT normal_items_month, count(id)... ^ : WITH normal_items AS (SELECT normal_items_month, count(id) as normal_items_total FROM (SELECT date_trunc('month',created_at) as normal_items_month, id from items WHERE items.a_foreign_key_id IS NULL) z group by normal_items_month), special_items AS (SELECT special_items_month, count(id) as special_items_total FROM (SELECT date_trunc('month',created_at) as special_items_month, id from items WHERE items.a_foreign_key_id IS NOT NULL) x group by special_items_month ) SELECT to_char(month, 'fmMon') as month, coalesce(normal_items_total, 0) as normal_items_total, coalesce(special_items_total, 0) as special_items_total FROM (select generate_series(min(normal_items_month), max(normal_items_month), '1 month'::interval) as month FROM normal_items) m LEFT OUTER JOIN normal_items ON normal_items_month = month LEFT OUTER JOIN special_items ON special_items_month = month
読みやすくするために、ステートメントは次のとおりです。
WITH normal_items AS (SELECT normal_items_month, count(id) as normal_items_total
FROM (SELECT date_trunc('month',created_at) as normal_items_month, id from items
WHERE items.a_foreign_key_id IS NULL) z
group by normal_items_month),
special_items AS (SELECT special_items_month, count(id) as special_items_total
FROM (SELECT date_trunc('month',created_at) as special_items_month, id from items
WHERE items.a_foreign_key_id IS NOT NULL) x
group by special_items_month )
SELECT
to_char(month, 'fmMon') as month,
coalesce(normal_items_total, 0) as normal_items_total,
coalesce(special_items_total, 0) as special_items_total
FROM (select generate_series(min(normal_items_month), max(normal_items_month), '1 month'::interval) as month FROM normal_items) m
LEFT OUTER JOIN normal_items ON normal_items_month = month
LEFT OUTER JOIN special_items ON special_items_month = month
これは、Google チャートで使用する統計情報を提供するだけです。出力は次のとおりです。
Jun 178 0
Jul 0 0
Aug 72 0
Sep 189 0
Oct 24 0
Nov 6 0
Dec 578 0
Jan 0 0
Feb 0 0
Mar 89 0
Apr 607 0
May 281 0
Jun 510 0
Jul 190 0
Aug 0 0
Sep 501 0
Oct 409 0
Nov 704 0