# MySQL database

HelixIAM runs on MySQL 8.4 and 8.0 (8.0.19 or later) as well as on [PostgreSQL](database.md). The server, the console and the features
are the same; this page covers what is different on MySQL: the versions, the settings the database needs, the JDBC
driver you add, the lengths of identifiers, and backup. Everything else on the [PostgreSQL page](database.md)
(settings, migrations, the health group) applies as written, with `DB_VENDOR=mysql`.

## Supported versions

The server checks the database when it starts.

| MySQL | What the server does |
|---|---|
| 8.0.18 or older (5.7 too) | Refuses to start, naming the version and the minimum (8.0.19: HelixIAM needs the row alias of `INSERT … AS new`, from 8.0.19, and enforced `CHECK` constraints, from 8.0.16). |
| 8.0.19 and later 8.0 releases | Starts, with a warning: MySQL 8.0 is at the end of its vendor support. It is tested. |
| 8.4 (LTS) | Starts. Tested. |
| Any other version (8.1 to 8.3, 9.x) | Starts, with a warning that the version is untested. With `HELIX_DATABASE_VERSION_STRICT=true` it refuses to start instead. |

MariaDB, which answers MySQL's protocol, is not MySQL: the server refuses it with `DB_VENDOR=mysql`, naming both.

## What the database needs

Create an empty database and a user that owns it. The server creates and alters the tables when the migrations run, so
the user needs all privileges on that one database and none outside it.

```sql
CREATE DATABASE helixiam CHARACTER SET utf8mb4;
CREATE USER 'helixiam'@'%' IDENTIFIED BY '<password>';
GRANT ALL PRIVILEGES ON helixiam.* TO 'helixiam'@'%';
```

MySQL's own defaults are right; change nothing else. The server makes what it needs of every connection it opens, and
refuses to start (naming the setting) when the database or the connection is not as follows:

| Setting | What the server requires | Why |
|---|---|---|
| Database character set (`character_set_database`) | `utf8mb4` | All text is stored as `utf8mb4`. A database created with another character set is refused. |
| Collation of the tables | set by the schema | Every text column is `utf8mb4_0900_bin`: comparisons are byte for byte, as on PostgreSQL. A realm `Acme` and a realm `acme`, or the client ids `App` and `app`, are different. The server's default collation (`utf8mb4_0900_ai_ci`) is not used for any column. |
| Transaction isolation | `READ-COMMITTED` | Set on every connection by the server, whatever the server default (`REPEATABLE-READ`) is. |
| Session time zone | UTC (`+00:00`) | Set on every connection. Times are stored as `DATETIME(6)` in UTC, with microseconds; the time zone of the MySQL server and of the JVM do not change what is stored. |
| SQL mode | includes `STRICT_ALL_TABLES` | Set on every connection: a value that does not fit is an error, never silently cut. |
| `lower_case_table_names` | `0` on Linux | Table names are case-sensitive. macOS and Windows hosts, which fold them, are accepted for development. |
| Storage engine | InnoDB | The only one the schema declares. |

`sql_require_primary_key=ON` (required by some managed MySQL services and by Group Replication setups) works: every
table of the schema has a primary key.

MySQL runs DDL (`CREATE TABLE`, `ALTER TABLE`) outside transactions: each statement commits by itself. A migration that
fails part-way therefore leaves the statements before it applied, and Flyway records the migration as failed. On the
first start, the one that builds the schema on the empty database, drop and recreate the database (it holds nothing
yet) and start again after correcting the cause. For a later migration, restore the backup taken before the upgrade.
On PostgreSQL a failed migration is rolled back entirely.

## The JDBC driver

HelixIAM does not ship MySQL Connector/J: it is licensed under the GPL-2.0 with the FOSS exception, so you download it
and give it to the server. The server loads the one jar in its driver directory (`/opt/helix/drivers`) and only when
its SHA-256 is on the list of tested drivers. This release is tested with:

| | |
|---|---|
| Driver | MySQL Connector/J 9.7.0 (`mysql-connector-j-9.7.0.jar`) |
| SHA-256 | `0353648eaa1c91e0f4020c959abf756bc866ffd583df22ae6b6f6e0cbd43eb44` |
| Download | `https://repo1.maven.org/maven2/com/mysql/mysql-connector-j/9.7.0/mysql-connector-j-9.7.0.jar` |

Check the SHA-256 of the file you downloaded before you use it:

```bash
curl -fLO https://repo1.maven.org/maven2/com/mysql/mysql-connector-j/9.7.0/mysql-connector-j-9.7.0.jar
echo "0353648eaa1c91e0f4020c959abf756bc866ffd583df22ae6b6f6e0cbd43eb44  mysql-connector-j-9.7.0.jar" | sha256sum -c
```

A jar with another checksum is refused at start-up. The directory and the jar must be read-only for the server. All
the ways to give it to the server, with examples: [Your image: add the database driver](database-driver.md#7-mysql).

=== "Helm"

    Build your own image, the server image plus Connector/J, with the release's `mysql.Dockerfile` (your build
    downloads the jar and Docker checks its SHA-256), push it, and run it:

    ```bash
    docker build -f mysql.Dockerfile -t registry.example.com/acme/helixiam:v1.1.5-mysql .
    docker push registry.example.com/acme/helixiam:v1.1.5-mysql
    helm upgrade --install helixiam oci://registry.helixiam.com/helixiam/charts/helixiam --version 1.1.5 \
      --set image.repository=registry.example.com/acme/helixiam --set image.tag=v1.1.5-mysql \
      --set database.vendor=mysql --set database.port=3306 --set database.host=mysql.db.svc \
      ...
    ```

    Or put the jar, and nothing else, on a volume and mount it with `database.driver.volume` (a
    `persistentVolumeClaim`, `hostPath` or `csi` source; not a `configMap` or `secret`):
    `--set database.driver.volume.persistentVolumeClaim.claimName=helix-drivers`.

    With neither, the server refuses to start, naming the driver directory.

=== "One Linux server"

    Put the jar in the empty `drivers/` folder (exactly one jar, `0444`, the folder `0555`;
    [the steps](database-driver.md#6-linux-server-and-native-bundle)), and set in `.env`:

    ```bash
    DB_VENDOR=mysql
    COMPOSE_PROFILES=bundled-mysql   # the bundled MySQL 8.4; with your own MySQL, delete the line and set DB_HOST
    DB_HOST=mysql
    DB_PORT=3306
    ```

## Settings

The `DB_*` variables are the ones of the [PostgreSQL page](database.md#settings), with `DB_VENDOR=mysql` and `DB_PORT=3306`.
`DB_SSLMODE` takes the same words (`disable`, `prefer`, `require`, `verify-ca`, `verify-full`).

With `verify-ca` or `verify-full`, `DB_SSL_ROOT_CERT` is the path of the PEM file with the CA certificates that signed
the database's certificate (one or more `-----BEGIN CERTIFICATE-----` blocks), as on PostgreSQL. Those certificates
are then the only ones trusted for the database connection. MySQL Connector/J cannot read PEM itself: at start-up the
server copies the certificates into a PKCS#12 truststore in its temporary directory (`/tmp`, a directory and a file only
the server's user can open, deleted when it stops), so `/tmp` must be writable, as it is in the chart and the Compose
bundles. A `DB_SSL_ROOT_CERT` that cannot be read, or holds no X.509 certificate, stops the server at start-up, naming
the file; the connection never falls back to another truststore. With an empty `DB_SSL_ROOT_CERT`, `verify-ca` and
`verify-full` trust the JVM's truststore (the public CAs of the JDK), which fits a managed MySQL whose certificate is
signed by a public CA. With `disable`, `prefer` and `require`, `DB_SSL_ROOT_CERT` is not used: `require` encrypts the
connection but does not verify the certificate.

| `DB_SSLMODE` | MySQL Connector/J `sslMode` |
|---|---|
| `disable` | `DISABLED` |
| `prefer` | `PREFERRED` |
| `require` | `REQUIRED` |
| `verify-ca` | `VERIFY_CA` |
| `verify-full` | `VERIFY_IDENTITY` (the host name must match the certificate) |

## Lengths of identifiers

On both databases a realm id is at most 100 characters and an identity-provider alias at most 150 (letters, digits, `.`,
`_` and `-`, starting with a letter or digit). The limits come from MySQL's key size (an index key is at most 3072 bytes,
four per character) and are the same on PostgreSQL, so a realm or provider moves between the two without surprises. The
admin API answers 400 with a field error for a longer or other value; a provider configured in `helix.federation` with
another alias stops the server at start-up, naming the alias.

## Backup and restore

Use MySQL's own tools, or your managed database's snapshots and point-in-time recovery. A logical backup with a
consistent snapshot, without locking the tables:

```bash
mysqldump --host "$DB_HOST" --user "$DB_USERNAME" --password --single-transaction --routines --triggers \
  --no-tablespaces helixiam > helixiam.sql
mysql --host "$DB_HOST" --user "$DB_USERNAME" --password helixiam < helixiam.sql   # restore into an empty database
```

With the Linux server bundle: `docker compose exec -T mysql sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" mysqldump -u "$MYSQL_USER"
--single-transaction --routines --triggers --no-tablespaces "$MYSQL_DATABASE"' > helixiam.sql`. Keep `DB_ENCRYPTION`
with the backup, apart from it: without it the encrypted data cannot be read.

## Moving from PostgreSQL

Copying a database from PostgreSQL to MySQL is not supported. Start a MySQL installation empty and recreate realms
with the [realm export and import](backup.md), or start with MySQL from the beginning. A provider alias that does not
follow the alias grammar can exist on a PostgreSQL installation that is older than the rule; it cannot be created on MySQL.

## Known differences

- A token request, a code exchange or an authorization request on MySQL makes two more database round trips than on
  PostgreSQL (MySQL has no statement that writes two tables at once); each is a lookup by key.
