Using the Mozilla SQL Parser — Part 2
Join the DZone community and get the full member experience.Join For Free
In the Using the Mozilla SQL Parser — Part 1 article on Mozilla SQL Parser, we covered how the moz-sql-parser package can be used to parse an SQL Select statement into a JSONified structure. In this part, we will cover how to extract names of the tables mentioned in the '
from' clause of the query.
The SQL we are using is
To parse this query, we use
parsed_query = parse(query)
parse is a method provided by the moz_sql_parser.
After parsing, the module generates a JSONified structure, as given below.
After parsing, the JSONified structure contains three main keys, namely '
from' and '
To extract names of tables, we will extract them from the '
from' clause. For this, we define a method named '
get_from_clause_tables'. To hold the table names and the table name aliases, we define two dictionaries, named
get_from_clause_tables' method is
In the method, we are checking the data type of the
from clause. We need to check the instance type of the
from_clause variable, due to the way the data table names are stored in the JSONified structure.
string-- If the
from_clausehas only one table, its data type is
stringand the '
from_clause' is nothing but the name of the table mentioned in the
fromclause of the query.
list-- If the
from_clausehas multiple tables, its data type is
dictionary), that contains names of the tables mentioned in the
fromclause. If the table has an alias, the entry is of type dictionary. If the table does not have an alias, the entry is of type string.
In the '
get_from_clause_tables' method, we are collecting the names of the tables used and their usage frequency. We are also collecting the alias names of the table and their usage frequency.
Upon execution, we get the output as
In this part, we covered how to extract names of tables given in the
from clause. In the next part (part three), we will cover how to extract tables mentioned in the
Opinions expressed by DZone contributors are their own.