Skip to main content

rbox_db/
ordering.rs

1// Copyright (C) 2026 Dylan Jones
2// SPDX-License-Identifier: GPL-3.0-only
3
4//! Ordered database collections and in-memory trees shared by both database formats.
5//!
6//! [`SequenceStore`] maintains contiguous positions within a collection. [`OrderedModel`]
7//! supplies record identity and persistence for batch plans; [`ModelTree`] adds ancestry
8//! validation and [`ModelList`] restricts moves to one collection. [`SequenceVisible`] is
9//! the compatibility facade for globally ordered visible rows.
10//!
11//! Insertion and move positions use the format's [`SequenceStore::START_SEQ`]. `None`
12//! means append. A batch's destination is its first final position after removing the
13//! selected members, and caller order is preserved. Duplicate move IDs are rejected.
14//! Batch operations and concrete model mutations run in transactions; low-level shift
15//! helpers belong inside those transactions. No-op moves preserve update metadata.
16//!
17//! [`TreeNode`] represents an in-memory snapshot. Sorting its child vectors does not
18//! persist database changes; use the model operations to edit stored ordering.
19
20use diesel::prelude::*;
21use diesel::result::{DatabaseErrorKind, Error};
22use std::cell::RefCell;
23use std::collections::HashMap;
24use std::fmt::Debug;
25use std::hash::Hash;
26use std::rc::Rc;
27
28use crate::model::{Model, ModelDelete};
29
30/// A database-backed ordered collection. A scope is a parent ID, playlist ID, or
31/// `()` for a global filtered collection. Positions are contiguous from `START_SEQ`.
32///
33/// Mutating primitives must be called inside the transaction that changes the item.
34/// Membership filters must be identical for counting, reading, shifting and renumbering.
35pub trait SequenceStore {
36    /// Collection identifier; retained as `ParentId` for compatibility with `TreeSeq`.
37    type ParentId: ?Sized + PartialEq + Debug;
38
39    /// First stored position, dictated by the model and database format.
40    ///
41    /// Master database collections conventionally start at one. OneLibrary uses
42    /// zero for playlist/My Tag siblings (also adopted for history siblings), but
43    /// one for playlist/history contents and visible browse settings.
44    /// Implementations must select their own start;
45    /// it cannot be inferred from the connection type.
46    const START_SEQ: i32 = 1;
47
48    /// Check collection existence and whether it accepts this kind of item.
49    fn is_valid_parent(conn: &mut SqliteConnection, parent: &Self::ParentId) -> QueryResult<bool>;
50
51    /// Number of members of the collection.
52    fn count_children(conn: &mut SqliteConnection, parent: &Self::ParentId) -> QueryResult<i32>;
53
54    /// Positions in ascending order.
55    fn get_seq_numbers(
56        conn: &mut SqliteConnection,
57        parent: &Self::ParentId,
58    ) -> QueryResult<Vec<i32>>;
59
60    /// Renumber by current position and stable item identity; only changed rows are written.
61    fn reset_seq(conn: &mut SqliteConnection, parent: &Self::ParentId) -> QueryResult<usize>;
62
63    /// Shift members in a half-open range by `delta`, including backend update metadata.
64    fn shift_seq(
65        conn: &mut SqliteConnection,
66        parent: &Self::ParentId,
67        range: std::ops::Range<i32>,
68        delta: i32,
69    ) -> QueryResult<usize>;
70
71    /// Check for gaps, duplicates and incorrect starting positions.
72    fn validate_seq_numbers(
73        conn: &mut SqliteConnection,
74        parent: &Self::ParentId,
75    ) -> QueryResult<bool> {
76        Ok(validate_seq_numbers(
77            &Self::get_seq_numbers(conn, parent)?,
78            Self::START_SEQ,
79        ))
80    }
81
82    /// Open a slot before an insertion.
83    fn increment_seq_gte(
84        conn: &mut SqliteConnection,
85        parent: &Self::ParentId,
86        seq: i32,
87    ) -> QueryResult<usize> {
88        let end = sequence_end(Self::START_SEQ, Self::count_children(conn, parent)?)?;
89        Self::shift_seq(conn, parent, seq..end, 1)
90    }
91    /// Close a slot after a deletion or before moving an item to another collection.
92    fn decrement_seq_gt(
93        conn: &mut SqliteConnection,
94        parent: &Self::ParentId,
95        seq: i32,
96    ) -> QueryResult<usize> {
97        let start = seq
98            .checked_add(1)
99            .ok_or_else(|| ordering_error("Position overflow"))?;
100        Self::shift_seq(conn, parent, start..i32::MAX, -1)
101    }
102
103    /// Shift positions `start <= position < end` upwards.
104    fn increment_seq_gte_lt(
105        conn: &mut SqliteConnection,
106        parent: &Self::ParentId,
107        start: i32,
108        end: i32,
109    ) -> QueryResult<usize> {
110        Self::shift_seq(conn, parent, start..end, 1)
111    }
112
113    /// Shift positions `start < position <= end` downwards.
114    fn decrement_seq_gt_lte(
115        conn: &mut SqliteConnection,
116        parent: &Self::ParentId,
117        start: i32,
118        end: i32,
119    ) -> QueryResult<usize> {
120        let start = start
121            .checked_add(1)
122            .ok_or_else(|| ordering_error("Position overflow"))?;
123        let end = end
124            .checked_add(1)
125            .ok_or_else(|| ordering_error("Position overflow"))?;
126        Self::shift_seq(conn, parent, start..end, -1)
127    }
128
129    /// Validate an insertion and open its slot. `None` appends.
130    fn update_seq_before_insert(
131        conn: &mut SqliteConnection,
132        parent: &Self::ParentId,
133        seq: Option<i32>,
134    ) -> QueryResult<(i32, usize)> {
135        if !Self::is_valid_parent(conn, parent)? {
136            return Err(ordering_error("Invalid collection"));
137        }
138        let end = sequence_end(Self::START_SEQ, Self::count_children(conn, parent)?)?;
139        let seq = checked_position(seq, Self::START_SEQ, end)?;
140        let n = if seq < end {
141            Self::shift_seq(conn, parent, seq..end, 1)?
142        } else {
143            0
144        };
145        Ok((seq, n))
146    }
147
148    /// Prepare a move between collections. The caller must update the item in the same transaction.
149    fn update_seq_before_move_to(
150        conn: &mut SqliteConnection,
151        old_parent: &Self::ParentId,
152        parent: &Self::ParentId,
153        old_seq: i32,
154        seq: Option<i32>,
155    ) -> QueryResult<Option<(i32, usize)>> {
156        if old_parent == parent {
157            return Ok(None);
158        }
159        if !Self::is_valid_parent(conn, parent)? {
160            return Err(ordering_error("Invalid collection"));
161        }
162        let end = sequence_end(Self::START_SEQ, Self::count_children(conn, parent)?)?;
163        let seq = checked_position(seq, Self::START_SEQ, end)?;
164        let mut n = Self::decrement_seq_gt(conn, old_parent, old_seq)?;
165        if seq < end {
166            n += Self::shift_seq(conn, parent, seq..end, 1)?;
167        }
168        Ok(Some((seq, n)))
169    }
170
171    /// Prepare a move within a collection, interpreting the destination as its final position.
172    fn update_seq_before_move_in(
173        conn: &mut SqliteConnection,
174        parent: &Self::ParentId,
175        old_seq: i32,
176        seq: Option<i32>,
177    ) -> QueryResult<Option<(i32, usize)>> {
178        let end = sequence_end(Self::START_SEQ, Self::count_children(conn, parent)?)?;
179        checked_position(Some(old_seq), Self::START_SEQ, end - 1)?;
180        let seq = checked_position(seq, Self::START_SEQ, end - 1)?;
181        if seq == old_seq {
182            return Ok(None);
183        }
184        let n = if seq > old_seq {
185            Self::decrement_seq_gt_lte(conn, parent, old_seq, seq)?
186        } else {
187            Self::increment_seq_gte_lt(conn, parent, seq, old_seq)?
188        };
189        Ok(Some((seq, n)))
190    }
191
192    /// Prepare a move within or between collections.
193    fn update_seq_before_move(
194        conn: &mut SqliteConnection,
195        old_parent: &Self::ParentId,
196        parent: &Self::ParentId,
197        old_seq: i32,
198        seq: Option<i32>,
199    ) -> QueryResult<Option<(i32, usize)>> {
200        if old_parent == parent {
201            Self::update_seq_before_move_in(conn, parent, old_seq, seq)
202        } else {
203            Self::update_seq_before_move_to(conn, old_parent, parent, old_seq, seq)
204        }
205    }
206}
207
208/// Compatibility name for the collection ordering interface.
209pub use SequenceStore as TreeSeq;
210
211/// Validate an ordered slice without overflowing on large positions.
212pub fn validate_seq_numbers(seqs: &[i32], start: i32) -> bool {
213    seqs.iter()
214        .enumerate()
215        .all(|(i, &seq)| i64::from(seq) == i64::from(start) + i as i64)
216}
217
218pub fn ordering_error(message: &str) -> Error {
219    Error::DatabaseError(
220        DatabaseErrorKind::RestrictViolation,
221        Box::new(message.to_owned()),
222    )
223}
224
225fn sequence_end(start: i32, count: i32) -> QueryResult<i32> {
226    if count < 0 {
227        return Err(ordering_error("Invalid collection size"));
228    }
229    start
230        .checked_add(count)
231        .ok_or_else(|| ordering_error("Position overflow"))
232}
233
234fn checked_position(seq: Option<i32>, start: i32, end: i32) -> QueryResult<i32> {
235    let seq = seq.unwrap_or(end);
236    if seq < start || seq > end {
237        return Err(ordering_error("Invalid sequence number"));
238    }
239    Ok(seq)
240}
241
242/// Model hooks used to plan a whole reorder before writing any rows.
243pub trait OrderedModel: Model + SequenceStore {
244    /// Owned identity of this entry, including every column of a composite key.
245    fn order_id(&self) -> <Self::Id as ToOwned>::Owned;
246    /// Collection containing this entry.
247    fn order_parent(&self) -> &Self::ParentId;
248    /// Stored position.
249    fn order_position(&self) -> i32;
250    /// Read one collection in position order, breaking ties by the full primary key.
251    fn ordered(conn: &mut SqliteConnection, parent: &Self::ParentId) -> QueryResult<Vec<Self>>;
252    /// Apply a validated plan. Called inside a transaction; update metadata belongs here.
253    fn write_order(
254        conn: &mut SqliteConnection,
255        changes: &[(&Self, &Self::ParentId, i32)],
256    ) -> QueryResult<usize>;
257
258    /// Repair a collection in stable position/key order, preserving metadata for unchanged rows.
259    fn renumber(conn: &mut SqliteConnection, parent: &Self::ParentId) -> QueryResult<usize> {
260        conn.transaction(|conn| {
261            let rows = Self::ordered(conn, parent)?;
262            let mut changes = Vec::new();
263            for (index, row) in rows.iter().enumerate() {
264                let index =
265                    i32::try_from(index).map_err(|_| ordering_error("Position overflow"))?;
266                let seq = sequence_end(Self::START_SEQ, index)?;
267                if row.order_position() != seq {
268                    changes.push((row, parent, seq));
269                }
270            }
271            Self::write_order(conn, &changes)
272        })
273    }
274}
275
276/// Delete selected subtrees once, even when both an ancestor and its descendant are selected.
277/// Duplicate IDs and missing records reject the whole batch before any deletion.
278pub fn delete_tree_batch<M: ModelTree + ModelDelete>(
279    conn: &mut SqliteConnection,
280    ids: Vec<&M::Id>,
281) -> QueryResult<usize> {
282    conn.transaction(|conn| {
283        let roots = tree_delete_roots::<M>(conn, &ids)?;
284        let mut count = 0;
285        for root in roots {
286            count += M::delete(conn, root)?;
287        }
288        Ok(count)
289    })
290}
291
292/// Validate a subtree deletion and remove selections already covered by an ancestor.
293pub fn tree_delete_roots<'a, M: ModelTree>(
294    conn: &mut SqliteConnection,
295    ids: &[&'a M::Id],
296) -> QueryResult<Vec<&'a M::Id>> {
297    use std::borrow::Borrow;
298    let mut roots = Vec::new();
299    for (i, id) in ids.iter().enumerate() {
300        if ids[..i].contains(id) {
301            return Err(ordering_error("Duplicate delete ID"));
302        }
303        let row = M::find(conn, id)?.ok_or(Error::NotFound)?;
304        let mut parent = row.order_parent().to_owned();
305        let mut seen: Vec<<M::Id as ToOwned>::Owned> = vec![(*id).to_owned()];
306        let mut covered = false;
307        loop {
308            let key: &M::Id = parent.borrow();
309            if seen.iter().any(|p| p.borrow() == key) {
310                return Err(ordering_error("Cyclic ancestry"));
311            }
312            if ids.contains(&key) {
313                covered = true;
314            }
315            let ancestor = M::find(conn, key)?;
316            seen.push(parent);
317            match ancestor {
318                Some(ancestor) => parent = ancestor.order_parent().to_owned(),
319                None => break,
320            }
321        }
322        if !covered {
323            roots.push(*id);
324        }
325    }
326
327    Ok(roots)
328}
329
330/// Tree operations add ancestry validation to collection ordering.
331pub trait ModelTree: OrderedModel<ParentId = <Self as Model>::Id> {
332    /// Reject invalid folders, self-parenting, descendant targets and existing ancestry cycles.
333    fn validate_destination(
334        conn: &mut SqliteConnection,
335        id: &Self::Id,
336        parent: &Self::Id,
337    ) -> QueryResult<()> {
338        use std::borrow::Borrow;
339        if !Self::is_valid_parent(conn, parent)? {
340            return Err(ordering_error("Invalid parent"));
341        }
342        let mut current = parent.to_owned();
343        let mut seen: Vec<<Self::Id as ToOwned>::Owned> = Vec::new();
344        loop {
345            let key: &Self::Id = current.borrow();
346            if key == id || seen.iter().any(|p| p.borrow() == key) {
347                return Err(ordering_error(
348                    "A tree move would create or encounter a cycle",
349                ));
350            }
351            let node = Self::find(conn, key)?;
352            seen.push(current);
353            match node {
354                Some(node) => current = node.order_parent().to_owned(),
355                None => return Ok(()), // The format's root sentinel is not a stored row.
356            }
357        }
358    }
359
360    /// Move one item atomically; `None` keeps the parent or appends within the destination.
361    fn move_to(
362        conn: &mut SqliteConnection,
363        id: &Self::Id,
364        parent_id: Option<&Self::Id>,
365        seq: Option<i32>,
366    ) -> QueryResult<usize>;
367
368    /// Move distinct items as a block, preserving caller order. The start position is measured
369    /// after removing selected destination members. Empty input is a no-op. The whole batch rolls
370    /// back on failure, and unchanged rows retain their update metadata.
371    fn move_all_to(
372        conn: &mut SqliteConnection,
373        ids: &[&Self::Id],
374        parent_id: &Self::Id,
375        start_seq: Option<i32>,
376    ) -> QueryResult<usize> {
377        conn.transaction(|conn| {
378            if ids.is_empty() {
379                return Ok(0);
380            }
381            for id in ids {
382                Self::validate_destination(conn, id, parent_id)?;
383            }
384            reorder_batch::<Self>(conn, ids, Some(parent_id), start_seq)
385        })
386    }
387}
388
389/// Reordering of entries within a single collection.
390pub trait ModelList: OrderedModel {
391    /// Move one item atomically. `None` appends.
392    fn move_to(conn: &mut SqliteConnection, id: &Self::Id, seq: Option<i32>) -> QueryResult<usize>;
393    /// Move distinct entries as a block. All entries must belong to the same collection.
394    /// Positions refer to the destination after removing the selected entries.
395    fn move_all_to(
396        conn: &mut SqliteConnection,
397        ids: &[&Self::Id],
398        start_seq: Option<i32>,
399    ) -> QueryResult<usize> {
400        conn.transaction(|conn| reorder_batch::<Self>(conn, ids, None, start_seq))
401    }
402}
403
404fn reorder_batch<M: OrderedModel>(
405    conn: &mut SqliteConnection,
406    ids: &[&M::Id],
407    target: Option<&M::ParentId>,
408    seq: Option<i32>,
409) -> QueryResult<usize> {
410    use std::borrow::Borrow;
411    if ids.is_empty() {
412        return Ok(0);
413    }
414    let mut selected = Vec::with_capacity(ids.len());
415    for (i, id) in ids.iter().enumerate() {
416        if ids[..i].contains(id) {
417            return Err(ordering_error("Duplicate move ID"));
418        }
419        selected.push(M::find(conn, id)?.ok_or(Error::NotFound)?);
420    }
421    let parent = target.unwrap_or_else(|| selected[0].order_parent());
422    if target.is_none() && selected.iter().any(|row| row.order_parent() != parent) {
423        return Err(ordering_error("List moves require a single collection"));
424    }
425    let mut scopes = vec![parent];
426    for row in &selected {
427        if !scopes.contains(&row.order_parent()) {
428            scopes.push(row.order_parent());
429        }
430    }
431    let mut groups = Vec::new();
432    for scope in scopes {
433        let mut members = M::ordered(conn, scope)?;
434        members.retain(|row| !ids.contains(&row.order_id().borrow()));
435        if scope == parent {
436            let count =
437                i32::try_from(members.len()).map_err(|_| ordering_error("Collection too large"))?;
438            let end = sequence_end(M::START_SEQ, count)?;
439            let position = checked_position(seq, M::START_SEQ, end)?;
440            let index = (position - M::START_SEQ) as usize;
441            members.splice(index..index, selected.iter().cloned());
442        }
443        groups.push((scope, members));
444    }
445    let mut changes = Vec::new();
446    let mut moved = 0;
447    for (scope, members) in &groups {
448        for (i, row) in members.iter().enumerate() {
449            let offset = i32::try_from(i).map_err(|_| ordering_error("Collection too large"))?;
450            let position = sequence_end(M::START_SEQ, offset)?;
451            if row.order_parent() != *scope || row.order_position() != position {
452                if ids.contains(&row.order_id().borrow()) {
453                    moved += 1;
454                }
455                changes.push((row, *scope, position));
456            }
457        }
458    }
459    if !changes.is_empty() {
460        M::write_order(conn, &changes)?;
461    }
462    Ok(moved)
463}
464
465/// Compatibility facade for globally ordered visible rows.
466pub trait SequenceVisible: SequenceStore<ParentId = ()> {
467    /// Count visible members.
468    fn count_visible(conn: &mut SqliteConnection) -> QueryResult<i32> {
469        Self::count_children(conn, &())
470    }
471    /// Read visible positions in order.
472    fn get_seq_numbers(conn: &mut SqliteConnection) -> QueryResult<Vec<i32>> {
473        <Self as SequenceStore>::get_seq_numbers(conn, &())
474    }
475    /// Renumber visible members only.
476    fn reset_seq(conn: &mut SqliteConnection) -> QueryResult<usize> {
477        <Self as SequenceStore>::reset_seq(conn, &())
478    }
479    /// Validate visible positions.
480    fn validate_seq_numbers(conn: &mut SqliteConnection) -> QueryResult<bool> {
481        <Self as SequenceStore>::validate_seq_numbers(conn, &())
482    }
483    /// Open a position in the visible list.
484    fn increment_seq_before_insert(conn: &mut SqliteConnection, seq: i32) -> QueryResult<usize> {
485        Self::increment_seq_gte(conn, &(), seq)
486    }
487    /// Prepare an insertion. Zero retains the legacy append convention for this one-based list.
488    fn update_seq_before_insert(conn: &mut SqliteConnection, seq: i32) -> QueryResult<i32> {
489        Ok(<Self as SequenceStore>::update_seq_before_insert(
490            conn,
491            &(),
492            if seq == 0 { None } else { Some(seq) },
493        )?
494        .0)
495    }
496    /// Close the position of a removed or hidden member.
497    fn decrement_seq_after_delete(conn: &mut SqliteConnection, seq: i32) -> QueryResult<usize> {
498        Self::decrement_seq_gt(conn, &(), seq)
499    }
500}
501
502pub type NodeRef<T> = Rc<RefCell<T>>;
503
504/// A trait for models that can be used as tree nodes.
505pub trait TreeNode: From<Self::Model> {
506    /// The reference model.
507    type Model: Model;
508    /// The unique identifier of the node.
509    type Id: ?Sized + Eq + Ord + Debug + Clone + Hash;
510
511    /// Returns the unique identifier of the node.
512    fn id(&self) -> Self::Id;
513    /// Returns the sequence number (ordering) of the node.
514    fn sequence(&self) -> i32;
515    /// Returns the parent identifier of the node.
516    fn parent_id(&self) -> Self::Id;
517    /// Returns a reference to the vector containing the child references.
518    fn children(&self) -> &Vec<NodeRef<Self>>;
519    /// Returns a mutable reference to the vector containing the child references.
520    fn children_mut(&mut self) -> &mut Vec<NodeRef<Self>>;
521
522    /// Sort children by position, breaking ties by their stable identifiers.
523    fn sort_children(&mut self) {
524        self.children_mut().sort_by(|a, b| {
525            let a_seq = a.borrow().sequence();
526            let b_seq = b.borrow().sequence();
527            a_seq
528                .cmp(&b_seq)
529                .then_with(|| a.borrow().id().cmp(&b.borrow().id()))
530        });
531    }
532}
533
534/// Sort the children of a tree node recursively.
535fn sort_tree_ref<N: TreeNode>(item: &mut NodeRef<N>) {
536    let mut item_borrow = item.borrow_mut();
537    item_borrow.sort_children();
538    for child in item_borrow.children_mut().iter_mut() {
539        sort_tree_ref(child);
540    }
541}
542
543/// Sorts a list of tree nodes recursively by their sequence number.
544fn sort_tree_list<N: TreeNode>(items: &mut Vec<NodeRef<N>>) {
545    items.sort_by(|a, b| {
546        let a_seq = a.borrow().sequence();
547        let b_seq = b.borrow().sequence();
548        a_seq
549            .cmp(&b_seq)
550            .then_with(|| a.borrow().id().cmp(&b.borrow().id()))
551    });
552    for item in items.iter_mut() {
553        sort_tree_ref(item);
554    }
555}
556
557/// Constructs a tree of nodes from a list of models.
558pub fn build_tree_list<M, N>(models: Vec<M>, root_id: N::Id) -> Vec<NodeRef<N>>
559where
560    N: TreeNode<Model = M>,
561    M: Model,
562{
563    let nodes: Vec<N> = models.into_iter().map(N::from).collect();
564
565    let mut map: HashMap<N::Id, NodeRef<N>> = HashMap::new();
566    let mut roots = Vec::new();
567
568    // Populate the map with nodes
569    for node in nodes.into_iter() {
570        let id = node.id();
571        let parent_id = node.parent_id();
572
573        let item: NodeRef<N> = Rc::new(RefCell::new(node));
574        if parent_id == root_id {
575            roots.push(item.clone());
576        }
577        map.insert(id.clone(), item);
578    }
579
580    // Build the tree structure
581    for node in map.values() {
582        let parent_id = node.borrow().parent_id();
583        if let Some(parent_node) = map.get(&parent_id) {
584            parent_node.borrow_mut().children_mut().push(node.clone());
585        }
586    }
587
588    // Sort the entire tree
589    sort_tree_list(&mut roots);
590
591    roots
592}