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.

666 lines
23 KiB

7 years ago
7 years ago
7 years ago
  1. # Copyright (C) 2017 - Today: GRAP (http://www.grap.coop)
  2. # @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  4. import logging
  5. from datetime import datetime
  6. from psycopg2 import ProgrammingError
  7. from odoo import _, api, fields, models, SUPERUSER_ID
  8. from odoo.exceptions import UserError
  9. from odoo.tools import pycompat, sql
  10. from odoo.addons.base.models.ir_model import IrModel
  11. _logger = logging.getLogger(__name__)
  12. @api.model
  13. def _instanciate(self, model_data):
  14. """ Return a class for the custom model given by
  15. parameters ``model_data``. """
  16. # This monkey patch is meant to avoid create/search tables for those
  17. # materialized views. Doing "super" doesn't work.
  18. class CustomModel(models.Model):
  19. _name = pycompat.to_native(model_data['model'])
  20. _description = model_data['name']
  21. _module = False
  22. _custom = True
  23. _transient = bool(model_data['transient'])
  24. __doc__ = model_data['info']
  25. # START OF patch
  26. if model_data['model'].startswith(BiSQLView._model_prefix):
  27. CustomModel._auto = False
  28. CustomModel._abstract = True
  29. # END of patch
  30. return CustomModel
  31. IrModel._instanciate = _instanciate
  32. class BiSQLView(models.Model):
  33. _name = 'bi.sql.view'
  34. _order = 'sequence'
  35. _inherit = ['sql.request.mixin']
  36. _sql_prefix = 'x_bi_sql_view_'
  37. _model_prefix = 'x_bi_sql_view.'
  38. _sql_request_groups_relation = 'bi_sql_view_groups_rel'
  39. _sql_request_users_relation = 'bi_sql_view_users_rel'
  40. _STATE_SQL_EDITOR = [
  41. ('model_valid', 'SQL View and Model Created'),
  42. ('ui_valid', 'Views, Action and Menu Created'),
  43. ]
  44. technical_name = fields.Char(
  45. string='Technical Name', required=True,
  46. help="Suffix of the SQL view. SQL full name will be computed and"
  47. " prefixed by 'x_bi_sql_view_'. Syntax should follow: "
  48. "https://www.postgresql.org/"
  49. "docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS")
  50. view_name = fields.Char(
  51. string='View Name', compute='_compute_view_name', readonly=True,
  52. store=True, help="Full name of the SQL view")
  53. model_name = fields.Char(
  54. string='Model Name', compute='_compute_model_name', readonly=True,
  55. store=True, help="Full Qualified Name of the transient model that will"
  56. " be created.")
  57. is_materialized = fields.Boolean(
  58. string='Is Materialized View', default=True, readonly=True,
  59. states={
  60. 'draft': [('readonly', False)],
  61. 'sql_valid': [('readonly', False)],
  62. })
  63. materialized_text = fields.Char(
  64. compute='_compute_materialized_text', store=True)
  65. size = fields.Char(
  66. string='Database Size', readonly=True,
  67. help="Size of the materialized view and its indexes")
  68. state = fields.Selection(selection_add=_STATE_SQL_EDITOR)
  69. view_order = fields.Char(string='View Order',
  70. required=True,
  71. readonly=False,
  72. states={'ui_valid': [('readonly', True)]},
  73. default="pivot,graph,tree",
  74. help='Comma-separated text. Possible values:'
  75. ' "graph", "pivot" or "tree"')
  76. query = fields.Text(
  77. help="SQL Request that will be inserted as the view. Take care to :\n"
  78. " * set a name for all your selected fields, specially if you use"
  79. " SQL function (like EXTRACT, ...);\n"
  80. " * Do not use 'SELECT *' or 'SELECT table.*';\n"
  81. " * prefix the name of the selectable columns by 'x_';",
  82. default="SELECT\n"
  83. " my_field as x_my_field\n"
  84. "FROM my_table")
  85. domain_force = fields.Text(
  86. string='Extra Rule Definition', default="[]", readonly=True,
  87. help="Define here access restriction to data.\n"
  88. " Take care to use field name prefixed by 'x_'."
  89. " A global 'ir.rule' will be created."
  90. " A typical Multi Company rule is for exemple \n"
  91. " ['|', ('x_company_id','child_of', [user.company_id.id]),"
  92. "('x_company_id','=',False)].",
  93. states={
  94. 'draft': [('readonly', False)],
  95. 'sql_valid': [('readonly', False)],
  96. })
  97. action_context = fields.Text(
  98. string="Action Context", default="{}", readonly=True,
  99. help="Define here a context that will be used"
  100. " by default, when creating the action.",
  101. states={
  102. 'draft': [('readonly', False)],
  103. 'sql_valid': [('readonly', False)],
  104. })
  105. has_group_changed = fields.Boolean(copy=False)
  106. bi_sql_view_field_ids = fields.One2many(
  107. string='SQL Fields', comodel_name='bi.sql.view.field',
  108. inverse_name='bi_sql_view_id')
  109. model_id = fields.Many2one(
  110. string='Odoo Model', comodel_name='ir.model', readonly=True)
  111. tree_view_id = fields.Many2one(
  112. string='Odoo Tree View', comodel_name='ir.ui.view', readonly=True)
  113. graph_view_id = fields.Many2one(
  114. string='Odoo Graph View', comodel_name='ir.ui.view', readonly=True)
  115. pivot_view_id = fields.Many2one(
  116. string='Odoo Pivot View', comodel_name='ir.ui.view', readonly=True)
  117. search_view_id = fields.Many2one(
  118. string='Odoo Search View', comodel_name='ir.ui.view', readonly=True)
  119. action_id = fields.Many2one(
  120. string='Odoo Action', comodel_name='ir.actions.act_window',
  121. readonly=True)
  122. menu_id = fields.Many2one(
  123. string='Odoo Menu', comodel_name='ir.ui.menu', readonly=True)
  124. cron_id = fields.Many2one(
  125. string='Odoo Cron', comodel_name='ir.cron', readonly=True,
  126. help="Cron Task that will refresh the materialized view")
  127. rule_id = fields.Many2one(
  128. string='Odoo Rule', comodel_name='ir.rule', readonly=True)
  129. group_ids = fields.Many2many(
  130. comodel_name='res.groups', readonly=True, states={
  131. 'draft': [('readonly', False)],
  132. 'sql_valid': [('readonly', False)],
  133. })
  134. sequence = fields.Integer(string='sequence')
  135. # Constrains Section
  136. @api.constrains('is_materialized')
  137. @api.multi
  138. def _check_index_materialized(self):
  139. for rec in self.filtered(lambda x: not x.is_materialized):
  140. if rec.bi_sql_view_field_ids.filtered(lambda x: x.is_index):
  141. raise UserError(_(
  142. 'You can not create indexes on non materialized views'))
  143. @api.constrains('view_order')
  144. @api.multi
  145. def _check_view_order(self):
  146. for rec in self:
  147. if rec.view_order:
  148. for vtype in rec.view_order.split(','):
  149. if vtype not in ('graph', 'pivot', 'tree'):
  150. raise UserError(_(
  151. 'Only graph, pivot or tree views are supported'))
  152. # Compute Section
  153. @api.depends('is_materialized')
  154. @api.multi
  155. def _compute_materialized_text(self):
  156. for sql_view in self:
  157. sql_view.materialized_text =\
  158. sql_view.is_materialized and 'MATERIALIZED' or ''
  159. @api.depends('technical_name')
  160. @api.multi
  161. def _compute_view_name(self):
  162. for sql_view in self:
  163. sql_view.view_name = '%s%s' % (
  164. sql_view._sql_prefix, sql_view.technical_name)
  165. @api.depends('technical_name')
  166. @api.multi
  167. def _compute_model_name(self):
  168. for sql_view in self:
  169. sql_view.model_name = '%s%s' % (
  170. sql_view._model_prefix, sql_view.technical_name)
  171. @api.onchange('group_ids')
  172. def onchange_group_ids(self):
  173. if self.state not in ('draft', 'sql_valid'):
  174. self.has_group_changed = True
  175. # Overload Section
  176. @api.multi
  177. def write(self, vals):
  178. res = super(BiSQLView, self).write(vals)
  179. if vals.get('sequence', False):
  180. for rec in self.filtered(lambda x: x.menu_id):
  181. rec.menu_id.sequence = rec.sequence
  182. return res
  183. @api.multi
  184. def unlink(self):
  185. if any(view.state not in ('draft', 'sql_valid') for view in self):
  186. raise UserError(
  187. _("You can only unlink draft views."
  188. "If you want to delete them, first set them to draft."))
  189. return super(BiSQLView, self).unlink()
  190. @api.multi
  191. def copy(self, default=None):
  192. self.ensure_one()
  193. default = dict(default or {})
  194. default.update({
  195. 'name': _('%s (Copy)') % self.name,
  196. 'technical_name': '%s_copy' % self.technical_name,
  197. })
  198. return super(BiSQLView, self).copy(default=default)
  199. # Action Section
  200. @api.multi
  201. def button_create_sql_view_and_model(self):
  202. for sql_view in self:
  203. if sql_view.state != 'sql_valid':
  204. raise UserError(_(
  205. "You can only process this action on SQL Valid items"))
  206. # Create ORM and access
  207. sql_view._create_model_and_fields()
  208. sql_view._create_model_access()
  209. # Create SQL View and indexes
  210. sql_view._create_view()
  211. sql_view._create_index()
  212. if sql_view.is_materialized:
  213. sql_view.cron_id = self.env['ir.cron'].create(
  214. sql_view._prepare_cron()).id
  215. sql_view.state = 'model_valid'
  216. @api.multi
  217. def button_set_draft(self):
  218. for sql_view in self:
  219. sql_view.menu_id.unlink()
  220. sql_view.action_id.unlink()
  221. sql_view.tree_view_id.unlink()
  222. sql_view.graph_view_id.unlink()
  223. sql_view.pivot_view_id.unlink()
  224. sql_view.search_view_id.unlink()
  225. if sql_view.cron_id:
  226. sql_view.cron_id.unlink()
  227. if sql_view.state in ('model_valid', 'ui_valid'):
  228. # Drop SQL View (and indexes by cascade)
  229. if sql_view.is_materialized:
  230. sql_view._drop_view()
  231. # Drop ORM
  232. sql_view._drop_model_and_fields()
  233. sql_view.write({'state': 'draft', 'has_group_changed': False})
  234. @api.multi
  235. def button_create_ui(self):
  236. self.tree_view_id = self.env['ir.ui.view'].create(
  237. self._prepare_tree_view()).id
  238. self.graph_view_id = self.env['ir.ui.view'].create(
  239. self._prepare_graph_view()).id
  240. self.pivot_view_id = self.env['ir.ui.view'].create(
  241. self._prepare_pivot_view()).id
  242. self.search_view_id = self.env['ir.ui.view'].create(
  243. self._prepare_search_view()).id
  244. self.action_id = self.env['ir.actions.act_window'].create(
  245. self._prepare_action()).id
  246. self.menu_id = self.env['ir.ui.menu'].create(
  247. self._prepare_menu()).id
  248. self.write({'state': 'ui_valid'})
  249. @api.multi
  250. def button_update_model_access(self):
  251. self._drop_model_access()
  252. self._create_model_access()
  253. self.write({'has_group_changed': False})
  254. @api.multi
  255. def button_refresh_materialized_view(self):
  256. self._refresh_materialized_view()
  257. @api.multi
  258. def button_open_view(self):
  259. return {
  260. 'type': 'ir.actions.act_window',
  261. 'res_model': self.model_id.model,
  262. 'search_view_id': self.search_view_id.id,
  263. 'view_mode': self.action_id.view_mode,
  264. }
  265. # Prepare Function
  266. @api.multi
  267. def _prepare_model(self):
  268. self.ensure_one()
  269. field_id = []
  270. for field in self.bi_sql_view_field_ids.filtered(
  271. lambda x: x.field_description is not False):
  272. field_id.append([0, False, field._prepare_model_field()])
  273. return {
  274. 'name': self.name,
  275. 'model': self.model_name,
  276. 'access_ids': [],
  277. 'field_id': field_id,
  278. }
  279. @api.multi
  280. def _prepare_model_access(self):
  281. self.ensure_one()
  282. res = []
  283. for group in self.group_ids:
  284. res.append({
  285. 'name': _('%s Access %s') % (
  286. self.model_name, group.full_name),
  287. 'model_id': self.model_id.id,
  288. 'group_id': group.id,
  289. 'perm_read': True,
  290. 'perm_create': False,
  291. 'perm_write': False,
  292. 'perm_unlink': False,
  293. })
  294. return res
  295. @api.multi
  296. def _prepare_cron(self):
  297. self.ensure_one()
  298. return {
  299. 'name': _('Refresh Materialized View %s') % self.view_name,
  300. 'user_id': SUPERUSER_ID,
  301. 'model_id': self.env['ir.model'].search([
  302. ('model', '=', self._name)], limit=1).id,
  303. 'state': 'code',
  304. 'code': 'model._refresh_materialized_view_cron(%s)' % self.ids,
  305. 'numbercall': -1,
  306. }
  307. @api.multi
  308. def _prepare_rule(self):
  309. self.ensure_one()
  310. return {
  311. 'name': _('Access %s') % self.name,
  312. 'model_id': self.model_id.id,
  313. 'domain_force': self.domain_force,
  314. 'global': True,
  315. }
  316. @api.multi
  317. def _prepare_tree_view(self):
  318. self.ensure_one()
  319. return {
  320. 'name': self.name,
  321. 'type': 'tree',
  322. 'model': self.model_id.model,
  323. 'arch':
  324. """<?xml version="1.0"?>"""
  325. """<tree string="Analysis">{}"""
  326. """</tree>""".format("".join(
  327. [x._prepare_tree_field()
  328. for x in self.bi_sql_view_field_ids]))
  329. }
  330. @api.multi
  331. def _prepare_graph_view(self):
  332. self.ensure_one()
  333. return {
  334. 'name': self.name,
  335. 'type': 'graph',
  336. 'model': self.model_id.model,
  337. 'arch':
  338. """<?xml version="1.0"?>"""
  339. """<graph string="Analysis" type="bar" stacked="True">{}"""
  340. """</graph>""".format("".join(
  341. [x._prepare_graph_field()
  342. for x in self.bi_sql_view_field_ids]))
  343. }
  344. @api.multi
  345. def _prepare_pivot_view(self):
  346. self.ensure_one()
  347. return {
  348. 'name': self.name,
  349. 'type': 'pivot',
  350. 'model': self.model_id.model,
  351. 'arch':
  352. """<?xml version="1.0"?>"""
  353. """<pivot string="Analysis" stacked="True">{}"""
  354. """</pivot>""".format("".join(
  355. [x._prepare_pivot_field()
  356. for x in self.bi_sql_view_field_ids]))
  357. }
  358. @api.multi
  359. def _prepare_search_view(self):
  360. self.ensure_one()
  361. return {
  362. 'name': self.name,
  363. 'type': 'search',
  364. 'model': self.model_id.model,
  365. 'arch':
  366. """<?xml version="1.0"?>"""
  367. """<search string="Analysis">{}"""
  368. """<group expand="1" string="Group By">{}</group>"""
  369. """</search>""".format(
  370. "".join(
  371. [x._prepare_search_field()
  372. for x in self.bi_sql_view_field_ids]),
  373. "".join(
  374. [x._prepare_search_filter_field()
  375. for x in self.bi_sql_view_field_ids]))
  376. }
  377. @api.multi
  378. def _prepare_action(self):
  379. self.ensure_one()
  380. view_mode = self.view_order
  381. first_view = view_mode.split(',')[0]
  382. if first_view == 'tree':
  383. view_id = self.tree_view_id.id
  384. elif first_view == 'pivot':
  385. view_id = self.pivot_view_id.id
  386. else:
  387. view_id = self.graph_view_id.id
  388. return {
  389. 'name': self._prepare_action_name(),
  390. 'res_model': self.model_id.model,
  391. 'type': 'ir.actions.act_window',
  392. 'view_mode': view_mode,
  393. 'view_id': view_id,
  394. 'search_view_id': self.search_view_id.id,
  395. 'context': self.action_context,
  396. }
  397. @api.multi
  398. def _prepare_action_name(self):
  399. self.ensure_one()
  400. if not self.is_materialized:
  401. return self.name
  402. return "%s (%s)" % (
  403. self.name,
  404. datetime.utcnow().strftime(_("%m/%d/%Y %H:%M:%S UTC")))
  405. @api.multi
  406. def _prepare_menu(self):
  407. self.ensure_one()
  408. return {
  409. 'name': self.name,
  410. 'parent_id': self.env.ref('bi_sql_editor.menu_bi_sql_editor').id,
  411. 'action': 'ir.actions.act_window,%s' % self.action_id.id,
  412. 'sequence': self.sequence,
  413. }
  414. # Custom Section
  415. def _log_execute(self, req):
  416. _logger.info("Executing SQL Request %s ..." % req)
  417. self.env.cr.execute(req)
  418. @api.multi
  419. def _drop_view(self):
  420. for sql_view in self:
  421. self._log_execute(
  422. "DROP %s VIEW IF EXISTS %s" % (
  423. sql_view.materialized_text, sql_view.view_name))
  424. sql_view.size = False
  425. @api.multi
  426. def _create_view(self):
  427. for sql_view in self:
  428. sql_view._drop_view()
  429. try:
  430. self._log_execute(sql_view._prepare_request_for_execution())
  431. sql_view._refresh_size()
  432. except ProgrammingError as e:
  433. raise UserError(_(
  434. "SQL Error while creating %s VIEW %s :\n %s") % (
  435. sql_view.materialized_text, sql_view.view_name,
  436. e.message))
  437. @api.multi
  438. def _create_index(self):
  439. for sql_view in self:
  440. for sql_field in sql_view.bi_sql_view_field_ids.filtered(
  441. lambda x: x.is_index is True):
  442. self._log_execute(
  443. "CREATE INDEX %s ON %s (%s);" % (
  444. sql_field.index_name, sql_view.view_name,
  445. sql_field.name))
  446. @api.multi
  447. def _create_model_and_fields(self):
  448. for sql_view in self:
  449. # Create model
  450. sql_view.model_id = self.env['ir.model'].create(
  451. self._prepare_model()).id
  452. sql_view.rule_id = self.env['ir.rule'].create(
  453. self._prepare_rule()).id
  454. # Drop table, created by the ORM
  455. if sql.table_exists(self._cr, sql_view.view_name):
  456. req = "DROP TABLE %s" % sql_view.view_name
  457. self._log_execute(req)
  458. @api.multi
  459. def _create_model_access(self):
  460. for sql_view in self:
  461. for item in sql_view._prepare_model_access():
  462. self.env['ir.model.access'].create(item)
  463. @api.multi
  464. def _drop_model_access(self):
  465. for sql_view in self:
  466. self.env['ir.model.access'].search(
  467. [('model_id', '=', sql_view.model_name)]).unlink()
  468. @api.multi
  469. def _drop_model_and_fields(self):
  470. for sql_view in self:
  471. if sql_view.rule_id:
  472. sql_view.rule_id.unlink()
  473. if sql_view.model_id:
  474. sql_view.model_id.with_context(_force_unlink=True).unlink()
  475. @api.multi
  476. def _hook_executed_request(self):
  477. self.ensure_one()
  478. req = """
  479. SELECT attnum,
  480. attname AS column,
  481. format_type(atttypid, atttypmod) AS type
  482. FROM pg_attribute
  483. WHERE attrelid = '%s'::regclass
  484. AND NOT attisdropped
  485. AND attnum > 0
  486. ORDER BY attnum;""" % self.view_name
  487. self._log_execute(req)
  488. return self.env.cr.fetchall()
  489. @api.multi
  490. def _prepare_request_check_execution(self):
  491. self.ensure_one()
  492. return "CREATE VIEW %s AS (%s);" % (self.view_name, self.query)
  493. @api.multi
  494. def _prepare_request_for_execution(self):
  495. self.ensure_one()
  496. query = """
  497. SELECT
  498. CAST(row_number() OVER () as integer) AS id,
  499. CAST(Null as timestamp without time zone) as create_date,
  500. CAST(Null as integer) as create_uid,
  501. CAST(Null as timestamp without time zone) as write_date,
  502. CAST(Null as integer) as write_uid,
  503. my_query.*
  504. FROM
  505. (%s) as my_query
  506. """ % self.query
  507. return "CREATE %s VIEW %s AS (%s);" % (
  508. self.materialized_text, self.view_name, query)
  509. @api.multi
  510. def _check_execution(self):
  511. """Ensure that the query is valid, trying to execute it.
  512. a non materialized view is created for this check.
  513. A rollback is done at the end.
  514. After the execution, and before the rollback, an analysis of
  515. the database structure is done, to know fields type."""
  516. self.ensure_one()
  517. sql_view_field_obj = self.env['bi.sql.view.field']
  518. columns = super(BiSQLView, self)._check_execution()
  519. field_ids = []
  520. for column in columns:
  521. existing_field = self.bi_sql_view_field_ids.filtered(
  522. lambda x: x.name == column[1])
  523. if existing_field:
  524. # Update existing field
  525. field_ids.append(existing_field.id)
  526. existing_field.write({
  527. 'sequence': column[0],
  528. 'sql_type': column[2],
  529. })
  530. else:
  531. # Create a new one if name is prefixed by x_
  532. if column[1][:2] == 'x_':
  533. field_ids.append(sql_view_field_obj.create({
  534. 'sequence': column[0],
  535. 'name': column[1],
  536. 'sql_type': column[2],
  537. 'bi_sql_view_id': self.id,
  538. }).id)
  539. # Drop obsolete view field
  540. self.bi_sql_view_field_ids.filtered(
  541. lambda x: x.id not in field_ids).unlink()
  542. if not self.bi_sql_view_field_ids:
  543. raise UserError(_(
  544. "No Column was found.\n"
  545. "Columns name should be prefixed by 'x_'."))
  546. return columns
  547. @api.model
  548. def _refresh_materialized_view_cron(self, view_ids):
  549. sql_views = self.search([
  550. ('is_materialized', '=', True),
  551. ('state', 'in', ['model_valid', 'ui_valid']),
  552. ('id', 'in', view_ids),
  553. ])
  554. return sql_views._refresh_materialized_view()
  555. @api.multi
  556. def _refresh_materialized_view(self):
  557. for sql_view in self.filtered(lambda x: x.is_materialized):
  558. req = "REFRESH %s VIEW %s" % (
  559. sql_view.materialized_text, sql_view.view_name)
  560. self._log_execute(req)
  561. sql_view._refresh_size()
  562. if sql_view.action_id:
  563. # Alter name of the action, to display last refresh
  564. # datetime of the materialized view
  565. sql_view.action_id.name = sql_view._prepare_action_name()
  566. @api.multi
  567. def _refresh_size(self):
  568. for sql_view in self:
  569. req = "SELECT pg_size_pretty(pg_total_relation_size('%s'));" % (
  570. sql_view.view_name)
  571. self._log_execute(req)
  572. sql_view.size = self.env.cr.fetchone()[0]
  573. @api.multi
  574. def button_preview_sql_expression(self):
  575. self.button_validate_sql_expression()
  576. res = self._execute_sql_request()
  577. raise UserError('\n'.join(map(lambda x: str(x), res[:100])))