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
//! PgDriverBuilder — ergonomic builder pattern for PgDriver connections.
use super::auth_types::{
AuthSettings, ConnectOptions, GssEncMode, GssTokenProvider, ScramChannelBindingMode, TlsMode,
};
use super::core::PgDriver;
use super::types::{PgError, PgResult};
use crate::driver::connection::TlsConfig;
// ============================================================================
// Connection Builder
// ============================================================================
/// Builder for creating PgDriver connections with named parameters.
/// # Example
/// ```ignore
/// let driver = PgDriver::builder()
/// .host("localhost")
/// .port(5432)
/// .user("admin")
/// .database("mydb")
/// .password("secret")
/// .connect()
/// .await?;
/// ```
#[derive(Default)]
pub struct PgDriverBuilder {
host: Option<String>,
port: Option<u16>,
user: Option<String>,
database: Option<String>,
password: Option<String>,
timeout: Option<std::time::Duration>,
pub(crate) connect_options: ConnectOptions,
}
impl PgDriverBuilder {
/// Create a new builder with default values.
pub fn new() -> Self {
Self::default()
}
/// Set the host (default: "127.0.0.1").
pub fn host(mut self, host: impl Into<String>) -> Self {
self.host = Some(host.into());
self
}
/// Set the port (default: 5432).
pub fn port(mut self, port: u16) -> Self {
self.port = Some(port);
self
}
/// Set the username (required).
pub fn user(mut self, user: impl Into<String>) -> Self {
self.user = Some(user.into());
self
}
/// Set the database name (required).
pub fn database(mut self, database: impl Into<String>) -> Self {
self.database = Some(database.into());
self
}
/// Set the password (optional, for cleartext/MD5/SCRAM-SHA-256 auth).
pub fn password(mut self, password: impl Into<String>) -> Self {
self.password = Some(password.into());
self
}
/// Set connection timeout (optional).
pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
self.timeout = Some(timeout);
self
}
/// Set TLS policy (`disable`, `prefer`, `require`).
pub fn tls_mode(mut self, mode: TlsMode) -> Self {
self.connect_options.tls_mode = mode;
self
}
/// Set GSSAPI session encryption mode (`disable`, `prefer`, `require`).
pub fn gss_enc_mode(mut self, mode: GssEncMode) -> Self {
self.connect_options.gss_enc_mode = mode;
self
}
/// Set custom CA bundle PEM for TLS validation.
pub fn tls_ca_cert_pem(mut self, ca_pem: Vec<u8>) -> Self {
self.connect_options.tls_ca_cert_pem = Some(ca_pem);
self
}
/// Enable mTLS using client certificate/key config.
pub fn mtls(mut self, config: TlsConfig) -> Self {
self.connect_options.mtls = Some(config);
self.connect_options.tls_mode = TlsMode::Require;
self
}
/// Override password-auth policy.
pub fn auth_settings(mut self, settings: AuthSettings) -> Self {
self.connect_options.auth = settings;
self
}
/// Set SCRAM channel-binding mode.
pub fn channel_binding_mode(mut self, mode: ScramChannelBindingMode) -> Self {
self.connect_options.auth.channel_binding = mode;
self
}
/// Opt into Linux io_uring for plain TCP transport.
pub fn io_uring(mut self, enabled: bool) -> Self {
self.connect_options.io_uring = enabled;
self
}
/// Set a stateful Kerberos/GSS/SSPI token provider.
pub fn gss_token_provider(mut self, provider: GssTokenProvider) -> Self {
self.connect_options.gss_token_provider = Some(provider);
self
}
/// Add a custom StartupMessage parameter.
///
/// Example: `.startup_param("application_name", "qail-replica")`
pub fn startup_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
let key = key.into();
let value = value.into();
self.connect_options
.startup_params
.retain(|(existing, _)| !existing.eq_ignore_ascii_case(&key));
self.connect_options.startup_params.push((key, value));
self
}
/// Enable logical replication startup mode (`replication=database`).
///
/// This is required before issuing commands like `IDENTIFY_SYSTEM` or
/// `CREATE_REPLICATION_SLOT` on a replication connection.
pub fn logical_replication(mut self) -> Self {
self.connect_options
.startup_params
.retain(|(k, _)| !k.eq_ignore_ascii_case("replication"));
self.connect_options
.startup_params
.push(("replication".to_string(), "database".to_string()));
self
}
/// Connect to PostgreSQL using the configured parameters.
pub async fn connect(self) -> PgResult<PgDriver> {
let host = self.host.unwrap_or_else(|| "127.0.0.1".to_string());
let port = self.port.unwrap_or(5432);
let user = self
.user
.ok_or_else(|| PgError::Connection("User is required".to_string()))?;
let database = self
.database
.ok_or_else(|| PgError::Connection("Database is required".to_string()))?;
let password = self.password;
let options = self.connect_options;
if let Some(timeout) = self.timeout {
let options = options.clone();
tokio::time::timeout(
timeout,
PgDriver::connect_with_options(
&host,
port,
&user,
&database,
password.as_deref(),
options,
),
)
.await
.map_err(|_| PgError::Timeout(format!("connection after {:?}", timeout)))?
} else {
PgDriver::connect_with_options(
&host,
port,
&user,
&database,
password.as_deref(),
options,
)
.await
}
}
}