-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCatalog.py
232 lines (180 loc) · 6.52 KB
/
Catalog.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import json
import os
import Index
tables = {} # empty dict,to store tables
catalogpath = '' # path of catalogs folder
tablecatalog = '' # path of table catalog file
indexcatalog = '' # path of index catalog file
indices = {} # empty dict,to store indices
class Table: # data structure to save a table
def __init__(self, table_name, pk=0):
self.table_name = table_name
self.primary_key = pk
columns = []
class Column: # data structure to save an attribute
def __init__(self, column_name, is_unique, type='char', length=16):
self.column_name = column_name
self.is_unique = is_unique
self.type = type
self.length = length
def __initialize__(__path): # initialize the file of catalog
global catalogpath
global tablecatalog
global indexcatalog
catalogpath = os.path.join(__path, 'dbfiles/catalogs')
tablecatalog = os.path.join(catalogpath, 'catalog_table')
indexcatalog = os.path.join(catalogpath, 'catalog_index')
if not os.path.exists(catalogpath):
os.makedirs(catalogpath)
f1 = open(tablecatalog, 'w')
f2 = open(indexcatalog, 'w')
f1.close()
f2.close()
__savefile__()
__loadfile__()
def __finalize__():
__savefile__()
def show_tables():
for table in list(tables.values()):
print(table.table_name)
def show_table(table_name: str):
global tables
table = tables[table_name]
for column in table.columns:
print(f"column name:{column.column_name}\t"
f"is unique:{column.is_unique}\t"
f"type:{column.type}\t", end='')
if column.type == 'char':
print(f"length:{column.length}", end='')
print('')
def create_table(table_name, attributes, pk):
global tables
cur_table = Table(table_name, pk)
columns = []
for attr in attributes:
columns.append(Column(attr['attribute_name'],
attr['unique'],
attr['type'],
attr['type_len']))
cur_table.columns = columns
seed = False
for index, __column in enumerate(cur_table.columns):
if __column.column_name == cur_table.primary_key:
cur_table.primary_key = index
seed = True
break
if seed == False:
raise Exception("primary_key '%s' does not exist."
% cur_table.primary_key)
tables[table_name] = cur_table
def drop_table(table_name):
tables.pop(table_name)
def check_types_of_table(table_name, values):
cur_table = tables[table_name]
if len(cur_table.columns) != len(values):
raise Exception("Table '%s' "
"has %d columns." % (table_name, len(cur_table.columns)))
for i, element in enumerate(cur_table.columns):
if element.type == 'float':
value = float(values[i])
elif element.type == 'int':
value = int(values[i])
else:
value = values[i]
if len(value) > element.length:
raise Exception("Table '%s' : column '%s' 's length"
" can be no longer than %d." % (table_name, element.column_name, element.length))
if element.is_unique:
# Index.check_unique(table_name, i, value)
pass
def exists_table(table_name):
for key in tables.keys():
if key == table_name:
raise Exception("Table already exists.")
def not_exists_table(table_name):
for key in tables.keys():
if key == table_name:
return
raise Exception("Table does not exist.")
def not_exists_index(index_name):
for key in indices.keys():
if key == index_name:
return
raise Exception("Index does not exist.")
def exists_index(index_name):
for key in indices.keys():
if key == index_name:
raise Exception("Index already exists.")
def drop_index(index_name):
indices.pop(index_name)
print("Successfully deleted index '%s'." % index_name)
def create_index(index_name, table, column):
indices[index_name] = {'table': table, 'column': column}
def check_select_statement(table_name, attributes, where):
# raise an exception if something is wrong
columns = []
for i in tables[table_name].columns:
columns.append(i.column_name)
if where is not None:
for i in where:
if i['l_op'] not in columns:
raise Exception("No column"
" name '%s'." % i['l_op'])
if attributes == ['*']:
return
for i in attributes:
if i not in columns:
raise Exception("No column name '%s'." % i)
def get_column_dic(table_name: str):
result = {}
cnt = 0
global tables
for fullcol in tables[table_name].columns:
colname = fullcol.column_name
result[colname] = cnt
cnt += 1
return result
def __loadfile__(): # from file to memory
f = open(tablecatalog)
json_tables = json.loads(f.read())
for table in json_tables.items():
temp_name = table[0]
temp_pk = table[1]['pk']
temp_columns = []
__table = Table(temp_name, temp_pk) # table_name&primary key
for __column in table[1]['columns'].items():
temp_attname = __column[0]
temp_isunique = __column[1][0]
temp_type = __column[1][1]
temp_len = __column[1][2]
temp_columns.append(Column(temp_attname, temp_isunique, temp_type, temp_len))
__table.columns = temp_columns
tables[temp_name] = __table # add into the tables dict in memory
f.close()
f = open(indexcatalog)
json_indices = f.read()
json_indices = json.loads(json_indices)
for index in json_indices.items():
temp_indexname = index[0] # name of this index
temp_index = index[1] # the actual component of this index
indices[temp_indexname] = temp_index
f.close()
def __savefile__(): # from memory to file
__tables = {}
for items in tables.items():
definition = {}
temp_name = items[0]
__columns = {}
for i in items[1].columns:
__columns[i.column_name] = [i.is_unique, i.type, i.length]
definition['columns'] = __columns
definition['pk'] = items[1].primary_key
__tables[temp_name] = definition
j_tables = json.dumps(__tables)
j_indices = json.dumps(indices)
f = open(tablecatalog, 'w')
f.write(j_tables)
f.close()
f = open(indexcatalog, 'w')
f.write(j_indices)
f.close()