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
use std::collections::HashMap;

use crate::change::ToField;
use crate::pb::database::{
    table_change::{Operation, PrimaryKey},
    CompositePrimaryKey, DatabaseChanges, TableChange,
};

impl DatabaseChanges {
    pub fn push_change<T: AsRef<str>, K: AsRef<str>>(
        &mut self,
        table: T,
        pk: K,
        ordinal: u64,
        operation: Operation,
    ) -> &mut TableChange {
        let table_change = TableChange::new(table, pk, ordinal, operation);
        self.table_changes.push(table_change);
        return self.table_changes.last_mut().unwrap();
    }

    pub fn push_change_composite<T: AsRef<str>>(
        &mut self,
        table: T,
        keys: HashMap<String, String>,
        ordinal: u64,
        operation: Operation,
    ) -> &mut TableChange {
        let table_change = TableChange::new_composite(table, keys, ordinal, operation);
        self.table_changes.push(table_change);
        return self.table_changes.last_mut().unwrap();
    }
}

impl TableChange {
    pub fn new<T: AsRef<str>, K: AsRef<str>>(
        entity: T,
        pk: K,
        ordinal: u64,
        operation: Operation,
    ) -> TableChange {
        TableChange {
            table: entity.as_ref().to_string(),
            primary_key: Some(PrimaryKey::Pk(pk.as_ref().to_string())),
            ordinal,
            operation: operation as i32,
            fields: vec![],
        }
    }

    pub fn new_composite<T: AsRef<str>>(
        entity: T,
        keys: HashMap<String, String>,
        ordinal: u64,
        operation: Operation,
    ) -> TableChange {
        TableChange {
            table: entity.as_ref().to_string(),
            primary_key: Some(PrimaryKey::CompositePk(CompositePrimaryKey { keys })),
            ordinal,
            operation: operation as i32,
            fields: vec![],
        }
    }

    pub fn change<N: AsRef<str>, T: ToField>(&mut self, name: N, change: T) -> &mut TableChange {
        self.fields.push(change.to_field(name));
        self
    }
}