# sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) 数据库已锁定

- **ID:** `python/pytest-parallel-db-fixture-conflict`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

多个 pytest-xdist worker 共享同一个 SQLite 文件；并发写入导致锁竞争和 OperationalError。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 7.x | active | — | — |
| 8.x | active | — | — |

## 解决方案

1. **** (95% 成功率)
   ```
   @pytest.fixture(scope='session')
def db_url(tmp_path_factory, worker_id):
    if worker_id == 'master':
        path = tmp_path_factory.mktemp('db') / 'test.db'
    else:
        path = tmp_path_factory.mktemp(f'db_{worker_id}') / 'test.db'
    return f'sqlite:///{path}'
   ```
2. **** (92% 成功率)
   ```
   # docker-compose.yml provides postgres
# conftest.py
@pytest.fixture(scope='session')
def db_url(worker_id):
    return f'postgresql://test:test@localhost/test_{worker_id}'
   ```

## 无效尝试

- **** — Reduces frequency but not correctness; long-running transactions still deadlock and CI slows down. (70% 失败率)
- **** — Defeats the purpose of parallel tests; CI time returns to serial levels. (90% 失败率)
- **** — WAL helps readers but writers still serialize; contention remains under heavy xdist load. (75% 失败率)
