Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recommend using where with ranges #316

Merged
merged 2 commits into from Jun 15, 2022
Merged

Conversation

pirj
Copy link
Member

@pirj pirj commented May 2, 2022

Related rubocop-rails ticket.

Keep in mind (added this an a "okish" example):
foo: bar.. replaces 'foo >= ?', bar
foo: bar... also replaces 'foo >= ?', bar (not 'foo' > ?', bar)
foo: ..bar replaces 'foo <= ?', bar
foo: ...bar replaces 'foo < ?', bar
But there is nothing that would replace a set of conditions where one is inclusive, and the other is exclusive:
'foo >= ? AND foo < ?'

Real-world examples (gathered from real-world-rspec):

discourse/lib/guardian.rb
459:    UserExport.where(user_id: @user.id, created_at: (Time.zone.now.beginning_of_day..Time.zone.now.end_of_day)).count == 0

sharetribe/app/controllers/invitations_controller.rb
95:    Invitation.where(inviter_id: inviter_id, created_at: 1.day.ago..Time.now).count

sharetribe/app/models/community.rb
542:    community_memberships.where(:created_at => time.ago..Time.now).collect(&:person)

spree/core/app/models/spree/order.rb
186:    scope :created_between, ->(start_date, end_date) { where(created_at: start_date..end_date) }
187:    scope :completed_between, ->(start_date, end_date) { where(completed_at: start_date..end_date) }

spree/core/app/models/concerns/spree/product_scopes.rb
59:        where(Price.table_name => { amount: low..high })

open-source-billing/lib/reporting/reports/invoice_detail.rb
42:          invoices = Invoice.with_clients.where(invoice_date: @report_criteria.from_date.to_time.beginning_of_day..@report_criteria.to_date.to_time.end_of_day)
44:          invoices = Invoice.with_clients.joins(:payments).where("payments.payment_date",@report_criteria.from_date.to_time.beginning_of_day..@report_criteria.to_date.to_time.end_of_day)

open-source-billing/lib/reporting/reports/item_sales.rb
56:            where("invoice_line_items.created_at" => @report_criteria.from_date.to_time.beginning_of_day..@report_criteria.to_date.to_time.end_of_day,

open-source-billing/lib/reporting/reports/payments_collected.rb
55:            where("payments.payment_date" => @report_criteria.from_date.to_time.beginning_of_day.in_time_zone..@report_criteria.to_date.to_time.end_of_day.in_time_zone)
76:            where("payments.payment_date" => @report_criteria.from_date.to_time.beginning_of_day.in_time_zone..@report_criteria.to_date.to_time.end_of_day.in_time_zone)

open-source-billing/lib/reporting/dashboard.rb
84:      invoices = Invoice.group("month(invoice_date)").where(:invoice_date => start_date..end_date).where(currency_filter).where(company_filter).sum("invoice_total")
86:      #payments = Payment.group("month(payment_date)").where(:payment_date => start_date..end_date).sum("payment_amount")
87:      payments = Payment.where(:payment_date => start_date..end_date).where("payment_type is null or payment_type != ?",'credit').where(payment_currency_filter).where(company_filter).group("month(payment_date)").sum("payment_amount")
106:      Invoice.where(invoice_date: Date.today.beginning_of_year..Date.today).where(currency_filter).where(company_filter).each do |invoice|
116:      Invoice.where(invoice_date: Date.today.beginning_of_year..Date.today).where(currency_filter).where(company_filter).each do |invoice|
164:        Invoice.where(:invoice_date => chart_date..chart_date.at_end_of_month).where(currency_filter).where(company_filter).order('created_at DESC')
166:        Payment.where(:payment_date => chart_date..chart_date.at_end_of_month).where(payment_currency_filter).where(company_filter).where("payment_type is null or payment_type != ?",'credit').order('created_at DESC')

forem/app/services/badges/award_yearly_club.rb
21:          User.registered.where(created_at: i.year.ago - 2.days...i.year.ago),

forem/app/services/rate_limit_checker.rb
119:    user.follows.where(created_at: (now.beginning_of_day..now)).size

forem/app/services/analytics_service.rb
101:    @comment_data = @comment_data.where(created_at: @start_date..@end_date)
102:    @reaction_data = @reaction_data.where(created_at: @start_date..@end_date)
103:    @page_view_data = @page_view_data.where(created_at: @start_date..@end_date)

forem/app/workers/metrics/check_data_update_script_statuses.rb
7:      failed_scripts = DataUpdateScript.failed.where(created_at: 1.day.ago..Time.current)

canvas-lms/gems/acts_as_list/lib/active_record/acts/list.rb
175:                list_scope.where(self.class.position_column => position..(current_position - 1))
178:                list_scope.where(self.class.position_column => (current_position + 1)..position)

canvas-lms/db/migrate/20170327150955_make_enrolllment_state_lock_not_null.rb
27:      EnrollmentState.where(enrollment_id: min_id..max_id, lock_version: nil).update_all(lock_version: 0)

canvas-lms/db/migrate/20200420020319_make_submission_course_id_not_null.rb
10:        next unless GuardRail.activate(:secondary) { Submission.where(id: start_at..end_at, course_id: nil).exists? }

canvas-lms/db/migrate/20181016171038_fix_enrollment_accepted_notification_category.rb
50:                                             .where(id: min_id..max_id)

canvas-lms/lib/notification_message_creator.rb
375:        scope = scope.where(created_at: start_time..end_time)

canvas-lms/lib/missing_policy_applicator.rb
45:              .where(score: nil, grade: nil, cached_due_date: 1.day.ago(now)..now,

canvas-lms/lib/data_fixup/backfill_moderation_graders.rb
23:    assignments = Assignment.where(id: start_at..end_at).where(moderated_grading: true).where("grader_count = 0 or grader_count is null")

canvas-lms/lib/data_fixup/resend_plagiarism_events.rb
137:                .where(submitted_at: start_time...end_time)

canvas-lms/lib/data_fixup/populate_course_id_on_submissions.rb
6:      Submission.where(id: min_id..max_id, course_id: nil).joins(:assignment).update_all("course_id = assignments.context_id")

canvas-lms/lib/data_fixup/fix_points_possible_sums_in_quizzes.rb
24:        affected_quizzes.where(id: min_id..max_id).find_each do |quiz|

canvas-lms/lib/data_fixup/populate_root_account_id_on_user_observers.rb
6:      UserObservationLink.where(id: min_id..max_id, root_account_id: nil)

canvas-lms/lib/data_fixup/populate_context_on_wiki_pages.rb
24:      WikiPage.where(id: min_id..max_id, context_id: nil).joins(wiki: :course).update_all("context_type='Course', context_id=courses.id")
25:      WikiPage.where(id: min_id..max_id, context_id: nil).joins(wiki: :group).update_all("context_type='Group', context_id=groups.id")

canvas-lms/lib/data_fixup/split_up_user_preferences.rb
23:      User.where(id: min_id..max_id).where("id < ? AND preferences IS NOT NULL", Shard::IDS_PER_SHARD).each do |u|

canvas-lms/lib/data_fixup/populate_root_account_ids_on_learning_outcomes.rb
29:      global_outcomes = LearningOutcome.where(id: batch_min..batch_max, context_id: nil)
52:      normal_outcomes = LearningOutcome.where(id: batch_min..batch_max).where("root_account_ids IS NULL OR root_account_ids = ?", "{}")

canvas-lms/lib/data_fixup/run_due_date_cacher_for_quiz_lti.rb
31:              .where(id: batch_start..batch_end, workflow_state: :available)

canvas-lms/lib/data_fixup/update_grading_standards_to_full_range.rb
23:      GradingStandard.where(version: 2, id: min..max).each do |grading_standard|

canvas-lms/lib/data_fixup/populate_root_account_ids_on_communication_channels.rb
23:      scope = CommunicationChannel.where(id: batch_min..batch_max, root_account_ids: nil)

canvas-lms/lib/data_fixup/populate_identity_hash_on_context_external_tools.rb
23:    ContextExternalTool.where(id: start_at..end_at, identity_hash: nil).find_in_batches do |tools|

canvas-lms/lib/data_fixup/populate_root_account_ids_on_conversations_tables.rb
24:                             .where(conversation: batch_min..batch_max)
27:      messages = ConversationMessage.joins(:conversation).where(conversation: batch_min..batch_max)

canvas-lms/lib/data_fixup/delete_extra_placeholder_submissions.rb
31:    Assignment.where(context_type: "Course", context_id: min_id..max_id).pluck(:context_id, :id).each do |c_id, a_id|

canvas-lms/lib/data_fixup/add_post_policies_to_assignments.rb
26:    Submission.joins(:assignment).where(id: start_at..end_at)
47:              .where(context_id: start_at..end_at)
63:    Course.where(id: start_at..end_at)

canvas-lms/lib/data_fixup/fix_overwritten_file_module_items.rb
25:        replacement_ids += Attachment.where(id: min_id..max_id, file_state: "deleted", could_be_locked: true)

canvas-lms/lib/data_fixup/populate_submission_anonymous_ids.rb
24:      Course.where(id: start_at..end_at).find_each do |course|

canvas-lms/lib/data_fixup/populate_points_for_all_scores.rb
39:      courses = Course.published.where(id: min_id..max_id)

canvas-lms/lib/data_fixup/populate_conversation_participant_private_hash.rb
25:      scope.where(conversation_participants: { id: min..max })

canvas-lms/lib/data_fixup/populate_root_account_id_on_models.rb
475:        scope = table.where(primary_key_field => batch_min..batch_max, :root_account_id => nil)
490:          .where(table.primary_key => batch_min..batch_max)
523:          .where(id: batch_min..batch_max)

canvas-lms/lib/data_fixup/populate_last_comment_at_on_submissions.rb
6:      Submission.where(id: min_id..max_id)

canvas-lms/lib/data_fixup/backfill_posted_at_on_submissions.rb
24:      Submission.where(id: min_id..max_id, posted_at: nil).where.not(graded_at: nil).update_all("posted_at = graded_at")

canvas-lms/lib/data_fixup/clear_old_user_root_account_ids.rb
26:        User.where(id: start_id..end_id)

canvas-lms/lib/data_fixup/populate_root_account_id_on_asset_user_accesses.rb
23:    to_transform = AssetUserAccess.where(id: min..max, context_type: "User")

canvas-lms/lib/data_fixup/copy_built_in_roles_by_root_account.rb
46:          klass.where(id: min_id..max_id, role_id: old_role_ids).joins(:role)
57:        AccountNotificationRole.where(id: min_id..max_id, role_id: old_role_ids).joins(:role)
75:      Enrollment.where(id: min_id..max_id, role_id: old_role_ids).joins(:role)

canvas-lms/lib/data_fixup/populate_root_account_id_on_calendar_events.rb
40:        CalendarEvent.where(id: batch_min..batch_max, context_type: ["AppointmentGroup", "User"])

canvas-lms/lib/data_fixup/cleanup_cross_shard_developer_keys.rb
31:      ids = DeveloperKey.where(id: batch_min..batch_max)

canvas-lms/lib/data_fixup/populate_root_account_id_on_attachments.rb
50:                  .where(id: batch_min..batch_max, root_account_id: nil)
90:      .where(id: batch_min..batch_max, root_account_id: nil)

canvas-lms/lib/data_fixup/backfill_nulls.rb
56:        update_count = scope.where(klass.primary_key => start_id..end_id).update_all(updates)

canvas-lms/lib/data_fixup/reinsert_assessment_question_file_verifiers.rb
49:        Quizzes::Quiz.where(id: min_id..max_id)
57:        Quizzes::QuizQuestion.where(id: min_id..max_id)

canvas-lms/lib/data_fixup/move_master_import_results.rb
24:      MasterCourses::MasterMigration.where(id: min_id..max_id).where.not(import_results: nil).each do |mig|

canvas-lms/lib/data_fixup/validate_assignment_overrides.rb
23:      Assignment.where(id: min_id..max_id).each(&:validate_assignment_overrides)

canvas-lms/lib/data_fixup/invalidate_built_in_role_caches.rb
24:      User.clear_cache_keys(klass.where(id: min_id..max_id).distinct.pluck(:user_id), cache_type)

canvas-lms/lib/data_fixup/clear_old_communication_channel_root_account_ids.rb
26:        CommunicationChannel.where(id: start_id..end_id)

canvas-lms/lib/data_fixup/populate_root_account_ids_on_users.rb
33:      User.where(id: batch_min..batch_max).update_all("root_account_ids=(#{uniquify})")

canvas-lms/lib/data_fixup/populate_scores_and_metadata_for_assignment_groups_and_teacher_view.rb
39:    courses = Course.published.where(id: min_id..max_id)

canvas-lms/lib/data_fixup/populate_context_on_outcome_proficiencies.rb
24:      OutcomeProficiency.where(id: min_id..max_id, context_id: nil).update_all("context_type='Account', context_id=account_id")

canvas-lms/lib/data_fixup/run_update_course_score_statistic.rb
25:      courses_ids_to_recompute = Course.active.where(id: batch_start..batch_end).pluck(:id)

canvas-lms/lib/data_fixup/populate_field_on_model_from_association.rb
38:      scope = table.where(primary_key_field => batch_min..batch_max, column => old_value)

canvas-lms/lib/data_fixup/fix_reinserted_verifier_question_yaml.rb
38:        Quizzes::Quiz.where(id: min_id..max_id)
46:        Quizzes::QuizQuestion.where(id: min_id..max_id)

canvas-lms/lib/data_fixup/delete_invalid_communication_channels.rb
25:      records = scope.where(id: min_id..max_id).pluck(:id, :user_id, :path).reject do |_id, _user_id, path|

mastodon/db/migrate/20181207011115_downcase_custom_emoji_domains.rb
8:      CustomEmoji.where(id: row['ids'].split(',')[0...-1]).destroy_all

canvas-lms/spec/lib/grade_calculator_spec.rb
1439:          Submission.where(user: @student, assignment: @assignments[0..2]).update_all(score: nil)
1451:          Assignment.where(id: @assignments[0..2].map(&:id)).update_all(omit_from_final_grade: true)

canvas-lms/spec/models/active_record_base_spec.rb
679:      expect(User.where(updated_at: 5.minutes.ago..).in_batches.update_all(updated_at: 10.minutes.ago)).to eq 1
684:      expect(User.where(updated_at: 5.minutes.ago..).in_batches.update_all(updated_at: Time.now.utc)).to eq 1
689:      expect(User.where(updated_at: 5.minutes.ago..5.minutes.from_now).in_batches.update_all(updated_at: 10.minutes.ago)).to eq 1
694:      expect(User.where(updated_at: 5.minutes.ago..5.minutes.from_now).in_batches.update_all(updated_at: Time.now.utc)).to eq 1
700:      expect(User.where(updated_at: 5.minutes.ago...5.minutes.from_now).in_batches.update_all(updated_at: 10.minutes.ago)).to eq 1

canvas-lms/config/initializers/active_record.rb
688:      where(primary_key => min_id..max_id).touch_all

canvas-lms/app/models/group_category.rb
239:    groups.where(deleted_at: [deleted_at - 10.minutes..deleted_at]).update_all(workflow_state: "available", deleted_at: nil)

canvas-lms/app/models/quizzes/quiz.rb
1215:      .where(user_due_date: start..ending)

canvas-lms/app/models/course.rb
812:  scope :recently_started, -> { where(start_at: 1.month.ago..Time.zone.now).order("start_at DESC").limit(10) }
813:  scope :recently_ended, -> { where(conclude_at: 1.month.ago..Time.zone.now).order("start_at DESC").limit(10) }

canvas-lms/app/models/enrollment_state.rb
218:      process_states_for(enrollments_needing_calculation(enrollment_scope).where(id: min_id..max_id))
291:      if invalidate_states(scope.where(id: min_id..max_id)) > 0
317:      scope = enrollments_for_account_ids(account_ids).where(id: min_id..max_id)

canvas-lms/app/models/grading_period_group.rb
149:      scope.where(id: min_id..max_id).update_all(updates.reverse_merge({ updated_at: Time.zone.now }))

canvas-lms/app/models/wiki_page.rb
78:  scope :todo_date_between, ->(starting, ending) { where(todo_date: starting...ending) }

canvas-lms/app/models/assignment.rb
2894:  scope :due_between, ->(start, ending) { where(due_at: start..ending) }
2900:                                           .where(due_at_overridden: true, due_at: start..ending)
2902:    scope1 = where(due_at: start..ending)
2909:        scope2.merge(unscoped.where.not(due_at: start..ending).or(unscoped.where(due_at: nil))),
2916:    with_user_due_date(user).where(user_due_date: start..ending)
3782:                 .where(close_date: look_back.minutes.ago(now)..now)

canvas-lms/app/models/calendar_event.rb
203:  scope :between, ->(start, ending) { where(start_at: start..ending) }

canvas-lms/app/models/grading_period.rb
214:      scores.where(id: min_id..max_id).update_all(workflow_state: :deleted)

canvas-lms/app/models/enrollment_term.rb
216:    courses_to_recompute.where(id: min_id..max_id).find_each do |course|

canvas-lms/app/models/account_notification.rb
367:          course_ids = Course.active.where(id: min_id..max_id, account_id: all_account_ids).pluck(:id)
381:          scope = AccountUser.where(id: min_id..max_id).active.where(account_id: all_account_ids)

canvas-lms/app/controllers/planner_controller.rb
287:                    shard.activate { PlannerNote.active.where(user: user, todo_date: @start_date..@end_date, course_id: course_ids) },
439:      scopes << WikiPage.where(todo_date: @start_date..@end_date, context: contexts).active
442:      scopes << WikiPage.where(todo_date: @start_date..@end_date, context: contexts).not_deleted
451:      scopes << DiscussionTopic.where(todo_date: @start_date..@end_date, context: contexts).published
454:      scopes << DiscussionTopic.where(todo_date: @start_date..@end_date, context: contexts).active

chatwoot/app/jobs/conversations/reopen_snoozed_conversations_job.rb
5:    Conversation.where(status: :snoozed).where(snoozed_until: 3.days.ago..Time.current).all.each(&:open!)

chatwoot/app/jobs/trigger_scheduled_items_job.rb
6:    Campaign.where(campaign_type: :one_off, campaign_status: :active).where(scheduled_at: 3.days.ago..Time.current).all.each do |campaign|

solidus/core/app/models/spree/order.rb
151:    scope :created_between, ->(start_date, end_date) { where(created_at: start_date..end_date) }
152:    scope :completed_between, ->(start_date, end_date) { where(completed_at: start_date..end_date) }

solidus/core/app/models/spree/product/scopes.rb
42:            joins(master: :prices).where(Price.table_name => { amount: low..high })

gitlabhq/lib/gitlab/background_migration/populate_latest_pipeline_ids.rb
12:        scope :in_range, -> (start_id, end_id) { where(id: start_id..end_id) }

gitlabhq/lib/gitlab/background_migration/encrypt_static_object_token.rb
21:          .where(id: start_id..end_id)
29:                          .where(id: first..last)

gitlabhq/lib/gitlab/background_migration/populate_topics_non_private_projects_count.rb
17:        Topic.where(id: start_id..stop_id).each_batch(of: SUB_BATCH_SIZE) do |batch|

gitlabhq/lib/gitlab/background_migration/backfill_ci_namespace_mirrors.rb
22:        batch_query = Namespace.base_query.where(id: start_id..end_id)
25:          ranged_query = Namespace.unscoped.base_query.where(id: first..last)

gitlabhq/lib/gitlab/background_migration/migrate_merge_request_diff_commit_users.rb
60:            .where(merge_request_diff_id: start_id...stop_id)

gitlabhq/lib/gitlab/background_migration/delete_orphaned_deployments.rb
11:          .where(id: start_id..end_id)

gitlabhq/lib/gitlab/background_migration/backfill_member_namespace_for_group_members.rb
31:          .where(source_key_column => start_id..stop_id)

gitlabhq/lib/gitlab/background_migration/update_jira_tracker_data_deployment_type_based_on_url.rb
25:      .where(id: start_id..end_id)

gitlabhq/lib/gitlab/background_migration/backfill_namespace_traversal_ids_children.rb
20:        batch_query = Namespace.base_query.where(id: start_id..end_id)
23:          ranged_query = Namespace.unscoped.base_query.where(id: first..last)

gitlabhq/lib/gitlab/background_migration/backfill_draft_status_on_merge_requests.rb
23:        eligible_mrs = MergeRequest.eligible.where(id: start_id..end_id).pluck(:id)

gitlabhq/lib/gitlab/background_migration/backfill_namespace_id_for_namespace_route.rb
32:          .where(source_key_column => start_id..stop_id)

gitlabhq/lib/gitlab/background_migration/cleanup_orphaned_lfs_objects_projects.rb
62:        batch = LfsObjectsProject.where(id: start_id..end_id)
71:              .where(id: (first..last), table_name => { id: nil })

gitlabhq/lib/gitlab/background_migration/remove_duplicate_vulnerabilities_findings.rb
20:    batch = VulnerabilitiesFinding.where(id: start_id..end_id)

gitlabhq/lib/gitlab/background_migration/backfill_integrations_type_new.rb
13:          .where(batch_column => start_id..stop_id)

gitlabhq/lib/gitlab/background_migration/project_namespaces/backfill_project_namespaces.rb
131:          relation = IsolatedModels::Project.where(projects[:id].between(start_id..end_id))

gitlabhq/lib/gitlab/background_migration/backfill_artifact_expiry_date.rb
23:        scope :between, -> (start_id, end_id) { where(id: start_id..end_id) }

gitlabhq/lib/gitlab/background_migration/backfill_snippet_repositories.rb
11:        snippets = snippet_relation.where(id: start_id..stop_id)

gitlabhq/lib/gitlab/background_migration/add_primary_email_to_emails_if_user_confirmed.rb
30:        User.confirmed.where(id: start_id..end_id).select(:id, :email, :confirmed_at).each_batch(of: INNER_BATCH_SIZE) do |users|

gitlabhq/lib/gitlab/background_migration/remove_all_trace_expiration_dates.rb
39:        scope :between, -> (start_id, end_id) { where(id: start_id..end_id) }

gitlabhq/lib/gitlab/background_migration/backfill_project_repositories.rb
207:          .where(id: start_id..stop_id)

gitlabhq/lib/gitlab/background_migration/populate_vulnerability_reads.rb
12:        vulnerability_model.where(id: start_id..end_id).each_batch(of: sub_batch_size) do |sub_batch|

gitlabhq/lib/gitlab/background_migration/backfill_namespace_traversal_ids_roots.rb
21:          .where(id: start_id..end_id)
31:                   .where(id: first..last)

gitlabhq/lib/gitlab/background_migration/populate_topics_total_projects_count_cache.rb
17:        Topic.where(id: start_id..stop_id).each_batch(of: SUB_BATCH_SIZE) do |batch|

gitlabhq/lib/gitlab/background_migration/drop_invalid_vulnerabilities.rb
20:      .where(id: start_id..end_id)

gitlabhq/lib/gitlab/background_migration/extract_project_topics_into_separate_table.rb
35:        Tagging.includes(:tag).where(taggable_type: 'Project', id: start_id..stop_id).each do |tagging|

gitlabhq/lib/gitlab/background_migration/migrate_null_private_profile_to_false.rb
13:        User.where(private_profile: nil, id: start_id..stop_id).update_all(private_profile: false)

gitlabhq/lib/gitlab/background_migration/fix_vulnerability_occurrences_with_hashes_as_raw_metadata.rb
32:        Finding.by_api_report_types.where(id: start_id..end_id).each do |finding|

gitlabhq/lib/gitlab/background_migration/drop_invalid_security_findings.rb
18:          .where(id: start_id..end_id)
27:            .where(id: first..last)

gitlabhq/lib/gitlab/background_migration/disable_expiration_policies_linked_to_no_container_images.rb
19:        ContainerExpirationPolicy.where(enabled: true, project_id: from_id..to_id).each_batch(of: BATCH_SIZE) do |batch|

gitlabhq/lib/gitlab/background_migration/reset_duplicate_ci_runners_token_encrypted_values_on_projects.rb
20:          .where(id: start_id..end_id)

gitlabhq/lib/gitlab/background_migration/fix_first_mentioned_in_commit_at.rb
70:        TmpIssueMetrics.from_2020.where(issue_id: start_id..end_id)

gitlabhq/lib/gitlab/background_migration/update_timelogs_null_spent_at.rb
13:            .where(spent_at: nil, id: start_id..stop_id)

gitlabhq/lib/gitlab/background_migration/migrate_personal_namespace_project_maintainer_to_owner.rb
34:          .where(source_key_column => start_id..stop_id)

gitlabhq/lib/gitlab/background_migration/backfill_user_namespace.rb
33:          .where(source_key_column => start_id..stop_id)

gitlabhq/lib/gitlab/background_migration/remove_vulnerability_finding_links.rb
14:          .where(id: start_id..stop_id)

gitlabhq/lib/gitlab/background_migration/reset_duplicate_ci_runners_token_values_on_projects.rb
20:          .where(id: start_id..end_id)

gitlabhq/lib/gitlab/background_migration/nullify_orphan_runner_id_on_ci_builds.rb
36:          .where(source_key_column => start_id..stop_id)

gitlabhq/lib/gitlab/background_migration/backfill_jira_tracker_deployment_type2.rb
39:          .where(id: start_id..stop_id, deployment_type: 0)

gitlabhq/lib/gitlab/background_migration/backfill_ci_queuing_tables.rb
127:        scope = BackfillCiQueuingTables::Ci::Build.pending.where(id: start_id..end_id)

gitlabhq/lib/gitlab/background_migration/backfill_issue_search_data.rb
12:        define_batchable_model(batch_table, connection: ActiveRecord::Base.connection).where(batch_column => start_id..stop_id).each_batch(of: sub_batch_size) do |sub_batch|

gitlabhq/lib/gitlab/background_migration/backfill_ci_project_mirrors.rb
21:        batch_query = Project.base_query.where(id: start_id..end_id)
24:          ranged_query = Project.unscoped.base_query.where(id: first..last)

gitlabhq/lib/gitlab/background_migration/migrate_u2f_webauthn.rb
16:        old_registrations = U2fRegistration.where(id: start_id..end_id)

gitlabhq/lib/gitlab/background_migration/migrate_project_taggings_context_from_tags_to_topics.rb
15:        Tagging.where(taggable_type: 'Project', context: 'tags', id: start_id..stop_id).each_batch(of: 500) do |relation|

gitlabhq/lib/gitlab/background_migration/copy_column_using_background_migration_job.rb
56:        define_batchable_model(source_table, connection: connection).where(source_key_column => start_id..stop_id)

gitlabhq/lib/gitlab/background_migration/legacy_uploads_migrator.rb
17:        Upload.where(id: start_id..end_id, uploader: 'AttachmentUploader', model_type: 'Note').find_each do |upload|

gitlabhq/lib/gitlab/background_migration/recalculate_vulnerabilities_occurrences_uuid.rb
92:      .where(id: start_id..end_id)

gitlabhq/lib/gitlab/contributions_calendar.rb
62:        .where(created_at: date_in_time_zone.beginning_of_day..date_in_time_zone.end_of_day)

gitlabhq/lib/gitlab/database/postgres_hll/batch_distinct_counter.rb
119:            .where(@relation.primary_key => (start...finish))

gitlabhq/lib/gitlab/database/partitioning_migration_helpers/backfill_partitioned_table.rb
53:            .where(source_key_column => start_id..stop_id)

gitlabhq/spec/services/bulk_update_integration_service_spec.rb
14:    Integration.inherited_descendants_from_self_or_ancestors_from(subgroup_integration).where(id: group_integration.id..integration.id)

gitlabhq/spec/services/bulk_create_integration_service_spec.rb
87:      let(:batch) { Project.where(id: Project.minimum(:id)..Project.maximum(:id)).without_integration(integration).in_namespace(integration.group.self_and_descendants) }

gitlabhq/spec/lib/gitlab/background_migration/backfill_integrations_type_new_spec.rb
42:    expect(integrations.where(id: 2..10).pluck(:type, :type_new)).to contain_exactly(
54:    expect(integrations.where.not(id: 2..10)).to all(have_attributes(type_new: nil))

gitlabhq/spec/lib/gitlab/usage/metrics/name_suggestion_spec.rb
56:        let(:relation) { ::Clusters::Cluster.aws_installed.enabled.where(created_at: 30.days.ago..2.days.ago ) }

gitlabhq/spec/lib/gitlab/database/postgres_hll/batch_distinct_counter_spec.rb
42:        expect(model).to receive(:where).with("id" => min_id..batch_end_id).and_call_original

gitlabhq/spec/lib/gitlab/database/background_migration/batched_job_spec.rb
360:        Event.where(id: 6..12).delete_all

gitlabhq/spec/lib/gitlab/database/batch_count_spec.rb
61:      allow(relation).to receive(:where).with("id" => 0..calculate_batch_size(batch_size)).and_return(too_big_batch_relation_mock)
64:      expect(relation).to receive(:where).with("id" => 0..calculate_batch_size(batch_size / 2)).and_return(double(send: 1))
149:      expect(relation).to receive(:where).with("id" => min_id..batch_end_id).and_return(double(send: 1))
278:      expect(relation).to receive(:where).with("id" => min_id..batch_end_id).and_return(double(send: 1))
364:      expect(relation).to receive(:where).with("id" => min_id..batch_end_id).and_return(double(send: 1))

gitlabhq/spec/workers/authorized_project_update/user_refresh_over_user_range_worker_spec.rb
20:        User.where(id: start_user_id..end_user_id).each do |user|

gitlabhq/app/workers/propagate_integration_project_worker.rb
18:    batch = Project.where(id: min_id..max_id).without_integration(integration)

gitlabhq/app/workers/propagate_integration_inherit_descendant_worker.rb
18:    batch = Integration.inherited_descendants_from_self_or_ancestors_from(integration).where(id: min_id..max_id)

gitlabhq/app/workers/propagate_integration_group_worker.rb
19:              Group.where(id: min_id..max_id).without_integration(integration)
21:              integration.group.descendants.where(id: min_id..max_id).without_integration(integration)

gitlabhq/app/workers/propagate_integration_inherit_worker.rb
18:    batch = Integration.where(id: min_id..max_id).by_type(integration.type).inherit_from_id(integration.id)

gitlabhq/app/workers/authorized_project_update/user_refresh_over_user_range_worker.rb
27:      User.where(id: start_user_id..end_user_id).find_each do |user| # rubocop: disable CodeReuse/ActiveRecord

gitlabhq/app/models/release.rb
44:  scope :released_within_2hrs, -> { where(released_at: Time.zone.now - 1.hour..Time.zone.now + 1.hour) }

gitlabhq/app/models/member.rb
152:    where(created_at: now.beginning_of_day..now.end_of_day)
154:  scope :last_ten_days_excluding_today, -> (today = Date.current) { where(created_at: (today - 10).beginning_of_day..(today - 1).end_of_day) }

gitlabhq/app/models/ci/job_artifact.rb
193:    scope :created_in_time_range, ->(from: nil, to: nil) { where(created_at: from..to) }

gitlabhq/app/models/ci/daily_build_group_report_result.rb
18:    scope :by_dates, -> (start_date, end_date) { where(date: start_date..end_date) }

camaleon-cms/app/apps/plugins/attack/attack_helper.rb
67:      r = q.where(created_at: config[:post][:sec].to_i.seconds.ago..Time.now)
77:      r = q.where(created_at: config[:get][:sec].to_i.seconds.ago..Time.now)

Specifically open ranges:

forem/app/services/badges/award_beloved_comment.rb
16:      Comment.includes(:user).where(public_reactions_count: comment_count..).find_each do |comment|

forem/app/services/users/suggest_recent.rb
28:        .where(score: article_score_average.., published_at: num_weeks.weeks.ago..)
51:      relation_as_array(user_relation.where(comments_count: num_comments + 1..), limit: limit)
61:        user_relation.where(articles_count: 1..).average(:articles_count) || User.average(:articles_count)
67:        user_relation.where(comments_count: 1..).average(:comments_count) || User.average(:comments_count)
73:        Article.where(score: 0..).average(:score) || Article.average(:score)

forem/app/services/users/suggest_for_sidebar.rb
34:        .where(public_reactions_count: minimum_reaction_count..)
35:        .where(published_at: 4.months.ago..)

forem/app/services/search/user.rb
45:    # preload the user ids of all suspended users and use those with `.where.not(id: ...)`

forem/app/services/feeds/import.rb
80:      users_scope.where(feed_fetched_at: nil).or(users_scope.where(feed_fetched_at: ..earlier_than))

forem/app/services/articles/feeds/basic.rb
15:          .where(score: 0..)

forem/app/controllers/stories/tagged_articles_controller.rb
58:      tag.articles.published.where(score: Settings::UserExperience.tag_feed_minimum_score..).count
72:        stories.where(score: -20..).order(published_at: :desc)

forem/app/workers/follows/update_points_worker.rb
30:      last_100_reactable_ids = user.reactions.where(reactable_type: "Article", points: 0..)
32:      last_100_long_page_view_article_ids = user.page_views.where(time_tracked_in_seconds: 45..)

forem/app/workers/articles/update_organic_page_views_worker.rb
34:      relation.where(created_at: timeframe..).sum(:counts_for_number_of_views)

forem/app/services/rate_limit_checker.rb
106:    user.comments.where(created_at: 5.minutes.ago...).size >

forem/app/models/github_repo.rb
30:    ids = where(updated_at: ...26.hours.ago).ids.map { |id| [id] }

forem/app/models/article.rb
98:             where(comments: { score: 11.. }, ancestry: nil, hidden_by_commentable_user: false, deleted: false)
311:    stories.where(published_at: 12.hours.ago.., comments_count: ..5, score: -3..).presence || stories
361:      where(score: Settings::UserExperience.home_feed_minimum_score..),

forem/app/queries/articles/active_threads_query.rb
37:                   relation = relation.where(score: MINIMUM_SCORE..).presence || relation
40:                   relation = relation.where(published_at: time_ago.., score: MINIMUM_SCORE..).presence || relation
43:                   relation = relation.where(published_at: 3.days.ago.., score: MINIMUM_SCORE..).presence || relation

canvas-lms/app/models/communication_channel.rb
390:  scope :bouncing, -> { where(bounce_count: RETIRE_THRESHOLD..) }

@pirj pirj self-assigned this May 2, 2022
@pirj pirj requested a review from a team May 2, 2022 15:38
@pirj pirj force-pushed the recommend-using-ranges-for-where branch from 337bb2b to 5bd06b2 Compare May 2, 2022 15:44
README.adoc Show resolved Hide resolved
README.adoc Outdated
# okish - there is no range syntax that would denote inclusion on one end and
# exclusion on another.
Customer.where("purchases_count > :min AND purchases_count <= :max", min: 0, max: 5)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note to self: extra blank line

@pirj pirj force-pushed the recommend-using-ranges-for-where branch from b2442c3 to bd73b49 Compare May 3, 2022 15:22
Customer.where("purchases_count > :min AND purchases_count <= :max", min: 0, max: 5)
----

NOTE: Rails 6.0 or later is required for endless range Ruby 2.6 syntax, and Rails 6.0.3 for beginless range Ruby 2.7 syntax.
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'created_at >= :start_date AND created_at <= :end_date',
start_date: params[:start_date], end_date: params[:end_date]
'orders_count >= :min_orders_count AND country_code = :country_code',
min_orders_count: params[:min_orders_count], country_code: params[:country_code]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this change is not related to the addition of Where with Ranges new rule, it could be opened as a separate PR.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On a second thought, I've made this change to make Named Placeholder example not to go against the new Where with Ranges.
Without this, it would have to be written as:

Client.where(created_at: params[:start_date]..params[:end_date])

which defeats the purpose of being a good example for Named Placeholder.

@pirj pirj force-pushed the recommend-using-ranges-for-where branch from bd73b49 to 0026eee Compare May 23, 2022 18:41
@bbatsov bbatsov merged commit 43a9832 into master Jun 15, 2022
@bbatsov
Copy link
Collaborator

bbatsov commented Jun 15, 2022

Looks good. Thanks!

@bbatsov bbatsov deleted the recommend-using-ranges-for-where branch June 15, 2022 08:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants