简体   繁体   English

PostgreSQL 10日期范围约束

[英]postgresql 10 date range contraint

I want to make a date range constraint in postgresql 10. In postgresql 9.6 this worked: 我想在postgresql 10中设置日期范围约束。在postgresql 9.6中,此方法有效:

CREATE TABLE project_lines (
  id SERIAL PRIMARY KEY,
  project_id INTEGER NOT NULL REFERENCES projects(id),
  description VARCHAR(200) NOT NULL,
  start_time TIMESTAMP NOT NULL,
  end_time TIMESTAMP CHECK(end_time > start_time),
  created_at TIMESTAMP NOT NULL DEFAULT NOW(),
  CONSTRAINT overlapping_times EXCLUDE USING GIST(
    project_id WITH =,
    tstzrange(start_time, COALESCE(end_time, 'infinity')) WITH &&
  )
);

But in postgresql 10 I am getting this error: 但是在PostgreSQL 10中,我得到这个错误:
functions in index expression must be marked IMMUTABLE

How can I make this constraint working? 如何使该约束起作用?

The start_time and end_time columns have type TIMESTAMP , while the tstzrange expects TIMESTAMPTZ (with time zone). start_timeend_time列的类型为TIMESTAMP ,而tstzrange期望的是TIMESTAMPTZ (带有时区)。 Apparently this conversion happens automatically, but it's not considered "IMMUTABLE". 显然,这种转换是自动发生的,但它不被认为是“不可改变的”。

The documentation at https://www.postgresql.org/docs/10/static/xfunc-volatility.html says 在文档https://www.postgresql.org/docs/10/static/xfunc-volatility.html

A common error is to label a function IMMUTABLE when its results depend on a configuration parameter. 一个常见的错误是标记的函数IMMUTABLE当其结果取决于配置参数。 For example, a function that manipulates timestamps might well have results that depend on the TimeZone setting. 例如,一个操作时间戳的函数可能有依赖于timezone设置的结果。 For safety, such functions should be labeled STABLE instead. 出于安全考虑,这样的函数应该标记为稳定。

You should probably use tsrange instead, or explicitly convert to timestamp with time zone (in a way that doesn't depend on server settings): 你或许应该使用tsrange代替,或显式转换与时区时间戳(在不依赖于服务器设置的方式):

tstzrange(start_time at time zone 'utc', COALESCE(end_time at time zone 'utc', 'infinity')) WITH &&

I don't know what has changed between versions, though (and I get the same error message with 9.6.6). 我不知道是什么版本之间改变了,虽然(我也得到了同样的错误消息9.6.6)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM