The following are some real examples that have resulted from this and these
patterns may apply to future cases.
#### Path to removing cross-database joins
The following steps are the process to remove cross-database joins between
`ci_*` and non `ci_*` tables:
1.**{check-circle}** Add all failing specs to the [`cross-join-allowlist.yml`](https://gitlab.com/gitlab-org/gitlab/-/blob/f5de89daeb468fc45e1e95a76d1b5297aa53da11/spec/support/database/cross-join-allowlist.yml)
file.
1.**{dotted-circle}** Find the code that caused the spec failure and wrap the isolated code
in [`allow_cross_joins_across_databases`](#allowlist-for-existing-cross-joins).
Link to a new issue assigned to the correct team to remove the specs from the
`cross-join-allowlist.yml` file.
1.**{dotted-circle}** Remove the `cross-join-allowlist.yml` file and stop allowing
whole test files.
1.**{dotted-circle}** Fix the problem and remove the `allow_cross_joins_across_databases` call.
1.**{dotted-circle}** Fix all the cross-joins and remove the `allow_cross_joins_across_databases` method.
[Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/68620) in GitLab 14.3, any
queries detected that join across databases raises an error (except
for pre-existing queries).
#### Suggestions for removing cross-database joins
#### Remove the code
The following sections are some real examples that were identified as joining across databases,
along with possible suggestions on how to fix them.
##### Remove the code
The simplest solution we've seen several times now has been an existing scope
that is unused. This is the easiest example to fix. So the first step is to
...
...
@@ -135,7 +158,7 @@ to evaluate, because `UsageData` is not critical to users and it may be possible
to get a similarly useful metric with a simpler approach. Alternatively we may
find that nobody is using these metrics, so we can remove them.
#### Use `preload` instead of `includes`
##### Use `preload` instead of `includes`
The `includes` and `preload` methods in Rails are both ways to avoid an N+1
query. The `includes` method in Rails uses a heuristic approach to determine
...
...
@@ -149,7 +172,7 @@ allows you to avoid the join, while still avoiding the N+1 query.
You can see a real example of this solution being used in
"Unsupported cross-join across '#{tables.join(", ")}' modifying '#{schemas.to_a.join(", ")}' discovered "\
"when executing query '#{sql}'"
"when executing query '#{sql}'. Please refer to https://docs.gitlab.com/ee/development/database/multiple_databases.html#removing-joins-between-ci_-and-non-ci_-tables for details on how to resolve this exception."