Help with refactoring a (probably unnecessarily) huge query
the query is attached... too big for messages š¤£
27 Replies
i'm sorry for creating this abomination...
Bro...
It seems like most of that query could be written with the query API and a
with
clause to do all the CTEs using relations insteadWhy would you write that with the sql operator and not with the drizzle syntax
I don't see anything in there not supported by drizzle
They didn't have union support until recently
so the new stuff should cover it then?
Yep
The types implementation in the Union is very tight. Let me know if you have any problems
Quick flex, I implemented it š
almost there! I currently have an issue with media, it's only pulling through a single object. not sure how to get it to pull through an array of the related media.
any tips or ideas on further refactoring?
Here?
You are joining postMultimedia with topPosts, but you are not selecting anything from topPosts
Maybe you're missing a where?
i don't understand š¤
it's essentially a mirror of what i had written initially in sql at this point
it's producing an object matching the 'selectObj' variable which i guess is obvious, and it's getting one media object with id and url. problem is i want it to produce an array of media objects
You'll probably need to aggregate it yourself. Or if you want the database to do it for you, you can use json_agg function
ah yeah that makes sense, since i was doing that manually before
Try that and let me know
are we able to order that?
also, tysm for spending time on this! š«”
What do you mean? order what?
i'll try just ordering it in the subquery
Oh, I see
when i was doing the raw sql i was ordering like this:
.orderBy(({ createdAt, media }) => [desc(createdAt), asc(media.url)])
Yeah, probably better to order it in the with
I think this is equivalent to:
I'm not sure that join is necessary
š® how could it not be?
oh right i can just use where i guess
Since there is no where, you are joining a table that you are not selecting
not following... we're selecting top 10 from posts, and media that belongs to those posts, hence the join
anyways, since i added the media
json_agg
it's now making me add *every *column as an entry to .groupBy, which i'm sure will not produce the intended result. sorry for being difficult š¤£I think you got it from here lol
at this point i'm gonna revert lol
No you're not
š
i don't understand this š¤
i'm new to json functionality in postgres so not sure why it's giving me an error like this for every column now.
PostgresError: column "top_posts.id" must appear in the GROUP BY clause or be used in an aggregate function
I wrote that query from memory, might have issues. I can't test right now in a database but I can suggest you run a
findMany
query with a related table.
Make sure you pass {logger: true}
to drizzle so you can see the query it produces
And then use it as guideidk what's funny about that, this is way more complex than just writing raw sql lmao