有一个可以抛出异常的 STABLE 函数可以吗?
Is it okay to have a STABLE function that can throw exceptions?
在不熟悉 Postgres 的情况下,我会谨慎地定义一个函数,这样它可能会被 planner/optimizer 跳过,否则它会引发异常。如果一个函数的波动性(STABLE
、VOLATILE
或 IMMUTABLE
)在引发异常时是否应该更改,或者它们是否以与 return 值相同的方式缓存?
是否有关于如何定义可以抛出的函数的既定约定?
根据 docs:
A VOLATILE
function can do anything, including modifying the database. It can return different results on successive calls with the same arguments. The optimizer makes no assumptions about the behavior of such functions. [...]
A STABLE
function cannot modify the database and is guaranteed to return the same results given the same arguments for all rows within a single statement. This category allows the optimizer to optimize multiple calls of the function to a single call. [...]
An IMMUTABLE
function cannot modify the database and is guaranteed to return the same results given the same arguments forever. This category allows the optimizer to pre-evaluate the function when a query calls it with constant arguments. [...]
关于 return 值的行为方式,这 crystal 很清楚,但未解决异常(发生在 RETURN
之前)。 ...我知道函数定义的其他部分,例如使用 STRICT
可能会导致规划器跳过可能的异常,但是这里呢?
是否存在潜在的边缘情况,其中 STABLE
函数定义为具有高调用成本(反过来使用其他 STABLE
and/or IMMUTABLE
函数来帮助它) 可能会在通常抛出时被跳过?
另一种回答这个问题的方法是解释 how/whether plpgsql compiler/interpreter 对待包含 RAISE EXCEPTION
的函数有任何不同,例如注意波动状态是否被出现的此类语句隐式改变在函数体中。
任何函数(VOLATILE、STABLE、IMMUTABLE)都可以引发异常。异常停止执行,然后回滚。
目前没有缓存任何结果。在某些情况下,STABLE 或 IMMUTABLE 函数的调用可以在计划时间内由它们的结果替换。如果函数索引可以使用IMMUTABLE函数,然后不调用该函数,使用索引中的值。
在不熟悉 Postgres 的情况下,我会谨慎地定义一个函数,这样它可能会被 planner/optimizer 跳过,否则它会引发异常。如果一个函数的波动性(STABLE
、VOLATILE
或 IMMUTABLE
)在引发异常时是否应该更改,或者它们是否以与 return 值相同的方式缓存?
是否有关于如何定义可以抛出的函数的既定约定?
根据 docs:
A
VOLATILE
function can do anything, including modifying the database. It can return different results on successive calls with the same arguments. The optimizer makes no assumptions about the behavior of such functions. [...]A
STABLE
function cannot modify the database and is guaranteed to return the same results given the same arguments for all rows within a single statement. This category allows the optimizer to optimize multiple calls of the function to a single call. [...]An
IMMUTABLE
function cannot modify the database and is guaranteed to return the same results given the same arguments forever. This category allows the optimizer to pre-evaluate the function when a query calls it with constant arguments. [...]
关于 return 值的行为方式,这 crystal 很清楚,但未解决异常(发生在 RETURN
之前)。 ...我知道函数定义的其他部分,例如使用 STRICT
可能会导致规划器跳过可能的异常,但是这里呢?
是否存在潜在的边缘情况,其中 STABLE
函数定义为具有高调用成本(反过来使用其他 STABLE
and/or IMMUTABLE
函数来帮助它) 可能会在通常抛出时被跳过?
另一种回答这个问题的方法是解释 how/whether plpgsql compiler/interpreter 对待包含 RAISE EXCEPTION
的函数有任何不同,例如注意波动状态是否被出现的此类语句隐式改变在函数体中。
任何函数(VOLATILE、STABLE、IMMUTABLE)都可以引发异常。异常停止执行,然后回滚。
目前没有缓存任何结果。在某些情况下,STABLE 或 IMMUTABLE 函数的调用可以在计划时间内由它们的结果替换。如果函数索引可以使用IMMUTABLE函数,然后不调用该函数,使用索引中的值。