I’m using Exposed, and I’m having trouble retrievi...
# ktor
t
I’m using Exposed, and I’m having trouble retrieving results from a select query..
I’ve got a ‘Reports’ table, a ‘User’ table, and a ‘Votes’ table. Votes is just a join table between user.id and report.id. I’m constructing a query to retrieve all reports, with an additional column representing the sum of their votes:
Copy code
suspend fun getReports(): List<Report> = DatabaseManager.dbQuery {
        val voteCount = Votes.userId.countDistinct()

        (Reports leftJoin Votes)
            .slice(Reports.columns + voteCount)
            .selectAll()
            .map { row ->
                Report(
                    row[Reports.id],
                    row[Reports.userId],
                    row[Reports.title],
                    row[Reports.description],
                    row[voteCount],
                    row[Reports.appVersion],
                    row[Reports.deviceName],
                    row[Reports.osVersion],
                    row[Reports.dateCreated],
                    row[Reports.dateResolved]
                )
            }
    }
But this only ever returns one row. What gives?
s
Isnt that how count works
t
What do you mean?
s
Well that aggregate functions collapse to the group
Maybe you want a group by also ?
t
For each report, I would like the count of votes for that report, distinct by user id
But this is a selectAll() function, not a count() function
s
Maybe you should write your sql and we can help translate it to exposed
t
Well, yeah that would be a good starting point.
Unfortunately, that’s half the problem for me as well
s
selectAll
just means no sql where clause
Try to group by
Reports.id
t
OK. Does that mean the slice is unnecessary?
s
No. You need to slice all the colums you use in the map
t
OK great, that’s all it took
Can you help me understand - I don’t get why groupBy is necessary, or helps here
s
Try to google sql aggregate functions
t
OK, will do. Thanks
I was mostly getting confused by the DSL, because it’s a little hard to translate to sql - and then I’m not that experienced writing complex sql queries, so I can’t validate it at all
So I don’t know if I’ve made a syntax error, misunderstood the dsl->sql mapping, or misunderstood the sql required!
s
slice is sql select select is sql where
t
slice is sql select
Hah, thanks so much for this lol
I couldn’t figure it out
k
yeah, Exposed can be pretty confusing. I ended up switching to ktorm which I like much better.
👍 1
d
I too am not a fan of Exposed. I may give ktorm a try.