Skip to content

Commit

Permalink
Better table name generation logic
Browse files Browse the repository at this point in the history
  • Loading branch information
mitsuhiko committed Mar 18, 2011
1 parent 1be46e0 commit 77f1a2b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
16 changes: 15 additions & 1 deletion flaskext/sqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,17 +429,31 @@ def get_engine(self):
return rv


def _defines_primary_key(d):
"""Figures out if the given dictonary defines a primary key column."""
return any(v.primary_key for k, v in d.iteritems()
if isinstance(v, sqlalchemy.Column))


class _BoundDeclarativeMeta(DeclarativeMeta):

def __new__(cls, name, bases, d):
tablename = d.get('__tablename__')
if not tablename:

# generate a table name automatically if it's missing and the
# class dictionary declares a primary key. We cannot always
# attach a primary key to support model inheritance that does
# not use joins. We also don't want a table name if a whole
# table is defined
if not tablename and not d.get('__table__') and \
_defines_primary_key(d):
def _join(match):
word = match.group()
if len(word) > 1:
return ('_%s_%s' % (word[:-1], word[-1])).lower()
return '_' + word.lower()
d['__tablename__'] = _camelcase_re.sub(_join, name).lstrip('_')

return DeclarativeMeta.__new__(cls, name, bases, d)

def __init__(self, name, bases, d):
Expand Down
18 changes: 17 additions & 1 deletion test_sqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ def test(self):

class RegressionTestCase(unittest.TestCase):

def test_polymorphic_inheritance(self):
def test_joined_inheritance(self):
app = flask.Flask(__name__)
db = sqlalchemy.SQLAlchemy(app)

Expand All @@ -298,6 +298,22 @@ class SubBase(Base):
self.assertEqual(SubBase.__tablename__, 'sub_base')
db.create_all()

def test_single_table_inheritance(self):
app = flask.Flask(__name__)
db = sqlalchemy.SQLAlchemy(app)

class Base(db.Model):
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.Unicode(20))
__mapper_args__ = {'polymorphic_on': type}

class SubBase(Base):
__mapper_args__ = {'polymorphic_identity': 'sub'}

self.assertEqual(Base.__tablename__, 'base')
self.assertEqual(SubBase.__tablename__, 'base')
db.create_all()


if __name__ == '__main__':
unittest.main()

0 comments on commit 77f1a2b

Please sign in to comment.