Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.
Sign upRaw SQL statement crashes / trait bound FromSqlRow not satisfied #584
Comments
This comment has been minimized.
Boscop
commented
Jan 20, 2017
•
|
With the help of @killercup I figured out what the problem was (thanks a lot!): #[derive(Queryable, Identifiable, Clone, Associations, Debug)]
#[belongs_to(User)]
pub struct Filter {
pub id: i64,
pub user_id: i64,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub name: String,
pub description: String
pub code: String,
pub params: String,
pub tags: Vec<String>,
}@killercup suggested I name all the rows explicitly to pull them through to the outer scope instead of using the catchall '*' (I also tried let query = sql(&format!(r#"
WITH ranking AS (
SELECT *
FROM (
SELECT
ts_rank(
to_tsvector('english', filters.name) ||
to_tsvector('english', filters.description) ||
to_tsvector('english', array_to_string(filters.tags, ' '))
, plainto_tsquery('{}'), 32) AS score,
id,
user_id,
created_at,
updated_at,
name,
description,
code,
params,
tags
FROM filters
) s
WHERE score > 0
ORDER BY score DESC
)
SELECT
id,
user_id,
created_at,
updated_at,
name,
description,
code,
params,
tags
FROM ranking;
"#, search_terms));
query.get_results::<models::filter::Filter>(&*database::connection().get().unwrap()).map_err(|e| e.into())But it's unelegant because:
So my remaining questions are:
|
This comment has been minimized.
Well if you want to select a subset of the fields in the table, you'll need a custom select clause. So not really.
I don't think so, but I'm also not sure I fully understand the goal of doing that.
The solution there is to use the query builder instead of a SQL string. Unless I'm missing something, your query is (other than the select clause) identical to: SELECT
ts_rank(
to_tsvector('english', filters.name) ||
to_tsvector('english', filters.description) ||
to_tsvector('english', array_to_string(filters.tags, ' '))
, plainto_tsquery('{}'), 32) AS score,
id,
user_id,
created_at,
updated_at,
name,
description,
code,
params,
tags
FROM filters
WHERE score > 0
ORDER BY score DESCIf that's the case, it's also identical to:
Which can be written in the query builder as:
This exact use case is actually in the documentation here |
This comment has been minimized.
Boscop
commented
Feb 2, 2017
|
Thanks! |
Boscop commentedJan 20, 2017
•
edited
This query works in my postgres console but crashes with diesel:
When specifying the type with
let query = sql::<Filter>(...it doesn't compile:There seems to be a missing parameter? But if I write
sql::<Filter, Pg>it complains about 2 parameters when 1 is required.I have another question: How to prevent SQL injection with the search_terms?