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.

80 lines
2.6 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2017 Therp BV <http://therp.nl>
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  4. from ..identifier_adapter import IdentifierAdapter
  5. from openerp import api, fields, models
  6. class CreateIndexesLine(models.TransientModel):
  7. _inherit = 'cleanup.purge.line'
  8. _name = 'cleanup.create_indexes.line'
  9. purged = fields.Boolean('Created')
  10. wizard_id = fields.Many2one('cleanup.create_indexes.wizard')
  11. field_id = fields.Many2one('ir.model.fields', required=True)
  12. @api.multi
  13. def purge(self):
  14. tables = set()
  15. for field in self.mapped('field_id'):
  16. model = self.env[field.model]
  17. name = '%s_%s_index' % (model._table, field.name)
  18. self.env.cr.execute(
  19. 'create index %s ON %s (%s)',
  20. (
  21. IdentifierAdapter(name, quote=False),
  22. IdentifierAdapter(model._table),
  23. IdentifierAdapter(field.name),
  24. ),
  25. )
  26. tables.add(model._table)
  27. for table in tables:
  28. self.env.cr.execute(
  29. 'analyze %s', (IdentifierAdapter(model._table),)
  30. )
  31. self.write({
  32. 'purged': True,
  33. })
  34. class CreateIndexesWizard(models.TransientModel):
  35. _inherit = 'cleanup.purge.wizard'
  36. _name = 'cleanup.create_indexes.wizard'
  37. _description = 'Create indexes'
  38. purge_line_ids = fields.One2many(
  39. 'cleanup.create_indexes.line', 'wizard_id',
  40. )
  41. @api.multi
  42. def find(self):
  43. for field in self.env['ir.model.fields'].search([
  44. ('index', '=', True),
  45. ]):
  46. if field.model not in self.env.registry:
  47. continue
  48. model = self.env[field.model]
  49. name = '%s_%s_index' % (model._table, field.name)
  50. self.env.cr.execute(
  51. 'select indexname from pg_indexes '
  52. 'where indexname=%s and tablename=%s',
  53. (name, model._table)
  54. )
  55. if self.env.cr.rowcount:
  56. continue
  57. self.env.cr.execute(
  58. 'select a.attname '
  59. 'from pg_attribute a '
  60. 'join pg_class c on a.attrelid=c.oid '
  61. 'join pg_tables t on t.tablename=c.relname '
  62. 'where attname=%s and c.relname=%s',
  63. (field.name, model._table,)
  64. )
  65. if not self.env.cr.rowcount:
  66. continue
  67. yield (0, 0, {
  68. 'name': '%s.%s' % (field.model, field.name),
  69. 'field_id': field.id,
  70. })