PageRenderTime 285ms CodeModel.GetById 160ms app.highlight 15ms RepoModel.GetById 106ms app.codeStats 0ms

/sqlautocode/formatter.py

https://code.google.com/p/sqlautocode/
Python | 123 lines | 117 code | 3 blank | 3 comment | 10 complexity | 75bf69edee1445bd1e96dd019a249e72 MD5 | raw file
  1import sqlalchemy
  2import config, constants, util
  3
  4def textclause_repr(self):
  5    return 'text(%r)' % self.text
  6
  7def table_repr(self):
  8    data = {
  9        'name': self.name,
 10        'columns': constants.NLTAB.join([repr(cl) for cl in self.columns]),
 11        'constraints': constants.NLTAB.join(
 12            [repr(cn) for cn in self.constraints
 13            if not isinstance(cn, sqlalchemy.PrimaryKeyConstraint)]),
 14        'index': '',
 15        'schema': self.schema != None and ",\n%sschema='%s'" % (constants.TAB, self.schema) or '',
 16        }
 17
 18    if data['constraints']:
 19        data['constraints'] = '\n%s%s,' % (constants.TAB, data['constraints'])
 20
 21    if data['columns']:
 22        data['columns'] = '\n%s%s' % (constants.TAB, data['columns'])
 23
 24    return util.as_out_str(constants.TABLE % data)
 25
 26def _repr_coltype_as(coltype, as_type):
 27    """repr a Type instance as a super type."""
 28
 29    specimen = object.__new__(as_type)
 30    specimen.__dict__ = coltype.__dict__
 31    return repr(specimen)
 32
 33def column_repr(self):
 34    kwarg = []
 35    if self.key != self.name:
 36        kwarg.append( 'key')
 37
 38    if hasattr(self, 'primary_key'):
 39        kwarg.append( 'primary_key')
 40
 41    if not self.nullable:
 42        kwarg.append( 'nullable')
 43    if self.onupdate:
 44        kwarg.append( 'onupdate')
 45    #issue: 
 46    #http://www.sqlalchemy.org/trac/wiki/06Migration#AnImportantExpressionLanguageGotcha
 47    if self.default is not None:
 48        kwarg.append( 'default')
 49    elif self.server_default:
 50        self.default = self.server_default.arg
 51        kwarg.append( 'default')
 52
 53    ks = ', '.join('%s=%r' % (k, getattr(self, k)) for k in kwarg )
 54
 55    name = self.name
 56
 57    if not hasattr(config, 'options') and config.options.generictypes:
 58        coltype = repr(self.type)
 59    elif type(self.type).__module__ == 'sqlalchemy.types':
 60        coltype = repr(self.type)
 61    else:
 62        # Try to 'cast' this column type to a cross-platform type
 63        # from sqlalchemy.types, dropping any database-specific type
 64        # arguments.
 65        for base in type(self.type).__mro__:
 66            if (base.__module__ == 'sqlalchemy.types' and
 67                base.__name__ in sqlalchemy.__all__):
 68                coltype = _repr_coltype_as(self.type, base)
 69                break
 70        # FIXME: if a dialect has a non-standard type that does not
 71        # derive from an ANSI type, there's no choice but to ignore
 72        # generic-types and output the exact type. However, import
 73        # headers have already been output and lack the required
 74        # dialect import.
 75        else:
 76            coltype = repr(self.type)
 77
 78    data = {'name': self.name,
 79            'type': coltype,
 80            'constraints': ', '.join([repr(cn) for cn in self.constraints]),
 81            'args': ks and ks or '',
 82            }
 83
 84    if data['constraints']:
 85        data['constraints'] = ', ' + data['constraints']
 86    if data['args']:
 87        data['args'] = ', ' + data['args']
 88
 89    return util.as_out_str(constants.COLUMN % data)
 90
 91def foreignkeyconstraint_repr(self):
 92    data = {'name': repr(self.name),
 93            'names': repr([x.parent.name for x in self.elements]),
 94            'specs': repr([x._get_colspec() for x in self.elements])
 95            }
 96    return util.as_out_str(constants.FOREIGN_KEY % data)
 97
 98def index_repr(index):
 99    cols = []
100    for column in index.columns:
101        # FIXME: still punting on the issue of unicode table names
102        if util.is_python_identifier(column.name):
103            cols.append('%s.c.%s' % (column.table.name, column.name))
104        else:
105            cols.append('%s.c[%r]' % (column.table.name, column.name))
106
107    data = {'name': repr(index.name),
108            'columns': ', '.join(cols),
109            'unique': repr(index.unique),
110            }
111    return util.as_out_str(constants.INDEX % data)
112
113def check_constraint_repr(cc):
114    data = {'sqltext': cc.sqltext}
115    return util.as_out_str(constants.CHECK_CONSTRAINT % data)
116
117def monkey_patch_sa():
118    sqlalchemy.sql.expression._TextClause.__repr__ = textclause_repr
119    sqlalchemy.schema.Table.__repr__ = table_repr
120    sqlalchemy.schema.Column.__repr__ = column_repr
121    sqlalchemy.schema.ForeignKeyConstraint.__repr__ = foreignkeyconstraint_repr
122    sqlalchemy.schema.Index.__repr__ = index_repr
123    sqlalchemy.schema.CheckConstraint.__repr__ = check_constraint_repr