Postgresql syntax error at or near "(" - ruby-on-rails

I trying to write some condition to pull out objects from database:
Page.where(published: true).where("`published_at` <= current_date()").where("`publication_end` IS NULL OR `publication_end` > current_date()")
When i enter it in the rails console i have the following error:
SELECT "pages".* FROM "pages" WHERE "pages"."published" = 't' AND (`published_at` <= current_date()) AND (`publication_end` IS NULL OR `publication_end` > current_date())
PG::SyntaxError: ERROR: syntax error at or near "("
LINE 1: ...blished" = 't' AND (`published_at` <= current_date()) AND (`...
^
: SELECT "pages".* FROM "pages" WHERE "pages"."published" = 't' AND (`published_at` <= current_date()) AND (`publication_end` IS NULL OR `publication_end` > current_date())
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near "("
LINE 1: ...blished" = 't' AND (`published_at` <= current_date()) AND (`...
^
: SELECT "pages".* FROM "pages" WHERE "pages"."published" = 't' AND (`published_at` <= current_date()) AND (`publication_end` IS NULL OR `publication_end` > current_date())
I,m Using Postgresql
Please help.

Remove the parentheses:
# select current_date();
ERROR: syntax error at or near "("
LINE 1: select current_date();
# select current_date;
date
------------
2014-02-19
(1 row)

i write:
Page.where(published: true).where("published_at <= current_date").where("publication_end IS NULL OR publication_end > current_date")
and now i ok
Thanks :)

Related

ActiveRecord AND + OR condition with multiple criteria

I'm using ActiveRecord to build a query and I got a parenthesis issue with generated SQL.
Here is a query creating my problem
joined_users = User.joins(:consumer)
users = joined_users.where(id: (1..3), name: 'foo').or(joined_users.where(consumer: {id: (1...4))
It creates the following SQL
SELECT "users".* FROM "users" INNER JOIN "consumers" "consumer" ON "consumer"."user_id" = "users"."id" WHERE ("users"."id" BETWEEN 1 AND 3 AND "users"."name" = 'foo' OR "consumer"."id" >= 1 AND "consumer"."id" < 4)
But actually, it should be
SELECT "users".* FROM "users" INNER JOIN "consumers" "consumer" ON "consumer"."user_id" = "users"."id" WHERE (("users"."id" BETWEEN 1 AND 3 AND "users"."name" = 'foo') OR ("consumer"."id" >= 1 AND "consumer"."id" < 4))
Do you get my point?
There are missing parenthesis separating the first where to the second with the or.
Bool logic is not the same at all with and without these parenthesis.
What am I missing?
I your particular case there should be no difference in query result, because logical AND operator has higher priority than logical OR, so:
A && B || C && D equals (A && B) || (C && D)
ActiveRecord will add parenthesis when it is needed, for example:
User.where(id: 1..3).or(User.where(id: 4...5)).where(email: 'some')
Will result in:
SELECT "users".* FROM "users" WHERE ("users"."id" BETWEEN 1 AND 3 OR "users"."id" >= 4 AND "users"."id" < 5) AND "users"."email" = 'some'

select columns from a table named ">"

For some reason my code created a series named ">" into influxdb database. I need to delete this series.
> show series
key
---
>,Test_Prog=python,User=unknown
Bazooka,Test_Name=helloworld,Test_Prog=C,User=unknown
I tried
> drop series from ">"
>
> drop series from "\>"
ERR: error parsing query: found \>, expected identifier at line 1, char 20
> drop series from "\\>"
>
> drop series from "\">\""
>
but nothing works. Furthermore I cant even access this series.
> select * from >
ERR: error parsing query: found >, expected identifier at line 1, char 15
> select * from ">"
> select * from '>'
ERR: error parsing query: found >, expected identifier at line 1, char 14
> select * from '\>'
ERR: error parsing query: found \>, expected identifier at line 1, char 17
> select * from "\>"
ERR: error parsing query: found \\>, expected identifier at line 1, char 17
> select * from "\\>"
>
> select * from "\u003E"
ERR: error parsing query: found \u, expected identifier at line 1, char 17
> select * from "\\u003E"
>
Is there any other way to access/delete this series?
Try DROP MEASUREMENT ">"
It's a series within the ">" measurement

Weird behavior of CAST with 0 in rails

Sorry for long query but its what im working with.
I got this query in rails
#posts = Cama::PostType.first.posts.joins(:custom_field_values).where("(status = ?) AND (cama_custom_fields_relationships.custom_field_slug = ? AND
CAST(cama_custom_fields_relationships.value AS INTEGER) >= ? AND
CAST(cama_custom_fields_relationships.value AS INTEGER) <= ? ) OR
(cama_custom_fields_relationships.custom_field_slug = ? AND
CAST(cama_custom_fields_relationships.value AS INTEGER) >= ? AND
CAST(cama_custom_fields_relationships.value AS INTEGER) <= ? ) AND
(LOWER(title) LIKE ? OR LOWER(content_filtered) LIKE ?)","published", "filtry-
powierzchnia", params['size-start'].to_i, params['size-end'].to_i,"filtry-
cena", params['price-start'].to_i, params['price-end'].to_i
,"%#{params[:q]}%",
"%#{params[:q]}%").group("cama_posts.id").having("COUNT(cama_custom_fields_rel
ationships.objectid) >= 2")
that make this sql
CamaleonCms::Post Load (0.9ms) SELECT "cama_posts".* FROM "cama_posts"
INNER JOIN "cama_custom_fields_relationships" ON
"cama_custom_fields_relationships"."objectid" = "cama_posts"."id" AND
"cama_custom_fields_relationships"."object_class" = $1 WHERE
"cama_posts"."post_class" = $2 AND "cama_posts"."taxonomy_id" = $3 AND
((status = 'published') AND
(cama_custom_fields_relationships.custom_field_slug = 'filtry-powierzchnia'
AND CAST(cama_custom_fields_relationships.value AS INTEGER) >= 1 AND
CAST(cama_custom_fields_relationships.value AS INTEGER) <= 10000 ) OR
(cama_custom_fields_relationships.custom_field_slug = 'filtry-cena' AND
CAST(cama_custom_fields_relationships.value AS INTEGER) >= 0 AND
CAST(cama_custom_fields_relationships.value AS INTEGER) <= 10000000 ) AND
(LOWER(title) LIKE '%%' OR LOWER(content_filtered) LIKE '%%')) GROUP BY
cama_posts.id HAVING (COUNT(cama_custom_fields_relationships.objectid) >= 2)
ORDER BY "cama_posts"."post_order" ASC, "cama_posts"."created_at" DESC LIMIT
$4 OFFSET $5 [["object_class", "Post"], ["post_class", "Post"],
["taxonomy_id", 2], ["LIMIT", 6], ["OFFSET", 0]]
As you can see Im using CAST, I can't change column just to integer, because its CMS. I created custom_field that suppoust to be integer but table in db is still text so im forced to do it that way.
Now everything is ok if my
..CAST(cama_custom_fields_relationships.value AS INTEGER) >= 1..
but when this value will be 0
so when my query will look like
CamaleonCms::Post Load (0.9ms) SELECT "cama_posts".* FROM "cama_posts"
INNER JOIN "cama_custom_fields_relationships" ON
"cama_custom_fields_relationships"."objectid" = "cama_posts"."id" AND
"cama_custom_fields_relationships"."object_class" = $1 WHERE
"cama_posts"."post_class" = $2 AND "cama_posts"."taxonomy_id" = $3 AND
((status = 'published') AND
(cama_custom_fields_relationships.custom_field_slug = 'filtry-powierzchnia'
AND ****CAST(cama_custom_fields_relationships.value AS INTEGER) >= 0**** AND
CAST(cama_custom_fields_relationships.value AS INTEGER) <= 10000 ) OR
(cama_custom_fields_relationships.custom_field_slug = 'filtry-cena' AND
CAST(cama_custom_fields_relationships.value AS INTEGER) >= 0 AND
CAST(cama_custom_fields_relationships.value AS INTEGER) <= 10000000 ) AND
(LOWER(title) LIKE '%%' OR LOWER(content_filtered) LIKE '%%')) GROUP BY
cama_posts.id HAVING (COUNT(cama_custom_fields_relationships.objectid) >= 2)
ORDER BY "cama_posts"."post_order" ASC, "cama_posts"."created_at" DESC LIMIT
$4 OFFSET $5 [["object_class", "Post"], ["post_class", "Post"],
["taxonomy_id", 2], ["LIMIT", 6], ["OFFSET", 0]]
Im getting error:
ActionView::Template::Error (PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "/media/1/asd.jpg"
: SELECT "cama_posts".* FROM "cama_posts" INNER JOIN "cama_custom_fields_relationships" ON "cama_custom_fields_relationships"."objectid" = "cama_posts"."id" AND "cama_custom_fields_relationships"."object_class" = $1 WHERE "cama_posts"."post_class" = $2 AND "cama_posts"."taxonomy_id" = $3 AND ((status = 'published') AND (cama_custom_fields_relationships.custom_field_slug = 'filtry-powierzchnia' AND CAST(cama_custom_fields_relationships.value AS INTEGER) >= 0 AND CAST(cama_custom_fields_relationships.value AS INTEGER) <= 10000 ) OR (cama_custom_fields_relationships.custom_field_slug = 'filtry-cena' AND CAST(cama_custom_fields_relationships.value AS INTEGER) >= 0 AND CAST(cama_custom_fields_relationships.value AS INTEGER) <= 10000000 ) AND (LOWER(title) LIKE '%%' OR LOWER(content_filtered) LIKE '%%')) GROUP BY cama_posts.id HAVING (COUNT(cama_custom_fields_relationships.objectid) >= 2) ORDER BY "cama_posts"."post_order" ASC, "cama_posts"."created_at" DESC LIMIT $4 OFFSET $5):
and #posts return it on the query lvl so its not error that occurs somewhere else.
I tried CASTing to numeric, same problem. It only happens when its starting condition, when there is another condition before it, it accepts 0 like in my example, the second condition after this one works with >= 0

Ruby ActiveRecord group and average "syntax error at or near "AS""

params = {device_id: "u100", device_point: "1", point_no: "1", max_date: "2016-12-01 12:00", min_date: "2016-12-01 11:40"}
I am working in a ruby/rails environment with a PG database.
I am trying to add to my device controller to use ActiveRecord to get 10 minute averages from a some dummy sensor data.
I can group by minute fine with;
.group("date_trunc('minute', device_time)").average('point_data_val')
e.g
device_data = DeviceDatum.select('device_time, point_data_val').filter(params.slice(:device_id, :device_point, :point_no, :iot_version, :iot_time, :device_time, :point_data_type, :point_data_val, :point_bat_val,:min_val, :max_val, :min_date, :max_date)).limit(1008).group("date_trunc('minute', device_time)").average('point_data_val')
(240.3ms) SELECT AVG("device_data"."point_data_val") AS average_point_data_val, date_trunc('minute', device_time) AS date_trunc_minute_device_time FROM "device_data" WHERE "device_data"."device_id" = $1 AND "device_data"."device_point" = $2 AND "device_data"."point_no" = $3 AND (device_time >= '2016-12-01 11:40') AND (device_time <= '2016-12-01 12:00') GROUP BY date_trunc('minute', device_time) LIMIT 1008 [["device_id", "u100"], ["device_point", 1], ["point_no", 1]]
=> {2016-12-01 11:41:00 +0900=>#<BigDecimal:7f91599cfbc0,'-0.4816E1',18(27)>, 2016-12-01 11:51:00 +0900=>#<BigDecimal:7f91599cf8f0,'-0.4868E1',18(27)>}
I found this method to do it
But when I try and use AS in the group method
DeviceDatum.select('device_time, point_data_val')
.filter(params.slice(:device_id, :device_point, :point_no, :iot_version, :iot_time, :device_time,
:point_data_type, :point_data_val, :point_bat_val,:min_val, :max_val, :min_date,
:max_date)).limit(1008)
.group("date_trunc('hour', device_time) AS hour_stump,
(extract(minute FROM device_time)::int / 10)
AS min10_slot,count(*)").average('point_data_val')
I am getting this error.
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near "AS"
LINE 1: ... 12:00') GROUP BY date_trunc('hour', device_time) AS hour_st... : SELECT AVG("device_data"."point_data_val") AS average_point_data_val, date_trunc('hour', device_time) AS hour_stump,(extract(minute FROM device_time)::int / 10) AS min10_slot,count(*) AS date_trunc_hour_device_time_as_hour_stump_extract_minute_from_d FROM "device_data" WHERE "device_data"."device_id" = $1 AND "device_data"."device_point" = $2 AND "device_data"."point_no" = $3 AND (device_time >= '2016-12-01 11:40') AND (device_time <= '2016-12-01 12:00') GROUP BY date_trunc('hour', device_time) AS hour_stump,(extract(minute FROM device_time)::int / 10) AS min10_slot,count(*) LIMIT 1008
from ...../bundle/ruby/2.1.0/gems/activerecord-4.2.6/lib/active_record/connection_adapters/postgresql_adapter.rb:637:in `prepare'
ActiveRecord seems to be using the options from the group method in sql it generates for average as well.
SELECT
AVG("device_data"."point_data_val") AS average_point_data_val,
date_trunc('hour', device_time) AS hour_stump,
(
extract(minute
FROM
device_time)::int / 10
)
AS min10_slot,
count(*) AS date_trunc_hour_device_time_as_hour_stump_extract_minute_from_d
FROM
"device_data"
WHERE
"device_data"."device_id" = $1
AND "device_data"."device_point" = $2
AND "device_data"."point_no" = $3
AND
(
device_time >= '2016-12-01 11:40'
)
AND
(
device_time <= '2016-12-01 12:00'
)
GROUP BY
date_trunc('hour', device_time) AS hour_stump,
(
extract(minute
FROM
device_time)::int / 10
)
AS min10_slot,
count(*) LIMIT 1008
What am I missing here?
I think that your group clause should look like this:
group("hour_stump, min10_slot,
date_trunc_hour_device_time_as_hour_stump_extract_minute_from_d")
if you use aliases in select clause. As #Fallenhero and #Iceman said, aliases in group by are not allowed.
If aliases are substituted in select automatically, I think the only way is to use functions as is
group("date_trunc('hour', device_time),
(extract(minute FROM device_time)::int / 10), count(*)")
.

PG::SyntaxError: ERROR: syntax error at or near "AS" Error Rails 4.1

I just upgraded rails to 4.1 and am getting this error:
PG::SyntaxError: ERROR: syntax error at or near "AS"
LINE 1: SELECT COUNT(count_column) FROM (SELECT * AS count_column F...
^
: SELECT COUNT(count_column) FROM (SELECT * AS count_column FROM (SELECT thread_id, max(id) as id FROM "messages" WHERE 1=0 AND (thread_id IS NOT NULL) GROUP BY thread_id) last JOIN messages ON messages.id = last.id LIMIT 5 OFFSET 0) subquery_for_count
Here is the method:
- as_myself do
%li#messages-open.icon-btn.email
- message_count = inbox_messages.count.is_a?(Hash) ? inbox_messages.count.values.first : inbox_messages.count
- if(message_count.present? && message_count > 0)
%span= message_count
New syntax in rails 4.1 is count(:all) fixed my problem.

Resources