Skip to content

virtual depth_cache #662

@mitsuru

Description

@mitsuru

I noticed a problem updating the depth_cache in the big tree.
Since it is a sequential update, the updates are issued in a large number of UPDATE statements.
I have solved this problem with generated columns. (It depends on MySQL, but Postgres may be able to handle it as well as Rails7)
rails/rails#41856

    change_table :table do |t|
      t.virtual :ancestry_depth, type: :integer, as: "LENGTH(ancestry) - LENGTH(REPLACE(ancestry, '/', '')) - 1", stored: true
      t.index :ancestry_depth
    end

This example depends on ancestry_format: :materialized_path2.

This solution has the problem that existing scopes cannot be used.

scope :before_depth, lambda { |depth| where("#{depth_cache_column} < ?", depth) }
scope :to_depth, lambda { |depth| where("#{depth_cache_column} <= ?", depth) }
scope :at_depth, lambda { |depth| where("#{depth_cache_column} = ?", depth) }
scope :from_depth, lambda { |depth| where("#{depth_cache_column} >= ?", depth) }
scope :after_depth, lambda { |depth| where("#{depth_cache_column} > ?", depth) }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions