/sqlautocode/formatter.py

https://code.google.com/p/sqlautocode/ · Python · 123 lines · 90 code · 21 blank · 12 comment · 31 complexity · 75bf69edee1445bd1e96dd019a249e72 MD5 · raw file

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