Skip to content

Commit 5542db0

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 c758358 commit 5542db0

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
@@ -32,6 +32,12 @@ def _get_collection(self, model):
3232
col = self.COLLECTIONS[model]
3333
return self._db[col]
3434

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

api/main.py

+6
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,12 @@ async def pubsub_startup():
3737
pubsub = await PubSub.create()
3838

3939

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

api/models.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -81,8 +81,12 @@ class DatabaseModel(ModelId):
8181
def update(self):
8282
"""Method to update model"""
8383

84+
@classmethod
85+
def create_indexes(cls, collection):
86+
"""Method to create index"""
87+
8488

85-
class User(ModelId):
89+
class User(DatabaseModel):
8690
"""API user model"""
8791
username: str
8892
hashed_password: str = Field(description='Hash of the plaintext password')
@@ -95,6 +99,11 @@ class User(ModelId):
9599
description='True if superuser otherwise False'
96100
)
97101

102+
@classmethod
103+
def create_indexes(cls, collection):
104+
"""Create an index to bind unique constraint to username"""
105+
collection.create_index("username", unique=True)
106+
98107

99108
class Revision(BaseModel):
100109
"""Linux kernel Git revision model"""

0 commit comments

Comments
 (0)