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;
47
48 fn is_valid_parent(conn: &mut SqliteConnection, parent: &Self::ParentId) -> QueryResult<bool>;
50
51 fn count_children(conn: &mut SqliteConnection, parent: &Self::ParentId) -> QueryResult<i32>;
53
54 fn get_seq_numbers(
56 conn: &mut SqliteConnection,
57 parent: &Self::ParentId,
58 ) -> QueryResult<Vec<i32>>;
59
60 fn reset_seq(conn: &mut SqliteConnection, parent: &Self::ParentId) -> QueryResult<usize>;
62
63 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 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 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 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 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 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 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 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 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 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
208pub use SequenceStore as TreeSeq;
210
211pub 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
242pub trait OrderedModel: Model + SequenceStore {
244 fn order_id(&self) -> <Self::Id as ToOwned>::Owned;
246 fn order_parent(&self) -> &Self::ParentId;
248 fn order_position(&self) -> i32;
250 fn ordered(conn: &mut SqliteConnection, parent: &Self::ParentId) -> QueryResult<Vec<Self>>;
252 fn write_order(
254 conn: &mut SqliteConnection,
255 changes: &[(&Self, &Self::ParentId, i32)],
256 ) -> QueryResult<usize>;
257
258 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
276pub 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
292pub 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
330pub trait ModelTree: OrderedModel<ParentId = <Self as Model>::Id> {
332 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(()), }
357 }
358 }
359
360 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 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
389pub trait ModelList: OrderedModel {
391 fn move_to(conn: &mut SqliteConnection, id: &Self::Id, seq: Option<i32>) -> QueryResult<usize>;
393 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
465pub trait SequenceVisible: SequenceStore<ParentId = ()> {
467 fn count_visible(conn: &mut SqliteConnection) -> QueryResult<i32> {
469 Self::count_children(conn, &())
470 }
471 fn get_seq_numbers(conn: &mut SqliteConnection) -> QueryResult<Vec<i32>> {
473 <Self as SequenceStore>::get_seq_numbers(conn, &())
474 }
475 fn reset_seq(conn: &mut SqliteConnection) -> QueryResult<usize> {
477 <Self as SequenceStore>::reset_seq(conn, &())
478 }
479 fn validate_seq_numbers(conn: &mut SqliteConnection) -> QueryResult<bool> {
481 <Self as SequenceStore>::validate_seq_numbers(conn, &())
482 }
483 fn increment_seq_before_insert(conn: &mut SqliteConnection, seq: i32) -> QueryResult<usize> {
485 Self::increment_seq_gte(conn, &(), seq)
486 }
487 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 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
504pub trait TreeNode: From<Self::Model> {
506 type Model: Model;
508 type Id: ?Sized + Eq + Ord + Debug + Clone + Hash;
510
511 fn id(&self) -> Self::Id;
513 fn sequence(&self) -> i32;
515 fn parent_id(&self) -> Self::Id;
517 fn children(&self) -> &Vec<NodeRef<Self>>;
519 fn children_mut(&mut self) -> &mut Vec<NodeRef<Self>>;
521
522 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
534fn 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
543fn 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
557pub 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 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 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_tree_list(&mut roots);
590
591 roots
592}