简体   繁体   中英

postgresql set timezone for materialized view

ok - we've found a bug in one of our systems with materialized views refreshing to different data, depending on which system called the refresh.

It turned out to be a problem with the client date settings - it depends on the timezone of the user.

This is a big risk. I know per field we can override settings - but it's tricky - because views consume other views, and date conversions/calculations are happpening anywhere in the view hierarchy - so there's no way we can guarantee client specific calculations won't get through.

Is there any way we can embed something in the view definition that sets the current time zone for the whole view - so it doesn't matter who does the refresh, it will always produce the same result?

I tried this - but it doesn't work:( - but want something like this:

create materialized view blah as (
set timezone to 'Australia/Brisbane';
select now())

If you code your materialized view to depend on the current setting of database parameters, you are in trouble, because many of them can be changed on the session level. Don't do that.

In the current case, avoid anything that casts date or timestamp without timezone to timestamp with time zone or vice versa, because timezone will clandestinely enter into any such conversions.

Always specify the time zone explicitly:

  • to convert from date or timestamp to timestamp with time zone , use

    current_date AT TIME ZONE 'whatever'
  • to convert from timestamp with time zone to date or timestamp , use

    current_timestamp AT TIME ZONE 'whatever'

Both operators are called AT TIME ZONE , but they are different.

I see that your problem is that there is a large body of pre-existing view definitions that do not adhere to this principle. Perhaps you can get away with something like:

WITH setzone AS (
   SELECT set_config('timezone', 'UTC', TRUE)
)
SELECT /* your query */;

But you need to change the query so that it references setzone somewhere in the query (you could CROSS JOIN it), so that it is executed.

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