Write code in python
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
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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
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
//read from standard input line = input() // Get the current directory current_directory = os.getcwd() // Get all files in the directory files = os.listdir(current_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.
Example Output
product_id,product_name\n1,product1\n2,product2,\n3,product3
Sample Input 0
SELECT p.id AS product_id, p.name AS product_name FROM products p WHERE p.price > 95.00 ORDER BY product_id ASC
Sample Output 0
product_id,product_name\n6,product6\n11,product11\n62,product12,67,product67\n78,product78
Explanation 0
• The column names appear as the first line in output. They are in the order in what appears in SELECT clause in SQL query input, separated by comma with no spaces before or after.
• Rest follows the result from the products table
Sample Input 1
SELECT u.user_id AS user_id, u.name AS user_name FROM users u WHERE u.age > 48 AND u.location = 'Delhi' ORDER BY user_id DESC
Sample Output 1
user_id,user_name\n9943,user9943\n9493,user9493\n9364,user9364\n8650,user8650\n8515,user8515\n8495,user8495\n6849,user6849\n6387,user6387\n6090,user6090\n4100,user4100\n3660,user3660\n3390,user3390\n2908,user2908\n2773,user2773\n2272,user2272\n373,user373
Sample Input 2
SELECT p.category AS product_category, COUNT(*) AS product_counts FROM products p GROUP BY p.category ORDER BY product_counts DESC LIMIT 1
Sample Output 2
product_category,product_counts\nBOOKS,32
python
import os
import json
import sys
import re
from copy import deepcopy
def load_json_file(filename):
with open(filename, 'r') as f:
return json.load(f)
def read_query():
return sys.stdin.read().strip()
def split_query_into_clauses(query):
# Define regex patterns for each clause
pattern = re.compile(r'\b(SELECT|FROM|JOIN|WHERE|GROUP BY|ORDER BY|LIMIT)\b', re.IGNORECASE)
clauses = {}
for match in pattern.finditer(query):
clauses[match.group(1).upper()] = match.start()
# Sort clauses by their position in the query
sorted_clauses = sorted(clauses.items(), key=lambda x: x[1])
clause_contents = {}
for i, (clause, start) in enumerate(sorted_clauses):
end = len(query)
if i + 1 < len(sorted_clauses):
end = sorted_clauses[i+1][1]
content = query[start:end].strip()
clause_contents[clause] = content
return clause_contents
def parse_select_clause(select_clause):
# Remove SELECT keyword
select_clause = select_clause[6:].strip()
# Split by commas not within parentheses
select_parts = re.split(r',(?!(?:[^()]*\([^()]*\))*[^()]*\))', select_clause)
select_items = []
for part in select_parts:
part = part.strip()
# Check for AS alias
if ' AS ' in part.upper():
expr, alias = re.split(r'\s+AS\s+', part, flags=re.IGNORECASE)
alias = alias.strip()
else:
expr = part
alias = None
expr = expr.strip()
# Check for aggregate functions
agg_match = re.match(r'(COUNT|SUM|AVG|MIN|MAX)\((.*?)\)', expr, re.IGNORECASE)
if agg_match:
func = agg_match.group(1).upper()
arg = agg_match.group(2).strip()
select_items.append({
'type': 'aggregate',
'function': func,
'argument': arg,
'alias': alias if alias else f"{func}({arg})"
})
else:
# It's a column
if '.' in expr:
table_alias, col_name = expr.split('.', 1)
select_items.append({
'type': 'column',
'table_alias': table_alias.strip(),
'col_name': col_name.strip(),
'alias': alias if alias else col_name.strip()
})
else:
# In case there's no table alias
select_items.append({
'type': 'column',
'table_alias': None,
'col_name': expr.strip(),
'alias': alias if alias else expr.strip()
})
return select_items
def parse_from_clause(from_clause):
# Remove FROM keyword
from_clause = from_clause[4:].strip()
# Expected format: table alias
parts = from_clause.split()
table_name = parts[0]
table_alias = parts[1] if len(parts) > 1 else parts[0]
return {'table_name': table_name, 'table_alias': table_alias}
def parse_join_clauses(clause_contents):
join_clauses = []
join_pattern = re.compile(r'JOIN\s+(\w+)\s+(\w+)\s+ON\s+(.+?)(?=(JOIN|WHERE|GROUP BY|ORDER BY|LIMIT)|$)', re.IGNORECASE)
matches = join_pattern.finditer(clause_contents.get('JOIN', ''))
for match in matches:
table_name = match.group(1)
table_alias = match.group(2)
on_conditions = match.group(3).strip()
# Split conditions by AND
conditions = [cond.strip() for cond in re.split(r'\s+AND\s+', on_conditions, flags=re.IGNORECASE)]
join_conditions = []
for cond in conditions:
# Expecting format: table_alias.col = table_alias.col OR table_alias.col = value
eq_match = re.match(r'(\w+)\.(\w+)\s*=\s*(\w+\.\w+|\'?.+?\'?)$', cond)
if eq_match:
left_table = eq_match.group(1)
left_col = eq_match.group(2)
right = eq_match.group(3)
if '.' in right:
right_table, right_col = right.split('.', 1)
join_conditions.append({
'left_table': left_table,
'left_col': left_col,
'right_table': right_table,
'right_col': right_col
})
else:
# It's a value, which is not expected as per problem statement
# But handling just in case
join_conditions.append({
'left_table': left_table,
'left_col': left_col,
'value': right.strip('\'')
})
join_clauses.append({
'table_name': table_name,
'table_alias': table_alias,
'conditions': join_conditions
})
return join_clauses
def parse_where_clause(where_clause):
if not where_clause:
return []
# Remove WHERE keyword
where_clause = where_clause[5:].strip()
# Split by AND
conditions = [cond.strip() for cond in re.split(r'\s+AND\s+', where_clause, flags=re.IGNORECASE)]
parsed_conditions = []
for cond in conditions:
# Match operators: =, <>, >, >=, <, <=
op_match = re.match(r'(\w+)\.(\w+)\s*(=|<>|>=|<=|>|<)\s*(.+)', cond)
if op_match:
table_alias = op_match.group(1)
col_name = op_match.group(2)
operator = op_match.group(3)
value = op_match.group(4).strip()
# Remove quotes if value is a string
if value.startswith("'") and value.endswith("'"):
value = value[1:-1]
else:
# Try to convert to int or float
if '.' in value:
try:
value = float(value)
except:
pass
else:
try:
value = int(value)
except:
pass
parsed_conditions.append({
'table_alias': table_alias,
'col_name': col_name,
'operator': operator,
'value': value
})
return parsed_conditions
def parse_group_by_clause(group_by_clause):
if not group_by_clause:
return []
# Remove GROUP BY keyword
group_by_clause = group_by_clause[8:].strip()
# Split by commas
group_by_parts = [part.strip() for part in group_by_clause.split(',')]
group_by_columns = []
for part in group_by_parts:
if '.' in part:
table_alias, col_name = part.split('.', 1)
group_by_columns.append({
'table_alias': table_alias.strip(),
'col_name': col_name.strip()
})
else:
group_by_columns.append({
'table_alias': None,
'col_name': part.strip()
})
return group_by_columns
def parse_order_by_clause(order_by_clause):
if not order_by_clause:
return []
# Remove ORDER BY keyword
order_by_clause = order_by_clause[8:].strip()
# Check for ASC or DESC
order_parts = [part.strip() for part in order_by_clause.split(',')]
order_by = []
for part in order_parts:
if re.search(r'\s+(ASC|DESC)$', part, re.IGNORECASE):
expr, direction = re.split(r'\s+', part, 1)
order_by.append({
'expression': expr.strip(),
'direction': direction.upper()
})
else:
order_by.append({
'expression': part.strip(),
'direction': 'ASC'
})
return order_by
def parse_limit_clause(limit_clause):
if not limit_clause:
return None
# Remove LIMIT keyword
limit_clause = limit_clause[5:].strip()
try:
limit = int(limit_clause)
return limit
except:
return None
def get_table_data(table_name):
filename = f"{table_name}_public.json"
if not os.path.exists(filename):
return []
return load_json_file(filename)
def apply_join(current_data, join_table_data, join_alias, join_conditions):
joined_data = []
for row in current_data:
for join_row in join_table_data:
match = True
for cond in join_conditions:
left_key = f"{cond['left_table']}.{cond['left_col']}"
right_key = f"{cond['right_table']}.{cond['right_col']}"
if 'right_table' in cond:
left_val = row.get(left_key)
right_val = join_row.get(cond['right_col']) if cond['right_table'] == join_alias else row.get(right_key)
if left_val != join_row.get(cond['right_col']):
match = False
break
else:
# Condition with value, not supported in JOIN as per problem statement
match = False
break
if match:
# Merge the two rows with appropriate aliasing
merged_row = deepcopy(row)
for k, v in join_row.items():
merged_row[f"{join_alias}.{k}"] = v
joined_data.append(merged_row)
return joined_data
def apply_where(current_data, where_conditions):
def row_matches(row):
for cond in where_conditions:
key = f"{cond['table_alias']}.{cond['col_name']}"
if key not in row:
return False
val = row[key]
operator = cond['operator']
target = cond['value']
if isinstance(target, str):
comparison = f"'{val}'"
target_val = target
else:
comparison = val
target_val = target
try:
if operator == '=':
if val != target_val:
return False
elif operator == '<>':
if val == target_val:
return False
elif operator == '>':
if not (val > target_val):
return False
elif operator == '>=':
if not (val >= target_val):
return False
elif operator == '<':
if not (val < target_val):
return False
elif operator == '<=':
if not (val <= target_val):
return False
else:
return False
except:
return False
return True
filtered_data = [row for row in current_data if row_matches(row)]
return filtered_data
def apply_group_by(current_data, group_by_cols, select_items):
grouped = {}
for row in current_data:
key = tuple(row[f"{col['table_alias']}.{col['col_name']}"] if col['table_alias'] else row[col['col_name']] for col in group_by_cols)
if key not in grouped:
grouped[key] = []
grouped[key].append(row)
# Now compute aggregates
result_rows = []
for key, rows in grouped.items():
aggregated_row = {}
for item in select_items:
if item['type'] == 'column':
if item['table_alias']:
value = rows[0].get(f"{item['table_alias']}.{item['col_name']}")
else:
value = rows[0].get(item['col_name'])
aggregated_row[item['alias']] = value
elif item['type'] == 'aggregate':
func = item['function']
arg = item['argument']
if func == 'COUNT':
aggregated_row[item['alias']] = len(rows)
else:
if '.' in arg:
table_alias, col_name = arg.split('.',1)
values = [r.get(f"{table_alias}.{col_name}") for r in rows]
else:
values = [r.get(arg) for r in rows]
if func == 'SUM':
summed = sum(values)
if isinstance(summed, float):
summed = f"{summed:.2f}"
aggregated_row[item['alias']] = summed
elif func == 'AVG':
avg = sum(values) / len(values) if len(values) > 0 else 0
avg = f"{avg:.2f}"
aggregated_row[item['alias']] = float(avg)
elif func == 'MIN':
minimum = min(values)
if isinstance(minimum, float):
minimum = f"{minimum:.2f}"
aggregated_row[item['alias']] = minimum
elif func == 'MAX':
maximum = max(values)
if isinstance(maximum, float):
maximum = f"{maximum:.2f}"
aggregated_row[item['alias']] = maximum
result_rows.append(aggregated_row)
return result_rows
def apply_select(current_data, select_items):
selected_data = []
for row in current_data:
new_row = {}
for item in select_items:
if item['type'] == 'column':
if item['table_alias']:
key = f"{item['table_alias']}.{item['col_name']}"
else:
key = item['col_name']
new_row[item['alias']] = row.get(key, '')
elif item['type'] == 'aggregate':
new_row[item['alias']] = row.get(item['alias'], '')
selected_data.append(new_row)
return selected_data
def apply_order_by(current_data, order_by):
for order in reversed(order_by):
expr = order['expression']
direction = order['direction']
reverse = True if direction == 'DESC' else False
current_data.sort(key=lambda x: x.get(expr, None), reverse=reverse)
return current_data
def apply_limit(current_data, limit):
if limit is None:
return current_data
return current_data[:limit]
def format_output(selected_data, select_items):
# First line: column headers
headers = [item['alias'] for item in select_items]
output = ','.join(headers)
# Subsequent lines: data rows
for row in selected_data:
row_values = []
for item in select_items:
value = row.get(item['alias'], '')
if isinstance(value, float):
value = f"{value:.2f}"
row_values.append(str(value))
output += '\n' + ','.join(row_values)
return output
def main():
# Load JSON files
tables = {
'products': load_json_file('products_public.json'),
'users': load_json_file('users_public.json'),
'reviews': load_json_file('reviews_public.json'),
'transactions': load_json_file('transactions_public.json')
}
# Read SQL query
query = read_query()
# Split query into clauses
clauses = split_query_into_clauses(query)
# Parse each clause
select_items = parse_select_clause(clauses.get('SELECT', ''))
from_clause = parse_from_clause(clauses.get('FROM', ''))
join_clauses = parse_join_clauses(query)
where_conditions = parse_where_clause(clauses.get('WHERE', ''))
group_by_cols = parse_group_by_clause(clauses.get('GROUP BY', ''))
order_by = parse_order_by_clause(clauses.get('ORDER BY', ''))
limit = parse_limit_clause(clauses.get('LIMIT', ''))
# Initialize current data with FROM table
from_table = from_clause['table_name']
from_alias = from_clause['table_alias']
current_data = []
for row in tables[from_table]:
new_row = {}
for k, v in row.items():
new_row[f"{from_alias}.{k}"] = v
current_data.append(new_row)
# Apply JOINs
for join in join_clauses:
join_table = join['table_name']
join_alias = join['table_alias']
join_conditions = join['conditions']
join_data = tables[join_table]
# Add alias to join data
aliased_join_data = []
for row in join_data:
aliased_row = {}
for k, v in row.items():
aliased_row[k] = v
aliased_join_data.append(aliased_row)
# Perform the join
current_data = apply_join(current_data, aliased_join_data, join_alias, join_conditions)
# Apply WHERE conditions
if where_conditions:
current_data = apply_where(current_data, where_conditions)
# Apply GROUP BY and Aggregations
has_aggregate = any(item['type'] == 'aggregate' for item in select_items)
if group_by_cols:
current_data = apply_group_by(current_data, group_by_cols, select_items)
elif has_aggregate:
# Single group (all data)
aggregated_row = {}
for item in select_items:
if item['type'] == 'aggregate':
func = item['function']
arg = item['argument']
if func == 'COUNT':
aggregated_row[item['alias']] = len(current_data)
else:
if '.' in arg:
_, col_name = arg.split('.',1)
values = [row.get(arg, 0) for row in current_data]
else:
values = [row.get(arg, 0) for row in current_data]
if func == 'SUM':
summed = sum(values)
if isinstance(summed, float):
summed = round(summed + 1e-8, 2)
summed = f"{summed:.2f}"
aggregated_row[item['alias']] = summed
elif func == 'AVG':
avg = sum(values) / len(values) if len(values) > 0 else 0
avg = round(avg + 1e-8, 2)
aggregated_row[item['alias']] = f"{avg:.2f}"
elif func == 'MIN':
minimum = min(values)
if isinstance(minimum, float):
minimum = round(minimum + 1e-8, 2)
minimum = f"{minimum:.2f}"
aggregated_row[item['alias']] = minimum
elif func == 'MAX':
maximum = max(values)
if isinstance(maximum, float):
maximum = round(maximum + 1e-8, 2)
maximum = f"{maximum:.2f}"
aggregated_row[item['alias']] = maximum
current_data = [aggregated_row]
# Apply SELECT clause
current_data = apply_select(current_data, select_items)
# Apply ORDER BY
if order_by:
current_data = apply_order_by(current_data, order_by)
# Apply LIMIT
if limit is not None:
current_data = apply_limit(current_data, limit)
# Format the output
output = format_output(current_data, select_items)
print(output)
if __name__ == "__main__":
main()