Alasql and Breeze entities, does this work? - breeze

I have the following object below which is a breeze.js entity. I am trying to do a basic group by function. In this case it is throwing an error. Is the issue is that Breeze entities are not supported? Basic select statements are working fine on this object!
Object-
count:1
description:"1 sweepstake ticket"
displayName:"1 sweepstake ticket"
payload:"1"
rewardId:14
type:3
var res = alasql('SELECT type, SUM(count) AS b FROM ? group by type', [data]);
console.log(res);
Getting this error:
{message: "Parse error on line 1:↵...LECT type, SUM(count) AS…-------------------^↵Expecting 'LPAR', got 'RPAR'", hash: Object}hash: Objectexpected: Array[1]0: "'LPAR'"length: 1__proto__: Array[0]line: 0loc: Objecttext: ")"token: "RPAR"proto: Objectmessage: "Parse error on line 1:↵...LECT type, SUM(count) AS b FROM ? group ↵-----------------------^↵Expecting 'LPAR', got 'RPAR'"proto: Error()(anonymous function) # angular.js:11655(anonymous function) # angular.js:8596(anonymous function) # angular.js:13256$eval # angular.js:14466$digest # angular.js:14282(anonymous function) # angular.js:14505e # angular.js:4924(anonymous function) # angular.js:5312
8notificationService.js:84 poller callback
Thanks

Resolved on the github site.
Here count is a AlaSQL's keyword, so can you rewrite the query with
enclosed [count] or backquotes count:
var res = alasql('SELECT type, SUM([count]) AS b FROM ? GROUP BY type', [data]);
https://github.com/agershun/alasql/issues/733

Related

How to Rescue ActiveRecord::StatementInvalid Error

Does anyone know how to rescue this ActiveRecord::StatementInvalid error in rails? The console displays "PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer...". I've tried inserting a pry into the rescue block, but it's never called.
if (resource_params[:term].present?)
begin
key = resource_params[:term]
scope = scope.where("id = ? OR item_type = ? OR item_id = ? OR event = ? OR object ILIKE ?", key, key, key, key, "%#{key}%")
rescue
# handle error
end
end
Please note that I know how to prevent the error from occurring (i.e. need to convert the key to type integer for the id columns). But, I'm trying to understand why it never reaches the rescue block.
UPDATE: my initial post contained a syntax error (namely: rescue e => error) as others correctly pointed out. i'm still receiving the same error without the syntax error; i've update the code to remove the incorrect syntax.
This isn't the correct syntax for rescue:
rescue e => error
if I try and use this I get undefined local variable or method 'e'
The standard way to rescue a specific error class is to use:
rescue ActiveRecord::StatementInvalid => e
To do a "naked rescue" (which is often advised against), leave out the class name:
rescue => e
Note that in all these cases the => e can be left out if you don't need a variable pointing to the error object.
rescue ActiveRecord::StatementInvalid => e is the right syntax and should work fine, but also keep in mind that exception should actually be raised within that block.
rails executes a query when we actually try using its output(for example rendering page where we are displaying output of a query).

undefined method 'exec_prepared' on Rails 4 postgresql query

Every time, I submit a form supposed to create a Deal and sending a very high nb of Prizes (>200K) to the Prize table using a transaction and raw postgresql, I have first the error 'undefined method exec_prepared' then if I reload the form then I get a new error 'ERROR: prepared statement 'xixie' already exists'.
I used this question wrong number of arguments (1 for 2..3) for Active Record postgresql query (Rails 4/postgresql 9.4) and Prepared Statement on Postgresql in Rails to create the following Postgresql query:
models deals.rb
CONNEXION = ActiveRecord::Base.connection.raw_connection
def create_prizes
Deal.transaction do
self.prize_number.times do |i|
st = CONNEXION.prepare('xixie', 'INSERT INTO prizes (deal_id) values ($1)')
values = [ { value: self.id} ]
st.exec_prepared('xixie', values )
st.close()
end
end
end
I have this problem in Local (not production) and I am not using any puma/unicorn. I do use Zeus and Guard.
Is it impossible with Rails4/postgresql prepared_statements to insert multiple rows at a time ?
How can I change the query to make it work ?
Also as Rails gives me ' ERROR: prepared statement 'xixie' already exists', I had to change multiple times the name of the prepared_statements but will they "live" forever? how can I "kill" them after I do all theses iterations trying to find the appropriate query.
EDIT
Updated the code after some proposed answer:
CONNECTION = ActiveRecord::Base.connection.raw_connection
def create_prizes
Deal.transaction do
self.prize_number.times do |i|
CONNECTION.prepare('mimiku', 'INSERT INTO deal_prizes (deal_id, created_at, updated_at) values ($1, $2, $3)')
CONNECTION.exec_prepared('mimiku', [ { value: self.id}, { value: '2009-01-23 20:21:13' }, { value: '2009-01-23 20:21:13' } ] )
end
# CONNECTION.close()
end
end
(added '2009-01-23 20:21:13' as Rails required created_at and updated_at for some reason).
I get this error:
ERROR: prepared statement "mimiku" already exists
Even if I change the name from 'mimiku' to 'somethingelse', I still get this type of error.
The prepare method returns a result according to the docs:
http://deveiate.org/code/pg/PG/Connection.html#method-i-prepare
Maybe try call exec_prepared on the connection object
connection = ActiveRecord::Base.connection.raw_connection
def create_prizes
begin
connection.describe_prepared('xixie')
rescue PG::InvalidSqlStatementName
connection.prepare('xixie', 'INSERT INTO prizes (deal_id) values ($1)')
end
Deal.transaction do
self.prize_number.times do |i|
connection.exec_prepared('xixie', [ { value: self.id} ] )
end
end
end
UPDATE: I reworked the code above to first check if a prepared statement exists. If it doesn't exist it creates it. Sorry I haven't realized it in the first place but you don't need to prepare a statement more than once. This is the actual benefit of such a statement, since it has to be only parsed once and can than be executed with different values, which is then much faster than a regular query.
As prepared statements last for the duration of the AR connection you only need to prepare it once.

Query multiple key values with Rails + Postgres hstore

I am trying to make a query to search for values in my hstore column properties. I am filtering issues by user input by attribute. It is possible to search Issues where email is X, or Issues where email is X and the sender is "someone". Soon I need to change to search using LIKE for similar results. So if you know how to do it with LIKE also, show both options please.
If I do this:
Issue.where("properties #> ('email => pugozufil#yahoo.com') AND properties #> ('email => pugozufil#yahoo.com')")
it returns a issue.
If I do this:
Issue.where("properties #> ('email => pugozufil#yahoo.com') AND properties #> ('sender => someone')")
Here I got an error, telling me:
ERROR: Syntax error near 'd' at position 11
I change the "#>" to "->" and now this error is displayed:
PG::DatatypeMismatch: ERROR: argument of AND must be type boolean, not type text
I need to know how to query the properties with more than one key/value pair, with "OR" or "AND", doesn't matter.
I wish to get one or more results that include those values I am looking for.
I end up doing like this. Using the array option of the method where. Also using the suggestion from #anusha in the comments. IDK why the downvote though, I couldn't find anything on how to do something simple like this. I had doubt in formatting my query and mostly with hstore. So I hope it helps someone in the future as sure it did for me now.
if params[:filter].present?
filters = params[:filter]
conditions = ["properties -> "]
query_values = []
filter_query = ""
filters.each do |k, v|
if filters[k].present?
filter_query += "'#{k}' LIKE ?"
filter_query += " OR "
query_values << "%#{v}%"
end
end
filter_query = filter_query[0...-(" OR ".size)] # remove the last ' OR '
conditions[0] += filter_query
conditions = conditions + query_values
#issues = #issues.where(conditions)
end

How can I use PostGIS functions in rails?

The query I'd like to run is:
SELECT zcta.geoid10, ST_AsGeoJSON(ST_simplify(zcta.geom,500)) FROM zcta WHERE zcta.geoid10 = '90210'
However in the Rails console when I enter this:
testquery = "SELECT zcta.geoid10, ST_AsGeoJSON(ST_simplify(zcta.geom,500)) FROM zcta WHERE zcta.geoid10 = '90210'"
Zcta.find_by_sql testquery
I get the following returned:
=> [#<Zcta >]
If I do a basic query asking for the result of any column I get the response I expect. This only happens with PostGIS functions. Any idea what to do?
Alias the calculated column and you will get a method added to the returned objects.
Zcta.
select("*, ST_AsGeoJSON(ST_simplify(geom,500)) as my_geo").
where(geoid10: '90210').each do |result|
puts result.my_geo
end

convert named_scope for rails 3

I have the following code wich throws an error with Rails 3 :
module Auditions
module Search
def self.included(base)
base.extend ClassMethods
...
base.named_scope :not_rated_by, lambda { |user_id| {
:conditions => ['NOT EXISTS (SELECT * FROM audition_tags bar WHERE bar.user_id = ? AND bar.audition_id = auditions.id)', user_id]
}}
...
end
end
end
When called the following error appears :
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2053809816 AND audition_tags.audition_id = auditions.id)) ORDER BY auditions.cr' at line 1: SELECT `auditions`.* FROM `auditions` WHERE (NOT EXISTS (SELECT * FROM audition_tags WHERE audition_tags.user_id = '#<ActiveRecord::Relation:0x104ee3c20>',2053809816 AND audition_tags.audition_id = auditions.id)) ORDER BY auditions.created_at DESC LIMIT 0, 10
As you can see it's like user_id is now a table containing an ActiveRelation object and well ... my user_id
I don't understand what's going on ... do you have an idea ?
Thanks
update : here's the complete SQL output :
SELECT `auditions`.* FROM `auditions` WHERE (NOT EXISTS (SELECT * FROM audition_tags as bar WHERE bar.user_id = '#<ActiveRecord::Relation:0x104aa6c48>',2053809816 AND bar.audition_id = auditions.id)) ORDER BY auditions.created_at DESC LIMIT 0, 10
update2 : here's the code calling my scope https://gist.github.com/ddddfeddf70264a81289
update3 : as you can see in my gist the chained scopes are called with a "call" :
scopes.inject(self) {|m,v| m.scopes[v[0]].call(m, v[1]) }
If I log the user_id sent it's a FixNum not an Array :
scopes.inject(self) do |m,v|
logger.info ">>> SCOPE : #{v[0].inspect} | ARG : #{v[1].inspect} | ARG CLASS : #{v[1].class.inspect} <<<"
m.scopes[v[0]].call(m, v[1])
end
So the problem is more precise now : I send a Fixnum as argument to my named_scope but got on output an Array of type : [ActiveRecord::Relation, FixNum]
update4 : I finally find the solution (but not sure why ???)
I replaced "call" by "send" and it works ...
results = scopes.inject(self) do |combined_scope, scope|
combined_scope.send(scope[0], scope[1])
end
Thanks all for your help !
Try this:
scope :not_rated_by, lambda { |user_id| {
where('NOT EXISTS (SELECT * FROM audition_tags bar WHERE bar.user_id = ? AND bar.audition_id = auditions.id)', user_id)
}
And by the way, could it be that there is a comma missing here, something should go bewtween audition_tags and bar?
FROM audition_tags bar
And also based on your error I think you are passing in a user object - not a ID, remember in Rails 3 everything is a ActiveRecord Relation so you have to call first or all on the relation first to get a result.
Example:
user = User.where('conditions').first
Auditions.not_rated_by(user.id)

Resources