March 20, 2012 15:03 / 0 comments / peewee

For fun I put together a small script that is capable of introspecting databases and generating peewee models. I borrowed the crucial bits from django's codebase, which has methods for introspecting column types and foreign key constraints.

The code is hopefully rather straightforward - it simply grabs the list of tables, column type information which is then mapped to peewee field types, then finally resolves foreign keys. The generated models are then dumped to standard out, along with a database declaration.

It is pretty new and I have not tested it extensively but am hopeful that it will make it easier to quickly throw a programmatic interface on top of existing dbs.

A little example

First you'll need to install peewee if you haven't already. The script was added a bit ago but wasn't added to the setup.py until 0.9.2:

pip install peewee

The script by default is configured to run with postgresql:

pwiz.py awesome_db --user=postgres

The generated output will look like:

from peewee import *

database = PostgresqlDatabase('awesome_db', **{'user': 'postgres'})

class UnknownFieldType(object):
    pass

class BaseModel(Model):
    class Meta:
        database = database

class Account(BaseModel):
    name = CharField()

    class Meta:
        db_table = 'account'

class Users(BaseModel):
    active = BooleanField()
    admin = BooleanField()
    email = CharField()
    join_date = DateTimeField()
    password = CharField()
    username = CharField()

    class Meta:
        db_table = 'users'

class Apikey(BaseModel):
    key = CharField()
    secret = CharField()
    user = ForeignKeyField(to=Users, db_column='user_id')

    class Meta:
        db_table = 'apikey'

Should the script encounter a field type it does not know how to handle it will create a reference to it by instantiating the "UnknownFieldType" class as a placeholder. The outputted code can then be imported and the models used.

Let's pretend we did:

pwiz.py awesome_db --user=postgres > pwiz_out.py

Then we can open an interactive shell and start using the models:

>>> from pwiz_out import *
>>> u = Users.get()
>>> u.username
u'charles'

Command line options

pwiz supports some standard database connection arguments:

Usage: pwiz.py [options] database_name

Options:
  -h, --help            show this help message and exit
  -H HOST, --host=HOST  
  -p PORT, --port=PORT  
  -u USER, --user=USER  
  -P PASSWORD, --password=PASSWORD
  -e ENGINE, --engine=ENGINE

Conclusion

I hope you find this script useful! Future improvements to look for:

Let me know if you have any questions or suggestions for improvements, thanks for reading!

Comments (0)


Commenting has been closed, but please feel free to contact me