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

# 管理数据库

> 在本节中，你将学习如何使用 Python SDK 管理数据库。为你的应用创建、检索、更新、删除和监控数据库。

[Client]: client

数据库是 Square Cloud 提供的托管服务，让你能够为应用存储和管理数据。支持的数据库包括 Redis、MongoDB、MySQL 和 PostgreSQL。

## 创建数据库

`client.create_database` 返回一个 `Database` 对象。

```python theme={null}
import squarecloud as square

client = square.Client(api_key='API_KEY')

async def example():
    # Create a MongoDB database with 1024MB of memory
    database = await client.create_database(
        name='my_database',
        memory=1024,  # Memory in MB
        type='mongo',  # "redis", "mongo", "mysql", or "postgres"
        version='8.0.11'  # Optional - version will be inferred if not provided
    )
    
    print(database.id)               # Database identifier
    print(database.name)             # Database name
    print(database.type)             # Database type
    print(database.cluster)          # Database cluster
    print(database.memory)           # Memory allocated (MB)
    print(database.cpu)              # CPU allocated
    print(database.password)         # Database password
    print(database.connection_url)   # Connection URL
    print(database.certificate)      # TLS certificate
```

## 检索数据库信息

`client.get_database_info` 返回一个 `DatabaseInfo` 对象。

```python theme={null}
import squarecloud as square

client = square.Client(api_key='API_KEY')

async def example():
    database_info = await client.get_database_info(database_id='DATABASE_ID')
    
    print(database_info.id)            # Database identifier
    print(database_info.name)          # Database name
    print(database_info.type)          # Database type
    print(database_info.owner)         # Database owner user ID
    print(database_info.cluster)       # Database cluster
    print(database_info.ram)           # RAM usage in MB
    print(database_info.port)          # Database port
    print(database_info.created_at)    # Creation date (ISO 8601)
    print(database_info.created_at_datetime)  # Creation date as datetime object
```

## 获取数据库状态

`client.get_database_status` 返回一个 `StatusData` 对象。

```python theme={null}
import squarecloud as square

client = square.Client(api_key='API_KEY')

async def example():
    status = await client.get_database_status(database_id='DATABASE_ID')
    
    print(status.ram)      # RAM usage
    print(status.cpu)      # CPU usage percentage
    print(status.network)  # Network statistics
    print(status.running)  # Whether database is running
    print(status.storage)  # Storage usage
```

## 列出所有数据库

`client.all_databases_status` 返回一个 `ResumedStatus` 对象列表。

```python theme={null}
import squarecloud as square

client = square.Client(api_key='API_KEY')

async def example():
    all_databases = await client.all_databases_status()
    
    for database in all_databases:
        print(f"Database: {database.id}")
        print(f"  CPU: {database.cpu}")
        print(f"  RAM: {database.ram}")
        print(f"  Running: {database.running}")
```

## 启动数据库

`client.start_database` 返回一个 `Response` 对象。

```python theme={null}
import squarecloud as square

client = square.Client(api_key='API_KEY')

async def example():
    response = await client.start_database(database_id='DATABASE_ID')
    print(f"Database started: {response.status}")
```

## 停止数据库

`client.stop_database` 返回一个 `Response` 对象。

```python theme={null}
import squarecloud as square

client = square.Client(api_key='API_KEY')

async def example():
    response = await client.stop_database(database_id='DATABASE_ID')
    print(f"Database stopped: {response.status}")
```

## 编辑数据库

`client.edit_database` 返回一个 `Response` 对象。你可以更新数据库名称和/或内存分配。

```python theme={null}
import squarecloud as square

client = square.Client(api_key='API_KEY')

async def example():
    # Update database name
    response = await client.edit_database(
        database_id='DATABASE_ID',
        name='new_database_name'
    )
    
    # Update memory allocation
    response = await client.edit_database(
        database_id='DATABASE_ID',
        memory=2048  # New memory in MB
    )
    
    # Update both name and memory
    response = await client.edit_database(
        database_id='DATABASE_ID',
        name='new_name',
        memory=2048
    )
    
    print(f"Database updated: {response.status}")
```

## 删除数据库

`client.delete_database` 返回一个 `Response` 对象。

```python theme={null}
import squarecloud as square

client = square.Client(api_key='API_KEY')

async def example():
    response = await client.delete_database(database_id='DATABASE_ID')
    print(f"Database deleted: {response.status}")
```

## 管理数据库凭据

### 获取数据库证书

`client.get_database_certificate` 返回一个 `Certificate` 对象。

```python theme={null}
import squarecloud as square

client = square.Client(api_key='API_KEY')

async def example():
    certificate = await client.get_database_certificate(database_id='DATABASE_ID')
    
    # Save certificate to file
    certificate.save()  # Saves as 'certificate.pem' by default
    
    # Save certificate with custom filename
    certificate.save(filename='my_cert', export_to='cert')
    
    # Save certificate to specific directory
    certificate.save(dir='./certs', filename='my_cert', export_to='cert')
```

### 重置数据库密码

`client.reset_database_password` 返回一个新的密码字符串。

```python theme={null}
import squarecloud as square

client = square.Client(api_key='API_KEY')

async def example():
    new_password = await client.reset_database_password(database_id='DATABASE_ID')
    print(f"New password: {new_password}")
```

### 重置数据库证书

`client.reset_database_certificate` 返回一个 `Response` 对象。

```python theme={null}
import squarecloud as square

client = square.Client(api_key='API_KEY')

async def example():
    response = await client.reset_database_certificate(database_id='DATABASE_ID')
    print(f"Certificate reset: {response.status}")
```

## 数据库数据结构

### Database

`Database` 对象表示一个包含完整详情的新创建的数据库：

| Property         | Type          | Description                       |
| ---------------- | ------------- | --------------------------------- |
| `id`             | `str`         | 数据库唯一标识符                          |
| `name`           | `str`         | 数据库名称                             |
| `type`           | `str`         | 数据库类型（redis、mongo、mysql、postgres） |
| `cluster`        | `str`         | 数据库 cluster 信息                    |
| `memory`         | `int`         | 分配的内存（MB）                         |
| `cpu`            | `int`         | 分配的 CPU（vCPU）                     |
| `password`       | `str`         | 数据库密码                             |
| `certificate`    | `Certificate` | 用于安全连接的 TLS 证书                    |
| `connection_url` | `str`         | 数据库的连接 URL                        |

### DatabaseInfo

`DatabaseInfo` 对象包含关于一个现有数据库的信息：

| Property     | Type  | Description                       |
| ------------ | ----- | --------------------------------- |
| `id`         | `str` | 数据库唯一标识符                          |
| `name`       | `str` | 数据库名称                             |
| `type`       | `str` | 数据库类型（redis、mongo、mysql、postgres） |
| `cluster`    | `str` | 数据库 cluster 信息                    |
| `owner`      | `str` | 数据库所有者的用户 ID                      |
| `port`       | `int` | 数据库端口                             |
| `ram`        | `int` | 当前 RAM 使用量（MB）                    |
| `created_at` | `str` | 创建时间戳（ISO 8601）                   |

### StatusData

`StatusData` 对象包含关于一个数据库的实时状态信息：

| Property  | Type   | Description   |
| --------- | ------ | ------------- |
| `ram`     | `str`  | 当前 RAM 使用量    |
| `cpu`     | `str`  | 当前 CPU 使用百分比  |
| `network` | `dict` | 网络统计信息（上传/下载） |
| `running` | `bool` | 数据库是否正在运行     |
| `storage` | `str`  | 存储使用量         |

## 支持的数据库类型

Square Cloud 支持以下数据库：

| Type       | Default Version | Description      |
| ---------- | --------------- | ---------------- |
| `redis`    | 7.4.5           | 用于缓存和实时应用的内存数据存储 |
| `mongo`    | 8.0.11          | NoSQL 文档数据库      |
| `mysql`    | 9.5             | 关系型数据库           |
| `postgres` | 17.6            | 高级关系型数据库         |
