# MySQL compatibility as a PostgreSQL 18 extension

> How OpenHalo 18 replaced a 320-file PostgreSQL 14 kernel fork with a 12-file protocol hook and the aux_mysql extension, preserved the PostgreSQL 18 ABI, and what an adversarial review uncovered.

---

LLMS index: [llms.txt](/llms.txt)

---

openHalo 1.0 taught PostgreSQL 14 to speak the MySQL wire protocol and SQL dialect by modifying roughly 320 files inside the PostgreSQL kernel. When we brought MySQL compatibility to PostgreSQL 18.6, we took a different route: keep a small, protocol-agnostic hook in the kernel and move every line of MySQL wire handling, grammar, parse-tree rewriting and runtime semantics into a loadable extension (`aux_mysql`).

This note records the design and findings from the 2026-11-07 porting study and the adversarial review of [OpenHalo 18](/docs/mysql/) (`v18.6`, commit `60e7a225`). For the current state of fixes and open issues, see [MySQL status](/docs/mysql/status/).

## Why openHalo 1.0 could not simply rebase to PostgreSQL 18 {#openhalo-1}

An audit of the openHalo 1.0 tree (`v1.0-pg14`, commit `f9aedb8`, closest to upstream `REL_14_13` and later merged with `REL_14_18`) showed why a direct rebase across four major PostgreSQL releases was impractical:

| Area | openHalo 1.0 (`v1.0-pg14`) | Impact on porting and maintenance |
| --- | --- | --- |
| Kernel diff | ~320 modified files (~12,000 lines changed) plus ~110,000 added lines in `src/` | Forked copies of the PG 14 analyzer and executor (`mys_gram.y` ~24k lines, `mys_tablecmds.c` ~17k lines) had to be re-forked on every major upgrade |
| Extension ABI | Altered `DestReceiver` signatures, added a column to `pg_proc`, set `N_ACL_RIGHTS = 14` | Broke binary compatibility with stock PostgreSQL 14 extensions |
| Built-in types | Hardcoded MySQL protocol branches inside `bool`, `float`, `numeric`, `varlena` and `like` | Mixed foreign dialect rules into core execution paths |
| Native parser | Modified the core PG parser to accept backticks, `"..."` strings, `\'` escapes and `DATE(text)` | `contrib/aux_mysql` (~35k lines of SQL + `mysm` C library) could not install on an unmodified PG parser |
| Legacy remnants | Trimmed from commercial Halo; kept Oracle fields (`proaccess`), backported `MERGE` and TDS tags | Extra surface area to untangle against native PG 15–18 features |
{.wide}

Between PostgreSQL 14 and 18, `MERGE` landed natively, `Value` nodes became `A_Const` unions, `returningList` became `ReturningClause`, `GrantRoleStmt` and `PartitionStrategy` changed, `varatt.h` split out, and dozens of analyzer and executor signatures shifted. Rebasing 320 scattered kernel files would have produced another isolated fork that could not load PGDG extension packages, and the same cost would recur on PostgreSQL 19. See [From openHalo 1.0](/docs/mysql/design/from-openhalo-1/).

## A 12-file protocol hook and the aux_mysql extension {#hook-and-extension}

OpenHalo 18 splits the system into two layers: a generic kernel patch that knows nothing about MySQL, and the `aux_mysql` extension (`contrib/aux_mysql`, named `halo_mysql` in the prototype) that carries all MySQL behavior.

```text
PostgreSQL 18.6 + protocol extension hooks (12 files, +357/-18)
  postmaster: listens on 5432 (libpq) and 3306 (MySQL) -> regular backends
  backend:    start -> authenticate -> read_command -> parse_query -> execute -> DestReceiver
       |
aux_mysql (contrib/aux_mysql)
  mysql_proto.c   MySQL wire packets, text/binary result sets, SQLSTATE -> MySQL errno
  mys_auth.c      caching_sha2_password (fast-auth cache, TLS / RSA-OAEP full auth)
  mys_stmt.c      COM_STMT_PREPARE / EXECUTE / CLOSE / RESET / SEND_LONG_DATA
  mys_txn.c       autocommit, implicit commits, statement rollback via savepoints
  parser/         openHalo MySQL grammar (mys_gram.y + mys_scan.l, ~29.5k lines)
  mys_rewrite.c   raw parse-tree rewrite before pg_analyze_and_rewrite
  mys_utility.c   ProcessUtility_hook for MySQL DDL and ENGINE= / ENCRYPTION= mapping
  mysm/ + sql/    openHalo C runtime (~15.4k lines) and SQL catalog (~35k lines)
```

### The kernel protocol hook {#protocol-hook}

The [protocol hook](/docs/kernel/protocol-hook/) (`pg18-protocol-hooks.patch`, commit `c4b3cbe` on PostgreSQL 18.6) modifies 12 files (`+357/−18` lines, including 181 lines in the new `protocol_extension.c` and `protocol_extension.h`). It intercepts only the boundary where a backend talks to its client:

- **Listener registration (`postmaster.c`, `protocol_extension.c`)**: `RegisterProtocolExtension()` and `ListenServerPortForProtocol()` bind port 3306 in `_PG_init` and pass `ClientSocket.protocol_id` to forked backends.
- **Startup and authentication (`backend_startup.c`, `postinit.c`)**: `start` performs the foreign handshake and sets `MyBackendType = B_BACKEND`; `authenticate` replaces `ClientAuthentication()` once shared catalogs are readable.
- **Command loop and client-only parser (`postgres.c`)**: `read_command` and `process_command` route `COM_QUERY` through `exec_simple_query()` and handle other `COM_*` packets in the extension. `parse_query` inside `pg_parse_client_query()` replaces the parser **only for top-level client queries**—SQL function bodies, `SPI` and extension scripts still use `pg_parse_query()`.
- **Output and error reporting (`dest.c`, `elog.c`, `guc.c`)**: `create_dest_receiver`, `end_command`, `null_command` and `send_ready_for_query` encode MySQL result sets and `OK`/`EOF` packets; `send_message` maps `SQLSTATE` to MySQL error numbers; `report_param_status` suppresses libpq `ParameterStatus` packets.

Because every MySQL connection is a standard PostgreSQL backend, `max_connections`, `pg_stat_activity`, `pg_hba.conf`, query cancellation and `secure_open_server()` TLS (`ssl_*`, `hostssl`, `pg_stat_ssl`) work out of the box. Native libpq connections pay only a `MyProtocolExtension == NULL` check.

### Moving MySQL semantics out of the kernel {#moving-semantics}

To leave PostgreSQL's analyzer, planner, executor and system catalogs untouched, `aux_mysql` combines four mechanisms ([How it works](/docs/mysql/architecture/)):

1. **Scripted grammar and SQL porting**: `tools/port_grammar.py` rewrites openHalo's ~29,500-line `mys_gram.y` and `mys_scan.l` to emit PG 18 parse nodes. `tools/port_aux_sql.py` translates openHalo's 35,000-line `aux_mysql` SQL catalog (~1,800 functions, ~500 operators, ~180 tables/views, ~70 types) into standard PostgreSQL syntax.
2. **Raw parse-tree rewriting (`mys_rewrite.c`)**: the grammar emits out-of-core enum tags (`AT_ModifyColumn`, `CONSTR_AUTOINC`, `ONCONFLICT_REPLACE`). Before `pg_analyze_and_rewrite()`, `mys_rewrite.c` translates them into identity columns, `ON CONFLICT` clauses, `@user` / `@@system` function calls and `COLLATE mysql.case_insensitive` clauses.
3. **DDL utility hook (`mys_utility.c`)**: `ProcessUtility_hook` handles MySQL `ALTER TABLE ... MODIFY / CHANGE / ADD INDEX / DROP PRIMARY KEY`, `SHOW`, `USE <schema>` and `ENGINE=` / `ENCRYPTION='Y'` access-method mapping.
4. **Authentication, prepared statements and transactions (`mys_auth.c`, `mys_stmt.c`, `mys_txn.c`)**: ~3,400 lines of new C code implement MySQL 8's default `caching_sha2_password` (shared-memory fast-auth cache plus TLS or RSA-OAEP full auth verified against `pg_authid.rolpassword` SCRAM/MD5 verifiers), `COM_STMT_*` binary prepared statements, autocommit, implicit DDL commits and savepoint-based statement rollback—without changing a line of the 12-file kernel patch.

## ABI preservation and cross-kernel portability {#abi-and-portability}

Keeping dialect semantics out of the kernel preserves binary compatibility with existing extensions. On 2026-11-07 (EL9 aarch64, `--enable-debug --enable-cassert`), `abidiff` compared the protocol hook against other multi-dialect PG 18 forks:

| Kernel | Non-test `src/` diff | `abidiff` changes | `NodeTag` | Stock PG 18 packages |
| --- | --- | --- | --- | --- |
| Protocol hook (`pg18-protocol-hooks`) | 12 files, `+357/−18` | 1 internal struct (`ClientSocket` +8B), 0 signatures | `479` | All 11 C/Rust packages pass |
| Babelfish 6.2 (PG 18.6) | 277 files, `+14,057/−734` | 31 structs (`FuncExpr`, `SelectStmt`, `Port`), 5 signatures | `479` → `480` | Citus crashes; `pg_search` fails |
| IvorySQL 5.6 (PG 18.6) | 2,782 files, `+887,695/−5,188` | 49 structs + `pg_attribute`, `pg_class`, `pg_proc` columns | Changed | Incompatible without rebuild |
| openHalo 1.0 (PG 14) | ~320 files + ~110k added lines | `DestReceiver`, `pg_proc`, `N_ACL_RIGHTS` | — | Incompatible with stock PG 14 |
{.wide}

The protocol hook changes no parse node, no catalog table and no exported function signature. Its only structure change appends `int protocol_id` to `ClientSocket` in `src/include/libpq/libpq-be.h` (`sizeof(ClientSocket)` grows from 144 to 152 bytes), a structure passed only between `postmaster.c`, `launch_backend.c` and `backend_startup.c`. Stock PGDG and Pigsty PG 18 packages—PostGIS 3.6, `pgvector` 0.8, Citus 14.3, TimescaleDB 2.31, `pg_cron`, `orafce`, VectorChord, `vchord_bm25`, `pg_search`, `pg_graphql` and `pgs3`—loaded and passed smoke tests unchanged ([ABI compatibility](/docs/kernel/abi/), [Extension matrix](/docs/kernel/extensions/)).

On 2026-11-07 (EL9 aarch64, `--enable-debug --enable-cassert`), the hook and extension also ported across five other PostgreSQL trees ([On other kernels](/docs/mysql/design/other-kernels/), [PostgreSQL 19](/docs/kernel/pg19/)):

- **OrioleDB (`patches18_4` on PG 18.6)** and **Percona Server for PG 18.4.2**: **0 conflicts**. Mapping `ENGINE=OrioleDB` to `orioledb` and `ENCRYPTION='Y'` to `pg_tde`'s `tde_heap` exposed a cross-extension bug: `pg_tde` decides whether a new file is encrypted in a `ddl_command_start` event trigger, whereas `aux_mysql` ran decomposed `ALTER TABLE` commands with `PROCESS_UTILITY_SUBCOMMAND`, skipping event triggers and writing `ALTER TABLE ... ENCRYPTION='Y'` files in cleartext. Switching `mys_utility.c` to `PROCESS_UTILITY_QUERY` fixed the bypass.
- **IvorySQL 5.6 (PG 18.6)**: **2 context conflicts**. After dropping `aux_mysql`'s unused `sys` schema, keeping existing `varchar → bigint` casts and combining `shared_preload_libraries`, one instance served Oracle (1521), MySQL (3317) and PostgreSQL (5443).
- **Babelfish 6.2 (PG 18.6)**: adapted to Babelfish's `ProtocolExtensionConfig` with a 2-file (`+36/−5`) delta (`fn_parse_query`, `PROTOCOL_EXTENSION_FALLTHROUGH`).
- **PostgreSQL `19rc1`**: **1 conflict** in `backend_startup.c` (`ProcessStartupPacket()` dropped two arguments); the `19rc1` kernel passed **239/239** regression tests, while `aux_mysql` had 47 compile errors from PG 19 API changes.

## What the adversarial review found in v18.6 {#review}

On 2026-11-07, an adversarial review evaluated OpenHalo 18 tag `v18.6` (`60e7a225`, OpenHalo layer `c380da3`) against stock PG 18.6 and openHalo 1.0 (`v1.0-pg14` / `f9aedb8`) on EL9.8 aarch64 (`--enable-debug --enable-cassert --with-openssl --with-icu`).

While core PG `make check` (231/231), `isolation` (122/122) and the `check-world` SQL subset (688/688) passed and standard drivers (Connector/J 8.4.0, `go-sql-driver` v1.9.3, PyMySQL v1.1.1, `mysql` CLI, `sysbench` 1.0.20) connected, the review **rejected `v18.6` as a stable release baseline**, identifying **11 Category A product blockers** and **3 verification/documentation gates**:

| ID | Finding in `v18.6` (`60e7a225`) | Origin vs 1.0 (`f9aedb8`) |
| --- | --- | --- |
| `F01` | `ALTER TABLE ... AUTO_INCREMENT` on a partitioned parent table triggers `SIGSEGV` in `table_is_empty` and resets all sessions | **18 crash regression** (1.0 did not crash, though start value had no effect) |
| `F02` | `AUTO_INCREMENT` high-water mark moves backwards when `is_called=false` or via `UPDATE`-only `mysql.setval()` | **18 regression** (1.0 generated `100` and kept `last_value = 100`) |
| `F03` | Concurrent `nextval` + explicit ID inserts deadlock (`1213`) when `sequence_advance` upgrades to `ExclusiveLock` | **18 regression** (1.0 committed both transactions) |
| `F04a` | Default `aux_mysql` setup worker races with `pg_dump` restores and perturbs `pg_visibility` TAP tests | **18 new integration defect** (1.0 installed manually) |
| `F05` | `CREATE TABLE ... LIKE` omits the `AUTO_INCREMENT` sync trigger, causing duplicate keys after explicit inserts | **18 regression** |
| `F06a` | `SHOW CREATE TABLE` emits literal `\n` and omits `AUTO_INCREMENT` (`SHOW COLUMNS` omits `Extra`) | **18 regression** |
| `F07` | `UNSIGNED AUTO_INCREMENT` drops the unsigned domain without a non-negative `CHECK`, accepting `-1` | **18 regression** (1.0 rejected `-1`) |
| `F09a` | `ALTER TABLE ... ADD COLUMN` without `COLLATE` forces `table_ci = true` on binary tables | **18 regression** |
| `F11` | `BLOB` / `VARBINARY` binary parameters (`0x00`, `0x80`, `0xff`) fail UTF-8 validation | **18 regression** |
| `F13` | `COM_STMT_EXECUTE` reports `decimals = 0` for `DATETIME(3)` and `DATETIME(6)`, truncating fractional seconds | **18 new protocol defect** (1.0 failed during `Prepare`) |
| `N01` | `COM_RESET_CONNECTION` returns `OK` without rolling back open transactions or clearing `@user` variables | **18 regression** on rollback and user variables |
| `G01`–`G03` | `tests/run.sh` ignores errors in `m1`–`m4` and `sysbench`; docs overstate "zero ABI change" (`ClientSocket` 144 → 152B); `check-world` times out (`RC=124`) | **18 verification and doc gates** |
{.wide}

Comparison against openHalo 1.0 also separated Category B findings: 18 regressions in single-statement `ALTER` auto-increment start values (`F08`), missing `ENUM`/`SET` (`F10`), `CHAR(n)` trailing spaces (`F12`), negative `TIME` (`N02`), `FLOAT` wire type `5` (`N03`) and missing `SHOW WARNINGS` (`N04`); new 18 integration gaps in Meson builds (`F14`) and `mysql.max_allowed_packet` (`F16a`); and issues inherited from 1.0 (`NO_BACKSLASH_ESCAPES` status bit `F15`, `SHOW CREATE` omitting `ON UPDATE` `F06b`, and `1.0.14.18` version string blocking `pg_upgrade` `N05`).

In external suites on `v18.6`, `go-sql-driver` v1.9.3 passed 49/72 server tests (21 failed, 2 skipped), PyMySQL v1.1.1 passed 123/175 (39 failed, 12 skipped, 1 xfail), and `sysbench` 1.0.20 ignored 42 and 264 errors in read-write and write-only runs. Clearing the Category A blockers and gates was roughly estimated at 20–35 person-days (rough estimate, not a commitment).

## Takeaways {#takeaways}

The 2026-11-07 study and review established two conclusions:

1. **The architectural boundary holds.** MySQL compatibility does not need a 320-file kernel fork; a 12-file protocol hook runs the MySQL protocol, parser and runtime inside an extension while keeping PostgreSQL 18's extension ABI intact.
2. **OpenHalo 18 `v18.6` is a development preview.** Replacing forked kernel code with parse-tree rewrites, triggers and new wire protocol routines introduced defects in sequence monotonicity, DDL round-trips, binary parameters and connection reset.

Local commits have since addressed the Category A blockers and several Category B gaps. Follow the current status in [MySQL status](/docs/mysql/status/) and [MySQL compatibility](/docs/mysql/compatibility/).

---

Backlinks:

- [Protocol, dialect and origins](/docs/mysql/architecture/)
