How to add a GROUP_BY clause in a Searchlogic query? - sql

I'm using Searchlogic with Rails 2.3.5 and I need to do add a GROUP_BY clause with 2 columns to my query. I tried:
User.search.group = "column1, column2" # Undefined method 'group'
User.search(:group => "column1, column2") # Searchlogic::Search::UnknownConditionError: The group is not a valid condition. You may only use conditions that map to a named scope
And neither worked. I couldn't find any other ways in Searchlogic's docs. Is there any other way?

According to this page: http://vladzloteanu.wordpress.com/2009/01/25/searchlogic-plugin-activerecord-search-on-steroids/
You can probably use:
User.search.conditions.group("column1,column2")

Related

Modify Ransack not_in query to include when field is nil

I am querying my model like so:
MyModel.search(year_not_in: [2000, 2010, 2015])
But am getting back results from MyModel ONLY where year is not nil. For example, the query hits where MyModel.year = 1999 but not where MyModel.year = nil. I expect nil to not be in that array but perhaps that is how it's defined in SQL.
Is there a way I can override the year or year_not_in ransacker to add the condition above?
I was able to solve this without overriding, though I would still be interested in how to do that. Joining statements like so was my solution:
.search(m: 'or', year_not_in: [2000, 2010, 2015], year_null: true)
First of all : this solution test with ransack (2.4.2) and rails 6.1.3
To achieve this, GEM ransack give us a solution is to add a new predicate :
If you'd like to add your own custom Ransack predicates
not_in_or_null
You can do it like this way :
"config/initializers/ransack.rb"
You add this
Ransack.configure do |config|
config.add_predicate 'not_in_or_null', arel_predicate: 'not_in_or_null'
end
module Arel
module Predications
def not_in_or_null(other)
left = not_in(other)
right = eq(nil)
left.or(right)
end
end
end
And than, you have a new predicate now.

Two arrays of conditions in single ActiveRecord 'where' clause

Let's say I have two pairs of SQL conditions like these:
a = [ "users.accepted = ? AND users.active_at > ?", true, Time.zone.now ]
b = [ "users.accepted = ? AND users.active_at > ?", false, Time.zone.now + 3.days ]
I can use code like User.where(a) to get all rows that satisfy the a condition. How can I use where to get rows that satisfy either a or b conditions? The result should be ActiveRecord::Relation.
There are a couple ways to go about this.
get meta_where or squeel depending upon your rails version. These are really great gems that enhance the Arel behavior of ActiveRecord::Relation.
write sql manually and pass it into the where method as a string. You might have to mess with sql injection more manually, but from your example above I didn't see any incoming values that were user generated strings.

Group by using linq with NHibernate 3.0

As far as I know group by has only been added in NHibernate 3.0, but even when using version 3, I can't get group by to work.
I have tried to do the following query:
Session.Query().GroupBy(gbftr
=> gbftr.Tag).OrderByDescending(obftr => obftr.Count()).Take(count).ToList();
But I receive the following error:
Antlr.Runtime.NoViableAltException'. [. OrderByDescending (. GroupBy (NHibernate.Linq.NhQueryable `1 [Forum.Core.ForumTagRelation] Quote ((gbftr,) => (gbftr.Tag)),), Quote ((obftr,) => (. Count (obftr,))),)]
Does anyone have an idea if I might be mistaken, and group by isn't implemented in NHibernate 3.0, or who knows what I might be doing wrong?
GroupBy does work, but it's the combination with other operators that is causing trouble.
For example, this works:
session.Query<Foo>().GroupBy(x => x.Tag).Select(x => x.Count()).ToList();
But if you try to use Skip/Take to page, it fails.
In short: some constructs are not supported yet; you can use HQL for those. I suggest you open an issue at http://jira.nhforge.org

Rails 3 ActiveRecord query using both SQL IN and SQL OR operators

I'm writing a Rails 3 ActiveRecord query using the "where" syntax, that uses both the SQL IN and the SQL OR operator and can't figure out how to use both of them together.
This code works (in my User model):
Question.where(:user_id => self.friends.ids)
#note: self.friends.ids returns an array of integers
but this code
Question.where(:user_id => self.friends.ids OR :target => self.friends.usernames)
returns this error
syntax error, unexpected tCONSTANT, expecting ')'
...user_id => self.friends.ids OR :target => self.friends.usern...
Any idea how to write this in Rails, or just what the raw SQL query should be?
You don't need to use raw SQL, just provide the pattern as a string, and add named parameters:
Question.where('user_id in (:ids) or target in (:usernames)',
:ids => self.friends.ids, :usernames => self.friends.usernames)
Or positional parameters:
Question.where('user_id in (?) or target in (?)',
self.friends.ids, self.friends.usernames)
You can also use the excellent Squeel gem, as #erroric pointed out on his answer (the my { } block is only needed if you need access to self or instance variables):
Question.where { user_id.in(my { self.friends.ids }) |
target.in(my { self.friends.usernames }) }
Though Rails 3 AR doesn't give you an or operator you can still achieve the same result without going all the way down to SQL and use Arel directly. By that I mean that you can do it like this:
t = Question.arel_table
Question.where(t[:user_id].in(self.friends.ids).or(t[:username].in(self.friends.usernames)))
Some might say it ain't so pretty, some might say it's pretty simply because it includes no SQL. Anyhow it most certainly could be prettier and there's a gem for it too: MetaWhere
For more info see this railscast: http://railscasts.com/episodes/215-advanced-queries-in-rails-3
and MetaWhere site: http://metautonomo.us/projects/metawhere/
UPDATE: Later Ryan Bates has made another railscast about metawhere and metasearch: http://railscasts.com/episodes/251-metawhere-metasearch
Later though Metawhere (and search) have become more or less legacy gems. I.e. they don't even work with Rails 3.1. The author felt they (Metawhere and search) needed drastic rewrite. So much that he actually went for a new gem all together. The successor of Metawhere is Squeel. Read more about the authors announcement here:
http://erniemiller.org/2011/08/31/rails-3-1-and-the-future-of-metawhere-and-metasearch/
and check out the project home page:
http://erniemiller.org/projects/squeel/
"Metasearch 2.0" is called Ransack and you can read something about it from here:
http://erniemiller.org/2011/04/01/ransack-the-library-formerly-known-as-metasearch-2-0/
Alternatively, you could use Squeel. To my eyes, it is simpler. You can accomplish both the IN (>>) and OR (|) operations using the following syntax:
Question.where{(:user_id >> my{friends.id}) | (:target >> my{friends.usernames})}
I generally wrap my conditions in (...) to ensure the appropriate order of operation - both the INs happen before the OR.
The my{...} block executes methods from the self context as defined before the Squeel call - in this case Question. Inside of the Squeel block, self refers to a Squeel object and not the Question object (see the Squeel Readme for more). You get around this by using the my{...} wrapper to restore the original context.
raw SQL
SELECT *
FROM table
WHERE user_id in (LIST OF friend.ids) OR target in (LIST OF friends.usernames)
with each list comma separate. I don't know the Rails ActiveRecord stuff that well. For AND you would just put a comma between those two conditions, but idk about OR

Encapsulating SQL in a named_scope

I was wondering if there was a way to use "find_by_sql" within a named_scope. I'd like to treat custom sql as named_scope so I can chain it to my existing named_scopes. It would also be good for optimizing a sql snippet I use frequently.
While you can put any SQL you like in the conditions of a named scope, if you then call find_by_sql then the 'scopes' get thrown away.
Given:
class Item
# Anything you can put in an sql WHERE you can put here
named_scope :mine, :conditions=>'user_id = 12345 and IS_A_NINJA() = 1'
end
This works (it just sticks the SQL string in there - if you have more than one they get joined with AND)
Item.mine.find :all
=> SELECT * FROM items WHERE ('user_id' = 887 and IS_A_NINJA() = 1)
However, this doesn't
Items.mine.find_by_sql 'select * from items limit 1'
=> select * from items limit 1
So the answer is "No". If you think about what has to happen behind the scenes then this makes a lot of sense. In order to build the SQL rails has to know how it fits together.
When you create normal queries, the select, joins, conditions, etc are all broken up into distinct pieces. Rails knows that it can add things to the conditions without affecting everything else (which is how with_scope and named_scope work).
With find_by_sql however, you just give rails a big string. It doesn't know what goes where, so it's not safe for it to go in and add the things it would need to add for the scopes to work.
This doesn't address exactly what you asked about, but you might investigate 'contruct_finder_sql'. It lets you can get the SQL of a named scope.
named_scope :mine, :conditions=>'user_id = 12345 and IS_A_NINJA() = 1'
named_scope :additional {
:condtions => mine.send(:construct_finder_sql,{}) + " additional = 'foo'"
}
sure why not
:named_scope :conditions => [ your sql ]