# 42P19 — 无效递归

> PostgreSQL SQLSTATE 42P19：来源与诊断参考。
---

# 42P19 — 无效递归

## 速览 {#at-a-glance}

`42P19`（**invalid_recursion**）递归项运行前会先检查递归查询结构。

<!-- BEGIN SQLSTATE FACTS: generated by scripts/generate.py; do not edit -->

| 字段 | 值 |
| --- | --- |
| SQLSTATE | `42P19` |
| 条件名 | `invalid_recursion` |
| 状态 | `有效` |
| 已知存在于 | `8.4.0` |
| 锁定快照 | `9.0.23, 9.1.24, 9.2.24, 9.3.25, 9.4.26, 9.5.25, 9.6.24, 10.23, 11.22, 12.22, 13.23, 14.24, 15.19, 16.15, 17.11, 18.6, 19beta3` |
| 宏 | `ERRCODE_INVALID_RECURSION` |
| 别名 | `—` |

<!-- source facts: data/errcodes/42P19.json -->
<!-- END SQLSTATE FACTS -->

## 含义 {#meaning}

递归查询校验会拒绝无法安全求值的递归项。18.6 核心检查递归项中使用聚合、非递归项 `UNION [ALL]` 递归项这一必要结构，以及递归引用的上下文和次数。选定的聚合 guard 针对的是聚合（`p_hasAggs`）；不能据此说所有窗口函数都被禁止。

## 诊断 {#diagnosis}

检查查询结构，而不只是 CTE 名称。分开锚点项与递归项，统计递归查询的引用次数，并检查引用是否出现在子查询或外连接的可空侧：`LEFT JOIN` 是右侧，`RIGHT JOIN` 是左侧，`FULL JOIN` 是两侧；单侧外连接的保留侧不受该 guard 限制。还要检查 `INTERSECT`/`EXCEPT` 上下文。找出递归项中的实际聚合，不要把所有窗口表达式都归入此错误。这能把结构性递归错误与 42P18 类型推断失败区分开。

## 处理 {#response}

将 CTE 改写为一个非递归锚点项，后接一个 `UNION` 或 `UNION ALL` 递归项，只在允许的上下文中保留一次递归引用；需要聚合时移到递归步骤之外。重试前验证终止条件和结果基数。如果 ERROR 发生在显式事务中，发送重写后的查询前先 `ROLLBACK` 或回滚到错误前的保存点。

## 消息 {#messages}

固定源码中的代表性消息包括：message: `aggregate functions are not allowed in a recursive query's recursive term`；message: `recursive query "%s" does not have the form non-recursive-term UNION [ALL] recursive-term`；message: `recursive reference to query "%s" must not appear more than once`。占位符由实际对象、列或参数填充。

## 版本 {#versions}

锁定目录显示该条件最早见于 PostgreSQL 8.4.0；行为说明固定在 PostgreSQL 18.6 源码，目录存在范围不等于每条消息或功能都从该版本开始。

## 相关 {#related}

- [`42P18`](../42p18/)
- [`42P07`](../42p07/)

## 来源 {#sources}

源码消息、行号和证据边界见 [作者证据](../../data/evidence/42p19.json)。

- `src/backend/parser/parse_agg.c:1329-1333` ([fixed source](https://github.com/postgres/postgres/blob/724edf9bde9d356724ad384a2e196edc3c9f80f7/src/backend/parser/parse_agg.c#L1329-L1333))
- `src/backend/parser/parse_cte.c:940-944` ([fixed source](https://github.com/postgres/postgres/blob/724edf9bde9d356724ad384a2e196edc3c9f80f7/src/backend/parser/parse_cte.c#L940-L944))
- `src/backend/parser/parse_cte.c:1072-1077` ([fixed source](https://github.com/postgres/postgres/blob/724edf9bde9d356724ad384a2e196edc3c9f80f7/src/backend/parser/parse_cte.c#L1072-L1077))
- `src/backend/parser/parse_cte.c:1056-1069` ([fixed source](https://github.com/postgres/postgres/blob/724edf9bde9d356724ad384a2e196edc3c9f80f7/src/backend/parser/parse_cte.c#L1056-L1069))
