DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Taming Parameter Sniffing in SQL Server 2022 With PSP Optimization
  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance
  • The English WHERE Clause: Plain-English Filters in Couchbase SQL++ Using Jev Model
  • Grounding AI Agents in Governed Data

Trending

  • Claude Code Superpowers: The 5-Tool Stack That Ends Limits and Context Amnesia
  • How to Keep AI Agents From Going Rogue Using Docker Sandbox
  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance
  • Android Application Security: Android Application Architecture

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. Using the Mozilla SQL Parser — Part 1

Using the Mozilla SQL Parser — Part 1

In this part, see how the author used the Mozilla SQL Parser to perform some analyses using multiple articles.

By 
Bipin Patwardhan
·
Oct. 01, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
5.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Introduction

During a couple of project implementations, I have come across a couple of internal solutions that claim to convert one SQL dialect to another. For example, converting Oracle SQL to Hive SQL (HQL) or converting SQL server SQL to Snowflake. As per my observations of their working, most of them are glorified find and replace operations. I agree that such solutions manage to address a lot of conversions, claiming them to be enterprise grade solutions has to be taken with a pinch of salt.

I believe that the better approach is to - at the minimum - use an SQL parser to do the tedious task of SQL statement parsing and getting it converted into some data structure. Once we get the data structure, we will be in a position to navigate it as per our requirement.

Recently, I was part of a project that has a similar requirement - convert one SQL dialect to another dialect. This dialect change is needed as the project involves data platform change. Though this task was with another team, I took it as an opportunity to explore options. Initially, I looked at ANTLR4, which is quite well-known. ANTLR4 is a parser generator that needs to be provided a grammar of the language. It then generates the parser, which in turn can be used to read the input and create an internal data structure called AST (abstract syntax tree), which can be traversed and manipulated as per our requirement.

As I did not have sufficient time to delve into the details of ANTLR4, I continued looking for alternatives that were SQL specific. While I found a couple of options, I would like to mention three libraries I came across and used for initial exploration. The three libraries are JSQLParser, Presto Parser and Mozilla SQL Parser. While the first two libraries are Java based, I was surprised to find a Python package for parsing SQL Select statements developed by Mozilla. Yes the same organization that maintains the Firefox browser and The Thunderbird email client - both of which I use on a regular basis.

Mozilla SQL Parser

In this part, I will cover how I used the Mozilla SQL Parser to perform some analysis using multiple articles. I will cover Presto Parser in a separate article.

The Mozilla SQL Parser is available as a Python package. Before using it, we need to install it as

pip install moz-sql-parser

Now that the parser is installed, let us write a simple application to parse an SQL select statement. The code is as follows

Python
 




xxxxxxxxxx
1
20


 
1
from moz_sql_parser import parse
2
import json
3

          
4
def parse_query_and_display(query):
5
    print("----- query -----")
6
    print("")
7
    print("parsing - {}".format(query))
8
    parsedQuery = parse(query)
9
    jsonOutput = json.dumps(parsedQuery, indent=2)
10
    print("")
11
    print("output json - {}".format(jsonOutput))
12
    print("")
13

          
14
if __name__ == "__main__":
15
    query = "SELECT s_name from student where s_id in \
16
        (select s_id from student_course where c_id in \
17
        (select c_id from course where c_name = 'DSA' \
18
        and c_name = 'dbms' or c_name = 'algorithm'));"
19
    parse_query_and_display(query)
20

          



The Mozilla SQL Parser parses the SQL statement and converts it into a JSONified structure, that we are displaying using the parse_query_and_display method. On execution, the output is as shown below

JSON
 




xxxxxxxxxx
1
28


 
1
{
2
  "select": { "value": "s_name" },
3
  "from": "student",
4
  "where": {
5
    "in": [ "s_id", {
6
        "select": { "value": "s_id" },
7
        "from": "student_course",
8
        "where": {
9
          "in": [ "c_id", {
10
              "select": { "value": "c_id" },
11
              "from": "course",
12
              "where": {
13
                "or": [ {
14
                    "and": [
15
                      { "eq": [ "c_name", { "literal": "DSA" } ] },
16
                      { "eq": [ "c_name", { "literal": "dbms" } ] }
17
                    ]
18
                  },
19
                  { "eq": [ "c_name", { "literal": "algorithm" } ] }
20
                ]
21
              }
22
            }
23
          ]
24
        }
25
      }
26
    ]
27
  }
28
}



In the second part, I will cover how I navigated the structure to identify tables in the "from" clause of the SQL statement.

sql Parser (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Taming Parameter Sniffing in SQL Server 2022 With PSP Optimization
  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance
  • The English WHERE Clause: Plain-English Filters in Couchbase SQL++ Using Jev Model
  • Grounding AI Agents in Governed Data

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook