1+ from typing import List , Union , Collection , Mapping , Optional , Dict
2+
3+ class Table :
4+ def __init__ (self , name : str , columns :int , rows : Dict , row_count : int = 0 ):
5+ self .name = name
6+ self .columns = columns
7+ self .rows = rows
8+ self .row_count = row_count
9+
10+ class SQL :
11+
12+ def __init__ (self , names : List [str ], columns : List [int ]):
13+ """
14+ two string arrays, names and columns, both of size n.
15+
16+ The ith table is represented by the name names[i] and contains columns[i] number of columns
17+ """
18+
19+ self .names = names
20+ self .columns = columns
21+ self .data = {}
22+
23+ for i in range (0 , len (self .names )):
24+ self .data [self .names [i ]] = Table (
25+ self .names [i ],
26+ self .columns [i ],
27+ {}
28+ )
29+
30+ return
31+
32+ def ins (self , name : str , row : List [str ]) -> bool :
33+ """
34+ Inserts row into the table name and returns true.
35+ If row.length does not match the expected number of columns, or name is not a valid table,
36+ returns false without any insertion.
37+ """
38+ table : Table = self .data .get (name , None )
39+ if table is None :
40+ return False
41+ if len (row ) != table .columns :
42+ return False
43+ table .row_count += 1
44+ table .rows [table .row_count ] = row
45+
46+ return True
47+
48+ def rmv (self , name : str , rowId : int ) -> None :
49+ """
50+ Removes the row rowId from the table name.
51+ If name is not a valid table or there is no row with id rowId, no removal is performed.
52+ """
53+ table = self .data .get (name , None )
54+ if table is None :
55+ return
56+
57+ if rowId in table .rows :
58+ del table .rows [rowId ]
59+ return
60+
61+ def sel (self , name : str , rowId : int , columnId : int ) -> str :
62+ """
63+ Returns the value of the cell at the specified rowId and columnId in the table name.
64+ If name is not a valid table, or the cell (rowId, columnId) is invalid, returns "<null>".
65+ """
66+ null = "<null>"
67+ table = self .data .get (name , None )
68+ if table is None :
69+ return null
70+
71+ if rowId not in table .rows :
72+ return null
73+
74+ try :
75+ return table .rows [rowId ][columnId - 1 ]
76+ except Exception :
77+ return null
78+
79+ def exp (self , name : str ) -> List [str ]:
80+ """
81+ Returns the rows present in the table name.
82+ If name is not a valid table, returns an empty array.
83+ Each row is represented as a string, with each cell value (including the row's id) separated by a ",".
84+ """
85+ table = self .data .get (name , None )
86+ if table is None :
87+ return []
88+
89+ result = []
90+
91+ for row_id , row in table .rows .items ():
92+ row_str = "," .join (row )
93+ result .append (f"{ row_id } ,{ row_str } " )
94+ return result
0 commit comments