To solve this problem, we'll create a Python program that acts as a simple SQL query engine for JSON data. The program will:
-
Parse the SQL Query: We'll manually parse the SQL query to extract different clauses such as SELECT, FROM, WHERE, JOIN, GROUP BY, ORDER BY, and LIMIT.
-
Load JSON Data: We'll load the JSON files (products_public.json, users_public.json, reviews_public.json, transactions_public.json) into pandas DataFrames for easy manipulation.
-
Execute the Query:
- FROM and JOIN: Identify the base table and perform any necessary INNER JOINs.
- WHERE: Apply filtering conditions.
- GROUP BY and Aggregations: Perform grouping and apply aggregate functions like
COUNT, SUM, AVG, MIN, MAX.
- ORDER BY: Sort the results based on specified columns.
- LIMIT: Restrict the number of output rows.
-
Format the Output: Convert the final DataFrame into the required string format with comma-separated values and newline separators.
Here's the complete Python program that accomplishes the above steps:
import json
import pandas as pd
import sys
import os
import re
from decimal import Decimal, ROUND_HALF_UP
def read_json_files():
current_directory = os.getcwd()
files = os.listdir(current_directory)
data = {}
for file in files:
if file.endswith('_public.json'):
table_name = file.split('_public.json')[0]
with open(os.path.join(current_directory, file), 'r') as f:
data[table_name] = pd.DataFrame(json.load(f))
return data
def parse_query(query):
# Remove extra spaces and newlines
query = ' '.join(query.strip().split())
# Regex patterns for different clauses
select_pattern = r'SELECT (.+?) FROM'
from_pattern = r'FROM (\w+)(?:\s+(\w+))?'
join_pattern = r'JOIN (\w+)(?:\s+(\w+))? ON (.+?)(?: WHERE| GROUP BY| ORDER BY| LIMIT|$)'
where_pattern = r'WHERE (.+?)(?: GROUP BY| ORDER BY| LIMIT|$)'
group_by_pattern = r'GROUP BY (.+?)(?: ORDER BY| LIMIT|$)'
order_by_pattern = r'ORDER BY (.+?)(?: LIMIT|$)'
limit_pattern = r'LIMIT (\d+)'
select_clause = re.search(select_pattern, query, re.IGNORECASE)
from_clause = re.search(from_pattern, query, re.IGNORECASE)
join_clause = re.search(join_pattern, query, re.IGNORECASE)
where_clause = re.search(where_pattern, query, re.IGNORECASE)
group_by_clause = re.search(group_by_pattern, query, re.IGNORECASE)
order_by_clause = re.search(order_by_pattern, query, re.IGNORECASE)
limit_clause = re.search(limit_pattern, query, re.IGNORECASE)
parsed = {}
if select_clause:
parsed['SELECT'] = select_clause.group(1).strip()
if from_clause:
parsed['FROM'] = {'table': from_clause.group(1).strip(), 'alias': from_clause.group(2).strip() if from_clause.group(2) else from_clause.group(1).strip()}
if join_clause:
parsed['JOIN'] = {'table': join_clause.group(1).strip(), 'alias': join_clause.group(2).strip() if join_clause.group(2) else join_clause.group(1).strip(), 'condition': join_clause.group(3).strip()}
if where_clause:
parsed['WHERE'] = where_clause.group(1).strip()
if group_by_clause:
parsed['GROUP BY'] = [x.strip() for x in group_by_clause.group(1).split(',')]
if order_by_clause:
order_terms = [x.strip() for x in order_by_clause.group(1).split(',')]
parsed['ORDER BY'] = []
for term in order_terms:
parts = term.split()
if len(parts) == 1:
parsed['ORDER BY'].append({'column': parts[0], 'order': 'ASC'})
else:
parsed['ORDER BY'].append({'column': parts[0], 'order': parts[1].upper()})
if limit_clause:
parsed['LIMIT'] = int(limit_clause.group(1).strip())
return parsed
def handle_aliases(data, from_alias, join_alias):
# Rename columns with aliases
data[from_alias] = data[from_alias].copy()
data[from_alias].columns = [f"{from_alias}.{col}" for col in data[from_alias].columns]
if join_alias:
data[join_alias] = data[join_alias].copy()
data[join_alias].columns = [f"{join_alias}.{col}" for col in data[join_alias].columns]
return data
def apply_where(df, where_clause):
# This is a simple WHERE parser handling AND and OR with basic conditions
# It does not handle parentheses or complex expressions
# Split by AND first
conditions = re.split(r'\s+AND\s+', where_clause, flags=re.IGNORECASE)
for cond in conditions:
or_conditions = re.split(r'\s+OR\s+', cond, flags=re.IGNORECASE)
if len(or_conditions) > 1:
# Apply OR logic
mask = False
for or_cond in or_conditions:
mask |= evaluate_condition(df, or_cond)
df = df[mask]
else:
df = df[evaluate_condition(df, cond)]
return df
def evaluate_condition(df, condition):
# Supports '=', '!=', '>', '<', '>=', '<='
match = re.match(r"(.+?)(=|!=|>|<|>=|<=)'?(.+?)'?$", condition)
if not match:
match = re.match(r"(.+?)(=|!=|>|<|>=|<=)(.+)$", condition)
if not match:
return pd.Series([True]*len(df)) # If condition not recognized, ignore it
left, operator, right = match.groups()
left = left.strip()
right = right.strip().strip("'")
if left not in df.columns:
return pd.Series([False]*len(df)) # Column does not exist
# Attempt to convert right to numeric if possible
try:
right_val = float(right)
except:
right_val = right
if operator == '=':
return df[left] == right_val
elif operator == '!=':
return df[left] != right_val
elif operator == '>':
return df[left] > right_val
elif operator == '<':
return df[left] < right_val
elif operator == '>=':
return df[left] >= right_val
elif operator == '<=':
return df[left] <= right_val
else:
return pd.Series([False]*len(df))
def parse_select(select_clause):
# Split by comma, handle AS
select_items = [x.strip() for x in select_clause.split(',')]
select_parsed = []
for item in select_items:
as_match = re.match(r'(.+?)\s+AS\s+(.+)', item, re.IGNORECASE)
if as_match:
expr, alias = as_match.groups()
select_parsed.append({'expr': expr.strip(), 'alias': alias.strip()})
else:
select_parsed.append({'expr': item, 'alias': item})
return select_parsed
def apply_select(df, select_parsed):
select_columns = []
aggregations = {}
for item in select_parsed:
expr = item['expr']
alias = item['alias']
agg_match = re.match(r'(COUNT|SUM|AVG|MIN|MAX)\((.+)\)', expr, re.IGNORECASE)
if agg_match:
func, col = agg_match.groups()
func = func.upper()
aggregations[alias] = {'func': func, 'col': col.strip()}
else:
select_columns.append({'expr': expr, 'alias': alias})
if aggregations and not df.empty:
agg_dict = {}
for alias, details in aggregations.items():
func = details['func']
col = details['col']
if func == 'COUNT':
agg_dict[alias] = (col, 'count')
elif func == 'SUM':
agg_dict[alias] = (col, 'sum')
elif func == 'AVG':
agg_dict[alias] = (col, 'mean')
elif func == 'MIN':
agg_dict[alias] = (col, 'min')
elif func == 'MAX':
agg_dict[alias] = (col, 'max')
aggregated = df.agg(**agg_dict).to_frame().T
# Handle rounding for SUM, AVG, MIN, MAX if they are double
for alias, details in aggregations.items():
func = details['func']
col = details['col']
if func in ['SUM', 'AVG', 'MIN', 'MAX']:
# Check if column is of type float
if pd.api.types.is_float_dtype(df[col]):
aggregated[alias] = aggregated[alias].apply(lambda x: f"{Decimal(x).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)}")
return aggregated.rename(columns=lambda x: x).reset_index(drop=True)
else:
selected_df = pd.DataFrame()
for item in select_columns:
expr = item['expr']
alias = item['alias']
if expr == '*':
selected_df = df.copy()
selected_df.columns = [alias if col == '*' else col for col in selected_df.columns]
else:
selected_df[alias] = df[expr]
return selected_df
def format_output(df, select_parsed):
# First line: column names in the order of select_parsed
headers = [item['alias'] for item in select_parsed]
output = ','.join(headers)
# Subsequent lines: rows
rows = []
for _, row in df.iterrows():
formatted_row = []
for item in select_parsed:
alias = item['alias']
val = row[alias]
if isinstance(val, float):
val = f"{Decimal(val).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)}"
val = format(val, 'f') # Remove scientific notation
formatted_row.append(str(val))
rows.append(','.join(formatted_row))
if rows:
output += '\n' + '\n'.join(rows)
return output
def main():
# Read JSON files
data = read_json_files()
# Read SQL query from standard input
query = sys.stdin.read()
# Parse the query
parsed = parse_query(query)
# Handle FROM and JOIN
if 'FROM' not in parsed:
print("No FROM clause found.")
return
from_table = parsed['FROM']['table']
from_alias = parsed['FROM']['alias']
data_subset = {}
data_subset[from_alias] = data[from_table]
if 'JOIN' in parsed:
join_table = parsed['JOIN']['table']
join_alias = parsed['JOIN']['alias']
join_condition = parsed['JOIN']['condition']
data_subset[join_alias] = data[join_table]
# Merge the dataframes based on join_condition
# Assume join_condition is in the form a.col1 = b.col2
join_match = re.match(r'(\w+\.\w+)\s*=\s*(\w+\.\w+)', join_condition)
if not join_match:
print("Unsupported JOIN condition.")
return
left, right = join_match.groups()
left_table, left_col = left.split('.')
right_table, right_col = right.split('.')
left_df = data_subset[left_table]
right_df = data_subset[right_table]
merged_df = pd.merge(left_df, right_df, left_on=left_col, right_on=right_col, how='inner', suffixes=('_left', '_right'))
data_subset = merged_df
else:
data_subset = data_subset[from_alias]
# Handle aliases in column names
if isinstance(data_subset, pd.DataFrame):
pass # No join, columns are as is
else:
# Joined dataframe
pass # Already merged
df = data_subset.copy()
# Apply WHERE clause
if 'WHERE' in parsed:
df = apply_where(df, parsed['WHERE'])
# Apply GROUP BY
if 'GROUP BY' in parsed:
group_by_cols = parsed['GROUP BY']
# Ensure all group_by_cols are in df
df_grouped = df.groupby(group_by_cols)
# Apply select (including aggregations)
select_parsed = parse_select(parsed['SELECT'])
aggregated = apply_select(df, select_parsed)
df = aggregated
else:
# Apply select
select_parsed = parse_select(parsed['SELECT'])
df = apply_select(df, select_parsed)
# Apply ORDER BY
if 'ORDER BY' in parsed:
order_by = parsed['ORDER BY']
sort_columns = [item['column'] for item in order_by]
ascending = [True if item['order'] == 'ASC' else False for item in order_by]
df = df.sort_values(by=sort_columns, ascending=ascending)
# Apply LIMIT
if 'LIMIT' in parsed:
limit = parsed['LIMIT']
df = df.head(limit)
# Format the output
if 'GROUP BY' in parsed:
select_parsed = parse_select(parsed['SELECT'])
else:
select_parsed = parse_select(parsed['SELECT'])
output = format_output(df, select_parsed)
print(output)
if __name__ == "__main__":
main()
Explanation of the Code
-
Reading JSON Files (read_json_files):
- The program reads all JSON files ending with
_public.json in the current directory.
- It loads each JSON file into a pandas DataFrame and stores them in a dictionary with the table name as the key.
-
Parsing the SQL Query (parse_query):
- The SQL query is parsed using regular expressions to extract different components like
SELECT, FROM, JOIN, WHERE, GROUP BY, ORDER BY, and LIMIT.
- Table aliases are handled to map the actual table names.
-
Handling Aliases and Joins:
- If there's a
JOIN clause, the program performs an INNER JOIN based on the specified condition.
- The join condition is expected to be in the format
table1.column1 = table2.column2.
-
Applying WHERE Clause (apply_where and evaluate_condition):
- The program can handle simple
WHERE conditions with AND and OR.
- It evaluates each condition and filters the DataFrame accordingly.
-
Parsing and Applying SELECT Clause (parse_select and apply_select):
- The
SELECT clause is parsed to identify columns and any aggregate functions.
- Aggregate functions like
COUNT, SUM, AVG, MIN, and MAX are applied as needed.
- The results are formatted, especially ensuring that floating-point numbers have two decimal places.
-
Handling GROUP BY:
- If a
GROUP BY clause is present, the program groups the DataFrame accordingly and applies the necessary aggregations.
-
Applying ORDER BY and LIMIT:
- The results can be sorted based on specified columns in ascending or descending order.
- The
LIMIT clause restricts the number of output rows.
-
Formatting the Output (format_output):
Assumptions and Constraints
- The SQL parser is simplistic and assumes that the query follows standard formatting without nested queries or complex expressions.
- Only INNER JOINs are supported.
- Aggregate functions are limited to one column as specified.
- The program does not handle SQL injection or malicious inputs.
Usage
To use the program:
-
Ensure that the JSON files (products_public.json, users_public.json, reviews_public.json, transactions_public.json) are present in the same directory as the script.
-
Run the Python script and provide the SQL query via standard input. For example:
echo "SELECT p.id AS product_id, p.name AS product_name FROM products p WHERE p.price > 10.00 ORDER BY product_id ASC" | python sql_engine.py
This will output the results in the specified format.