Skip to content

Commit 287f67b

Browse files
committed
use the inflection library for converting Table class names to database table names
Whilst investigating the bug with mixins, I realised that if a `Table` has a name like `ManagerA`, the database table was wrongly being called `manager` instead of `manager_a`. To avoid similar subtle bugs, I replaced the regular expression previously used with a popular library.
1 parent b6f1804 commit 287f67b

File tree

3 files changed

+21
-11
lines changed

3 files changed

+21
-11
lines changed

piccolo/utils/naming.py

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,8 @@
1-
import re
1+
import inflection
22

33

4-
_camel_words = re.compile(r"([A-Z][a-z0-9_]+)")
5-
6-
7-
def _camel_to_snake(s):
8-
""" Convert CamelCase to snake_case.
4+
def _camel_to_snake(string: str):
5+
"""
6+
Convert CamelCase to snake_case.
97
"""
10-
return "_".join(
11-
[
12-
i.lower() for i in _camel_words.split(s)[1::2]
13-
]
14-
)
8+
return inflection.underscore(string)

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ black
44
colorama>=0.4.0
55
Jinja2>=2.11.0
66
targ>=0.1.0
7+
inflection>=0.5.1

tests/utils/test_naming.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from piccolo.utils.naming import _camel_to_snake
2+
from unittest import TestCase
3+
4+
5+
class TestCamelToSnake(TestCase):
6+
def test_converting_tablenames(self):
7+
"""
8+
Make sure Table names are converted correctly.
9+
"""
10+
self.assertEqual(_camel_to_snake("HelloWorld"), "hello_world")
11+
self.assertEqual(_camel_to_snake("Manager1"), "manager1")
12+
self.assertEqual(_camel_to_snake("ManagerAbc"), "manager_abc")
13+
self.assertEqual(_camel_to_snake("ManagerABC"), "manager_abc")
14+
self.assertEqual(_camel_to_snake("ManagerABCFoo"), "manager_abc_foo")
15+
self.assertEqual(_camel_to_snake("ManagerA"), "manager_a")

0 commit comments

Comments
 (0)