Search code examples
kotlinkotlin-exposed

How do I add tables to the from clause?


I have a scenario where I need more than one table in my from clause but there is no field to join the two tables on so I don't need a join. Basically, what I want my SQL query to look like is this:

SELECT 
cg.id, cg.effective_date 
FROM 
"user" u, community_guidelines cg 
WHERE 
u.id = 1 AND 
u.guidelines_accepted_date < cg.effective_date

I tried to get this to work in code but did not have any luck. Is there a way to explicitly add a table to the from clause of my query?

CommunityGuidelinesTable
            .select { (UserTable.id eq userId) and
                    (UserTable.guidelinesAcceptedDate less CommunityGuidelinesTable.effectiveDate) }
            .orderBy(CommunityGuidelinesTable.effectiveDate to SortOrder.DESC)
            .mapNotNull {
                it.toCommunityGuidelines()
            }
            .firstOrNull()

Solution

  • Ok, I think I figured this out. Was not at all what I was expecting.

    CommunityGuidelinesTable
                .join(UserTable, JoinType.INNER, additionalConstraint = { UserTable.id eq userId })
                .slice(CommunityGuidelinesTable.id, CommunityGuidelinesTable.effectiveDate, CommunityGuidelinesTable.guidelinesText)
                .select {
                        (UserTable.guidelinesAcceptedDate less CommunityGuidelinesTable.effectiveDate) }
                .orderBy(CommunityGuidelinesTable.effectiveDate to SortOrder.DESC)
                .mapNotNull {
                    it.toCommunityGuidelines()
                }
                .firstOrNull()
    

    I got the inspiration from this blog post https://blog.jdriven.com/2019/07/kotlin-exposed-a-lightweight-sql-library/