2017-08-08 77 views
1

我有這樣定義的列:如何使用JOOQ將Postgres「infinity」插入時間戳字段?

expiry timestamp(0) without time zone not null 

隨着Postgres的,我可以發出SQL這樣的:

insert into my_table(expiry) values ('infinity') 

我已經通過JOOQ DOCO挖,但找不到任何例子處理這個問題。 我可以用JOOQ做到嗎 - 它會是什麼樣子?

此外,是否有可能使用UpdatableRecord?我可以使用Timestamp的某種無限「標誌」實例嗎?

回答

1

好吧,找到一種方法直接做到這一點。

MyRecord r = db.insertInto(
    MY_RECORD, 
    MY_RECORD.ID, 
    MY_RECORD.CREATED, 
    MY_RECORD.EXPIRY 
).values(
    val(id), 
    currentTimestamp(), 
    val("infinity").cast(Timestamp.class) 
).returning().fetchOne(); 

但是,這感覺更像是一個解決辦法,而不是做正確的方式。鑄造一個字符串轉換爲timestamp似乎有點迂迴的我,所以我寫了一個CustomField要使用它,查詢更方便:

public class TimestampLiteral extends CustomField<Timestamp> { 
    public static final TimestampLiteral INFINITY = 
    new TimestampLiteral("'infinity'"); 
    public static final TimestampLiteral NEGATIVE_INFINITY = 
    new TimestampLiteral("'-infinity'"); 
    public static final TimestampLiteral TODAY = 
    new TimestampLiteral("'today'"); 

    private String literalValue; 

    public TimestampLiteral(String literalValue){ 
    super("timestamp_literal", SQLDataType.TIMESTAMP); 
    this.literalValue = literalValue; 
    } 

    @Override 
    public void accept(Context<?> context){ 
    context.visit(delegate(context.configuration())); 
    } 

    private QueryPart delegate(Configuration configuration){ 
    switch(configuration.dialect().family()){ 
     case POSTGRES: 
     return DSL.field(literalValue); 

     default: 
     throw new UnsupportedOperationException(
      "Dialect not supported - rethink your life choices."); 
    } 
    } 

} 

則該查詢:

MyRecord r = db.insertInto(
    MY_RECORD, 
    MY_RECORD.ID, 
    MY_RECORD.CREATED, 
    MY_RECORD.EXPIRY 
).values(
    val(id), 
    TimestampLiteral.TODAY, 
    TimestampLiteral.INFINITY 
).returning().fetchOne(); 

別不知道這是否是「正確」的方式來做到這一點,但似乎目前工作。

仍然有興趣聽到有沒有辦法用UpdatableRecord來做到這一點。

相關問題