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
//! `FraiseClient` implementation
use super::connection_string::{ConnectionInfo, TransportType};
use super::query_builder::QueryBuilder;
use crate::connection::{Connection, ConnectionConfig, Transport};
#[allow(unused_imports)] // Reason: used only in doc links for `# Errors` sections
use crate::error::WireError;
use crate::stream::JsonStream;
use crate::Result;
use serde::de::DeserializeOwned;
/// FraiseQL wire protocol client
pub struct FraiseClient {
conn: Connection,
}
impl FraiseClient {
/// Connect to Postgres using connection string
///
/// # Errors
///
/// Returns [`WireError::Config`] if the connection string is invalid or missing required
/// fields. Returns [`WireError`] if the TCP or Unix socket connection fails, or if
/// startup/authentication is rejected by the server.
///
/// # Examples
///
/// ```no_run
/// // Requires: live Postgres server.
/// # async fn example() -> fraiseql_wire::Result<()> {
/// use fraiseql_wire::FraiseClient;
///
/// // TCP connection
/// let client = FraiseClient::connect("postgres://localhost/mydb").await?;
///
/// // Unix socket
/// let client = FraiseClient::connect("postgres:///mydb").await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns [`WireError::Config`] if the connection string is malformed or missing
/// required fields (host/port for TCP, path for Unix sockets).
/// Returns [`WireError::Io`] if the underlying TCP or Unix socket connection fails.
pub async fn connect(connection_string: &str) -> Result<Self> {
let info = ConnectionInfo::parse(connection_string)?;
let transport = match info.transport {
TransportType::Tcp => {
let host = info.host.as_ref().ok_or_else(|| {
crate::WireError::Config("TCP transport requires a host".into())
})?;
let port = info.port.ok_or_else(|| {
crate::WireError::Config("TCP transport requires a port".into())
})?;
Transport::connect_tcp(host, port).await?
}
TransportType::Unix => {
let path = info.unix_socket.as_ref().ok_or_else(|| {
crate::WireError::Config("Unix transport requires a socket path".into())
})?;
Transport::connect_unix(path).await?
}
};
let mut conn = Connection::new(transport);
let config = info.to_config();
conn.startup(&config).await?;
Ok(Self { conn })
}
/// Connect to Postgres with TLS encryption
///
/// TLS is configured independently from the connection string. The connection string
/// should contain the hostname and credentials (user/password), while TLS configuration
/// is provided separately via `TlsConfig`.
///
/// # Errors
///
/// Returns [`WireError::Config`] if the connection string is invalid, TLS is requested
/// over a Unix socket, or required fields are missing. Returns [`WireError::Io`] if the
/// TLS handshake or TCP connection fails.
///
/// # Examples
///
/// ```no_run
/// // Requires: live Postgres server with TLS.
/// # async fn example() -> fraiseql_wire::Result<()> {
/// use fraiseql_wire::{FraiseClient, connection::TlsConfig};
///
/// // Configure TLS with system root certificates
/// let tls = TlsConfig::builder()
/// .verify_hostname(true)
/// .build()?;
///
/// // Connect with TLS
/// let client = FraiseClient::connect_tls("postgres://secure.db.example.com/mydb", tls).await?;
/// # Ok(())
/// # }
/// ```
pub async fn connect_tls(
connection_string: &str,
tls_config: crate::connection::TlsConfig,
) -> Result<Self> {
let info = ConnectionInfo::parse(connection_string)?;
let transport = match info.transport {
TransportType::Tcp => {
let host = info.host.as_ref().ok_or_else(|| {
crate::WireError::Config("TCP transport requires a host".into())
})?;
let port = info.port.ok_or_else(|| {
crate::WireError::Config("TCP transport requires a port".into())
})?;
Transport::connect_tcp_tls(host, port, &tls_config).await?
}
TransportType::Unix => {
return Err(crate::WireError::Config(
"TLS is only supported for TCP connections".into(),
));
}
};
let mut conn = Connection::new(transport);
let config = info.to_config();
conn.startup(&config).await?;
Ok(Self { conn })
}
/// Connect to Postgres with custom connection configuration
///
/// This method allows you to configure timeouts, keepalive intervals, and other
/// connection options. The connection configuration is merged with parameters from
/// the connection string.
///
/// # Errors
///
/// Returns [`WireError::Config`] if the connection string is invalid or missing required
/// fields. Returns [`WireError::Io`] if the TCP or Unix socket connection fails, or if
/// startup/authentication is rejected by the server.
///
/// # Examples
///
/// ```no_run
/// // Requires: live Postgres server.
/// # async fn example() -> fraiseql_wire::Result<()> {
/// use fraiseql_wire::{FraiseClient, connection::ConnectionConfig};
/// use std::time::Duration;
///
/// // Build connection configuration with timeouts
/// let config = ConnectionConfig::builder("localhost", "mydb")
/// .password("secret")
/// .statement_timeout(Duration::from_secs(30))
/// .keepalive_idle(Duration::from_secs(300))
/// .application_name("my_app")
/// .build();
///
/// // Connect with configuration
/// let client = FraiseClient::connect_with_config("postgres://localhost:5432/mydb", config).await?;
/// # Ok(())
/// # }
/// ```
pub async fn connect_with_config(
connection_string: &str,
config: ConnectionConfig,
) -> Result<Self> {
let info = ConnectionInfo::parse(connection_string)?;
let transport = match info.transport {
TransportType::Tcp => {
let host = info.host.as_ref().ok_or_else(|| {
crate::WireError::Config("TCP transport requires a host".into())
})?;
let port = info.port.ok_or_else(|| {
crate::WireError::Config("TCP transport requires a port".into())
})?;
Transport::connect_tcp(host, port).await?
}
TransportType::Unix => {
let path = info.unix_socket.as_ref().ok_or_else(|| {
crate::WireError::Config("Unix transport requires a socket path".into())
})?;
Transport::connect_unix(path).await?
}
};
// Apply TCP keepalive when configured.
if let Some(idle) = config.keepalive_idle {
if let Err(e) = transport.apply_keepalive(idle) {
tracing::warn!("Failed to apply TCP keepalive (idle={idle:?}): {e}");
}
}
let mut conn = Connection::new(transport);
conn.startup(&config).await?;
Ok(Self { conn })
}
/// Connect to Postgres with both custom configuration and TLS encryption
///
/// This method combines connection configuration (timeouts, keepalive, etc.)
/// with TLS encryption for secure connections with advanced options.
///
/// # Errors
///
/// Returns [`WireError::Config`] if the connection string is invalid, TLS is requested
/// over a Unix socket, or required fields are missing. Returns [`WireError::Io`] if the
/// TLS handshake or TCP connection fails.
///
/// # Examples
///
/// ```no_run
/// // Requires: live Postgres server with TLS.
/// # async fn example() -> fraiseql_wire::Result<()> {
/// use fraiseql_wire::{FraiseClient, connection::{ConnectionConfig, TlsConfig}};
/// use std::time::Duration;
///
/// // Configure connection with timeouts
/// let config = ConnectionConfig::builder("localhost", "mydb")
/// .password("secret")
/// .statement_timeout(Duration::from_secs(30))
/// .build();
///
/// // Configure TLS
/// let tls = TlsConfig::builder()
/// .verify_hostname(true)
/// .build()?;
///
/// // Connect with both configuration and TLS
/// let client = FraiseClient::connect_with_config_and_tls(
/// "postgres://secure.db.example.com/mydb",
/// config,
/// tls
/// ).await?;
/// # Ok(())
/// # }
/// ```
pub async fn connect_with_config_and_tls(
connection_string: &str,
config: ConnectionConfig,
tls_config: crate::connection::TlsConfig,
) -> Result<Self> {
let info = ConnectionInfo::parse(connection_string)?;
let transport = match info.transport {
TransportType::Tcp => {
let host = info.host.as_ref().ok_or_else(|| {
crate::WireError::Config("TCP transport requires a host".into())
})?;
let port = info.port.ok_or_else(|| {
crate::WireError::Config("TCP transport requires a port".into())
})?;
Transport::connect_tcp_tls(host, port, &tls_config).await?
}
TransportType::Unix => {
return Err(crate::WireError::Config(
"TLS is only supported for TCP connections".into(),
));
}
};
// Apply TCP keepalive when configured.
if let Some(idle) = config.keepalive_idle {
if let Err(e) = transport.apply_keepalive(idle) {
tracing::warn!("Failed to apply TCP keepalive (idle={idle:?}): {e}");
}
}
let mut conn = Connection::new(transport);
conn.startup(&config).await?;
Ok(Self { conn })
}
/// Start building a query for an entity with automatic deserialization
///
/// The type parameter T controls consumer-side deserialization only.
/// Type T does NOT affect SQL generation, filtering, ordering, or wire protocol.
///
/// # Examples
///
/// Type-safe query (recommended):
/// ```no_run
/// // Requires: live Postgres server.
/// # async fn example(client: fraiseql_wire::FraiseClient) -> fraiseql_wire::Result<()> {
/// use serde::Deserialize;
/// use futures::stream::StreamExt;
///
/// #[derive(Deserialize)]
/// struct User {
/// id: String,
/// name: String,
/// }
///
/// let mut stream = client
/// .query::<User>("user")
/// .where_sql("data->>'type' = 'customer'") // SQL predicate
/// .where_rust(|json| {
/// // Rust predicate (applied client-side, on JSON)
/// json["estimated_value"].as_f64().unwrap_or(0.0) > 1000.0
/// })
/// .order_by("data->>'name' ASC")
/// .execute()
/// .await?;
///
/// while let Some(result) = stream.next().await {
/// let user: User = result?;
/// println!("User: {}", user.name);
/// }
/// # Ok(())
/// # }
/// ```
///
/// Raw JSON query (debugging, forward compatibility):
/// ```no_run
/// // Requires: live Postgres server.
/// # async fn example(client: fraiseql_wire::FraiseClient) -> fraiseql_wire::Result<()> {
/// use futures::stream::StreamExt;
///
/// let mut stream = client
/// .query::<serde_json::Value>("user") // Escape hatch
/// .execute()
/// .await?;
///
/// while let Some(result) = stream.next().await {
/// let json = result?;
/// println!("JSON: {:?}", json);
/// }
/// # Ok(())
/// # }
/// ```
pub fn query<T: DeserializeOwned + std::marker::Unpin + 'static>(
self,
entity: impl Into<String>,
) -> QueryBuilder<T> {
QueryBuilder::new(self, entity)
}
/// Execute a raw SQL query (must match fraiseql-wire constraints)
pub(crate) async fn execute_query(
self,
sql: &str,
chunk_size: usize,
max_memory: Option<usize>,
soft_limit_warn_threshold: Option<f32>,
soft_limit_fail_threshold: Option<f32>,
) -> Result<JsonStream> {
self.conn
.streaming_query(
sql,
chunk_size,
max_memory,
soft_limit_warn_threshold,
soft_limit_fail_threshold,
false, // enable_adaptive_chunking: disabled by default for backward compatibility
None, // adaptive_min_chunk_size
None, // adaptive_max_chunk_size
)
.await
}
}