# 並行寫入

> 並行寫入（Concurrent Writes）— Turso 官方文件。
> Canonical HTML: https://tursodb.cn/zh-tw/docs/tursodb/concurrent-writes/
> Upstream Source (MIT): https://docs.turso.tech/tursodb/concurrent-writes
> Language: zh-TW

---
在預設設定下，Turso 同一時間僅允許一條連線進行寫入。啟用 MVCC（多版本並行控制，Multi-Version Concurrency Control）後，多條連線即可同時寫入。若兩筆交易修改了相同資料，其中一筆會收到衝突錯誤，並必須回復（Rollback）後重試。

## 啟用 MVCC

在您的資料庫連線上設定日誌模式（Journal Mode）：

```sql
PRAGMA journal_mode = 'mvcc';
```

## BEGIN CONCURRENT

使用 `BEGIN CONCURRENT` 取代 `BEGIN` 來開啟交易，讓其他寫入連線得以並行執行：

```sql
BEGIN CONCURRENT;
-- your writes here
COMMIT;
```

若兩筆交易修改了相同的資料列，其中一筆將收到衝突錯誤，並必須回復後重試。寫入互不重疊資料的交易則能無衝突地並行完成。

## 處理衝突

您的應用程式必須偵測衝突錯誤並重新嘗試執行該交易。

## 範例

<div class="doc-tabs" data-doc-tabs>
<div class="doc-tab-list" role="tablist">
<button type="button" role="tab" class="doc-tab-btn is-active" aria-selected="true" data-tab-idx="0">Rust</button>
<button type="button" role="tab" class="doc-tab-btn" aria-selected="false" data-tab-idx="1">JavaScript</button>
<button type="button" role="tab" class="doc-tab-btn" aria-selected="false" data-tab-idx="2">Python</button>
</div>
<div class="doc-tab-panel is-active" role="tabpanel" data-tab-panel="0">

```rust
fn is_retryable(e: &Error) -> bool {
    matches!(e, Error::Busy(_) | Error::BusySnapshot(_))
        || matches!(e, Error::Error(msg) if msg.contains("conflict"))
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    let tmp = NamedTempFile::new().expect("failed to create temp file");
    let db = Builder::new_local(tmp.path().to_str().unwrap())
        .build()
        .await?;

    let conn = db.connect()?;
    conn.pragma_update("journal_mode", "'mvcc'").await?;
    conn.execute("CREATE TABLE hits (val INTEGER)", ()).await?;

    let mut handles = Vec::new();
    for _ in 0..16 {
        let db = db.clone();
        handles.push(tokio::spawn(async move {
            let val = rand::rng().random_range(1..=100);
            let conn = db.connect()?;
            loop {
                conn.execute("BEGIN CONCURRENT", ()).await?;
                let result = conn
                    .execute(&format!("INSERT INTO hits VALUES ({val})"), ())
                    .await
                    .and(conn.execute("COMMIT", ()).await);
                match result {
                    Ok(_) => return Ok::<_, Error>(val),
                    Err(ref e) if is_retryable(e) => {
                        let _ = conn.execute("ROLLBACK", ()).await;
                        tokio::task::yield_now().await;
                    }
                    Err(e) => {
                        let _ = conn.execute("ROLLBACK", ()).await;
                        return Err(e);
                    }
                }
            }
        }));
    }

    for handle in handles {
        handle.await.expect("task panicked")?;
    }

    Ok(())
}
```

</div>
<div class="doc-tab-panel" role="tabpanel" data-tab-panel="1" hidden>

```js
const DB_PATH = join(mkdtempSync(join(tmpdir(), "turso-mvcc-")), "hits.db");

function isRetryable(err) {
  const msg = (err?.message ?? "").toLowerCase();
  return msg.includes("conflict") || msg.includes("busy");
}

async function writeWorker() {
  const val = Math.floor(Math.random() * 100) + 1;
  const db = await connect(DB_PATH);
  try {
    await db.exec("PRAGMA journal_mode = 'mvcc'");
    while (true) {
      await db.exec("BEGIN CONCURRENT");
      try {
        await db.exec(`INSERT INTO hits VALUES (${val})`);
        await db.exec("COMMIT");
        return val;
      } catch (err) {
        try { await db.exec("ROLLBACK"); } catch (_) {}
        if (!isRetryable(err)) throw err;
        await new Promise((r) => setImmediate(r));
      }
    }
  } finally {
    await db.close();
  }
}

const setup = await connect(DB_PATH);
await setup.exec("PRAGMA journal_mode = 'mvcc'");
await setup.exec("CREATE TABLE hits (val INTEGER)");
await setup.close();

await Promise.all(Array.from({ length: 16 }, () => writeWorker()));
```

</div>
<div class="doc-tab-panel" role="tabpanel" data-tab-panel="2" hidden>

```python
def is_retryable(e: Exception) -> bool:
    msg = str(e).lower()
    return "conflict" in msg or "busy" in msg

def write_worker(db_path: str) -> int:
    val = random.randint(1, 100)
    conn = turso.connect(db_path)
    try:
        conn.execute("PRAGMA journal_mode = 'mvcc'").fetchone()
        while True:
            conn.execute("BEGIN CONCURRENT")
            try:
                conn.execute("INSERT INTO hits VALUES (?)", (val,))
                conn.execute("COMMIT")
                return val
            except Exception as e:
                try:
                    conn.execute("ROLLBACK")
                except Exception:
                    pass
                if not is_retryable(e):
                    raise
    finally:
        conn.close()

async def main() -> None:
    with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as tmp:
        db_path = tmp.name

    setup = turso.connect(db_path)
    setup.execute("PRAGMA journal_mode = 'mvcc'").fetchone()
    setup.execute("CREATE TABLE hits (val INTEGER)")
    setup.commit()
    setup.close()

    tasks = [asyncio.to_thread(write_worker, db_path) for _ in range(16)]
    await asyncio.gather(*tasks)

asyncio.run(main())
```

</div>
</div>


試試完整範例：
[Rust](https://github.com/tursodatabase/turso/blob/main/bindings/rust/examples/concurrent_writes.rs) · [JavaScript](https://github.com/tursodatabase/turso/blob/main/examples/javascript/concurrent-writes/index.mjs) · [Python](https://github.com/tursodatabase/turso/blob/main/examples/python/concurrent_writes.py)
