I need to implement the following query with Ecto, however it doesn't compile saying the subquery statement is not a valid expression.
query = from p in Passphrase,
left_join: pi in PassphraseInvalidation, on: p.id == pi.target_passphrase_id,
join: u in User, on: p.user_id == u.id,
where: p.passkey == ^passkey and
is_nil(pi.inserted_at) and
p.inserted_at > ago(5, "month") and
p.inserted_at > subquery(from pr in PasswordReset,
where: pr.user_id == u.id,
select: max(pr.inserted_at)),
select: {u, p}
user = Repo.one!(query)
(Ecto.Query.CompileError) subquery(from(pr in PasswordReset, where: pr.user_id() == ^u.id(), select: max(pr.inserted_at()))) is not a valid query expression.
The equivalent PgSQL query would be something like:
SELECT u.*, p.*
FROM passphrases p
LEFT OUTER JOIN passphrase_invalidations pi ON p.id = pi.target_passphrase_id
INNER JOIN users u ON p.user_id = u.id
WHERE p.passkey = '/* some passkey */' AND
pi.inserted_at IS NULL AND
u.id = 2 AND
p.inserted_at > (SELECT max(pr.inserted_at)
FROM password_resets pr
WHERE pr.user_id = u.id)
Is there a way to implement that, or am I missing something?
As of Ecto 2.1.0, according to https://hexdocs.pm/ecto/Ecto.Query.html#subquery/1, subqueries cannot be use in where:
Subqueries are currently only supported in the from and join fields.
You can use fragment and put the entire subquery in it for now:
p.inserted_at > fragment("(SELECT max(pr.inserted_at) FROM password_resets pr WHERE pr.user_id = u.id)")
where just became available (Ecto 3.4.3)
https://hexdocs.pm/ecto/Ecto.Query.html#subquery/2
Related
My Dear
I tried to run the following ad-hoc database query in Moodle but i got it error
there any way to fix it , thanks
*My target to find all the external links (URL) from course page
SELECT
concat('<a target="_new" href=%%WWWROOT%%/course/view.php?id=',
c.id, '">', c.fullname, '</a>') AS Course
,c.shortname,r.name
,(
SELECT CONCAT(u.firstname,' ', u.lastname) AS Teacher
FROM prefix_role_assignments AS ra
JOIN prefix_context AS ctx ON ra.contextid = ctx.id
JOIN prefix_user AS u ON u.id = ra.userid
WHERE ra.roleid = 3
AND ctx.instanceid = c.id
LIMIT 1
) AS Teacher
,concat('<a target="_new" href="%%WWWROOT%%/mod/resource/view.php?id=',
r.id, '">', r.name, '</a>') AS Resource
FROM prefix_resource AS r
JOIN prefix_course AS c ON r.course = c.id
WHERE r.reference LIKE 'https://stackoverflow.com/%'
Error message :
" Error when executing the query: ERROR: Incorrect number of query
parameters. Expected 2, got 0"
When executing SQL statements in Moodle, any '?' characters are used to indicate placeholders for parameters that need to be provided along with the query.
From the style of your query, I'm assuming you're using report_customsql or block_configurablereports for your query, so you won't have the option of providing such parameters.
If you look at the documentation here: https://docs.moodle.org/en/Custom_SQL_queries_report you will see that the workaround for this is to replace any '?' characters in your query with '%%Q%%'.
So the fixed query should look like:
SELECT concat('<a target="_new" href="%%WWWROOT%%/course/view.php%%Q%%id=',c.id,'">',c.fullname,'</a>') AS Course,
c.shortname,r.name, (SELECT CONCAT(u.firstname,' ', u.lastname) AS Teacher
FROM prefix_role_assignments AS ra
JOIN prefix_context AS ctx ON ra.contextid = ctx.id
JOIN prefix_user AS u ON u.id = ra.userid
WHERE ra.roleid = 3 AND ctx.instanceid = c.id LIMIT 1) AS Teacher,
concat('<a target="_new" href="%%WWWROOT%%/mod/resource/view.php%%Q%%id=',r.id,'">',r.name,'</a>') AS Resource
FROM prefix_resource AS r
JOIN prefix_course AS c ON r.course = c.id
WHERE r.reference LIKE 'https://stackoverflow.com/%'
How can I write a linq to entities query that includes a group by and a having clause?
For example in SQL:
SELECT * FROM dbo.tblParent p
INNER JOIN
(
SELECT a.ID
FROM dbo.tblParent a
join dbo.tblChild c ON a.ID = c.FkParentID
WHERE a.ColValue = 167
GROUP BY A.ID
HAVING COUNT(c.ID) = 1
) t ON p.ID = t.ID
I found my own answer.
// this is far from pretty but it works as far as I can tell
Apps = (from x in context.tblParents
join t in (
from p in context.tblParents
join c in context.tblChilds
on p.ID equals c.FkParentID
where p.ColValue == 167
group c.ID by p.ID into grouped
where grouped.Count() == 1
select new { grouped.Key }) on x.ID equals t.Key
select x);
I have 2 n-n relationships between posts and tags tables. This is my query in Postgres:
SELECT t0.*, array_to_string(array_agg(t2.tag), ', ')
FROM "posts" AS t0
INNER JOIN "posts_tags" AS t1 ON (t0.id = t1.post_id)
INNER JOIN "tags" AS t2 ON (t1.tag_id = t2.id)
GROUP BY t0.id
I tried to use something similar in Ecto:
Repo.all(
from p in Post,
join: a in Post_Tag, on: p.id == a.post_id,
join: t in Tag, on: a.tag_id == t.id,
select: {p, array_to_string(array_agg(t.tag),', ')},
limit: ^limit,
offset: ^offset,
group_by: p.id
)
But I get this error:
(Ecto.Query.CompileError) `array_to_string(array_agg(t.tag()), ', ')` is not a valid query expression.
You will need to use a fragment/1 for the array_to_string(...) portion of your query. I have not tested it, but it should look something like:
fragment("array_to_string(array_agg(?), ', ')", t.tag)
I have moved from mysql to psql, but find it hard to get my head around the UPDATE statement using multiple left joins.
How would you rewrite this in Postgres? (I am using postresql 9.4)
update task t
left join project p on t.project_id = p.id
left join client c on t.client_id = c.id
left join user u on t.user_id = u.id
set t.project_name = p.name,
t.client_name = c.name,
t.user_name = u.name;
Any pointer will be welcome.
Here you go:
WITH task_data AS (
SELECT t.id,
p.name AS project_name,
c.name AS client_name,
u.name AS user_name
FROM task t
LEFT JOIN project p ON t.project_id = p.id
LEFT JOIN client c ON t.client_id = c.id
LEFT JOIN "user" u ON t.user_id = u.id
)
UPDATE task t
FROM task_data d
SET
project_name = d.project_name,
client_name = d.client_name,
user_name = d.user_name
WHERE t.id = d.id
I would be curious to see if there is a more efficient way
I am trying to write the following SQL query as a JPA query. The SQL query works (MySQL database) but I don't know how to translate it. I get a error token right after the first FROM. There are probably other errors here too because I was not able to find any guides on how to do sub-queries in the from part, aliasing and so on.
SQL query
SELECT tbl.* from (
SELECT u.*, COUNT(u.id) AS question_count FROM app_user AS u
INNER JOIN question AS q ON u.id = q.user_id GROUP BY u.id
) AS tbl ORDER BY tbl.question_count DESC LIMIT 10;
JPA query:
SELECT tbl FROM (SELECT u, COUNT(u.id) question_count FROM User u
INNER JOIN u.questions q ON u.id = q.user_id GROUP BY u.id) tbl
ORDER BY tbl.question_count LIMIT 10")
I can't test this with anything right now, but something along the lines of:
final String queryStr = "SELECT u, COUNT(u.id) FROM User u, Questions q WHERE u.id = q.user_id GROUP BY u.id ORDER BY COUNT(u.id) DESC";
Query query = em().createQuery(queryStr);
query.setMaxResults(10);
List<Object[]> results = query.getResultList(); //Index [0] will contain the User-object, [1] will contain Long with result of COUNT(u.id)