You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

122 lines
4.4 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2014-2016 Therp BV <http://therp.nl>
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  4. from openerp import _, api, fields, models
  5. from openerp.exceptions import UserError
  6. class CleanupPurgeLineColumn(models.TransientModel):
  7. _inherit = 'cleanup.purge.line'
  8. _name = 'cleanup.purge.line.column'
  9. model_id = fields.Many2one('ir.model', 'Model', required=True,
  10. ondelete='CASCADE')
  11. wizard_id = fields.Many2one(
  12. 'cleanup.purge.wizard.column', 'Purge Wizard', readonly=True)
  13. @api.multi
  14. def purge(self):
  15. """
  16. Unlink columns upon manual confirmation.
  17. """
  18. for line in self:
  19. if line.purged:
  20. continue
  21. model_pool = self.env[line.model_id.model]
  22. # Check whether the column actually still exists.
  23. # Inheritance such as stock.picking.in from stock.picking
  24. # can lead to double attempts at removal
  25. self.env.cr.execute(
  26. 'SELECT count(attname) FROM pg_attribute '
  27. 'WHERE attrelid = '
  28. '( SELECT oid FROM pg_class WHERE relname = %s ) '
  29. 'AND attname = %s',
  30. (model_pool._table, line.name))
  31. if not self.env.cr.fetchone()[0]:
  32. continue
  33. self.logger.info(
  34. 'Dropping column %s from table %s',
  35. line.name, model_pool._table)
  36. self.env.cr.execute(
  37. """
  38. ALTER TABLE "%s" DROP COLUMN "%s"
  39. """ % (model_pool._table, line.name))
  40. line.write({'purged': True})
  41. self.env.cr.commit()
  42. return True
  43. class CleanupPurgeWizardColumn(models.TransientModel):
  44. _inherit = 'cleanup.purge.wizard'
  45. _name = 'cleanup.purge.wizard.column'
  46. _description = 'Purge columns'
  47. # List of known columns in use without corresponding fields
  48. # Format: {table: [fields]}
  49. blacklist = {
  50. 'wkf_instance': ['uid'], # lp:1277899
  51. }
  52. @api.model
  53. def get_orphaned_columns(self, model_pools):
  54. """
  55. From openobject-server/openerp/osv/orm.py
  56. Iterate on the database columns to identify columns
  57. of fields which have been removed
  58. """
  59. columns = list(set([
  60. column
  61. for model_pool in model_pools
  62. for column in model_pool._columns
  63. if not (isinstance(model_pool._columns[column],
  64. fields.fields.function) and
  65. not model_pool._columns[column].store)
  66. ]))
  67. columns += models.MAGIC_COLUMNS
  68. columns += self.blacklist.get(model_pools[0]._table, [])
  69. self.env.cr.execute(
  70. "SELECT a.attname FROM pg_class c, pg_attribute a "
  71. "WHERE c.relname=%s AND c.oid=a.attrelid AND a.attisdropped=False "
  72. "AND pg_catalog.format_type(a.atttypid, a.atttypmod) "
  73. "NOT IN ('cid', 'tid', 'oid', 'xid') "
  74. "AND a.attname NOT IN %s",
  75. (model_pools[0]._table, tuple(columns)))
  76. return [column for column, in self.env.cr.fetchall()]
  77. @api.model
  78. def find(self):
  79. """
  80. Search for columns that are not in the corresponding model.
  81. Group models by table to prevent false positives for columns
  82. that are only in some of the models sharing the same table.
  83. Example of this is 'sale_id' not being a field of stock.picking.in
  84. """
  85. res = []
  86. # mapping of tables to tuples (model id, [pool1, pool2, ...])
  87. table2model = {}
  88. for model in self.env['ir.model'].search([]):
  89. if model.model not in self.env:
  90. continue
  91. model_pool = self.env[model.model]
  92. if not model_pool._auto:
  93. continue
  94. table2model.setdefault(
  95. model_pool._table, (model.id, [])
  96. )[1].append(model_pool)
  97. for table, model_spec in table2model.iteritems():
  98. for column in self.get_orphaned_columns(model_spec[1]):
  99. res.append((0, 0, {
  100. 'name': column,
  101. 'model_id': model_spec[0]}))
  102. if not res:
  103. raise UserError(_('No orphaned columns found'))
  104. return res
  105. purge_line_ids = fields.One2many(
  106. 'cleanup.purge.line.column', 'wizard_id', 'Columns to purge')