tangled
alpha
login
or
join now
bernsteinbear.com
/
db.py
0
fork
atom
this repo has no description
0
fork
atom
overview
issues
pulls
pipelines
authored by
Max Bernstein
and committed by
GitHub
2 years ago
a688a437
+83
1 changed file
expand all
collapse all
unified
split
db.py
+83
db.py
reviewed
···
1
1
+
database = {}
2
2
+
3
3
+
4
4
+
def init():
5
5
+
global database
6
6
+
database = {"tables": {}}
7
7
+
8
8
+
9
9
+
def CREATE_TABLE(name):
10
10
+
table = {"name": name, "rows": []}
11
11
+
database["tables"][name] = table
12
12
+
return table
13
13
+
14
14
+
15
15
+
def FROM(*table_names):
16
16
+
assert len(table_names) > 0
17
17
+
match table_names:
18
18
+
case (table_name,):
19
19
+
return database["tables"][table_name]
20
20
+
case (table_name, *rest):
21
21
+
return CROSS_JOIN(database["tables"][table_name], FROM(*rest))
22
22
+
23
23
+
24
24
+
def SELECT(table, columns, aliases=None):
25
25
+
if aliases is None:
26
26
+
aliases = {}
27
27
+
newrows = []
28
28
+
colnames = {}
29
29
+
for col in columns:
30
30
+
colnames[col] = aliases.get(col, col)
31
31
+
for row in table["rows"]:
32
32
+
newrow = {}
33
33
+
for col in columns:
34
34
+
newrow[colnames[col]] = row[col]
35
35
+
newrows.append(newrow)
36
36
+
return {"name": table["name"], "rows": newrows}
37
37
+
38
38
+
39
39
+
def WHERE(table, pred):
40
40
+
return {"name": table["name"], "rows": [row for row in table["rows"] if pred(row)]}
41
41
+
42
42
+
43
43
+
def INSERT_INTO(table_name, *rows):
44
44
+
table = database["tables"][table_name]
45
45
+
table["rows"].extend(rows)
46
46
+
47
47
+
48
48
+
def CROSS_JOIN(a, b):
49
49
+
result = {"name": "", "rows": []}
50
50
+
for x in a["rows"]:
51
51
+
for y in b["rows"]:
52
52
+
row = {}
53
53
+
for k in x:
54
54
+
column_name = a["name"] + "." + k if a["name"] else k
55
55
+
row[column_name] = x[k]
56
56
+
for k in y:
57
57
+
column_name = b["name"] + "." + k if b["name"] else k
58
58
+
row[column_name] = y[k]
59
59
+
row["_tableRows"] = (x, y)
60
60
+
result["rows"].append(row)
61
61
+
return result
62
62
+
63
63
+
64
64
+
def INNER_JOIN(a, b, pred):
65
65
+
return {"name": "", "rows": [row for row in CROSS_JOIN(a, b)["rows"] if pred(row)]}
66
66
+
67
67
+
68
68
+
init()
69
69
+
CREATE_TABLE("User")
70
70
+
INSERT_INTO("User", {"id": 0, "name": "Alice", "age": 25})
71
71
+
INSERT_INTO("User", {"id": 1, "name": "Bob", "age": 28})
72
72
+
INSERT_INTO("User", {"id": 2, "name": "Charles", "age": 29})
73
73
+
CREATE_TABLE("Post")
74
74
+
INSERT_INTO("Post", {"id": 0, "user_id": 1, "text": "Hello from Bob"})
75
75
+
INSERT_INTO("Post", {"id": 1, "user_id": 0, "text": "Hello from Alice"})
76
76
+
77
77
+
User = FROM("User")
78
78
+
Post = FROM("Post")
79
79
+
result = INNER_JOIN(User, Post, lambda row: row["User.id"] == row["Post.user_id"])
80
80
+
result = SELECT(
81
81
+
result, ["User.name", "Post.text"], {"User.name": "Author", "Post.text": "Message"}
82
82
+
)
83
83
+
print(result)