More SQL Parsing!

11.697.25301 · active · verified Thu Apr 16

mo-sql-parsing is a Python library designed to parse SQL queries into a JSON-izable parse tree. It aims to convert various SQL dialects, initially targeting MySQL, into a structured JSON format, making it easier to translate or analyze SQL for different datastores. As of version 11.697.25301, the library is actively maintained, with ongoing issue resolution and regular updates, as indicated by its high version number and recent activity on GitHub (October 2024 Project Status).

Common errors

Warnings

Install

Imports

Quickstart

The `mo_sql_parsing` library's primary function is `parse`, which takes a SQL string and returns a JSON-like Python dictionary representing the parse tree. Specialized parsers like `parse_sqlserver` and `parse_mysql` are available for dialect-specific syntax.

from mo_sql_parsing import parse

# Basic SELECT query
sql_query = "select count(1) from jobs"
parsed_json = parse(sql_query)
print(f"Parsed basic query: {parsed_json}")
# Expected: {'select': {'value': {'count': 1}}, 'from': 'jobs'}

# SELECT with aliases
sql_query_aliases = "select a as hello, b as world from jobs"
parsed_json_aliases = parse(sql_query_aliases)
print(f"Parsed query with aliases: {parsed_json_aliases}")
# Expected: {'select': [{'value': 'a', 'name': 'hello'}, {'value': 'b', 'name': 'world'}], 'from': 'jobs'}

# Example with SQLServer-specific parsing
from mo_sql_parsing import parse_sqlserver
sqlserver_query = "SELECT [Timestamp] FROM [table]"
parsed_sqlserver = parse_sqlserver(sqlserver_query)
print(f"Parsed SQLServer query: {parsed_sqlserver}")
# Expected: {'select': 'Timestamp', 'from': 'table'}

view raw JSON →