How to select unix timestamp as date in Jooq?

江枫思渺然 提交于 2020-05-27 09:26:07

问题


I am working in with a database in which dates are stored as unix time (seconds since 1970). I have the following sql which works as expected:

select CONVERT_TZ(FROM_UNIXTIME(creation_date), @@session.time_zone, "Europe/Berlin")
from transaction; 

This is how I tried to do it in Jooq:

dsl.select(DSL.date(TRANSACTION.CREATION_DATE) // This does not work
   .from(TRANSACTION)
   .fetch();

回答1:


You're using quite a few vendor specific functions there, which are not supported out of the box in jOOQ. As always, when you run into this situation, you can roll your own support by using plain SQL templating, ideally by building your own library:

public static Field<Timestamp> fromUnixtime(Field<? extends Number> field) {
    return field("from_unixtime({0})", SQLDataType.TIMESTAMP, field);
}

public static Field<Timestamp> convertTz(
    Field<Timestamp> field,
    Field<String> fromTz,
    Field<String> toTz
) {
    return field("convert_tz({0}, {1}, {2})", SQLDataType.TIMESTAMP, field, fromTz, toTz);
}

public static Field<String> sessionTimeZone() {
    return field("@@session.time_zone", SQLDataType.VARCHAR);
}

Now, you can use it like this:

dsl.select(convertTz(
        fromUnixtime(TRANSACTION.CREATION_DATE), 
        sessionTimeZone(), 
        inline("Europe/Berlin"))
   )
   .from(TRANSACTION)
   .fetch();

Or, take it a step further and wrap all of these expressions in yet another auxiliary function, like this one:

public static Field<Timestamp> fromUnixtimeToBerlinTZ(Field<? extends Number> field) {
    return convertTz(
        fromUnixtime(TRANSACTION.CREATION_DATE), 
        sessionTimeZone(), 
        inline("Europe/Berlin")
    );
}

All of these examples are assuming the usual static import:

import static org.jooq.impl.DSL.*;


来源:https://stackoverflow.com/questions/60848890/how-to-select-unix-timestamp-as-date-in-jooq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!