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.

264 lines
8.9 KiB

  1. # Copyright (C) 2015 Akretion (<http://www.akretion.com>)
  2. # Copyright (C) 2017 - Today: GRAP (http://www.grap.coop)
  3. # @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
  4. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  5. import re
  6. import uuid
  7. from io import StringIO
  8. import base64
  9. from psycopg2 import ProgrammingError
  10. from odoo import _, api, fields, models
  11. from odoo.exceptions import UserError
  12. class SQLRequestMixin(models.AbstractModel):
  13. _name = 'sql.request.mixin'
  14. _description = '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. # pylint: disable=sql-injection
  122. if params:
  123. query = self.query % params
  124. else:
  125. query = self.query
  126. query = query
  127. if mode in ('fetchone', 'fetchall'):
  128. pass
  129. elif mode == 'stdout':
  130. query = "COPY (%s) TO STDOUT WITH %s" % (query, copy_options)
  131. elif mode in 'view':
  132. query = "CREATE VIEW %s AS (%s);" % (query, view_name)
  133. elif mode in 'materialized_view':
  134. self._check_materialized_view_available()
  135. query = "CREATE MATERIALIZED VIEW %s AS (%s);" % (query, view_name)
  136. else:
  137. raise UserError(_("Unimplemented mode : '%s'" % mode))
  138. if rollback:
  139. rollback_name = self._create_savepoint()
  140. try:
  141. if mode == 'stdout':
  142. output = StringIO.StringIO()
  143. self.env.cr.copy_expert(query, output)
  144. output.getvalue()
  145. res = base64.b64encode(output.getvalue())
  146. output.close()
  147. else:
  148. self.env.cr.execute(query)
  149. if mode == 'fetchall':
  150. res = self.env.cr.fetchall()
  151. elif mode == 'fetchone':
  152. res = self.env.cr.fetchone()
  153. finally:
  154. self._rollback_savepoint(rollback_name)
  155. return res
  156. # Private Section
  157. @api.model
  158. def _create_savepoint(self):
  159. rollback_name = '%s_%s' % (
  160. self._name.replace('.', '_'), uuid.uuid1().hex)
  161. # pylint: disable=sql-injection
  162. req = "SAVEPOINT %s" % (rollback_name)
  163. self.env.cr.execute(req)
  164. return rollback_name
  165. @api.model
  166. def _rollback_savepoint(self, rollback_name):
  167. # pylint: disable=sql-injection
  168. req = "ROLLBACK TO SAVEPOINT %s" % (rollback_name)
  169. self.env.cr.execute(req)
  170. @api.model
  171. def _check_materialized_view_available(self):
  172. self.env.cr.execute("SHOW server_version;")
  173. res = self.env.cr.fetchone()[0].split('.')
  174. minor_version = float('.'.join(res[:2]))
  175. if minor_version < 9.3:
  176. raise UserError(_(
  177. "Materialized View requires PostgreSQL 9.3 or greater but"
  178. " PostgreSQL %s is currently installed.") % (minor_version))
  179. @api.multi
  180. def _clean_query(self):
  181. self.ensure_one()
  182. query = self.query.strip()
  183. while query[-1] == ';':
  184. query = query[:-1]
  185. self.query = query
  186. @api.multi
  187. def _check_prohibited_words(self):
  188. """Check if the query contains prohibited words, to avoid maliscious
  189. SQL requests"""
  190. self.ensure_one()
  191. query = self.query.lower()
  192. for word in self.PROHIBITED_WORDS:
  193. expr = r'\b%s\b' % word
  194. is_not_safe = re.search(expr, query)
  195. if is_not_safe:
  196. raise UserError(_(
  197. "The query is not allowed because it contains unsafe word"
  198. " '%s'") % (word))
  199. @api.multi
  200. def _check_execution(self):
  201. """Ensure that the query is valid, trying to execute it. A rollback
  202. is done after."""
  203. self.ensure_one()
  204. query = self._prepare_request_check_execution()
  205. rollback_name = self._create_savepoint()
  206. res = False
  207. try:
  208. self.env.cr.execute(query)
  209. res = self._hook_executed_request()
  210. except ProgrammingError as e:
  211. raise UserError(
  212. _("The SQL query is not valid:\n\n %s") % e)
  213. finally:
  214. self._rollback_savepoint(rollback_name)
  215. return res
  216. @api.multi
  217. def _prepare_request_check_execution(self):
  218. """Overload me to replace some part of the query, if it contains
  219. parameters"""
  220. self.ensure_one()
  221. return self.query
  222. def _hook_executed_request(self):
  223. """Overload me to insert custom code, when the SQL request has
  224. been executed, before the rollback.
  225. """
  226. self.ensure_one()
  227. return False