Skip to content

Commit 0ecb0d5

Browse files
author
Jeny Sadadia
committed
api: create database indexes on startup
Implement method Database.create_indexes to create indexes on model collections. Implement User.create_index to bind unique constraint to username field. Signed-off-by: Jeny Sadadia <[email protected]>
1 parent 0fa4f1d commit 0ecb0d5

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

api/db.py

+6
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@ def _get_collection(self, model):
3333
col = self.COLLECTIONS[model]
3434
return self._db[col]
3535

36+
async def create_indexes(self):
37+
"""Create indexes for models"""
38+
for model in self.COLLECTIONS:
39+
col = self._get_collection(model)
40+
model.create_indexes(col)
41+
3642
async def find_all(self, model):
3743
"""Find all objects of a given model"""
3844
col = self._get_collection(model)

api/main.py

+6
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,12 @@ async def pubsub_startup():
3535
pubsub = await PubSub.create()
3636

3737

38+
@app.on_event('startup')
39+
async def create_indexes():
40+
"""Startup event handler to create database indexes"""
41+
await db.create_indexes()
42+
43+
3844
async def get_current_user(
3945
security_scopes: SecurityScopes,
4046
token: str = Depends(auth.oauth2_scheme)):

api/models.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,12 @@ class DatabaseModel(ModelId):
8686
def update(self):
8787
"""Method to update model"""
8888

89+
@classmethod
90+
def create_indexes(cls, collection):
91+
"""Method to create indexes"""
92+
8993

90-
class User(ModelId):
94+
class User(DatabaseModel):
9195
"""API user model"""
9296
username: str
9397
hashed_password: str = Field(description='Hash of the plaintext password')
@@ -100,6 +104,11 @@ class User(ModelId):
100104
description='True if superuser otherwise False'
101105
)
102106

107+
@classmethod
108+
def create_indexes(cls, collection):
109+
"""Create an index to bind unique constraint to username"""
110+
collection.create_index("username", unique=True)
111+
103112

104113
class KernelVersion(BaseModel):
105114
"""Linux kernel version model"""

0 commit comments

Comments
 (0)