Formatting Postgres row_to_json response for query - ruby

I have the following Postgres query:
"SELECT \"responses\".\"index\", \"responses\".\"created_at\",
ROUND(AVG(\"responses\".\"numeric\")) AS numeric
FROM \"responses\"
WHERE \"responses\".\"time\" = '#{time}'
GROUP BY \"responses\".\"index\", \"responses\".\"created_at\""
I'm trying to output the response as json using row_to_json. I can use:
"select row_to_json(row)
from (
SELECT \"responses\".\"index\", \"responses\".\"created_at\",
ROUND(AVG(\"responses\".\"numeric\")) AS numeric
FROM \"responses\"
WHERE \"responses\".\"time\" = '#{time}'
GROUP BY \"responses\".\"index\", \"responses\".\"created_at\"
) row"
Which will give me:
{"row_to_json"=>"{\"index\":1,\"created_at\":\"2014-07-12 03:51:00\",\"numeric\":3}"}
However I don't really want the response nested in the row_to_json hash. Is there a simple way to remove that so I just return:
"{\"index\":1,\"created_at\":\"2014-07-12 03:51:00\",\"numeric\":3}"

You should use array_to_json and array_agg functions.
For example:
SELECT array_to_json(array_agg(row_to_json(row))) FROM ...
It will return a correct JSON array
References:
http://hashrocket.com/blog/posts/faster-json-generation-with-postgresql
http://reefpoints.dockyard.com/2014/05/27/avoid-rails-when-generating-json-responses-with-postgresql.html

Related

Laravel - WhereExists returning "Invalid parameter number: parameter was not defined"

I'm trying to use whereExists() on an existing Eloquent query builder (called $trips):
$trips = $trips->whereExists(function ($query) use ($filterValue) {
$query->from(DB::raw("jsonb_array_elements(passengers->'adults'->'persons') as p(person)"))
->whereRaw("p.person->>'name' LIKE '?%'", $filterValue);
});
The query I'm trying to create in raw postgres format is the following (this query works fine using pgAdmin):
SELECT *
from trips
WHERE exists (select *
from jsonb_array_elements(passengers -> 'adults' -> 'persons') as p(person)
where p.person ->> 'name' LIKE 'Prof%');
And I'm receiving this error:
Invalid parameter number: parameter was not defined
I think the problem is small, but I can't see it myself.
The parameter definition in your whereRaw() statement is not quite correct. Parameterized queries are not just string replacements. Your query as written doesn't have a parameter in it, it has a string literal of '?%'. You need to change this to a query parameter, and append the % wildcard to the string you pass in.
Try this:
->whereRaw("p.person->>'name' LIKE ?", $filterValue.'%')

Select multi condition on parameter with Rethinkdb

I want to retrieve all User or get all User with Name variable. I'm using Rethinkdb and I want to convert SQL Server to Rethinkdb with my query
SQL Server:
SELECT * FROM User
WHERE Name = '' OR Name = # Name
This 's my Rethinkdb query, but It not working right
rethink.table('User')
.filter(
rethink.row('Name').eq(Name).or(rethink.row('Name'))
)
.run(conn, callback)
You could do:
r.table('User').filter(function(d){
return r.expr([Name, ""]).contains(d('Name'))
})

Write query which run on array by considring sub query in Parse

I need to write a query in such way that the array(collection) is contain only sub query objects.
Suppose we have the two tables as follows:
TableA:
objectId, name
TableB:
objectId, names[array of name: parse pointer collection]
Here is my code which I tried:
// sub query
var subQuery = new Parse.Query('TableA');
subQuery.doesNotExist('name');
// main query
var query = new Parse.Query('TableB');
query.exists("names");
//query.containsAll("names", subQuery); // this means names should contain all subQuery, so this is not use full for me.
query.matchesQuery("names", subQuery);
This code is running fine, but this is not working as I want and also not showing the any error.
It seems that you don't need a subquery per se, but rather to first query your list of names, and then use that in your main query. What you seem to be looking for is: containedIn( key, values ) , as in:
query.containedIn("name", namesFromFirstQuery)

removing backslashes in the query using codeigniter mysql

Post value is multi select, means values are coming in the form of array
if(!empty($_POST['form_type']))
{
$test = implode("','",$_POST['form_type']);
$this->db->where_in('enquiry.type_of_enquiry',"'".$test."'");
}
my query is like this
SELECT `sobha_enquiry`.`name`, `sobha_enquiry`.`date_created`, `sobha_enquiry`.`company`, `sobha_enquiry`.`form_of`, `sobha_enquiry`.`projectname`, `sobha_enquiry`.`city`, `sobha_enquiry`.`country`, `sobha_enquiry`.`phone`, `sobha_enquiry`.`type_of_enquiry`, `sobha_enquiryzone`.`enquiry_id`, `sobha_enquiry`.`hearaboutus`, `sobha_enquiry`.`email`, `sobha_enquiry`.`comments`, `sobha_enquiry`.`address`, `sobha_admin`.`id`, `sobha_admin`.`city_id` FROM (`sobha_senquiry`) LEFT JOIN `sobha_enquiryzone` ON `sobha_enquiryzone`.`enquiry_id` =`sobha_enquiry`.`id` LEFT JOIN `sobha_admin` ON `sobha_admin`.`city_id`=`sobha_enquiryzone`.`city_id` WHERE `sobha_enquiry`.`type_of_enquiry` IN ('\'register form\',\'feedback form\'') GROUP BY `sobha_enquiry`.`id` ORDER BY `sobha_enquiry`.`id` desc LIMIT 15
since i used implode function it is coming like this IN ('\'register form\',\'feedback form\'') i want to remove those backslashes . Please help me
$this->db->where_in() will accept array as second argument.
So there is no need for imploding the data.
if(!empty($_POST['form_type']))
{
$this->db->where_in('enquiry.type_of_enquiry',$_POST['form_type']);
}
This will result as,
WHERE `enquiry`.`type_of_enquiry` IN ('register form','feedback form')
You can refer this link for more info, Codeigniter Active Record Documentation

How to write a query with two ? placeholders in sequence?

I am using a NamedParameterJdbcTemplate, but found that this problem is in the underlying JdbcTemplate class, so I will show the problem as it occurs with the JdbcTemplate (so let's not worry about the safety of the SQL query here).
Here's what I am trying to achieve:
String sql = "SELECT * FROM clients ORDER BY ? ?";
return jdbcTemplate.query(sql,
new Object[] { "name", "ASC" },
new ClientResultSetExtractor());
I expected the first place-holder to be replaced with "name" and the second with "ASC", which would create the valid SQL query:
SELECT * FROM clients ORDER BY name ASC
But unfortunately, running that jdbc query does not work:
ERROR: syntax error at or near "$2" at character 35
STATEMENT: SELECT * FROM clients ORDER BY $1 $2
What am I doing wrong?
EDIT
I had assumed the problem was the two placeholders in sequence, but even when I remove the first one, it still won't accept just the last one, which should tell the query whether to sort in ASC or DESC order. Is this a bug, and if not, why the heck is this not acceptable????
You're trying to use parameters incorrectly.
Parameters are not column names or SQL statement keywords. They're data content (eg., WHERE LastName = ? is a valid parameterized statement, WHERE ? = 'Smith' is not).

Resources