# psycopg2.OperationalError: 错误：无法创建临时文件：设备上没有剩余空间 提示：您可能需要增加 max_files_per_process 限制。

- **ID:** `database/temp-file-limit-exceeded`
- **领域:** database
- **类别:** resource_error
- **错误码:** `53100`
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

PostgreSQL 已耗尽了临时文件目录中的磁盘空间或内核的文件描述符限制，导致无法为查询执行创建临时文件。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| PostgreSQL 12 | active | — | — |
| PostgreSQL 13 | active | — | — |
| PostgreSQL 14 | active | — | — |
| PostgreSQL 15 | active | — | — |
| PostgreSQL 16 | active | — | — |

## 解决方案

1. ```
   使用 `df -h` 和 `df -i` 检查包含 pg_stat_tmp 和 base 目录的分区磁盘使用情况。通过删除旧的 WAL 文件或归档日志来释放空间：`pg_archivecleanup /path/to/archive $(ls -t /path/to/archive | tail -1)`
   ```
2. ```
   向临时目录添加更多磁盘空间或挂载更大的卷。然后重启 PostgreSQL，或将 temp_tablespaces 设置为空间充足的卷上的表空间：`ALTER SYSTEM SET temp_tablespaces = 'fast_disk'; SELECT pg_reload_conf();`
   ```
3. ```
   如果问题是文件描述符限制，在 postgresql.conf 中增加 max_files_per_process 并重启：`ALTER SYSTEM SET max_files_per_process = 2000;` 然后重启服务器
   ```

## 无效尝试

- **Increase max_files_per_process in postgresql.conf without checking disk space** — The error is usually caused by full disk, not file descriptor limit; raising max_files_per_process won't free disk space (60% 失败率)
- **Delete random files from pg_tblspc thinking they are temporary** — pg_tblspc contains symbolic links to tablespaces; deleting them can corrupt the database (80% 失败率)
- **Restart PostgreSQL without clearing temp files** — Restarting doesn't reclaim disk space; the underlying issue of full disk or exhausted inodes remains (70% 失败率)
