## Database

### 初始化

```python
from xll_kit.database.session_manager import init_session_manager

init_session_manager(database_uri)
```

## Session

### 事务

```python
from xll_kit.database.session_manager import get_session_manager

session_manager = get_session_manager()
with session_manager.session_scope() as session:
    user = User(name="parent")
    session.add(user)

    try:
        # ✅ 在同一个 session 上创建 SAVEPOINT
        with session.begin_nested():
            risky_user = User(name="risky")
            session.add(risky_user)
            raise Exception("Simulated error")
    except Exception:
        # 嵌套事务回滚，不影响父事务
        pass

    # 父事务继续 commit
```

```python

with session_manager.transaction() as session:
    user = self.user_crud.get_by_id(session, user_id)
    if not user:
        raise NotFound("user not found")

    self.user_crud.update_name(session, user, name)

with session_manager.transaction() as session:
    order = self.order_crud.create(session, order_data)

    for item in items:
        try:
            with self.session_manager.savepoint(session):
                self.item_crud.create(session, item)
        except Exception:
            logger.warning("单个 item 创建失败，跳过")

    return order
```

```python
# ✅ 正确：嵌套事务
from xll_kit.database.session_manager import get_session_manager

session_manager = get_session_manager()
with session_manager.session_scope() as session:
    user = User(name="Alice")
    session.add(user)
    session.flush()  # 获取 user.id

    # 尝试高风险操作
    try:
        with SessionManager.savepoint(session):
            payment = Payment(user_id=user.id, amount=100)
            session.add(payment)

            # 调用可能失败的外部 API
            if not external_payment_api.charge(payment):
                raise PaymentError("Payment failed")
    except PaymentError:
        # 支付失败，但用户仍然创建成功
        logger.warning(f"Payment failed for user {user.id}")

    # 用户数据依然会 commit
```