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