File tree 3 files changed +22
-1
lines changed
3 files changed +22
-1
lines changed Original file line number Diff line number Diff line change @@ -32,6 +32,12 @@ def _get_collection(self, model):
32
32
col = self .COLLECTIONS [model ]
33
33
return self ._db [col ]
34
34
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
+
35
41
async def find_all (self , model ):
36
42
"""Find all objects of a given model"""
37
43
col = self ._get_collection (model )
Original file line number Diff line number Diff line change @@ -37,6 +37,12 @@ async def pubsub_startup():
37
37
pubsub = await PubSub .create ()
38
38
39
39
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
+
40
46
async def get_current_user (
41
47
security_scopes : SecurityScopes ,
42
48
token : str = Depends (auth .oauth2_scheme )):
Original file line number Diff line number Diff line change @@ -81,8 +81,12 @@ class DatabaseModel(ModelId):
81
81
def update (self ):
82
82
"""Method to update model"""
83
83
84
+ @classmethod
85
+ def create_indexes (cls , collection ):
86
+ """Method to create index"""
87
+
84
88
85
- class User (ModelId ):
89
+ class User (DatabaseModel ):
86
90
"""API user model"""
87
91
username : str
88
92
hashed_password : str = Field (description = 'Hash of the plaintext password' )
@@ -95,6 +99,11 @@ class User(ModelId):
95
99
description = 'True if superuser otherwise False'
96
100
)
97
101
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
+
98
107
99
108
class Revision (BaseModel ):
100
109
"""Linux kernel Git revision model"""
You can’t perform that action at this time.
0 commit comments