Daily Snippet, Developer to developer

python’s time:using sqlautocode

While playing with sqlalchemy, I want to generate entity class for tables in database. That’s sqlautocode come in.

The first thing to do  to use sqlautocode is declare class DummyConfig where we put connection string.

I have a sqlite file ‘sqlal.db’ and table users and employee.

class DummyConfig:
    def __init__(self, engine='sqlite:///D:/PROYEK/Sample And Exercise goes HERE/pyCoba/src/db/sqlal.db'):
        self.engine  = engine

    example = True
    schema = None
    interactive = None

declare some variable and print your entity class.

from sqlautocode.declarative import ModelFactory
from sqlalchemy.orm import class_mapper

config = DummyConfig()
factory = ModelFactory(config)

factory.used_model_names = []
factory.used_table_names = []

User = factory.create_model(factory._metadata.tables['users'])
Employee = factory.create_model(factory._metadata.tables['employee'])

class_mapper(User, True)
class_mapper(Employee, True)

print User.__repr__()
print Employee.__repr__()

This is the output

class User(DeclarativeBase):
 __tablename__ = 'users'

 #column definitions
 fullname = Column(u'fullname', VARCHAR(length=None, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False))
 id = Column(u'id', INTEGER(), primary_key=True, nullable=False)
 name = Column(u'name', VARCHAR(length=None, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False))
 password = Column(u'password', VARCHAR(length=None, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False))

 #relation definitions

class Employee(DeclarativeBase):
 __tablename__ = 'employee'

 #column definitions
 id = Column(u'id', INTEGER(), primary_key=True, nullable=False)
 nama = Column(u'nama', CHAR(length=None, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False))

 #relation definitions

One thought on “python’s time:using sqlautocode

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s