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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • DZone's Article Submission Guidelines
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • Comparing Cloud Hosting vs. Self Hosting
  • Observability Architecture: Financial Payments Introduction

Trending

  • DZone's Article Submission Guidelines
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • Comparing Cloud Hosting vs. Self Hosting
  • Observability Architecture: Financial Payments Introduction
  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.

Bipin Patwardhan user avatar by
Bipin Patwardhan
·
Oct. 01, 20 · Tutorial
Like (3)
Save
Tweet
Share
4.66K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Trending

  • DZone's Article Submission Guidelines
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • Comparing Cloud Hosting vs. Self Hosting
  • Observability Architecture: Financial Payments Introduction

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: