如何插入Postgres" infinity"使用JOOQ进入时间戳字段?

时间:2017-08-08 06:30:23

标签: postgresql jooq sql-timestamp

我的列定义如下:

expiry timestamp(0) without time zone not null

使用Postgres,我可以发布SQL:

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

我一直在挖掘JOOQ doco,但无法找到任何解决这个问题的例子。 我可以用JOOQ做到这一点 - 它会是什么样子?

此外,是否可以使用UpdatableRecord?是否有某种无限的标志"我可以使用Timestamp的实例?

2 个答案:

答案 0 :(得分:2)

好的,找到了直接做的方法。

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

答案 1 :(得分:1)

我创建了一个java.sql.Timestamp,并将org.postgresql.PGStatement.DATE_POSITIVE_INFINITY传递给其构造函数。

create.insertInto(
  MY_RECORD, 
  MY_RECORD.ID,
  MY_RECORD.CREATED,
  MY_RECORD.EXPIRY
).values(
  1,
  new Timestamp(System.currentTimeMillis()),
  new Timestamp(PGStatement.DATE_POSITIVE_INFINITY)
).execute();