> ## Documentation Index
> Fetch the complete documentation index at: https://docs.squarecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Databases

> Square Cloud のデータベースをプロビジョニング、監視、管理します。認証情報のローテーションや snapshot も含みます。

<Info>
  データベースは `api.databases` モジュールによって公開されます。これは v4 で追加されました。**Standard、Pro、Enterprise** プランで利用できます。
</Info>

## データベースの作成

`api.databases.create(options)` は新しいデータベースをプロビジョニングします。`password` と `certificate` は **作成時にのみ** 返されます。今すぐ保存してください。

```typescript theme={null}
const created = await api.databases.create({
    name: "my-mongo",
    memory: 512,
    type: "mongo",
    version: "7.0",
});

console.log(created.id);
console.log(created.connection_url);
console.log(created.password);     // 一度だけ表示される — 安全に保存すること
console.log(created.certificate);  // 一度だけ表示される — 安全に保存すること
```

| Field     | Type     | Description                              |
| --------- | -------- | ---------------------------------------- |
| `name`    | `string` | 表示名                                      |
| `memory`  | `number` | 割り当てるメモリ (MB)                            |
| `type`    | `string` | エンジンスラッグ (例: `mongo`、`postgres`、`mysql`) |
| `version` | `string` | エンジンバージョン (例: `"7.0"`)                   |

## データベースの一覧取得

`api.user.get()` は、あなたが所有するすべてのデータベースの `Collection` を `user.databases` に設定します:

```typescript theme={null}
const user = await api.user.get();

for (const [id, db] of user.databases) {
    console.log(`${db.name} (${id}) — ${db.type} ${db.ram}MB`);
}
```

## 単一のデータベースの取得

```typescript theme={null}
const db = await api.databases.fetch(created.id);

console.log(db.id);
console.log(db.name);
console.log(db.owner);
console.log(db.type);
console.log(db.ram);
console.log(db.cluster);
console.log(db.port);
console.log(db.createdAt);
```

## ライフサイクル

```typescript theme={null}
await db.start();
await db.stop();
```

## ステータスとメトリクス

```typescript theme={null}
const status = await db.getStatus();
console.log(`${status.status} • CPU ${status.usage.cpu} • RAM ${status.usage.ram}`);

const metrics = await db.getMetrics();
console.log(`${metrics.length} metric points (up to 288 over 24h)`);
```

### すべてのデータベースの概要ステータス

```typescript theme={null}
const all = await api.databases.statusAll();

for (const summary of all) {
    console.log(`${summary.databaseId} → ${summary.running ? "running" : "stopped"}`);

    // .fetch() で完全なステータスに昇格させる
    if (summary.running) {
        const full = await summary.fetch();
        console.log(full.usage);
    }
}
```

## 更新

`db.update(options)` は表示名やメモリ割り当てを変更します。少なくとも 1 つのフィールドを指定する必要があります。

```typescript theme={null}
await db.update({ name: "primary-db", ram: 1024 });
```

## 認証情報

`db.credentials.certificate()` は TLS 証明書（base64 エンコードされた PEM）を返します:

```typescript theme={null}
const cert = await db.credentials.certificate();
console.log(`Certificate length: ${cert.length}`);
```

`db.credentials.reset(type)` は、パスワードまたは証明書のいずれかをローテーションします。

```typescript theme={null}
// パスワードをローテーションする — 新しい値は一度だけ表示される
const { password } = await db.credentials.reset("password");
console.log(`New password: ${password}`);

// 証明書をローテーションする — 新しいものは .certificate() で取得する
await db.credentials.reset("certificate");
const newCert = await db.credentials.certificate();
```

<Warning>
  `db.credentials.certificate()` と `db.credentials.reset()` は、データベースが **稼働中** であることを必要とします。
</Warning>

## Snapshots

`db.snapshots` は、アプリケーションの snapshot API をミラーリングします。

```typescript theme={null}
import { writeFile } from "node:fs/promises";

const snapshots = await db.snapshots.list();
console.log(`${snapshots.length} snapshots stored`);

const fresh = await db.snapshots.create();
console.log(`Download URL: ${fresh.url}`);

const buffer = await db.snapshots.download();
await writeFile("./db-backup.tar.gz", buffer);

await db.snapshots.restore(
    "00000000-0000-4000-8000-000000000000_mongo",
    "v1",
);
```

<Note>
  `app.snapshots.restore({ snapshotId, versionId })` とは異なり、`db.snapshots.restore(snapshotId, versionId)` は位置引数を取ります。
</Note>

## データベースの削除

<Warning>
  データベースの削除は取り消せません。データを復元する必要があるかもしれない場合は、最新の snapshot があることを確認してください。
</Warning>

```typescript theme={null}
await db.delete();
```
