1- import pandas as pd
2-
3- class RelationalAlgebra :
4- def __init__ (self ):
5- self .tables = {}
6-
7- def create_table (self , name , columns , data ):
8- self .tables [name ] = pd .DataFrame (data , columns = columns )
9- print (f"Created table { name } with columns { columns } and data { data } " )
10-
11- def select (self , table_name , condition ):
12- table = self .tables [table_name ]
13- selected_rows = table .query (condition )
14- print (f"Selected rows from table { table_name } where { condition } :\n { selected_rows } " )
15- return selected_rows
16-
17- def project (self , table_name , columns ):
18- table = self .tables [table_name ]
19- projected_data = table [columns ]
20- print (f"Projected columns { columns } from table { table_name } :\n { projected_data } " )
21- return projected_data
22-
23- def join (self , table1_name , table2_name , join_condition ):
24- table1 = self .tables [table1_name ]
25- table2 = self .tables [table2_name ]
26- joined_data = pd .merge (table1 , table2 , how = 'inner' , left_on = join_condition [0 ], right_on = join_condition [1 ])
27- print (f"Joined data from tables { table1_name } and { table2_name } on { join_condition } :\n { joined_data } " )
28- return joined_data
29-
30- # Example usage
31- db = RelationalAlgebra ()
32-
33- db .create_table ("Students" , ["ID" , "Name" , "Age" ], [[1 , "Alice" , 20 ], [2 , "Bob" , 22 ]])
34- db .create_table ("Courses" , ["ID" , "Course" ], [[1 , "Math" ], [2 , "History" ]])
35-
36- selected_students = db .select ("Students" , "Age > 20" )
37- projected_students = db .project ("Students" , ["Name" , "Age" ])
38- joined_data = db .join ("Students" , "Courses" , ["ID" , "ID" ])
1+ '''
2+ INFO
3+ input : sql query
4+ output relational algebra expression
5+ '''
6+ sql_input = '''SELECT *
7+ FROM instructor AS I
8+ INNER JOIN teaches AS T ON I.ID = T.ID
9+ WHERE I.dept_name = “Music” AND T.year = 2009 '''
10+
11+ def sql_to_rel (query ):
12+ query_words = query .split ()
13+ dict = {
14+ "SELECT" :"σ" ,
15+ "*" :"" ,
16+ "FROM" :"" ,
17+ "INNER JOIN" :"⋈" ,
18+ "ON" :"" ,
19+ "WHERE" :""
20+ }
21+ ra = []
22+ flag_table = False
23+ flag_condition = 0
24+ tables = []
25+ join = ""
26+ conditions = []
27+ for word in query_words :
28+ if word == "SELECT" :
29+ ra .append ("σ" )
30+ elif word == "AS" :
31+ flag_table = True
32+ elif flag_table :
33+ tables .append (word )
34+ flag_table = False
35+ elif word == "ON" :
36+ flag_condition = 5
37+ elif flag_condition > 0 :
38+ conditions .append (word )
39+ flag_condition - - 1
40+ elif word == "JOIN" :
41+ join = "⋈"
42+
43+
44+ for c in conditions :
45+ if c == "AND" :
46+ ra .append ("^" )
47+ continue
48+ elif c == "WHERE" :
49+ continue
50+ ra .append (c )
51+ for t in tables :
52+ ra .append (t )
53+ ra .append (join )
54+ join = ""
55+ print ("Input sql -> " ,sql_input )
56+ print ("RA -> " ,ra )
57+
58+ sql_to_rel (sql_input )
0 commit comments