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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
use std::{
    collections::HashSet,
    fmt::Write as _,
    iter,
    path::PathBuf,
    time::{Duration, Instant},
};

use chrono::{DateTime, Utc};
use futures::{
    future::{join_all, try_join_all},
    FutureExt, StreamExt,
};
use openssl::{
    error::ErrorStack,
    ssl::{SslConnector, SslMethod},
};
use postgres_openssl::MakeTlsConnector;
use serde_with::serde_as;
use snafu::{ResultExt, Snafu};
use tokio::time;
use tokio_postgres::{
    config::{ChannelBinding, Host, SslMode, TargetSessionAttrs},
    types::FromSql,
    Client, Config, Error as PgError, NoTls, Row,
};
use tokio_stream::wrappers::IntervalStream;
use vector_lib::config::LogNamespace;
use vector_lib::configurable::configurable_component;
use vector_lib::{
    internal_event::{CountByteSize, InternalEventHandle as _, Registered},
    json_size::JsonSize,
};
use vector_lib::{metric_tags, ByteSizeOf, EstimatedJsonEncodedSizeOf};

use crate::{
    config::{SourceConfig, SourceContext, SourceOutput},
    event::metric::{Metric, MetricKind, MetricTags, MetricValue},
    internal_events::{
        CollectionCompleted, EndpointBytesReceived, EventsReceived, PostgresqlMetricsCollectError,
        StreamClosedError,
    },
};

macro_rules! tags {
    ($tags:expr) => { $tags.clone() };
    ($tags:expr, $($key:expr => $value:expr),*) => {
        {
            let mut tags = $tags.clone();
            $(
                tags.replace($key.into(), String::from($value));
            )*
            tags
        }
    };
}

macro_rules! counter {
    ($value:expr) => {
        MetricValue::Counter {
            value: $value as f64,
        }
    };
}

macro_rules! gauge {
    ($value:expr) => {
        MetricValue::Gauge {
            value: $value as f64,
        }
    };
}

#[derive(Debug, Snafu)]
enum BuildError {
    #[snafu(display("invalid endpoint: {}", source))]
    InvalidEndpoint { source: PgError },
    #[snafu(display("host missing"))]
    HostMissing,
    #[snafu(display("multiple hosts not supported: {:?}", hosts))]
    MultipleHostsNotSupported { hosts: Vec<Host> },
}

#[derive(Debug, Snafu)]
enum ConnectError {
    #[snafu(display("failed to create tls connector: {}", source))]
    TlsFailed { source: ErrorStack },
    #[snafu(display("failed to connect ({}): {}", endpoint, source))]
    ConnectionFailed { source: PgError, endpoint: String },
    #[snafu(display("failed to get PostgreSQL version ({}): {}", endpoint, source))]
    SelectVersionFailed { source: PgError, endpoint: String },
    #[snafu(display("version ({}) is not supported", version))]
    InvalidVersion { version: String },
}

#[derive(Debug, Snafu)]
enum CollectError {
    #[snafu(display("failed to get value by key: {} (reason: {})", key, source))]
    PostgresGetValue { source: PgError, key: &'static str },
    #[snafu(display("query failed: {}", source))]
    QueryError { source: PgError },
}

/// Configuration of TLS when connecting to PostgreSQL.
#[configurable_component]
#[derive(Clone, Debug)]
#[serde(deny_unknown_fields)]
struct PostgresqlMetricsTlsConfig {
    /// Absolute path to an additional CA certificate file.
    ///
    /// The certificate must be in the DER or PEM (X.509) format.
    #[configurable(metadata(docs::examples = "certs/ca.pem"))]
    ca_file: PathBuf,
}

/// Configuration for the `postgresql_metrics` source.
#[serde_as]
#[configurable_component(source(
    "postgresql_metrics",
    "Collect metrics from the PostgreSQL database."
))]
#[derive(Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct PostgresqlMetricsConfig {
    /// A list of PostgreSQL instances to scrape.
    ///
    /// Each endpoint must be in the [Connection URI
    /// format](https://www.postgresql.org/docs/current/libpq-connect.html#id-1.7.3.8.3.6).
    #[configurable(metadata(
        docs::examples = "postgresql://postgres:vector@localhost:5432/postgres"
    ))]
    endpoints: Vec<String>,

    /// A list of databases to match (by using [POSIX Regular
    /// Expressions](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP)) against
    /// the `datname` column for which you want to collect metrics from.
    ///
    /// If not set, metrics are collected from all databases. Specifying `""` includes metrics where `datname` is
    /// `NULL`.
    ///
    /// This can be used in conjunction with `exclude_databases`.
    #[configurable(metadata(
        docs::examples = "^postgres$",
        docs::examples = "^vector$",
        docs::examples = "^foo",
    ))]
    include_databases: Option<Vec<String>>,

    /// A list of databases to match (by using [POSIX Regular
    /// Expressions](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-POSIX-REGEXP)) against
    /// the `datname` column for which you don’t want to collect metrics from.
    ///
    /// Specifying `""` includes metrics where `datname` is `NULL`.
    ///
    /// This can be used in conjunction with `include_databases`.
    #[configurable(metadata(docs::examples = "^postgres$", docs::examples = "^template.*",))]
    exclude_databases: Option<Vec<String>>,

    /// The interval between scrapes.
    #[serde(default = "default_scrape_interval_secs")]
    #[serde_as(as = "serde_with::DurationSeconds<u64>")]
    #[configurable(metadata(docs::human_name = "Scrape Interval"))]
    scrape_interval_secs: Duration,

    /// Overrides the default namespace for the metrics emitted by the source.
    #[serde(default = "default_namespace")]
    namespace: String,

    #[configurable(derived)]
    tls: Option<PostgresqlMetricsTlsConfig>,
}

impl Default for PostgresqlMetricsConfig {
    fn default() -> Self {
        Self {
            endpoints: vec![],
            include_databases: None,
            exclude_databases: None,
            scrape_interval_secs: Duration::from_secs(15),
            namespace: "postgresql".to_owned(),
            tls: None,
        }
    }
}

impl_generate_config_from_default!(PostgresqlMetricsConfig);

pub const fn default_scrape_interval_secs() -> Duration {
    Duration::from_secs(15)
}

pub fn default_namespace() -> String {
    "postgresql".to_owned()
}

#[async_trait::async_trait]
#[typetag::serde(name = "postgresql_metrics")]
impl SourceConfig for PostgresqlMetricsConfig {
    async fn build(&self, mut cx: SourceContext) -> crate::Result<super::Source> {
        let datname_filter = DatnameFilter::new(
            self.include_databases.clone().unwrap_or_default(),
            self.exclude_databases.clone().unwrap_or_default(),
        );
        let namespace = Some(self.namespace.clone()).filter(|namespace| !namespace.is_empty());

        let mut sources = try_join_all(self.endpoints.iter().map(|endpoint| {
            PostgresqlMetrics::new(
                endpoint.clone(),
                datname_filter.clone(),
                namespace.clone(),
                self.tls.clone(),
            )
        }))
        .await?;

        let duration = self.scrape_interval_secs;
        let shutdown = cx.shutdown;
        Ok(Box::pin(async move {
            let mut interval = IntervalStream::new(time::interval(duration)).take_until(shutdown);
            while interval.next().await.is_some() {
                let start = Instant::now();
                let metrics = join_all(sources.iter_mut().map(|source| source.collect())).await;
                emit!(CollectionCompleted {
                    start,
                    end: Instant::now()
                });

                let metrics: Vec<Metric> = metrics.into_iter().flatten().collect();
                let count = metrics.len();

                if (cx.out.send_batch(metrics).await).is_err() {
                    emit!(StreamClosedError { count });
                    return Err(());
                }
            }

            Ok(())
        }))
    }

    fn outputs(&self, _global_log_namespace: LogNamespace) -> Vec<SourceOutput> {
        vec![SourceOutput::new_metrics()]
    }

    fn can_acknowledge(&self) -> bool {
        false
    }
}

#[derive(Debug)]
struct PostgresqlClient {
    config: Config,
    tls_config: Option<PostgresqlMetricsTlsConfig>,
    client: Option<(Client, usize)>,
    endpoint: String,
}

impl PostgresqlClient {
    fn new(config: Config, tls_config: Option<PostgresqlMetricsTlsConfig>) -> Self {
        let endpoint = config_to_endpoint(&config);
        Self {
            config,
            tls_config,
            client: None,
            endpoint,
        }
    }

    async fn take(&mut self) -> Result<(Client, usize), ConnectError> {
        match self.client.take() {
            Some((client, version)) => Ok((client, version)),
            None => self.build_client().await,
        }
    }

    fn set(&mut self, value: (Client, usize)) {
        self.client.replace(value);
    }

    async fn build_client(&self) -> Result<(Client, usize), ConnectError> {
        // Create postgresql client
        let client = match &self.tls_config {
            Some(tls_config) => {
                let mut builder =
                    SslConnector::builder(SslMethod::tls_client()).context(TlsFailedSnafu)?;
                builder
                    .set_ca_file(tls_config.ca_file.clone())
                    .context(TlsFailedSnafu)?;
                let connector = MakeTlsConnector::new(builder.build());

                let (client, connection) =
                    self.config.connect(connector).await.with_context(|_| {
                        ConnectionFailedSnafu {
                            endpoint: &self.endpoint,
                        }
                    })?;
                tokio::spawn(connection);
                client
            }
            None => {
                let (client, connection) =
                    self.config
                        .connect(NoTls)
                        .await
                        .with_context(|_| ConnectionFailedSnafu {
                            endpoint: &self.endpoint,
                        })?;
                tokio::spawn(connection);
                client
            }
        };

        // Log version if required
        if tracing::level_enabled!(tracing::Level::DEBUG) {
            let version_row = client
                .query_one("SELECT version()", &[])
                .await
                .with_context(|_| SelectVersionFailedSnafu {
                    endpoint: &self.endpoint,
                })?;
            let version = version_row
                .try_get::<&str, &str>("version")
                .with_context(|_| SelectVersionFailedSnafu {
                    endpoint: &self.endpoint,
                })?;
            debug!(message = "Connected to server.", endpoint = %self.endpoint, server_version = %version);
        }

        // Get server version and check that we support it
        let row = client
            .query_one("SHOW server_version_num", &[])
            .await
            .with_context(|_| SelectVersionFailedSnafu {
                endpoint: &self.endpoint,
            })?;

        let version = row
            .try_get::<&str, &str>("server_version_num")
            .with_context(|_| SelectVersionFailedSnafu {
                endpoint: &self.endpoint,
            })?;

        let version = match version.parse::<usize>() {
            Ok(version) if version >= 90600 => version,
            Ok(_) | Err(_) => {
                return Err(ConnectError::InvalidVersion {
                    version: version.to_string(),
                })
            }
        };

        //
        Ok((client, version))
    }
}

#[derive(Debug, Clone)]
struct DatnameFilter {
    pg_stat_database_sql: String,
    pg_stat_database_conflicts_sql: String,
    match_params: Vec<String>,
}

impl DatnameFilter {
    fn new(include: Vec<String>, exclude: Vec<String>) -> Self {
        let (include_databases, include_null) = Self::clean_databases(include);
        let (exclude_databases, exclude_null) = Self::clean_databases(exclude);
        let (match_sql, match_params) =
            Self::build_match_params(include_databases, exclude_databases);

        let mut pg_stat_database_sql = "SELECT * FROM pg_stat_database".to_owned();
        if !match_sql.is_empty() {
            pg_stat_database_sql += " WHERE";
            pg_stat_database_sql += &match_sql;
        }
        match (include_null, exclude_null) {
            // Nothing
            (false, false) => {}
            // Include tracking objects not in database
            (true, false) => {
                pg_stat_database_sql += if match_sql.is_empty() {
                    " WHERE"
                } else {
                    " OR"
                };
                pg_stat_database_sql += " datname IS NULL";
            }
            // Exclude tracking objects not in database, precedence over include
            (false, true) | (true, true) => {
                pg_stat_database_sql += if match_sql.is_empty() {
                    " WHERE"
                } else {
                    " AND"
                };
                pg_stat_database_sql += " datname IS NOT NULL";
            }
        }

        let mut pg_stat_database_conflicts_sql =
            "SELECT * FROM pg_stat_database_conflicts".to_owned();
        if !match_sql.is_empty() {
            pg_stat_database_conflicts_sql += " WHERE";
            pg_stat_database_conflicts_sql += &match_sql;
        }

        Self {
            pg_stat_database_sql,
            pg_stat_database_conflicts_sql,
            match_params,
        }
    }

    fn clean_databases(names: Vec<String>) -> (Vec<String>, bool) {
        let mut set = names.into_iter().collect::<HashSet<_>>();
        let null = set.remove("");
        (set.into_iter().collect(), null)
    }

    fn build_match_params(include: Vec<String>, exclude: Vec<String>) -> (String, Vec<String>) {
        let mut query = String::new();
        let mut params = vec![];

        if !include.is_empty() {
            query.push_str(" (");
            for (i, name) in include.into_iter().enumerate() {
                params.push(name);
                if i > 0 {
                    query.push_str(" OR");
                }
                write!(query, " datname ~ ${}", params.len()).expect("write to String never fails");
            }
            query.push(')');
        }

        if !exclude.is_empty() {
            if !query.is_empty() {
                query.push_str(" AND");
            }

            query.push_str(" NOT (");
            for (i, name) in exclude.into_iter().enumerate() {
                params.push(name);
                if i > 0 {
                    query.push_str(" OR");
                }
                write!(query, " datname ~ ${}", params.len()).expect("write to String never fails");
            }
            query.push(')');
        }

        (query, params)
    }

    fn get_match_params(&self) -> Vec<&(dyn tokio_postgres::types::ToSql + Sync)> {
        let mut params: Vec<&(dyn tokio_postgres::types::ToSql + Sync)> =
            Vec::with_capacity(self.match_params.len());
        for item in self.match_params.iter() {
            params.push(item);
        }
        params
    }

    async fn pg_stat_database(&self, client: &Client) -> Result<Vec<Row>, PgError> {
        client
            .query(
                self.pg_stat_database_sql.as_str(),
                self.get_match_params().as_slice(),
            )
            .await
    }

    async fn pg_stat_database_conflicts(&self, client: &Client) -> Result<Vec<Row>, PgError> {
        client
            .query(
                self.pg_stat_database_conflicts_sql.as_str(),
                self.get_match_params().as_slice(),
            )
            .await
    }

    async fn pg_stat_bgwriter(&self, client: &Client) -> Result<Row, PgError> {
        client
            .query_one("SELECT * FROM pg_stat_bgwriter", &[])
            .await
    }
}

struct PostgresqlMetrics {
    client: PostgresqlClient,
    endpoint: String,
    namespace: Option<String>,
    tags: MetricTags,
    datname_filter: DatnameFilter,
    events_received: Registered<EventsReceived>,
}

impl PostgresqlMetrics {
    async fn new(
        endpoint: String,
        datname_filter: DatnameFilter,
        namespace: Option<String>,
        tls_config: Option<PostgresqlMetricsTlsConfig>,
    ) -> Result<Self, BuildError> {
        // Takes the raw endpoint, parses it into a configuration, and then we set `endpoint` back to a sanitized
        // version of the original value, dropping things like username/password, etc.
        let config: Config = endpoint.parse().context(InvalidEndpointSnafu)?;
        let endpoint = config_to_endpoint(&config);

        let hosts = config.get_hosts();
        let host = match hosts.len() {
            0 => return Err(BuildError::HostMissing),
            1 => match &hosts[0] {
                Host::Tcp(host) => host.clone(),
                #[cfg(unix)]
                Host::Unix(path) => path.to_string_lossy().to_string(),
            },
            _ => {
                return Err(BuildError::MultipleHostsNotSupported {
                    hosts: config.get_hosts().to_owned(),
                })
            }
        };

        let tags = metric_tags!(
            "endpoint" => endpoint.clone(),
            "host" => host,
        );

        Ok(Self {
            client: PostgresqlClient::new(config, tls_config),
            endpoint,
            namespace,
            tags,
            datname_filter,
            events_received: register!(EventsReceived),
        })
    }

    async fn collect(&mut self) -> Box<dyn Iterator<Item = Metric> + Send> {
        match self.collect_metrics().await {
            Ok(metrics) => Box::new(
                iter::once(self.create_metric("up", gauge!(1.0), tags!(self.tags))).chain(metrics),
            ),
            Err(error) => {
                emit!(PostgresqlMetricsCollectError {
                    error,
                    endpoint: &self.endpoint,
                });
                Box::new(iter::once(self.create_metric(
                    "up",
                    gauge!(0.0),
                    tags!(self.tags),
                )))
            }
        }
    }

    async fn collect_metrics(&mut self) -> Result<impl Iterator<Item = Metric>, String> {
        let (client, client_version) = self
            .client
            .take()
            .await
            .map_err(|error| error.to_string())?;

        match try_join_all(vec![
            self.collect_pg_stat_database(&client, client_version)
                .boxed(),
            self.collect_pg_stat_database_conflicts(&client).boxed(),
            self.collect_pg_stat_bgwriter(&client).boxed(),
        ])
        .await
        {
            Ok(result) => {
                let (count, json_byte_size, received_byte_size) =
                    result
                        .iter()
                        .fold((0, JsonSize::zero(), 0), |res, (set, size)| {
                            (
                                res.0 + set.len(),
                                res.1 + set.estimated_json_encoded_size_of(),
                                res.2 + size,
                            )
                        });
                emit!(EndpointBytesReceived {
                    byte_size: received_byte_size,
                    protocol: "tcp",
                    endpoint: &self.endpoint,
                });
                self.events_received
                    .emit(CountByteSize(count, json_byte_size));
                self.client.set((client, client_version));
                Ok(result.into_iter().flat_map(|(metrics, _)| metrics))
            }
            Err(error) => Err(error.to_string()),
        }
    }

    async fn collect_pg_stat_database(
        &self,
        client: &Client,
        client_version: usize,
    ) -> Result<(Vec<Metric>, usize), CollectError> {
        let rows = self
            .datname_filter
            .pg_stat_database(client)
            .await
            .context(QuerySnafu)?;

        let mut metrics = Vec::with_capacity(20 * rows.len());
        let mut reader = RowReader::default();
        for row in rows.iter() {
            let db = reader.read::<Option<&str>>(row, "datname")?.unwrap_or("");

            metrics.extend_from_slice(&[
                self.create_metric(
                    "pg_stat_database_datid",
                    gauge!(reader.read::<u32>(row, "datid")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_numbackends",
                    gauge!(reader.read::<i32>(row, "numbackends")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_xact_commit_total",
                    counter!(reader.read::<i64>(row, "xact_commit")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_xact_rollback_total",
                    counter!(reader.read::<i64>(row, "xact_rollback")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_blks_read_total",
                    counter!(reader.read::<i64>(row, "blks_read")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_blks_hit_total",
                    counter!(reader.read::<i64>(row, "blks_hit")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_tup_returned_total",
                    counter!(reader.read::<i64>(row, "tup_returned")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_tup_fetched_total",
                    counter!(reader.read::<i64>(row, "tup_fetched")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_tup_inserted_total",
                    counter!(reader.read::<i64>(row, "tup_inserted")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_tup_updated_total",
                    counter!(reader.read::<i64>(row, "tup_updated")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_tup_deleted_total",
                    counter!(reader.read::<i64>(row, "tup_deleted")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_conflicts_total",
                    counter!(reader.read::<i64>(row, "conflicts")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_temp_files_total",
                    counter!(reader.read::<i64>(row, "temp_files")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_temp_bytes_total",
                    counter!(reader.read::<i64>(row, "temp_bytes")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_deadlocks_total",
                    counter!(reader.read::<i64>(row, "deadlocks")?),
                    tags!(self.tags, "db" => db),
                ),
            ]);
            if client_version >= 120000 {
                metrics.extend_from_slice(&[
                    self.create_metric(
                        "pg_stat_database_checksum_failures_total",
                        counter!(reader
                            .read::<Option<i64>>(row, "checksum_failures")?
                            .unwrap_or(0)),
                        tags!(self.tags, "db" => db),
                    ),
                    self.create_metric(
                        "pg_stat_database_checksum_last_failure",
                        gauge!(reader
                            .read::<Option<DateTime<Utc>>>(row, "checksum_last_failure")?
                            .map(|t| t.timestamp())
                            .unwrap_or(0)),
                        tags!(self.tags, "db" => db),
                    ),
                ]);
            }
            metrics.extend_from_slice(&[
                self.create_metric(
                    "pg_stat_database_blk_read_time_seconds_total",
                    counter!(reader.read::<f64>(row, "blk_read_time")? / 1000f64),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_blk_write_time_seconds_total",
                    counter!(reader.read::<f64>(row, "blk_write_time")? / 1000f64),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_stats_reset",
                    gauge!(reader
                        .read::<Option<DateTime<Utc>>>(row, "stats_reset")?
                        .map(|t| t.timestamp())
                        .unwrap_or(0)),
                    tags!(self.tags, "db" => db),
                ),
            ]);
        }
        Ok((metrics, reader.into_inner()))
    }

    async fn collect_pg_stat_database_conflicts(
        &self,
        client: &Client,
    ) -> Result<(Vec<Metric>, usize), CollectError> {
        let rows = self
            .datname_filter
            .pg_stat_database_conflicts(client)
            .await
            .context(QuerySnafu)?;

        let mut metrics = Vec::with_capacity(5 * rows.len());
        let mut reader = RowReader::default();
        for row in rows.iter() {
            let db = reader.read::<&str>(row, "datname")?;

            metrics.extend_from_slice(&[
                self.create_metric(
                    "pg_stat_database_conflicts_confl_tablespace_total",
                    counter!(reader.read::<i64>(row, "confl_tablespace")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_conflicts_confl_lock_total",
                    counter!(reader.read::<i64>(row, "confl_lock")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_conflicts_confl_snapshot_total",
                    counter!(reader.read::<i64>(row, "confl_snapshot")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_conflicts_confl_bufferpin_total",
                    counter!(reader.read::<i64>(row, "confl_bufferpin")?),
                    tags!(self.tags, "db" => db),
                ),
                self.create_metric(
                    "pg_stat_database_conflicts_confl_deadlock_total",
                    counter!(reader.read::<i64>(row, "confl_deadlock")?),
                    tags!(self.tags, "db" => db),
                ),
            ]);
        }
        Ok((metrics, reader.into_inner()))
    }

    async fn collect_pg_stat_bgwriter(
        &self,
        client: &Client,
    ) -> Result<(Vec<Metric>, usize), CollectError> {
        let row = self
            .datname_filter
            .pg_stat_bgwriter(client)
            .await
            .context(QuerySnafu)?;
        let mut reader = RowReader::default();

        Ok((
            vec![
                self.create_metric(
                    "pg_stat_bgwriter_checkpoints_timed_total",
                    counter!(reader.read::<i64>(&row, "checkpoints_timed")?),
                    tags!(self.tags),
                ),
                self.create_metric(
                    "pg_stat_bgwriter_checkpoints_req_total",
                    counter!(reader.read::<i64>(&row, "checkpoints_req")?),
                    tags!(self.tags),
                ),
                self.create_metric(
                    "pg_stat_bgwriter_checkpoint_write_time_seconds_total",
                    counter!(reader.read::<f64>(&row, "checkpoint_write_time")? / 1000f64),
                    tags!(self.tags),
                ),
                self.create_metric(
                    "pg_stat_bgwriter_checkpoint_sync_time_seconds_total",
                    counter!(reader.read::<f64>(&row, "checkpoint_sync_time")? / 1000f64),
                    tags!(self.tags),
                ),
                self.create_metric(
                    "pg_stat_bgwriter_buffers_checkpoint_total",
                    counter!(reader.read::<i64>(&row, "buffers_checkpoint")?),
                    tags!(self.tags),
                ),
                self.create_metric(
                    "pg_stat_bgwriter_buffers_clean_total",
                    counter!(reader.read::<i64>(&row, "buffers_clean")?),
                    tags!(self.tags),
                ),
                self.create_metric(
                    "pg_stat_bgwriter_maxwritten_clean_total",
                    counter!(reader.read::<i64>(&row, "maxwritten_clean")?),
                    tags!(self.tags),
                ),
                self.create_metric(
                    "pg_stat_bgwriter_buffers_backend_total",
                    counter!(reader.read::<i64>(&row, "buffers_backend")?),
                    tags!(self.tags),
                ),
                self.create_metric(
                    "pg_stat_bgwriter_buffers_backend_fsync_total",
                    counter!(reader.read::<i64>(&row, "buffers_backend_fsync")?),
                    tags!(self.tags),
                ),
                self.create_metric(
                    "pg_stat_bgwriter_buffers_alloc_total",
                    counter!(reader.read::<i64>(&row, "buffers_alloc")?),
                    tags!(self.tags),
                ),
                self.create_metric(
                    "pg_stat_bgwriter_stats_reset",
                    gauge!(reader
                        .read::<DateTime<Utc>>(&row, "stats_reset")?
                        .timestamp()),
                    tags!(self.tags),
                ),
            ],
            reader.into_inner(),
        ))
    }

    fn create_metric(&self, name: &str, value: MetricValue, tags: MetricTags) -> Metric {
        Metric::new(name, MetricKind::Absolute, value)
            .with_namespace(self.namespace.clone())
            .with_tags(Some(tags))
            .with_timestamp(Some(Utc::now()))
    }
}

#[derive(Default)]
struct RowReader(usize);

impl RowReader {
    pub fn read<'a, T: FromSql<'a> + ByteSizeOf>(
        &mut self,
        row: &'a Row,
        key: &'static str,
    ) -> Result<T, CollectError> {
        let value = row_get_value::<T>(row, key)?;
        self.0 += value.size_of();
        Ok(value)
    }

    pub const fn into_inner(self) -> usize {
        self.0
    }
}

fn row_get_value<'a, T: FromSql<'a> + ByteSizeOf>(
    row: &'a Row,
    key: &'static str,
) -> Result<T, CollectError> {
    row.try_get::<&str, T>(key)
        .map_err(|source| CollectError::PostgresGetValue { source, key })
}

fn config_to_endpoint(config: &Config) -> String {
    let mut params: Vec<(&'static str, String)> = vec![];

    // options
    if let Some(options) = config.get_options() {
        params.push(("options", options.to_string()));
    }

    // application_name
    if let Some(name) = config.get_application_name() {
        params.push(("application_name", name.to_string()));
    }

    // ssl_mode, ignore default value (SslMode::Prefer)
    match config.get_ssl_mode() {
        SslMode::Disable => params.push(("sslmode", "disable".to_string())),
        SslMode::Prefer => {} // default, ignore
        SslMode::Require => params.push(("sslmode", "require".to_string())),
        // non_exhaustive enum
        _ => {
            warn!("Unknown variant of \"SslMode\".");
        }
    };

    // host
    for host in config.get_hosts() {
        match host {
            Host::Tcp(host) => params.push(("host", host.to_string())),
            #[cfg(unix)]
            Host::Unix(path) => params.push(("host", path.to_string_lossy().to_string())),
        }
    }

    // port
    for port in config.get_ports() {
        params.push(("port", port.to_string()));
    }

    // connect_timeout
    if let Some(connect_timeout) = config.get_connect_timeout() {
        params.push(("connect_timeout", connect_timeout.as_secs().to_string()));
    }

    // keepalives, ignore default value (true)
    if !config.get_keepalives() {
        params.push(("keepalives", "1".to_owned()));
    }

    // keepalives_idle, ignore default value (2 * 60 * 60)
    let keepalives_idle = config.get_keepalives_idle().as_secs();
    if keepalives_idle != 2 * 60 * 60 {
        params.push(("keepalives_idle", keepalives_idle.to_string()));
    }

    // target_session_attrs, ignore default value (TargetSessionAttrs::Any)
    match config.get_target_session_attrs() {
        TargetSessionAttrs::Any => {} // default, ignore
        TargetSessionAttrs::ReadWrite => {
            params.push(("target_session_attrs", "read-write".to_owned()))
        }
        // non_exhaustive enum
        _ => {
            warn!("Unknown variant of \"TargetSessionAttr\".");
        }
    }

    // channel_binding, ignore default value (ChannelBinding::Prefer)
    match config.get_channel_binding() {
        ChannelBinding::Disable => params.push(("channel_binding", "disable".to_owned())),
        ChannelBinding::Prefer => {} // default, ignore
        ChannelBinding::Require => params.push(("channel_binding", "require".to_owned())),
        // non_exhaustive enum
        _ => {
            warn!("Unknown variant of \"ChannelBinding\".");
        }
    }

    format!(
        "postgresql:///{}?{}",
        config.get_dbname().unwrap_or(""),
        params
            .into_iter()
            .map(|(k, v)| format!(
                "{}={}",
                percent_encoding(k.as_bytes()),
                percent_encoding(v.as_bytes())
            ))
            .collect::<Vec<String>>()
            .join("&")
    )
}

fn percent_encoding(input: &'_ [u8]) -> String {
    percent_encoding::percent_encode(input, percent_encoding::NON_ALPHANUMERIC).to_string()
}

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

    #[test]
    fn generate_config() {
        crate::test_util::test_generate_config::<PostgresqlMetricsConfig>();
    }
}

#[cfg(all(test, feature = "postgresql_metrics-integration-tests"))]
mod integration_tests {
    use std::path::PathBuf;

    use super::*;
    use crate::{
        event::Event,
        test_util::components::{assert_source_compliance, PULL_SOURCE_TAGS},
        tls, SourceSender,
    };

    fn pg_host() -> String {
        std::env::var("PG_HOST").unwrap_or_else(|_| "localhost".into())
    }

    fn pg_socket() -> PathBuf {
        std::env::var("PG_SOCKET")
            .map(PathBuf::from)
            .unwrap_or_else(|_| {
                let current_dir = std::env::current_dir().unwrap();
                current_dir
                    .join("tests")
                    .join("data")
                    .join("postgresql-local-socket")
            })
    }

    fn pg_url() -> String {
        std::env::var("PG_URL")
            .unwrap_or_else(|_| format!("postgres://vector:vector@{}/postgres", pg_host()))
    }

    async fn test_postgresql_metrics(
        endpoint: String,
        tls: Option<PostgresqlMetricsTlsConfig>,
        include_databases: Option<Vec<String>>,
        exclude_databases: Option<Vec<String>>,
    ) -> Vec<Event> {
        assert_source_compliance(&PULL_SOURCE_TAGS, async move {
            let config: Config = endpoint.parse().unwrap();
            let tags_endpoint = config_to_endpoint(&config);
            let tags_host = match config.get_hosts().first().unwrap() {
                Host::Tcp(host) => host.clone(),
                #[cfg(unix)]
                Host::Unix(path) => path.to_string_lossy().to_string(),
            };

            let (sender, mut recv) = SourceSender::new_test();

            tokio::spawn(async move {
                PostgresqlMetricsConfig {
                    endpoints: vec![endpoint],
                    tls,
                    include_databases,
                    exclude_databases,
                    ..Default::default()
                }
                .build(SourceContext::new_test(sender, None))
                .await
                .unwrap()
                .await
                .unwrap()
            });

            let event = time::timeout(time::Duration::from_secs(3), recv.next())
                .await
                .expect("fetch metrics timeout")
                .expect("failed to get metrics from a stream");
            let mut events = vec![event];
            loop {
                match time::timeout(time::Duration::from_millis(10), recv.next()).await {
                    Ok(Some(event)) => events.push(event),
                    Ok(None) => break,
                    Err(_) => break,
                }
            }

            assert!(events.len() > 1);

            // test up metric
            assert_eq!(
                events
                    .iter()
                    .map(|e| e.as_metric())
                    .find(|e| e.name() == "up")
                    .unwrap()
                    .value(),
                &gauge!(1)
            );

            // test namespace and tags
            for event in &events {
                let metric = event.as_metric();

                assert_eq!(metric.namespace(), Some("postgresql"));
                assert_eq!(
                    metric.tags().unwrap().get("endpoint").unwrap(),
                    &tags_endpoint
                );
                assert_eq!(metric.tags().unwrap().get("host").unwrap(), &tags_host);
            }

            // test metrics from different queries
            let names = vec![
                "pg_stat_database_datid",
                "pg_stat_database_conflicts_confl_tablespace_total",
                "pg_stat_bgwriter_checkpoints_timed_total",
            ];
            for name in names {
                assert!(events.iter().any(|e| e.as_metric().name() == name));
            }

            events
        })
        .await
    }

    #[tokio::test]
    async fn test_host() {
        test_postgresql_metrics(pg_url(), None, None, None).await;
    }

    #[tokio::test]
    async fn test_local() {
        let endpoint = format!(
            "postgresql:///postgres?host={}&user=vector&password=vector",
            pg_socket().to_str().unwrap()
        );
        test_postgresql_metrics(endpoint, None, None, None).await;
    }

    #[tokio::test]
    async fn test_host_ssl() {
        test_postgresql_metrics(
            format!("{}?sslmode=require", pg_url()),
            Some(PostgresqlMetricsTlsConfig {
                ca_file: tls::TEST_PEM_CA_PATH.into(),
            }),
            None,
            None,
        )
        .await;
    }

    #[tokio::test]
    async fn test_host_include_databases() {
        let events = test_postgresql_metrics(
            pg_url(),
            None,
            Some(vec!["^vec".to_owned(), "gres$".to_owned()]),
            None,
        )
        .await;

        for event in events {
            let metric = event.into_metric();

            if let Some(db) = metric.tags().unwrap().get("db") {
                assert!(db == "vector" || db == "postgres");
            }
        }
    }

    #[tokio::test]
    async fn test_host_exclude_databases() {
        let events = test_postgresql_metrics(
            pg_url(),
            None,
            None,
            Some(vec!["^vec".to_owned(), "gres$".to_owned()]),
        )
        .await;

        for event in events {
            let metric = event.into_metric();

            if let Some(db) = metric.tags().unwrap().get("db") {
                assert!(db != "vector" && db != "postgres");
            }
        }
    }

    #[tokio::test]
    async fn test_host_exclude_databases_empty() {
        test_postgresql_metrics(pg_url(), None, None, Some(vec!["".to_owned()])).await;
    }

    #[tokio::test]
    async fn test_host_include_databases_and_exclude_databases() {
        let events = test_postgresql_metrics(
            pg_url(),
            None,
            Some(vec!["template\\d+".to_owned()]),
            Some(vec!["template0".to_owned()]),
        )
        .await;

        for event in events {
            let metric = event.into_metric();

            if let Some(db) = metric.tags().unwrap().get("db") {
                assert!(db == "template1");
            }
        }
    }
}