Skip to content

Commit fb37dc3

Browse files
author
Jeny Sadadia
committed
api.db: decouple model indexes from DB engine
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]>
1 parent eb358a4 commit fb37dc3

File tree

2 files changed

+16
-8
lines changed

2 files changed

+16
-8
lines changed

api/db.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,12 @@ def _get_collection(self, model):
6262
async def create_indexes(self):
6363
"""Create indexes for models"""
6464
for model in self.COLLECTIONS:
65+
indexes = model.get_indexes()
66+
if not indexes:
67+
continue
6568
col = self._get_collection(model)
66-
model.create_indexes(col)
69+
for index in indexes:
70+
col.create_index(index.field, **index.attributes)
6771

6872
async def find_one(self, model, **kwargs):
6973
"""Find one object with matching attributes

api/models.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
)
3030
from bson import ObjectId
3131
from kernelci.api.models_base import DatabaseModel, ModelId
32+
from pydantic.dataclasses import dataclass
3233

3334

3435
# PubSub model definitions
@@ -66,9 +67,11 @@ class UserGroup(DatabaseModel):
6667
)
6768

6869
@classmethod
69-
def create_indexes(cls, collection):
70-
"""Create an index to bind unique constraint to group name"""
71-
collection.create_index("name", unique=True)
70+
def get_indexes(cls):
71+
"""Get an index to bind unique constraint to group name"""
72+
return [
73+
cls.Index('name', {'unique': True}),
74+
]
7275

7376

7477
class User(BeanieBaseUser, Document, # pylint: disable=too-many-ancestors
@@ -86,10 +89,11 @@ class Settings(BeanieBaseUser.Settings):
8689
name = "user"
8790

8891
@classmethod
89-
def create_indexes(cls, collection):
90-
"""Create an index to bind unique constraint to email"""
91-
collection.create_index("email", unique=True)
92-
92+
def get_indexes(cls):
93+
"""Get indices"""
94+
return [
95+
cls.Index('email', {'unique': True}),
96+
]
9397

9498
class UserRead(schemas.BaseUser[PydanticObjectId], ModelId):
9599
"""Schema for reading a user"""

0 commit comments

Comments
 (0)