1use 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
30pub trait SequenceStore {
36 type ParentId: ?Sized + PartialEq + Debug;
38
39 const START_SEQ: i32 = 1;
44
45 fn is_valid_parent(conn: &mut SqliteConnection, parent: &Self::ParentId) -> QueryResult<bool>;
47
48 fn count_children(conn: &mut SqliteConnection, parent: &Self::ParentId) -> QueryResult<i32>;
50
51 fn get_seq_numbers(
53 conn: &mut SqliteConnection,
54 parent: &Self::ParentId,
55 ) -> QueryResult<Vec<i32>>;
56
57 fn reset_seq(conn: &mut SqliteConnection, parent: &Self::ParentId) -> QueryResult<usize>;
59
60 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 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 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 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 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 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 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 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 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 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
205pub use SequenceStore as TreeSeq;
207
208pub 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
239pub trait OrderedModel: Model + SequenceStore {
241 fn order_id(&self) -> <Self::Id as ToOwned>::Owned;
243 fn order_parent(&self) -> &Self::ParentId;
245 fn order_position(&self) -> i32;
247 fn ordered(conn: &mut SqliteConnection, parent: &Self::ParentId) -> QueryResult<Vec<Self>>;
249 fn write_order(
251 conn: &mut SqliteConnection,
252 changes: &[(&Self, &Self::ParentId, i32)],
253 ) -> QueryResult<usize>;
254
255 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
273pub 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
289pub 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
327pub trait ModelTree: OrderedModel<ParentId = <Self as Model>::Id> {
329 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(()), }
354 }
355 }
356
357 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 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
386pub trait ModelList: OrderedModel {
388 fn move_to(conn: &mut SqliteConnection, id: &Self::Id, seq: Option<i32>) -> QueryResult<usize>;
390 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
462pub trait SequenceVisible: SequenceStore<ParentId = ()> {
464 fn count_visible(conn: &mut SqliteConnection) -> QueryResult<i32> {
466 Self::count_children(conn, &())
467 }
468 fn get_seq_numbers(conn: &mut SqliteConnection) -> QueryResult<Vec<i32>> {
470 <Self as SequenceStore>::get_seq_numbers(conn, &())
471 }
472 fn reset_seq(conn: &mut SqliteConnection) -> QueryResult<usize> {
474 <Self as SequenceStore>::reset_seq(conn, &())
475 }
476 fn validate_seq_numbers(conn: &mut SqliteConnection) -> QueryResult<bool> {
478 <Self as SequenceStore>::validate_seq_numbers(conn, &())
479 }
480 fn increment_seq_before_insert(conn: &mut SqliteConnection, seq: i32) -> QueryResult<usize> {
482 Self::increment_seq_gte(conn, &(), seq)
483 }
484 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 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
501pub trait TreeNode: From<Self::Model> {
503 type Model: Model;
505 type Id: ?Sized + Eq + Ord + Debug + Clone + Hash;
507
508 fn id(&self) -> Self::Id;
510 fn sequence(&self) -> i32;
512 fn parent_id(&self) -> Self::Id;
514 fn children(&self) -> &Vec<NodeRef<Self>>;
516 fn children_mut(&mut self) -> &mut Vec<NodeRef<Self>>;
518
519 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
531fn 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
540fn 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
554pub 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 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 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_tree_list(&mut roots);
587
588 roots
589}