ktorm icon indicating copy to clipboard operation
ktorm copied to clipboard

Render CastingExpression as "cast" function in PostgreSQL dialect

Open arustleund opened this issue 5 years ago • 3 comments

Can the CastingExpression be rendered in PostgreSQL thusly?

    override fun <T : Any> visitCasting(expr: CastingExpression<T>): CastingExpression<T> {
        write("cast(")
        super.visit(expr.expression)
        removeLastBlank()
        write(" as ")
        write(expr.sqlType.typeName)
        write(") ")
        return expr
    }

Or is this not the intention of this expression?

arustleund avatar May 19 '20 05:05 arustleund

CastingExpression was originally design just to make Kotlin's type checking happy, and it doesn't influence the generated SQL.

Assuming we want to join two tables together, in which one has an int id and the other has a long id:

object T1 : Table<Nothing>("t1") {
    val id by int("id")
}

object T2 : Table<Nothing>("t2") {
    val id by long("id")
}

We might write code like this:

database.from(T1).leftJoin(T2, on = T1.id eq T2.id)

Then the compiler complains that the types of these two ids are not matched. We have to modifiy it as follows:

database.from(T1).leftJoin(T2, on = T1.id.toLong() eq T2.id)

Just a trick.

vincentlauvlwj avatar May 21 '20 16:05 vincentlauvlwj

I just read the document of PostgreSQL's cast function. It will be great to actually generate a cast function in SQL.

vincentlauvlwj avatar May 21 '20 16:05 vincentlauvlwj

Hello,

any update on this one?

I'd be interested in this function too :)

d35h avatar May 04 '22 16:05 d35h