PageRenderTime 325ms CodeModel.GetById 161ms app.highlight 14ms RepoModel.GetById 147ms app.codeStats 0ms

/sqlautocode/main.py

https://code.google.com/p/sqlautocode/
Python | 139 lines | 117 code | 14 blank | 8 comment | 20 complexity | 7414ee583848b955c4771f9a176208a4 MD5 | raw file
  1import sys
  2import config, util, constants
  3from util import emit
  4from declarative import ModelFactory
  5
  6def emit_table(indent, db, options, table):
  7    """Emit table representation."""
  8    emit('%s%s%s%s = %r' % (indent, options.table_prefix, table.name, options.table_suffix, table))
  9    emit_index(indent, db, options, table)
 10
 11def emit_z3c_objects(indent, db, options, table):
 12    emit_table(indent, db, options, table)
 13    emit(indent + ('class %(tn)sObject(MappedClassBase): pass\n'
 14                    '%(tab)smapper(%(tn)sObject, %(tn)s)') % {'tn':table.name, 'tab':indent})
 15
 16def emit_index(indent, db, options, table):
 17    """docstring for emit_index"""
 18    if not options.noindex:
 19        indexes = []
 20        if not table.indexes:
 21            # for certain dialects we need to include index support
 22            if hasattr(db.dialect, 'indexloader'):
 23                indexes = db.dialect.indexloader(db).indexes(table)
 24            else:
 25                print >>config.err, 'It seems that this dialect does not support indexes!'
 26        else:
 27            indexes = list(table.indexes)
 28        emit(*[indent + repr(index) for index in indexes])
 29
 30def main():
 31    config.configure()
 32
 33    options = config.options
 34    if options.declarative:
 35        config.interactive = None
 36        if options.interactive:
 37            config.interactive = True
 38        config.schema = None
 39        if options.schema:
 40            config.schema = options.schema
 41        config.example=False
 42        if options.example:
 43            config.example=True
 44        factory = ModelFactory(config)
 45        emit(repr(factory))
 46        config.out.close()
 47        config.out = sys.stdout
 48        print >>config.err, "Output written to %s" % options.output
 49        return
 50
 51    import formatter
 52    formatter.monkey_patch_sa()
 53    
 54    import sqlalchemy
 55    from sqlalchemy.engine.reflection import Inspector
 56    db, options = config.engine, config.options
 57    metadata = sqlalchemy.MetaData(db)
 58
 59    print >>config.err, 'Starting...'
 60    conn = db.connect()
 61    inspector = Inspector.from_engine(conn)
 62
 63    if options.schema != None:
 64        reflection_schema=options.schema
 65    else:
 66        try:
 67            reflection_schema = inspector.default_schema_name
 68        except NotImplementedError:
 69            reflection_schema = None
 70
 71    tablenames = inspector.get_table_names(reflection_schema)
 72
 73    # fixme: don't set up output until we're sure there's work to do!
 74    if options.tables:
 75        subset, missing, unglobbed = util.glob_intersection(tablenames,
 76                                                            options.tables)
 77        for identifier in missing:
 78            print >>config.err, 'Table "%s" not found.' % identifier
 79        for glob in unglobbed:
 80            print >>config.err, '"%s" matched no tables.' % glob
 81        if not subset:
 82            print >>config.err, "No tables matched!"
 83            sys.exit(1)
 84
 85        tablenames = subset
 86
 87    # some header with imports
 88    if options.generictypes:
 89        dialect = ''
 90    else:
 91        d1 = 'from sqlalchemy.databases.%s import *\n' % db.name
 92        d2 = 'from sqlalchemy.dialects.%s import *\n' % db.name
 93        #Determine with one is correct...
 94        dialect = util.select_imports([d1, d2])
 95    
 96    header = options.z3c and constants.HEADER_Z3C or constants.HEADER
 97    emit(header % {'dialect': dialect, 'encoding': options.encoding})
 98
 99    for tname in tablenames:
100        print >>config.err, "Generating python model for table %s" % (
101            util.as_sys_str(tname))
102
103        table = sqlalchemy.Table(tname, metadata, schema=reflection_schema, autoload=True)
104        if options.schema is None:
105            # we're going to remove the schema from the table so that it
106            #  isn't rendered in the output.  If we don't put back the
107            #  correct value, it may cause errors when other tables reference
108            #  this one.
109            original_schema = table.schema
110            table.schema = None
111        else:
112            original_schema = options.schema
113
114        indent = ''
115
116        INC = '\n\n'
117        emit(INC)
118        if options.z3c:
119            emit_z3c_objects(constants.TAB, db, options, table)
120        else:
121            emit_table('', db, options, table)
122
123        table.schema = original_schema
124
125    if options.z3c:
126        emit(constants.FOOTER_Z3C)
127
128    # print some example
129    if options.example:
130        emit('\n' + constants.FOOTER_EXAMPLE % {
131            'url': unicode(db.url), 'tablename': tablenames[0]})
132
133    if options.output:
134        emit('\n')
135        config.out.close()
136        config.out = sys.stdout
137        print >>config.err, "Output written to %s" % options.output
138
139# vim:ts=4:sw=4:expandtab