Skip to content

Commit

Permalink
Update metadata to allow multiple db concurrently in app (#52)
Browse files Browse the repository at this point in the history
* adding __metadata__ from database instance during DataBaseModel.setup(), added Float to supported supported_sqlalchemy_types. BaseMeta now creates separate instances instead of global class references

* creating BaseMeta instance for each separate Database instance

* added test for multiple databases

* added test_multiple_databases test to Makefile

* added test_multiple_databases test to Makefile

---------

Co-authored-by: Joshua (codemation)
  • Loading branch information
codemation authored Mar 29, 2023
1 parent 2256dfd commit 658e9f8
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 13 deletions.
12 changes: 12 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,18 @@
"console": "integratedTerminal",
"cwd": "${workspaceFolder}"
},
{
"name": "test_multiple_databases)",
"type": "python",
"request": "launch",
"module": "pytest",
"args": [
"tests/test_multiple_databases.py",
"-sx"
],
"console": "integratedTerminal",
"cwd": "${workspaceFolder}"
},
{
"name": "test migrations)",
"type": "python",
Expand Down
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ test:
pytest tests/test_query_caching.py -s -x;
pytest tests/test_querying.py -s -x;
pytest tests/test_query_no_caching.py -s -x;
pytest tests/test_multiple_databases.py -s -x;

test-migrations:
python tests/migrations/test_migrations.py
26 changes: 14 additions & 12 deletions pydbantic/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
Boolean,
Date,
DateTime,
Float,
Integer,
LargeBinary,
Numeric,
Expand Down Expand Up @@ -79,16 +80,17 @@ def get_model_getter(model, primary_key, primary_key_value):


class BaseMeta:
translations: dict = {
str: sqlalchemy.String,
int: sqlalchemy.Integer,
float: sqlalchemy.Float,
bool: sqlalchemy.Boolean,
dict: sqlalchemy.LargeBinary,
list: sqlalchemy.LargeBinary,
tuple: sqlalchemy.LargeBinary,
}
tables: dict = {}
def __init__(self):
self.translations: dict = {
str: sqlalchemy.String,
int: sqlalchemy.Integer,
float: sqlalchemy.Float,
bool: sqlalchemy.Boolean,
dict: sqlalchemy.LargeBinary,
list: sqlalchemy.LargeBinary,
tuple: sqlalchemy.LargeBinary,
}
self.tables: dict = {}


def Relationship(
Expand Down Expand Up @@ -116,6 +118,7 @@ def Relationship(
Boolean,
JSON,
VARCHAR,
Float,
]


Expand Down Expand Up @@ -402,8 +405,6 @@ def not_matches(self, choices: List[Any]) -> DataBaseModelCondition:


class DataBaseModel(BaseModel):
__metadata__: BaseMeta = BaseMeta()

class Config:
arbitrary_types_allowed = True

Expand Down Expand Up @@ -497,6 +498,7 @@ def deserialize(cls: Type[T], data, expected_type=None):

@classmethod
def setup(cls: Type[T], database) -> None:
cls.__metadata__ = database.__metadata__
cls.__tablename__ = getattr(cls, "__tablename__", cls.__name__)
cls.update_backward_refs()

Expand Down
3 changes: 2 additions & 1 deletion pydbantic/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from sqlalchemy import create_engine

from pydbantic.cache import Redis
from pydbantic.core import DatabaseInit, DataBaseModel, TableMeta
from pydbantic.core import BaseMeta, DatabaseInit, DataBaseModel, TableMeta
from pydbantic.translations import DEFAULT_TRANSLATIONS


Expand Down Expand Up @@ -49,6 +49,7 @@ def __init__(
else {},
)
self.use_alembic = use_alembic
self.__metadata__: BaseMeta = BaseMeta()

self.DEFAULT_TRANSLATIONS = DEFAULT_TRANSLATIONS

Expand Down
26 changes: 26 additions & 0 deletions tests/test_multiple_databases.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import pytest

from pydbantic import Database, DataBaseModel


@pytest.mark.asyncio
async def test_multiple_database():
class DB1Model1(DataBaseModel):
__tablename__ = "model1"
data: str
data2: str

class DB2Model1(DataBaseModel):
__tablename__ = "model1"
data: str
data2: str

db1 = await Database.create("sqlite:///db1", tables=[DB1Model1])
db2 = await Database.create("sqlite:///db2", tables=[DB2Model1])

assert not await DB1Model1.all()
assert not await DB2Model1.all()

await DB1Model1.create(data="1", data2="2")
assert await DB1Model1.all()
assert not await DB2Model1.all()

0 comments on commit 658e9f8

Please sign in to comment.