chewdata 3.6.1

Extract Transform and Load data
Documentation
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
//! Read and write data into postgres database.
//!
//! ### Configuration
//!
//! | key        | alias           | Description                                      | Default Value | Possible Values         |
//! | ---------- | --------------- | ------------------------------------------------ | ------------- | ----------------------- |
//! | type       | -               | Required in order to use this connector          | `psql`        | `psql` / `pgsql` / `pg` |
//! | endpoint   | `url`           | Endpoint of the connector                        | ``            | String                  |
//! | database   | `db`            | The database name                                | ``            | String                  |
//! | collection | `col` / `table` | The collection name                              | ``            | String                  |
//! | query      | -               | SQL Query to find an element into the collection | ``            | String                  |
//! | parameters | `params`        | Parameters used to inject into the SQL query     | `null`        | Json structure          |
//! | paginator  | -               | Paginator parameters                             | [`self::Offset`]        | [`self::Offset`] |
//! | counter    | count           | Count the number of elements for pagination      | `null`        | [`self::Scan`] |
//!
//! ### Examples
//!
//! ```json
//! [
//!     {
//!         "type": "w",
//!         "connector":{
//!             "type": "mongodb",
//!             "endpoint": "mongodb://admin:admin@localhost:27017",
//!             "db": "tests",
//!             "collection": "test",
//!             "update_options": {
//!                 "upsert": true
//!             }
//!         },
//!         "concurrency_limit":3
//!     }
//! ]
//! ```
use super::counter::psql::CounterType;
use super::paginator::psql::PaginatorType;
use super::Connector;
use crate::helper::json_pointer::JsonPointer;
use crate::helper::string::{DisplayOnlyForDebugging, Obfuscate};
use crate::{helper::mustache::Mustache, DataResult};
use crate::{DataSet, DataStream};
use async_lock::OnceCell;
use async_stream::stream;
use async_trait::async_trait;
use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};
use dashmap::DashMap;
use futures::Stream;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use sqlx::postgres::{PgArguments, PgPoolOptions, PgRow};
use sqlx::{Arguments, Column, Pool, Postgres, Row, TypeInfo};
use std::pin::Pin;
use std::sync::{Arc, OnceLock};
use std::{
    fmt,
    io::{Error, ErrorKind, Result},
};

type SharedClients = DashMap<String, Arc<OnceCell<Pool<Postgres>>>>;
static CLIENTS: OnceLock<SharedClients> = OnceLock::new();

#[derive(Deserialize, Serialize, Clone)]
#[serde(default, deny_unknown_fields)]
pub struct Psql {
    #[serde(alias = "url")]
    pub endpoint: String,
    #[serde(alias = "db")]
    pub database: String,
    #[serde(alias = "col")]
    #[serde(alias = "table")]
    pub collection: String,
    #[serde(alias = "params")]
    pub parameters: Value,
    pub query: Option<String>,
    #[serde(alias = "paginator")]
    pub paginator_type: PaginatorType,
    #[serde(alias = "counter")]
    #[serde(alias = "count")]
    pub counter_type: CounterType,
    #[serde(alias = "conn")]
    pub max_connections: usize,
    #[serde(skip)]
    #[serde(default)]
    client: Option<Pool<Postgres>>,
}

impl Default for Psql {
    fn default() -> Self {
        Psql {
            endpoint: Default::default(),
            database: Default::default(),
            collection: Default::default(),
            parameters: Default::default(),
            query: Default::default(),
            paginator_type: PaginatorType::default(),
            counter_type: CounterType::default(),
            max_connections: 5,
            client: None,
        }
    }
}

impl fmt::Debug for Psql {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Psql")
            .field("endpoint", &self.endpoint.to_obfuscate())
            .field("database", &self.database)
            .field("collection", &self.collection)
            .field("parameters", &self.parameters.display_only_for_debugging())
            .field("query", &self.query)
            .field(
                "paginator_type",
                &self.paginator_type.display_only_for_debugging(),
            )
            .field(
                "counter_type",
                &self.counter_type.display_only_for_debugging(),
            )
            .field("max_connections", &self.max_connections)
            .finish()
    }
}

impl Psql {
    /// Transform mustache query into sanitized psql query with his arguments
    /// Query: SELECT * FROM {{ collection }} WHERE "a"={{ a }};
    /// Return: (SELECT * FROM collection WHERE "a" = $1, "a")
    pub fn query_sanitized(
        &self,
        query: &str,
        parameters: &Value,
    ) -> Result<(String, PgArguments)> {
        let mut map = Map::default();
        let regex = regex::Regex::new("\\{{2}([^}]*)\\}{2}")
            .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
        let mut query_sanitized = query.to_owned();
        let mut query_binding: PgArguments = Default::default();
        let mut count = 1;

        map.insert("table".to_string(), Value::String(self.collection.clone()));
        map.insert(
            "collection".to_string(),
            Value::String(self.collection.clone()),
        );
        query_sanitized.replace_mustache(Value::Object(map));

        for captured in regex.captures_iter(query_sanitized.clone().as_ref()) {
            let pattern_captured = captured[0].to_string();
            let value_captured = captured[1].trim().to_string();
            let json_pointer = value_captured.to_string().to_json_pointer();

            match parameters.pointer(&json_pointer) {
                Some(Value::Null) => {
                    let replace_by_is_null = regex::Regex::new(
                        format!(r"=\s*{}", regex::escape(pattern_captured.as_str())).as_str(),
                    )
                    .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
                    let replace_by_is_not_null = regex::Regex::new(
                        format!(r"(!=|<>)\s*{}", regex::escape(pattern_captured.as_str())).as_str(),
                    )
                    .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;

                    if replace_by_is_null.is_match(query_sanitized.as_str()) {
                        query_sanitized = replace_by_is_null
                            .replace(query_sanitized.as_str(), " IS NULL")
                            .to_string();
                        continue;
                    }

                    if replace_by_is_not_null.is_match(query_sanitized.as_str()) {
                        query_sanitized = replace_by_is_not_null
                            .replace(query_sanitized.as_str(), " IS NOT NULL")
                            .to_string();
                        continue;
                    }

                    query_binding
                        .add("NULL")
                        .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
                }
                Some(Value::String(string)) => {
                    let mut is_query_binded = false;
                    if let Ok(date) = string.parse::<NaiveDate>() {
                        query_binding
                            .add(date)
                            .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
                        is_query_binded = true;
                    }
                    if let Ok(date) = string.parse::<NaiveDateTime>() {
                        query_binding
                            .add(date)
                            .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
                        is_query_binded = true;
                    }
                    if let Ok(date) = string.parse::<DateTime<Utc>>() {
                        query_binding
                            .add(date)
                            .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
                        is_query_binded = true;
                    }
                    if !is_query_binded {
                        query_binding
                            .add(string)
                            .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
                    }
                }
                Some(Value::Number(number)) => {
                    if number.is_f64() {
                        query_binding
                            .add(number.as_f64().unwrap_or_default())
                            .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
                    } else if number.is_i64() {
                        query_binding
                            .add(number.as_i64().unwrap_or_default())
                            .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
                    } else if number.is_u64() {
                        query_binding
                            .add(number.as_u64().unwrap_or_default() as i64)
                            .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
                    }
                }
                Some(Value::Bool(boolean)) => {
                    query_binding
                        .add(boolean)
                        .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
                }
                Some(Value::Array(vec)) => {
                    query_binding
                        .add(Value::Array(vec.clone()))
                        .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
                }
                Some(Value::Object(map)) => {
                    query_binding
                        .add(Value::Object(map.clone()))
                        .map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
                }
                None => {
                    warn!(
                        pattern = pattern_captured.as_str(),
                        value = value_captured.as_str(),
                        path = json_pointer.as_str(),
                        parameters = format!("{:?}", parameters).as_str(),
                        "The value can't be resolved",
                    );
                    continue;
                }
            };

            query_sanitized =
                query_sanitized.replace(pattern_captured.as_str(), format!("${}", count).as_str());
            count += 1;
        }

        Ok((query_sanitized, query_binding))
    }
    #[instrument(name = "psql::client_mut")]
    pub async fn client_mut(&mut self) -> Result<Pool<Postgres>> {
        if self.client.is_none() {
            let client = get_or_create_client(self.path(), self.max_connections).await?;

            trace!("initialize the client in the connector");
            self.client = Some(client);
        }

        Ok(self.client.clone().unwrap())
    }
    #[instrument(name = "psql::client")]
    pub async fn client(&self) -> Result<Pool<Postgres>> {
        if self.client.is_none() {
            trace!("initialize client");
            return get_or_create_client(self.path(), self.max_connections).await;
        }

        Ok(self.client.clone().unwrap())
    }
}

async fn get_or_create_client(path: String, max_connection: usize) -> Result<Pool<Postgres>> {
    let clients = CLIENTS.get_or_init(DashMap::new);
    let key = path.clone();

    let cell = clients
        .entry(key.clone())
        .or_insert_with(|| Arc::new(OnceCell::new()))
        .clone();

    let client = cell
        .get_or_try_init(|| async {
            trace!(key = ?key, "storing client in shared container");

            let client = PgPoolOptions::new()
                .max_connections(max_connection as u32)
                .connect(&path)
                .await
                .map_err(|e| Error::new(ErrorKind::Interrupted, e))?;

            Ok::<Pool<Postgres>, anyhow::Error>(client)
        })
        .await
        .unwrap();

    Ok(client.clone())
}

#[async_trait]
impl Connector for Psql {
    /// See [`Connector::path`] for more details.
    fn path(&self) -> String {
        format!("{}/{}", self.endpoint, self.database)
    }
    /// See [`Connector::set_parameters`] for more details.
    fn set_parameters(&mut self, parameters: Value) {
        self.parameters = parameters;
    }
    /// See [`Connector::is_variable`] for more details.
    fn is_variable(&self) -> bool {
        match &self.query {
            Some(query) => query.has_mustache(),
            None => false,
        }
    }
    /// See [`Connector::is_resource_will_change`] for more details.
    fn is_resource_will_change(&self, _new_parameters: Value) -> Result<bool> {
        Ok(false)
    }
    /// See [`Connector::len`] for more details.
    ///
    /// # Examples
    ///
    /// ```
    /// use chewdata::connector::psql::Psql;
    /// use chewdata::document::json::Json;
    /// use chewdata::connector::Connector;
    /// use smol::prelude::*;
    /// use std::io;
    ///
    /// use macro_rules_attribute::apply;
    /// use smol_macros::main;
    ///
    /// #[apply(main!)]
    /// async fn main() -> io::Result<()> {
    ///     let mut connector = Psql::default();
    ///     connector.endpoint = "psql://admin:admin@localhost:5432".into();
    ///     connector.database = "postgres".into();
    ///     connector.collection = "public.read".into();
    ///     let len = connector.len().await.unwrap();
    ///     assert!(0 < len, "The connector should have a size upper than zero");
    ///
    ///     Ok(())
    /// }
    /// ```
    #[instrument(name = "psql::len")]
    async fn len(&self) -> Result<usize> {
        match self.counter_type.count(self).await {
            Ok(count) => Ok(count),
            Err(e) => {
                warn!(
                    error = e.to_string(),
                    "Can't count the number of element, return 0"
                );

                Ok(0)
            }
        }
    }
    /// See [`Connector::fetch`] for more details.
    ///
    /// # Examples
    ///
    /// ```
    /// use chewdata::connector::psql::Psql;
    /// use chewdata::document::json::Json;
    /// use chewdata::connector::Connector;
    /// use serde_json::Value;
    /// use smol::prelude::*;
    /// use std::io;
    /// use smol::stream::StreamExt;
    ///
    /// use macro_rules_attribute::apply;
    /// use smol_macros::main;
    ///
    /// #[apply(main!)]
    /// async fn main() -> io::Result<()> {
    ///     let mut connector = Psql::default();
    ///     connector.endpoint = "postgres://admin:admin@localhost".into();
    ///     connector.database = "postgres".into();
    ///     connector.collection = "public.read".into();
    ///     connector.query =
    ///         Some("SELECT * FROM {{ collection }} WHERE \"number\" = {{ number }} AND \"string\" = {{ string }} AND \"boolean\" = {{ boolean }} AND \"null\" = {{ null }} AND \"array\" = {{ array }} AND \"object\" = {{ object }} AND \"date\" = {{ date }} AND \"round\" = {{ round }};".to_string());
    ///     let data: Value = serde_json::from_str(
    ///         r#"{"number":1,"group":1,"string":"value to test 5416","boolean":false,"null":null,"array":[1,2],"object":{"field":"value"},"date":"2019-12-31T00:00:00.000Z","round":10.156}"#,
    ///     )
    ///     .unwrap();
    ///     connector.set_parameters(data);
    ///     let datastream = connector.fetch().await.unwrap().unwrap();
    ///     assert!(
    ///         1 == datastream.count().await,
    ///         "The datastream must contain one record"
    ///     );
    ///
    ///     Ok(())
    /// }
    /// ```
    #[instrument(name = "psql::fetch")]
    async fn fetch(&mut self) -> std::io::Result<Option<DataStream>> {
        let (query_sanitized, binding) = match &self.query {
            Some(query) => self.query_sanitized(query, &self.parameters),
            None => self.query_sanitized("SELECT * FROM {{ collection }}", &self.parameters),
        }?;

        let data = sqlx::query_with(query_sanitized.as_str(), binding)
            .map(|row: PgRow| {
                let mut map = Map::default();

                for col in row.columns() {
                    // See mapping here [`https://github.com/launchbadge/sqlx/blob/061fdcabd72896d9bc3abb4ea4af6712a04bc0a8/sqlx-core/src/postgres/types/mod.rs`]
                    let value = match col.type_info().name() {
                        "BOOL" => match row.try_get::<bool, usize>(col.ordinal()) {
                            Ok(val) => Value::Bool(val),
                            Err(_) => Value::Null,
                        },
                        "\"CHAR\"" => match row.try_get::<i8, usize>(col.ordinal()) {
                            Ok(val) => Value::Number(serde_json::Number::from(val)),
                            Err(_) => Value::Null,
                        },
                        "SMALLINT" | "SMALLSERIAL" | "INT2" => {
                            match row.try_get::<i16, usize>(col.ordinal()) {
                                Ok(val) => Value::Number(serde_json::Number::from(val)),
                                Err(_) => Value::Null,
                            }
                        }
                        "INT" | "SERIAL" | "INT4" => match row.try_get::<i32, usize>(col.ordinal())
                        {
                            Ok(val) => Value::Number(serde_json::Number::from(val)),
                            Err(_) => Value::Null,
                        },
                        "BIGINT" | "BIGSERIAL" | "INT8" => {
                            match row.try_get::<i64, usize>(col.ordinal()) {
                                Ok(val) => Value::Number(serde_json::Number::from(val)),
                                Err(_) => Value::Null,
                            }
                        }
                        "REAL" | "FLOAT4" => match row.try_get::<f32, usize>(col.ordinal()) {
                            Ok(val) => {
                                Value::Number(serde_json::Number::from_f64(val as f64).unwrap())
                            }
                            Err(_) => Value::Null,
                        },
                        "DOUBLE PRECISION" | "FLOAT8" => match row
                            .try_get::<f64, usize>(col.ordinal())
                        {
                            Ok(val) => Value::Number(serde_json::Number::from_f64(val).unwrap()),
                            Err(_) => Value::Null,
                        },
                        "VARCHAR" | "CHAR(N)" | "TEXT" | "NAME" => {
                            match row.try_get::<String, usize>(col.ordinal()) {
                                Ok(val) => Value::String(val),
                                Err(_) => Value::Null,
                            }
                        }
                        "BYTEA" => match row.try_get::<Vec<u8>, usize>(col.ordinal()) {
                            Ok(val) => Value::String(String::from_utf8(val).unwrap()),
                            Err(_) => Value::Null,
                        },
                        "DATE" => match row.try_get::<NaiveDate, usize>(col.ordinal()) {
                            Ok(val) => Value::String(val.to_string()),
                            Err(_) => Value::Null,
                        },
                        "TIME" => match row.try_get::<NaiveTime, usize>(col.ordinal()) {
                            Ok(val) => Value::String(val.to_string()),
                            Err(_) => Value::Null,
                        },
                        "TIMESTAMPTZ" => match row.try_get::<DateTime<Utc>, usize>(col.ordinal()) {
                            Ok(val) => Value::String(val.to_string()),
                            Err(_) => Value::Null,
                        },
                        "TIMESTAMP" => match row.try_get::<NaiveDateTime, usize>(col.ordinal()) {
                            Ok(val) => Value::String(val.to_string()),
                            Err(_) => Value::Null,
                        },
                        "JSON" | "JSONB" => match row.try_get::<Value, usize>(col.ordinal()) {
                            Ok(val) => val,
                            Err(_) => Value::Null,
                        },
                        _ => match row.try_get(col.ordinal()) {
                            Ok(val) => Value::String(val),
                            Err(_) => Value::Null,
                        },
                    };
                    map.insert(col.name().to_string(), value);
                }
                Value::Object(map)
            })
            .fetch_all(&self.client_mut().await?)
            .await
            .map_err(|e| Error::new(ErrorKind::Interrupted, e))?;

        info!("Fetch data with success");

        if data.is_empty() {
            return Ok(None);
        }

        let dataset: Vec<DataResult> = data.into_iter().map(DataResult::Ok).collect();

        Ok(Some(Box::pin(stream! {
            for data in dataset {
                yield data;
            }
        })))
    }
    /// See [`Connector::send`] for more details.
    ///
    /// # Examples
    ///
    /// ```
    /// use chewdata::connector::psql::Psql;
    /// use chewdata::document::json::Json;
    /// use chewdata::connector::Connector;
    /// use chewdata::DataResult;
    /// use smol::prelude::*;
    /// use std::io;
    ///
    /// use macro_rules_attribute::apply;
    /// use smol_macros::main;
    ///
    /// #[apply(main!)]
    /// async fn main() -> io::Result<()> {
    ///     let mut connector = Psql::default();
    ///     connector.endpoint = "postgres://admin:admin@localhost:5432".into();
    ///     connector.database = "postgres".into();
    ///     connector.collection = "public.send".into();
    ///     connector.erase().await.unwrap();
    ///
    ///     let expected_result1 = DataResult::Ok(
    ///         serde_json::from_str(
    ///             r#"{"number":110,"string":"value1","boolean":true,"special_char":"€"}"#,
    ///         )
    ///         .unwrap(),
    ///     );
    ///     let dataset = vec![expected_result1.clone()];
    ///     connector.send(&dataset).await.unwrap();
    ///
    ///     Ok(())
    /// }
    /// ```
    #[instrument(skip(dataset), name = "psql::send")]
    async fn send(&mut self, dataset: &DataSet) -> std::io::Result<Option<DataStream>> {
        let query = match &self.query {
            Some(query) => query.clone(),
            None => {
                let query_start = "INSERT INTO {{ collection }}".to_string();
                let mut query_fields = "".to_string();
                let mut query_values = "".to_string();
                let value = dataset[0].to_value();

                if let Value::Object(map) = value {
                    for (field, _) in map {
                        if !query_fields.is_empty() {
                            query_fields.push_str(", ");
                            query_values.push_str(", ");
                        }
                        query_fields.push_str(format!("\"{}\"", field).as_str());
                        query_values.push_str(format!("{{{{ {} }}}}", field).as_str());
                    }
                };

                format!(
                    "{} ({}) VALUES ({});",
                    query_start, query_fields, query_values
                )
            }
        };

        for data in dataset {
            let (query_sanitized, binding) = self.query_sanitized(&query, &data.to_value())?;

            match sqlx::query_with(query_sanitized.as_str(), binding)
                .execute(&self.client_mut().await?)
                .await
            {
                Ok(_) => Ok(()),
                Err(e) => {
                    warn!(
                        error = format!("{}", e).as_str(),
                        query = query.as_str(),
                        "Can't send data"
                    );
                    Err(Error::new(ErrorKind::Interrupted, e))
                }
            }?;
        }

        info!("Send data with success");

        Ok(None)
    }
    /// See [`Connector::erase`] for more details.
    ///
    /// # Examples
    ///
    /// ```
    /// use chewdata::connector::psql::Psql;
    /// use chewdata::document::json::Json;
    /// use chewdata::connector::Connector;
    /// use chewdata::DataResult;
    /// use smol::prelude::*;
    /// use std::io;
    ///
    /// use macro_rules_attribute::apply;
    /// use smol_macros::main;
    ///
    /// #[apply(main!)]
    /// async fn main() -> io::Result<()> {
    ///     let mut connector = Psql::default();
    ///     connector.endpoint = "psql://admin:admin@localhost".into();
    ///     connector.database = "postgres".into();
    ///     connector.collection = "public.erase".into();
    ///
    ///     let expected_result1 =
    ///         DataResult::Ok(serde_json::from_str(r#"{"data":"value1"}"#).unwrap());
    ///     let dataset = vec![expected_result1];
    ///     connector.send(&dataset).await.unwrap();
    ///     connector.erase().await.unwrap();
    ///
    ///     let mut connector_read = connector.clone();
    ///     let datastream = connector_read.fetch().await.unwrap();
    ///     assert!(datastream.is_none(), "The datastream should be empty");
    ///
    ///     Ok(())
    /// }
    /// ```
    #[instrument(name = "psql::erase")]
    async fn erase(&mut self) -> Result<()> {
        let (query_sanitized, _) =
            self.query_sanitized("DELETE FROM {{ collection }}", &Value::Null)?;

        sqlx::query(query_sanitized.as_str())
            .execute(&self.client_mut().await?)
            .await
            .map_err(|e| Error::new(ErrorKind::Interrupted, e))?;

        info!("Erase data with success");
        Ok(())
    }
    /// See [`Connector::paginate`] for more details.
    async fn paginate(
        &self,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<Box<dyn Connector>>> + Send>>> {
        self.paginator_type.paginate(self).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::DataResult;
    use macro_rules_attribute::apply;
    use smol::stream::StreamExt;
    use smol_macros::test;

    #[apply(test!)]
    async fn len() {
        let mut connector = Psql::default();
        connector.endpoint = "psql://admin:admin@localhost:5432".into();
        connector.database = "postgres".into();
        connector.collection = "public.read".into();
        let len = connector.len().await.unwrap();
        assert!(0 < len, "The connector should have a size upper than zero.");
    }
    #[apply(test!)]
    async fn fetch() {
        let mut connector = Psql::default();
        connector.endpoint = "psql://admin:admin@localhost:5432".into();
        connector.database = "postgres".into();
        connector.collection = "public.read".into();
        let datastream = connector.fetch().await.unwrap().unwrap();
        assert!(
            0 < datastream.count().await,
            "The inner connector should have a size upper than zero."
        );
    }
    #[apply(test!)]
    async fn fetch_with_parameters() {
        let mut connector = Psql::default();
        connector.endpoint = "postgres://admin:admin@localhost".into();
        connector.database = "postgres".into();
        connector.collection = "public.read".into();
        connector.query =
            Some("SELECT * FROM {{ collection }} WHERE \"number\" = {{ number }} AND \"string\" = {{ string }} AND \"boolean\" = {{ boolean }} AND \"null\" = {{ null }} AND \"array\" = {{ array }} AND \"object\" = {{ object }} AND \"date\" = {{ date }} AND \"round\" = {{ round }}".to_string());
        let data: Value = serde_json::from_str(
            r#"{"number":1,"group":1,"string":"value to test 5416","boolean":false,"null":null,"array":[1,2],"object":{"field":"value"},"date":"2019-12-31T00:00:00.000Z","round":10.156}"#,
        )
        .unwrap();
        connector.set_parameters(data);
        let datastream = connector.fetch().await.unwrap().unwrap();
        assert!(
            1 == datastream.count().await,
            "The datastream must contain one record."
        );
    }
    #[apply(test!)]
    async fn erase() {
        let mut connector = Psql::default();
        connector.endpoint = "psql://admin:admin@localhost".into();
        connector.database = "postgres".into();
        connector.collection = "public.erase".into();

        let expected_result1 =
            DataResult::Ok(serde_json::from_str(r#"{"data":"value1"}"#).unwrap());
        let dataset = vec![expected_result1];
        connector.send(&dataset).await.unwrap();
        connector.erase().await.unwrap();

        let mut connector_read = connector.clone();
        let datastream = connector_read.fetch().await.unwrap();
        assert!(datastream.is_none(), "The datastream should be empty.");
    }
    #[apply(test!)]
    async fn send_new_data() {
        let mut connector = Psql::default();
        connector.endpoint = "postgres://admin:admin@localhost:5432".into();
        connector.database = "postgres".into();
        connector.collection = "public.send".into();
        connector.erase().await.unwrap();

        let expected_result1 = DataResult::Ok(
            serde_json::from_str(
                r#"{"number":110,"string":"value1","boolean":true,"special_char":"€"}"#,
            )
            .unwrap(),
        );
        let expected_result2 = DataResult::Ok(
            serde_json::from_str(
                r#"{"number":111,"string":"value2","boolean":false,"special_char":null}"#,
            )
            .unwrap(),
        );
        let dataset = vec![expected_result1.clone(), expected_result2.clone()];
        connector.send(&dataset).await.unwrap();

        let mut connector_read = connector.clone();
        let mut datastream = connector_read.fetch().await.unwrap().unwrap();
        assert_eq!(
            110,
            datastream
                .next()
                .await
                .unwrap()
                .to_value()
                .get("number")
                .unwrap()
                .as_u64()
                .unwrap()
        );
        assert_eq!(
            111,
            datastream
                .next()
                .await
                .unwrap()
                .to_value()
                .get("number")
                .unwrap()
                .as_u64()
                .unwrap()
        );
    }
    #[apply(test!)]
    async fn update_existing_data() {
        let mut connector = Psql::default();
        connector.endpoint = "postgres://admin:admin@localhost".into();
        connector.database = "postgres".into();
        connector.collection = "public.send_update".into();
        connector.erase().await.unwrap();

        let expected_result1 = DataResult::Ok(
            serde_json::from_str(r#"{"number":110,"group":1,"string":"value1"}"#).unwrap(),
        );
        let dataset = vec![expected_result1.clone()];
        let mut connector_update = connector.clone();
        connector_update.send(&dataset).await.unwrap();

        let expected_result2 = DataResult::Ok(
            serde_json::from_str(r#"{"number":111,"group":1,"string":"value2"}"#).unwrap(),
        );
        let dataset = vec![expected_result2.clone()];
        let mut connector_update = connector.clone();
        connector_update.send(&dataset).await.unwrap();

        let data: Value =
            serde_json::from_str(r#"{"number":110,"group":1,"string":"value3"}"#).unwrap();
        let dataset = vec![DataResult::Ok(data.clone())];
        let mut connector_update = connector.clone();
        connector_update.set_parameters(data);
        connector_update.query = Some("UPDATE {{ collection }} SET \"group\" = {{ group }}, \"string\" = {{ string }} WHERE \"number\" = {{ number }}".to_string());
        connector_update.send(&dataset).await.unwrap();

        let mut connector_read = connector.clone();
        connector_read.query =
            Some("SELECT * FROM {{ collection }} ORDER BY \"number\" ASC".to_string());
        let mut datastream = connector_read.fetch().await.unwrap().unwrap();
        assert_eq!(
            "value3",
            datastream
                .next()
                .await
                .unwrap()
                .to_value()
                .get("string")
                .unwrap()
                .as_str()
                .unwrap()
        );
        assert_eq!(
            "value2",
            datastream
                .next()
                .await
                .unwrap()
                .to_value()
                .get("string")
                .unwrap()
                .as_str()
                .unwrap()
        );
    }
    #[apply(test!)]
    async fn upsert() {
        let mut connector = Psql::default();
        connector.endpoint = "postgres://admin:admin@localhost".into();
        connector.database = "postgres".into();
        connector.collection = "public.send_with_key".into();
        connector.erase().await.unwrap();

        let expected_result1 = DataResult::Ok(
            serde_json::from_str(
                r#"{"number":110,"group":1,"string":"value1","object":{"field":"value"}}"#,
            )
            .unwrap(),
        );
        let dataset = vec![expected_result1.clone()];
        let mut connector_update = connector.clone();
        connector_update.send(&dataset).await.unwrap();

        let expected_result2 = DataResult::Ok(
            serde_json::from_str(r#"{"number":111,"group":1,"string":"value2"}"#).unwrap(),
        );
        let dataset = vec![expected_result2.clone()];
        let mut connector_update = connector.clone();
        connector_update.send(&dataset).await.unwrap();

        let data: Value =
            serde_json::from_str(r#"{"number":110,"group":1,"string":"value3"}"#).unwrap();
        let dataset = vec![DataResult::Ok(data.clone())];
        let mut connector_update = connector.clone();
        connector_update.set_parameters(data);
        connector_update.query = Some("INSERT INTO {{ collection }} (\"group\",\"string\",\"number\") VALUES ({{ group }},{{ string }},{{ number }}) ON CONFLICT (\"number\") DO UPDATE SET \"group\"=excluded.group,\"string\"=excluded.string".to_string());
        connector_update.send(&dataset).await.unwrap();

        let mut connector_read = connector.clone();
        connector_read.query =
            Some("SELECT * FROM {{ collection }} ORDER BY \"number\" ASC".to_string());
        let mut datastream = connector_read.fetch().await.unwrap().unwrap();
        assert_eq!(
            "value3",
            datastream
                .next()
                .await
                .unwrap()
                .to_value()
                .get("string")
                .unwrap()
                .as_str()
                .unwrap()
        );
        assert_eq!(
            "value2",
            datastream
                .next()
                .await
                .unwrap()
                .to_value()
                .get("string")
                .unwrap()
                .as_str()
                .unwrap()
        );
    }
    #[apply(test!)]
    async fn sql_injection() {
        let mut connector = Psql::default();
        connector.endpoint = "postgres://admin:admin@localhost".into();
        connector.database = "postgres".into();
        connector.collection = "public.send_with_key".into();
        connector.query =
            Some("SELECT * FROM {{ collection }} WHERE \"number\" = {{ number }} AND \"string\" = {{ string }}".to_string());
        let data: Value =
            serde_json::from_str(r#"{"number":1,"string":"value' OR 1=1;--"}"#).unwrap();
        connector.set_parameters(data);
        let datastream = connector.fetch().await.unwrap();
        assert!(datastream.is_none(), "The sql injection return no data.");
    }
}