41.4. Выражения
Все выражения, используемые в операторах PL/pgSQL, обрабатываются основным исполнителем SQL-сервера. Например, для вычисления такого выражения:
IF выражение
THEN ...
PL/pgSQL отправит следующий запрос исполнителю SQL:
SELECT выражение
При формировании команды SELECT
все вхождения имён переменных PL/pgSQL заменяются параметрами, как подробно описано в Подразделе 41.11.1. Это позволяет один раз подготовить план выполнения команды SELECT
и повторно использовать его в последующих вычислениях с различными значениями переменных. Таким образом, при первом использовании выражения, по сути происходит выполнение команды PREPARE
. Например, если мы объявили две целочисленные переменные x
и y
, и написали:
IF x < y THEN ...
то, что реально происходит за сценой, эквивалентно:
PREPARE имя_оператора
(integer, integer) AS SELECT $1 < $2;
и затем, эта подготовленная команда исполняется (EXECUTE
) для каждого оператора IF
с текущими значениями переменных PL/pgSQL, переданных как значения параметров. Обычно эти детали не важны для пользователей PL/pgSQL, но их полезно знать при диагностировании проблем. Более подробно об этом рассказывается в Подразделе 41.11.2.
41.4. Expressions
All expressions used in PL/pgSQL statements are processed using the server's main SQL executor. For example, when you write a PL/pgSQL statement like
IF expression
THEN ...
PL/pgSQL will evaluate the expression by feeding a query like
SELECT expression
to the main SQL engine. While forming the SELECT
command, any occurrences of PL/pgSQL variable names are replaced by parameters, as discussed in detail in Section 41.11.1. This allows the query plan for the SELECT
to be prepared just once and then reused for subsequent evaluations with different values of the variables. Thus, what really happens on first use of an expression is essentially a PREPARE
command. For example, if we have declared two integer variables x
and y
, and we write
IF x < y THEN ...
what happens behind the scenes is equivalent to
PREPARE statement_name
(integer, integer) AS SELECT $1 < $2;
and then this prepared statement is EXECUTE
d for each execution of the IF
statement, with the current values of the PL/pgSQL variables supplied as parameter values. Normally these details are not important to a PL/pgSQL user, but they are useful to know when trying to diagnose a problem. More information appears in Section 41.11.2.