> ## 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` オブジェクトは、新しく作成されたデータベースの完全な詳細を表します。

| プロパティ            | 型             | 説明                                        |
| ---------------- | ------------- | ----------------------------------------- |
| `id`             | `str`         | データベースの一意な識別子                             |
| `name`           | `str`         | データベース名                                   |
| `type`           | `str`         | データベースタイプ (redis, mongo, mysql, postgres) |
| `cluster`        | `str`         | データベースクラスタ情報                              |
| `memory`         | `int`         | 割り当てられたメモリ (MB)                           |
| `cpu`            | `int`         | 割り当てられた CPU (vCPU)                        |
| `password`       | `str`         | データベースパスワード                               |
| `certificate`    | `Certificate` | セキュア接続用の TLS 証明書                          |
| `connection_url` | `str`         | データベースの接続 URL                             |

### DatabaseInfo

`DatabaseInfo` オブジェクトは、既存のデータベースに関する情報を含みます。

| プロパティ        | 型     | 説明                                        |
| ------------ | ----- | ----------------------------------------- |
| `id`         | `str` | データベースの一意な識別子                             |
| `name`       | `str` | データベース名                                   |
| `type`       | `str` | データベースタイプ (redis, mongo, mysql, postgres) |
| `cluster`    | `str` | データベースクラスタ情報                              |
| `owner`      | `str` | データベース所有者のユーザー ID                         |
| `port`       | `int` | データベースポート                                 |
| `ram`        | `int` | 現在の RAM 使用量 (MB)                          |
| `created_at` | `str` | 作成タイムスタンプ (ISO 8601)                      |

### StatusData

`StatusData` オブジェクトは、データベースに関するリアルタイムのステータス情報を含みます。

| プロパティ     | 型      | 説明                       |
| --------- | ------ | ------------------------ |
| `ram`     | `str`  | 現在の RAM 使用量              |
| `cpu`     | `str`  | 現在の CPU 使用率              |
| `network` | `dict` | ネットワーク統計 (アップロード/ダウンロード) |
| `running` | `bool` | データベースが稼働中かどうか           |
| `storage` | `str`  | ストレージ使用量                 |

## サポートされているデータベースタイプ

Square Cloud は以下のデータベースをサポートしています。

| タイプ        | デフォルトバージョン | 説明                                 |
| ---------- | ---------- | ---------------------------------- |
| `redis`    | 7.4.5      | キャッシュやリアルタイムアプリケーション向けのインメモリデータストア |
| `mongo`    | 8.0.11     | NoSQL ドキュメントデータベース                 |
| `mysql`    | 9.5        | リレーショナルデータベース                      |
| `postgres` | 17.6       | 高度なリレーショナルデータベース                   |
