From a3f262cb96733cc041a7df1a43fe0f81c71f1474 Mon Sep 17 00:00:00 2001
From: Yugo Nagata <nagata@sraoss.co.jp>
Date: Wed, 13 Aug 2025 19:16:06 +0900
Subject: [PATCH 2/2] pgbench: Add syntax for variable exisitence check

Now, :{?var} can be used in meta-command arguments. It can not
be used in SQL statements.
---
 src/bin/pgbench/exprscan.l |  4 +++-
 src/bin/pgbench/pgbench.c  | 27 +++++++++++++++++++++++++--
 2 files changed, 28 insertions(+), 3 deletions(-)

diff --git a/src/bin/pgbench/exprscan.l b/src/bin/pgbench/exprscan.l
index 5747af38cb2..fb14f5276e7 100644
--- a/src/bin/pgbench/exprscan.l
+++ b/src/bin/pgbench/exprscan.l
@@ -182,12 +182,14 @@ notnull			[Nn][Oo][Tt][Nn][Uu][Ll][Ll]
 {else}			{ return ELSE_KW; }
 {end}			{ return END_KW; }
 
-:{alnum}+		{
+:{alnum}+		|
+:\{\?{alnum}+\}	{
 					yylval->str = pg_strdup(yytext + 1);
 					return VARIABLE;
 				}
 
 {null}			{ return NULL_CONST; }
+
 {true}			{
 					yylval->bval = true;
 					return BOOLEAN_CONST;
diff --git a/src/bin/pgbench/pgbench.c b/src/bin/pgbench/pgbench.c
index 14d1261ff8d..ae0b9ccaf83 100644
--- a/src/bin/pgbench/pgbench.c
+++ b/src/bin/pgbench/pgbench.c
@@ -1920,7 +1920,6 @@ parseVariable(const char *sql, int *eaten, PsqlScanQuoteType *quote)
 	int			start;
 	int			len;
 
-
 	if (sql[i] == '\'')
 	{
 		i++;
@@ -2958,12 +2957,36 @@ evaluateExpr(CState *st, PgBenchExpr *expr, PgBenchValue *retval)
 		case ENODE_VARIABLE:
 			{
 				Variable   *var;
+				char	   *varname = expr->u.variable.varname;
+				bool		is_test_var = false;
+
+				if (varname[0] == '{' && varname[1] == '?')
+				{
+					int len;
+
+					is_test_var = true;
+					varname = pg_strdup(varname + 2);
+					len = strlen(varname);
+					varname[len - 1] = '\0';
+				}
 
-				if ((var = lookupVariable(&st->variables, expr->u.variable.varname)) == NULL)
+				if ((var = lookupVariable(&st->variables, varname)) == NULL)
 				{
 					pg_log_error("undefined variable \"%s\"", expr->u.variable.varname);
+					if (is_test_var)
+					{
+						free(varname);
+						setBoolValue(retval, false);
+						return true;
+					}
 					return false;
 				}
+				else if (is_test_var)
+				{
+					setBoolValue(retval, true);
+					free(varname);
+					return true;
+				}
 
 				if (!makeVariableValue(var))
 					return false;
-- 
2.43.0

