콘텐츠로 이동
한국어

MariaDB

이 콘텐츠는 아직 번역되지 않았습니다.

The MariaDB backend is the sibling of the Postgres backend for teams on MariaDB or MySQL. It provides the same three components — MariaDbJournal, MariaDbSnapshotStore, and MariaDbDurableStateStore — against a single database, via the official mariadb connector (which speaks both MariaDB and MySQL).

It’s a separate implementation from Postgres (not a shared dialect layer), so the SQL is idiomatic MariaDB, but the public contract and behaviour are identical.

mariadb is an optional peer dependency:

Terminal window
bun add mariadb

Imported when a MariaDB store opens — at startup, or on first use when the boot-time open is turned off — like every other adapter.

import {
ActorSystem,
ActorSystemOptions,
} from 'actor-ts';
import {
MariaDbJournalOptions,
MariaDbSnapshotStoreOptions,
MariaDbDurableStateStoreOptions,
RegisterMariaDbPluginsOptions,
registerMariaDbPlugins,
} from 'actor-ts/persistence';
const mariaDbJournalOptions = MariaDbJournalOptions.create().withPoolConfig(connection);
const mariaDbSnapshotStoreOptions = MariaDbSnapshotStoreOptions.create()
.withPoolConfig(connection)
.withKeepN(3);
const mariaDbDurableStateStoreOptions = MariaDbDurableStateStoreOptions.create().withPoolConfig(connection);
const registerMariaDbPluginsOptions = RegisterMariaDbPluginsOptions.create()
.withJournal(mariaDbJournalOptions)
.withSnapshotStore(mariaDbSnapshotStoreOptions)
.withDurableStateStore(mariaDbDurableStateStoreOptions);
const actorSystemOptions = ActorSystemOptions.create()
.withConfig({
'actor-ts': {
persistence: {
journal: { plugin: 'actor-ts.persistence.journal.mariadb' },
'snapshot-store': { plugin: 'actor-ts.persistence.snapshot-store.mariadb' },
'durable-state': { plugin: 'actor-ts.persistence.durable-state.mariadb' },
},
},
})
.withPersistence({ plugins: [(persistence) => registerMariaDbPlugins(persistence, registerMariaDbPluginsOptions)] });
const system = ActorSystem.create('my-app', actorSystemOptions);
// connection = { host, port: 3306, user, password, database } — or pass a
// shared `pool` (from mariadb.createPool) at the top level via
// `.withPool(pool)` to reuse one pool across all three, or a connection
// URL via `.withUrl(...)`.

As with Postgres, the plug-in runs inside ActorSystem.create, and the configuration selects all three stores, which open as part of the startup: a database the node cannot reach fails the startup rather than the first persisted message, with autoCreateTables on or off — see opening the stores at startup. The durable-state store is also returned, for a caller that would rather pass it into its DurableStateActor settings by hand; a store wired that way is not a selected one, so it opens on first use rather than with the startup.

The plugin id is the config section, so the block named after the id is the block that plugin reads (#872). Everything except the live objects can come from application.conf, which means registerMariaDbPlugins(persistence) needs no options at all:

import { ActorSystem, ActorSystemOptions } from 'actor-ts';
import { registerMariaDbPlugins } from 'actor-ts/persistence';
const systemOptions = ActorSystemOptions.create().withPersistence({
plugins: [(persistence) => registerMariaDbPlugins(persistence)],
});
const system = ActorSystem.create('my-app', systemOptions);
actor-ts.persistence {
journal { plugin = "actor-ts.persistence.journal.mariadb" }
snapshot-store { plugin = "actor-ts.persistence.snapshot-store.mariadb" }
durable-state { plugin = "actor-ts.persistence.durable-state.mariadb" }
journal.mariadb { url = ${?DATABASE_URL}, events-table = "events" }
snapshot-store.mariadb { url = ${?DATABASE_URL}, keep-n = 5 }
durable-state.mariadb { url = ${?DATABASE_URL}, table = "durable_state" }
}

Options passed to registerMariaDbPlugins still win, field by field, and a field you leave unset falls through to the block rather than blanking it — so a shared pool in code and the table names in HOCON is a normal mix. A pre-built pool and a serializer have no leaf at all: they are live objects, and a config file cannot express one. Neither does poolConfig — the connector’s whole option surface, which stays code-only. tags-table is read but ships as a comment rather than a key, because its default is derived from events-table, and absence is what keeps the two in step.

What you do tune on the pool has typed leaves (#1490), each a comment in the reference configuration so that leaving it out keeps the connector’s own default:

actor-ts.persistence.journal.mariadb {
url = ${?DATABASE_URL}
max-pool-size = 20 # connectionLimit (default 10)
acquire-timeout = 5s # acquireTimeout (default 10s)
idle-timeout = 10m # idleTimeout, whole seconds only (default 1800s)
connect-timeout = 2s # connectTimeout (default 1s)
ca-file = "/etc/ssl/maria-ca.pem" # read when the pool opens, handed over as ssl.ca
}

Each reaches the connector only when set — laid over the url, which is parsed the way the connector parses it so its host, database and options survive. The store checks them when it is built: a size or timeout that is not a positive whole number, an idle-timeout that is not a whole number of seconds (the connector counts it in seconds), or a timeout longer than a timer can hold is refused with an OptionsError — and so is a leaf beside the same option in poolConfig or in the url’s query (max-pool-size beside connectionLimit=, say), which names both instead of letting one quietly win. ca-file is a path the framework reads, never the certificate itself, and the one route to a private CA from configuration: the url’s ssl is a bare switch. It is refused beside a url ssl the connector reads as false — anything but exactly true, so ssl=TRUE too — since that turns TLS off.

durable-state.plugin now selects this backend’s durable-state store. It used to be built eagerly and handed back from registerMariaDbPlugins, so it could only be wired by threading that instance through application code. The returned handle still works and still yields the same instance — it is simply built when it is first asked for rather than at registration, which for a selected store is the startup.

type MariaDbConnection = {
url?: string; // mariadb://user:pass@host:3306/db
poolConfig?: Record<string, unknown>; // { host, port, user, password, database, … }
pool?: MariaDbPoolLike; // pre-built / shared pool
maxPoolSize?: number; // connectionLimit, default 10 (max-pool-size)
acquireTimeoutMs?: number; // acquireTimeout, default 10 000 (acquire-timeout)
idleTimeoutMs?: number; // idleTimeout in whole s, default 1800 s (idle-timeout)
connectTimeoutMs?: number; // connectTimeout, default 1 000 (connect-timeout)
caFile?: string; // PEM file read into ssl.ca (ca-file)
};
interface MariaDbJournalOptions extends MariaDbConnection {
eventsTable?: string; tagsTable?: string; autoCreateTables?: boolean;
}
interface MariaDbSnapshotStoreOptions extends MariaDbConnection {
snapshotsTable?: string; keepN?: number; autoCreateTables?: boolean;
}
interface MariaDbDurableStateStoreOptions extends MariaDbConnection {
table?: string; autoCreateTables?: boolean;
}

Discrete poolConfig (host/user/password/database) is the most portable way to connect; url and a pre-built pool are also accepted. The options are validated when the store is constructed — the MariaDB stores had no validator before the typed connection fields arrived.

Same shape as Postgres, with MariaDB types — VARCHAR(255) ids, BIGINT sequence/revision/timestamp, LONGTEXT payloads — and indexes declared inline in CREATE TABLE (portable across MariaDB/MySQL versions, unlike CREATE INDEX IF NOT EXISTS):

CREATE TABLE events (
persistence_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,
sequence_nr BIGINT NOT NULL,
payload LONGTEXT NOT NULL,
tags TEXT,
timestamp BIGINT NOT NULL,
PRIMARY KEY (persistence_id, sequence_nr),
INDEX idx_events_pid (persistence_id)
);
-- events_tags, snapshots, durable_state: as Postgres, with the types above

Every persistence_id and tag column carries an explicit COLLATE utf8mb4_bin. Without it the column inherits the server default — utf8mb4_general_ci on a stock MariaDB, utf8mb4_0900_ai_ci on MySQL 8 — and both of those fold case and accents.

A persistence_id is not merely a value: it is the name of an event stream and half of the events primary key. Under a folding collation Alice and alice are therefore one stream here and two on Postgres, SQLite, MongoDB and DynamoDB. An actor started as Alice recovers alice’s events, folds them into its own state and appends into alice’s stream — a cross-entity read whose only symptom is a run of JournalConcurrencyErrors that reads like a storage fault. The same column keys durable-state load, revision CAS and delete, so there a collision overwrites and deletes another entity’s state.

Validating the id cannot fix this: Alice and alice are both perfectly legal ids. What differs is the comparison, which is a property of the column.

utf8mb4_bin compares code point by code point, the way every other backend already does. It is also the portable spelling — utf8mb4_0900_bin is MySQL 8 only and MariaDB has never had it. Naming a collation with no CHARACTER SET fixes the charset to utf8mb4 as well, rather than leaving it on whatever the database defaults to.

One divergence survives on purpose: utf8mb4_bin is PAD SPACE, so 'alice ' still equals 'alice' here where Postgres keeps them apart. The NO PAD binary collations are vendor-split (utf8mb4_nopad_bin on MariaDB, utf8mb4_0900_bin on MySQL), so there is nothing portable to pin — avoid trailing whitespace in ids you generate.

The DDL is CREATE TABLE IF NOT EXISTS and autoCreateTables defaults to true, so an existing database does not pick this up: the framework never revisits a table it finds. New deployments get the collation silently; an older database keeps the server default until you run the migration below — but it no longer does so quietly. Each store reads its own tables out of information_schema when it opens and warns if a persistence_id or tag column comes back on a collation that is not binary, naming the table, the column and the collation it found. A selected store opens as part of the startup, so the warning is in the startup log; with the boot-time open turned off the store connects lazily instead and warns on first use, at the first persistence operation. That read needs no DDL rights and runs whether or not autoCreateTables is set, because a schema the operator manages is the one most likely to predate the pin. Run this once per database, with no node writing:

ALTER TABLE events MODIFY persistence_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL;
ALTER TABLE events_tags MODIFY persistence_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,
MODIFY tag VARCHAR(255) COLLATE utf8mb4_bin NOT NULL;
ALTER TABLE events_meta MODIFY persistence_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL;
ALTER TABLE snapshots MODIFY persistence_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL;
ALTER TABLE durable_state MODIFY persistence_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL;

MODIFY replaces the whole column definition, so NOT NULL has to be repeated — omit it and the column silently becomes nullable. Changing the collation of an indexed column is not an in-place alteration, so InnoDB rebuilds each table: budget a lock for the duration and disk for a second copy.

Between the first two statements the tag-query join compares an events column with an events_tags column of a different collation. MariaDB does not refuse that the way SQL Server does: where one side is _bin and the other _ci of the same character set, the _bin collation wins, so the join runs under utf8mb4_bin and returns the right rows — but the side not yet converted cannot use its index for the comparison, so tag queries in that window are slow rather than wrong. A tagsTable pointed at a new table beside a legacy events is that window made permanent, until events is re-collated too.

The startup warning reports per column, which is what tells that state apart from an untouched schema: restart a node mid-migration and the warning names only the columns still to convert, and says the schema is half migrated. A tagsTable beside a legacy events reads the same way, every time the store opens, until you finish the job.

Check for damage before migrating, while the folding collation is still what GROUP BY uses:

SELECT persistence_id,
COUNT(DISTINCT persistence_id COLLATE utf8mb4_bin) AS spellings
FROM events
GROUP BY persistence_id
HAVING spellings > 1;

Any row means two ids have already been sharing a stream. The ALTER splits them apart again, and each half is then missing the other’s events — so those actors fail recovery loudly with JournalIntegrityError (a hole in the sequence) instead of quietly serving a merged history. That is the better failure, but it is still a failure: decide what those streams ought to be before you migrate, not after.

MariaDbQuery reads the events_tags index exactly as PostgresQuery does — same statements, same three plans, only the placeholders differ. See Tag queries on the Postgres page for the shapes.

import { MariaDbJournal, MariaDbJournalOptions, MariaDbQuery } from 'actor-ts/persistence';
const journalOptions = MariaDbJournalOptions.create().withUrl(process.env.MARIADB_URL!);
const eventsJournal = new MariaDbJournal(journalOptions);
const query = new MariaDbQuery(eventsJournal);

The behaviour is identical; the SQL differs:

OperationPostgresMariaDB
Placeholders$1, $2?
Tag dedup insertON CONFLICT DO NOTHINGINSERT IGNORE
Snapshot upsertON CONFLICT … DO UPDATEON DUPLICATE KEY UPDATE
keepN pruneNOT IN (SELECT … LIMIT)derived-table-wrapped subquery¹
Durable create conflictON CONFLICT DO NOTHING → rowCountplain INSERT, catch ER_DUP_ENTRY (1062)
Concurrency backstopSQLSTATE 23505ER_DUP_ENTRY / 1062
Contention backstopSQLSTATE 40001 / 40P01ER_CHECKREAD (1020), 1213, 1205²
Id / tag comparisonTEXT — byte-exact alreadyVARCHAR(255) COLLATE utf8mb4_bin³

¹ MySQL/MariaDB reject LIMIT inside a bare IN (SELECT …) against the table being deleted, so the prune wraps the subquery in a derived table.

² A losing writer does not always reach the primary key. Under real contention InnoDB aborts it first — “Record has changed since last read” (errno 1020) — so the duplicate-key backstop alone would have handed the caller an opaque JournalError and no way to tell a retryable race from a storage failure. Those aborts are classified too, but they are only reported as JournalConcurrencyError when a re-read shows the head actually moved; otherwise the error stands, because a lock-wait timeout against an unrelated long transaction is a real failure and retrying it would spin. The same applies to durable-state CAS.

³ Postgres compares TEXT byte-exactly, so it needs nothing; MariaDB would otherwise inherit a case-folding server default and merge two entities into one stream. See Why persistence_id and tag are collated.

BIGINT may surface from the connector as a JS bigint; the backend coerces sequence/revision/timestamp to number at the mapping boundary.

  • PostgreSQL — the sibling backend, with the fuller walkthrough of registration + concurrency.
  • Cassandra journal — distributed, for scale-out.
  • Durable state — the state-oriented alternative to event sourcing.