@@ -511,8 +511,59 @@ 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+ if relkind == "v" :
532+ raise UserError (
533+ self .env ._ (
534+ "View '%(view_name)s' exists but is a regular view, "
535+ "not a materialized view. "
536+ "Please drop it first or uncheck 'Is Materialized View'." ,
537+ view_name = self .view_name ,
538+ )
539+ )
540+ return relkind == "m"
541+ else :
542+ if relkind == "m" :
543+ raise UserError (
544+ self .env ._ (
545+ "View '%(view_name)s' exists but is a materialized view, "
546+ "not a regular view. "
547+ "Please drop it first or check 'Is Materialized View'." ,
548+ view_name = self .view_name ,
549+ )
550+ )
551+ return relkind == "v"
552+
553+ def _drop_view (self , raise_if_not_exists = True ):
515554 for sql_view in self :
555+ if not sql_view ._view_exists ():
556+ if raise_if_not_exists :
557+ raise UserError (
558+ self .env ._ (
559+ "Cannot drop %(view_type)s view '%(view_name)s'. "
560+ "The view does not exist in the database." ,
561+ view_type = sql_view .materialized_text .lower () or "regular" ,
562+ view_name = sql_view .view_name ,
563+ )
564+ )
565+ continue
566+
516567 self ._log_execute (
517568 SQL ("DROP {materialized_text} VIEW IF EXISTS {view_name}" ).format (
518569 materialized_text = SQL (sql_view .materialized_text ),
@@ -523,7 +574,7 @@ def _drop_view(self):
523574
524575 def _create_view (self ):
525576 for sql_view in self :
526- sql_view ._drop_view ()
577+ sql_view ._drop_view (raise_if_not_exists = False )
527578 try :
528579 self ._log_execute (sql_view ._prepare_request_for_execution ())
529580 sql_view ._refresh_size ()
@@ -679,6 +730,15 @@ def _refresh_materialized_view_cron(self, view_ids):
679730
680731 def _refresh_materialized_view (self ):
681732 for sql_view in self .filtered (lambda x : x .is_materialized ):
733+ if not sql_view ._view_exists ():
734+ raise UserError (
735+ self .env ._ (
736+ "Cannot refresh materialized view '%(view_name)s'. "
737+ "The view does not exist in the database." ,
738+ view_name = sql_view .view_name ,
739+ )
740+ )
741+
682742 req = f"REFRESH { sql_view .materialized_text } VIEW { sql_view .view_name } "
683743 self ._log_execute (req )
684744 sql_view ._refresh_size ()
0 commit comments