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
//! vehicle

pub use crate::grpc::server::vehicle::*;
pub mod group;

use anyhow::Result;
use chrono::{DateTime, Utc};
use log::debug;
use std::collections::HashMap;
use tokio_postgres::row::Row;
use tokio_postgres::types::Type as PsqlFieldType;
use uuid::Uuid;

use super::base::simple_resource::*;
use super::base::{FieldDefinition, ResourceDefinition};
use crate::common::ArrErr;
use crate::grpc::{GrpcDataObjectType, GrpcField, GrpcFieldOption};

// Generate `From` trait implementations for GenericResource into and from Grpc defined Resource
crate::build_generic_resource_impl_from!();

// Generate grpc server implementations
crate::build_grpc_simple_resource_impl!(vehicle);

impl Resource for ResourceObject<Data> {
    fn get_definition() -> ResourceDefinition {
        ResourceDefinition {
            psql_table: String::from("vehicle"),
            psql_id_cols: vec![String::from("vehicle_id")],
            fields: HashMap::from([
                (
                    String::from("vehicle_model_id"),
                    FieldDefinition::new(PsqlFieldType::UUID, true),
                ),
                (
                    String::from("serial_number"),
                    FieldDefinition::new(PsqlFieldType::TEXT, true),
                ),
                (
                    String::from("registration_number"),
                    FieldDefinition::new(PsqlFieldType::TEXT, true),
                ),
                (
                    String::from("description"),
                    FieldDefinition::new(PsqlFieldType::TEXT, false),
                ),
                (
                    String::from("asset_group_id"),
                    FieldDefinition::new(PsqlFieldType::UUID, false),
                ),
                (
                    String::from("schedule"),
                    FieldDefinition::new(PsqlFieldType::TEXT, false),
                ),
                (
                    String::from("last_maintenance"),
                    FieldDefinition::new(PsqlFieldType::TIMESTAMPTZ, false),
                ),
                (
                    String::from("next_maintenance"),
                    FieldDefinition::new(PsqlFieldType::TIMESTAMPTZ, false),
                ),
                (
                    String::from("hangar_id"),
                    FieldDefinition::new(PsqlFieldType::UUID, false),
                ),
                (
                    String::from("hangar_bay_id"),
                    FieldDefinition::new(PsqlFieldType::UUID, false),
                ),
                (
                    String::from("created_at"),
                    FieldDefinition::new_read_only(PsqlFieldType::TIMESTAMPTZ, true)
                        .set_default(String::from("CURRENT_TIMESTAMP")),
                ),
                (
                    String::from("updated_at"),
                    FieldDefinition::new_read_only(PsqlFieldType::TIMESTAMPTZ, true)
                        .set_default(String::from("CURRENT_TIMESTAMP")),
                ),
                (
                    String::from("deleted_at"),
                    FieldDefinition::new_internal(PsqlFieldType::TIMESTAMPTZ, false),
                ),
            ]),
        }
    }

    fn get_table_indices() -> Vec<String> {
        [
            r#"ALTER TABLE vehicle ADD CONSTRAINT fk_hangar_id FOREIGN KEY(hangar_id) REFERENCES vertiport(vertiport_id)"#.to_owned(),
            r#"ALTER TABLE vehicle ADD CONSTRAINT fk_hangar_bay_id FOREIGN KEY(hangar_bay_id) REFERENCES vertipad(vertipad_id)"#.to_owned(),
        ].to_vec()
    }
}

impl GrpcDataObjectType for Data {
    fn get_field_value(&self, key: &str) -> Result<GrpcField, ArrErr> {
        match key {
            "vehicle_model_id" => Ok(GrpcField::String(self.vehicle_model_id.clone())),
            "serial_number" => Ok(GrpcField::String(self.serial_number.clone())), // ::prost::alloc::string::String,
            "registration_number" => Ok(GrpcField::String(self.registration_number.clone())), // ::prost::alloc::string::String,
            "description" => Ok(GrpcField::Option(GrpcFieldOption::String(
                self.description.clone(),
            ))), // ::core::option::Option<::prost::alloc::string::String>,
            "asset_group_id" => Ok(GrpcField::Option(GrpcFieldOption::String(
                self.asset_group_id.clone(),
            ))), // ::core::option::Option<::prost::alloc::string::String>,
            "schedule" => Ok(GrpcField::Option(GrpcFieldOption::String(
                self.schedule.clone(),
            ))), // ::core::option::Option<::prost::alloc::string::String>,
            "hangar_id" => Ok(GrpcField::Option(GrpcFieldOption::String(
                self.hangar_id.clone(),
            ))), // ::core::option::Option<::prost::alloc::string::String>,
            "hangar_bay_id" => Ok(GrpcField::Option(GrpcFieldOption::String(
                self.hangar_bay_id.clone(),
            ))), //::core::option::Option<::prost_types::Timestamp>,
            "last_maintenance" => Ok(GrpcField::Option(GrpcFieldOption::Timestamp(
                self.last_maintenance.clone(),
            ))), //::core::option::Option<::prost_types::Timestamp>,
            "next_maintenance" => Ok(GrpcField::Option(GrpcFieldOption::Timestamp(
                self.next_maintenance.clone(),
            ))), //::core::option::Option<::prost_types::Timestamp>,
            "created_at" => Ok(GrpcField::Option(GrpcFieldOption::Timestamp(
                self.created_at.clone(),
            ))), //::core::option::Option<::prost_types::Timestamp>,
            "updated_at" => Ok(GrpcField::Option(GrpcFieldOption::Timestamp(
                self.updated_at.clone(),
            ))), //::core::option::Option<::prost_types::Timestamp>,
            _ => Err(ArrErr::Error(format!(
                "Invalid key specified [{}], no such field found",
                key
            ))),
        }
    }
}

#[cfg(not(tarpaulin_include))]
// no_coverage: Can not be tested in unittest until https://github.com/sfackler/rust-postgres/pull/979 has been merged
impl TryFrom<Row> for Data {
    type Error = ArrErr;

    fn try_from(row: Row) -> Result<Self, ArrErr> {
        debug!("(try_from) Converting Row to vehicle::Data: {:?}", row);

        let last_maintenance: Option<prost_wkt_types::Timestamp> = row
            .get::<&str, Option<DateTime<Utc>>>("last_maintenance")
            .map(|val| val.into());
        let next_maintenance: Option<prost_wkt_types::Timestamp> = row
            .get::<&str, Option<DateTime<Utc>>>("next_maintenance")
            .map(|val| val.into());
        let created_at: Option<prost_wkt_types::Timestamp> = row
            .get::<&str, Option<DateTime<Utc>>>("created_at")
            .map(|val| val.into());
        let updated_at: Option<prost_wkt_types::Timestamp> = row
            .get::<&str, Option<DateTime<Utc>>>("updated_at")
            .map(|val| val.into());

        let asset_group_id: Option<Uuid> = row.get("asset_group_id");
        let asset_group_id = asset_group_id.map(|val| val.to_string());

        let hangar_id: Option<Uuid> = row.get("hangar_id");
        let hangar_id = hangar_id.map(|val| val.to_string());

        let hangar_bay_id: Option<Uuid> = row.get("hangar_bay_id");
        let hangar_bay_id = hangar_bay_id.map(|val| val.to_string());

        Ok(Data {
            vehicle_model_id: row.get::<&str, Uuid>("vehicle_model_id").to_string(),
            serial_number: row.get::<&str, String>("serial_number"),
            registration_number: row.get::<&str, String>("registration_number"),
            description: row.get::<&str, Option<String>>("description"),
            asset_group_id,
            schedule: row.get::<&str, Option<String>>("schedule"),
            hangar_id,
            hangar_bay_id,
            last_maintenance,
            next_maintenance,
            created_at,
            updated_at,
        })
    }
}

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

    #[tokio::test]
    async fn test_vehicle_schema() {
        crate::get_log_handle().await;
        ut_info!("(test_vehicle_schema) start");

        let id = Uuid::new_v4().to_string();
        let data = mock::get_data_obj();
        let object: ResourceObject<Data> = Object {
            id,
            data: Some(data.clone()),
        }
        .into();
        test_schema::<ResourceObject<Data>, Data>(object);

        let result = validate::<ResourceObject<Data>>(&data);
        assert!(result.is_ok());
        if let Ok((sql_fields, validation_result)) = result {
            ut_info!("{:?}", sql_fields);
            ut_info!("{:?}", validation_result);
            assert_eq!(validation_result.success, true);
        }
        ut_info!("(test_vehicle_schema) success");
    }

    #[tokio::test]
    async fn test_vehicle_invalid_data() {
        crate::get_log_handle().await;
        ut_info!("(test_vehicle_invalid_data) start");

        let data = Data {
            vehicle_model_id: String::from("INVALID"),
            serial_number: String::from(""),
            registration_number: String::from(""),
            description: Some(String::from("")),
            asset_group_id: Some(String::from("INVALID")),
            schedule: Some(String::from("")),
            hangar_id: Some(String::from("INVALID")),
            hangar_bay_id: Some(String::from("INVALID")),
            last_maintenance: Some(prost_wkt_types::Timestamp {
                seconds: -1,
                nanos: -1,
            }),
            next_maintenance: Some(prost_wkt_types::Timestamp {
                seconds: -1,
                nanos: -1,
            }),
            // The fields below are read_only, should not be returned as invalid
            // by validation even though they are invalid
            created_at: Some(prost_wkt_types::Timestamp {
                seconds: -1,
                nanos: -1,
            }),
            updated_at: Some(prost_wkt_types::Timestamp {
                seconds: -1,
                nanos: -1,
            }),
        };

        let result = validate::<ResourceObject<Data>>(&data);
        assert!(result.is_ok());
        if let Ok((data, validation_result)) = result {
            ut_debug!(
                "(test_vehicle_invalid_data) validation result: {:?}",
                validation_result
            );
            ut_debug!("(test_vehicle_invalid_data) data: {:?}", data);
            assert_eq!(validation_result.success, false);

            let expected_errors = vec![
                "hangar_id",
                "hangar_bay_id",
                "next_maintenance",
                "last_maintenance",
                "vehicle_model_id",
                "asset_group_id",
            ];
            assert_eq!(expected_errors.len(), validation_result.errors.len());
            assert!(contains_field_errors(&validation_result, &expected_errors));
        }
        ut_info!("(test_vehicle_invalid_data) success");
    }

    #[tokio::test]
    async fn test_vehicle_model_type_as_str_name() {
        crate::get_log_handle().await;
        ut_info!("(test_vehicle_model_type_as_str_name) start");

        assert_eq!(VehicleModelType::VtolCargo.as_str_name(), "VTOL_CARGO");
        assert_eq!(
            VehicleModelType::VtolPassenger.as_str_name(),
            "VTOL_PASSENGER"
        );

        ut_info!("(test_vehicle_model_type_as_str_name) success");
    }

    #[tokio::test]
    async fn test_vehicle_model_type_from_str_name() {
        crate::get_log_handle().await;
        ut_info!("(test_vehicle_model_type_from_str_name) start");

        assert_eq!(
            VehicleModelType::from_str_name("VTOL_CARGO"),
            Some(VehicleModelType::VtolCargo)
        );
        assert_eq!(
            VehicleModelType::from_str_name("VTOL_PASSENGER"),
            Some(VehicleModelType::VtolPassenger)
        );

        assert_eq!(VehicleModelType::from_str_name("INVALID"), None);

        ut_info!("(test_vehicle_model_type_from_str_name) success");
    }
}