Problem Statement
You are given 4 JSON files named products, reviews, users, transactions that contains information about various products sold by an e-commerce company, user information, reviews written by users and all transactions made on the products.
Your task is to develop a SQL query engine that can execute SQL queries on JSON data. The engine is expected to handle the following types of queries -
• SELECT
• WHERE
• JOIN (INNER type only)
• GROUP BY
• ORDER BY
• LIMIT
• Aggregate functions (COUNT(*), AVG, SUM, MIN, MAX)
•
The SQL query will be provided as input will always follow the syntax below. The way to read the syntax definition is - square brackets [ ] indicate optional presence of that element in the query and curly braces { } indicates mandatory where applicable. Pipe | separated values indicates any one of the options. ... indicates one or many such elements can exist.
SELECT {table_alias | join_table_alias}.col_name AS column_alias, … FROM table table_alias [ JOIN table join_table_alias on joinexpr [AND joinexpr ... ] ] … [WHERE expr [AND expr ... ] ] [GROUP BY {table_alias.col_name, … }] ORDER BY {column_alias, … } { ASC | DESC } [LIMIT n]
The joinexpr in JOIN can have multiple conditions, however it will be always AND clauses. One condition will always be of form below,
{table_alias | join_table_alias}.col_name = {value | {table_alias | join_table_alias}.col_name}}
The expr in WHERE can have multiple conditions, however it will be always AND clauses. One condition will always be of form below,
{table_alias | join_table_alias}.col_name {operator} {value}
The supported operators in WHERE expr for the engine are the ones below only:
• = (equals)
• <> (not equals)
• > (greater than)
• >= (greater than or equal to )
• < (less than)
• <= (less than or equal to)
Supported aggregations:
1 COUNT(*)
◦ provides the count of rows in the result set.
◦ Result must be integer type
2 SUM( {table_alias|join_table_alias}.col_name )
◦ Only one column supported
◦ For Double column, result must be rounded to 2 decimal places and always have 2 decimal places
3 AVG( {table_alias|join_table_alias}.col_name )
◦ Only one column supported
◦ For Double column, result must be rounded to 2 decimal places and always have 2 decimal places
4 MIN( {table_alias|join_table_alias}.col_name )
◦ Only one column supported
◦ For Double column, result must be rounded to 2 decimal places and always have 2 decimal places
5 MAX( {table_alias|join_table_alias}.col_name )
◦ Only one column supported
◦ For Double column, result must be rounded to 2 decimal places and always have 2 decimal places
The engine will be tested with four JSON files: products, reviews, users, transactions with each file representing a table name.
Input Format
Data Files
Data Files are available in your program current directory :
• products_public.json
• users_public.json
• reviews_public.json
• transactions_public.json
Sample Input
The input will be the below string available in standard input:
SELECT p.id AS product_id, p.name AS product_name FROM products p WHERE p.price > 10.00 ORDER BY product_id ASC
Assistant
Reading the Input
You can read the input SQL query as standard input.
To read the data files (e.g. products_public.json, user_public.json ... etc) , you can use some of the below code snippets:
Python
current_directory = os.getcwd()
files = os.listdir(current_directory) // Get all files in the directory
Constraints
Product attributes:
• id: Unique product id, type: int32, constraint: unique in file
• name: Product name, type: string, constraint: none
• category: Product category, type: string, constraint: none
• price: Price of the product, type: double, constraint: positive with 2 decimal precision
User attributes:
• user_id: Unique user id, type: int32, constraint: unique in file
• name: User name, type: string, constraint: none
• age: Age of the user, type: int32, constraint: positive number
• location: City of the user, type: string, constraint: none
Review attributes:
• product_id: Id of product, type: int32, constraint: part of unique key in file
• user_id: Id of user, type: int32, constraint: part of unique key in file
• rating: Rating by user, type: int32, constraint: 0 - 5 both inclusive
• comment: Comment by user, type: string, constraint: none
Transaction attributes:
• transaction_id: Unique id of transaction, type: int32, constraint: unique in file
• product_id: Id of product, type: int32, constraint: none
• user_id: Id of user, type: int32, constraint: none
• price: Price at which 1 unit of product was sold, type: double, constraint: positive with 2 decimal precision
• quantity: Total units bought, type: int32, constraint: positive number
• date: Date when transaction happened, type: string, constraint: format YYYY-MM-DD
• total_amount: Quantity * price, type: double, constraint: always greater than 0
Output Format
Guidelines
• The output must be a string
• Since we expect several rows and columns, essentially a tabular output, please use comma separator with no spaces before and after to separate out columns and line separator \n to separate out rows.
• the first line of the output must be the column names expected in the result, separated by comma with no spaces before and after. The order of the column names also matters and must match with what is provided in SQL query input.
Make an AST and make sure to think of alias
also use this [json.loads(line) for line in f]
dont use external libraries
To develop a SQL query engine that operates on JSON data files (products_public.json, users_public.json, reviews_public.json, transactions_public.json), we'll use Python's standard libraries. The engine will parse the SQL query, execute it against the JSON data, and produce the desired output.
Below is a comprehensive Python script that accomplishes this task:
python
import json
import os
import sys
import re
from collections import defaultdict
from copy import deepcopy
def load_json_table(filename):
with open(filename, 'r') as f:
data = [json.loads(line) for line in f]
return data
def parse_sql(query):
# Regex patterns for different clauses
select_pattern = r'SELECT\s+(.*?)\s+FROM\s+'
from_pattern = r'FROM\s+(\w+)\s+(\w+)'
join_pattern = r'JOIN\s+(\w+)\s+(\w+)\s+ON\s+([^WHEREGROUPORDERLIMIT]*)'
where_pattern = r'WHERE\s+([^GROUPORDERLIMIT]*)'
group_by_pattern = r'GROUP\s+BY\s+([^ORDERLIMIT]*)'
order_by_pattern = r'ORDER\s+BY\s+([^LIMIT]*)'
limit_pattern = r'LIMIT\s+(\d+)'
# Extract SELECT clause
select_match = re.search(select_pattern, query, re.IGNORECASE)
if not select_match:
raise Exception("Invalid SQL: SELECT clause not found")
select_clause = select_match.group(1).strip()
# Extract FROM clause
from_match = re.search(from_pattern, query, re.IGNORECASE)
if not from_match:
raise Exception("Invalid SQL: FROM clause not found")
from_table, from_alias = from_match.group(1), from_match.group(2)
# Extract JOIN clauses
joins = []
for join in re.finditer(join_pattern, query, re.IGNORECASE):
join_table, join_alias, join_conditions = join.group(1), join.group(2), join.group(3).strip()
conditions = [cond.strip() for cond in join_conditions.split('AND')]
joins.append({'table': join_table, 'alias': join_alias, 'conditions': conditions})
# Extract WHERE clause
where_clause = None
where_match = re.search(where_pattern, query, re.IGNORECASE)
if where_match:
where_clause = [cond.strip() for cond in where_match.group(1).strip().split('AND')]
# Extract GROUP BY clause
group_by = None
group_by_match = re.search(group_by_pattern, query, re.IGNORECASE)
if group_by_match:
group_by = [col.strip() for col in group_by_match.group(1).strip().split(',')]
# Extract ORDER BY clause
order_by = None
order = 'ASC'
order_by_match = re.search(order_by_pattern, query, re.IGNORECASE)
if order_by_match:
order_by = [col.strip() for col in order_by_match.group(1).strip().split(',')]
# Check for ASC or DESC
order_direction = re.search(r'(ASC|DESC)', query, re.IGNORECASE)
if order_direction:
order = order_direction.group(1).upper()
# Extract LIMIT clause
limit = None
limit_match = re.search(limit_pattern, query, re.IGNORECASE)
if limit_match:
limit = int(limit_match.group(1))
# Parse SELECT columns
select_columns = []
agg_functions = {}
for col in select_clause.split(','):
col = col.strip()
# Check for AS alias
if ' AS ' in col.upper():
col_expr, alias = re.split(r'\s+AS\s+', col, flags=re.IGNORECASE)
else:
col_expr = col
alias = col
# Check for aggregation functions
agg_match = re.match(r'(COUNT|SUM|AVG|MIN|MAX)\((\*|\w+\.\w+)\)', col_expr, re.IGNORECASE)
if agg_match:
func, operand = agg_match.group(1).upper(), agg_match.group(2)
agg_functions[alias] = {'func': func, 'operand': operand}
else:
select_columns.append({'expr': col_expr, 'alias': alias})
return {
'select': select_columns,
'aggregates': agg_functions,
'from': {'table': from_table, 'alias': from_alias},
'joins': joins,
'where': where_clause,
'group_by': group_by,
'order_by': order_by,
'order': order,
'limit': limit
}
def build_table_map(tables):
table_map = {}
for table in tables:
table_map[table['alias']] = table['data']
return table_map
def apply_join(left_table, left_alias, right_table, right_alias, conditions):
joined = []
for left_row in left_table:
for right_row in right_table:
match = True
for cond in conditions:
# Condition format: alias.col = alias.col or alias.col = value
m = re.match(r'(\w+\.\w+)\s*=\s*(\w+\.\w+|\S+)', cond)
if not m:
match = False
break
left_cond, right_cond = m.group(1), m.group(2)
# Parse left condition
left_alias_cond, left_col = left_cond.split('.')
left_val = left_row[left_col]
# Parse right condition
if '.' in right_cond:
right_alias_cond, right_col = right_cond.split('.')
# Fetch from right row
right_val = right_row[right_col]
else:
# It's a value (could be string or number)
right_val = parse_value(right_cond)
if left_val != right_val:
match = False
break
if match:
# Merge the two rows with aliases
merged = {}
for k, v in left_row.items():
merged[f"{left_alias}.{k}"] = v
for k, v in right_row.items():
merged[f"{right_alias}.{k}"] = v
joined.append(merged)
return joined
def parse_value(val):
# Remove quotes if present
if val.startswith("'") and val.endswith("'"):
return val[1:-1]
elif val.startswith('"') and val.endswith('"'):
return val[1:-1]
else:
# Try to convert to int or float
try:
if '.' in val:
return float(val)
else:
return int(val)
except:
return val
def apply_where(rows, where_clause):
if not where_clause:
return rows
filtered = []
for row in rows:
match = True
for cond in where_clause:
# Condition format: alias.col operator value
m = re.match(r'(\w+\.\w+)\s*(=|<>|>=|<=|>|<)\s*(.+)', cond)
if not m:
match = False
break
col, op, val = m.group(1), m.group(2), m.group(3)
val = parse_value(val)
# Get the value from the row
if col not in row:
match = False
break
row_val = row[col]
# Compare based on operator
if op == '=':
if row_val != val:
match = False
break
elif op == '<>':
if row_val == val:
match = False
break
elif op == '>':
if not (row_val > val):
match = False
break
elif op == '>=':
if not (row_val >= val):
match = False
break
elif op == '<':
if not (row_val < val):
match = False
break
elif op == '<=':
if not (row_val <= val):
match = False
break
if match:
filtered.append(row)
return filtered
def apply_group_by(rows, group_by):
if not group_by:
return {'all': rows}
grouped = defaultdict(list)
for row in rows:
key = tuple(row[col] for col in group_by)
grouped[key].append(row)
return grouped
def apply_select(group_rows, select_columns, aggregates, aliases):
results = []
for alias, rows in group_rows.items():
result_row = {}
# Handle aggregate functions
for alias_name, agg in aggregates.items():
func = agg['func']
operand = agg['operand']
if operand == '*':
values = rows
else:
values = [r[operand] for r in rows]
if func == 'COUNT':
result_row[alias_name] = len(values)
elif func == 'SUM':
result_row[alias_name] = round(sum(values), 2)
result_row[alias_name] = f"{result_row[alias_name]:.2f}"
elif func == 'AVG':
avg = sum(values) / len(values) if len(values) > 0 else 0
result_row[alias_name] = round(avg,2)
result_row[alias_name] = f"{result_row[alias_name]:.2f}"
elif func == 'MIN':
min_val = min(values) if values else None
if isinstance(min_val, float):
min_val = round(min_val,2)
min_val = f"{min_val:.2f}"
result_row[alias_name] = min_val
elif func == 'MAX':
max_val = max(values) if values else None
if isinstance(max_val, float):
max_val = round(max_val,2)
max_val = f"{max_val:.2f}"
result_row[alias_name] = max_val
# Handle selected columns
for col in select_columns:
expr = col['expr']
alias_name = col['alias']
if expr in rows[0]:
result_row[alias_name] = rows[0][expr]
else:
result_row[alias_name] = None
results.append(result_row)
return results
def apply_order_by(results, order_by, order):
if not order_by:
return results
reverse = True if order == 'DESC' else False
for col in reversed(order_by):
results.sort(key=lambda x: x[col], reverse=reverse)
return results
def apply_limit(results, limit):
if limit is None:
return results
return results[:limit]
def main():
# Read SQL query from standard input
query = sys.stdin.read().strip()
# Parse the SQL
parsed_sql = parse_sql(query)
# Load all tables
current_directory = os.getcwd()
tables = []
table_files = {
'products': 'products_public.json',
'users': 'users_public.json',
'reviews': 'reviews_public.json',
'transactions': 'transactions_public.json'
}
for tbl in ['products', 'users', 'reviews', 'transactions']:
filename = table_files[tbl]
filepath = os.path.join(current_directory, filename)
data = load_json_table(filepath)
tables.append({'table': tbl, 'alias': parsed_sql['from']['alias'] if tbl == parsed_sql['from']['table'] else None, 'data': data})
# Update aliases correctly
for join in parsed_sql['joins']:
for tbl in tables:
if tbl['table'] == join['table'] and tbl['alias'] is None:
tbl['alias'] = join['alias']
# Create table map
table_map = {}
for tbl in tables:
table_map[tbl['alias']] = tbl['data']
# Start with FROM table
from_alias = parsed_sql['from']['alias']
current_rows = deepcopy(table_map[from_alias])
# Prefix columns with alias
prefixed_rows = []
for row in current_rows:
prefixed = {}
for k, v in row.items():
prefixed[f"{from_alias}.{k}"] = v
prefixed_rows.append(prefixed)
current_rows = prefixed_rows
# Apply JOINs
for join in parsed_sql['joins']:
join_alias = join['alias']
join_table = join['table']
join_conditions = join['conditions']
right_table = deepcopy(table_map[join_alias])
# Prefix columns with alias
prefixed_right = []
for row in right_table:
prefixed = {}
for k, v in row.items():
prefixed[f"{join_alias}.{k}"] = v
prefixed_right.append(prefixed)
current_rows = apply_join(current_rows, from_alias, prefixed_right, join_alias, join_conditions)
# Apply WHERE clause
current_rows = apply_where(current_rows, parsed_sql['where'])
# Apply GROUP BY
grouped = apply_group_by(current_rows, parsed_sql['group_by'])
# Apply SELECT and Aggregations
select_columns = parsed_sql['select']
aggregates = parsed_sql['aggregates']
results = apply_select(grouped, select_columns, aggregates, select_columns)
# Apply ORDER BY
results = apply_order_by(results, parsed_sql['order_by'], parsed_sql['order'])
# Apply LIMIT
results = apply_limit(results, parsed_sql['limit'])
# Prepare Output
# Determine the header
header = []
for col in select_columns:
header.append(col['alias'])
for alias in aggregates.keys():
header.append(alias)
# To maintain the order as per the SELECT clause
if aggregates:
# Replace header with SELECT aliases followed by aggregates
header = [col['alias'] for col in select_columns]
for alias in aggregates.keys():
header.append(alias)
print(','.join(header))
# Print rows
for row in results:
row_values = []
for col in header:
val = row.get(col, '')
if isinstance(val, float):
val = f"{val:.2f}"
row_values.append(str(val))
print(','.join(row_values))
if __name__ == "__main__":
main()
Explanation of the Code
Loading JSON Data:
The load_json_table function reads each JSON file line by line and loads it into a list of dictionaries.
Parsing the SQL Query:
The parse_sql function uses regular expressions to dissect the SQL query into its constituent parts: SELECT, FROM, JOIN, WHERE, GROUP BY, ORDER BY, and LIMIT.
It also identifies any aggregate functions present in the SELECT clause.
Building Table Maps and Applying Joins:
After loading all relevant tables, the script builds a mapping of table aliases to their data.
The apply_join function performs inner joins based on the specified conditions.
Filtering with WHERE Clause:
The apply_where function filters rows based on the conditions provided in the WHERE clause.
Grouping Data:
If a GROUP BY clause is present, the apply_group_by function groups the data accordingly.
Selecting Columns and Applying Aggregates:
The apply_select function handles the selection of columns and the computation of aggregate functions like COUNT, SUM, AVG, MIN, and MAX.
Ordering and Limiting Results:
The apply_order_by function sorts the results based on the ORDER BY clause.
The apply_limit function restricts the number of output rows if a LIMIT is specified.
Generating the Output:
The script prints the column headers followed by the result rows, adhering to the specified output format.
Assumptions and Constraints
Aliases: The script assumes that all table aliases used in the SQL query are correctly mapped and that column references are fully qualified with their respective aliases.
Aggregate Functions: Only one aggregate function per column is supported, and aggregation is performed after grouping.
Data Types: The script handles data types as per the constraints specified, such as rounding double types to two decimal places.
No External Libraries: Apart from Python's standard libraries (json, os, sys, re, collections, copy), no external libraries are used.
How to Use the Script
Prepare the JSON Files:
Ensure that the JSON files (products_public.json, users_public.json, reviews_public.json, transactions_public.json) are present in the current working directory.
Run the Script:
You can execute the script by passing the SQL query through standard input. For example:
bash
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
Output:
The script will output the results in the specified comma-separated format, starting with the column headers.
Sample Input and Output
Sample Input:
sql
SELECT p.id AS product_id, p.name AS product_name FROM products p WHERE p.price > 10.00 ORDER BY product_id ASC
Sample Output:
code
product_id,product_name
1,Product A
2,Product B
3,Product C
Note: The actual output will depend on the data present in your JSON files.
Handling Edge Cases
No Matching Rows: If the WHERE clause filters out all rows, the script will output only the headers with no subsequent data rows.
Invalid SQL Queries: The script includes basic error handling for missing clauses, but it assumes that the SQL syntax adheres to the defined structure.
Conclusion
This Python script provides a foundational SQL query engine capable of executing basic SQL queries with SELECT, WHERE, JOIN, GROUP BY, ORDER BY, LIMIT, and aggregate functions on JSON data files. While it covers the specified requirements, further enhancements can be made to handle more complex SQL features and optimize performance for larger datasets.