Skip to main content

laravel_nestedset/
schema.rs

1//! The migration helpers: `table.nested_set()`.
2
3use laravel::db::schema::Blueprint;
4
5/// Adds the nested set columns and their index to a table.
6///
7/// ```no_run
8/// use laravel_nestedset::NestedSetBlueprint;
9///
10/// # async fn example() -> laravel::Result<()> {
11/// # let tx = laravel::db::default_connection()?;
12/// tx.schema()
13///     .create("categories", |table| {
14///         table.id();
15///         table.string("name");
16///         table.nested_set();
17///         table.timestamps();
18///     })
19///     .await?;
20/// # Ok(())
21/// # }
22/// ```
23pub trait NestedSetBlueprint {
24    /// Adds `lft` and `rgt` (big integers, default `0`), a nullable `parent_id`, and the indexes
25    /// the queries and writes use: on `lft, rgt, parent_id`, on `rgt`, and on `parent_id`.
26    fn nested_set(&mut self);
27
28    /// [`nested_set`](Self::nested_set) for a table with several trees: the index starts with
29    /// the scope columns, such as `["menu_id"]`, which the table must already define.
30    fn nested_set_scoped(&mut self, scope: &[&str]);
31
32    /// [`nested_set`](Self::nested_set) for a model with a UUID key: `parent_id` is a nullable
33    /// UUID.
34    fn nested_set_uuid(&mut self);
35
36    /// Drops what [`nested_set`](Self::nested_set) added.
37    fn drop_nested_set(&mut self);
38
39    /// Adds the optional `depth` column (big integer, default `0`) and an index on it. Return it
40    /// from [`NestedSet::depth_column`](crate::NestedSet::depth_column), then run
41    /// [`fix_tree`](crate::NestedSet::fix_tree) once to fill it on a table that has rows.
42    fn nested_set_depth(&mut self);
43}
44
45impl NestedSetBlueprint for Blueprint {
46    fn nested_set(&mut self) {
47        self.nested_set_scoped(&[]);
48    }
49
50    fn nested_set_uuid(&mut self) {
51        self.big_integer("lft").default(0);
52        self.big_integer("rgt").default(0);
53        self.uuid("parent_id").nullable();
54        self.index(["lft", "rgt", "parent_id"]);
55        self.index("parent_id");
56    }
57
58    fn nested_set_scoped(&mut self, scope: &[&str]) {
59        self.big_integer("lft").default(0);
60        self.big_integer("rgt").default(0);
61        self.big_integer("parent_id").nullable();
62        let scoped = |columns: &[&str]| -> Vec<String> {
63            scope.iter().chain(columns).map(|column| (*column).to_owned()).collect()
64        };
65        self.index(scoped(&["lft", "rgt", "parent_id"]));
66        self.index("parent_id");
67    }
68
69    fn nested_set_depth(&mut self) {
70        self.big_integer("depth").default(0);
71        self.index("depth");
72    }
73
74    fn drop_nested_set(&mut self) {
75        self.drop_column(["lft", "rgt", "parent_id"]);
76    }
77}