95 lines
3.1 KiB
Python
95 lines
3.1 KiB
Python
from table import Table
|
|
|
|
class SQL:
|
|
def __init__(self, tables: dict, query: str) -> None:
|
|
self.tables = tables
|
|
self.query = query.replace(";", "")
|
|
|
|
def __str__(self) -> str:
|
|
pass
|
|
|
|
# SELECIONAR * DE tabela
|
|
def execute(self):
|
|
query_parts = self.query.split(" ")
|
|
|
|
if query_parts[0] == "SELECIONAR":
|
|
self.select(query_parts)
|
|
else:
|
|
pass
|
|
|
|
# SELECIONAR * DE tabela JUNTAR tabela2 coluna ONDE coluna = valor
|
|
def select(self, query_parts: list) -> None:
|
|
where_filter = None
|
|
join_stmt = None
|
|
|
|
if "JUNTAR" in query_parts:
|
|
index = query_parts.index("JUNTAR")
|
|
join_table = query_parts[index + 1]
|
|
join_column = query_parts[index + 2]
|
|
join_stmt = [self.tables[join_table], join_column]
|
|
|
|
if "ONDE" in query_parts:
|
|
index = query_parts.index("ONDE")
|
|
where_filter_column = query_parts[index + 1]
|
|
where_filter_operator = query_parts[index + 2]
|
|
where_filter_value = query_parts[index + 3]
|
|
where_filter = [where_filter_column, where_filter_operator, where_filter_value]
|
|
|
|
# parse TABLE
|
|
table = self.tables[query_parts[3]]
|
|
|
|
# parse SELECT COLUMNS
|
|
column_list = query_parts[1].split(",")
|
|
for i in range(len(column_list)):
|
|
column_list[i] = column_list[i].strip()
|
|
|
|
if column_list[0] == '*':
|
|
column_list = table.columns
|
|
|
|
# print the columns
|
|
print(', '.join(column_list))
|
|
print('-' * 20)
|
|
|
|
# print the rows
|
|
tables_columns = table.columns
|
|
tables_rows = table.rows
|
|
|
|
if join_stmt is not None:
|
|
join_table = join_stmt[0]
|
|
join_column = join_stmt[1]
|
|
|
|
for row in table.rows:
|
|
column_index = table.columns.index(join_column)
|
|
row_value = row[column_index]
|
|
|
|
for join_row in join_table.rows:
|
|
join_column_index = join_table.columns.index(join_column)
|
|
join_row_value = join_row[join_column_index]
|
|
|
|
if row_value == join_row_value:
|
|
tables_rows.append(row + join_row)
|
|
|
|
tables_columns = table.columns + join_table.columns
|
|
|
|
for row in tables_rows:
|
|
if where_filter is not None:
|
|
column_index = tables_columns.index(where_filter[0])
|
|
row_value = row[column_index]
|
|
|
|
if where_filter[1] == '=':
|
|
if row_value != where_filter[2]:
|
|
continue
|
|
elif where_filter[1] == '>':
|
|
if row_value <= where_filter[2]:
|
|
continue
|
|
elif where_filter[1] == '<':
|
|
if row_value >= where_filter[2]:
|
|
continue
|
|
|
|
row_values = []
|
|
for column in column_list:
|
|
column_index = tables_columns.index(column)
|
|
row_values.append(row[column_index])
|
|
|
|
print(', '.join(row_values))
|