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.

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