-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathchange.rs
1325 lines (1097 loc) · 40.7 KB
/
change.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use pgt_text_size::{TextLen, TextRange, TextSize};
use std::ops::{Add, Sub};
use crate::workspace::{ChangeFileParams, ChangeParams};
use super::{Document, Statement, document};
#[derive(Debug, PartialEq, Eq)]
pub enum StatementChange {
Added(AddedStatement),
Deleted(Statement),
Modified(ModifiedStatement),
}
#[derive(Debug, PartialEq, Eq)]
pub struct AddedStatement {
pub stmt: Statement,
pub text: String,
}
#[derive(Debug, PartialEq, Eq)]
pub struct ModifiedStatement {
pub old_stmt: Statement,
pub old_stmt_text: String,
pub new_stmt: Statement,
pub new_stmt_text: String,
pub change_range: TextRange,
pub change_text: String,
}
impl StatementChange {
#[allow(dead_code)]
pub fn statement(&self) -> &Statement {
match self {
StatementChange::Added(stmt) => &stmt.stmt,
StatementChange::Deleted(stmt) => stmt,
StatementChange::Modified(changed) => &changed.new_stmt,
}
}
}
/// Returns all relevant details about the change and its effects on the current state of the document.
struct Affected {
/// Full range of the change, including the range of all statements that intersect with the change
affected_range: TextRange,
/// All indices of affected statement positions
affected_indices: Vec<usize>,
/// The index of the first statement position before the change, if any
prev_index: Option<usize>,
/// The index of the first statement position after the change, if any
next_index: Option<usize>,
/// the full affected range includng the prev and next statement
full_affected_range: TextRange,
}
impl Document {
/// Applies a file change to the document and returns the affected statements
pub fn apply_file_change(&mut self, change: &ChangeFileParams) -> Vec<StatementChange> {
// cleanup all diagnostics with every change because we cannot guarantee that they are still valid
// this is because we know their ranges only by finding slices within the content which is
// very much not guaranteed to result in correct ranges
self.diagnostics.clear();
let changes = change
.changes
.iter()
.flat_map(|c| self.apply_change(c))
.collect();
self.version = change.version;
changes
}
/// Helper method to drain all positions and return them as deleted statements
fn drain_positions(&mut self) -> Vec<StatementChange> {
self.positions
.drain(..)
.map(|(id, _)| {
StatementChange::Deleted(Statement {
id,
path: self.path.clone(),
})
})
.collect()
}
/// Applies a change to the document and returns the affected statements
///
/// Will always assume its a full change and reparse the whole document
fn apply_full_change(&mut self, change: &ChangeParams) -> Vec<StatementChange> {
let mut changes = Vec::new();
changes.extend(self.drain_positions());
self.content = change.apply_to_text(&self.content);
let (ranges, diagnostics) = document::split_with_diagnostics(&self.content, None);
self.diagnostics = diagnostics;
// Do not add any statements if there is a fatal error
if self.has_fatal_error() {
return changes;
}
changes.extend(ranges.into_iter().map(|range| {
let id = self.id_generator.next();
let text = self.content[range].to_string();
self.positions.push((id, range));
StatementChange::Added(AddedStatement {
stmt: Statement {
path: self.path.clone(),
id,
},
text,
})
}));
changes
}
fn insert_statement(&mut self, range: TextRange) -> usize {
let pos = self
.positions
.binary_search_by(|(_, r)| r.start().cmp(&range.start()))
.unwrap_err();
let new_id = self.id_generator.next();
self.positions.insert(pos, (new_id, range));
new_id
}
/// Returns all relevant details about the change and its effects on the current state of the document.
/// - The affected range is the full range of the change, including the range of all statements that intersect with the change
/// - All indices of affected statement positions
/// - The index of the first statement position before the change, if any
/// - The index of the first statement position after the change, if any
/// - the full affected range includng the prev and next statement
fn get_affected(
&self,
change_range: TextRange,
content_size: TextSize,
diff_size: TextSize,
is_addition: bool,
) -> Affected {
let mut start = change_range.start();
let mut end = change_range.end().min(content_size);
let mut affected_indices = Vec::new();
let mut prev_index = None;
let mut next_index = None;
for (index, (_, pos_range)) in self.positions.iter().enumerate() {
if pos_range.intersect(change_range).is_some() {
affected_indices.push(index);
start = start.min(pos_range.start());
end = end.max(pos_range.end());
} else if pos_range.end() <= change_range.start() {
prev_index = Some(index);
} else if pos_range.start() >= change_range.end() && next_index.is_none() {
next_index = Some(index);
break;
}
}
let start_incl = prev_index
.map(|i| self.positions[i].1.start())
.unwrap_or(start);
let end_incl = next_index
.map(|i| self.positions[i].1.end())
.unwrap_or_else(|| end);
let end_incl = if is_addition {
end_incl.add(diff_size)
} else {
end_incl.sub(diff_size)
};
let end = if is_addition {
end.add(diff_size)
} else {
end.sub(diff_size)
};
Affected {
affected_range: {
let end = end.min(content_size);
TextRange::new(start.min(end), end)
},
affected_indices,
prev_index,
next_index,
full_affected_range: TextRange::new(start_incl, end_incl.min(content_size)),
}
}
fn move_ranges(&mut self, offset: TextSize, diff_size: TextSize, is_addition: bool) {
self.positions
.iter_mut()
.skip_while(|(_, r)| offset > r.start())
.for_each(|(_, range)| {
let new_range = if is_addition {
range.add(diff_size)
} else {
range.sub(diff_size)
};
*range = new_range;
});
}
/// Applies a single change to the document and returns the affected statements
fn apply_change(&mut self, change: &ChangeParams) -> Vec<StatementChange> {
// if range is none, we have a full change
if change.range.is_none() {
return self.apply_full_change(change);
}
// i spent a relatively large amount of time thinking about how to handle range changes
// properly. there are quite a few edge cases to consider. I eventually skipped most of
// them, because the complexity is not worth the return for now. we might want to revisit
// this later though.
let mut changed: Vec<StatementChange> = Vec::with_capacity(self.positions.len());
let change_range = change.range.unwrap();
let new_content = change.apply_to_text(&self.content);
// we first need to determine the affected range and all affected statements, as well as
// the index of the prev and the next statement, if any. The full affected range is the
// affected range expanded to the start of the previous statement and the end of the next
let Affected {
affected_range,
affected_indices,
prev_index,
next_index,
full_affected_range,
} = self.get_affected(
change_range,
new_content.text_len(),
change.diff_size(),
change.is_addition(),
);
// if within a statement, we can modify it if the change results in also a single statement
if affected_indices.len() == 1 {
let changed_content = get_affected(&new_content, affected_range);
let (new_ranges, diags) =
document::split_with_diagnostics(changed_content, Some(affected_range.start()));
self.diagnostics = diags;
if self.has_fatal_error() {
// cleanup all positions if there is a fatal error
changed.extend(self.drain_positions());
// still process text change
self.content = new_content;
return changed;
}
if new_ranges.len() == 1 {
let affected_idx = affected_indices[0];
let new_range = new_ranges[0].add(affected_range.start());
let (old_id, old_range) = self.positions[affected_idx];
// move all statements after the afffected range
self.move_ranges(old_range.end(), change.diff_size(), change.is_addition());
let new_id = self.id_generator.next();
self.positions[affected_idx] = (new_id, new_range);
changed.push(StatementChange::Modified(ModifiedStatement {
old_stmt: Statement {
id: old_id,
path: self.path.clone(),
},
old_stmt_text: self.content[old_range].to_string(),
new_stmt: Statement {
id: new_id,
path: self.path.clone(),
},
new_stmt_text: changed_content[new_ranges[0]].to_string(),
// change must be relative to the statement
change_text: change.text.clone(),
// make sure we always have a valid range >= 0
change_range: change_range
.checked_sub(old_range.start())
.unwrap_or(change_range.sub(change_range.start())),
}));
self.content = new_content;
return changed;
}
}
// in any other case, parse the full affected range
let changed_content = get_affected(&new_content, full_affected_range);
let (new_ranges, diags) =
document::split_with_diagnostics(changed_content, Some(full_affected_range.start()));
self.diagnostics = diags;
if self.has_fatal_error() {
// cleanup all positions if there is a fatal error
changed.extend(self.drain_positions());
// still process text change
self.content = new_content;
return changed;
}
// delete and add new ones
if let Some(next_index) = next_index {
changed.push(StatementChange::Deleted(Statement {
id: self.positions[next_index].0,
path: self.path.clone(),
}));
self.positions.remove(next_index);
}
for idx in affected_indices.iter().rev() {
changed.push(StatementChange::Deleted(Statement {
id: self.positions[*idx].0,
path: self.path.clone(),
}));
self.positions.remove(*idx);
}
if let Some(prev_index) = prev_index {
changed.push(StatementChange::Deleted(Statement {
id: self.positions[prev_index].0,
path: self.path.clone(),
}));
self.positions.remove(prev_index);
}
new_ranges.iter().for_each(|range| {
let actual_range = range.add(full_affected_range.start());
let new_id = self.insert_statement(actual_range);
changed.push(StatementChange::Added(AddedStatement {
stmt: Statement {
id: new_id,
path: self.path.clone(),
},
text: new_content[actual_range].to_string(),
}));
});
// move all statements after the afffected range
self.move_ranges(
full_affected_range.end(),
change.diff_size(),
change.is_addition(),
);
self.content = new_content;
changed
}
}
impl ChangeParams {
pub fn diff_size(&self) -> TextSize {
match self.range {
Some(range) => {
let range_length: usize = range.len().into();
let text_length = self.text.chars().count();
let diff = (text_length as i64 - range_length as i64).abs();
TextSize::from(u32::try_from(diff).unwrap())
}
None => TextSize::from(u32::try_from(self.text.chars().count()).unwrap()),
}
}
pub fn is_addition(&self) -> bool {
self.range.is_some() && self.text.len() > self.range.unwrap().len().into()
}
pub fn is_deletion(&self) -> bool {
self.range.is_some() && self.text.len() < self.range.unwrap().len().into()
}
pub fn apply_to_text(&self, text: &str) -> String {
if self.range.is_none() {
return self.text.clone();
}
let range = self.range.unwrap();
let start = usize::from(range.start());
let end = usize::from(range.end());
let mut new_text = String::new();
new_text.push_str(&text[..start]);
new_text.push_str(&self.text);
if end < text.len() {
new_text.push_str(&text[end..]);
}
new_text
}
}
fn get_affected(content: &str, range: TextRange) -> &str {
let start_byte = content
.char_indices()
.nth(usize::from(range.start()))
.map(|(i, _)| i)
.unwrap_or(content.len());
let end_byte = content
.char_indices()
.nth(usize::from(range.end()))
.map(|(i, _)| i)
.unwrap_or(content.len());
&content[start_byte..end_byte]
}
#[cfg(test)]
mod tests {
use super::*;
use pgt_diagnostics::Diagnostic;
use pgt_text_size::TextRange;
use crate::workspace::{ChangeFileParams, ChangeParams};
use pgt_fs::PgTPath;
impl Document {
pub fn get_text(&self, idx: usize) -> String {
self.content[self.positions[idx].1.start().into()..self.positions[idx].1.end().into()]
.to_string()
}
}
fn assert_document_integrity(d: &Document) {
let ranges = pgt_statement_splitter::split(&d.content)
.expect("Unexpected scan error")
.ranges;
assert!(
ranges.len() == d.positions.len(),
"should have the correct amount of positions"
);
assert!(
ranges
.iter()
.all(|r| { d.positions.iter().any(|(_, stmt_range)| stmt_range == r) }),
"all ranges should be in positions"
);
}
#[test]
fn open_doc_with_scan_error() {
let input = "select id from users;\n\n\n\nselect 1443ddwwd33djwdkjw13331333333333;";
let d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0);
assert_eq!(d.positions.len(), 0);
assert!(d.has_fatal_error());
}
#[test]
fn change_into_scan_error_within_statement() {
let path = PgTPath::new("test.sql");
let input = "select id from users;\n\n\n\nselect 1;";
let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0);
assert_eq!(d.positions.len(), 2);
assert!(!d.has_fatal_error());
let change = ChangeFileParams {
path: path.clone(),
version: 1,
changes: vec![ChangeParams {
text: "d".to_string(),
range: Some(TextRange::new(33.into(), 33.into())),
}],
};
let changed = d.apply_file_change(&change);
assert_eq!(d.content, "select id from users;\n\n\n\nselect 1d;");
assert!(
changed
.iter()
.all(|c| matches!(c, StatementChange::Deleted(_))),
"should delete all statements"
);
assert!(d.positions.is_empty(), "should clear all positions");
assert_eq!(d.diagnostics.len(), 1, "should return a scan error");
assert_eq!(
d.diagnostics[0].location().span,
Some(TextRange::new(32.into(), 34.into())),
"should have correct span"
);
assert!(d.has_fatal_error());
}
#[test]
fn change_into_scan_error_across_statements() {
let path = PgTPath::new("test.sql");
let input = "select id from users;\n\n\n\nselect 1;";
let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0);
assert_eq!(d.positions.len(), 2);
assert!(!d.has_fatal_error());
let change = ChangeFileParams {
path: path.clone(),
version: 1,
changes: vec![ChangeParams {
text: "1d".to_string(),
range: Some(TextRange::new(7.into(), 33.into())),
}],
};
let changed = d.apply_file_change(&change);
assert_eq!(d.content, "select 1d;");
assert!(
changed
.iter()
.all(|c| matches!(c, StatementChange::Deleted(_))),
"should delete all statements"
);
assert!(d.positions.is_empty(), "should clear all positions");
assert_eq!(d.diagnostics.len(), 1, "should return a scan error");
assert_eq!(
d.diagnostics[0].location().span,
Some(TextRange::new(7.into(), 9.into())),
"should have correct span"
);
assert!(d.has_fatal_error());
}
#[test]
fn change_from_invalid_to_invalid() {
let path = PgTPath::new("test.sql");
let input = "select 1d;";
let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0);
assert_eq!(d.positions.len(), 0);
assert!(d.has_fatal_error());
assert_eq!(d.diagnostics.len(), 1);
let change = ChangeFileParams {
path: path.clone(),
version: 1,
changes: vec![ChangeParams {
text: "2e".to_string(),
range: Some(TextRange::new(7.into(), 9.into())),
}],
};
let changed = d.apply_file_change(&change);
assert_eq!(d.content, "select 2e;");
assert!(changed.is_empty(), "should not emit any changes");
assert!(d.positions.is_empty(), "should keep positions empty");
assert_eq!(d.diagnostics.len(), 1, "should still have a scan error");
assert_eq!(
d.diagnostics[0].location().span,
Some(TextRange::new(7.into(), 9.into())),
"should have updated span"
);
assert!(d.has_fatal_error());
}
#[test]
fn change_from_invalid_to_valid() {
let path = PgTPath::new("test.sql");
let input = "select 1d;";
let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0);
assert_eq!(d.positions.len(), 0);
assert!(d.has_fatal_error());
assert_eq!(d.diagnostics.len(), 1);
let change = ChangeFileParams {
path: path.clone(),
version: 1,
changes: vec![ChangeParams {
text: "1".to_string(),
range: Some(TextRange::new(7.into(), 9.into())),
}],
};
let changed = d.apply_file_change(&change);
assert_eq!(d.content, "select 1;");
assert_eq!(changed.len(), 1, "should emit one change");
assert!(matches!(
changed[0],
StatementChange::Added(AddedStatement { .. })
));
assert_eq!(d.positions.len(), 1, "should have one position");
assert!(d.diagnostics.is_empty(), "should have no diagnostics");
assert!(!d.has_fatal_error());
}
#[test]
fn within_statements() {
let path = PgTPath::new("test.sql");
let input = "select id from users;\n\n\n\nselect * from contacts;";
let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0);
assert_eq!(d.positions.len(), 2);
let change = ChangeFileParams {
path: path.clone(),
version: 1,
changes: vec![ChangeParams {
text: "select 1;".to_string(),
range: Some(TextRange::new(23.into(), 23.into())),
}],
};
let changed = d.apply_file_change(&change);
assert_eq!(changed.len(), 5);
assert_eq!(
changed
.iter()
.filter(|c| matches!(c, StatementChange::Deleted(_)))
.count(),
2
);
assert_eq!(
changed
.iter()
.filter(|c| matches!(c, StatementChange::Added(_)))
.count(),
3
);
assert_document_integrity(&d);
}
#[test]
fn within_statements_2() {
let path = PgTPath::new("test.sql");
let input = "alter table deal alter column value drop not null;\n";
let mut d = Document::new(path.clone(), input.to_string(), 0);
assert_eq!(d.positions.len(), 1);
let change1 = ChangeFileParams {
path: path.clone(),
version: 1,
changes: vec![ChangeParams {
text: " ".to_string(),
range: Some(TextRange::new(17.into(), 17.into())),
}],
};
let changed1 = d.apply_file_change(&change1);
assert_eq!(changed1.len(), 1);
assert_eq!(
d.content,
"alter table deal alter column value drop not null;\n"
);
assert_document_integrity(&d);
let change2 = ChangeFileParams {
path: path.clone(),
version: 2,
changes: vec![ChangeParams {
text: " ".to_string(),
range: Some(TextRange::new(18.into(), 18.into())),
}],
};
let changed2 = d.apply_file_change(&change2);
assert_eq!(changed2.len(), 1);
assert_eq!(
d.content,
"alter table deal alter column value drop not null;\n"
);
assert_document_integrity(&d);
let change3 = ChangeFileParams {
path: path.clone(),
version: 3,
changes: vec![ChangeParams {
text: " ".to_string(),
range: Some(TextRange::new(19.into(), 19.into())),
}],
};
let changed3 = d.apply_file_change(&change3);
assert_eq!(changed3.len(), 1);
assert_eq!(
d.content,
"alter table deal alter column value drop not null;\n"
);
assert_document_integrity(&d);
let change4 = ChangeFileParams {
path: path.clone(),
version: 4,
changes: vec![ChangeParams {
text: " ".to_string(),
range: Some(TextRange::new(20.into(), 20.into())),
}],
};
let changed4 = d.apply_file_change(&change4);
assert_eq!(changed4.len(), 1);
assert_eq!(
d.content,
"alter table deal alter column value drop not null;\n"
);
assert_document_integrity(&d);
}
#[test]
fn julians_sample() {
let path = PgTPath::new("test.sql");
let input = "select\n *\nfrom\n test;\n\nselect\n\nalter table test\n\ndrop column id;";
let mut d = Document::new(path.clone(), input.to_string(), 0);
assert_eq!(d.positions.len(), 4);
let change1 = ChangeFileParams {
path: path.clone(),
version: 1,
changes: vec![ChangeParams {
text: " ".to_string(),
range: Some(TextRange::new(31.into(), 31.into())),
}],
};
let changed1 = d.apply_file_change(&change1);
assert_eq!(changed1.len(), 1);
assert_eq!(
d.content,
"select\n *\nfrom\n test;\n\nselect \n\nalter table test\n\ndrop column id;"
);
assert_document_integrity(&d);
// problem: this creates a new statement
let change2 = ChangeFileParams {
path: path.clone(),
version: 2,
changes: vec![ChangeParams {
text: ";".to_string(),
range: Some(TextRange::new(32.into(), 32.into())),
}],
};
let changed2 = d.apply_file_change(&change2);
assert_eq!(changed2.len(), 4);
assert_eq!(
changed2
.iter()
.filter(|c| matches!(c, StatementChange::Deleted(_)))
.count(),
2
);
assert_eq!(
changed2
.iter()
.filter(|c| matches!(c, StatementChange::Added(_)))
.count(),
2
);
assert_document_integrity(&d);
let change3 = ChangeFileParams {
path: path.clone(),
version: 3,
changes: vec![ChangeParams {
text: "".to_string(),
range: Some(TextRange::new(32.into(), 33.into())),
}],
};
let changed3 = d.apply_file_change(&change3);
assert_eq!(changed3.len(), 1);
assert!(matches!(&changed3[0], StatementChange::Modified(_)));
assert_eq!(
d.content,
"select\n *\nfrom\n test;\n\nselect \n\nalter table test\n\ndrop column id;"
);
match &changed3[0] {
StatementChange::Modified(changed) => {
assert_eq!(changed.old_stmt_text, "select ;");
assert_eq!(changed.new_stmt_text, "select");
assert_eq!(changed.change_text, "");
assert_eq!(changed.change_range, TextRange::new(7.into(), 8.into()));
}
_ => panic!("expected modified statement"),
}
assert_document_integrity(&d);
}
#[test]
fn across_statements() {
let path = PgTPath::new("test.sql");
let input = "select id from users;\nselect * from contacts;";
let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0);
assert_eq!(d.positions.len(), 2);
let change = ChangeFileParams {
path: path.clone(),
version: 1,
changes: vec![ChangeParams {
text: ",test from users;\nselect 1;".to_string(),
range: Some(TextRange::new(9.into(), 45.into())),
}],
};
let changed = d.apply_file_change(&change);
assert_eq!(changed.len(), 4);
assert!(matches!(
changed[0],
StatementChange::Deleted(Statement { id: 1, .. })
));
assert!(matches!(
changed[1],
StatementChange::Deleted(Statement { id: 0, .. })
));
assert!(
matches!(&changed[2], StatementChange::Added(AddedStatement { stmt: _, text }) if text == "select id,test from users;")
);
assert!(
matches!(&changed[3], StatementChange::Added(AddedStatement { stmt: _, text }) if text == "select 1;")
);
assert_document_integrity(&d);
}
#[test]
fn append_whitespace_to_statement() {
let path = PgTPath::new("test.sql");
let input = "select id";
let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0);
assert_eq!(d.positions.len(), 1);
let change = ChangeFileParams {
path: path.clone(),
version: 1,
changes: vec![ChangeParams {
text: " ".to_string(),
range: Some(TextRange::new(9.into(), 10.into())),
}],
};
let changed = d.apply_file_change(&change);
assert_eq!(changed.len(), 1);
assert_document_integrity(&d);
}
#[test]
fn apply_changes() {
let path = PgTPath::new("test.sql");
let input = "select id from users;\nselect * from contacts;";
let mut d = Document::new(PgTPath::new("test.sql"), input.to_string(), 0);
assert_eq!(d.positions.len(), 2);
let change = ChangeFileParams {
path: path.clone(),
version: 1,
changes: vec![ChangeParams {
text: ",test from users\nselect 1;".to_string(),
range: Some(TextRange::new(9.into(), 45.into())),
}],
};
let changed = d.apply_file_change(&change);
assert_eq!(changed.len(), 4);
assert_eq!(
changed[0],
StatementChange::Deleted(Statement {
path: path.clone(),
id: 1
})
);
assert_eq!(
changed[1],
StatementChange::Deleted(Statement {
path: path.clone(),
id: 0
})
);
assert_eq!(
changed[2],
StatementChange::Added(AddedStatement {
stmt: Statement {
path: path.clone(),
id: 2
},
text: "select id,test from users".to_string()
})
);
assert_eq!(
changed[3],
StatementChange::Added(AddedStatement {
stmt: Statement {
path: path.clone(),
id: 3
},
text: "select 1;".to_string()
})
);
assert_eq!("select id,test from users\nselect 1;", d.content);
assert_document_integrity(&d);
}
#[test]
fn removing_newline_at_the_beginning() {
let path = PgTPath::new("test.sql");
let input = "\n";
let mut d = Document::new(path.clone(), input.to_string(), 1);
assert_eq!(d.positions.len(), 0);
let change = ChangeFileParams {
path: path.clone(),
version: 2,
changes: vec![ChangeParams {
text: "\nbegin;\n\nselect 1\n\nrollback;\n".to_string(),
range: Some(TextRange::new(0.into(), 1.into())),
}],
};
let changes = d.apply_file_change(&change);
assert_eq!(changes.len(), 3);
assert_document_integrity(&d);
let change2 = ChangeFileParams {
path: path.clone(),
version: 3,
changes: vec![ChangeParams {
text: "".to_string(),
range: Some(TextRange::new(0.into(), 1.into())),
}],
};
let changes2 = d.apply_file_change(&change2);
assert_eq!(changes2.len(), 1);
assert_document_integrity(&d);
}
#[test]
fn apply_changes_at_end_of_statement() {
let path = PgTPath::new("test.sql");
let input = "select id from\nselect * from contacts;";
let mut d = Document::new(path.clone(), input.to_string(), 1);
assert_eq!(d.positions.len(), 2);
let change = ChangeFileParams {
path: path.clone(),
version: 2,
changes: vec![ChangeParams {
text: " contacts;".to_string(),
range: Some(TextRange::new(14.into(), 14.into())),
}],
};
let changes = d.apply_file_change(&change);
assert_eq!(changes.len(), 1);
assert!(matches!(changes[0], StatementChange::Modified(_)));
assert_eq!(