From 66e624486d859e0c8360026866855b5915b96538 Mon Sep 17 00:00:00 2001
From: Mergen Imeev <imeevma@tarantool.org>
Date: Tue, 10 Oct 2023 12:47:06 +0300
Subject: [PATCH] sql: introduce sql_fieldno_by_expr()

This patch introduces the sql_fieldno_by_expr() function. This function
is used to search for a space field based on a given expression.

Needed for #4467

NO_DOC=refactoring
NO_TEST=refactoring
NO_CHANGELOG=refactoring
---
 src/box/sql/build.c  | 12 ++++--------
 src/box/sql/expr.c   |  6 ++++++
 src/box/sql/sqlInt.h |  7 +++++++
 3 files changed, 17 insertions(+), 8 deletions(-)

diff --git a/src/box/sql/build.c b/src/box/sql/build.c
index 819c29677f..f2b58cf772 100644
--- a/src/box/sql/build.c
+++ b/src/box/sql/build.c
@@ -3344,24 +3344,20 @@ int
 sql_fieldno_by_name(struct Parse *parse_context, struct Expr *field_name,
 		    uint32_t *fieldno)
 {
-	struct space_def *def = parse_context->create_table_def.new_space->def;
+	const struct space *space = parse_context->create_table_def.new_space;
 	struct Expr *name = sqlExprSkipCollate(field_name);
 	if (name->op != TK_ID) {
 		diag_set(ClientError, ER_INDEX_DEF_UNSUPPORTED, "Expressions");
 		parse_context->is_aborted = true;
 		return -1;
 	}
-	uint32_t i;
-	for (i = 0; i < def->field_count; ++i) {
-		if (strcmp(def->fields[i].name, name->u.zToken) == 0)
-			break;
-	}
-	if (i == def->field_count) {
+	uint32_t id = sql_fieldno_by_expr(space, name);
+	if (id == UINT32_MAX) {
 		diag_set(ClientError, ER_SQL_CANT_RESOLVE_FIELD, name->u.zToken);
 		parse_context->is_aborted = true;
 		return -1;
 	}
-	*fieldno = i;
+	*fieldno = id;
 	return 0;
 }
 
diff --git a/src/box/sql/expr.c b/src/box/sql/expr.c
index d8a872251b..5775ef8b84 100644
--- a/src/box/sql/expr.c
+++ b/src/box/sql/expr.c
@@ -5436,3 +5436,9 @@ sqlClearTempRegCache(Parse * pParse)
 	pParse->nRangeReg = 0;
 }
 
+uint32_t
+sql_fieldno_by_expr(const struct space *space, const struct Expr *expr)
+{
+	assert(expr->op == TK_ID);
+	return sql_space_fieldno(space, expr->u.zToken);
+}
diff --git a/src/box/sql/sqlInt.h b/src/box/sql/sqlInt.h
index bf9fa94d1a..4c2464c1c1 100644
--- a/src/box/sql/sqlInt.h
+++ b/src/box/sql/sqlInt.h
@@ -3153,6 +3153,13 @@ sql_fieldno_by_token(const struct space *space, const struct Token *name);
 uint32_t
 sql_fieldno_by_id(const struct space *space, const struct IdList_item *id);
 
+/**
+ * Return the fieldno of the field with the name defined by the expression.
+ * Return UINT32_MAX if the field was not found.
+ */
+uint32_t
+sql_fieldno_by_expr(const struct space *space, const struct Expr *expr);
+
 /**
  * Return the tuple foreign key constraint with the name defined by the token.
  * Return NULL if the tuple foreign key constraint was not found.
-- 
GitLab