I want to use an alias for the order by clause in ...
# exposed
j
I want to use an alias for the order by clause in Exposed Kotlin like so:
Copy code
6371 * ACOS(COS(RADIANS(:latitude)) * COS(RADIANS(`lat`)) * COS(RADIANS(:longitude) - RADIANS(`lng`)) + SIN(RADIANS(:latitude)) * SIN(RADIANS(`lat`))) AS `distance`
Anyone with an idea on how to implement this?
s
Use the alias function
e
alias.aliasOnlyExpression
could be useful
j
How exactly @spand @Endre Deak
Anyone? Not sure how to use the alias function in this specific usecase.
e
what’s your full query
?
j
To simplify, I'm getting a list of offices. I want to order them by location
Something like:
Copy code
Offices
    .leftJoin(Doctors, { Offices.doctor }, { Doctors.id })
    .slice(
       ...,
       ...,
).selectAll().limit(20).orderBy(...)
I know I can have the calculations in Kotlin like so but I still don't understand how to use the alias function to order the query.
Copy code
val distance = 6371 *
        Math.acos(
            Math.cos(Math.toRadians(myLatitude)) *
                    Math.cos(Math.toRadians(officeLatitude)) *
                    Math.cos(
                        Math.toRadians(officeLongitude) -
                                Math.toRadians(myLongitude)
                    ) +
                    Math.sin(Math.toRadians(myLatitude)) *
                    Math.sin(Math.toRadians(officeLatitude))
        )
How do you think i can use alias.aliasOnlyExpression @Endre Deak?
s
If you really want the database to do that then you need to convert the math expression to an exposed expression like you would in the
.select { }
block
j
I would really need an example
t
As there is no such functions like acos/cos/etc in Exposed (and it would be great if you'll contribute them:) first of all you need to declare such functions:
Copy code
fun CustomDoubleFunction(
    functionName: String,
    vararg params: Expression<*>
): CustomFunction<BigDecimal> = CustomFunction(functionName, DoubleColumnType(), *params)

fun Radiants(exp: Expression<BigDecimal>) = CustomDoubleFunction("RADIANTS", exp)
after that when you'll have all needed functions you can write:
Copy code
val distance = Acos(Cos(Radiants(MyTable.lattitue))) * ...
e
👆 A bunch of those functions would do that.