From 75e6daae0fe119f222d4495869e43112b68c8736 Mon Sep 17 00:00:00 2001
From: "Andrey M. Borodin" <x4mmm@flight.local>
Date: Mon, 20 Feb 2023 10:28:02 -0800
Subject: [PATCH v4 1/2] Fix incorrect argument handling in psql \watch

Incorrectly parsed argument was silently substituted with 1 second.
This is changed to proper error message.

Authour: Andrey Borodin <amborodin@acm.org>
Reviewed-by: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Reviewed-by: Nathan Bossart <nathandbossart@gmail.com>
Thread: https://postgr.es/m/CAAhFRxiZ2-n_L1ErMm9AZjgmUK%3DqS6VHb%2B0SaMn8sqqbhF7How%40mail.gmail.com
---
 src/bin/psql/command.c | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)

diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c
index 955397ee9d..b1707eb972 100644
--- a/src/bin/psql/command.c
+++ b/src/bin/psql/command.c
@@ -2776,9 +2776,15 @@ exec_command_watch(PsqlScanState scan_state, bool active_branch,
 		/* Convert optional sleep-length argument */
 		if (opt)
 		{
-			sleep = strtod(opt, NULL);
-			if (sleep <= 0)
-				sleep = 1;
+			char *opt_end;
+			sleep = strtod(opt, &opt_end);
+			if (sleep < 0 || *opt_end)
+			{
+				pg_log_error("Watch period must be non-negative number, but argument is '%s'", opt);
+				free(opt);
+				resetPQExpBuffer(query_buf);
+				return PSQL_CMD_ERROR;
+			}
 			free(opt);
 		}
 
@@ -5183,6 +5189,9 @@ do_watch(PQExpBuffer query_buf, double sleep)
 		if (pagerpipe && ferror(pagerpipe))
 			break;
 
+		if (sleep == 0)
+			continue;
+
 #ifdef WIN32
 
 		/*
-- 
2.32.0 (Apple Git-132)

