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.

647 lines
22 KiB

8 years ago
8 years ago
8 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.ir.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. has_group_changed = fields.Boolean(copy=False)
  98. bi_sql_view_field_ids = fields.One2many(
  99. string='SQL Fields', comodel_name='bi.sql.view.field',
  100. inverse_name='bi_sql_view_id')
  101. model_id = fields.Many2one(
  102. string='Odoo Model', comodel_name='ir.model', readonly=True)
  103. tree_view_id = fields.Many2one(
  104. string='Odoo Tree View', comodel_name='ir.ui.view', readonly=True)
  105. graph_view_id = fields.Many2one(
  106. string='Odoo Graph View', comodel_name='ir.ui.view', readonly=True)
  107. pivot_view_id = fields.Many2one(
  108. string='Odoo Pivot View', comodel_name='ir.ui.view', readonly=True)
  109. search_view_id = fields.Many2one(
  110. string='Odoo Search View', comodel_name='ir.ui.view', readonly=True)
  111. action_id = fields.Many2one(
  112. string='Odoo Action', comodel_name='ir.actions.act_window',
  113. readonly=True)
  114. menu_id = fields.Many2one(
  115. string='Odoo Menu', comodel_name='ir.ui.menu', readonly=True)
  116. cron_id = fields.Many2one(
  117. string='Odoo Cron', comodel_name='ir.cron', readonly=True,
  118. help="Cron Task that will refresh the materialized view")
  119. rule_id = fields.Many2one(
  120. string='Odoo Rule', comodel_name='ir.rule', readonly=True)
  121. group_ids = fields.Many2many(
  122. comodel_name='res.groups', readonly=True, states={
  123. 'draft': [('readonly', False)],
  124. 'sql_valid': [('readonly', False)],
  125. })
  126. sequence = fields.Integer(string='sequence')
  127. # Constrains Section
  128. @api.constrains('is_materialized')
  129. @api.multi
  130. def _check_index_materialized(self):
  131. for rec in self.filtered(lambda x: not x.is_materialized):
  132. if rec.bi_sql_view_field_ids.filtered(lambda x: x.is_index):
  133. raise UserError(_(
  134. 'You can not create indexes on non materialized views'))
  135. @api.constrains('view_order')
  136. @api.multi
  137. def _check_view_order(self):
  138. for rec in self:
  139. if rec.view_order:
  140. for vtype in rec.view_order.split(','):
  141. if vtype not in ('graph', 'pivot', 'tree'):
  142. raise UserError(_(
  143. 'Only graph, pivot or tree views are supported'))
  144. # Compute Section
  145. @api.depends('is_materialized')
  146. @api.multi
  147. def _compute_materialized_text(self):
  148. for sql_view in self:
  149. sql_view.materialized_text =\
  150. sql_view.is_materialized and 'MATERIALIZED' or ''
  151. @api.depends('technical_name')
  152. @api.multi
  153. def _compute_view_name(self):
  154. for sql_view in self:
  155. sql_view.view_name = '%s%s' % (
  156. sql_view._sql_prefix, sql_view.technical_name)
  157. @api.depends('technical_name')
  158. @api.multi
  159. def _compute_model_name(self):
  160. for sql_view in self:
  161. sql_view.model_name = '%s%s' % (
  162. sql_view._model_prefix, sql_view.technical_name)
  163. @api.onchange('group_ids')
  164. def onchange_group_ids(self):
  165. if self.state not in ('draft', 'sql_valid'):
  166. self.has_group_changed = True
  167. # Overload Section
  168. @api.multi
  169. def write(self, vals):
  170. res = super(BiSQLView, self).write(vals)
  171. if vals.get('sequence', False):
  172. for rec in self.filtered(lambda x: x.menu_id):
  173. rec.menu_id.sequence = rec.sequence
  174. return res
  175. @api.multi
  176. def unlink(self):
  177. if any(view.state not in ('draft', 'sql_valid') for view in self):
  178. raise UserError(
  179. _("You can only unlink draft views."
  180. "If you want to delete them, first set them to draft."))
  181. return super(BiSQLView, self).unlink()
  182. @api.multi
  183. def copy(self, default=None):
  184. self.ensure_one()
  185. default = dict(default or {})
  186. default.update({
  187. 'name': _('%s (Copy)') % self.name,
  188. 'technical_name': '%s_copy' % self.technical_name,
  189. })
  190. return super(BiSQLView, self).copy(default=default)
  191. # Action Section
  192. @api.multi
  193. def button_create_sql_view_and_model(self):
  194. for sql_view in self:
  195. if sql_view.state != 'sql_valid':
  196. raise UserError(_(
  197. "You can only process this action on SQL Valid items"))
  198. # Create ORM and access
  199. sql_view._create_model_and_fields()
  200. sql_view._create_model_access()
  201. # Create SQL View and indexes
  202. sql_view._create_view()
  203. sql_view._create_index()
  204. if sql_view.is_materialized:
  205. sql_view.cron_id = self.env['ir.cron'].create(
  206. sql_view._prepare_cron()).id
  207. sql_view.state = 'model_valid'
  208. @api.multi
  209. def button_set_draft(self):
  210. for sql_view in self:
  211. sql_view.menu_id.unlink()
  212. sql_view.action_id.unlink()
  213. sql_view.tree_view_id.unlink()
  214. sql_view.graph_view_id.unlink()
  215. sql_view.pivot_view_id.unlink()
  216. sql_view.search_view_id.unlink()
  217. if sql_view.cron_id:
  218. sql_view.cron_id.unlink()
  219. if sql_view.state in ('model_valid', 'ui_valid'):
  220. # Drop SQL View (and indexes by cascade)
  221. if sql_view.is_materialized:
  222. sql_view._drop_view()
  223. # Drop ORM
  224. sql_view._drop_model_and_fields()
  225. sql_view.write({'state': 'draft', 'has_group_changed': False})
  226. @api.multi
  227. def button_create_ui(self):
  228. self.tree_view_id = self.env['ir.ui.view'].create(
  229. self._prepare_tree_view()).id
  230. self.graph_view_id = self.env['ir.ui.view'].create(
  231. self._prepare_graph_view()).id
  232. self.pivot_view_id = self.env['ir.ui.view'].create(
  233. self._prepare_pivot_view()).id
  234. self.search_view_id = self.env['ir.ui.view'].create(
  235. self._prepare_search_view()).id
  236. self.action_id = self.env['ir.actions.act_window'].create(
  237. self._prepare_action()).id
  238. self.menu_id = self.env['ir.ui.menu'].create(
  239. self._prepare_menu()).id
  240. self.write({'state': 'ui_valid'})
  241. @api.multi
  242. def button_update_model_access(self):
  243. self._drop_model_access()
  244. self._create_model_access()
  245. self.write({'has_group_changed': False})
  246. @api.multi
  247. def button_refresh_materialized_view(self):
  248. self._refresh_materialized_view()
  249. @api.multi
  250. def button_open_view(self):
  251. return {
  252. 'type': 'ir.actions.act_window',
  253. 'res_model': self.model_id.model,
  254. 'search_view_id': self.search_view_id.id,
  255. 'view_mode': self.action_id.view_mode,
  256. }
  257. # Prepare Function
  258. @api.multi
  259. def _prepare_model(self):
  260. self.ensure_one()
  261. field_id = []
  262. for field in self.bi_sql_view_field_ids.filtered(
  263. lambda x: x.field_description is not False):
  264. field_id.append([0, False, field._prepare_model_field()])
  265. return {
  266. 'name': self.name,
  267. 'model': self.model_name,
  268. 'access_ids': [],
  269. 'field_id': field_id,
  270. }
  271. @api.multi
  272. def _prepare_model_access(self):
  273. self.ensure_one()
  274. res = []
  275. for group in self.group_ids:
  276. res.append({
  277. 'name': _('%s Access %s') % (
  278. self.model_name, group.full_name),
  279. 'model_id': self.model_id.id,
  280. 'group_id': group.id,
  281. 'perm_read': True,
  282. 'perm_create': False,
  283. 'perm_write': False,
  284. 'perm_unlink': False,
  285. })
  286. return res
  287. @api.multi
  288. def _prepare_cron(self):
  289. self.ensure_one()
  290. return {
  291. 'name': _('Refresh Materialized View %s') % self.view_name,
  292. 'user_id': SUPERUSER_ID,
  293. 'model_id': self.env['ir.model'].search([
  294. ('model', '=', self._name)], limit=1).id,
  295. 'state': 'code',
  296. 'code': 'model._refresh_materialized_view_cron(%s)' % self.ids,
  297. 'numbercall': -1,
  298. }
  299. @api.multi
  300. def _prepare_rule(self):
  301. self.ensure_one()
  302. return {
  303. 'name': _('Access %s') % self.name,
  304. 'model_id': self.model_id.id,
  305. 'domain_force': self.domain_force,
  306. 'global': True,
  307. }
  308. @api.multi
  309. def _prepare_tree_view(self):
  310. self.ensure_one()
  311. return {
  312. 'name': self.name,
  313. 'type': 'tree',
  314. 'model': self.model_id.model,
  315. 'arch':
  316. """<?xml version="1.0"?>"""
  317. """<tree string="Analysis">{}"""
  318. """</tree>""".format("".join(
  319. [x._prepare_tree_field()
  320. for x in self.bi_sql_view_field_ids]))
  321. }
  322. @api.multi
  323. def _prepare_graph_view(self):
  324. self.ensure_one()
  325. return {
  326. 'name': self.name,
  327. 'type': 'graph',
  328. 'model': self.model_id.model,
  329. 'arch':
  330. """<?xml version="1.0"?>"""
  331. """<graph string="Analysis" type="bar" stacked="True">{}"""
  332. """</graph>""".format("".join(
  333. [x._prepare_graph_field()
  334. for x in self.bi_sql_view_field_ids]))
  335. }
  336. @api.multi
  337. def _prepare_pivot_view(self):
  338. self.ensure_one()
  339. return {
  340. 'name': self.name,
  341. 'type': 'pivot',
  342. 'model': self.model_id.model,
  343. 'arch':
  344. """<?xml version="1.0"?>"""
  345. """<pivot string="Analysis" stacked="True">{}"""
  346. """</pivot>""".format("".join(
  347. [x._prepare_pivot_field()
  348. for x in self.bi_sql_view_field_ids]))
  349. }
  350. @api.multi
  351. def _prepare_search_view(self):
  352. self.ensure_one()
  353. return {
  354. 'name': self.name,
  355. 'type': 'search',
  356. 'model': self.model_id.model,
  357. 'arch':
  358. """<?xml version="1.0"?>"""
  359. """<search string="Analysis">{}"""
  360. """<group expand="1" string="Group By">{}</group>"""
  361. """</search>""".format(
  362. "".join(
  363. [x._prepare_search_field()
  364. for x in self.bi_sql_view_field_ids]),
  365. "".join(
  366. [x._prepare_search_filter_field()
  367. for x in self.bi_sql_view_field_ids]))
  368. }
  369. @api.multi
  370. def _prepare_action(self):
  371. self.ensure_one()
  372. view_mode = self.view_order
  373. return {
  374. 'name': self._prepare_action_name(),
  375. 'res_model': self.model_id.model,
  376. 'type': 'ir.actions.act_window',
  377. 'view_mode': view_mode,
  378. }
  379. @api.multi
  380. def _prepare_action_name(self):
  381. self.ensure_one()
  382. if not self.is_materialized:
  383. return self.name
  384. return "%s (%s)" % (
  385. self.name,
  386. datetime.utcnow().strftime(_("%m/%d/%Y %H:%M:%S UTC")))
  387. @api.multi
  388. def _prepare_menu(self):
  389. self.ensure_one()
  390. return {
  391. 'name': self.name,
  392. 'parent_id': self.env.ref('bi_sql_editor.menu_bi_sql_editor').id,
  393. 'action': 'ir.actions.act_window,%s' % self.action_id.id,
  394. 'sequence': self.sequence,
  395. }
  396. # Custom Section
  397. def _log_execute(self, req):
  398. _logger.info("Executing SQL Request %s ..." % req)
  399. self.env.cr.execute(req)
  400. @api.multi
  401. def _drop_view(self):
  402. for sql_view in self:
  403. self._log_execute(
  404. "DROP %s VIEW IF EXISTS %s" % (
  405. sql_view.materialized_text, sql_view.view_name))
  406. sql_view.size = False
  407. @api.multi
  408. def _create_view(self):
  409. for sql_view in self:
  410. sql_view._drop_view()
  411. try:
  412. self._log_execute(sql_view._prepare_request_for_execution())
  413. sql_view._refresh_size()
  414. except ProgrammingError as e:
  415. raise UserError(_(
  416. "SQL Error while creating %s VIEW %s :\n %s") % (
  417. sql_view.materialized_text, sql_view.view_name,
  418. e.message))
  419. @api.multi
  420. def _create_index(self):
  421. for sql_view in self:
  422. for sql_field in sql_view.bi_sql_view_field_ids.filtered(
  423. lambda x: x.is_index is True):
  424. self._log_execute(
  425. "CREATE INDEX %s ON %s (%s);" % (
  426. sql_field.index_name, sql_view.view_name,
  427. sql_field.name))
  428. @api.multi
  429. def _create_model_and_fields(self):
  430. for sql_view in self:
  431. # Create model
  432. sql_view.model_id = self.env['ir.model'].create(
  433. self._prepare_model()).id
  434. sql_view.rule_id = self.env['ir.rule'].create(
  435. self._prepare_rule()).id
  436. # Drop table, created by the ORM
  437. if sql.table_exists(self._cr, sql_view.view_name):
  438. req = "DROP TABLE %s" % sql_view.view_name
  439. self._log_execute(req)
  440. @api.multi
  441. def _create_model_access(self):
  442. for sql_view in self:
  443. for item in sql_view._prepare_model_access():
  444. self.env['ir.model.access'].create(item)
  445. @api.multi
  446. def _drop_model_access(self):
  447. for sql_view in self:
  448. self.env['ir.model.access'].search(
  449. [('model_id', '=', sql_view.model_name)]).unlink()
  450. @api.multi
  451. def _drop_model_and_fields(self):
  452. for sql_view in self:
  453. if sql_view.rule_id:
  454. sql_view.rule_id.unlink()
  455. if sql_view.model_id:
  456. sql_view.model_id.with_context(_force_unlink=True).unlink()
  457. @api.multi
  458. def _hook_executed_request(self):
  459. self.ensure_one()
  460. req = """
  461. SELECT attnum,
  462. attname AS column,
  463. format_type(atttypid, atttypmod) AS type
  464. FROM pg_attribute
  465. WHERE attrelid = '%s'::regclass
  466. AND NOT attisdropped
  467. AND attnum > 0
  468. ORDER BY attnum;""" % self.view_name
  469. self._log_execute(req)
  470. return self.env.cr.fetchall()
  471. @api.multi
  472. def _prepare_request_check_execution(self):
  473. self.ensure_one()
  474. return "CREATE VIEW %s AS (%s);" % (self.view_name, self.query)
  475. @api.multi
  476. def _prepare_request_for_execution(self):
  477. self.ensure_one()
  478. query = """
  479. SELECT
  480. CAST(row_number() OVER () as integer) AS id,
  481. CAST(Null as timestamp without time zone) as create_date,
  482. CAST(Null as integer) as create_uid,
  483. CAST(Null as timestamp without time zone) as write_date,
  484. CAST(Null as integer) as write_uid,
  485. my_query.*
  486. FROM
  487. (%s) as my_query
  488. """ % self.query
  489. return "CREATE %s VIEW %s AS (%s);" % (
  490. self.materialized_text, self.view_name, query)
  491. @api.multi
  492. def _check_execution(self):
  493. """Ensure that the query is valid, trying to execute it.
  494. a non materialized view is created for this check.
  495. A rollback is done at the end.
  496. After the execution, and before the rollback, an analysis of
  497. the database structure is done, to know fields type."""
  498. self.ensure_one()
  499. sql_view_field_obj = self.env['bi.sql.view.field']
  500. columns = super(BiSQLView, self)._check_execution()
  501. field_ids = []
  502. for column in columns:
  503. existing_field = self.bi_sql_view_field_ids.filtered(
  504. lambda x: x.name == column[1])
  505. if existing_field:
  506. # Update existing field
  507. field_ids.append(existing_field.id)
  508. existing_field.write({
  509. 'sequence': column[0],
  510. 'sql_type': column[2],
  511. })
  512. else:
  513. # Create a new one if name is prefixed by x_
  514. if column[1][:2] == 'x_':
  515. field_ids.append(sql_view_field_obj.create({
  516. 'sequence': column[0],
  517. 'name': column[1],
  518. 'sql_type': column[2],
  519. 'bi_sql_view_id': self.id,
  520. }).id)
  521. # Drop obsolete view field
  522. self.bi_sql_view_field_ids.filtered(
  523. lambda x: x.id not in field_ids).unlink()
  524. if not self.bi_sql_view_field_ids:
  525. raise UserError(_(
  526. "No Column was found.\n"
  527. "Columns name should be prefixed by 'x_'."))
  528. return columns
  529. @api.model
  530. def _refresh_materialized_view_cron(self, view_ids):
  531. sql_views = self.search([
  532. ('is_materialized', '=', True),
  533. ('state', 'in', ['model_valid', 'ui_valid']),
  534. ('id', 'in', view_ids),
  535. ])
  536. return sql_views._refresh_materialized_view()
  537. @api.multi
  538. def _refresh_materialized_view(self):
  539. for sql_view in self.filtered(lambda x: x.is_materialized):
  540. req = "REFRESH %s VIEW %s" % (
  541. sql_view.materialized_text, sql_view.view_name)
  542. self._log_execute(req)
  543. sql_view._refresh_size()
  544. if sql_view.action_id:
  545. # Alter name of the action, to display last refresh
  546. # datetime of the materialized view
  547. sql_view.action_id.name = sql_view._prepare_action_name()
  548. @api.multi
  549. def _refresh_size(self):
  550. for sql_view in self:
  551. req = "SELECT pg_size_pretty(pg_total_relation_size('%s'));" % (
  552. sql_view.view_name)
  553. self._log_execute(req)
  554. sql_view.size = self.env.cr.fetchone()[0]
  555. @api.multi
  556. def button_preview_sql_expression(self):
  557. self.button_validate_sql_expression()
  558. res = self._execute_sql_request()
  559. raise UserError('\n'.join(map(lambda x: str(x), res[:100])))