Skip to content

Commit 3a49ddc

Browse files
authored
Merge pull request #578 from TotallyNotRobots/support-sql-orm
Add support for sqlalchemy ORM objects
2 parents e9dbbd0 + b8c45bf commit 3a49ddc

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

cloudbot/plugin.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from functools import partial
77
from operator import attrgetter
88
from pathlib import Path
9-
from typing import Dict, List, MutableMapping, Optional
9+
from typing import Dict, List, MutableMapping, Optional, Type, cast
1010
from weakref import WeakValueDictionary
1111

1212
import sqlalchemy
@@ -54,6 +54,9 @@ def find_tables(code):
5454
):
5555
# if it's a Table, and it's using our metadata, append it to the list
5656
tables.append(obj)
57+
elif isinstance(obj, type) and issubclass(obj, database.Base):
58+
obj = cast(Type[database.Base], obj)
59+
tables.append(obj.__table__)
5760

5861
return tables
5962

tests/core_tests/test_plugin_manager.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from unittest.mock import MagicMock
66

77
import pytest
8+
import sqlalchemy as sa
89
from sqlalchemy import Column, String, Table, inspect
910

1011
from cloudbot import hook
@@ -56,6 +57,28 @@ def test_get_plugin(mock_manager):
5657
assert mock_manager.find_plugin("test") is None
5758

5859

60+
def test_find_tables(mock_manager):
61+
file_path = mock_manager.bot.plugin_dir / "test.py"
62+
file_name = file_path.name
63+
64+
class TestTable(database.Base):
65+
__tablename__ = "foo"
66+
67+
test_id = sa.Column(sa.Integer, primary_key=True)
68+
69+
mod = MockModule(tbl=TestTable)
70+
obj = Plugin(
71+
str(file_path),
72+
file_name,
73+
"test",
74+
mod,
75+
)
76+
77+
table_names = [t.name for t in obj.tables]
78+
79+
assert table_names == ["foo"]
80+
81+
5982
def test_can_load(mock_manager):
6083
mock_manager.bot.config.clear()
6184

0 commit comments

Comments
 (0)