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

# Go SDK: managed databases

> Create, inspect, update, start, stop and delete managed databases, read their status and metrics, and manage their credentials with c.Databases.

`c.Databases` manages Square Cloud's managed databases (MongoDB, MySQL, PostgreSQL and Redis). Every method takes `ctx` first and, except `Create` and `StatusAll`, the database id next. To list your databases, use [`c.Account.Me`](/en/sdks/go/client#account): its `Databases` slice has every database the key can see.

Database hosting needs a Standard, Pro or Enterprise plan.

Each snippet below runs on its own inside this program: paste one at a time into `main` and run `goimports` (see [Running the examples](/en/sdks/go/client#running-the-examples)).

```go theme={"system"}
package main

import (
	"context"
	"os"

	"github.com/squarecloudofc/sdk-api-go/v3"
)

var (
	ctx        = context.Background()
	c          = squarecloud.New(os.Getenv("SQUARECLOUD_API_KEY"))
	databaseID = "abc123def456abc123def456"
)

func main() {
	// Paste one snippet here, then run goimports.
}
```

## Creating a database

```go theme={"system"}
db, err := c.Databases.Create(ctx, squarecloud.DatabaseCreate{
	Name:    "my-db",
	Type:    squarecloud.DatabasePostgres, // DatabaseMongo, DatabaseMySQL, DatabaseRedis, DatabasePostgres
	Version: "17",                         // a full version or a prefix
	Memory:  1024,                         // MB
})
if err != nil {
	log.Fatal(err)
}

fmt.Println(db.ID, db.ConnectionURL, db.Cluster)
fmt.Println(db.Password) // shown only here: save it
if db.Certificate != nil {
	fmt.Println(*db.Certificate) // base64 PEM (private key, then certificate)
}
```

| Field | Description |
| - | - |
| `Name` (`name`) | 1 to 32 characters |
| `Type` (`type`) | `DatabaseMongo`, `DatabaseMySQL`, `DatabaseRedis` or `DatabasePostgres` (`mongo`, `mysql`, `redis`, `postgres`) |
| `Version` (`version`) | A full version or a prefix such as `"8"` |
| `Memory` (`memory`) | MB, an `int`. At least 512 for Redis and 1024 for the others |

The result is a `DatabaseCreated` with `ID`, `Name`, `Memory`, `CPU` (`float64`), `Type`, `Password`, `Certificate` (`*string`, `nil` when the API sends none), `ConnectionURL` (`connection_url`) and `Cluster`. The password and certificate are only returned by `Create` (and by [`ResetCredentials`](#credentials)). Without a `ctx` deadline, the call waits at least 2 minutes before timing out.

| Status | Code | When |
| - | - | - |
| 400 | `INVALID_NAME` | The name is not 1 to 32 characters |
| 400 | `INVALID_DATABASE_TYPE`, `INVALID_DATABASE_VERSION` | Unknown type or unsupported version |
| 400 | `INVALID_MEMORY` | `memory` is not a whole number (a fraction or a string). `Memory` is an `int`, so the Go SDK never sends one |
| 400 | `INSUFFICIENT_MEMORY` | `Memory` is below the engine's minimum or exceeds the available memory |
| 400 | `CLUSTER_SELECTION_FAILED` | No cluster had enough capacity |
| 400 / 500 | `DATABASE_CREATION_FAILED` | Provisioning failed |
| 403 | `UPGRADE_REQUIRED` | The plan has no database hosting |
| 503 | `CLUSTER_MAINTENANCE_TRY_LATER` | Provisioning is paused for maintenance |

## Getting a database

```go theme={"system"}
db, err := c.Databases.Get(ctx, databaseID)
if err != nil {
	log.Fatal(err)
}

fmt.Println(db.ID, db.Name, db.Type, db.RAM, db.Port, db.Cluster, db.CreatedAt)
```

## Updating a database

`Update(ctx, databaseID, squarecloud.DatabaseUpdate{Name, RAM})` renames or resizes a database. Zero fields are not sent; set at least one (400 `NO_UPDATE_DATA` otherwise).

```go theme={"system"}
if err := c.Databases.Update(ctx, databaseID, squarecloud.DatabaseUpdate{Name: "orders", RAM: 2048}); err != nil {
	log.Fatal(err)
}
```

## Start and stop

```go theme={"system"}
if err := c.Databases.Start(ctx, databaseID); err != nil {
	log.Fatal(err)
}
if err := c.Databases.Stop(ctx, databaseID); err != nil {
	log.Fatal(err)
}
```

Like app lifecycle calls, without a `ctx` deadline they wait at least 2 minutes, and a refusal is **409** with a code and an empty message: `CONTAINER_ALREADY_STARTED`, `CONTAINER_ALREADY_STOPPED`, `CONTAINER_NOT_FOUND`, `CONTAINER_INSUFFICIENT_DISK_SPACE`, `CONTAINER_NETWORK_CONFLICT` or `ACTION_FAILED`. While a snapshot restore runs, they are 403 `RESTORE_IN_PROGRESS`.

## Status and metrics

`Status(ctx, databaseID)` returns formatted values; `StatusRaw(ctx, databaseID)` returns numbers. `StatusAll(ctx)` returns one summary per database. `Metrics(ctx, databaseID)` returns the last 24 hours, one point every 5 minutes, newest first.

```go theme={"system"}
status, err := c.Databases.Status(ctx, databaseID)
if err != nil {
	log.Fatal(err)
}
fmt.Println(status.Running, status.CPU, status.RAM) // true "0.5%" "120.4MB"

raw, err := c.Databases.StatusRaw(ctx, databaseID)
if err != nil {
	log.Fatal(err)
}
fmt.Println(raw.CPU, raw.RAM) // 0.5 120.4

items, err := c.Databases.StatusAll(ctx)
if err != nil {
	log.Fatal(err)
}
for _, it := range items {
	fmt.Println(it.ID, it.Running, it.CPU, it.RAM) // CPU and RAM only while running
}

points, err := c.Databases.Metrics(ctx, databaseID)
if err != nil {
	log.Fatal(err)
}
if len(points) > 0 {
	fmt.Println(points[0].Date, points[0].CPU, points[0].RAM)
}
```

The status fields are the same as [app status](/en/sdks/go/managing_application#status).

## Credentials

`Certificate(ctx, databaseID)` returns the TLS certificate as base64-encoded PEM. `ResetCredentials(ctx, databaseID, reset)` rotates the password (`squarecloud.ResetPassword`, returns the new one) or the certificate (`squarecloud.ResetCertificate`, returns `""`). The database must be running (400 `DATABASE_NOT_RUNNING`).

```go theme={"system"}
certificate, err := c.Databases.Certificate(ctx, databaseID)
if err != nil {
	log.Fatal(err)
}
pem, err := base64.StdEncoding.DecodeString(certificate)
if err != nil {
	log.Fatal(err)
}
if err := os.WriteFile("database.pem", pem, 0o600); err != nil {
	log.Fatal(err)
}
```

```go theme={"system"}
password, err := c.Databases.ResetCredentials(ctx, databaseID, squarecloud.ResetPassword)
if err != nil {
	log.Fatal(err)
}
fmt.Println(password) // the new password: save it

if _, err := c.Databases.ResetCredentials(ctx, databaseID, squarecloud.ResetCertificate); err != nil {
	log.Fatal(err)
}
```

## Deleting a database

```go theme={"system"}
if err := c.Databases.Delete(ctx, databaseID); err != nil {
	log.Fatal(err)
}
```

<Warning>
  Deletion is permanent. Take a [snapshot](/en/sdks/go/snapshots) first if you may need the data again.
</Warning>

## Snapshots

`c.Databases.Snapshots` has the same `List`, `Create` and `Restore` as apps. See [Snapshots](/en/sdks/go/snapshots).

## Next steps

<CardGroup cols={3}>
  <Card title="Workspaces" icon="users" href="/en/sdks/go/workspaces">
    Share apps with your team.
  </Card>

  <Card title="Database API reference" icon="code" href="/en/api-reference/endpoint/databases/create">
    The REST endpoints behind these methods.
  </Card>

  <Card title="Databases from the CLI" icon="terminal" href="/en/cli-reference/databases">
    The same actions from the terminal.
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.