Converting Existing Oracle SQL to MySQL: Where Do SQLAlchemy and SQLGlot Fit?

June 25, 2025

When preparing for a hospital information-system assessment, we had to calculate some indicators using data from multiple business systems. The hospital information system (HIS) and laboratory information system (LIS) each had their own database. Ophthalmology also had its own outpatient and medical record systems. Most source databases ran Oracle, though a few used other engines. Even when vendors used Oracle, each maintained its own database with a different administrator account. A SQL statement from an old document could run in one database without being able to read tables in another system.

Shortly before I took over the queries, the hospital had spent a substantial sum on a third-party data synchronization platform. It periodically pulled from the source systems and consolidated their data into one TiDB cluster. A single query could now join tables originating in different systems. By the time I started, we had a common query endpoint, but the SQL in the documents still targeted the source databases. The choice of MySQL as the target dialect was straightforward: TiDB would execute the queries. Some tables had also been renamed during synchronization. Each old name had to be matched to its actual name in the cluster.

Take a time filter. The source used TO_DATE('2025-06-24 13:05:00', 'yyyy-mm-dd hh24:mi:ss'). How many things need to change for MySQL? There's the function name, but also the notation for minutes and seconds in the second argument. Shift the time boundary and the subsequent COUNT(*) may return a plausible number that distorts the final ratio.

Before compiling a query for MySQL, check what you're starting with

My first approach to Oracle functions in the documents was text replacement. An early JavaScript script had a rule replacing NVL( with COALESCE(. For two date columns of the same type, NVL(actual_date, planned_date) chooses the actual date first and uses the planned date only if the former is null. MySQL's COALESCE(actual_date, planned_date) expresses the same order. My regex only recognized the function name. When the argument types differ, Oracle's NVL also performs implicit conversions, so the target result still needs checking after the rename.1

How would you preserve that precedence when rewriting a query with an object-relational mapper (ORM)? I read a Prisma question about expressing an existing PostgreSQL query using Prisma Client's where. It used COALESCE to choose between two dates and a default, then compare the result with the current time. If you decompose it into conditions, you must check the second date only when the first is null. Otherwise, a record that has not expired might get selected because its fallback date is earlier. The function expresses this succinctly. Prisma's $queryRaw can execute native SQL, but the caller still needs to supply SQL the target database accepts.2

I became interested in SQLAlchemy because it can compile the same query expression for different databases. Here an “expression” is a structured Python object. When I use select(), SQLAlchemy knows which part is a table and which is a filter. It can hand that structure to the target dialect's compiler for output. SQLAlchemy's ORM can also describe tables and relationships with Python classes, which came in handy later when building a query management page.3

But the SELECT in the old document arrived as a string. Pass it to SQLAlchemy's text() and it is treated as textual SQL, with support for operations such as parameter binding. Even if I then compile it for MySQL, the original TO_DATE remains. I checked this simplified example in the project's SQLAlchemy environment.4

from sqlalchemy import text
from sqlalchemy.dialects import mysql

stmt = text("SELECT TO_DATE('2025-06-24', 'yyyy-mm-dd') FROM DUAL")
print(stmt.compile(dialect=mysql.dialect()))
# SELECT TO_DATE('2025-06-24', 'yyyy-mm-dd') FROM DUAL

I needed an extra step: first read the source into a syntax tree. For TO_DATE, for example, a program must distinguish the function name, the date text to parse, and the format string specifying how to read it. Knowing each part's role gives it a chance to express the same thing in the target syntax.

SQLGlot can read the tree in one dialect and emit it in another. For an official date function example, suppose I want to display an order date as 2025-06-24. DuckDB uses STRFTIME(order_date, '%Y-%m-%d'). Calling sqlglot.transpile with read="duckdb" parses DuckDB syntax, and write="hive" produces Hive syntax. The result is DATE_FORMAT(order_date, 'yyyy-MM-dd'). The function name changes, and the four-digit year marker %Y becomes Hive's yyyy.5

Why change the time format after converting the function to STR_TO_DATE?

The official example writes a date as text. My query needed to go the other direction, parsing text into a date before comparing it to a time in a table. I set the input and output dialects to Oracle and MySQL and ran the following with SQLGlot 26.30.0, preserved from the project. I replaced the business table and fields with a generic orders table.6

import sqlglot

oracle_sql = """
SELECT COUNT(*) FROM orders
WHERE created_at >= TO_DATE('2025-06-24 13:05:00', 'yyyy-mm-dd hh24:mi:ss')
"""
mysql_sql = sqlglot.transpile(oracle_sql, read="oracle", write="mysql")[0]
print(mysql_sql)

This version generated the following date condition:

WHERE created_at >= STR_TO_DATE('2025-06-24 13:05:00', 'yyyy-mm-dd hh24:mi:ss')

The function name changed, but the format string survived untouched. MySQL's STR_TO_DATE reads a four-digit year with %Y, a month with %m, and minutes with %i. To express 1:05 p.m., this example needs the following MySQL condition.7

WHERE created_at >= STR_TO_DATE('2025-06-24 13:05:00', '%Y-%m-%d %H:%i:%s')

I added date rules in two places. Immediately after the transpile above, I directly corrected lowercase Oracle format strings left in the output.6

mysql_format = "%Y-%m-%d %H:%i:%s"
mysql_sql = mysql_sql.replace("yyyy-mm-dd hh24:mi:ss", mysql_format)

The second was after replacing table names and emitting SQL again from the syntax tree. Another spelling of the format string and function name also appeared at that stage. Below I have put the batch script's two regular expressions into a function so the change is visible with a single date expression.6

import re

def fix_date_output(sql):
    sql = re.sub(r"%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%i:%s", sql, flags=re.I)
    return re.sub(r"STR_TO_TIME", "STR_TO_DATE", sql, flags=re.I)

print(fix_date_output("STR_TO_TIME('2025-06-24 13:05:00', '%Y-%m-%d %H:%M:%S')"))
# STR_TO_DATE('2025-06-24 13:05:00', '%Y-%m-%d %H:%i:%s')

These rules operate directly on output text. For a general-purpose converter, I would restrict them to the format argument of date functions. A query could also contain 'yyyy-mm-dd hh24:mi:ss' as a hint to display in a report, for example. Global replacement would alter the hint too.6

Why can a query use the right dialect and still fail to find a table?

Suppose an old document says FROM orders o and the synchronized table is called SYNC_ORDERS. Both dialects understand FROM orders o. The transpiler has no way to know the name the third-party platform assigned. We need another input: the mapping from source tables to target tables.

I listed this mapping separately in the script. After parsing the query as MySQL, the script looks up each table node, replaces the table name, and keeps the alias. In this example the filter's o.created_at still points to the same table. These table names are illustrative. The actual mapping used the project's synchronized tables.6

To prepare the mapping, I also used the syntax tree to list the referenced source tables, then Python's get_close_matches to pick candidates from the target names. Name similarity alone can match a main table to a detail table. In a fictionalized example, ORDERS and ORDERS_ITEM share a substring, but counting orders and counting order lines are different things. I added a filter requiring the candidate to end in the complete source name, leaving it blank when it didn't match. During replacement, the script used only the target names recorded in the mapping.8

The following adapts my script and uses two sets of target names to demonstrate a match and an exclusion. The committed version examined only the closest match, returning None if it failed the suffix test.8

from difflib import get_close_matches

def suggest_target(source, targets):
    source = source.upper()
    names = [target.upper() for target in targets]
    matches = get_close_matches(source, names, n=1, cutoff=0.6)
    if matches and matches[0].endswith(source):
        return matches[0]
    return None

print(suggest_target("orders", ["sync_orders"]))  # SYNC_ORDERS
print(suggest_target("orders", ["orders_item"]))  # None

The hospital reports also included Caché SQL. Some target tables were never named in the source statement. It contained only a field pointing to another record. In that case we also needed to know which table and key the field referenced, as described in rewriting Caché SQL's -> as a TiDB JOIN.

Why did the conversion report success when it left table names in subqueries unchanged?

Once I had a mapping, I tried renaming the table node directly and got property 'name' of 'Table' object has no setter. SQLGlot's Table.name is readable, but you can't assign to it. I later realized names inside subqueries were staying unchanged. The committed solution walks the entire abstract syntax tree (AST) and returns a new node whenever it encounters a table, carrying its alias over. This abridged version of the script demonstrates the effect with a query containing a subquery.9

import sqlglot
from sqlglot.expressions import Table

mapping = {"ORDERS": "SYNC_ORDERS"}
sql = "SELECT (SELECT COUNT(*) FROM ORDERS o) FROM `DUAL`"

def replace_table(node):
    if isinstance(node, Table):
        name = mapping.get(node.name) or node.name
        return Table(this=f"`{name}`", alias=node.alias)
    return node

tree = sqlglot.parse_one(sql, read="mysql")
print(tree.transform(replace_table).sql())
# SELECT (SELECT COUNT(*) FROM `SYNC_ORDERS` AS o) FROM `DUAL`

The most time-consuming problem occurred before traversal. The transpiler had already emitted MySQL, and the outer query ended with backtick-quoted FROM `DUAL`. I suspected the combination of a plus sign and FROM DUAL and even examined the terminal escape code that underlined a character in the error. It turned out I had omitted the input dialect from the second parse_one call. With SQLGlot 26.30.0, removing read="mysql" from the example produces Unexpected token before the code even reaches the table traversal.9

The first batch log had six table-replacement errors yet ended with zero failures. On exception, replace_table_names returned its input SQL. Since it was already MySQL, it could pass the final syntax check even with the old names. In a later log the table errors disappeared, but six original Oracle statements still failed the initial check. Reviewing a batch like this today, I would check the results for input syntax, table mapping, and target syntax separately.9

How can we tell whether the converted query still computes the same number?

Renamed functions and valid syntax demonstrate only one stage of progress. SQLGlot's documentation says it defaults to warnings and “best-effort translation” for certain unsupported conversions. In a batch, unsupported_level=sqlglot.ErrorLevel.RAISE lets the library stop on unsupported items it recognizes. The format string above still needs a unit test. An absence of warnings cannot replace checking results.10

In the same example, two questions interest me more than the printed SQL:

  1. Does executing SELECT STR_TO_DATE('2025-06-24 13:05:00', '%Y-%m-%d %H:%i:%s') by itself on the target return the expected 2025-06-24 13:05:00? This isolates date parsing from table data.
  2. Put three orders in identical test data on both sides, timestamped 13:04:59, 13:05:00, and 13:05:01 on that day. Both the source and target queries should return 2 for COUNT(*). With data far from the cutoff, even an incorrect >= boundary can be hard to spot.

Two is the expected result for this fixture. In the assessment, we needed to trace each numerator and denominator to its own SQL. Even if both versions returned a number, we had to check date boundaries and joined tables to see whether they actually measured the same indicator.

What other tools handle parts of the job?

TaskTool or approach I'd useDecision still needed
Define tables, constraints, and relationships and write new queriesSQLAlchemy models and expressions, or a JS ORM supporting the target databaseWhich driver connects to the database and how the model represents business relationships. Supporting Oracle connections answers only part of that question.3
Read Oracle SQL from existing documents and generate MySQL SQLSQLGlot with explicit read="oracle" and write="mysql"How to handle unfamiliar functions, format strings, real table names, and divergent results.510
Add rules for a few known exceptionsModify recognized function arguments or table nodes. Keep an input and expected output for each exceptionWhich syntax structure the rule applies to and which literals must be preserved.

I wanted to know whether one set of business logic could run on SQL Server, MySQL, and Oracle. I checked Prisma's SQL Server support and read Oracle support discussions for Prisma and Drizzle. Prisma v6 already had SQL Server and MySQL connectors. Oracle remained a feature request. Even if an ORM could connect to every target, these legacy queries still required a transpiler capable of reading Oracle and emitting MySQL.11 For what can be shared in newly written logic, see Can SQLite and SQL Server share a data access layer?. I later compared the Oracle support, query styles, and migration approaches of four Node.js tools in How do you choose a Node.js ORM?.

Looking back, specialized dialect transpilers later appeared in the JavaScript ecosystem as well. The sqlingo project, which appeared in 2026, is implemented in TypeScript. Polyglot exposes a Rust/Wasm transpiler to JavaScript. Older intranet machines also need to be able to run the released package. For example the Polyglot SDK 0.10.0 manifest requires Node.js 22 or later, whereas I was considering 13.6.0. In a browser, I'd also need to check the loader and Wasm module requirements against the old Chrome version. Separating transpilation from execution means this constraint applies only to the machine that actually runs the transpiler.12

How do standard transpilation, custom rules, and AI corrections fit together?

I designed the assessment-query workflow in three layers.

  1. Standard transpilation. I extracted SQL from Markdown, checked the Oracle syntax, then asked SQLGlot to generate MySQL. Functions such as TO_DATE first went through the library's built-in rules.
  2. Custom transpilation. For recurring problems with unambiguous fixes, I put rules into the script. It rewrote date formats as above and source table names using the synchronization mapping, then checked the MySQL syntax. The batch script I actually ran reached this stage and wrote the results to translations.json.6
  3. AI correction as a fallback. Running the documents statement by statement revealed that some original SQL was wrong to begin with. Changing dialects or table names couldn't fix it. I remember adding a correction flow in which AI revised those statements based on the specific error and we tried running them again. Even when a query returned a result, I still needed to check what the numerator and denominator counted against the assessment definition.

Human review was part of that design. A reviewer compared the proposed correction against the original SQL and error. Yes ran the revised SQL on a trial basis. No sent it back for revision. A successful run then required a check against the indicator definition. An incorrect result went back for revision and another run. Once the run and definition both checked out, the query could be stored for that indicator and reused.

flowchart TD
    A["标准转写 · Oracle → MySQL"] --> B["自定义转写 · 日期格式和表名"]
    B --> C["检查并试跑 SQL"]
    C -->|报错| D["AI 提出修改建议"]
    D --> R{"人工审核修改"}
    R -->|Yes · 试跑| C
    R -->|No · 退回| D
    C -->|取得结果| E{"取数口径正确?"}
    E -->|是| F["查询定义入库"]
    E -->|否| G["按指标口径修订"] --> C

To reuse verified queries, I needed to store them alongside the indicator formulas. The management page for my batch query tool, SqlQueryManagement, used a FastAPI backend for these definitions. If an indicator used T2 / C2, for example, the backend stored the formula, variable names, and SQL for each variable using SQLAlchemy. The next time someone opened the page they could inspect and edit the definitions. I tested these features with local SQLite.13 My plan had been to deploy to a server running a newer Linux version after testing. As I remember it, the management service only reached testing and never ran in production on the hospital intranet.

The surviving script can generate conversion files independently, while the intranet execution tool has its own entry point. One possibility was to convert SQL first and then send it to the intranet Windows 7 machine to execute. I no longer remember whether that was how we divided the work. For how the tool reached colleagues, see a retrospective on the Windows 7 batch SQL tool.

Footnotes

  1. CaiBorui. (2025, May 28). Add SQL dialect function name convert feature [local Git commit bddfacb]. level5sql, convertSqlDialect in index.js. Oracle. (n.d.). NVL, SQL Language Reference 19c, Purpose. Argument types and implicit conversion. ↩

  2. devklick. (2022, May 13). Mimic COALESCE behaviour using groups of conditions when querying with Prisma client [Question]. Stack Overflow. Original date condition and null branches. Prisma. (n.d.). Raw queries, Prisma ORM v6 Documentation. Executing queries with $queryRaw. ↩

  3. SQLAlchemy authors. (n.d.). SQL expression language foundational constructs (ClauseElement.compile). SQLAlchemy 2.0 Documentation. Compiling an expression for a specified dialect. ↩ ↩2

  4. SQLAlchemy authors. (n.d.). Column elements and expressions (text). SQLAlchemy 2.0 Documentation. TextClause and textual SQL. ↩

  5. SQLGlot contributors. (n.d.). SQLGlot API documentation. SQLGlot. Formatting and Transpiling (accessed May 30, 2025, after searching for whether DBeaver could convert SQL dialects). SQLGlot contributors. (2025). SQLGlot 26.30.0 (Examples). PyPI. Version information and dialect conversion examples. ↩ ↩2

  6. CaiBorui. (2025, June 25). Add scripts for auto transpiling SQL dialects and replacing table names [local Git commit 9236bf6]. level5sql, pyscripts/run.py and pyscripts/transpile.py. Examples adapted from the actual problem. Original date-mask spellings retained and checked with SQLGlot 26.30.0. ↩ ↩2 ↩3 ↩4 ↩5 ↩6

  7. Oracle. (n.d.). Date and time functions (DATE_FORMAT, STR_TO_DATE). MySQL 8.0 Reference Manual. Format specifiers · STR_TO_DATE. ↩

  8. CaiBorui. (2025, June 25). Add scripts for auto transpiling SQL dialects and replacing table names [local Git commit 9236bf6]. level5sql, get_source_table_names and create_source_to_target_mapping in pyscripts/getTableNames.py. ↩ ↩2

  9. CaiBorui. (2025, June 24). Debugging table-name replacement and batch run logs [private development records]. Cursor table-replacement session and level5sql's pyscripts/log.txt and log2.txt. Code adapted from replace_table_names in the next day's commit 9236bf6, omitting internal names and log output. ↩ ↩2 ↩3

  10. SQLGlot contributors. (n.d.). SQLGlot API documentation (Unsupported Errors, para. 1). Handling unsupported conversions. ↩ ↩2

  11. Prisma. (n.d.). Supported databases, Prisma ORM v6 Documentation. Supported databases. ikdi. (2023, March 19). Add support for Oracle DB [Discussion #2442]. GitHub. Discussion of Oracle support. kanso-git. (2020, June 25). Support Oracle DB [Issue #2853]. GitHub. Oracle support request. ↩

  12. sqlingo contributors. (2026). sqlingo [TypeScript library]. GitHub. Project description. Polyglot contributors. (2026). @polyglot-sql/sdk 0.10.0 [package manifest, engines]. npm. Node version requirements. ↩

  13. CaiBorui [S2thend]. (2025, July 2). Add Python backend service [local Git commit b088abf]. SqlQueryManagement, server-py/src/sqlman/database/models.py and server-py/src/sqlman/api/endpoints.py. Commit 4a06444 added the companion web page that day. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-06-25). Converting Existing Oracle SQL to MySQL: Where Do SQLAlchemy and SQLGlot Fit?. https://caiborui.com/blog/2025-06-25-zh-oracle-to-mysql-sqlglot-sqlalchemy-entrans

@misc{borui2025-2b32e068,
  author = {borui},
  title = {{Converting Existing Oracle SQL to MySQL: Where Do SQLAlchemy and SQLGlot Fit?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-06-25-zh-oracle-to-mysql-sqlglot-sqlalchemy-entrans}
}