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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  • SQL Server Index Optimization Strategies: Best Practices with Ola Hallengren’s Scripts
  • How to Restore a Transaction Log Backup in SQL Server
  • How to Attach SQL Database Without a Transaction Log File

Trending

  • Integrating Security as Code: A Necessity for DevSecOps
  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  • Building Scalable and Resilient Data Pipelines With Apache Airflow
  • Issue and Present Verifiable Credentials With Spring Boot and Android
  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 user avatar
Bipin Patwardhan
·
Oct. 01, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
5.4K 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.

Related

  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  • SQL Server Index Optimization Strategies: Best Practices with Ola Hallengren’s Scripts
  • How to Restore a Transaction Log Backup in SQL Server
  • How to Attach SQL Database Without a Transaction Log File

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!