OCA reporting engine fork for dev and update.
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.

495 lines
17 KiB

  1. # -*- coding: utf-8 -*-
  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 logging
  6. from psycopg2 import ProgrammingError
  7. from openerp import _, api, fields, models, SUPERUSER_ID
  8. from openerp.exceptions import Warning as UserError
  9. _logger = logging.getLogger(__name__)
  10. class BiSQLView(models.Model):
  11. _name = 'bi.sql.view'
  12. _inherit = ['sql.request.mixin']
  13. _sql_prefix = 'x_bi_sql_view_'
  14. _model_prefix = 'x_bi_sql_view.'
  15. _sql_request_groups_relation = 'bi_sql_view_groups_rel'
  16. _sql_request_users_relation = 'bi_sql_view_users_rel'
  17. _STATE_SQL_EDITOR = [
  18. ('model_valid', 'SQL View and Model Created'),
  19. ('ui_valid', 'Graph, action and Menu Created'),
  20. ]
  21. technical_name = fields.Char(
  22. string='Technical Name', required=True,
  23. help="Suffix of the SQL view. (SQL full name will be computed and"
  24. " prefixed by 'x_bi_sql_view_'. Should have correct"
  25. "syntax. For more information, see https://www.postgresql.org/"
  26. "docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS")
  27. view_name = fields.Char(
  28. string='View Name', compute='_compute_view_name', readonly=True,
  29. store=True, help="Full name of the SQL view")
  30. model_name = fields.Char(
  31. string='Model Name', compute='_compute_model_name', readonly=True,
  32. store=True, help="Full Qualified Name of the transient model that will"
  33. " be created.")
  34. is_materialized = fields.Boolean(
  35. string='Is Materialized View', default=True, readonly=True,
  36. states={'draft': [('readonly', False)]})
  37. materialized_text = fields.Char(
  38. compute='_compute_materialized_text', store=True)
  39. size = fields.Char(
  40. string='Database Size', readonly=True,
  41. help="Size of the materialized view and its indexes")
  42. state = fields.Selection(selection_add=_STATE_SQL_EDITOR)
  43. query = fields.Text(
  44. help="SQL Request that will be inserted as the view. Take care to :\n"
  45. " * set a name for all your selected fields, specially if you use"
  46. " SQL function (like EXTRACT, ...);\n"
  47. " * Do not use 'SELECT *' or 'SELECT table.*';\n"
  48. " * prefix the name of the selectable columns by 'x_';",
  49. default="SELECT\n"
  50. " my_field as x_my_field\n"
  51. "FROM my_table")
  52. domain_force = fields.Text(
  53. string='Extra Rule Definition', default="[]", help="Define here"
  54. " access restriction to data.\n"
  55. " Take care to use field name prefixed by 'x_'."
  56. " A global 'ir.rule' will be created."
  57. " A typical Multi Company rule is for exemple \n"
  58. " ['|', ('x_company_id','child_of', [user.company_id.id]),"
  59. "('x_company_id','=',False)].")
  60. has_group_changed = fields.Boolean(copy=False)
  61. bi_sql_view_field_ids = fields.One2many(
  62. string='SQL Fields', comodel_name='bi.sql.view.field',
  63. inverse_name='bi_sql_view_id')
  64. model_id = fields.Many2one(
  65. string='Odoo Model', comodel_name='ir.model', readonly=True)
  66. graph_view_id = fields.Many2one(
  67. string='Odoo Graph View', comodel_name='ir.ui.view', readonly=True)
  68. search_view_id = fields.Many2one(
  69. string='Odoo Search View', comodel_name='ir.ui.view', readonly=True)
  70. action_id = fields.Many2one(
  71. string='Odoo Action', comodel_name='ir.actions.act_window',
  72. readonly=True)
  73. menu_id = fields.Many2one(
  74. string='Odoo Menu', comodel_name='ir.ui.menu', readonly=True)
  75. cron_id = fields.Many2one(
  76. string='Odoo Cron', comodel_name='ir.cron', readonly=True,
  77. help="Cron Task that will refresh the materialized view")
  78. rule_id = fields.Many2one(
  79. string='Odoo Rule', comodel_name='ir.rule', readonly=True)
  80. # Compute Section
  81. @api.depends('is_materialized')
  82. @api.multi
  83. def _compute_materialized_text(self):
  84. for sql_view in self:
  85. sql_view.materialized_text =\
  86. sql_view.is_materialized and 'MATERIALIZED' or ''
  87. @api.depends('technical_name')
  88. @api.multi
  89. def _compute_view_name(self):
  90. for sql_view in self:
  91. sql_view.view_name = '%s%s' % (
  92. sql_view._sql_prefix, sql_view.technical_name)
  93. @api.depends('technical_name')
  94. @api.multi
  95. def _compute_model_name(self):
  96. for sql_view in self:
  97. sql_view.model_name = '%s%s' % (
  98. sql_view._model_prefix, sql_view.technical_name)
  99. @api.onchange('group_ids')
  100. def onchange_group_ids(self):
  101. if self.state not in ('draft', 'sql_valid'):
  102. self.has_group_changed = True
  103. # Overload Section
  104. @api.multi
  105. def unlink(self):
  106. non_draft_views = self.search([
  107. ('id', 'in', self.ids),
  108. ('state', 'not in', ('draft', 'sql_valid'))])
  109. if non_draft_views:
  110. raise UserError(_("You can only unlink draft views"))
  111. return self.unlink()
  112. @api.multi
  113. def copy(self, default=None):
  114. self.ensure_one()
  115. default = dict(default or {})
  116. default.update({
  117. 'name': _('%s (Copy)') % (self.name),
  118. 'technical_name': '%s_copy' % (self.technical_name),
  119. })
  120. return super(BiSQLView, self).copy(default=default)
  121. # Action Section
  122. @api.multi
  123. def button_create_sql_view_and_model(self):
  124. for sql_view in self:
  125. if sql_view.state != 'sql_valid':
  126. raise UserError(_(
  127. "You can only process this action on SQL Valid items"))
  128. # Create ORM and acess
  129. sql_view._create_model_and_fields()
  130. sql_view._create_model_access()
  131. # Create SQL View and indexes
  132. sql_view._create_view()
  133. sql_view._create_index()
  134. if sql_view.is_materialized:
  135. sql_view.cron_id = self.env['ir.cron'].create(
  136. sql_view._prepare_cron()).id
  137. sql_view.state = 'model_valid'
  138. @api.multi
  139. def button_set_draft(self):
  140. for sql_view in self:
  141. if sql_view.state in ('model_valid', 'ui_valid'):
  142. # Drop SQL View (and indexes by cascade)
  143. sql_view._drop_view()
  144. # Drop ORM
  145. sql_view._drop_model_and_fields()
  146. sql_view.graph_view_id.unlink()
  147. sql_view.action_id.unlink()
  148. sql_view.menu_id.unlink()
  149. sql_view.rule_id.unlink()
  150. if sql_view.cron_id:
  151. sql_view.cron_id.unlink()
  152. sql_view.write({'state': 'draft', 'has_group_changed': False})
  153. @api.multi
  154. def button_create_ui(self):
  155. self.graph_view_id = self.env['ir.ui.view'].create(
  156. self._prepare_graph_view()).id
  157. self.search_view_id = self.env['ir.ui.view'].create(
  158. self._prepare_search_view()).id
  159. self.action_id = self.env['ir.actions.act_window'].create(
  160. self._prepare_action()).id
  161. self.menu_id = self.env['ir.ui.menu'].create(
  162. self._prepare_menu()).id
  163. self.write({'state': 'ui_valid'})
  164. @api.multi
  165. def button_update_model_access(self):
  166. self._drop_model_access()
  167. self._create_model_access()
  168. self.write({'has_group_changed': False})
  169. @api.multi
  170. def button_refresh_materialized_view(self):
  171. self._refresh_materialized_view()
  172. @api.multi
  173. def button_open_view(self):
  174. return {
  175. 'type': 'ir.actions.act_window',
  176. 'res_model': self.model_id.model,
  177. 'view_id': self.graph_view_id.id,
  178. 'search_view_id': self.search_view_id.id,
  179. 'view_type': 'graph',
  180. 'view_mode': 'graph',
  181. }
  182. # Prepare Function
  183. @api.multi
  184. def _prepare_model(self):
  185. self.ensure_one()
  186. field_id = []
  187. for field in self.bi_sql_view_field_ids.filtered(
  188. lambda x: x.field_description is not False):
  189. field_id.append([0, False, field._prepare_model_field()])
  190. return {
  191. 'name': self.name,
  192. 'model': self.model_name,
  193. 'access_ids': [],
  194. 'field_id': field_id,
  195. }
  196. @api.multi
  197. def _prepare_model_access(self):
  198. self.ensure_one()
  199. res = []
  200. for group in self.group_ids:
  201. res.append({
  202. 'name': _('%s Access %s') % (
  203. self.model_name, group.full_name),
  204. 'model_id': self.model_id.id,
  205. 'group_id': group.id,
  206. 'perm_read': True,
  207. 'perm_create': False,
  208. 'perm_write': False,
  209. 'perm_unlink': False,
  210. })
  211. return res
  212. @api.multi
  213. def _prepare_cron(self):
  214. self.ensure_one()
  215. return {
  216. 'name': _('Refresh Materialized View %s') % (self.view_name),
  217. 'user_id': SUPERUSER_ID,
  218. 'model': 'bi.sql.view',
  219. 'function': 'button_refresh_materialized_view',
  220. 'args': repr(([self.id],))
  221. }
  222. @api.multi
  223. def _prepare_rule(self):
  224. self.ensure_one()
  225. return {
  226. 'name': _('Access %s') % (self.name),
  227. 'model_id': self.model_id.id,
  228. 'domain_force': self.domain_force,
  229. 'global': True,
  230. }
  231. @api.multi
  232. def _prepare_graph_view(self):
  233. self.ensure_one()
  234. return {
  235. 'name': self.name,
  236. 'type': 'graph',
  237. 'model': self.model_id.model,
  238. 'arch':
  239. """<?xml version="1.0"?>"""
  240. """<graph string="Analysis" type="pivot" stacked="True">{}"""
  241. """</graph>""".format("".join(
  242. [x._prepare_graph_field()
  243. for x in self.bi_sql_view_field_ids]))
  244. }
  245. @api.multi
  246. def _prepare_search_view(self):
  247. self.ensure_one()
  248. return {
  249. 'name': self.name,
  250. 'type': 'search',
  251. 'model': self.model_id.model,
  252. 'arch':
  253. """<?xml version="1.0"?>"""
  254. """<search string="Analysis">{}"""
  255. """<group expand="1" string="Group By">{}</group>"""
  256. """</search>""".format(
  257. "".join(
  258. [x._prepare_search_field()
  259. for x in self.bi_sql_view_field_ids]),
  260. "".join(
  261. [x._prepare_search_filter_field()
  262. for x in self.bi_sql_view_field_ids]))
  263. }
  264. @api.multi
  265. def _prepare_action(self):
  266. self.ensure_one()
  267. return {
  268. 'name': self.name,
  269. 'res_model': self.model_id.model,
  270. 'type': 'ir.actions.act_window',
  271. 'view_type': 'form',
  272. 'view_mode': 'graph',
  273. 'view_id': self.graph_view_id.id,
  274. 'search_view_id': self.search_view_id.id,
  275. }
  276. @api.multi
  277. def _prepare_menu(self):
  278. self.ensure_one()
  279. return {
  280. 'name': self.name,
  281. 'parent_id': self.env.ref('bi_sql_editor.menu_bi_sql_editor').id,
  282. 'action': 'ir.actions.act_window,%s' % (self.action_id.id),
  283. }
  284. # Custom Section
  285. def _log_execute(self, req):
  286. _logger.info("Executing SQL Request %s ..." % (req))
  287. self.env.cr.execute(req)
  288. @api.multi
  289. def _drop_view(self):
  290. for sql_view in self:
  291. self._log_execute(
  292. "DROP %s VIEW IF EXISTS %s" % (
  293. sql_view.materialized_text, sql_view.view_name))
  294. sql_view.size = False
  295. @api.multi
  296. def _create_view(self):
  297. for sql_view in self:
  298. sql_view._drop_view()
  299. try:
  300. self._log_execute(sql_view._prepare_request_for_execution())
  301. sql_view._refresh_size()
  302. except ProgrammingError as e:
  303. raise UserError(_(
  304. "SQL Error while creating %s VIEW %s :\n %s") % (
  305. sql_view.materialized_text, sql_view.view_name,
  306. e.message))
  307. @api.multi
  308. def _create_index(self):
  309. for sql_view in self:
  310. for sql_field in sql_view.bi_sql_view_field_ids.filtered(
  311. lambda x: x.is_index is True):
  312. self._log_execute(
  313. "CREATE INDEX %s ON %s (%s);" % (
  314. sql_field.index_name, sql_view.view_name,
  315. sql_field.name))
  316. @api.multi
  317. def _create_model_and_fields(self):
  318. for sql_view in self:
  319. # Create model
  320. sql_view.model_id = self.env['ir.model'].create(
  321. self._prepare_model()).id
  322. sql_view.rule_id = self.env['ir.rule'].create(
  323. self._prepare_rule()).id
  324. # Drop table, created by the ORM
  325. req = "DROP TABLE %s" % (sql_view.view_name)
  326. self.env.cr.execute(req)
  327. @api.multi
  328. def _create_model_access(self):
  329. for sql_view in self:
  330. for item in sql_view._prepare_model_access():
  331. self.env['ir.model.access'].create(item)
  332. @api.multi
  333. def _drop_model_access(self):
  334. for sql_view in self:
  335. self.env['ir.model.access'].search(
  336. [('model_id', '=', sql_view.model_name)]).unlink()
  337. @api.multi
  338. def _drop_model_and_fields(self):
  339. for sql_view in self:
  340. sql_view.model_id.unlink()
  341. @api.multi
  342. def _hook_executed_request(self):
  343. self.ensure_one()
  344. req = """
  345. SELECT attnum,
  346. attname AS column,
  347. format_type(atttypid, atttypmod) AS type
  348. FROM pg_attribute
  349. WHERE attrelid = '%s'::regclass
  350. AND NOT attisdropped
  351. AND attnum > 0
  352. ORDER BY attnum;""" % (self.view_name)
  353. self.env.cr.execute(req)
  354. return self.env.cr.fetchall()
  355. @api.multi
  356. def _prepare_request_check_execution(self):
  357. self.ensure_one()
  358. return "CREATE VIEW %s AS (%s);" % (self.view_name, self.query)
  359. @api.multi
  360. def _prepare_request_for_execution(self):
  361. self.ensure_one()
  362. query = """
  363. SELECT
  364. CAST(row_number() OVER () as integer) AS id,
  365. CAST(Null as timestamp without time zone) as create_date,
  366. CAST(Null as integer) as create_uid,
  367. CAST(Null as timestamp without time zone) as write_date,
  368. CAST(Null as integer) as write_uid,
  369. my_query.*
  370. FROM
  371. (%s) as my_query
  372. """ % (self.query)
  373. return "CREATE %s VIEW %s AS (%s);" % (
  374. self.materialized_text, self.view_name, query)
  375. @api.multi
  376. def _check_execution(self):
  377. """Ensure that the query is valid, trying to execute it.
  378. a non materialized view is created for this check.
  379. A rollback is done at the end.
  380. After the execution, and before the rollback, an analysis of
  381. the database structure is done, to know fields type."""
  382. self.ensure_one()
  383. sql_view_field_obj = self.env['bi.sql.view.field']
  384. columns = super(BiSQLView, self)._check_execution()
  385. field_ids = []
  386. for column in columns:
  387. existing_field = self.bi_sql_view_field_ids.filtered(
  388. lambda x: x.name == column[1])
  389. if existing_field:
  390. # Update existing field
  391. field_ids.append(existing_field.id)
  392. existing_field.write({
  393. 'sequence': column[0],
  394. 'sql_type': column[2],
  395. })
  396. else:
  397. # Create a new one if name is prefixed by x_
  398. if column[1][:2] == 'x_':
  399. field_ids.append(sql_view_field_obj.create({
  400. 'sequence': column[0],
  401. 'name': column[1],
  402. 'sql_type': column[2],
  403. 'bi_sql_view_id': self.id,
  404. }).id)
  405. # Drop obsolete view field
  406. self.bi_sql_view_field_ids.filtered(
  407. lambda x: x.id not in field_ids).unlink()
  408. if not self.bi_sql_view_field_ids:
  409. raise UserError(_(
  410. "No Column was found.\n"
  411. "Columns name should be prefixed by 'x_'."))
  412. return columns
  413. @api.multi
  414. def _refresh_materialized_view(self):
  415. for sql_view in self:
  416. req = "REFRESH %s VIEW %s" % (
  417. sql_view.materialized_text, sql_view.view_name)
  418. self._log_execute(req)
  419. sql_view._refresh_size()
  420. @api.multi
  421. def _refresh_size(self):
  422. for sql_view in self:
  423. req = "SELECT pg_size_pretty(pg_total_relation_size('%s'));" % (
  424. sql_view.view_name)
  425. self.env.cr.execute(req)
  426. sql_view.size = self.env.cr.fetchone()[0]