laravel-nestedset 0.2.2

Nested set trees for Laravel Rust models: fast subtree and ancestor queries, safe under concurrent writes.
Documentation
//! The migration helpers: `table.nested_set()`.

use laravel::db::schema::Blueprint;

/// Adds the nested set columns and their index to a table.
///
/// ```no_run
/// use laravel_nestedset::NestedSetBlueprint;
///
/// # async fn example() -> laravel::Result<()> {
/// # let tx = laravel::db::default_connection()?;
/// tx.schema()
///     .create("categories", |table| {
///         table.id();
///         table.string("name");
///         table.nested_set();
///         table.timestamps();
///     })
///     .await?;
/// # Ok(())
/// # }
/// ```
pub trait NestedSetBlueprint {
    /// Adds `lft` and `rgt` (big integers, default `0`), a nullable `parent_id`, and the indexes
    /// the queries and writes use: on `lft, rgt, parent_id`, on `rgt`, and on `parent_id`.
    fn nested_set(&mut self);

    /// [`nested_set`](Self::nested_set) for a table with several trees: the index starts with
    /// the scope columns, such as `["menu_id"]`, which the table must already define.
    fn nested_set_scoped(&mut self, scope: &[&str]);

    /// [`nested_set`](Self::nested_set) for a model with a UUID key: `parent_id` is a nullable
    /// UUID.
    fn nested_set_uuid(&mut self);

    /// Drops what [`nested_set`](Self::nested_set) added.
    fn drop_nested_set(&mut self);

    /// Adds the optional `depth` column (big integer, default `0`) and an index on it. Return it
    /// from [`NestedSet::depth_column`](crate::NestedSet::depth_column), then run
    /// [`fix_tree`](crate::NestedSet::fix_tree) once to fill it on a table that has rows.
    fn nested_set_depth(&mut self);
}

impl NestedSetBlueprint for Blueprint {
    fn nested_set(&mut self) {
        self.nested_set_scoped(&[]);
    }

    fn nested_set_uuid(&mut self) {
        self.big_integer("lft").default(0);
        self.big_integer("rgt").default(0);
        self.uuid("parent_id").nullable();
        self.index(["lft", "rgt", "parent_id"]);
        self.index("parent_id");
    }

    fn nested_set_scoped(&mut self, scope: &[&str]) {
        self.big_integer("lft").default(0);
        self.big_integer("rgt").default(0);
        self.big_integer("parent_id").nullable();
        let scoped = |columns: &[&str]| -> Vec<String> {
            scope.iter().chain(columns).map(|column| (*column).to_owned()).collect()
        };
        self.index(scoped(&["lft", "rgt", "parent_id"]));
        self.index("parent_id");
    }

    fn nested_set_depth(&mut self) {
        self.big_integer("depth").default(0);
        self.index("depth");
    }

    fn drop_nested_set(&mut self) {
        self.drop_column(["lft", "rgt", "parent_id"]);
    }
}