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.

258 lines
8.7 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright (C) 2015 Akretion (<http://www.akretion.com>)
  3. # Copyright (C) 2017 - Today: GRAP (http://www.grap.coop)
  4. # @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
  5. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  6. import re
  7. import uuid
  8. import StringIO
  9. import base64
  10. from psycopg2 import ProgrammingError
  11. from odoo import _, api, fields, models
  12. from odoo.exceptions import UserError
  13. class SQLRequestMixin(models.AbstractModel):
  14. _name = 'sql.request.mixin'
  15. _clean_query_enabled = True
  16. _check_prohibited_words_enabled = True
  17. _check_execution_enabled = True
  18. _sql_request_groups_relation = False
  19. _sql_request_users_relation = False
  20. STATE_SELECTION = [
  21. ('draft', 'Draft'),
  22. ('sql_valid', 'SQL Valid'),
  23. ]
  24. PROHIBITED_WORDS = [
  25. 'delete',
  26. 'drop',
  27. 'insert',
  28. 'alter',
  29. 'truncate',
  30. 'execute',
  31. 'create',
  32. 'update',
  33. 'ir_config_parameter',
  34. ]
  35. # Default Section
  36. @api.model
  37. def _default_group_ids(self):
  38. ir_model_obj = self.env['ir.model.data']
  39. return [ir_model_obj.xmlid_to_res_id(
  40. 'sql_request_abstract.group_sql_request_user')]
  41. @api.model
  42. def _default_user_ids(self):
  43. return []
  44. # Columns Section
  45. name = fields.Char('Name', required=True)
  46. query = fields.Text(
  47. string='Query', required=True, help="You can't use the following words"
  48. ": DELETE, DROP, CREATE, INSERT, ALTER, TRUNCATE, EXECUTE, UPDATE.")
  49. state = fields.Selection(
  50. string='State', selection=STATE_SELECTION, default='draft',
  51. help="State of the Request:\n"
  52. " * 'Draft': Not tested\n"
  53. " * 'SQL Valid': SQL Request has been checked and is valid")
  54. group_ids = fields.Many2many(
  55. comodel_name='res.groups', string='Allowed Groups',
  56. relation=_sql_request_groups_relation,
  57. column1='sql_id', column2='group_id',
  58. default=_default_group_ids)
  59. user_ids = fields.Many2many(
  60. comodel_name='res.users', string='Allowed Users',
  61. relation=_sql_request_users_relation,
  62. column1='sql_id', column2='user_id',
  63. default=_default_user_ids)
  64. # Action Section
  65. @api.multi
  66. def button_validate_sql_expression(self):
  67. for item in self:
  68. if item._clean_query_enabled:
  69. item._clean_query()
  70. if item._check_prohibited_words_enabled:
  71. item._check_prohibited_words()
  72. if item._check_execution_enabled:
  73. item._check_execution()
  74. item.state = 'sql_valid'
  75. @api.multi
  76. def button_set_draft(self):
  77. self.write({'state': 'draft'})
  78. # API Section
  79. @api.multi
  80. def _execute_sql_request(
  81. self, params=None, mode='fetchall', rollback=True,
  82. view_name=False, copy_options="CSV HEADER DELIMITER ';'"):
  83. """Execute a SQL request on the current database.
  84. ??? This function checks before if the user has the
  85. right to execute the request.
  86. :param params: (dict) of keys / values that will be replaced in
  87. the sql query, before executing it.
  88. :param mode: (str) result type expected. Available settings :
  89. * 'view': create a view with the select query. Extra param
  90. required 'view_name'.
  91. * 'materialized_view': create a MATERIALIZED VIEW with the
  92. select query. Extra parameter required 'view_name'.
  93. * 'fetchall': execute the select request, and return the
  94. result of 'cr.fetchall()'.
  95. * 'fetchone' : execute the select request, and return the
  96. result of 'cr.fetchone()'
  97. :param rollback: (boolean) mention if a rollback should be played after
  98. the execution of the query. Please keep this feature enabled
  99. for security reason, except if necessary.
  100. (Ignored if @mode in ('view', 'materialized_view'))
  101. :param view_name: (str) name of the view.
  102. (Ignored if @mode not in ('view', 'materialized_view'))
  103. :param copy_options: (str) mentions extra options for
  104. "COPY request STDOUT WITH xxx" request.
  105. (Ignored if @mode != 'stdout')
  106. ..note:: The following exceptions could be raised:
  107. psycopg2.ProgrammingError: Error in the SQL Request.
  108. odoo.exceptions.UserError:
  109. * 'mode' is not implemented.
  110. * materialized view is not supported by the Postgresql Server.
  111. """
  112. self.ensure_one()
  113. res = False
  114. # Check if the request is in a valid state
  115. if self.state == 'draft':
  116. raise UserError(_(
  117. "It is not allowed to execute a not checked request."))
  118. # Disable rollback if a creation of a view is asked
  119. if mode in ('view', 'materialized_view'):
  120. rollback = False
  121. params = params and params or {}
  122. query = self.env.cr.mogrify(self.query, params).decode('utf-8')
  123. if mode in ('fetchone', 'fetchall'):
  124. pass
  125. elif mode == 'stdout':
  126. query = "COPY (%s) TO STDOUT WITH %s" % (query, copy_options)
  127. elif mode in 'view':
  128. query = "CREATE VIEW %s AS (%s);" % (query, view_name)
  129. elif mode in 'materialized_view':
  130. self._check_materialized_view_available()
  131. query = "CREATE MATERIALIZED VIEW %s AS (%s);" % (query, view_name)
  132. else:
  133. raise UserError(_("Unimplemented mode : '%s'" % mode))
  134. if rollback:
  135. rollback_name = self._create_savepoint()
  136. try:
  137. if mode == 'stdout':
  138. output = StringIO.StringIO()
  139. self.env.cr.copy_expert(query, output)
  140. output.getvalue()
  141. res = base64.b64encode(output.getvalue())
  142. output.close()
  143. else:
  144. self.env.cr.execute(query)
  145. if mode == 'fetchall':
  146. res = self.env.cr.fetchall()
  147. elif mode == 'fetchone':
  148. res = self.env.cr.fetchone()
  149. finally:
  150. self._rollback_savepoint(rollback_name)
  151. return res
  152. # Private Section
  153. @api.model
  154. def _create_savepoint(self):
  155. rollback_name = '%s_%s' % (
  156. self._name.replace('.', '_'), uuid.uuid1().hex)
  157. req = "SAVEPOINT %s" % (rollback_name)
  158. self.env.cr.execute(req)
  159. return rollback_name
  160. @api.model
  161. def _rollback_savepoint(self, rollback_name):
  162. req = "ROLLBACK TO SAVEPOINT %s" % (rollback_name)
  163. self.env.cr.execute(req)
  164. @api.model
  165. def _check_materialized_view_available(self):
  166. self.env.cr.execute("SHOW server_version;")
  167. res = self.env.cr.fetchone()[0].split('.')
  168. minor_version = float('.'.join(res[:2]))
  169. if minor_version < 9.3:
  170. raise UserError(_(
  171. "Materialized View requires PostgreSQL 9.3 or greater but"
  172. " PostgreSQL %s is currently installed.") % (minor_version))
  173. @api.multi
  174. def _clean_query(self):
  175. self.ensure_one()
  176. query = self.query.strip()
  177. while query[-1] == ';':
  178. query = query[:-1]
  179. self.query = query
  180. @api.multi
  181. def _check_prohibited_words(self):
  182. """Check if the query contains prohibited words, to avoid maliscious
  183. SQL requests"""
  184. self.ensure_one()
  185. query = self.query.lower()
  186. for word in self.PROHIBITED_WORDS:
  187. expr = r'\b%s\b' % word
  188. is_not_safe = re.search(expr, query)
  189. if is_not_safe:
  190. raise UserError(_(
  191. "The query is not allowed because it contains unsafe word"
  192. " '%s'") % (word))
  193. @api.multi
  194. def _check_execution(self):
  195. """Ensure that the query is valid, trying to execute it. A rollback
  196. is done after."""
  197. self.ensure_one()
  198. query = self._prepare_request_check_execution()
  199. rollback_name = self._create_savepoint()
  200. res = False
  201. try:
  202. self.env.cr.execute(query)
  203. res = self._hook_executed_request()
  204. except ProgrammingError as e:
  205. raise UserError(
  206. _("The SQL query is not valid:\n\n %s") % e.message)
  207. finally:
  208. self._rollback_savepoint(rollback_name)
  209. return res
  210. @api.multi
  211. def _prepare_request_check_execution(self):
  212. """Overload me to replace some part of the query, if it contains
  213. parameters"""
  214. self.ensure_one()
  215. return self.query
  216. def _hook_executed_request(self):
  217. """Overload me to insert custom code, when the SQL request has
  218. been executed, before the rollback.
  219. """
  220. self.ensure_one()
  221. return False