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.

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