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

# Gestione dei Database

> In questa sezione imparerai a gestire i database usando l'SDK Python. Crea, recupera, aggiorna, elimina e monitora i database per le tue applicazioni.

[Client]: client

I database sono servizi gestiti forniti da Square Cloud che ti permettono di memorizzare e gestire i dati delle tue applicazioni. I database supportati includono Redis, MongoDB, MySQL e PostgreSQL.

## Creare un database

`client.create_database` restituisce un oggetto `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
```

## Recuperare le informazioni di un database

`client.get_database_info` restituisce un oggetto `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
```

## Ottenere lo stato di un database

`client.get_database_status` restituisce un oggetto `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
```

## Elencare tutti i database

`client.all_databases_status` restituisce una lista di oggetti `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}")
```

## Avviare un database

`client.start_database` restituisce un oggetto `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}")
```

## Arrestare un database

`client.stop_database` restituisce un oggetto `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}")
```

## Modificare un database

`client.edit_database` restituisce un oggetto `Response`. Puoi aggiornare il nome del database e/o l'allocazione di memoria.

```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}")
```

## Eliminare un database

`client.delete_database` restituisce un oggetto `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}")
```

## Gestire le credenziali del database

### Ottenere il certificato del database

`client.get_database_certificate` restituisce un oggetto `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')
```

### Reimpostare la password del database

`client.reset_database_password` restituisce una nuova stringa 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}")
```

### Reimpostare il certificato del database

`client.reset_database_certificate` restituisce un oggetto `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}")
```

## Strutture dati del database

### Database

L'oggetto `Database` rappresenta un database appena creato con tutti i dettagli:

| Proprietà        | Tipo          | Descrizione                                      |
| ---------------- | ------------- | ------------------------------------------------ |
| `id`             | `str`         | Identificatore univoco del database              |
| `name`           | `str`         | Nome del database                                |
| `type`           | `str`         | Tipo di database (redis, mongo, mysql, postgres) |
| `cluster`        | `str`         | Informazioni sul cluster del database            |
| `memory`         | `int`         | Memoria allocata (MB)                            |
| `cpu`            | `int`         | CPU allocata (vCPU)                              |
| `password`       | `str`         | Password del database                            |
| `certificate`    | `Certificate` | Certificato TLS per la connessione sicura        |
| `connection_url` | `str`         | URL di connessione al database                   |

### DatabaseInfo

L'oggetto `DatabaseInfo` contiene informazioni su un database esistente:

| Proprietà    | Tipo  | Descrizione                                      |
| ------------ | ----- | ------------------------------------------------ |
| `id`         | `str` | Identificatore univoco del database              |
| `name`       | `str` | Nome del database                                |
| `type`       | `str` | Tipo di database (redis, mongo, mysql, postgres) |
| `cluster`    | `str` | Informazioni sul cluster del database            |
| `owner`      | `str` | ID utente del proprietario del database          |
| `port`       | `int` | Porta del database                               |
| `ram`        | `int` | Utilizzo corrente della RAM (MB)                 |
| `created_at` | `str` | Timestamp di creazione (ISO 8601)                |

### StatusData

L'oggetto `StatusData` contiene informazioni di stato in tempo reale su un database:

| Proprietà | Tipo   | Descrizione                                |
| --------- | ------ | ------------------------------------------ |
| `ram`     | `str`  | Utilizzo corrente della RAM                |
| `cpu`     | `str`  | Percentuale di utilizzo corrente della CPU |
| `network` | `dict` | Statistiche di rete (upload/download)      |
| `running` | `bool` | Indica se il database è in esecuzione      |
| `storage` | `str`  | Utilizzo dello storage                     |

## Tipi di database supportati

Square Cloud supporta i seguenti database:

| Tipo       | Versione predefinita | Descrizione                                                     |
| ---------- | -------------------- | --------------------------------------------------------------- |
| `redis`    | 7.4.5                | Data store in memoria per caching e applicazioni in tempo reale |
| `mongo`    | 8.0.11               | Database documentale NoSQL                                      |
| `mysql`    | 9.5                  | Database relazionale                                            |
| `postgres` | 17.6                 | Database relazionale avanzato                                   |
