Skip to main content

feldera_types/transport/
postgres.rs

1use serde::{Deserialize, Serialize};
2use std::fmt::Display;
3use utoipa::ToSchema;
4
5/// PostgreSQL write mode.
6///
7/// Determines how the PostgreSQL output connector writes data to the target table.
8#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
9pub enum PostgresWriteMode {
10    /// Materialized mode: perform direct INSERT, UPDATE, and DELETE operations on the table.
11    /// This is the default behavior and maintains the postgres table as a materialized snapshot of the output view.
12    #[default]
13    #[serde(rename = "materialized")]
14    Materialized,
15
16    /// CDC (Change Data Capture) mode: write all operations as INSERT operations
17    /// into a Postgres table that serves as an append-only event log.
18    /// In this mode, inserts, updates, and deletes are all represented as new rows
19    /// with metadata columns describing the operation type and timestamp.
20    #[serde(rename = "cdc")]
21    Cdc,
22}
23
24impl Display for PostgresWriteMode {
25    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26        match self {
27            Self::Materialized => write!(f, "materialized"),
28            Self::Cdc => write!(f, "cdc"),
29        }
30    }
31}
32
33/// TLS/SSL configuration for PostgreSQL connectors.
34#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
35pub struct PostgresTlsConfig {
36    /// A sequence of CA certificates in PEM format.
37    pub ssl_ca_pem: Option<String>,
38
39    /// Path to a file containing a sequence of CA certificates in PEM format.
40    pub ssl_ca_location: Option<String>,
41
42    /// The client certificate in PEM format.
43    pub ssl_client_pem: Option<String>,
44
45    /// Path to the client certificate.
46    pub ssl_client_location: Option<String>,
47
48    /// The client certificate key in PEM format.
49    pub ssl_client_key: Option<String>,
50
51    /// Path to the client certificate key.
52    pub ssl_client_key_location: Option<String>,
53
54    /// The path to the certificate chain file.
55    /// The file must contain a sequence of PEM-formatted certificates,
56    /// the first being the leaf certificate, and the remainder forming
57    /// the chain of certificates up to and including the trusted root certificate.
58    pub ssl_certificate_chain_location: Option<String>,
59
60    /// True to enable hostname verification when using TLS. True by default.
61    ///
62    /// When false, the certificate chain is still verified against the
63    /// trusted CA; only the requirement that the server name appears in the
64    /// certificate is lifted.
65    pub verify_hostname: Option<bool>,
66}
67
68impl PostgresTlsConfig {
69    pub fn has_tls(&self) -> bool {
70        self.ssl_ca_pem.is_some() || self.ssl_ca_location.is_some()
71    }
72}
73
74/// Postgres CDC input connector configuration.
75///
76/// Uses logical replication to capture ongoing changes from a Postgres database.
77/// Requires a pre-created publication. Automatic source migrations require a
78/// superuser; with administrator-installed source objects and
79/// `run_source_migrations = false`, a replication role with the documented
80/// source-table and etl state-store privileges can be used instead.
81/// Tables must have primary keys and `REPLICA IDENTITY FULL` is recommended
82/// for UPDATE/DELETE support.
83#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
84pub struct PostgresCdcReaderConfig {
85    /// Postgres connection URI. Automatic source migrations require a superuser.
86    /// With `run_source_migrations = false`, the user needs REPLICATION and the
87    /// grants described in [Running as a non-superuser](https://docs.feldera.com/connectors/sources/postgresql-cdc#running-as-a-non-superuser).
88    /// See: <https://docs.rs/tokio-postgres/0.7.12/tokio_postgres/config/struct.Config.html>
89    pub uri: String,
90
91    /// Name of the pre-created Postgres publication to replicate from.
92    pub publication: String,
93
94    /// Postgres table to replicate, schema-qualified (e.g. "public.orders").
95    /// A name given without a schema refers to a table in "public".
96    /// Must be included in the publication.
97    pub source_table: String,
98
99    /// Whether the connector runs etl's source migrations on startup.
100    ///
101    /// The source migrations install the schema helper functions and the
102    /// `ddl_command_end` event trigger. Creating the event trigger requires a
103    /// superuser, so a de-elevated role can set this to `false` and have an
104    /// administrator install the source objects out-of-band. Disabling this
105    /// does not skip the state-store migrations, which run on every start
106    /// regardless.
107    ///
108    /// Default: `true`.
109    #[serde(default = "default_run_source_migrations")]
110    #[schema(default = default_run_source_migrations)]
111    pub run_source_migrations: bool,
112
113    /// TLS/SSL configuration.
114    #[serde(flatten)]
115    #[schema(inline)]
116    pub tls: PostgresTlsConfig,
117}
118
119fn default_run_source_migrations() -> bool {
120    true
121}
122
123impl PostgresCdcReaderConfig {
124    pub fn validate(&self) -> Result<(), String> {
125        if self.publication.trim().is_empty() {
126            return Err("publication cannot be empty".to_string());
127        }
128
129        if self.source_table.trim().is_empty() {
130            return Err("source_table cannot be empty".to_string());
131        }
132
133        if self.tls.ssl_client_pem.is_some()
134            || self.tls.ssl_client_location.is_some()
135            || self.tls.ssl_client_key.is_some()
136            || self.tls.ssl_client_key_location.is_some()
137            || self.tls.ssl_certificate_chain_location.is_some()
138        {
139            return Err(
140                "client-certificate TLS options (ssl_client_pem, ssl_client_location, \
141                 ssl_client_key, ssl_client_key_location, ssl_certificate_chain_location) \
142                 are not supported by the Postgres CDC connector as the underlying etl crate \
143                 doesn't support client-certificate TLS yet. CA-based TLS via ssl_ca_pem \
144                 or ssl_ca_location is supported. Please file an issue if you require \
145                 client-certificate TLS support: https://github.com/feldera/feldera/issues/
146                 "
147                .to_string(),
148            );
149        }
150
151        if self.tls.verify_hostname == Some(false) {
152            return Err(
153                "disabling hostname verification is not supported by the Postgres CDC connector"
154                    .to_string(),
155            );
156        }
157
158        Ok(())
159    }
160}
161
162/// Postgres input connector configuration.
163#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
164pub struct PostgresReaderConfig {
165    /// Postgres URI.
166    /// See: <https://docs.rs/tokio-postgres/0.7.12/tokio_postgres/config/struct.Config.html>
167    pub uri: String,
168
169    /// Query that specifies what data to fetch from postgres.
170    pub query: String,
171
172    /// TLS/SSL configuration.
173    #[serde(flatten)]
174    #[schema(inline)]
175    pub tls: PostgresTlsConfig,
176}
177
178/// Postgres output connector configuration.
179#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
180pub struct PostgresWriterConfig {
181    /// Postgres URI.
182    /// See: <https://docs.rs/tokio-postgres/0.7.12/tokio_postgres/config/struct.Config.html>
183    pub uri: String,
184
185    /// The table to write the output to.
186    pub table: String,
187
188    /// Write mode for the connector.
189    ///
190    /// - `materialized` (default): Perform direct INSERT, UPDATE, and DELETE operations on the table.
191    /// - `cdc`: Write all operations as INSERT operations into an append-only event log
192    ///   with additional metadata columns describing the operation type and timestamp.
193    #[serde(default)]
194    #[schema(default = PostgresWriteMode::default)]
195    pub mode: PostgresWriteMode,
196
197    /// Name of the operation metadata column in CDC mode.
198    ///
199    /// Only used when `mode = "cdc"`. This column will contain:
200    /// - `"i"` for insert operations
201    /// - `"u"` for upsert operations
202    /// - `"d"` for delete operations
203    ///
204    /// Default: `"__feldera_op"`
205    #[serde(default = "default_cdc_op_column")]
206    #[schema(default = default_cdc_op_column)]
207    pub cdc_op_column: String,
208
209    /// Name of the timestamp metadata column in CDC mode.
210    ///
211    /// Only used when `mode = "cdc"`. This column will contain the timestamp
212    /// (in RFC 3339 format) when the batch of updates was output
213    /// by the pipeline.
214    ///
215    /// Default: `"__feldera_ts"`
216    #[serde(default = "default_cdc_ts_column")]
217    #[schema(default = default_cdc_ts_column)]
218    pub cdc_ts_column: String,
219
220    /// TLS/SSL configuration.
221    #[serde(flatten)]
222    #[schema(inline)]
223    pub tls: PostgresTlsConfig,
224
225    /// The maximum number of records in a single buffer.
226    pub max_records_in_buffer: Option<usize>,
227
228    /// The maximum buffer size in for a single operation.
229    /// Note that the buffers of `INSERT`, `UPDATE` and `DELETE` queries are
230    /// separate.
231    /// Default: 1 MiB
232    #[schema(default = default_max_buffer_size)]
233    #[serde(default = "default_max_buffer_size")]
234    pub max_buffer_size_bytes: usize,
235
236    /// Specifies how the connector handles conflicts when executing an `INSERT`
237    /// into a table with a primary key. By default, an existing row with the same
238    /// key is overwritten. Setting this flag to `true` preserves the existing row
239    /// and ignores the new insert.
240    ///
241    /// This setting does not affect `UPDATE` statements, which always replace the
242    /// value associated with the key.
243    ///
244    /// This setting is not supported when `mode = "cdc"`, since all operations
245    /// are performed as append-only `INSERT`s into the target table.
246    /// Any conflict in CDC mode will result in an error.
247    ///
248    /// Default: `false`
249    #[serde(default)]
250    pub on_conflict_do_nothing: bool,
251
252    /// The number of threads to use during encoding.
253    ///
254    /// Default: 1
255    #[serde(default = "default_writer_threads")]
256    #[schema(default = default_writer_threads)]
257    pub threads: usize,
258
259    /// The names of the extra columns in the Postgres table that are not part of the view schema.
260    ///
261    /// These connector can write user-defined values, configured using the `set_extra_columns` connector command,
262    /// to these columns.
263    #[serde(default, skip_serializing_if = "Vec::is_empty")]
264    pub extra_columns: Vec<String>,
265}
266
267fn default_max_buffer_size() -> usize {
268    usize::pow(2, 20)
269}
270
271fn default_writer_threads() -> usize {
272    1
273}
274
275fn default_cdc_op_column() -> String {
276    "__feldera_op".to_string()
277}
278
279fn default_cdc_ts_column() -> String {
280    "__feldera_ts".to_string()
281}
282
283impl PostgresWriterConfig {
284    pub fn validate(&self) -> Result<(), String> {
285        match self.mode {
286            PostgresWriteMode::Cdc => {
287                if self.cdc_op_column.trim().is_empty() {
288                    return Err("cdc_op_column cannot be empty in CDC mode".to_string());
289                }
290                if self.cdc_ts_column.trim().is_empty() {
291                    return Err("cdc_ts_column cannot be empty in CDC mode".to_string());
292                }
293
294                if !self.cdc_op_column.is_ascii() {
295                    return Err("cdc_op_column must contain only ASCII characters".to_string());
296                }
297
298                if !self.cdc_ts_column.is_ascii() {
299                    return Err("cdc_ts_column must contain only ASCII characters".to_string());
300                }
301
302                if self.on_conflict_do_nothing {
303                    return Err("on_conflict_do_nothing not supported in CDC mode since all operations are performed as append-only INSERTs into the target table".to_string());
304                }
305            }
306            PostgresWriteMode::Materialized => {
307                if self.cdc_ts_column != default_cdc_ts_column()
308                    && !self.cdc_ts_column.trim().is_empty()
309                {
310                    return Err(
311                        "cdc_ts_column must not be set when in MATERIALIZED mode".to_string()
312                    );
313                }
314                if self.cdc_op_column != default_cdc_op_column()
315                    && !self.cdc_op_column.trim().is_empty()
316                {
317                    return Err(
318                        "cdc_op_column must not be set when in MATERIALIZED mode".to_string()
319                    );
320                }
321            }
322        };
323
324        if self.threads == 0 {
325            return Err("threads must be at least 1".to_string());
326        }
327
328        Ok(())
329    }
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335    use serde_json::json;
336
337    fn postgres_cdc_config(tls: PostgresTlsConfig) -> PostgresCdcReaderConfig {
338        PostgresCdcReaderConfig {
339            uri: "postgres://user:password@localhost:5432/database".to_string(),
340            publication: "publication".to_string(),
341            source_table: "public.table".to_string(),
342            run_source_migrations: true,
343            tls,
344        }
345    }
346
347    #[test]
348    fn postgres_cdc_config_rejects_client_certificate_tls_options() {
349        let config = postgres_cdc_config(PostgresTlsConfig {
350            ssl_client_pem: Some("client".to_string()),
351            ..Default::default()
352        });
353
354        let err = config.validate().unwrap_err();
355        assert!(err.contains("client-certificate TLS options"));
356        assert!(err.contains("client-certificate TLS support"));
357        assert!(!err.contains("doesn't support TLS yet"));
358    }
359
360    #[test]
361    fn postgres_cdc_config_rejects_disabled_hostname_verification() {
362        let config = postgres_cdc_config(PostgresTlsConfig {
363            verify_hostname: Some(false),
364            ..Default::default()
365        });
366
367        let err = config.validate().unwrap_err();
368        assert!(err.contains("disabling hostname verification"));
369    }
370
371    #[test]
372    fn postgres_cdc_config_accepts_default_tls() {
373        let config = postgres_cdc_config(PostgresTlsConfig::default());
374
375        assert!(config.validate().is_ok());
376    }
377
378    #[test]
379    fn postgres_cdc_config_rejects_empty_publication() {
380        let mut config = postgres_cdc_config(PostgresTlsConfig::default());
381        config.publication = "   ".to_string();
382
383        let err = config.validate().unwrap_err();
384        assert!(err.contains("publication cannot be empty"));
385    }
386
387    #[test]
388    fn postgres_cdc_config_rejects_empty_source_table() {
389        let mut config = postgres_cdc_config(PostgresTlsConfig::default());
390        config.source_table = "\t".to_string();
391
392        let err = config.validate().unwrap_err();
393        assert!(err.contains("source_table cannot be empty"));
394    }
395
396    #[test]
397    fn postgres_cdc_config_defaults_run_source_migrations_to_true() {
398        let config: PostgresCdcReaderConfig = serde_json::from_value(json!({
399            "uri": "postgres://user:password@localhost:5432/database",
400            "publication": "publication",
401            "source_table": "public.table",
402        }))
403        .unwrap();
404
405        assert!(config.run_source_migrations);
406    }
407
408    #[test]
409    fn postgres_cdc_config_honors_run_source_migrations_false() {
410        let config: PostgresCdcReaderConfig = serde_json::from_value(json!({
411            "uri": "postgres://user:password@localhost:5432/database",
412            "publication": "publication",
413            "source_table": "public.table",
414            "run_source_migrations": false,
415        }))
416        .unwrap();
417
418        assert!(!config.run_source_migrations);
419    }
420
421    #[test]
422    fn postgres_cdc_config_round_trips_run_source_migrations() {
423        for enabled in [true, false] {
424            let mut config = postgres_cdc_config(PostgresTlsConfig::default());
425            config.run_source_migrations = enabled;
426            let json = serde_json::to_value(&config).unwrap();
427            assert_eq!(json["run_source_migrations"], enabled);
428            let decoded: PostgresCdcReaderConfig = serde_json::from_value(json).unwrap();
429            assert_eq!(decoded, config);
430        }
431    }
432}