kotlin-orm / ktorm

A lightweight ORM framework for Kotlin with strong-typed SQL DSL and sequence APIs.
https://www.ktorm.org
Apache License 2.0
2.09k stars 148 forks source link

Table aliased not exposing properties (unresolved reference) #505

Open shi-rudo opened 1 year ago

shi-rudo commented 1 year ago

Using Spring-Boot 3.0.6 with Java 17:

    implementation("org.ktorm:ktorm-core:3.6.0")
    implementation("org.ktorm:ktorm-support-postgresql:3.6.0")
    implementation("org.ktorm:ktorm-jackson:3.6.0")

The tables taken from the docs :

object Departments : Table<Nothing>("t_department") {
    val id = int("id").primaryKey()
    val name = varchar("name")
    val location = varchar("location")
}

object Employees : Table<Nothing>("t_employee") {
    val id = int("id").primaryKey()
    val name = varchar("name")
    val job = varchar("job")
    val managerId = int("manager_id")
    val hireDate = date("hire_date")
    val salary = long("salary")
    val departmentId = int("department_id")
}

Note: using concrete classes instead Nothing does not fix the problem

Method based on docs:

    private fun prepareQuery(): Query {
        val emp = Employees.aliased("emp") // Line 3, give an alias to the Employees table.
        val mgr = Employees.aliased("mgr") // Line 4, give another alias to the Employees table.
        val dept = Departments.aliased("dept")

        return db
            .from(emp)
            .leftJoin(mgr, on = emp.managerId eq mgr.id) // Line 8, join one Employees table to the other. 
            .leftJoin(dept, on = emp.departmentId eq dept.id)
            .select(emp.name, mgr.name, dept.name)
            .orderBy(emp.id.asc())
    }

The compiler says Unresolved reference: managerId 🚨

error

Any ideas what I am doing wrong? Thanks a lot!

shi-rudo commented 1 year ago

Arr, I should read further ...

open class Employees(alias: String?) : Table<Nothing>("t_employee", alias) {
    companion object : Employees(null)
    override fun aliased(alias: String) = Employees(alias)

    val id = int("id").primaryKey()
    val name = varchar("name")
    val job = varchar("job")
    val managerId = int("manager_id")
    val departmentId = int("department_id")
}

works, you can close