code:
def convert_keywords(query):
# Define a mapping of keywords to their replacements (case-insensitive)
keyword_mapping = {
re.compile(r'\bfetch\b', re.IGNORECASE): 'SELECT',
re.compile(r'\bput\b', re.IGNORECASE): 'INSERT',
re.compile(r'\bremove\b', re.IGNORECASE): 'DELETE',
re.compile(r'\bmerge\b', re.IGNORECASE): 'JOIN',
re.compile(r'\bfilter\b', re.IGNORECASE): 'WHERE',
}
# Replace keywords in the query
for keyword, replacement in keyword_mapping.items():
query = keyword.sub(replacement, query)
return query
def parse_query(query):
# Use regular expression to split by space or comma, excluding commas within parentheses
tokens = re.split(r'[,\s]+(?![^()]*))', query.upper())
# Remove empty strings from the list
tokens = [token for token in tokens if token]
# Handle 'AND' as a separate token
tokens = [token if token != 'AND' else 'AND' for token in tokens]
return tokens
def parse_query(query):
# Use regular expression to match tokens while preserving string literals
pattern = re.compile(r"(‘[^’]'|“[^”]“)|([,\s]+(?![^()]*))|\s+)")
# Split the query into tokens using the compiled pattern
tokens = re.split(pattern, query)
# Exclude matches for empty strings and splitter groups
tokens = [token for token in tokens if token and not token.isspace() and not pattern.match(token)]
# Handle special words ‘AND’, ‘ORDER’, ‘BY’ as separate tokens if necessary
return tokens
def custom_sort(data, column, ascending=True):
"""
Custom sorting function to sort a DataFrame by a specified column.
Parameters:
- data: DataFrame to be sorted
- column: Column by which to sort the DataFrame
- ascending: If True, sort in ascending order; if False, sort in descending order
Returns:
- Sorted DataFrame
"""
# Extract the values of the specified column
column_values = data[column].tolist()
# Create a list of tuples containing index and corresponding values
indexed_values = list(enumerate(column_values))
# Sort the list of tuples based on values and order
sorted_values = sorted(indexed_values, key=lambda x: x[1], reverse=not ascending)
# Extract the sorted indices
sorted_indices = [index for index, _ in sorted_values]
# Reorder the DataFrame based on the sorted indices
sorted_data = data.iloc[sorted_indices]
return sorted_data
class Database:
def __init__(self, chunk_size=100):
self.chunk_size = chunk_size
self.property_info_chunks = []
self.sales_info_chunks = []
def load_sales_info(self, file_path):
sales_columns = ['zip_code', 'city', 'status', 'prev_sold_date', 'price', 'state']
with open(file_path, 'r') as csvfile:
reader = csv.DictReader(csvfile)
chunk = []
for row in reader:
chunk.append(row)
if len(chunk) == self.chunk_size:
self.sales_info_chunks.append(pd.DataFrame(chunk, columns=sales_columns))
chunk = []
if chunk:
self.sales_info_chunks.append(pd.DataFrame(chunk, columns=sales_columns))
def load_property_info(self, file_path):
property_columns = ['bed', 'bath', 'acre_lot', 'house_size', 'zip_code', 'city']
with open(file_path, 'r') as csvfile:
reader = csv.DictReader(csvfile)
chunk = []
for row in reader:
chunk.append(row)
if len(chunk) == self.chunk_size:
self.property_info_chunks.append(pd.DataFrame(chunk, columns=property_columns))
chunk = []
if chunk:
self.property_info_chunks.append(pd.DataFrame(chunk, columns=property_columns))
# Save property_info_chunks back to the CSV file
self.save_chunks_to_csv('property_info.csv', self.property_info_chunks)
def save_chunks_to_csv(self, file_path, chunks):
# Concatenate all chunks and save to CSV
if chunks:
df = pd.concat(chunks, ignore_index=True)
df.to_csv(file_path, index=False)
def retrieve_data(self, columns, table_name, conditions=None, order_by=None, aggregation=None, join=None):
if table_name.upper() == 'PROPERTYINFO':
table_chunks = self.property_info_chunks
elif table_name.upper() == 'SALESINFO':
table_chunks = self.sales_info_chunks
else:
return "Invalid table name."
# Convert column names to uppercase and trim whitespace
columns = [col.strip().lower() for col in columns]
# Ensure all columns exist in the dataset (case-insensitive)
matching_columns = [col for col in table_chunks[0].columns if col.lower() in columns]
if not matching_columns:
# If no specific columns are specified, include all columns
matching_columns = table_chunks[0].columns
# Concatenate relevant chunks
table = pd.concat([chunk[matching_columns] for chunk in table_chunks], ignore_index=True)
# Apply WHERE condition if present
if conditions:
table = self.filter_data(table, conditions)
# Ensure consistent 'city' values
if 'city' in matching_columns:
table['city'] = table['city'].str.strip().str.upper()
# Handle JOIN operation if present
if join:
join_table_name, join_column = join
join_table_chunks = self.property_info_chunks if join_table_name.upper() == 'PROPERTYINFO' else self.sales_info_chunks
# Concatenate the relevant chunks for the join table
join_table = pd.concat([chunk for chunk in join_table_chunks], ignore_index=True)
# Perform the JOIN operation
table = pd.merge(table, join_table, left_on=matching_columns, right_on=[join_column], how='inner')
if aggregation:
table = self.aggregate_data(table, aggregation)
if order_by:
order_by_column, order_by_direction = order_by[0], 'ASC'
if len(order_by) > 1 and order_by[1].upper() == 'DESC':
order_by_direction = 'DESC'
# Use the custom sorting function
table = custom_sort(table, column=order_by_column, ascending=(order_by_direction == 'ASC'))
return table
def filter_data(self, data, conditions):
# Process conditions
while "AND" in conditions:
and_index = conditions.index("AND")
data = self.apply_condition(data, conditions[:and_index])
conditions = conditions[and_index + 1:]
# Process the last or single condition
data = self.apply_condition(data, conditions)
return data
def apply_condition(self, data, condition):
# Assuming condition is [‘column’, ‘operator’, ‘value’] without ‘AND’
column, operator, value = condition[0], condition[1], "".join(condition[2:])
# Handle string values
if value.startswith("‘") and value.endswith("’"):
value = value[1:-1] # Remove the surrounding single quotes
column_lower = column.lower() # Convert column name to lowercase
# Apply the correct operator
if operator == '=':
condition_result = data[column_lower] == value # Use lowercase column name
elif operator == '<>':
condition_result = data[column_lower] != value
# Additional operators (>, <, >=, <=) can be added here
# Apply the condition to the data
return data[condition_result]
def insert_data(self, table_name, values):
# Check if the table name is valid
if table_name.upper() == 'PROPERTYINFO':
# Column names for property_info.csv
property_columns = ['bed', 'bath', 'acre_lot', 'house_size', 'zip_code', 'city']
# Create a dictionary to store values for each column
property_info = {column: [] for column in property_columns}
# Extract values from the tuple and append to the dictionary
for column, value in zip(property_columns, eval(values[0])):
# Convert the value to the appropriate type
if column == 'acre_lot':
value = float(value)
property_info[column].append(value)
array_lengths = [len(value) for value in property_info.values()]
# Check that all arrays have the same length
if len(set(array_lengths)) != 1:
raise ValueError("All arrays must be of the same length.")
# Create a DataFrame and append it to the property_info_chunks list
df = pd.DataFrame(property_info)
self.property_info_chunks.append(df)
self.save_chunks_to_csv('property_info.csv', self.property_info_chunks)
return f"Inserted values into {table_name}: {', '.join(values)}"
elif table_name.upper() == 'SALESINFO':
# Column names for sales_info.csv
sales_columns = ['zip_code', 'city', 'status', 'prev_sold_date', 'price', 'state']
# Create a dictionary to store values for each column
sales_info = {column: [] for column in sales_columns}
# Iterate over columns and values and append to the dictionary
for column, value in zip(sales_columns, values):
# Convert the value to the appropriate type
if column == 'price':
value = float(value)
sales_info[column].append(value)
# Print the values being inserted
print(f"Values being inserted: {sales_info}")
# Print the lengths of the arrays
array_lengths = [len(value) for value in sales_info.values()]
print(f"Array lengths: {array_lengths}")
# Check that all arrays have the same length
if len(set(array_lengths)) != 1:
raise ValueError("All arrays must be of the same length.")
# Create a DataFrame and append it to the sales_info_chunks list
df = pd.DataFrame(sales_info)
self.sales_info_chunks.append(df)
self.save_chunks_to_csv('sales_info.csv', self.sales_info_chunks)
return f"Inserted values into {table_name}: {', '.join(values)}"
else:
return f"Invalid table name: {table_name}"
# Modify the 'retrieve_data_groupby' method in the Database class
def retrieve_data_groupby(self, columns, table_name, groupby_columns, order_by=None, aggregation=None):
print("Debug: Starting retrieve_data_groupby")
groupby_columns = [col.lower() for col in groupby_columns]
data = self.retrieve_data(columns, table_name)
if data is None:
print("Error: No data found.")
return None
# Clean the city names for consistent grouping
if 'city' in groupby_columns:
data['city'] = data['city'].str.strip().str.upper()
print("Debug: Data retrieved successfully")
if aggregation:
# Check if the aggregation function is valid
valid_aggregations = {'COUNT', 'SUM', 'AVG', 'MIN', 'MAX'}
aggregation_function = aggregation[0]
if aggregation_function not in valid_aggregations:
print(f"Error: Invalid aggregation function '{aggregation_function}'.")
return None
# Print some debug information
print("Debug: Aggregation Function:", aggregation_function)
print("Debug: Data Columns:", data.columns)
# Perform the aggregation
if aggregation_function == 'COUNT':
aggregated_data = data.groupby(groupby_columns).size().reset_index(name='count')
# Fill missing values with 0 for consistency
aggregated_data['count'] = aggregated_data['count'].fillna(0).astype(int)
else:
# Handle other aggregation functions...
pass
print("Debug: Aggregation performed successfully")
# Apply ORDER BY clause if present
if order_by:
order_by_column, order_by_direction = order_by[0], 'ASC'
if len(order_by) > 1 and order_by[1].upper() == 'DESC':
order_by_direction = 'DESC'
# Check if the ordered column is part of the result
if order_by_column.lower() in aggregated_data.columns:
# Sort only if the ordered column is present
aggregated_data = aggregated_data.sort_values(by=order_by_column.lower(), ascending=(order_by_direction == 'ASC'))
else:
print(f"Error: Column '{order_by_column}' not found in the result set.")
print("Debug: Returning aggregated data")
return aggregated_data
else:
print("Debug: Returning data without aggregation")
return data
def aggregate_data(self, data, aggregation):
# Assuming aggregation is a tuple ('column_name', 'function')
column, func = aggregation
if func.upper() == 'COUNT':
return data.groupby(column).size().reset_index(name=func.lower())
elif func.upper() == 'SUM':
return data.groupby(column).sum().reset_index()
elif func.upper() == 'AVG':
return data.groupby(column).mean().reset_index()
else:
print(f"Error: Unsupported aggregation function '{func}'.")
return data
class QueryExecutor:
def init(self, database):
self.database = database
def execute_query(self, query):
converted_query = convert_keywords(query)
# After converting, parse the query into tokens using parse_query
tokens = parse_query(converted_query)
command = tokens[0]
if command == 'SELECT':
return self.handle_select(tokens)
elif command == 'INSERT':
return self.handle_insert(tokens[1:])
elif command == 'DELETE':
return self.handle_delete(tokens[1:])
elif command == 'UPDATE':
return self.handle_update(tokens[1:])
elif command == 'EXIT':
return self.handle_exit()
else:
return "Unrecognized command."
def handle_select(self, tokens):
if 'FROM' in tokens:
index_from = tokens.index('FROM')
projection_list = tokens[1:index_from]
table_name = tokens[index_from + 1]
# Check if GROUP BY clause is present
if 'GROUP' in tokens:
index_group = tokens.index('GROUP')
groupby_columns = tokens[index_group + 2:]
order_by = None
if 'ORDER' in tokens:
index_order = tokens.index('ORDER')
order_by = tokens[index_order + 2:]
order_by = [order_by[i] if order_by[i] not in ('ASC', 'DESC') else order_by[i].upper() for i in range(len(order_by))]
# Extract aggregation function and column if present
aggregation = None
if 'SUM' in tokens or 'COUNT' in tokens or 'AVG' in tokens or 'MIN' in tokens or 'MAX' in tokens:
index_aggregation = min(tokens.index('SUM') if 'SUM' in tokens else len(tokens),
tokens.index('COUNT') if 'COUNT' in tokens else len(tokens),
tokens.index('AVG') if 'AVG' in tokens else len(tokens),
tokens.index('MIN') if 'MIN' in tokens else len(tokens),
tokens.index('MAX') if 'MAX' in tokens else len(tokens))
aggregation = tokens[index_aggregation:index_aggregation + 3]
result = self.database.retrieve_data_groupby(projection_list, table_name, groupby_columns, order_by, aggregation)
# Check if the result is a DataFrame
if isinstance(result, pd.DataFrame):
print(result.columns)
else:
print(result)
return result
else:
# No GROUP BY clause, proceed with regular retrieval
conditions = None
if 'WHERE' in tokens:
index_where = tokens.index('WHERE')
conditions = tokens[index_where + 1:]
result = self.database.retrieve_data(projection_list, table_name, conditions)
# Check if the result is a DataFrame
if isinstance(result, pd.DataFrame):
print(result.columns)
else:
print(result)
return result
else:
return "Invalid SELECT query. Missing FROM clause."
def handle_insert(self, tokens):
if 'INTO' in tokens:
index_into = tokens.index('INTO')
table_name = tokens[index_into + 1]
# Check if VALUES clause is present
if 'VALUES' in tokens:
index_values = tokens.index('VALUES')
values = tokens[index_values + 1:]
# Handle the insertion of values into the table
result = self.database.insert_data(table_name, values)
return result
else:
return "Invalid INSERT query. Missing VALUES clause."
else:
return "Invalid INSERT query. Missing INTO clause."
def handle_delete(self, tokens):
return "Handling DELETE: " + " ".join(tokens)
def handle_update(self, tokens):
return "Handling UPDATE: " + " ".join(tokens)
def handle_exit(self):
return "Exiting the system."
query:
Test the SELECT query
query = "FeTch all from propertyinfo"
result = query_executor.execute_query(query)
print(result)
error:
error Traceback (most recent call last)
/Users/midas/Library/CloudStorage/Dropbox/DSCI 551/Project/project copy.ipynb Cell 6 line 3
1 # Test the SELECT query
2 query = "FeTch all from propertyinfo"
----> 3 result = query_executor.execute_query(query)
4 print(result)
/Users/midas/Library/CloudStorage/Dropbox/DSCI 551/Project/project copy.ipynb Cell 6 line 3
364 converted_query = convert_keywords(query)
366 # After converting, parse the query into tokens using parse_query
--> 367 tokens = parse_query(converted_query)
368 command = tokens[0]
370 if command == 'SELECT':
/Users/midas/Library/CloudStorage/Dropbox/DSCI 551/Project/project copy.ipynb Cell 6 line 3
29 def parse_query(query):
30 # Use regular expression to match tokens while preserving string literals
---> 31 pattern = re.compile(r"(‘[^’]'|“[^”]“)|([,\s]+(?![^()]*))|\s+)")
33 # Split the query into tokens using the compiled pattern
34 tokens = re.split(pattern, query)
File /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/re/init.py:227, in compile(pattern, flags)
225 def compile(pattern, flags=0):
226 "Compile a regular expression pattern, returning a Pattern object."
...
--> 985 raise source.error("unbalanced parenthesis")
987 for g in p.state.grouprefpos:
988 if g >= p.state.groups:
error: unbalanced parenthesis at position 38