Fix DML not allowed error when creating views

What does this MR do and why?

Adds a fix for DMLNotAllowedError when creating views.

As CREATE VIEW is a DDL statement, and can also include DML statements, this was causing the following error:

Gitlab::Database::QueryAnalyzers::RestrictAllowedSchemas::DMLNotAllowedError: Select/DML queries (SELECT/UPDATE/DELETE) are disallowed in the DDL (structure) mode. Modifying of '["<table_name>"]' ([:gitlab_main]) with 'CREATE VIEW issues AS SELECT * FROM <table_name> /*application:web,db_config_name:main,line:/lib/gitlab/database/rename_table_helpers.rb:9:in `block in rename_table_safely'*/'. For more information visit: https://docs.gitlab.com/ee/development/database/migrations_for_multiple_databases.html

How to set up and validate locally

From master

  1. Create a new migration rails g migration test_create_view
# frozen_string_literal: true

class TestCreateView < Gitlab::Database::Migration[2.2]
  milestone '17.2'

  def change
    connection.execute('CREATE OR REPLACE VIEW my_view AS SELECT * FROM projects WHERE id = 1')
  end
end
  1. You will see the following error:
❯ rails db:migrate
main: == [advisory_lock_connection] object_id: 127880, pg_backend_pid: 28587
main: == 20240621013445 TestCreateView: migrating ===================================
main: == [advisory_lock_connection] object_id: 127880, pg_backend_pid: 28587
rails aborted!
Gitlab::Database::QueryAnalyzers::RestrictAllowedSchemas::DMLNotAllowedError: Select/DML queries (SELECT/UPDATE/DELETE) are disallowed in the DDL (structure) mode. Modifying of '["projects"]' ([:gitlab_main]) with 'CREATE OR REPLACE VIEW my_view AS SELECT * FROM projects WHERE id = 1 /*application:web,db_config_name:main,line:/db/migrate/20240621013445_test_create_view.rb:7:in `change'*/'. For more information visit: https://docs.gitlab.com/ee/development/database/migrations_for_multiple_databases.html
  1. Switch to this branch
  2. Execute the migration
  3. Migration should be executed successfully

Related to #436942 (closed)

Edited by Leonardo da Rosa

Merge request reports

Loading