Correct syntax to HAVING with thinking sphinx - sphinx

I have a query and I want to run the same with thinking sphinx, but I'm having problems with HAVING clause. The relevant code is the following:
#technology_index.rb
has taggings.tag_id, :as => :tag_id
has id, :as => :technology_id
#technology.rb
search(params[:query],
with: { tag_id: params[:filter].values.flatten },
group_by: :technology_id,
having: "COUNT(`technology_id`)=#{params[:filter].size}"
)
This throws me the following error (new lines in error message are mine):
sphinxql: syntax error, unexpected IDENT, expecting '*' near '`technology_id`)=1 LIMIT 0, 20;
SHOW META' - SELECT *, groupby() AS sphinx_internal_group, id AS sphinx_document_id,
count(DISTINCT sphinx_document_id) AS sphinx_internal_count
FROM `technology_core` WHERE MATCH('fibrosis') AND `tag_id` IN (2)
AND `sphinx_deleted` = 0 GROUP BY `technology_id` HAVING COUNT(`technology_id`)=1
LIMIT 0, 20; SHOW META
The problem is with having: clause, because if I remove it, at least the query works.
Is supposed since 2.2.1 beta HAVING is supported (using 2.2.6), the same for TS 3.1 (using 3.1.2). I couldn't find any info about use of HAVING in the docs, but if I try something like having: "COUNT(*)>1" works so I guess, I'm just invoking it incorrectly. What should be the correct way to use having: with TS ?

It seems that something like having: "COUNT('technology_id')=#{params[:filter].size}" is still not supported by sphinx.
Anyway my query worked with having: "COUNT(*)=#{params[:filter].size} as I was grouping by technology_id.

Related

DataGrip: How to chop long 'returning' part?

I have the following problem with formatting a PostgreSQL query in Datagrip (and also in all other JetBrains products regarding PG queries):
update some_table
set some_column = 42
where id = 42
returning val_a as "valA",
val_b as "valB",
val_c as "valC",
val_d as "valD",
val_e as "valE",
val_f as "valF",
val_g as "valG";
When I now use the built-in SQL formatter, DataGrip produces this:
update some_table
set some_column = 42
where id = 42
returning val_a as "valA", val_b as "valB", val_c as "valC", val_d as "valD", val_e as "valE", val_f as "valF", val_g as "valG";
You see what the issue is: All returned values are in one line (it even ignores my max-line-length setting). I tried different settings in my IDE but to no avail. Note that for now, I don't care if the returned vals are indented or aligned or whatever, I just want the query to be "readable".
Looking forward to a solution and thanks in advance!
There is no option for that :( Please, file a request
https://youtrack.jetbrains.com/newIssue?project=DBE

How to insert similar value into multiple locations of a psycopg2 query statement using dict? [duplicate]

I have a Python script that runs a pgSQL file through SQLAlchemy's connection.execute function. Here's the block of code in Python:
results = pg_conn.execute(sql_cmd, beg_date = datetime.date(2015,4,1), end_date = datetime.date(2015,4,30))
And here's one of the areas where the variable gets inputted in my SQL:
WHERE
( dv.date >= %(beg_date)s AND
dv.date <= %(end_date)s)
When I run this, I get a cryptic python error:
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) argument formats can't be mixed
…followed by a huge dump of the offending SQL query. I've run this exact code with the same variable convention before. Why isn't it working this time?
I encountered a similar issue as Nikhil. I have a query with LIKE clauses which worked until I modified it to include a bind variable, at which point I received the following error:
DatabaseError: Execution failed on sql '...': argument formats can't be mixed
The solution is not to give up on the LIKE clause. That would be pretty crazy if psycopg2 simply didn't permit LIKE clauses. Rather, we can escape the literal % with %%. For example, the following query:
SELECT *
FROM people
WHERE start_date > %(beg_date)s
AND name LIKE 'John%';
would need to be modified to:
SELECT *
FROM people
WHERE start_date > %(beg_date)s
AND name LIKE 'John%%';
More details in the pscopg2 docs: http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries
As it turned out, I had used a SQL LIKE operator in the new SQL query, and the % operand was messing with Python's escaping capability. For instance:
dv.device LIKE 'iPhone%' or
dv.device LIKE '%Phone'
Another answer offered a way to un-escape and re-escape, which I felt would add unnecessary complexity to otherwise simple code. Instead, I used pgSQL's ability to handle regex to modify the SQL query itself. This changed the above portion of the query to:
dv.device ~ E'iPhone.*' or
dv.device ~ E'.*Phone$'
So for others: you may need to change your LIKE operators to regex '~' to get it to work. Just remember that it'll be WAY slower for large queries. (More info here.)
For me it's turn out I have % in sql comment
/* Any future change in the testing size will not require
a change here... even if we do a 100% test
*/
This works fine:
/* Any future change in the testing size will not require
a change here... even if we do a 100pct test
*/

Not able to pass complete datetime(Y-m-d H:i:s) in DB::raw in eloquent

$shop=DB::table('shops')
->leftJoin('orderbookings',function($join)
{
$join->on('shops.id','=','orderbookings.shop_id');
$join->on('orderbookings.created_at','>=',DB::raw(date("Y-m-d",strtotime("now"))));
})
->select('shops.*')
->selectRaw('COUNT(orderbookings.id) as totalorder, SUM(orderbookings.grand_total) as gtotal')
->orderBy('shops.shop_name', 'asc')
->groupby('shops.id')
->paginate(10);
Above code working fine(But not giving total order and amount correct) and also gives result almost close to what I want,
But I am not able to give date format (Y-m-d H:i:s), it shows syntax error. I am using Laravel 5.2 version
Note: I want to give time as well with date to rectify result,
On giving [example: 2017-03-08 11:15:00] shows syntax error
working query in mysql
SELECT COUNT(orderbookings.id), SUM(orderbookings.grand_total), shops.shop_name FROMshopsLEFT JOIN orderbookings on orderbookings.shop_id = shops.id and orderbookings.created_at BETWEEN "2015-10-22 17:02:02" AND "2017-03-07 17:02:02" GROUP BY shops.id
But not able to to convert in eloquent
You should be able to do the following:
$join->on('orderbookings.created_at', '>=', date("Y-m-d"));
You don't need to use DB::raw, and leaving the second parameter null for date, assumes "now".
If this doesn't solve your issue, please post the exact error you're seeing.

Syntax error on DB2 XMLELEMENT

I get this error when trying out this command in the BIRT Classic Models sample database in Data Studio
select xmlelement(name "custno", customers.customernumber) from customers
Syntax error: Encountered "\"custno\"" at line 1, column 24.
I do not know how to correct it.
Thanks.
I'm not familiar with db2, but according to this your statement looks quite alrigth (although I'd place an alias to name this field...)
But this
Syntax error: Encountered "\"custno\"" at line 1, column 24.
seems to be a quite clear hint, that your error is connected to the NAME of the element.
I'm pretty sure, that this statement was created on string level.
Did you try to escape the "-characters with \"?
The SQL reaching the engine might look like
select xmlelement(name \"custno\", customers.customernumber) from customers
or
select xmlelement(name "\"custno"\", customers.customernumber) from customers
... which is wrong of course...
But to be honest: just guessing...

Laravel 5.1 Invalid datetime format: 7 ERROR: invalid input syntax for type date error

I've been having trouble with eloquent that keeps returning error. Below is the query that i tried to run in laravel.
$actives = ProjectVersion::join('version_employees as ve', 've.report_id' ,'=', 'project_versions.id')
->join('employees as e', 've.employee_id', '=', 'e.id')
->whereBetween(\DB::raw("'1985-05-27'::date"),[
\DB::raw("to_date(timeline->>'start_time', 'YYYY-MM-DD')"),
\DB::raw("to_date(timeline->>'release_time', 'YYYY-MM-DD')")])
->groupBy('e.name')
->select(\DB::raw('count(e.id), e.name'))
->get();
Now this returns an error of
Invalid datetime format: 7 ERROR: invalid input syntax for type date: "to_date(timeline->>'start_time', 'YYYY-MM-DD')"
The full query returned by the error message is
SELECT count(e.id), e.name
FROM "project_versions" inner join "version_employees" as "ve" on "ve"."report_id" = "project_versions"."id" inner join "employees" as "e" on "ve"."employee_id" = "e"."id"
WHERE '1985-05-27'::date
BETWEEN to_date(timeline->>'start_time', 'YYYY-MM-DD')
AND to_date(timeline->>'release_time', 'YYYY-MM-DD')
GROUP BY "e"."name"
The thing is that when i run this query in pgadmin, it runs fine and returns the result that i wants.
I've been stuck for hours debugging this. Any idea on where the problem is ?
Well first off, it's not really eloquent in the way you're using it with all those Raw statements ;-)
Try using the Carbon class: Carbon::now()->toDateString() will return a date in the Y-m-d format.
For the where clause, if I'm understanding your query correctly, you can use 2 where clauses instead of the whereBetween with Raw SQL: ->where('start_time', '>', $start_time_preprocessed_by_carbon)->where('release_time', '<', $release_time_preprocessed_by_carbon)
And you seem to want the count which means you can end with a ->count() instead of a ->get()
I'd love to give you the full query but couldn't decipher it completely. However these implementations should give you a nudge in the right direction! They will help you abstract your query further to the point that Laravel's internal query generator will translate the code into the correct syntax for your database!