Reverse engineer SQLAlchemy declarative class definition from existing MySQL database?
-
07-07-2019 - |
Question
I have a pre-existing mysql database containing around 50 tables.
Rather than hand code a declarative style SqlAlchemy class (as shown here) for each table, is there a tool/script/command I can run against the mysql database that will generate a python class in the declarative style for each table in the database?
To take just one table as an example (would generate for all 50 ideally) as follows:
+---------+--------------------+
| dept_no | dept_name |
+---------+--------------------+
| d009 | Customer Service |
| d005 | Development |
| d002 | Finance |
| d003 | Human Resources |
| d001 | Marketing |
| d004 | Production |
| d006 | Quality Management |
| d008 | Research |
| d007 | Sales |
+---------+--------------------+
Is there a tool/script/command that can generate a text file containing something like:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Department(Base):
__tablename__ = 'departments'
dept_no = Column(String(5), primary_key=True)
dept_name = Column(String(50))
def __init__(self, dept_no, dept_name):
self.dept_no = dept_no
self.dept_name = dept_name
def __repr__(self):
return "<Department('%s','%s')>" % (self.dept_no, self.dept_name)
Solution
use sqlautocode:
It is a flexible tool to autogenerate a model from an existing database.
This is a slightly different approach to SqlSoup, which lets you use tables without explicitly defining them. On the other hand, sqlalutocode will generate actual python code.
OTHER TIPS
Now (in 2015) you probably would want to use https://pypi.python.org/pypi/sqlacodegen instead!
Keep in mind declarative can be used with reflected tables. So if startup time weren't a huge issue you could do this:
engine = create_engine('mysql://...')
meta = MetaData()
meta.reflect(bind=engine)
for table in meta.tables.values():
print """
class %s(Base):
__table__ = Table(%r, Base.metadata, autoload=True)
""" % (table.name, table.name)
other than that autocode is probably the way to go.
SqlSoup can perform introspective mapping of an existing SQL schema.