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
use crate::{db_anti_corruption::Connection, DbError, Row, ToSql};

use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json;
use std::ops::Deref;
use uuid::Uuid;

/// Helper function to create a SQL SELECT statement for a DbEntity table.
/// This method returns the (id, version, data) tuple
pub fn select_part(table_name: &str, distinct: bool, alias: Option<&str>) -> String {
    let (alias, table_name) = if let Some(alias) = alias {
        (format!("{}.", alias), format!("{} {}", table_name, alias))
    } else {
        ("".to_owned(), table_name.to_owned())
    };
    format!(
        "{select} {alias}id, {alias}version, {alias}data FROM {table_name}",
        select = if distinct {
            "SELECT DISTINCT"
        } else {
            "SELECT"
        },
        table_name = table_name,
        alias = alias
    )
}

/// Helper function to create the a SQL ORDER BY statement.
///
/// *order_by* clauses are joined by ", " and *alias* is prepended with "."
/// to each *order_by* element.
pub fn make_sort_statement(order_by: &[&str], alias: Option<&str>) -> String {
    match alias {
        Some(alias) => order_by
            .iter()
            .map(|&item| format!("{}.{}", alias, item))
            .collect::<Vec<String>>()
            .join(", "),
        _ => order_by.join(", "),
    }
}

/// This trait is maps data in a data table and
/// it's used along with DbEntity structure
pub trait DbData: Serialize + DeserializeOwned {
    /// The name of the db table where the implementing struct is mapped to.
    fn table_name() -> &'static str;

    /// Table name from instance
    fn table_name1(&self) -> &'static str {
        Self::table_name()
    }
    /// Convenience function that returns the select part for the associated db table.
    fn select_part() -> String {
        select_part(Self::table_name(), false, None)
    }

    /// Select part from instance
    fn select_part1(&self) -> String {
        Self::select_part()
    }

    /// returns the "id" column of the db row (same as DbEntity::id). If the DbData is not connected to the db, then result is None
    fn id(&self) -> Option<Uuid>;
    /// returns the "version" column of the db row (same as DbEntity::version). If the DbData is not connected to the db, then result is None
    fn version(&self) -> Option<i32>;

    fn set_id(&mut self, uuid: Uuid);
    fn set_version(&mut self, version: i32);
}

/// This struct is used to create a mapping for a data table.
pub struct DbEntity<T>
where
    T: DbData + Serialize + DeserializeOwned,
{
    /// This is the effective primary key of the record. Its also used to build relations with other tables
    pub id: Uuid,
    /// This field is used as a record check and identifies possible conflicts for parallel operations.
    /// version should always autoinc on record update
    pub version: i32,
    /// The real information that a data table record is containing
    pub data: T,
}

impl<T> DbEntity<T>
where
    T: DbData + Serialize + DeserializeOwned,
{
    /// Simple method used to create a new record
    pub fn new(id: Uuid, version: i32, data: T) -> Self {
        Self { id, version, data }
    }

    /// Given a data this method uses DbData#find_table_id_and_version to find a possible candidate for record or creates
    /// a new one that will need to be persisted with the insert method.
    pub fn from_data(data: T) -> Self {
        match (data.id(), data.version()) {
            (Some(uuid), Some(version)) => Self {
                id: uuid,
                version,
                data,
            },
            _ => Self {
                id: Uuid::new_v4(),
                version: 0,
                data,
            },
        }
    }

    /// Given a database row (id, version, data) returns a DbEntity.
    pub fn from_row(row: &Row) -> Result<Self, DbError> {
        let uuid: Uuid = row.get(0);
        let version: i32 = row.get(1);
        let mut data: T = serde_json::from_value(row.get::<_, serde_json::Value>(2))
            .map_err(DbError::from)
            .unwrap();
        data.set_id(uuid);
        data.set_version(version);
        Ok(DbEntity::new(uuid, version, data))
    }

    /// Given a database rows of (id, version, data) tuples returns a Vec of DbEntity.
    pub fn from_rows(rows: &[Row]) -> Result<Vec<Self>, DbError> {
        if rows.is_empty() {
            Ok(vec![])
        } else {
            Ok(rows
                .iter()
                .map(|row| DbEntity::from_row(&row).unwrap())
                .collect())
        }
    }

    fn out_of_sync_err(&self) -> DbError {
        DbError::new(&format!("{}:{} out of sync", self.id, self.version), None)
    }

    /// Inserts a new record into the associated table
    pub async fn insert<'a>(&mut self, conn: &Connection) -> Result<(), DbError> {
        let prepared_s = conn
            .prepare(&format!(
                "INSERT INTO  {table_name} (id, version, data) VALUES ($1, $2+1, $3)",
                table_name = T::table_name()
            ))
            .await?;
        conn.execute(
            &prepared_s,
            &[
                &self.id,
                &self.version,
                &serde_json::to_value(&self.data).unwrap(),
            ],
        )
        .await?;
        self.version += 1;
        self.data.set_id(self.id.clone());
        self.data.set_version(self.version);
        Ok(())
    }

    /// Persists the record
    pub async fn update(&mut self, conn: &Connection) -> Result<(), DbError> {
        let prepared_s = conn
            .prepare(&format!(
                "UPDATE {table_name} SET
            version=$2+1,
            data=$3
            WHERE
            id = $1 AND
            version = $2",
                table_name = T::table_name()
            ))
            .await?;
        let updated = conn
            .execute(
                &prepared_s,
                &[
                    &self.id,
                    &self.version,
                    &serde_json::to_value(&self.data).unwrap(),
                ],
            )
            .await?
            == 1;
        if updated {
            self.version += 1;
            self.data.set_version(self.version);
            Ok(())
        } else {
            Err(self.out_of_sync_err())
        }
    }

    /// Performs a record deletion
    pub async fn delete(&mut self, conn: &Connection) -> Result<(), DbError> {
        let prepared_s = conn
            .prepare(&format!(
                "DELETE FROM {table_name}
            WHERE
            id = $1 AND
            version = $2",
                table_name = T::table_name()
            ))
            .await?;
        let deleted = conn
            .execute(&prepared_s, &[&self.id, &self.version])
            .await?
            == 1;
        if deleted {
            self.version = 0;
            Ok(())
        } else {
            Err(self.out_of_sync_err())
        }
    }

    /// Searches for a record where filter over data column (JSONB) matches provided parameters.
    /// ## Example
    /// ```ignore
    /// DbEntity::<User>::find_by(db_conn, ("data->>'user_name'=$1", &["some_name"]));
    /// ```
    pub async fn find_by(
        conn: &Connection,
        filter: (&str, &[&(dyn ToSql + Sync)]),
    ) -> Result<Option<Self>, DbError> {
        let prepared_s = conn
            .prepare(&format!(
                "{select_part} WHERE {filter}",
                select_part = T::select_part(),
                filter = filter.0,
            ))
            .await?;

        let result = conn.query(&prepared_s, filter.1).await?;
        if result.is_empty() {
            Ok(None)
        } else {
            let row = &result.get(0).unwrap();
            DbEntity::from_row(&row).map(Some)
        }
    }

    /// Searching all matching records defined by filter clause (first element of the filter tuple)\
    /// A sorting clause can be given.\
    /// Limit and offset define the perimeter of the query result.
    /// ## Example
    /// ```ignore
    /// DbEntity::<User>::find_all(
    ///    db_conn,
    ///    (
    ///        "data->>'user_name'=$1",
    ///        &["some_name"],
    ///        Some(&["data->>'user_name' DESC"]),
    ///        0,
    ///        100,
    ///    ),
    /// );
    /// ```
    pub async fn find_all(
        conn: &Connection,
        filter: Option<(&str, &[&(dyn ToSql + Sync)])>,
        sorting: Option<&[&str]>,
        offset: i64,
        limit: i64,
    ) -> Result<Vec<Self>, DbError> {
        let prepared_s = conn.prepare(&format!(
            "{select_part}{where}{sorting}{offset}{limit}",
            select_part = T::select_part(),
            where = match filter {
                Some(where_clause) => format!(" WHERE {}",where_clause.0),
                None => String::from(""),
            },
            sorting = match sorting {
                Some(sorting_statement) => format!(" ORDER BY {}", make_sort_statement(sorting_statement, None) ),
                None => String::from("")
            },
            offset = format!(" OFFSET ${}", match filter {
                    Some(filter) => filter.1.len() + 1,
                    None => 1
            }),
            limit = if limit < 0 {
                    "".to_string()
                } else {
                    format!(" LIMIT ${}", match filter {
                        Some(filter) => filter.1.len() + 2,
                        None => 2
                })
            },
        )).await?;

        let params: Vec<&(dyn ToSql + Sync)> = if limit < 0 {
            match filter {
                Some(filter) => [filter.1, &[&offset]].concat(),
                None => vec![&offset],
            }
        } else {
            match filter {
                Some(filter) => [filter.1, &[&offset, &limit]].concat(),
                None => vec![&offset, &limit],
            }
        };
        let result = conn.query(&prepared_s, &params[..]).await?;
        DbEntity::from_rows(&result)
    }
}

impl<T> Deref for DbEntity<T>
where
    T: DbData + Serialize + DeserializeOwned,
{
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.data
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_derive::*;

    #[derive(Serialize, Deserialize, Debug)]
    pub struct User {
        pub user_name: String,
        pub first_name: String,
        pub last_name: String,
    }

    impl DbData for User {
        fn table_name() -> &'static str {
            "intrared.users"
        }
        fn id(&self) -> Option<Uuid> {
            None
        }

        fn version(&self) -> Option<i32> {
            None
        }
        fn set_id(&mut self, _uuid: Uuid) {}
        fn set_version(&mut self, _version: i32) {}
    }

    impl User {
        fn new(user_name: &str, first_name: &str, last_name: &str) -> Self {
            User {
                user_name: user_name.to_string(),
                first_name: first_name.to_string(),
                last_name: last_name.to_string(),
            }
        }
    }

    #[test]
    fn test_schema_instance_retrieval() {
        let user1 = User::new("user_name", "John", "Doe");

        assert!(user1.table_name1() == User::table_name());
    }

    #[test]
    fn test_dbentity_deref() {
        let full_name =
            |user: &User| -> String { format!("{} {}", user.last_name, user.first_name) };

        let entity_status =
            |entity: &DbEntity<User>| -> String { format!("{}:{}", entity.id, entity.version) };

        let uuid = Uuid::new_v4();
        let data = User::new("user_name", "John", "Doe");

        let expected_status = format!("{}:0", uuid);
        let expected_full_name = full_name(&data);

        let user_dbe = DbEntity::new(uuid, 0, data);

        assert_eq!(entity_status(&user_dbe), expected_status);
        assert_eq!(full_name(&user_dbe), expected_full_name);
    }

    #[test]
    fn test_select_extra_columns() {
        #[derive(Serialize, Deserialize)]
        struct Test {};

        impl DbData for Test {
            fn table_name() -> &'static str {
                "intrared.test"
            }

            fn select_part() -> String {
                format!(
                    "{}, {}",
                    select_part(Self::table_name(), false, None),
                    "another_col"
                )
            }

            fn id(&self) -> Option<Uuid> {
                None
            }

            fn version(&self) -> Option<i32> {
                None
            }
            fn set_id(&mut self, _uuid: Uuid) {}
            fn set_version(&mut self, _version: i32) {}
        };
        let t = Test {};

        assert_eq!(Test::select_part(), t.select_part1());
    }
}