generate.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. #!/usr/bin/env python
  2. import os
  3. import re
  4. import MySQLdb as mysql
  5. from itertools import combinations
  6. from argparse import ArgumentParser
  7. from singplur import singularize
  8. PRIMARY_KEY = 'id'
  9. TAB = '\t'
  10. def php_value(data, indent=0):
  11. """
  12. Convert Python data types to PHP code. Tuples or lists are used for
  13. single-line arrays, sets for multiline arrays, dictionaries for associative
  14. arrays, and strings are encapsulated in single quotes.
  15. """
  16. if isinstance(data, str):
  17. return "'%s'" % data.replace("'", "\\'")
  18. tabs = (indent + 1) * TAB
  19. if type(data) in (list, tuple):
  20. return 'array(%s)' % ', '.join(map(php_value, data))
  21. elif isinstance(data, dict):
  22. if not data:
  23. return 'array()'
  24. lines = ["'%s' => %s" % (k, php_value(v, indent + 1))
  25. for k, v in data.iteritems()]
  26. elif isinstance(data, set):
  27. if not data:
  28. return 'array()'
  29. lines = [php_value(item, indent + 1) for item in data]
  30. else:
  31. return str(data)
  32. return 'array(\n%s\n%s)' % (',\n'.join([tabs + line for line in lines]),
  33. indent * TAB)
  34. def php_assoc((arg, kwargs)):
  35. assocs = ["'%s' => %s" % (k, php_value(v)) for k, v in kwargs.iteritems()]
  36. return 'array(%s)' % ', '.join([php_value(arg)] + assocs)
  37. def php_static_var(name, value):
  38. return 'static $%s = %s;' % (name, value)
  39. def php_static_array(name, values):
  40. array = 'array(%s)' if len(values) < 2 \
  41. else 'array(\n{0}{0}%s\n{0})'.format(TAB)
  42. lines = map(php_assoc, values)
  43. array_values = (',\n' + 2 * TAB).join(lines)
  44. return php_static_var(name, array % array_values)
  45. def php_block(php_code):
  46. return '<?php\n\n%s\n\n?>' % php_code
  47. class Model(object):
  48. def __init__(self, table, options):
  49. self.table = table
  50. self.options = options
  51. self.attributes = []
  52. self.primary_key = []
  53. self.foreign_keys = []
  54. self.has_many = []
  55. self.has_one = []
  56. self.belongs_to = []
  57. def __str__(self):
  58. return '<Model "%s" table=%s>' % (self.name(), self.table)
  59. def singular_name(self):
  60. return singularize(self.table)
  61. def classname(self):
  62. return singularize(re.sub('(?:^|_)([a-z])',
  63. lambda m: m.group(1).upper(), self.table))
  64. def read_attributes(self, conn):
  65. fields = read_fields(conn, self.table)
  66. is_protected = lambda field: field['Key'] in ('PRI', 'MUL')
  67. self.protected_fields, accessible = partition(is_protected, fields)
  68. self.accessible_attr = [field['Field'] for field in accessible]
  69. def process_keys(self, models):
  70. for field in self.protected_fields:
  71. name = field['Field']
  72. if field['Key'] == 'PRI':
  73. self.primary_key.append(name)
  74. elif field['Key'] == 'MUL':
  75. self.add_foreign_key(name, models)
  76. # Has-many through
  77. if len(self.belongs_to) > 1:
  78. relations = [find_model(name, models)
  79. for name, options in self.belongs_to]
  80. for a, b in combinations(relations, 2):
  81. a.add_has_relation(b, through=self.table)
  82. b.add_has_relation(a, through=self.table)
  83. def add_has_relation(self, model, **kwargs):
  84. options = self.relopts(model)
  85. options.update(kwargs)
  86. name = model.singular_name()
  87. if [self.singular_name(), name] in self.options.get('has_one', []):
  88. self.has_one.append((name, options))
  89. else:
  90. self.has_many.append((model.table, options))
  91. def relopts(self, model, **kwargs):
  92. relopts = kwargs
  93. if self.options.get('create_select', True):
  94. relopts['select'] = PRIMARY_KEY + ', ' \
  95. + ', '.join(model.accessible_attr)
  96. return relopts
  97. def add_foreign_key(self, name, models):
  98. self.foreign_keys.append(name)
  99. singular = re.sub('_' + PRIMARY_KEY + '$', '', name)
  100. try:
  101. other_model = find_model(singular, models)
  102. except ValueError:
  103. return
  104. self.belongs_to.append((singular, self.relopts(other_model)))
  105. other_model.add_has_relation(self)
  106. def strip_array(self, attr):
  107. array = getattr(self, attr)
  108. if len(array) == 1:
  109. relation, opts = array[0]
  110. if not len(opts):
  111. return php_static_var(attr, php_value(relation))
  112. def php_has_many(self):
  113. stripped = self.strip_array('has_many')
  114. if stripped:
  115. return stripped
  116. if self.has_many:
  117. return php_static_array('has_many', self.has_many)
  118. def php_has_one(self):
  119. stripped = self.strip_array('has_one')
  120. if stripped:
  121. return stripped
  122. if self.has_one:
  123. return php_static_array('has_one', self.has_one)
  124. def php_belongs_to(self):
  125. stripped = self.strip_array('belongs_to')
  126. if stripped:
  127. return stripped
  128. if self.belongs_to:
  129. return php_static_array('belongs_to', self.belongs_to)
  130. def php_has_many_and_belongs_to(self):
  131. if not self.has_many or not self.belongs_to:
  132. return
  133. def php_attr_accessible(self):
  134. # All attributes except primary/foreign keys are accessible
  135. if self.accessible_attr:
  136. return php_static_var('attr_accessible',
  137. php_value(self.accessible_attr))
  138. def generate_php(self, add_php_block=False):
  139. # Class definition
  140. classname = self.classname()
  141. if self.options.get('namespace'):
  142. namespace = 'namespace %s;\n\n' % self.options['namespace']
  143. #classname = options['namespace'] + '\\' + classname
  144. else:
  145. namespace = ''
  146. classdef = 'class %s extends ActiveRecord\\Model {\n%%s\n}' % classname
  147. # Indented lines within class definition
  148. lines = []
  149. if self.options.get('create_relations', True):
  150. lines += [
  151. self.php_has_many(),
  152. self.php_has_one(),
  153. self.php_belongs_to(),
  154. self.php_has_many_and_belongs_to(),
  155. ]
  156. if self.options.get('create_accessible', True):
  157. lines.append(self.php_attr_accessible())
  158. inner_lines = [TAB + line for line in lines if line is not None]
  159. php = namespace + classdef % '\n'.join(inner_lines)
  160. return php_block(php) if add_php_block else php
  161. def filename(self):
  162. return self.classname().replace('_', '') + '.php'
  163. def create_path_from_dir(self, dirname):
  164. return os.path.dirname(dirname + '//') + '/' + self.filename()
  165. def save_in_file(self, path):
  166. code = self.generate_php(True)
  167. f = open(path, 'w')
  168. f.write(code)
  169. f.close()
  170. def find_model(singular_name, models):
  171. for model in models:
  172. if model.singular_name() == singular_name:
  173. return model
  174. raise ValueError('No model found for "%s".' % singular_name)
  175. def flatten(iterable):
  176. return reduce(lambda a, b: a + b, map(list, iterable), [])
  177. def create_models(conn, options):
  178. models = [Model(table, options) for table in read_tables(conn)]
  179. for model in models:
  180. model.read_attributes(conn)
  181. for model in models:
  182. model.process_keys(models)
  183. return models
  184. def refine_model(conn, model, models):
  185. for field in read_fields(conn, model.table):
  186. model.add_attribute(field, models)
  187. def read_tables(conn):
  188. cur = conn.cursor()
  189. cur.execute('show tables')
  190. tables = flatten(cur.fetchall())
  191. cur.close()
  192. return tables
  193. def read_fields(conn, table):
  194. cur = conn.cursor(mysql.cursors.DictCursor)
  195. cur.execute('show columns from `%s`' % table)
  196. fields = cur.fetchall()
  197. cur.close()
  198. return fields
  199. def partition(callback, iterable):
  200. """
  201. Partition an iterable into two parts using a callback that returns a
  202. boolean.
  203. Example:
  204. >>> partition(lambda x: x & 1, range(6))
  205. ([1, 3, 5], [0, 2, 4])
  206. """
  207. a, b = [], []
  208. for item in iterable:
  209. (a if callback(item) else b).append(item)
  210. return a, b
  211. def parse_options():
  212. parser = ArgumentParser(description='Generate PHPActiveRecord models.')
  213. parser.add_argument('dbname', help='database name')
  214. parser.add_argument('-H', '--host', metavar='ADDRESS', default='localhost',
  215. help='MySQL server address')
  216. parser.add_argument('-u', '--user', metavar='USERNAME', default='root',
  217. help='MySQL username')
  218. parser.add_argument('-p', '--password', default='', help='MySQL password')
  219. parser.add_argument('--has-one', nargs=2, dest='opt_has_one',
  220. help='one-to-one relationships of the form '
  221. '\'payment receipt\', where one payment has one '
  222. 'receipt', action='append', default=[])
  223. parser.add_argument('--namespace', default='', dest='opt_namespace',
  224. help='PHP namespace to create models classes in')
  225. parser.add_argument('--create-select', action='store_true',
  226. help='whether to create the \'select\' option in '
  227. 'relations', dest='opt_create_select')
  228. parser.add_argument('--create-accessible', dest='opt_create_accessible',
  229. help='whether to create the \'$attr_accessible\' '
  230. 'variable, containing all ' 'attributes except '
  231. 'primary or foreing keys', action='store_true')
  232. parser.add_argument('-a', '--create-all', action='store_true',
  233. help='create all available options and variables')
  234. parser.add_argument('-d', '--dir', help='directory to save model files in')
  235. parser.add_argument('-s', '--spaces', nargs='?', const=4, type=int,
  236. help='use spaces instead of tabs (4 by default)')
  237. args = parser.parse_args()
  238. options = {}
  239. for arg, value in args._get_kwargs():
  240. if arg[:4] == 'opt_':
  241. options[arg[4:]] = value
  242. if args.create_all:
  243. options['create_select'] = options['create_accessible'] = True
  244. if args.spaces:
  245. TAB = args.spaces * ' '
  246. return args, options
  247. if __name__ == '__main__': # pragma: nocover
  248. args, options = parse_options()
  249. conn = mysql.connect(args.host, args.user, args.password, args.dbname)
  250. models = create_models(conn, options)
  251. conn.close()
  252. if args.dir:
  253. if not os.path.exists(args.dir):
  254. os.makedirs(args.dir)
  255. for model in models:
  256. path = model.create_path_from_dir(args.dir)
  257. model.save_in_file(path)
  258. print 'Saved model %s in %s' % (model.classname(), path)
  259. else:
  260. for model in models:
  261. print model.generate_php()