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
use crate::{
    env::EnvClient,
    external::{env_push_stack, read_raw, update_raw, write_raw},
    symbol, to_fixed, SdkError,
};
use serde::{Deserialize, Serialize};
use soroban_sdk::xdr::{Limits, WriteXdr};

#[derive(Clone, Deserialize, Serialize)]
pub struct TypeWrap(pub Vec<u8>);

impl TypeWrap {
    pub fn to_i128(&self) -> i128 {
        let bytes = to_fixed::<u8, 16>(self.0.clone());
        i128::from_be_bytes(bytes)
    }

    pub fn to_u64(&self) -> u64 {
        let bytes = to_fixed::<u8, 8>(self.0.clone());
        u64::from_be_bytes(bytes)
    }
}

/// Object returned by database reads.
/// It's a wrapper for table rows.
#[derive(Clone, Deserialize, Serialize)]
pub struct TableRows {
    /// Rows within the table
    pub rows: Vec<TableRow>,
}

/// Condition clauses that can be applied when reading the
/// database.
pub enum Condition {
    /// A given column is equal to a certain object.
    ColumnEqualTo(String, Vec<u8>),
}

/// Wraps a single row.
#[derive(Clone, Deserialize, Serialize)]
pub struct TableRow {
    /// Vector of wrapped columns.
    pub row: Vec<TypeWrap>,
}

mod unsafe_helpers {
    use crate::external::env_push_stack;

    pub(crate) unsafe fn push_head(table_name: i64, columns: Vec<i64>) {
        env_push_stack(table_name as i64);
        env_push_stack(columns.len() as i64);

        for col in columns {
            env_push_stack(col)
        }
    }

    pub(crate) unsafe fn push_data_segments(segments: Vec<(i64, i64)>) {
        env_push_stack(segments.len() as i64);

        for segment in segments {
            env_push_stack(segment.0);
            env_push_stack(segment.1);
        }
    }
}

#[derive(Clone, Default)]
pub struct Database {}

impl Database {
    pub fn read_table(table_name: &str, columns: &[&str]) -> Result<TableRows, SdkError> {
        let table_name = symbol::Symbol::try_from_bytes(table_name.as_bytes()).unwrap();
        let cols = columns
            .into_iter()
            .map(|col| symbol::Symbol::try_from_bytes(col.as_bytes()).unwrap().0 as i64)
            .collect::<Vec<i64>>();

        unsafe { unsafe_helpers::push_head(table_name.0 as i64, cols) }

        let (status, offset, size) = unsafe { read_raw() };
        SdkError::express_from_status(status)?;

        let table = {
            let memory: *const u8 = offset as *const u8;

            let slice = unsafe { core::slice::from_raw_parts(memory, size as usize) };

            if let Ok(table) = bincode::deserialize::<TableRows>(slice) {
                table
            } else {
                return Err(SdkError::Conversion);
            }
        };

        Ok(table)
    }

    pub fn write_table(
        table_name: &str,
        columns: &[&str],
        segments: &[&[u8]],
    ) -> Result<(), SdkError> {
        let table_name = symbol::Symbol::try_from_bytes(table_name.as_bytes()).unwrap();
        let cols = columns
            .into_iter()
            .map(|col| symbol::Symbol::try_from_bytes(col.as_bytes()).unwrap().0 as i64)
            .collect::<Vec<i64>>();

        let segments = segments
            .into_iter()
            .map(|segment| (segment.as_ptr() as i64, segment.len() as i64))
            .collect::<Vec<(i64, i64)>>();

        unsafe {
            unsafe_helpers::push_head(table_name.0 as i64, cols);
            unsafe_helpers::push_data_segments(segments);
        }

        let status = unsafe { write_raw() };
        SdkError::express_from_status(status)
    }

    pub fn update_table(
        table_name: &str,
        columns: &[&str],
        segments: &[&[u8]],
        conditions: &[Condition],
    ) -> Result<(), SdkError> {
        let table_name = symbol::Symbol::try_from_bytes(table_name.as_bytes()).unwrap();
        let cols = columns
            .into_iter()
            .map(|col| symbol::Symbol::try_from_bytes(col.as_bytes()).unwrap().0 as i64)
            .collect::<Vec<i64>>();

        let segments = segments
            .into_iter()
            .map(|segment| (segment.as_ptr() as i64, segment.len() as i64))
            .collect::<Vec<(i64, i64)>>();

        unsafe {
            unsafe_helpers::push_head(table_name.0 as i64, cols);
            unsafe_helpers::push_data_segments(segments);

            env_push_stack(conditions.len() as i64);

            let mut args = Vec::new();
            for cond in conditions {
                let (colname, operator, value) = match cond {
                    Condition::ColumnEqualTo(colname, value) => (colname, 0, value),
                };

                env_push_stack(
                    symbol::Symbol::try_from_bytes(colname.as_bytes())
                        .unwrap()
                        .0 as i64,
                );
                env_push_stack(operator as i64);

                args.push((value.as_ptr() as i64, value.len() as i64))
            }

            env_push_stack(args.len() as i64);

            for segment in args {
                env_push_stack(segment.0);
                env_push_stack(segment.1);
            }
        }

        let status = unsafe { update_raw() };
        SdkError::express_from_status(status)
    }
}

/// Simple wrapper for building conditions.
pub struct UpdateTable {
    conditions: Vec<Condition>,
}

impl UpdateTable {
    /// Creates a new table update object.
    pub fn new() -> Self {
        Self { conditions: vec![] }
    }

    /// Adds a new condition in the update according to which a given column
    /// should be equal to an XDR object.
    pub fn column_equal_to_xdr(&mut self, column: impl ToString, xdr: &impl WriteXdr) -> &mut Self {
        let bytes = xdr.to_xdr(Limits::none()).unwrap();
        let condition = Condition::ColumnEqualTo(column.to_string(), bytes);
        self.conditions.push(condition);

        self
    }

    /// Adds a new condition in the update according to which a given column
    /// should be equal to the matching bytes array.
    ///
    /// This filter should be used when dealing with non-XDR types. Serialization
    /// must be carried by the implementor.
    pub fn column_equal_to_bytes(&mut self, column: impl ToString, bytes: &[u8]) -> &mut Self {
        let condition = Condition::ColumnEqualTo(column.to_string(), bytes.to_vec());
        self.conditions.push(condition);

        self
    }

    /// Executes the update.
    pub fn execute(&mut self, interact: &impl DatabaseInteract) {
        interact.update(&EnvClient::empty(), &self.conditions)
    }
}

/// Trait that DatabaseDerive structures implement
pub trait DatabaseInteract {
    /// Reads from the database into a vector of `Self`.
    fn read_to_rows(env: &EnvClient) -> Vec<Self>
    where
        Self: Sized;

    /// Inserts a row `Self` into the database table.
    fn put(&self, env: &EnvClient);

    /// Updates an existing row with `Self` into the database table
    /// using the provided conditions as update filter.
    fn update(&self, env: &EnvClient, conditions: &[Condition]);
}