@@ -511,8 +511,41 @@ def _log_execute(self, req):
511511 _logger .info (f"Executing SQL Request { req } ..." )
512512 self .env .cr .execute (req )
513513
514- def _drop_view (self ):
514+ def _view_exists (self ):
515+ self .ensure_one ()
516+ query = """
517+ SELECT c.relkind
518+ FROM pg_class c
519+ JOIN pg_namespace n ON n.oid = c.relnamespace
520+ WHERE c.relname = %s
521+ AND n.nspname = current_schema()
522+ """
523+ self .env .cr .execute (query , (self .view_name ,))
524+ result = self .env .cr .fetchone ()
525+
526+ if not result :
527+ return False
528+
529+ relkind = result [0 ]
530+ if self .is_materialized :
531+ return relkind == "m"
532+ else :
533+ return relkind == "v"
534+
535+ def _drop_view (self , raise_if_not_exists = True ):
515536 for sql_view in self :
537+ if not sql_view ._view_exists ():
538+ if raise_if_not_exists :
539+ raise UserError (
540+ self .env ._ (
541+ "Cannot drop %(view_type)s view '%(view_name)s'. "
542+ "The view does not exist in the database." ,
543+ view_type = sql_view .materialized_text .lower () or "regular" ,
544+ view_name = sql_view .view_name ,
545+ )
546+ )
547+ continue
548+
516549 self ._log_execute (
517550 SQL ("DROP {materialized_text} VIEW IF EXISTS {view_name}" ).format (
518551 materialized_text = SQL (sql_view .materialized_text ),
@@ -523,7 +556,7 @@ def _drop_view(self):
523556
524557 def _create_view (self ):
525558 for sql_view in self :
526- sql_view ._drop_view ()
559+ sql_view ._drop_view (raise_if_not_exists = False )
527560 try :
528561 self ._log_execute (sql_view ._prepare_request_for_execution ())
529562 sql_view ._refresh_size ()
@@ -679,6 +712,15 @@ def _refresh_materialized_view_cron(self, view_ids):
679712
680713 def _refresh_materialized_view (self ):
681714 for sql_view in self .filtered (lambda x : x .is_materialized ):
715+ if not sql_view ._view_exists ():
716+ raise UserError (
717+ self .env ._ (
718+ "Cannot refresh materialized view '%(view_name)s'. "
719+ "The view does not exist in the database." ,
720+ view_name = sql_view .view_name ,
721+ )
722+ )
723+
682724 req = f"REFRESH { sql_view .materialized_text } VIEW { sql_view .view_name } "
683725 self ._log_execute (req )
684726 sql_view ._refresh_size ()
0 commit comments