Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse engineer SQLAlchemy declarative class definition from existing MySQL database?

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)
like image 938
Peter McG Avatar asked Sep 15 '09 06:09

Peter McG


3 Answers

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.

like image 126
nosklo Avatar answered Oct 23 '22 18:10

nosklo


Now (in 2015) you probably would want to use https://pypi.python.org/pypi/sqlacodegen instead!

like image 22
Johannes Fahrenkrug Avatar answered Oct 23 '22 20:10

Johannes Fahrenkrug


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.

like image 8
zzzeek Avatar answered Oct 23 '22 20:10

zzzeek