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
//! Domo Dataset API
//!
//! # [`DatasetsRequestBuilder`](`crate::pitchfork::DatasetsRequestBuilder`) implements all available dataset API endpoints and functionality
//!
//! Additional Resources:
//! - [Domo Dataset API Reference](https://developer.domo.com/docs/dataset-api-reference/dataset)
use super::policy::Policy;
use super::user::Owner;
use crate::util::csv::{ deserialize_csv_str, serialize_to_csv_str};
use serde_json::json;
use serde_json::Value;

use crate::error::{PitchforkError, PitchforkErrorKind};
use crate::pitchfork::{DatasetsRequestBuilder, DomoRequest};
use log::debug;
use reqwest::Method;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::collections::HashMap;
use std::error::Error;
use std::marker::PhantomData;
use std::str::{self, FromStr};

impl<'t> DatasetsRequestBuilder<'t, Dataset> {
    /// Retreives details for a `Dataset`
    ///
    /// # Example
    /// ```no_run
    /// # use domo_pitchfork::error::PitchforkError;
    /// use domo_pitchfork::pitchfork::DomoPitchfork;
    /// let domo = DomoPitchfork::with_token("token");
    /// let dataset_info = domo.datasets().info("dataset id")?;
    /// println!("Dataset Details: \n{:#?}", dataset_info);
    /// # Ok::<(), PitchforkError>(())
    /// ```
    ///
    pub fn info(mut self, dataset_id: &str) -> Result<Dataset, PitchforkError> {
        self.url.push_str(dataset_id);
        let req = Self {
            method: Method::GET,
            auth: self.auth,
            url: self.url,
            resp_t: PhantomData,
            body: None,
        };
        req.retrieve_and_deserialize_json()
    }

    /// List Datasets starting from a given offset up to a given limit.
    /// Max limit is 50.
    /// # Example
    /// ```no_run
    /// # use domo_pitchfork::error::PitchforkError;
    /// use domo_pitchfork::pitchfork::DomoPitchfork;
    /// let domo = DomoPitchfork::with_token("token");
    /// let dataset_list = domo.datasets().list(5,0)?;
    /// dataset_list.iter().map(|ds| println!("Dataset Name: {}", ds.name.as_ref().unwrap()));
    /// # Ok::<(),PitchforkError>(())
    /// ```
    pub fn list(mut self, limit: u32, offset: u32) -> Result<Vec<Dataset>, PitchforkError> {
        // TODO: impl sort optional query param
        self.url
            .push_str(&format!("?limit={}&offset={}", limit, offset));
        let req = Self {
            method: Method::GET,
            auth: self.auth,
            url: self.url,
            resp_t: PhantomData,
            body: None,
        };
        let ds_list = serde_json::from_reader(req.send_json()?)?;
        Ok(ds_list)
    }

    /// Create a new empty Domo Dataset.
    pub fn create(self, ds_meta: &DatasetSchema) -> Result<Dataset, PitchforkError> {
        let body = serde_json::to_string(ds_meta)?;
        debug!("body: {}", body);
        let req = Self {
            method: Method::POST,
            auth: self.auth,
            url: self.url,
            resp_t: PhantomData,
            body: Some(body),
        };
        req.retrieve_and_deserialize_json()
    }

    /// Delete the dataset for the given id.
    /// This is destructive and cannot be reversed.
    /// # Example
    /// ```no_run
    /// # use domo_pitchfork::pitchfork::DomoPitchfork;
    /// # let token = "token_here";
    /// let domo = DomoPitchfork::with_token(&token);
    ///
    /// // if it fails to delete print err msg.
    /// if let Err(e) = domo.datasets().delete("ds_id") {
    ///     println!("{}", e)
    /// }
    /// ```
    pub fn delete(mut self, dataset_id: &str) -> Result<(), PitchforkError> {
        self.url.push_str(dataset_id);
        let req = Self {
            method: Method::DELETE,
            auth: self.auth,
            url: self.url,
            resp_t: PhantomData,
            body: None,
        };
        req.send_json()?;
        Ok(())
    }

    /// Modify an existing Domo Dataset.
    pub fn modify(
        mut self,
        dataset_id: &str,
        ds_meta: &DatasetSchema,
    ) -> Result<Dataset, PitchforkError> {
        self.url.push_str(dataset_id);
        let body = serde_json::to_string(ds_meta)?;
        debug!("body: {}", body);
        let req = Self {
            method: Method::PUT,
            auth: self.auth,
            url: self.url,
            resp_t: PhantomData,
            body: Some(body),
        };
        let ds = serde_json::from_reader(req.send_json()?)?;
        Ok(ds)
    }

    /// Returns data from the DataSet based on a SQL query.
    /// # Example
    /// ```no_run
    /// # use domo_pitchfork::pitchfork::DomoPitchfork;
    /// # let token = "token_here";
    /// let domo = DomoPitchfork::with_token(&token);
    /// let dq = domo.datasets()
    ///             .query_data("ds_id", "SELECT * FROM table");
    /// match dq {
    ///     Ok(query_result) => {
    ///         println!("{:#?}", query_result);
    ///     },
    ///     Err(e) => println!("{}", e),
    /// };
    /// ```
    /// [Domo Dataset API Query Reference](https://developer.domo.com/docs/dataset-api-reference/dataset#Query%20a%20DataSet)
    pub fn query_data(
        mut self,
        dataset_id: &str,
        sql_query: &str,
    ) -> Result<DatasetQueryData, PitchforkError> {
        self.url.push_str(&format!("query/execute/{}", dataset_id));
        let body = json!({ "sql": sql_query });
        let req = Self {
            method: Method::POST,
            auth: self.auth,
            url: self.url,
            resp_t: PhantomData,
            body: Some(body.to_string()),
        };
        let dq = serde_json::from_reader(req.send_json()?)?;
        Ok(dq)
    }

    /// Retrieve data from a Domo Dataset as a csv string.
    pub fn download_data(
        mut self,
        dataset_id: &str,
        include_csv_headers: bool,
    ) -> Result<String, PitchforkError> {
        self.url.push_str(&format!(
            "{}/data?includeHeader={}",
            dataset_id, include_csv_headers
        ));
        self.send_json()?.text().map_err(PitchforkError::from)
    }

    /// Retrieve data from a Domo Dataset and Deserialize the retrieved data into a Vec<T>.
    pub fn get_data<T: DeserializeOwned>(
        mut self,
        dataset_id: &str,
    ) -> Result<Vec<T>, PitchforkError> {
        self.url.push_str(&format!(
            "{}/data?includeHeader=true",
            dataset_id
        ));
        deserialize_csv_str(&self.send_json()?.text().map_err(PitchforkError::from)?)
    }

    /// Upload data to the Domo Dataset.
    pub fn upload_from_str(
        mut self,
        dataset_id: &str,
        data_rows: String,
    ) -> Result<(), PitchforkError> {
        self.url.push_str(&format!("{}/data", dataset_id));
        let req = Self {
            method: Method::PUT,
            auth: self.auth,
            url: self.url,
            resp_t: PhantomData,
            body: Some(data_rows),
        };
        req.send_csv()?;
        Ok(())
    }

    /// Upload data to the Domo Dataset.
    pub fn upload_serializable<T: Serialize>(
        mut self,
        dataset_id: &str,
        data: &[T],
    ) -> Result<(), PitchforkError> {
        self.url.push_str(&format!("{}/data", dataset_id));
        let req = Self {
            method: Method::PUT,
            auth: self.auth,
            url: self.url,
            resp_t: PhantomData,
            body: Some(
                serialize_to_csv_str(&data)
                    .map_err(|e| PitchforkError::from(e).with_kind(PitchforkErrorKind::Csv))?,
            ),
        };
        req.send_csv()?;
        Ok(())
    }

    /// Retrieves details of a given policy for a Dataset
    pub fn pdp_policy_info(
        mut self,
        dataset_id: &str,
        policy_id: u32,
    ) -> Result<Policy, PitchforkError> {
        self.url
            .push_str(&format!("{}/policies/{}", dataset_id, policy_id));
        let req = Self {
            method: Method::GET,
            auth: self.auth,
            url: self.url,
            resp_t: PhantomData,
            body: None,
        };
        let dq = serde_json::from_reader(req.send_json()?)?;
        Ok(dq)
    }

    /// Add a new PDP Policy to a dataset.
    pub fn add_pdp_policy(
        mut self,
        dataset_id: &str,
        policy: &Policy,
    ) -> Result<Policy, PitchforkError> {
        self.url.push_str(&format!("{}/policies", dataset_id));
        let body = serde_json::to_string(policy)?;
        debug!("body: {}", body);
        let req = Self {
            method: Method::POST,
            auth: self.auth,
            url: self.url,
            resp_t: PhantomData,
            body: Some(body),
        };
        let ds = serde_json::from_reader(req.send_json()?)?;
        Ok(ds)
    }

    /// Modify an existing PDP Policy on a dataset.
    pub fn modify_pdp_policy(
        mut self,
        dataset_id: &str,
        policy_id: u32,
        policy: &Policy,
    ) -> Result<Policy, PitchforkError> {
        self.url
            .push_str(&format!("{}/policies/{}", dataset_id, policy_id));
        let body = serde_json::to_string(policy)?;
        debug!("body: {}", body);
        let req = Self {
            method: Method::PUT,
            auth: self.auth,
            url: self.url,
            resp_t: PhantomData,
            body: Some(body),
        };
        let ds = serde_json::from_reader(req.send_json()?)?;
        Ok(ds)
    }

    /// Delete a PDP policy from a Dataset
    pub fn delete_pdp_policy(
        mut self,
        dataset_id: &str,
        policy_id: u32,
    ) -> Result<(), PitchforkError> {
        self.url
            .push_str(&format!("{}/policies/{}", dataset_id, policy_id));
        let req = Self {
            method: Method::DELETE,
            auth: self.auth,
            url: self.url,
            resp_t: PhantomData,
            body: None,
        };
        req.send_json()?;
        Ok(())
    }

    /// Retrieves a list of all policies for a Dataset
    pub fn policies(mut self, dataset_id: &str) -> Result<Vec<Policy>, PitchforkError> {
        self.url.push_str(&format!("{}/policies", dataset_id));
        let req = Self {
            method: Method::GET,
            auth: self.auth,
            url: self.url,
            resp_t: PhantomData,
            body: None,
        };
        let dq = serde_json::from_reader(req.send_json()?)?;
        Ok(dq)
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DatasetQueryData {
    pub datasource: String,
    pub columns: Vec<String>,
    pub metadata: Vec<DataQueryMetadata>,
    pub rows: Vec<Vec<Value>>, // Array of Arrays
    #[serde(rename = "numRows")]
    pub num_rows: u64,
    #[serde(rename = "numColumns")]
    pub num_columns: u16,
    #[serde(rename = "fromcache")]
    pub from_cache: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DataQueryMetadata {
    #[serde(rename = "type")]
    pub data_type: String,
    #[serde(rename = "dataSourceId")]
    pub data_source_id: String,
    #[serde(rename = "maxLength")]
    pub max_length: i32,
    #[serde(rename = "minLength")]
    pub min_length: i32,
    #[serde(rename = "periodIndex")]
    pub period_index: i32,
}
///[Dataset object](https://developer.domo.com/docs/dataset-api-reference/dataset#The%20DataSet%20object)
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Dataset {
    pub id: String,
    pub name: Option<String>,
    pub description: Option<String>,
    pub columns: Option<i32>,
    pub rows: Option<i32>,
    pub schema: Option<Schema>,
    #[serde(rename = "createdAt")]
    pub created_at: Option<String>,
    #[serde(rename = "updatedAt")]
    pub updated_at: Option<String>,
    #[serde(rename = "dataCurrentAt")]
    pub data_current_at: Option<String>,
    #[serde(rename = "pdpEnabled")]
    pub pdp_enabled: Option<bool>,
    pub owner: Option<Owner>,
    pub policies: Option<Vec<Policy>>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DatasetSchema {
    pub name: String,
    pub description: String,
    pub rows: u32,
    pub schema: Schema,
}

// TODO: Fix Link
///[Schema Object](https://developer.domo.com/)
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Schema {
    #[serde(rename = "columns")]
    pub columns: Vec<Column>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Column {
    #[serde(rename = "type")]
    pub column_type: String,
    pub name: String,
}

impl DatasetSchema {
    pub fn from_hashmap(
        name: String,
        description: String,
        col_schema: &HashMap<String, FieldType>,
    ) -> Self {
        Self {
            name,
            description,
            rows: 0,
            schema: Schema::from_hashmap(&col_schema),
        }
    }
}

impl Schema {
    pub fn from_hashmap(cols: &HashMap<String, FieldType>) -> Self {
        let mut columns: Vec<Column> = Vec::new();
        for (col, typ) in cols {
            let typ_str = match typ {
                FieldType::TUnicode => "STRING".to_string(),
                FieldType::TFloat => "DOUBLE".to_string(),
                FieldType::TInteger => "LONG".to_string(),
                _ => "STRING".to_string(),
            };
            columns.push(Column {
                column_type: typ_str,
                name: col.to_string(),
            })
        }
        Self { columns }
    }
}

pub enum DomoDataType {
    STRING,
    LONG,
    DECIMAL,
    DOUBLE,
    DATETIME,
    DATE,
}

impl DomoDataType {
    // TODO: document where this is needed
    #[allow(dead_code)]
    fn from_fieldtype(typ: FieldType) -> Self {
        match typ {
            FieldType::TNull | FieldType::TUnicode => DomoDataType::STRING,
            // TUnicode => DomoDataType::STRING,
            FieldType::TInteger => DomoDataType::LONG,
            FieldType::TFloat => DomoDataType::DECIMAL,
            _ => DomoDataType::STRING,
        }
    }
}

impl From<DomoDataType> for String {
    fn from(domo_type: DomoDataType) -> Self {
        match domo_type {
            DomoDataType::STRING => "STRING".to_owned(),
            DomoDataType::LONG => "LONG".to_owned(),
            DomoDataType::DECIMAL => "DOUBLE".to_owned(),
            DomoDataType::DOUBLE => "DOUBLE".to_owned(),
            DomoDataType::DATETIME => "DATETIME".to_owned(),
            DomoDataType::DATE => "DATE".to_owned(),
        }
    }
}

// This introduces a type alias so that we can conveniently reference our
// record type.
pub type Record = HashMap<String, String>;
pub type CsvColumnTypes = HashMap<String, FieldType>;

pub fn check_field_type(rec: &Record, cols: &mut CsvColumnTypes) -> Result<(), Box<dyn Error>> {
    for (key, value) in rec.iter() {
        let typ = FieldType::from_sample(value.as_bytes());
        let cur_typ = cols.entry(key.to_string()).or_insert(typ);
        cur_typ.merge(typ);
    }
    Ok(())
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FieldType {
    TUnknown,
    TNull,
    TUnicode,
    TFloat,
    TInteger,
}

impl FieldType {
    pub fn merge(&mut self, other: Self) {
        *self =
            match (*self, other) {
                (FieldType::TUnicode, FieldType::TUnicode) => FieldType::TUnicode,
                (FieldType::TFloat, FieldType::TFloat) => FieldType::TFloat,
                (FieldType::TInteger, FieldType::TInteger) => FieldType::TInteger,
                // Null does not impact the type.
                (FieldType::TNull, any) | (any, FieldType::TNull) => any,
                // There's no way to get around an unknown.
                (FieldType::TUnknown, _) | (_, FieldType::TUnknown) => FieldType::TUnknown,
                // Integers can degrade to floats.
                (FieldType::TFloat, FieldType::TInteger)
                | (FieldType::TInteger, FieldType::TFloat) => FieldType::TFloat,
                // Numbers can degrade to Unicode strings.
                (FieldType::TUnicode, FieldType::TFloat)
                | (FieldType::TFloat, FieldType::TUnicode) => FieldType::TUnicode,
                (FieldType::TUnicode, FieldType::TInteger)
                | (FieldType::TInteger, FieldType::TUnicode) => FieldType::TUnicode,
            };
    }

    pub fn from_sample(sample: &[u8]) -> Self {
        if sample.is_empty() {
            return FieldType::TNull;
        }
        let string = match str::from_utf8(sample) {
            Err(_) => return FieldType::TUnknown,
            Ok(s) => s,
        };
        if string.parse::<i64>().is_ok() {
            return FieldType::TInteger;
        }
        if string.parse::<f64>().is_ok() {
            return FieldType::TFloat;
        }
        FieldType::TUnicode
    }

    pub fn is_number(self) -> bool {
        self == FieldType::TFloat || self == FieldType::TInteger
    }

    pub fn is_null(self) -> bool {
        self == FieldType::TNull
    }
}

impl Default for FieldType {
    // The default is the most specific type.
    // Type inference proceeds by assuming the most specific type and then
    // relaxing the type as counter-examples are found.
    fn default() -> Self {
        FieldType::TNull
    }
}

// TODO: Check if this is actually needed
#[allow(dead_code)]
fn from_bytes<T: FromStr>(bytes: &[u8]) -> Option<T> {
    str::from_utf8(bytes).ok().and_then(|s| s.parse().ok())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    #[test]
    fn test_dataset_schema_serialization() {
        let c = Column {
            column_type: "STRING".to_string(),
            name: "column name".to_string(),
        };
        let s = Schema { columns: vec![c] };
        let d_schema = DatasetSchema {
            name: "test dataset".to_string(),
            description: "test description".to_string(),
            rows: 0,
            schema: s,
        };
        let expected = json!({
            "name": "test dataset",
            "description": "test description",
            "rows": 0,
            "schema": {
                "columns": [{
                    "type": "STRING",
                    "name": "column name"
                }]
            },
        });

        let v = serde_json::to_value(d_schema).unwrap();
        assert_eq!(v, expected);
    }

    #[test]
    fn test_fieldtype_merge() {
        panic!();
    }

    #[test]
    fn test_fieldtype_from_sample() {
        panic!();
    }

    #[test]
    fn test_check_fieldtype() {
        panic!();
    }

    #[test]
    fn test_schema_from_hashmap() {
        panic!();
    }

    #[test]
    fn test_datasetschema_from_hashmap() {
        panic!();
    }

}