Opened 10 months ago

Closed 10 months ago

Last modified 10 months ago

#35193 closed Bug (invalid)

Range dumper assumes timezone aware datetimes.

Reported by: Mapiarz Owned by: nobody
Component: Database layer (models, ORM) Version: 4.2
Severity: Normal Keywords: psycopg3
Cc: Florian Apolloner Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hi. I encountered a blocker that I'm not sure how to resolve.

I'm running Django 4.2 and wanted to update from psycopg2 to psycopg (the latest version 3).

The update itself is quite simple in my case and almost everything works except timezone unaware datetime ranges. Let me explain.

In my app, I have timezones enabled. For a few rare exceptions, I need to store timezone unaware datetimes. I was able to accomplish this by subclassing the DateTimeField shipped by Django and removing the related timezone conversions. Furthermore, I also need timezone unaware datetime ranges. That's also easy since I can subclass DateTimeRangeField and specify my timezone unaware field as the base_field, use timezone unaware range_type and make sure the correct db_type is returned from db_type method (tsrange).

This has gotten me a very long way with psycopg2. After migrating to latest psycopg, I started getting a DB crash whenever I try to modify one of my objects that has a timezone unaware datetime range. This crash, specifically, happens when checking an ExclusionConstraint with an OVERLAPS expression on the datetime range. The error is:

Got a database error calling check() on ...: cannot cast type tstzrange to tsrange ...02-17 00:00:00","2024-02-24 00:00:00")'::tstzrange::tsrange)...

As far as I can tell, this is caused by django.db.backends.postgresql.psycopg_any.DjangoRangeDumper which assumes that there can only ever be timezone aware timestamps.

Overall, I'm not sure how to proceed. I'm not familiar with the django postgres backend or psycopg itself. Please advise.

Change History (2)

comment:1 by Mariusz Felisiak, 10 months ago

Cc: Florian Apolloner added
Keywords: psycopg3 added
Resolution: invalid
Status: newclosed
Summary: Timezone unaware datetimes and psycopg 3Range dumper assumes timezone aware datetimes.
Type: UncategorizedBug

Thanks for the report. As far as I'm aware, there is no way in the dumper to detect that you're using tsrange and change the behavior. You should be able to use register_dumper() to override the dumper.

comment:2 by Mapiarz, 10 months ago

Thanks Mariusz.

In the overriden dumper, is it ok to never cast to tstzrange like the built in dumper does? I'm not sure why that is needed in the first place and I don't want to break something with 'normal' (i.e. timezone aware) fields.

Note: See TracTickets for help on using tickets.
Back to Top