> ## 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.

# 数据库

> 置备、监控和管理 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);     // shown once — store securely
console.log(created.certificate);  // shown once — store securely
```

| 字段        | 类型       | 说明                                  |
| --------- | -------- | ----------------------------------- |
| `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"}`);

    // Promote to the full status with .fetch()
    if (summary.running) {
        const full = await summary.fetch();
        console.log(full.usage);
    }
}
```

## 更新

`db.update(options)` 修改显示名称和/或内存分配。至少必须提供一个字段。

```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}
// Rotate the password — the new value is shown only once
const { password } = await db.credentials.reset("password");
console.log(`New password: ${password}`);

// Rotate the certificate — fetch the new one via .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();
```
