---
title: MySQL
description: "Run your Models on MySQL 8.4 or later, or MariaDB 10.11 or later, through Hyperdrive in a Worker, or through mysql2 on Node and Bun."
seo:
  description: "Use Arbor on MySQL or MariaDB: install mysql2, connect through Hyperdrive, a connection string or a Pool, and what works differently from D1, from returned rows to text."
---

## Installing

The MySQL adapter comes with `@forestfuture/arbor`, as its `/mysql` entry. Install the library with `mysql2`, version 3.13 or later:

```sh
npm install @forestfuture/arbor mysql2
```

Then name your database in [`arbor.jsonc`](/command-line#declaring-your-databases), with `npx arbor init --adapter mysql`.

It needs MySQL 8.4 or later, or MariaDB 10.11 or later. Arbor is tested on MySQL 8.4 and 9.7, and on MariaDB 10.11 and 12.3. Run your server in UTC with its default strict `sql_mode`, so a value a column can’t hold is refused rather than changed.

A Worker on MySQL needs `"compatibility_flags": ["nodejs_compat"]` in its Wrangler config, for `mysql2`.

Your Models, queries, and callbacks work the same on MySQL. The sections after [Connecting](#connecting) are the places MySQL works differently from D1. [MariaDB](#mariadb) says where MariaDB works differently from MySQL.

## Connecting

Your schema names a binding with `adapter: mysql({ binding: "DATABASE_URL" })`. On Node and Bun, the binding is the environment variable of that name, holding a connection string such as `mysql://app@localhost:3306/app_development`. With it set, `User.find(id)` works with nothing to set up. The first query opens a pool from the connection string, and every later query uses it. If the variable isn’t set, a query throws `NoDatabase` naming it.

:::tip
The pool never keeps your process running, so a script exits when its work is done.
:::

`connect` takes a connection string or a mysql2 Pool. To choose the pool’s settings, pass your own Pool, which your app ends when it shuts down:

```ts
import { createPool } from "mysql2/promise";
import { withDatabase } from "@forestfuture/arbor";
import { connect } from "@forestfuture/arbor/mysql";

const pool = createPool({ uri: process.env.DATABASE_URL, connectionLimit: 20 });
const db = connect(pool);
await withDatabase(db, () => runTests());
```

Inside `withDatabase`, a Database serves your Models when it reaches the database the variable names: the same user, host, port, and database. A Pool built from the variable’s connection string serves, and so does one built from the same settings. One on another database doesn’t, and the binding’s own pool serves instead.

## Connecting through Hyperdrive

In a Worker, reach MySQL through a Hyperdrive binding. `connect` takes it. Open the request’s database from it:

```ts
import { withDatabase } from "@forestfuture/arbor";
import { connect } from "@forestfuture/arbor/mysql";

export default {
  fetch(request, env) {
    const db = connect(env.HYPERDRIVE);
    return withDatabase(db, () => app.fetch(request, env));
  },
};
```

The first query inside `withDatabase` opens a connection, and the rest of the request shares it. It closes when `withDatabase` finishes. Without `withDatabase`, each query opens a connection of its own and closes it when it’s done.

Your schema names the binding with `adapter: mysql({ binding: "HYPERDRIVE" })`, so `User.find(id)` works in a Worker with nothing to set up.

A Pool you pass to `connect` in a Worker needs `disableEval: true`, since Workers refuse code made from strings.

:::warning[Hyperdrive caches reads]
Hyperdrive caches the results of reads, and a write doesn’t clear them. A read soon after a write can return the rows as they were before it. To turn caching off, run `npx wrangler hyperdrive update <id> --caching-disabled`.
:::

:::note
Hyperdrive lists MySQL up to 8.x, so Arbor is tested through Hyperdrive on MySQL 8.4. It tests MySQL 9.7 on Node only.
:::

## Running on Bun

The same entry runs on Bun through `mysql2`, as on Node. Your binding is the environment variable, and the pool never keeps your process running. Arbor is tested on Bun with MySQL 8.4.

## Batches are transactions

A [batch](/batches#batching-writes) is written whole or not at all, as on D1. On MySQL its writes run between `START TRANSACTION` and `COMMIT`, on a connection of its own. A query your request sends while the batch runs stays outside the transaction, so a failed batch never rolls it back. A [locked](/optimistic-locking) write that changes no row rolls the batch back before it commits, and throws `StaleRecord`.

A deadlock fails the batch with MySQL’s own error, and isn’t tried again.

## Rows a write returns

MySQL has no `RETURNING`. Your Models read a written row back by its key, in the write’s transaction, so `create` and `save` see the defaults MySQL filled in, as on D1. A row is read back by the key it gives, or by the key MySQL generated for it. `onQuery` hears the write alone, and its `meta.insertId` holds a generated key.

A bulk insert whose keys MySQL generates can’t be read back, since MySQL doesn’t promise its keys are consecutive. It resolves to no rows when you leave `returning` out, and throws a `TypeError` when you give one:

```ts
const { rows } = await User.insertAll([
  { email: "jane@example.com" },
  { email: "sam@example.com" },
]);
// rows: []
```

Give each row its key to have its rows returned. An upsert whose rows don’t give their keys throws a `TypeError` when you give `returning`, for the same reason.

## Upserts match any unique index

MySQL’s `ON DUPLICATE KEY UPDATE` updates the row that any unique index finds, and can’t name the index to match on. An upsert matches on all of them, so `uniqueBy` other than the primary key throws a `TypeError`. Skipping a duplicate leaves the row as it was, and never hides another error, as `INSERT IGNORE` would.

An upsert’s `rowsAffected` is MySQL’s: a row it inserted counts once, a row it updated twice, and a clashing row it left as it was once. Rows it left as they were are also returned.

## Text compares in the column’s collation

MySQL compares text by the column’s collation. The default collation is `utf8mb4_0900_ai_ci`, which ignores case and accents, so `User.where({ name: "jane" })` also finds `"Jane"` and `"Jané"`, and a unique index refuses both. It also sorts capitals and lowercase letters together, where D1 sorts every capital first. To compare a column’s text exactly, give it a binary collation such as `utf8mb4_0900_bin`.

That collation also ignores the NUL character (`\u0000`), so text that differs only by one compares equal.

## Times are UTC

A `datetime` attribute is stored in a `DATETIME` column as UTC, with no zone, and read back as UTC. `onQuery` shows it as ISO text. A `DATETIME` holds the years 1000 to 9999, so a time outside them fails with MySQL’s own error.

## Large integers

A `BIGINT` column reads as a number. A value past `Number.MAX_SAFE_INTEGER` throws a `TypeError` naming its attribute, rather than reading as a number that’s slightly wrong. For exact numbers of any size, use a `DECIMAL` column and a [`decimal`](/attribute-types#storing-exact-numbers-days-and-times) attribute.

Sequence keys and counters never get near that limit. Ids made elsewhere can pass it, such as snowflake ids or ids from another service. To check a database before you use Arbor with it, run this in the `mysql` client, connected to that database:

```sql
SET SESSION group_concat_max_len = 1000000;
SELECT COALESCE(GROUP_CONCAT(
  CONCAT(
    'SELECT ', QUOTE(CONCAT(TABLE_NAME, '.', COLUMN_NAME)), ' AS `column` FROM `',
    REPLACE(TABLE_NAME, '`', '``'), '` HAVING MAX(`', REPLACE(COLUMN_NAME, '`', '``'),
    '`) > 9007199254740991 OR MIN(`', REPLACE(COLUMN_NAME, '`', '``'), '`) < -9007199254740991')
  SEPARATOR ' UNION ALL '), 'SELECT NULL AS `column` FROM DUAL WHERE FALSE')
INTO @checks
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND DATA_TYPE = 'bigint';
PREPARE checks FROM @checks;
EXECUTE checks;
DEALLOCATE PREPARE checks;
```

It lists each `BIGINT` column that holds a value Arbor can’t read. It can read every row of those tables, so run it on a replica or at a quiet time.

Keep such ids in a `VARCHAR(64) COLLATE utf8mb4_bin` column, rather than `DECIMAL`. It reads as a `string` attribute, which keeps every digit, writes to JSON without loss, and links to text, integer, or uuid keys in other tables. The binary collation compares ids exactly. Assign and look up each id as text, such as `"1234567890123456789"`.

To change a column and the foreign keys that reference it, drop each constraint first, then add it back:

```sql
ALTER TABLE events DROP FOREIGN KEY fk_events_account_id;
ALTER TABLE accounts MODIFY id VARCHAR(64) COLLATE utf8mb4_bin NOT NULL;
ALTER TABLE events MODIFY account_id VARCHAR(64) COLLATE utf8mb4_bin;
ALTER TABLE events ADD CONSTRAINT fk_events_account_id
  FOREIGN KEY (account_id) REFERENCES accounts (id);
```

Run `SHOW CREATE TABLE` on each referencing table to find its constraints’ names. `MODIFY` replaces the column’s whole definition, so repeat `NOT NULL` and any default it needs.

In the generated schema, a `VARCHAR` key gets `generateId: true`, so a record built without an id gets a random UUID. When every id comes from elsewhere, turn that off in the Model:

```ts
// src/models/account.ts
import { ApplicationRecord } from "./application-record";

export class Account extends ApplicationRecord {
  static override attributes = {
    id: { generateId: false },
  } as const;
}
```

:::note
A text column sorts as text, so `"10"` comes before `"9"`. Positive ids of the same length sort as their numbers do.
:::

## Bound parameters

A statement binds at most 65,535 values. The adapter binds lists and a bulk insert’s rows as one JSON value, as on D1, so `where({ id: [...] })` and `insertAll` work with any number of values. `onQuery` shows each `real` in that value as text, which MySQL reads exactly. A statement longer than your server’s `max_allowed_packet` fails with MySQL’s own error.

## Raw SQL stays on its database

An [`sql` fragment](/conditions#writing-sql-fragments) is sent as you wrote it. `onQuery` and `toSql()` show names quoted with backticks. In MySQL, `||` means OR, so use `CONCAT()` to join text.

## Distinct records ordered by another column

MySQL refuses to order `distinct()` records by a column they don’t select, and throws its own error. Select the column, or order by one you select.

## JSON columns keep the value MySQL reads

A `JSON` column keeps the JSON value MySQL reads from your text, not the text itself. A raw query reads its object’s keys in MySQL’s order. Your Models read the same value either way.

Before MySQL 9.5, MySQL rounds some numbers as it reads JSON. A number with many digits, or a very large or small one, can be stored as the number next to it. `0.9103171217409103` is stored as `0.9103171217409104`. A number with a few decimals, such as a price, is stored exactly. A condition on the column rounds its number the same way, so it finds the row, and also any row holding the rounded number. To keep such a number exact before MySQL 9.5, store it in a `real` attribute.

:::tip
MySQL 9.5 and later store every number exactly.
:::

## Constraint errors name their table

MySQL’s constraint errors name their table. A unique failure has the columns of the index it clashed on, which the adapter reads from your database. A foreign-key failure has `.table` and `.columns` too. The values MySQL repeats in its errors are left out, so a log never holds them.

## Migrations are applied by the command

On MySQL, `arbor migrate` applies your migrations itself. It records each one’s version in a `schema_migrations` table. A version is the number a file’s name starts with, so every file’s name needs one.

Each migration runs between `START TRANSACTION` and `COMMIT`, one statement at a time. A `DELIMITER` line changes what ends a statement, as in the `mysql` client, so a trigger or a procedure can hold semicolons.

:::warning[A schema change commits as it runs]
MySQL commits a `CREATE TABLE` or an `ALTER TABLE` as soon as it runs, and can’t undo it. A migration that fails after one leaves the statements before it applied, and isn’t recorded. The error names the statement that failed and says which ones are applied. Undo them or finish the migration by hand, then run `arbor migrate` again.
:::

A second `arbor migrate` at the same time is refused, through a lock named for the database. [Migrating the real database](/command-line#arbor-migrate) needs its connection string and a route to its server.

## Reading the schema

`arbor schema` reads your schema from the database your `url` names, so a local server needs to be running. Run [`arbor migrate`](/command-line#arbor-migrate) first. MySQL’s column types decide the attributes, as [Mapping MySQL’s columns](/command-line#mapping-mysqls-columns) shows. A column’s name never does.

## Generated migrations

The generators write every name in backticks and end each table with `DEFAULT CHARSET=utf8mb4`. A key made in code is `CHAR(36)`, and `--id integer` gives a `BIGINT AUTO_INCREMENT` key. A `string` column is `VARCHAR(255)`, since MySQL can’t index a `TEXT` column without a length.

A reference’s foreign key is a constraint of its own, `fk_line_items_order_id`, since MariaDB ignores one in a column’s definition. Removing the reference drops it first.

A generated migration can add a `NOT NULL` column without a default. MySQL fills the rows a table has with an empty value, such as `''` or `0`. It refuses a date column on a table with rows, and MariaDB fills one with a zero date.

## MariaDB

The same entry runs on MariaDB, with the same binding and `connect`. When a Database first connects, it asks the server for its `VERSION()`, and writes MariaDB’s SQL from then on. Until then, `toSql()` shows MySQL’s SQL, but a query is always sent in the SQL of the server it reaches.

MariaDB works differently from MySQL in a few places:

- A plain insert returns its rows with `RETURNING`, so a bulk insert whose keys MariaDB generates returns them. An upsert’s rows are still read back by their keys. An upsert or an insert that skips duplicates throws a `TypeError` when you give `returning` and its rows don’t give their keys.
- Text compares in the column’s collation, as on MySQL. MariaDB’s default collation ignores case. It’s `utf8mb4_general_ci` on 10.11 and `utf8mb4_uca1400_ai_ci` from 11.5. To compare a column’s text exactly, give it `utf8mb4_bin` or `utf8mb4_nopad_bin`.
- A `JSON` column is `LONGTEXT` that must hold valid JSON. It keeps the text you wrote, and a condition on it compares that text.
- A refusal’s `TypeError` names MariaDB, and a failed `CHECK` constraint is MariaDB’s error 4025.
- `arbor schema` reads a `LONGTEXT` column with a `json_valid` check as a `json` attribute. It reads string defaults as MariaDB writes them, quoted.
