0

我有一个 Railsfind_by_sql方法可以在本地、控制台和语句中正常工作,也可以直接在 Postgresql 中使用,但是ActiveRecord::StatementInvalid当我将它部署到 Heroku 时,该语句会导致错误。

我在本地运行 Postgresql 版本 9.0.3,并在其 Cedar 堆栈上的 Heroku 上使用共享数据库。

我得到的错误是:

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 Charts 一起使用的统计信息,输出为:

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
4

2 回答 2

3

Heroku 的共享计划运行PostgreSQL 8.3不支持WITH关键字(在 中介绍PostgreSQL 8.4)。

如果您升级到 Heroku 的专用数据库包,您将能够使用PostgreSQL 9.1.

于 2012-05-08T21:56:06.227 回答
2

默认的 Heroku 共享数据库是 Postgres 8.3 - 您可以在共享数据库计划的公开测试版中使用 9.1 - 更多详细信息,请访问https://postgres.heroku.com/blog/past/2012/4/26/heroku_postgres_development_plan/

对于生产,您可以以每月 50 美元的价格使用新宣布的 Crane 计划https://postgres.heroku.com/blog/past/2012/4/26/heroku_postgres_development_plan/

于 2012-05-08T22:06:25.303 回答