简体   繁体   中英

postgresql 10 date range contraint

I want to make a date range constraint in postgresql 10. In postgresql 9.6 this worked:

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:
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). 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

A common error is to label a function IMMUTABLE when its results depend on a configuration parameter. For example, a function that manipulates timestamps might well have results that depend on the TimeZone setting. 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):

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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