Commit c5c03187 authored by Adam Hegyi's avatar Adam Hegyi

Fix MultipleDatabases offenses

This change fixes some of the MultipleDatabases offenses.
parent a05f26bf
......@@ -2879,45 +2879,9 @@ Style/RegexpLiteralMixedPreserve:
- 'spec/support/helpers/require_migration.rb'
- 'spec/views/layouts/_head.html.haml_spec.rb'
# WIP see: https://gitlab.com/gitlab-org/gitlab/-/issues/335808
Database/MultipleDatabases:
Exclude:
- 'app/mailers/previews/notify_preview.rb'
- 'app/models/application_setting.rb'
- 'app/models/internal_id.rb'
- 'app/services/auto_merge/base_service.rb'
- 'app/services/ci/delete_unit_tests_service.rb'
- 'app/services/ci/unlock_artifacts_service.rb'
- 'app/services/deployments/update_environment_service.rb'
- 'app/services/design_management/copy_design_collection/copy_service.rb'
- 'app/services/feature_flags/create_service.rb'
- 'app/services/feature_flags/destroy_service.rb'
- 'app/services/feature_flags/update_service.rb'
- 'app/services/issuable/clone/base_service.rb'
- 'app/services/issuable/common_system_notes_service.rb'
- 'app/services/issuable/destroy_label_links_service.rb'
- 'app/services/packages/create_dependency_service.rb'
- 'app/services/packages/go/create_package_service.rb'
- 'app/services/packages/npm/create_package_service.rb'
- 'app/services/packages/terraform_module/create_package_service.rb'
- 'app/services/projects/cleanup_service.rb'
- 'app/services/projects/fetch_statistics_increment_service.rb'
- 'app/services/releases/update_service.rb'
- 'app/services/todos/destroy/destroyed_issuable_service.rb'
- 'ee/app/models/dora/daily_metrics.rb'
- 'ee/app/services/analytics/devops_adoption/enabled_namespaces/bulk_delete_service.rb'
- 'ee/app/services/approval_rules/finalize_service.rb'
- 'ee/app/services/approval_rules/project_rule_destroy_service.rb'
- 'ee/app/services/app_sec/dast/site_profiles/create_service.rb'
- 'ee/app/services/app_sec/dast/site_profiles/update_service.rb'
- 'ee/app/services/ci/minutes/update_build_minutes_service.rb'
- 'ee/app/services/ee/issuable/common_system_notes_service.rb'
- 'ee/app/services/group_saml/group_managed_accounts/transfer_membership_service.rb'
- 'ee/app/services/group_saml/sign_up_service.rb'
- 'ee/app/services/iterations/roll_over_issues_service.rb'
- 'ee/app/services/security/store_scan_service.rb'
- 'ee/app/services/timebox_report_service.rb'
- 'ee/app/services/vulnerability_feedback/create_service.rb'
- 'ee/lib/ee/gitlab/checks/push_rule_check.rb'
- 'ee/lib/ee/gitlab/database.rb'
- 'ee/lib/gitlab/geo/database_tasks.rb'
- 'ee/lib/gitlab/geo/geo_tasks.rb'
......@@ -2933,14 +2897,7 @@ Database/MultipleDatabases:
- 'lib/after_commit_queue.rb'
- 'lib/api/rubygem_packages.rb'
- 'lib/backup/manager.rb'
- 'lib/gitlab/analytics/cycle_analytics/stage_query_helpers.rb'
- 'lib/gitlab/chaos.rb'
- 'lib/gitlab/current_settings.rb'
- 'lib/gitlab/database/batch_count.rb'
- 'lib/gitlab/database/batch_counter.rb'
- 'lib/gitlab/database/count/reltuples_count_strategy.rb'
- 'lib/gitlab/database/count/tablesample_count_strategy.rb'
- 'lib/gitlab/database/grant.rb'
- 'lib/gitlab/database/load_balancing/load_balancer.rb'
- 'lib/gitlab/database/load_balancing.rb'
- 'lib/gitlab/database/load_balancing/sticking.rb'
......@@ -2962,7 +2919,6 @@ Database/MultipleDatabases:
- 'lib/gitlab/database/schema_cache_with_renamed_table.rb'
- 'lib/gitlab/database/schema_migrations/context.rb'
- 'lib/gitlab/database/schema_version_files.rb'
- 'lib/gitlab/database/similarity_score.rb'
- 'lib/gitlab/database/unidirectional_copy_trigger.rb'
- 'lib/gitlab/database/with_lock_retries.rb'
- 'lib/gitlab/gitlab_import/importer.rb'
......@@ -2971,13 +2927,8 @@ Database/MultipleDatabases:
- 'lib/gitlab/import_export/relation_tree_restorer.rb'
- 'lib/gitlab/legacy_github_import/importer.rb'
- 'lib/gitlab/metrics/samplers/database_sampler.rb'
- 'lib/gitlab/optimistic_locking.rb'
- 'lib/gitlab/otp_key_rotator.rb'
- 'lib/gitlab/profiler.rb'
- 'lib/gitlab/seeder.rb'
- 'lib/gitlab/sherlock/query.rb'
- 'lib/gitlab/sql/glob.rb'
- 'lib/gitlab/sql/set_operator.rb'
- 'lib/system_check/orphans/repository_check.rb'
- 'spec/db/schema_spec.rb'
- 'spec/features/admin/dashboard_spec.rb'
......@@ -2993,9 +2944,6 @@ Database/MultipleDatabases:
- 'spec/lib/gitlab/profiler_spec.rb'
- 'spec/lib/gitlab/query_limiting/active_support_subscriber_spec.rb'
- 'spec/lib/gitlab/sidekiq_logging/structured_logger_spec.rb'
- 'spec/lib/gitlab/sql/cte_spec.rb'
- 'spec/lib/gitlab/sql/glob_spec.rb'
- 'spec/lib/gitlab/sql/recursive_cte_spec.rb'
- 'spec/lib/gitlab/usage_data_metrics_spec.rb'
- 'spec/lib/gitlab/usage_data_queries_spec.rb'
- 'spec/lib/gitlab/usage/metrics/names_suggestions/relation_parsers/constraints_spec.rb'
......@@ -3003,11 +2951,6 @@ Database/MultipleDatabases:
- 'spec/lib/gitlab/usage/metrics/instrumentations/database_metric_spec.rb'
- 'spec/lib/gitlab/utils/usage_data_spec.rb'
- 'spec/models/application_setting_spec.rb'
- 'spec/models/concerns/case_sensitivity_spec.rb'
- 'spec/models/concerns/sortable_spec.rb'
- 'spec/models/concerns/where_composite_spec.rb'
- 'spec/models/experiment_spec.rb'
- 'spec/models/internal_id_spec.rb'
- 'spec/models/project_feature_usage_spec.rb'
- 'spec/models/users_statistics_spec.rb'
- 'spec/requests/api/statistics_spec.rb'
......
......@@ -246,7 +246,7 @@ class NotifyPreview < ActionMailer::Preview
def cleanup
email = nil
ActiveRecord::Base.transaction do
ActiveRecord::Base.transaction do # rubocop: disable Database/MultipleDatabases
email = yield
raise ActiveRecord::Rollback
end
......
......@@ -627,7 +627,7 @@ class ApplicationSetting < ApplicationRecord
# prevent this from happening, we do a sanity check that the
# primary key constraint is present before inserting a new entry.
def self.check_schema!
return if ActiveRecord::Base.connection.primary_key(self.table_name).present?
return if connection.primary_key(self.table_name).present?
raise "The `#{self.table_name}` table is missing a primary key constraint in the database schema"
end
......
......@@ -83,7 +83,7 @@ class InternalId < ApplicationRecord
self.internal_id_transactions_total.increment(
operation: operation,
usage: usage.to_s,
in_transaction: ActiveRecord::Base.connection.transaction_open?.to_s
in_transaction: ActiveRecord::Base.connection.transaction_open?.to_s # rubocop: disable Database/MultipleDatabases
)
end
......@@ -317,7 +317,7 @@ class InternalId < ApplicationRecord
stmt.set(arel_table[:last_value] => new_value)
stmt.wheres = InternalId.filter_by(scope, usage).arel.constraints
ActiveRecord::Base.connection.insert(stmt, 'Update InternalId', 'last_value')
ActiveRecord::Base.connection.insert(stmt, 'Update InternalId', 'last_value') # rubocop: disable Database/MultipleDatabases
end
def create_record!(subject, scope, usage, init)
......
......@@ -6,7 +6,7 @@ module AutoMerge
include MergeRequests::AssignsMergeParams
def execute(merge_request)
ActiveRecord::Base.transaction do
ActiveRecord::Base.transaction do # rubocop: disable Database/MultipleDatabases
register_auto_merge_parameters!(merge_request)
yield if block_given?
end
......@@ -29,7 +29,7 @@ module AutoMerge
end
def cancel(merge_request)
ActiveRecord::Base.transaction do
ActiveRecord::Base.transaction do # rubocop: disable Database/MultipleDatabases
clear_auto_merge_parameters!(merge_request)
yield if block_given?
end
......@@ -41,7 +41,7 @@ module AutoMerge
end
def abort(merge_request, reason)
ActiveRecord::Base.transaction do
ActiveRecord::Base.transaction do # rubocop: disable Database/MultipleDatabases
clear_auto_merge_parameters!(merge_request)
yield if block_given?
end
......
......@@ -23,7 +23,7 @@ module Ci
def delete_batch!(klass)
deleted = 0
ActiveRecord::Base.transaction do
klass.transaction do
ids = klass.deletable.lock('FOR UPDATE SKIP LOCKED').limit(BATCH_SIZE).pluck(:id)
break if ids.empty?
......
......@@ -17,7 +17,7 @@ module Ci
SQL
loop do
break if ActiveRecord::Base.connection.exec_query(query).empty?
break if Ci::Pipeline.connection.exec_query(query).empty?
end
end
......
......@@ -26,7 +26,7 @@ module Deployments
end
def update_environment(deployment)
ActiveRecord::Base.transaction do
ActiveRecord::Base.transaction do # rubocop: disable Database/MultipleDatabases
# Renew attributes at update
renew_external_url
renew_auto_stop_in
......
......@@ -36,7 +36,7 @@ module DesignManagement
with_temporary_branch do
copy_commits!
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
design_ids = copy_designs!
version_ids = copy_versions!
copy_actions!(design_ids, version_ids)
......
......@@ -6,7 +6,7 @@ module FeatureFlags
return error('Access Denied', 403) unless can_create?
return error('Version is invalid', :bad_request) unless valid_version?
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
feature_flag = project.operations_feature_flags.new(params)
if feature_flag.save
......
......@@ -11,7 +11,7 @@ module FeatureFlags
def destroy_feature_flag(feature_flag)
return error('Access Denied', 403) unless can_destroy?(feature_flag)
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
if feature_flag.destroy
save_audit_event(audit_event(feature_flag))
......
......@@ -12,7 +12,7 @@ module FeatureFlags
return error('Access Denied', 403) unless can_update?(feature_flag)
return error('Not Found', 404) unless valid_user_list_ids?(feature_flag, user_list_ids(params))
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
feature_flag.assign_attributes(params)
feature_flag.strategies.each do |strategy|
......
......@@ -14,7 +14,7 @@ module Issuable
# Using transaction because of a high resources footprint
# on rewriting notes (unfolding references)
#
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
@new_entity = create_new_entity
update_new_entity
......
......@@ -9,7 +9,7 @@ module Issuable
# We disable touch so that created system notes do not update
# the noteable's updated_at field
ActiveRecord::Base.no_touching do
ApplicationRecord.no_touching do
if is_update
if issuable.previous_changes.include?('title')
create_title_change_note(issuable.previous_changes['title'].first)
......
......@@ -22,7 +22,7 @@ module Issuable
SQL
loop do
result = ActiveRecord::Base.connection.execute(delete_query)
result = LabelLink.connection.execute(delete_query)
break if result.cmd_tuples == 0
end
......
......@@ -27,7 +27,7 @@ module Packages
dependencies_to_insert = names_and_version_patterns.reject { |k, _| k.in?(existing_names) }
end
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
inserted_ids = bulk_insert_package_dependencies(dependencies_to_insert)
bulk_insert_package_dependency_links(type, (existing_ids + inserted_ids))
end
......
......@@ -23,7 +23,7 @@ module Packages
files[:mod] = prepare_file(version, :mod, version.gomod)
files[:zip] = prepare_file(version, :zip, version.archive.string)
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
# create new package and files
package = create_package
files.each { |type, (file, digests)| create_file(package, type, file, digests) }
......
......@@ -9,7 +9,7 @@ module Packages
return error('Package already exists.', 403) if current_package_exists?
return error('File is too large.', 400) if file_size_exceeded?
ActiveRecord::Base.transaction { create_npm_package! }
ApplicationRecord.transaction { create_npm_package! }
end
private
......
......@@ -11,7 +11,7 @@ module Packages
return error('Package version already exists.', 403) if current_package_version_exists?
return error('File is too large.', 400) if file_size_exceeded?
ActiveRecord::Base.transaction { create_terraform_module_package! }
ApplicationRecord.transaction { create_terraform_module_package! }
end
private
......
......@@ -65,7 +65,7 @@ module Projects
def cleanup_diffs(response)
old_commit_shas = extract_old_commit_shas(response.entries)
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
cleanup_merge_request_diffs(old_commit_shas)
cleanup_note_diff_files(old_commit_shas)
end
......
......@@ -15,7 +15,7 @@ module Projects
ON CONFLICT (project_id, date) DO UPDATE SET fetch_count = #{table_name}.fetch_count + 1
SQL
ActiveRecord::Base.connection.execute(increment_fetch_count_sql)
ProjectDailyStatistic.connection.execute(increment_fetch_count_sql)
end
private
......
......@@ -18,7 +18,7 @@ module Releases
# when it does assign_attributes instead of actual saving
# this leads to the validation error being raised
# see https://gitlab.com/gitlab-org/gitlab/-/merge_requests/43385
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
if release.update(params)
execute_hooks(release, 'update')
success(tag: existing_tag, release: release, milestones_updated: milestones_updated?(previous_milestones))
......
......@@ -20,7 +20,7 @@ module Todos
SQL
loop do
result = ActiveRecord::Base.connection.execute(delete_query)
result = Todo.connection.execute(delete_query)
break if result.cmd_tuples == 0
......
......@@ -43,7 +43,7 @@ module Dora
)
VALUES (
#{environment.id},
#{ActiveRecord::Base.connection.quote(date.to_s)},
#{connection.quote(date.to_s)},
(#{deployment_frequency}),
(#{lead_time_for_changes})
)
......
......@@ -14,7 +14,7 @@ module Analytics
result = nil
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
deletion_services.each do |service|
response = service.execute
......
......@@ -17,7 +17,7 @@ module AppSec
def execute(name:, target_url:, **params)
return ServiceResponse.error(message: _('Insufficient permissions')) unless allowed?
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
@dast_site = ::DastSites::FindOrCreateService.new(project, current_user).execute!(url: target_url)
params.merge!(project: project, dast_site: dast_site, name: name).compact!
......
......@@ -21,7 +21,7 @@ module AppSec
return ServiceResponse.error(message: _('Cannot modify %{profile_name} referenced in security policy') % { profile_name: dast_site_profile.name }) if referenced_in_security_policy?
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
auditor = AppSec::Dast::SiteProfiles::Audit::UpdateService.new(project, current_user, {
dast_site_profile: dast_site_profile,
new_params: params.dup,
......
......@@ -11,7 +11,7 @@ module ApprovalRules
def execute
return unless merge_request.merged?
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
if merge_request.approval_rules.regular.exists?
merge_group_members_into_users
else
......
......@@ -9,7 +9,7 @@ module ApprovalRules
end
def execute
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
# Removes only MR rules associated with project rule
remove_associated_approval_rules_from_unmerged_merge_requests
......
......@@ -10,7 +10,7 @@ module EE
def execute(issuable, old_labels: [], old_milestone: nil, is_update: true)
super
ActiveRecord::Base.no_touching do
ApplicationRecord.no_touching do
handle_weight_change
handle_iteration_change
......
......@@ -18,7 +18,7 @@ module GroupSaml
return false unless current_user.verified_email?(saml_email)
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
if destroy_non_gma_identities && leave_non_gma_memberships && transfer_user
identity_linker = Gitlab::Auth::GroupSaml::IdentityLinker.new(current_user, oauth_data, session, group.saml_provider)
identity_linker.link
......
......@@ -11,7 +11,7 @@ module GroupSaml
end
def execute
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
new_user.managing_group = group if group.saml_provider&.enforced_group_managed_accounts?
if new_user.save
......
......@@ -18,7 +18,7 @@ module Iterations
from_iteration.issues.opened.each_batch(of: BATCH_SIZE) do |issues|
add_iteration_events, remove_iteration_events = iteration_events(issues)
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
issues.update_all(sprint_id: to_iteration.id, updated_at: rolled_over_at)
Gitlab::Database.bulk_insert(ResourceIterationEvent.table_name, remove_iteration_events) # rubocop:disable Gitlab/BulkInsert
Gitlab::Database.bulk_insert(ResourceIterationEvent.table_name, add_iteration_events) # rubocop:disable Gitlab/BulkInsert
......
......@@ -43,7 +43,7 @@ module Security
end
def update_deduplicated_findings
ActiveRecord::Base.transaction do
Security::Scan.transaction do
security_scan.findings.update_all(deduplicated: false)
security_scan.findings
......
......@@ -168,7 +168,7 @@ class TimeboxReportService
strong_memoize(:resource_events) do
union = Gitlab::SQL::Union.new([resource_timebox_events, state_events, weight_events]) # rubocop: disable Gitlab/Union
ActiveRecord::Base.connection.execute("(#{union.to_sql}) ORDER BY created_at LIMIT #{EVENT_COUNT_LIMIT + 1}")
ApplicationRecord.connection.execute("(#{union.to_sql}) ORDER BY created_at LIMIT #{EVENT_COUNT_LIMIT + 1}")
end
end
# rubocop: enable CodeReuse/ActiveRecord
......
......@@ -58,7 +58,7 @@ module VulnerabilityFeedback
def create_issue
# Wrap Feedback and Issue creation in the same transaction
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
issue = @params[:issue]
# Create a new issue if one does not exist
......@@ -126,7 +126,7 @@ module VulnerabilityFeedback
end
def dismiss_existing_vulnerability
ActiveRecord::Base.transaction do
ApplicationRecord.transaction do
if dismiss_vulnerability? && existing_vulnerability
Vulnerabilities::DismissService.new(current_user,
existing_vulnerability,
......
......@@ -94,7 +94,7 @@ module EE
yield
end
ensure # rubocop: disable Layout/RescueEnsureAlignment
ActiveRecord::Base.clear_active_connections!
ActiveRecord::Base.clear_active_connections! # rubocop: disable Database/MultipleDatabases
end
end
end
......
......@@ -5,7 +5,7 @@ module Gitlab
module CycleAnalytics
module StageQueryHelpers
def execute_query(query)
ActiveRecord::Base.connection.execute(query.to_sql)
ApplicationRecord.connection.execute(query.to_sql)
end
def zero_interval
......
......@@ -31,7 +31,7 @@ module Gitlab
expected_end_time = Time.now + duration_s
while Time.now < expected_end_time
ActiveRecord::Base.connection.execute("SELECT 1")
ApplicationRecord.connection.execute("SELECT 1")
end_interval_time = Time.now + [duration_s, interval_s].min
rand while Time.now < end_interval_time
......
......@@ -31,7 +31,7 @@ module Gitlab
end
def count(batch_size: nil, mode: :itself, start: nil, finish: nil)
raise 'BatchCount can not be run inside a transaction' if ActiveRecord::Base.connection.transaction_open?
raise 'BatchCount can not be run inside a transaction' if @relation.connection.transaction_open?
check_mode!(mode)
......
......@@ -54,7 +54,7 @@ module Gitlab
# Querying tuple stats only works on the primary. Due to load balancing, the
# easiest way to do this is to start a transaction.
ActiveRecord::Base.transaction do
ActiveRecord::Base.transaction do # rubocop: disable Database/MultipleDatabases
get_statistics(non_sti_table_names, check_statistics: check_statistics).each_with_object({}) do |row, data|
model = table_to_model[row.table_name]
data[model] = row.estimate
......
......@@ -61,7 +61,7 @@ module Gitlab
#{where_clause(model)}
SQL
rows = ActiveRecord::Base.connection.select_all(query)
rows = ActiveRecord::Base.connection.select_all(query) # rubocop: disable Database/MultipleDatabases
Integer(rows.first['count'])
end
......
......@@ -10,7 +10,7 @@ module Gitlab
# We _must not_ use quote_table_name as this will produce double
# quotes on PostgreSQL and for "has_table_privilege" we need single
# quotes.
connection = ActiveRecord::Base.connection
connection = ActiveRecord::Base.connection # rubocop: disable Database/MultipleDatabases
quoted_table = connection.quote(table)
begin
......
......@@ -57,7 +57,7 @@ module Gitlab
# @param finish final pkey range
# @return [Gitlab::Database::PostgresHll::Buckets] HyperLogLog data structure instance that can estimate number of unique elements
def execute(batch_size: nil, start: nil, finish: nil)
raise 'BatchCount can not be run inside a transaction' if ActiveRecord::Base.connection.transaction_open?
raise 'BatchCount can not be run inside a transaction' if ActiveRecord::Base.connection.transaction_open? # rubocop: disable Database/MultipleDatabases
batch_size ||= DEFAULT_BATCH_SIZE
start = actual_start(start)
......
......@@ -67,7 +67,7 @@ module Gitlab
def self.build_expression(search:, rules:)
return EXPRESSION_ON_INVALID_INPUT if search.blank? || rules.empty?
quoted_search = ActiveRecord::Base.connection.quote(search.to_s)
quoted_search = ApplicationRecord.connection.quote(search.to_s)
first_expression, *expressions = rules.map do |rule|
rule_to_arel(quoted_search, rule)
......@@ -110,7 +110,7 @@ module Gitlab
# CAST(multiplier AS numeric)
def self.multiplier_expression(rule)
quoted_multiplier = ActiveRecord::Base.connection.quote(rule.fetch(:multiplier, DEFAULT_MULTIPLIER).to_s)
quoted_multiplier = ApplicationRecord.connection.quote(rule.fetch(:multiplier, DEFAULT_MULTIPLIER).to_s)
Arel::Nodes::NamedFunction.new('CAST', [Arel.sql(quoted_multiplier).as('numeric')])
end
......
......@@ -11,7 +11,7 @@ module Gitlab
retry_attempts = 0
begin
ActiveRecord::Base.transaction do
ActiveRecord::Base.transaction do # rubocop: disable Database/MultipleDatabases
yield(subject)
end
rescue ActiveRecord::StaleObjectError
......
......@@ -36,7 +36,7 @@ module Gitlab
raise ArgumentError, "New key is too short! Must be 256 bits" if new_key.size < 64
write_csv do |csv|
ActiveRecord::Base.transaction do
User.transaction do
User.with_two_factor.in_batches do |relation| # rubocop: disable Cop/InBatches
rows = relation.pluck(:id, :encrypted_otp_secret, :encrypted_otp_secret_iv, :encrypted_otp_secret_salt)
rows.each do |row|
......@@ -54,7 +54,7 @@ module Gitlab
# rubocop: disable CodeReuse/ActiveRecord
def rollback!
ActiveRecord::Base.transaction do
User.transaction do
CSV.foreach(filename, headers: HEADERS, return_headers: false) do |row|
User.where(id: row['user_id']).update_all(encrypted_otp_secret: row['old_value'])
end
......
......@@ -119,18 +119,18 @@ module Gitlab
def self.with_custom_logger(logger)
original_colorize_logging = ActiveSupport::LogSubscriber.colorize_logging
original_activerecord_logger = ActiveRecord::Base.logger
original_activerecord_logger = ApplicationRecord.logger
original_actioncontroller_logger = ActionController::Base.logger
if logger
ActiveSupport::LogSubscriber.colorize_logging = false
ActiveRecord::Base.logger = logger
ApplicationRecord.logger = logger
ActionController::Base.logger = logger
end
yield.tap do
ActiveSupport::LogSubscriber.colorize_logging = original_colorize_logging
ActiveRecord::Base.logger = original_activerecord_logger
ApplicationRecord.logger = original_activerecord_logger
ActionController::Base.logger = original_actioncontroller_logger
end
end
......
......@@ -17,7 +17,7 @@ module Gitlab
end
def q(string)
ActiveRecord::Base.connection.quote(string)
ApplicationRecord.connection.quote(string)
end
end
end
......
......@@ -33,7 +33,7 @@ module Gitlab
# aren't incremented properly when joining relations together this way.
# By using "unprepared_statements" we remove the usage of placeholders
# (thus fixing this problem), at a slight performance cost.
fragments = ActiveRecord::Base.connection.unprepared_statement do
fragments = ApplicationRecord.connection.unprepared_statement do
relations.map do |rel|
remove_order ? rel.reorder(nil).to_sql : rel.to_sql
end.reject(&:blank?)
......
......@@ -8,9 +8,9 @@ RSpec.describe Gitlab::SQL::CTE do
relation = User.where(id: 1)
cte = described_class.new(:cte_name, relation)
sql = cte.to_arel.to_sql
name = ActiveRecord::Base.connection.quote_table_name(:cte_name)
name = ApplicationRecord.connection.quote_table_name(:cte_name)
sql1 = ActiveRecord::Base.connection.unprepared_statement do
sql1 = ApplicationRecord.connection.unprepared_statement do
relation.except(:order).to_sql
end
......@@ -30,8 +30,8 @@ RSpec.describe Gitlab::SQL::CTE do
cte = described_class.new(:cte_name, nil)
table = Arel::Table.new(:kittens)
source_name = ActiveRecord::Base.connection.quote_table_name(:cte_name)
alias_name = ActiveRecord::Base.connection.quote_table_name(:kittens)
source_name = ApplicationRecord.connection.quote_table_name(:cte_name)
alias_name = ApplicationRecord.connection.quote_table_name(:kittens)
expect(cte.alias_to(table).to_sql).to eq("#{source_name} AS #{alias_name}")
end
......
......@@ -46,10 +46,10 @@ RSpec.describe Gitlab::SQL::Glob do
end
def query(sql)
ActiveRecord::Base.connection.select_all(sql)
ApplicationRecord.connection.select_all(sql)
end
def quote(string)
ActiveRecord::Base.connection.quote(string)
ApplicationRecord.connection.quote(string)
end
end
......@@ -14,9 +14,9 @@ RSpec.describe Gitlab::SQL::RecursiveCTE do
cte << rel2
sql = cte.to_arel.to_sql
name = ActiveRecord::Base.connection.quote_table_name(:cte_name)
name = ApplicationRecord.connection.quote_table_name(:cte_name)
sql1, sql2 = ActiveRecord::Base.connection.unprepared_statement do
sql1, sql2 = ApplicationRecord.connection.unprepared_statement do
[rel1.except(:order).to_sql, rel2.except(:order).to_sql]
end
......@@ -28,8 +28,8 @@ RSpec.describe Gitlab::SQL::RecursiveCTE do
it 'returns an alias for the CTE' do
table = Arel::Table.new(:kittens)
source_name = ActiveRecord::Base.connection.quote_table_name(:cte_name)
alias_name = ActiveRecord::Base.connection.quote_table_name(:kittens)
source_name = ApplicationRecord.connection.quote_table_name(:cte_name)
alias_name = ApplicationRecord.connection.quote_table_name(:kittens)
expect(cte.alias_to(table).to_sql).to eq("#{source_name} AS #{alias_name}")
end
......@@ -37,8 +37,8 @@ RSpec.describe Gitlab::SQL::RecursiveCTE do
it 'replaces dots with an underscore' do
table = Arel::Table.new('gitlab.kittens')
source_name = ActiveRecord::Base.connection.quote_table_name(:cte_name)
alias_name = ActiveRecord::Base.connection.quote_table_name(:gitlab_kittens)
source_name = ApplicationRecord.connection.quote_table_name(:cte_name)
alias_name = ApplicationRecord.connection.quote_table_name(:gitlab_kittens)
expect(cte.alias_to(table).to_sql).to eq("#{source_name} AS #{alias_name}")
end
......
......@@ -41,10 +41,10 @@ RSpec.describe Gitlab::Utils::UsageData do
describe '#estimate_batch_distinct_count' do
let(:error_rate) { Gitlab::Database::PostgresHll::BatchDistinctCounter::ERROR_RATE } # HyperLogLog is a probabilistic algorithm, which provides estimated data, with given error margin
let(:relation) { double(:relation) }
let(:relation) { double(:relation, connection: double(:connection)) }
before do
allow(ActiveRecord::Base.connection).to receive(:transaction_open?).and_return(false)
allow(ActiveRecord::Base.connection).to receive(:transaction_open?).and_return(false) # rubocop: disable Database/MultipleDatabases
end
it 'delegates counting to counter class instance' do
......@@ -95,6 +95,10 @@ RSpec.describe Gitlab::Utils::UsageData do
let(:build_needs_estimated_cardinality) { 5.217656147118495 }
let(:ci_builds_estimated_cardinality) { 2.0809220082170614 }
before do
allow(ActiveRecord::Base.connection).to receive(:transaction_open?).and_return(false) # rubocop: disable Database/MultipleDatabases
end
context 'different counting parameters' do
before_all do
1.upto(3) { |i| create(:ci_build_need, name: i, build: build) }
......
......@@ -4,7 +4,7 @@ require 'spec_helper'
RSpec.describe CaseSensitivity do
describe '.iwhere' do
let_it_be(:connection) { ActiveRecord::Base.connection }
let_it_be(:connection) { Namespace.connection }
let_it_be(:model) do
Class.new(ActiveRecord::Base) do
include CaseSensitivity
......
......@@ -70,8 +70,8 @@ RSpec.describe Sortable do
it 'ascending' do
expect(relation).to receive(:reorder).once.and_call_original
table = Regexp.escape(ActiveRecord::Base.connection.quote_table_name(:namespaces))
column = Regexp.escape(ActiveRecord::Base.connection.quote_column_name(:name))
table = Regexp.escape(ApplicationRecord.connection.quote_table_name(:namespaces))
column = Regexp.escape(ApplicationRecord.connection.quote_column_name(:name))
sql = relation.order_by('name_asc').to_sql
......@@ -81,8 +81,8 @@ RSpec.describe Sortable do
it 'descending' do
expect(relation).to receive(:reorder).once.and_call_original
table = Regexp.escape(ActiveRecord::Base.connection.quote_table_name(:namespaces))
column = Regexp.escape(ActiveRecord::Base.connection.quote_column_name(:name))
table = Regexp.escape(ApplicationRecord.connection.quote_table_name(:namespaces))
column = Regexp.escape(ApplicationRecord.connection.quote_column_name(:name))
sql = relation.order_by('name_desc').to_sql
......
......@@ -8,7 +8,7 @@ RSpec.describe WhereComposite do
let(:model) do
tbl_name = test_table_name
Class.new(ActiveRecord::Base) do
Class.new(ApplicationRecord) do
self.table_name = tbl_name
include WhereComposite
......@@ -16,7 +16,7 @@ RSpec.describe WhereComposite do
end
def connection
ActiveRecord::Base.connection
ApplicationRecord.connection
end
before_all do
......
......@@ -258,7 +258,7 @@ RSpec.describe Experiment do
let(:variant) { :experimental }
it 'does not initiate a transaction' do
expect(ActiveRecord::Base.connection).not_to receive(:transaction)
expect(Experiment.connection).not_to receive(:transaction)
subject
end
......@@ -360,7 +360,7 @@ RSpec.describe Experiment do
let(:context) { {} }
it 'does not initiate a transaction' do
expect(ActiveRecord::Base.connection).not_to receive(:transaction)
expect(Experiment.connection).not_to receive(:transaction)
subject
end
......
......@@ -88,7 +88,7 @@ RSpec.describe InternalId do
context 'when executed outside of transaction' do
it 'increments counter with in_transaction: "false"' do
allow(ActiveRecord::Base.connection).to receive(:transaction_open?) { false }
allow(ActiveRecord::Base.connection).to receive(:transaction_open?) { false } # rubocop: disable Database/MultipleDatabases
expect(InternalId.internal_id_transactions_total).to receive(:increment)
.with(operation: :generate, usage: 'issues', in_transaction: 'false').and_call_original
......@@ -147,7 +147,7 @@ RSpec.describe InternalId do
let(:value) { 2 }
it 'increments counter with in_transaction: "false"' do
allow(ActiveRecord::Base.connection).to receive(:transaction_open?) { false }
allow(ActiveRecord::Base.connection).to receive(:transaction_open?) { false } # rubocop: disable Database/MultipleDatabases
expect(InternalId.internal_id_transactions_total).to receive(:increment)
.with(operation: :reset, usage: 'issues', in_transaction: 'false').and_call_original
......@@ -218,7 +218,7 @@ RSpec.describe InternalId do
context 'when executed outside of transaction' do
it 'increments counter with in_transaction: "false"' do
allow(ActiveRecord::Base.connection).to receive(:transaction_open?) { false }
allow(ActiveRecord::Base.connection).to receive(:transaction_open?) { false } # rubocop: disable Database/MultipleDatabases
expect(InternalId.internal_id_transactions_total).to receive(:increment)
.with(operation: :track_greatest, usage: 'issues', in_transaction: 'false').and_call_original
......
......@@ -11,7 +11,7 @@ RSpec.describe Analytics::UsageTrends::CounterJobWorker do
let(:job_args) { [users_measurement_identifier, user_1.id, user_2.id, recorded_at] }
before do
allow(ActiveRecord::Base.connection).to receive(:transaction_open?).and_return(false)
allow(::Analytics::UsageTrends::Measurement.connection).to receive(:transaction_open?).and_return(false)
end
include_examples 'an idempotent worker' do
......
......@@ -7,7 +7,7 @@ RSpec.describe Users::CreateStatisticsWorker do
subject { described_class.new.perform }
before do
allow(ActiveRecord::Base.connection).to receive(:transaction_open?).and_return(false)
allow(UsersStatistics.connection).to receive(:transaction_open?).and_return(false)
end
context 'when successful' do
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment