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.

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