laravel-nestedset 0.1.0

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.
///
/// ```ignore
/// use laravel_nestedset::NestedSetBlueprint;
///
/// tx.schema()
///     .create("categories", |table| {
///         table.id();
///         table.string("name");
///         table.nested_set();
///         table.timestamps();
///     })
///     .await?;
/// ```
pub trait NestedSetBlueprint {
    /// Adds `lft` and `rgt` (big integers, default `0`), a nullable `parent_id`, and an index
    /// on `lft`, `rgt`, and `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]);

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

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

    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 mut columns: Vec<String> = scope.iter().map(|column| (*column).to_owned()).collect();
        columns.extend(["lft", "rgt", "parent_id"].map(str::to_owned));
        self.index(columns);
        self.index("parent_id");
    }

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