From 2e215c0ddb3665c8145f22520bce905efe6d954d Mon Sep 17 00:00:00 2001
From: Alexander Korotkov <akorotkov@postgresql.org>
Date: Sat, 19 Oct 2019 11:18:32 +0300
Subject: [PATCH 1/2] Refactor timestamp2timestamptz_opt_error()

While casting from timestamp to timestamptz we do timestamp2tm() then
tm2timestamp().  This commit eliminates call to tm2timestamp().  Instead, it
directly applies timezone offset to the original timestamp value.  This make
upcoming jsonpath overflow handling easier.  Also, it should save us some CPU
cycles.

Discussion: https://postgr.es/m/CAPpHfdvRPRh_mTGar5WmDeRZ%3DU5dOXHdxspYYD%3D76m3knNGjXA%40mail.gmail.com
Author: Alexander Korotkov
Reviewed-by: Tom Lane
---
 src/backend/utils/adt/timestamp.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/src/backend/utils/adt/timestamp.c b/src/backend/utils/adt/timestamp.c
index 84bc97d40c3..90ebb50e1f5 100644
--- a/src/backend/utils/adt/timestamp.c
+++ b/src/backend/utils/adt/timestamp.c
@@ -5210,8 +5210,17 @@ timestamp2timestamptz_opt_error(Timestamp timestamp, bool *have_error)
 	{
 		tz = DetermineTimeZoneOffset(tm, session_timezone);
 
-		if (!tm2timestamp(tm, fsec, &tz, &result))
+		result = dt2local(timestamp, -tz);
+
+		if (IS_VALID_TIMESTAMP(result))
+		{
 			return result;
+		}
+		else if (have_error)
+		{
+			*have_error = true;
+			return (TimestampTz) 0;
+		}
 	}
 
 	if (have_error)
-- 
2.14.3

