Skip to content

Commit

Permalink
api.db: decouple model indexes from DB engine
Browse files Browse the repository at this point in the history
Implement a dataclass `Index` to store model field names
and constraints to create indexes. Instead of directly
creating indexes from model method for specific DB engine
(at the moment, MongoDB), implement a method to get indexes
from models independent of DB engine i.e. list of
`DatabaseModel.Index` class instances. Create MongoDB specific
indexes in the database method `Database.create_indexes`.

Signed-off-by: Jeny Sadadia <[email protected]>
  • Loading branch information
Jeny Sadadia authored and JenySadadia committed Feb 26, 2024
1 parent 49ebedf commit 4f69b70
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
6 changes: 5 additions & 1 deletion api/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,12 @@ def _get_collection(self, model):
async def create_indexes(self):
"""Create indexes for models"""
for model in self.COLLECTIONS:
indexes = model.get_indexes()
if not indexes:
continue
col = self._get_collection(model)
model.create_indexes(col)
for index in indexes:
col.create_index(index.field, **index.attributes)

async def find_one(self, model, **kwargs):
"""Find one object with matching attributes
Expand Down
16 changes: 10 additions & 6 deletions api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,11 @@ class UserGroup(DatabaseModel):
)

@classmethod
def create_indexes(cls, collection):
"""Create an index to bind unique constraint to group name"""
collection.create_index("name", unique=True)
def get_indexes(cls):
"""Get an index to bind unique constraint to group name"""
return [
cls.Index('name', {'unique': True}),
]


class User(BeanieBaseUser, Document, # pylint: disable=too-many-ancestors
Expand All @@ -86,9 +88,11 @@ class Settings(BeanieBaseUser.Settings):
name = "user"

@classmethod
def create_indexes(cls, collection):
"""Create an index to bind unique constraint to email"""
collection.create_index("email", unique=True)
def get_indexes(cls):
"""Get indices"""
return [
cls.Index('email', {'unique': True}),
]


class UserRead(schemas.BaseUser[PydanticObjectId], ModelId):
Expand Down

0 comments on commit 4f69b70

Please sign in to comment.