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.

116 lines
4.7 KiB

  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # OpenERP, Open Source Management Solution
  5. # Copyright (C) 2015 Akretion (<http://www.akretion.com>).
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as
  9. # published by the Free Software Foundation, either version 3 of the
  10. # License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. from openerp import models, fields, api
  22. from openerp.osv.orm import setup_modifiers
  23. import StringIO
  24. import base64
  25. import datetime
  26. from lxml import etree
  27. from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
  28. import uuid
  29. class SqlFileWizard(models.TransientModel):
  30. _name = "sql.file.wizard"
  31. _description = "Allow the user to save the file with sql request's data"
  32. binary_file = fields.Binary('File', readonly=True)
  33. file_name = fields.Char('File Name', readonly=True)
  34. valid = fields.Boolean()
  35. sql_export_id = fields.Many2one(comodel_name='sql.export', required=True)
  36. @api.model
  37. def fields_view_get(self, view_id=None, view_type='form',
  38. toolbar=False, submenu=False):
  39. """
  40. Display dinamicaly parameter fields depending on the sql_export.
  41. """
  42. res = super(SqlFileWizard, self).fields_view_get(
  43. view_id=view_id, view_type=view_type, toolbar=toolbar,
  44. submenu=submenu)
  45. export_obj = self.env['sql.export']
  46. if view_type == 'form':
  47. sql_export = export_obj.browse(self._context.get('active_id'))
  48. if sql_export.field_ids:
  49. eview = etree.fromstring(res['arch'])
  50. group = etree.Element(
  51. 'group', name="variables_group", colspan="4")
  52. toupdate_fields = []
  53. for field in sql_export.field_ids:
  54. kwargs = {'name': "%s" % field.name}
  55. toupdate_fields.append(field.name)
  56. view_field = etree.SubElement(group, 'field', **kwargs)
  57. setup_modifiers(view_field, self.fields_get(field.name))
  58. res['fields'].update(self.fields_get(toupdate_fields))
  59. placeholder = eview.xpath(
  60. "//separator[@string='variables_placeholder']")[0]
  61. placeholder.getparent().replace(
  62. placeholder, group)
  63. res['arch'] = etree.tostring(eview, pretty_print=True)
  64. return res
  65. @api.multi
  66. def export_sql(self):
  67. self.ensure_one()
  68. sql_export = self.sql_export_id
  69. today = datetime.datetime.now()
  70. today_tz = fields.Datetime.context_timestamp(
  71. sql_export, today)
  72. date = today_tz.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
  73. output = StringIO.StringIO()
  74. variable_dict = {}
  75. if sql_export.field_ids:
  76. for field in sql_export.field_ids:
  77. variable_dict[field.name] = self[field.name]
  78. if "%(company_id)s" in sql_export.query:
  79. variable_dict['company_id'] = self.env.user.company_id.id
  80. if "%(user_id)s" in sql_export.query:
  81. variable_dict['user_id'] = self._uid
  82. format_query = self.env.cr.mogrify(
  83. sql_export.query, variable_dict).decode('utf-8')
  84. query = "COPY (" + format_query + ") TO STDOUT WITH " + \
  85. sql_export.copy_options
  86. name = 'export_query_%s' % uuid.uuid1().hex
  87. self.env.cr.execute("SAVEPOINT %s" % name)
  88. try:
  89. self.env.cr.copy_expert(query, output)
  90. output.getvalue()
  91. new_output = base64.b64encode(output.getvalue())
  92. output.close()
  93. finally:
  94. self.env.cr.execute("ROLLBACK TO SAVEPOINT %s" % name)
  95. self.write({
  96. 'binary_file': new_output,
  97. 'file_name': sql_export.name + '_' + date + '.csv'
  98. })
  99. if not sql_export.valid:
  100. sql_export.sudo().valid = True
  101. return {
  102. 'view_type': 'form',
  103. 'view_mode': 'form',
  104. 'res_model': 'sql.file.wizard',
  105. 'res_id': self.id,
  106. 'type': 'ir.actions.act_window',
  107. 'target': 'new',
  108. 'context': self._context,
  109. 'nodestroy': True,
  110. }