npgsql icon indicating copy to clipboard operation
npgsql copied to clipboard

Npgsql.NodaTime: Write instant (utc) into timestamptz database field not works as expected

Open eschgi opened this issue 8 years ago • 8 comments

Steps to reproduce

Set timezone of the connection string to another timezone than UTC (for example to Asia/Tokyo) Server=127.0.0.1;Port=5432;Pooling=false;User ID=postgres;Password=******;CommandTimeout=600;Timezone=Asia/Tokyo

Get current instant: Instant currentInstant = Clock.GetCurrentInstant();

Insert this instant into a timestamptz field.

Open your favorite postgres database tool. Set the time zone to UTC. Execute following sql statement: set time zone 'UTC';

Compare the database timestamp with the saved timestamp. The timestamp's are different.

The issue

An instant isn't saved correctly into a timestamptz field.

Further technical details

Npgsql version: 4.0.2 PostgreSQL version: 10.5 Operating system: Windows 10

eschgi avatar Aug 13 '18 09:08 eschgi

@eschgi Are you expecting the instant created in your local system time zone to be converted into a different time zone by the NodaTime plugin upon saving?

austindrenski avatar Aug 13 '18 13:08 austindrenski

@austindrenski Is an instant not an utc time? The documentation of noda time says following:

An instant is defined by an integral number of 'ticks' since the Unix epoch (typically described as January 1st 1970, midnight, UTC, ISO calendar), where a tick is equal to 100 nanoseconds. There are 10,000 ticks in a millisecond. An Instant has no concept of a particular time zone or calendar: it simply represents a point in time that can be globally agreed-upon.

Here the link to the documentation:

  • https://nodatime.org/1.3.x/api/NodaTime.Instant.html

The timestamptz database field represents also an UTC time. The documentation of postgres says following:

For timestamp with time zone, the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system's timezone parameter, and is converted to UTC using the offset for the timezone zone.

Here the documentation of postgres:

  • https://www.postgresql.org/docs/current/static/datatype-datetime.html

The instant is an UTC time and the timestamptz is an UTC time. I except that the two UTC times are equal.

eschgi avatar Aug 13 '18 14:08 eschgi

Ah, more timestamptz-related issues... This type really is best avoided.

Yes, timestamp with time zone can be used to represent a UTC time, but what really sets it apart from regular timestamp is that PostgreSQL performs conversions on input/output, based on the PostgreSQL session-configured timezone. In the PostgreSQL documentation you quoted above, note the following:

An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system's timezone parameter, and is converted to UTC using the offset for the timezone zone.

Npgsql sends your Instant as-is, in binary format, where there is no timezone specification - it's just a 64-bit integer representing the timestamp. PostgreSQL treats this incoming value as if "no time zone is stated", and assumes it's in the session timezone, which in your case is Asia/Tokyo, and converts it to UTC. This is why you see a different timestamp when reading the value.

You can resolve this by always setting the session timezone to UTC, even when inserting. But if you just want to store UTC everywhere, it is highly recommended you switch to timestamp without time zone, which stops PostgreSQL from doing any sort of timezone-related conversion when reading or writing. There's no reason to use timestamp with time zone if all you want is to store UTC timestamps.

Am closing this issue as this is the expected behavior, but feel free to post back here to continue the discussion or if anything is unclear.

roji avatar Aug 14 '18 06:08 roji

Thanks for the quick feedback.

I've made some tests with timestamptz and i've changed following code in the Npgsql.NodaTime and EFCore.PG.NodaTime plugin.

Changes in Npgsql.Nodatime class NpgsqlNodaTimeExtensions: Added the instant type to the clr types of timestamp with time zone.

/// <summary>
/// Sets up NodaTime mappings for the PostgreSQL date/time types.
/// </summary>
/// <param name="mapper">The type mapper to set up (global or connection-specific)</param>
public static INpgsqlTypeMapper UseNodaTime(this INpgsqlTypeMapper mapper)
	=> mapper
		.AddMapping(new NpgsqlTypeMappingBuilder
		{
			PgTypeName = "timestamp",
			NpgsqlDbType = NpgsqlDbType.Timestamp,
			DbTypes = new[] { DbType.DateTime, DbType.DateTime2 },
			ClrTypes = new[] { /*typeof(Instant), */typeof(LocalDateTime) },
			InferredDbType = DbType.DateTime,
			TypeHandlerFactory = new TimestampHandlerFactory()
		}.Build())
		.AddMapping(new NpgsqlTypeMappingBuilder
		{
			PgTypeName = "timestamp with time zone",
			NpgsqlDbType = NpgsqlDbType.TimestampTz,
			ClrTypes = new[] { typeof(Instant), typeof(ZonedDateTime), typeof(OffsetDateTime) },
			TypeHandlerFactory = new TimestampTzHandlerFactory()
		}.Build())
                ...

Changes in EFCore.PG.NodaTime class NodaTimePlugin: Removed the instant timestamp and tsrange mapping and added instant timestamptz and tstzrange mapping.

public class NodaTimePlugin : NpgsqlEntityFrameworkPlugin
{
        ...

	public override void AddMappings(NpgsqlTypeMappingSource typeMappingSource)
	{
                //typeMappingSource.ClrTypeMappings[typeof(Instant)] = _timestampInstant;
		typeMappingSource.ClrTypeMappings[typeof(LocalDateTime)] = _timestampLocalDateTime;

		typeMappingSource.StoreTypeMappings["timestamp"] =
			typeMappingSource.StoreTypeMappings["timestamp without time zone"] =
				new RelationalTypeMapping[] { _timestampInstant, _timestampLocalDateTime };

		typeMappingSource.ClrTypeMappings[typeof(Instant)] = _timestamptzInstant; // Added instant timestamptz mapping
		typeMappingSource.ClrTypeMappings[typeof(ZonedDateTime)] = _timestamptzZonedDateTime;
		typeMappingSource.ClrTypeMappings[typeof(OffsetDateTime)] = _timestamptzOffsetDateTime;

		typeMappingSource.StoreTypeMappings["timestamptz"] =
			typeMappingSource.StoreTypeMappings["timestamp with time zone"] =
				new RelationalTypeMapping[] { _timestamptzInstant, _timestamptzZonedDateTime, _timestamptzOffsetDateTime };

		typeMappingSource.ClrTypeMappings[typeof(LocalDate)] = _date;
		typeMappingSource.StoreTypeMappings["date"] = new RelationalTypeMapping[] { _date };

		typeMappingSource.ClrTypeMappings[typeof(LocalTime)] = _time;
		typeMappingSource.StoreTypeMappings["time"] = new RelationalTypeMapping[] { _time };

		typeMappingSource.ClrTypeMappings[typeof(OffsetTime)] = _timetz;
		typeMappingSource.StoreTypeMappings["timetz"] = new RelationalTypeMapping[] { _timetz };

		typeMappingSource.ClrTypeMappings[typeof(Period)] = _period;
		typeMappingSource.StoreTypeMappings["interval"] = new RelationalTypeMapping[] { _period };

		// Ranges
                //typeMappingSource.ClrTypeMappings[typeof(NpgsqlRange<Instant>)] = _timestampInstantRange;
		typeMappingSource.ClrTypeMappings[typeof(NpgsqlRange<LocalDateTime>)] = _timestampLocalDateTimeRange;

		typeMappingSource.StoreTypeMappings["tsrange"] =
			new RelationalTypeMapping[] { _timestampInstantRange, _timestampLocalDateTimeRange };
                
                
		typeMappingSource.ClrTypeMappings[typeof(NpgsqlRange<Instant>)] = _timestamptzInstantRange; // Added instant timestamptz mapping
		typeMappingSource.ClrTypeMappings[typeof(NpgsqlRange<ZonedDateTime>)] = _timestamptzZonedDateTimeRange;
		typeMappingSource.ClrTypeMappings[typeof(NpgsqlRange<OffsetDateTime>)] = _timestamptzOffsetDateTimeRange;

		typeMappingSource.StoreTypeMappings["tstzrange"] =
			new RelationalTypeMapping[] { _timestamptzInstantRange, _timestamptzZonedDateTimeRange, _timestamptzOffsetDateTimeRange };

		typeMappingSource.ClrTypeMappings[typeof(NpgsqlRange<LocalDate>)] = _dateRange;
		typeMappingSource.StoreTypeMappings["daterange"] = new RelationalTypeMapping[] { _dateRange };
	}
        ...

With this changes an instant is now saved and also loaded from the database how we expect. Is this a good idea or total nonsense?

When we want to save a local datetime we would use the LocalDateTime noda time class.

Kind regards Stefan

eschgi avatar Aug 14 '18 10:08 eschgi

@roji What do you think about our approach? See please post before.

Kind regards Stefan

eschgi avatar Aug 20 '18 05:08 eschgi

@eschgi, if I understand correctly, you're changing the default mapping of Instant from timestamp without time zone to timestamp with time zone...

Can you please explain exactly what you're trying to achieve? You're of course free to to change any aspect of Npgsql you want, but these mappings have been well thought out and I'm not sure you want to be messing with internal driver details to get your application working.

Why are you using timestamp with time zone rather than timestamp without time zone? If you're just using Instant as UTC timestamp representations, timestamp without time zone is the better way to represent that.

PS If you're only using EF Core, the Npgsql ADO.NET modifications shouldn't be necessary. The mapping decision is made at the EF Core level, and then passed on to the ADO.NET layer via NpgsqlDbType.

roji avatar Aug 20 '18 06:08 roji

@roji We want only save local timestamps in timestamp database fields and utc timestamp only in timestamptz database fields. So we know exactly, local timestamps are always only saved in timestamp database fields and utc timestamps are only saved in timestamptz database fields.

Also we want that the admin tools (for example pgadmin) are showing the local timestamp (in the timezone of the user) instead of the utc timestamp.

Kind regards Stefan

eschgi avatar Aug 20 '18 07:08 eschgi

We want only save local timestamps in timestamp database fields and utc timestamp only in timestamptz database fields. So we know exactly, local timestamps are always only saved in timestamp database fields and utc timestamps are only saved in timestamptz database fields.

I don't your application, so there's a chance the following is totally wrong, but I really, really recommend that you rethink this. timestamptz really isn't about storing UTC timestamps, it's about PostgreSQL performing timezone conversions when reading/writing values to the database. These conversions happen according to the connection's configured timezone, which is usually not the way you want to do things. It's better to leave the database out of timezone conversion logic.

I really recommend that unless you have a very good reason, store everything in UTC, always, everywhere. If needed, store the user's timezone as well, and convert from the UTC timestamps to the user's local time zone only when needed, e.g. for display purposes. In NodaTime terms, this means that your application uses Instant, storing that in the database as timestamp without time zone. When you need to display a timestamp, convert your Instant to ZonedDateTime with the user's timezone, which you either store in the database or get from the user (e.g. browser setting).

Also we want that the admin tools (for example pgadmin) are showing the local timestamp (in the timezone of the user) instead of the utc timestamp.

How are you planning for that to happen? Are you storing the user's timezone in the database? Even if you are, pgadmin will not know to use it for your "local timestamps" (you have one column with a local timestamp and another column with the user's timezone...).

Once again, pgadmin will show timestamp without time zone as-is, without any conversions to any local time zone (which is a good thing). It will show timestamp with time zone based on whatever your PostgreSQL session's TimeZone happens to be; this depends on your connection string, or worse, on where your PostgreSQL server happens to be hosted.

roji avatar Aug 20 '18 10:08 roji