/sqlautocode/main.py

https://code.google.com/p/sqlautocode/ · Python · 139 lines · 104 code · 23 blank · 12 comment · 30 complexity · 7414ee583848b955c4771f9a176208a4 MD5 · raw file

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