MySQL Destination
Upsert records into MySQL tables using
INSERT ... ON DUPLICATE KEY UPDATE.
YAML Example
destination:
type: mysql
host_env: MYSQL_HOST
port: 3306
dbname_env: MYSQL_DATABASE
user_env: MYSQL_USER
password_env: MYSQL_PASSWORD
table: interviewer_learning_profiles
upsert_key: [user_id, company_id]
Configuration
| Field | Type | Default | Description |
|---|---|---|---|
type | "mysql" | — | Required |
connection_string_env | string | null | null | Env var with full connection string (takes precedence) |
host / host_env | string | — | Hostname (direct or env var) |
port | int | 3306 | Port number |
dbname / dbname_env | string | — | Database name |
user / user_env | string | — | Username |
password / password_env | string | — | Password |
table | string | — | Target table (e.g. mydb.scores for schema-qualified) |
upsert_key | list[str] | — | Columns for ON DUPLICATE KEY UPDATE (must have a UNIQUE / PRIMARY KEY constraint) |
ssl | SslConfig | null | null | SSL/TLS config |
json_columns | list[str] | null | null | Columns containing JSON values (encoded as JSON strings via _serializer) |
Authentication
Option 1: Individual fields (recommended)
host_env: MYSQL_HOST
dbname_env: MYSQL_DATABASE
user_env: MYSQL_USER
password_env: MYSQL_PASSWORD
Option 2: Connection string
connection_string_env: MYSQL_URL
# e.g. mysql://user:pass@host:3306/dbname
SSL (mTLS):
ssl:
enabled: true
ca_env: MYSQL_SSL_CA # path to CA cert
cert_env: MYSQL_SSL_CERT # path to client cert
key_env: MYSQL_SSL_KEY # path to client key
Common Patterns
Upsert by composite key:
table: user_skills
upsert_key: [user_id, skill_id]
The MySQL connector serialises dict / list values to JSON strings via the shared _serializer module (consolidated in v0.7.5 alongside Postgres) — both encode through json.dumps.
Schema-aware by default (introspect_schema: true). At sync start drt reads INFORMATION_SCHEMA.COLUMNS for the target table once and routes each value by the column's real type — so a dict/list lands as JSON in a JSON column with no configuration. Introspection is best-effort: if information_schema isn't readable (locked-down grants) or the table doesn't exist yet, drt silently falls back to encoding every complex value. Set introspect_schema: false to disable it.
MySQL is supported by managed destination tables: opt-in
create-if-missing, pre-load drift checks, and nullable column appends. The guide lists the required
CREATE / ALTER privileges and explains why a fallback-typed primary key uses VARCHAR(255).
Use json_columns to override introspection with an explicit allowlist — it always takes priority and surfaces an early error when an unlisted column carries a complex value:
json_columns: [preferences, metadata]
Match policy (match_policy, #757) — only-update / only-create:
sync:
mode: upsert
match_policy: update_only # upsert (default) | update_only | create_only
destination:
type: mysql
table: crm.contacts
upsert_key: [tenant_id, contact_id]
The default upsert policy inserts missing rows and updates existing rows.
match_policy can narrow that behavior when either half would be harmful:
update_onlyemitsUPDATE ... SET ... WHERE <upsert_key>, so a row missing from MySQL is skipped instead of inserted. It requires at least one non-key column andSELECTaccess to the target: MySQL reports rows changed, not rows matched, so drt performs a key-existence probe only when an UPDATE reports zero. That keeps an existing row whose values were already identical classified as a success rather than a false no-match.create_onlyuses a normalINSERT. Because MySQL uses the same1062response for every PRIMARY or UNIQUE constraint, drt verifies a duplicate against the configuredupsert_key: an existing match is counted as skipped, while a collision on some other unique constraint remains a normal row error. drt deliberately does not useINSERT IGNORE, because MySQL can turn invalid values into warnings and insert coerced data, and it does not use a no-opON DUPLICATE KEY UPDATE, because that would activate UPDATE triggers on rows promised to remain untouched.create_onlyalso assumesupsert_keyis backed by a PRIMARY or UNIQUE index: without one MySQL raises no1062, so the plainINSERTwould add the duplicate row (the same assumption the defaultupsertalready makes viaON DUPLICATE KEY UPDATE).
Both policies require a non-empty upsert_key and SELECT access to the target
table (the probes run only for ambiguous zero-row updates or duplicate inserts).
Policy-declined rows increment SyncResult.skipped and its skipped_no_match
breakdown; they are not errors. The policies compose with field mappings, masks,
and lookups, but are rejected for mode: replace and mode: mirror, whose write
semantics are incompatible.
Replace mode (TRUNCATE + INSERT):
sync:
mode: replace
Zero-downtime replace via staging swap:
sync:
mode: replace
replace_strategy: swap # default: truncate
drt creates a shadow table {table}__drt_swap, populates it across batches, then issues a single atomic RENAME TABLE from finalize_sync — MySQL guarantees the multi-table RENAME TABLE original TO old, shadow TO original is atomic in one statement, so readers of the original table never see an empty or half-populated state.
Requirements: the destination user needs CREATE, ALTER, DROP, and RENAME privileges on the schema.
Caveats:
- Tables with dependent views or triggers are not recommended for swap mode — the rename can break dependent objects.
- If a sync is killed before completion, an orphan shadow may remain. Drop manually with
DROP TABLE {table}__drt_swap. Auto-cleanup is tracked in #433.
Same replace_strategy: swap is supported on Postgres (transactional ALTER TABLE ... RENAME) and ClickHouse (atomic EXCHANGE TABLES, requires CH 21.8+).
Mirror mode (differential delete, #340 Step 2 — v0.7.7+):
sync:
mode: mirror
destination:
type: mysql
table: hr.employees
upsert_key: [employee_id] # required for mirror
Mirror upserts every source row (same as full), then issues a single end-of-sync DELETE that removes destination rows whose upsert_key was not observed in the source. The MySQL implementation builds the NOT IN list with explicit %s placeholders because pymysql does not auto-expand a tuple-of-tuples parameter the way psycopg2 does:
- single-column form:
DELETE FROM \` WHERE `` NOT IN (%s, %s, ...)` with a flat values list - composite form:
DELETE FROM \` WHERE (`c1`, `c2`) NOT IN ((%s, %s), (%s, %s), ...)` with values flattened row-major
The same
_quote_identhelper that v0.7.4 (PR #514) hardened across all replace / insert / upsert / row-count paths is reused for the DELETE —mydb.scorescorrectly renders as`mydb`.`scores`regardless of which mode you use.Mirror is appropriate when rows disappearing from the source should disappear from the destination — master tables (employees / SKUs / permissions) where deletions need to propagate without the TRUNCATE / re-insert cost of
replacemode.Comparison:
Mode New rows Updated rows Removed-from-source rows Cost shape upsert/fullupsert upsert stay in destination upsert per row replaceINSERT INSERT DELETEd as side effect TRUNCATE + INSERT all mirrorupsert upsert DELETEd by upsert_key NOT IN (...) upsert per row + 1 DELETE Safety guards:
- Empty source short-circuit — if no batch ever delivered records, the DELETE is skipped. A transient empty source (auth failure mid-extract, vendor outage) cannot wipe the destination.
- Run-time change guards —
sync.guards.max_deletesandmax_delete_pctexecute the final mirror DELETE inside the finalize transaction, judge its authoritative affected-row count, and roll it back on a trip. Destination mirror first counts the exact scoped percentage baseline; tracked mirror counts its staged-state baseline, while diff mirror has no percentage baseline and fails closed. Guarded finalization also verifies that the target table—and_drt_synced_keysfor tracked mirror—uses InnoDB; an unknown or non-transactional engine is refused before DELETE because rollback cannot provide the safety contract.drt run --force-guardsproceeds and records the override. Replace-swap is guarded by locked-table counts before the swap (and also requires an InnoDB target); replace-truncate is not. - Failed rows excluded from the key set — only successfully upserted keys count as "observed source state"; a row that failed during upsert won't cause its destination counterpart to be deleted.
upsert_keyrequired — load() raisesValueErrorbefore any write ifdestination.upsert_keyis empty.- Composite keys supported —
upsert_key: [tenant_id, employee_id]producesWHERE (tenant_id, employee_id) NOT IN (...).
Memory constraint: the in-process key set is memory-bound to source key cardinality. For tables with more than a few million keys the temp-table strategy (#340 follow-up) will be more appropriate. Mirror as shipped today is appropriate for small/medium reference tables.
Tracked mirror (
mirror.strategy: tracked, #686) — for tables the application also writes to:sync:mode: mirrormirror:strategy: tracked # default: "destination" (the behaviour described above)Instead of diffing against the whole destination table (only correct when drt exclusively owns it),
trackedpersists the set ofupsert_keytuples drt has itself synced in a drt-managed_drt_synced_keystable (created lazily in the target's database) and deletes onlypreviously-synced − current-sourcekeys — so rows the application wrote are never deletion candidates. First run baselines without deleting; lost state re-baselines with a WARN; target delete + state rewrite share one transaction. See the Postgres tracked-mirror section for the full semantics — the MySQL implementation is identical apart from placeholder building (explicit%slists).Required destination privileges (#695): tracked mirror needs
DELETEon the target plus grants on the state table, beyond themode: fullset (SELECT, INSERT, UPDATE). This bit a real least-privilege MySQL rollout ((1142, "CREATE command denied to user … for table '_drt_synced_keys'")):-- target table: DELETE is the tracked-mirror additionGRANT SELECT, INSERT, UPDATE, DELETE ON `analytics`.`scores` TO 'retl_user'@'%';-- state table: pre-provision it once as an admin to skip the CREATE grantCREATE TABLE IF NOT EXISTS `analytics`.`_drt_synced_keys` (sync_name VARCHAR(255) NOT NULL,key_hash CHAR(64) NOT NULL,key_json TEXT NOT NULL,PRIMARY KEY (sync_name, key_hash)) ENGINE=InnoDB;GRANT SELECT, INSERT, DELETE ON `analytics`.`_drt_synced_keys` TO 'retl_user'@'%';-- table-level grants can be issued before the table existsTwo MySQL-specific traps:
- The DELETE grant fails late, not on the first run. The first run baselines and issues no deletes, so a missing
DELETEprivilege only detonates on the first real generation change — potentially weeks after rollout. Grant it up front. CREATE TABLE IF NOT EXISTSstill needsCREATE— MySQL checks the privilege before the existence check, so pre-creating_drt_synced_keysalone did not historically avoid the grant. Since v0.8.x drt first probesinformation_schema.tablesand skips the CREATE entirely when the table already exists, so an admin can pre-provision the state table (SQL above) and run the sync user with no DDL privilege — the sanctioned pattern for "no CREATE for app users" hardening.
Tracked mirror uses a temporary staging table to compute the state diff server-side when the user has
CREATE TEMPORARY TABLES. That database-scoped privilege is optional: when it is unavailable, drt transparently reads the sync's state and computes the same diff client-side. The no-DDL pre-provisioning contract above therefore stays intact, with the tradeoff that a very large_drt_synced_keysset uses correspondingly more process memory during the fallback.Scoped mirror (
mirror.scope, #687):scope: [parent_id]restricts the mirror DELETE to rows whose scope values appeared in this run's source — the stateless fit for 1:N regeneration (delete stale children under regenerated parents, never touch rows under unobserved parents). Composable withstrategy: tracked(#694) for co-writer-safe 1:N regeneration, providedscopeis a subset ofupsert_key. See the Postgres scoped-mirror section for the full semantics — identical on MySQL.Same
sync.mode: mirroris supported on Postgres (Step 1 — psycopg2's tuple-of-tuples auto-expansion), ClickHouse (Step 3 —ALTER TABLE ... DELETE WHEREmutation withmutations_sync=1), and Snowflake (Step 4 — forces the MERGE write path regardless ofconfig.mode). BigQuery follows once contributor PR #584 lands.mirror.strategy: trackedis currently Postgres + MySQL only.Schema-qualified table identifiers
MySQL identifier quoting applies consistently across all paths thanks to the
_quote_identhelper hardened in v0.7.4 (PR #514):scores→`scores`mydb.scores→`mydb`.`scores`
This means you can write
table: mydb.scoreswithout worrying about reserved words, mixed case, or schema-qualified addressing being mis-quoted on any of the replace / insert / upsert / row-count / swap / mirror paths.As a source — retry on transient extract failures (#766)
When MySQL is the source of a sync, opening the connection and running the model query are retried automatically (3 attempts, exponential backoff from 1s, capped at 60s). No configuration — it is always on, and separate from the
sync.retryknobs that govern the load side.Retried (pymysql):
InterfaceError— always; pymysql raises it when its own connection object is unusable.OperationalErroronly with a client-side connection errno:2002(can't connect via socket),2003(can't connect to host),2006(server has gone away),2013(lost connection during query),2055.
Not retried: anything else. Unlike the Postgres source,
OperationalErroris not retried on class alone — pymysql overloads it across both the client errno space and the server's, where it also covers permanent conditions like 1045 access denied and 1049 unknown database. Retrying a bad password three times is pure waste and can trip an account-lockout policy. AnOperationalErrorwith no usable errno is treated as permanent: failing fast beats retrying something unclassifiable.⚠️ Scope: connection + query execution + fetching the result set only. A failure after the first row has been yielded is not retried and fails the sync — those rows are already loaded into the destination and cannot be un-sent. See API_REFERENCE for the full rationale.
Notes
- Requires
pip install drt-core[mysql](usespymysql) - Query tagging (#768): every write query gets a leading
/* drt app=drt sync=<name> run_id=<id> ... */comment by default (MySQL has no native session/job-tagging mechanism) — seequery_taggingindocs/llm/API_REFERENCE.md. upsert_keycolumns must have a UNIQUE or PRIMARY KEY constraint on the target tabledrt testvalidators (row_count, not_null, freshness, unique, accepted_values, query) work with MySQL--dry-runshows row count diff formode: replace- The connection uses
charset: utf8mb4andautocommit: falseby default so multi-statement work runs in a single transaction
- composite form: