forked from Peng-YM/LeetCode-Anki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.py
102 lines (78 loc) · 2.26 KB
/
database.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
import logging
import pathlib
from peewee import *
from utils import parser
if parser.get("DB", "debug") == "True":
# logger
logger = logging.getLogger('peewee')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)
# connect or create the database
directory = parser.get("DB", "path")
p = pathlib.Path(directory)
p.mkdir(parents=True, exist_ok=True)
database = SqliteDatabase(directory + "/LeetCode.sqlite")
# data models
class BaseModel(Model):
class Meta:
database = database
class Problem(BaseModel):
display_id = IntegerField(unique=True)
level = CharField()
title = CharField()
slug = CharField(unique=True)
description = TextField()
accepted = BooleanField()
# find the tags related to this question
@property
def tags(self):
return (
Tag.select().join(
ProblemTag, on=Tag.slug == ProblemTag.tag
).where(
ProblemTag.problem == self.id
)
)
@property
def solution(self):
return (
Solution.select().where(
Solution.problem == self.id
)
)
class Submission(BaseModel):
slug = ForeignKeyField(Problem, 'slug', backref='submissions')
language = CharField()
source = TextField()
created = DateField()
class Tag(BaseModel):
name = CharField()
slug = CharField(unique=True, primary_key=True)
@property
def problems(self):
return (
Problem.select().join(
ProblemTag, on=Problem.id == ProblemTag.problem
).where(
ProblemTag.tag == self.slug
).order_by(
Problem.id
)
)
class ProblemTag(BaseModel):
problem = ForeignKeyField(Problem)
tag = ForeignKeyField(Tag)
class Meta:
indexes = (
# Specify a unique multi-column index on from/to-user.
(('problem', 'tag'), True),
)
class Solution(BaseModel):
problem = ForeignKeyField(Problem, primary_key=True)
content = TextField()
url = CharField()
def create_tables():
with database:
database.create_tables([Problem, Solution, Submission, Tag, ProblemTag])
if __name__ == '__main__':
create_tables()