2017-08-08 74 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来做到这一点。

相关问题