Skip to main content

reddb_server/wire/postgres/
server.rs

1//! PostgreSQL wire-protocol listener (Phase 3.1 PG parity).
2//!
3//! Accepts TCP connections from PG-compatible clients, drives the startup
4//! handshake, and routes simple/extended-query frames into the existing
5//! `RedDBRuntime::execute_query` path. Results are adapted back into PG
6//! `RowDescription` + `DataRow` frames via `types::value_to_pg_wire_bytes`.
7
8use std::collections::HashMap;
9use std::sync::Arc;
10
11use tokio::io::{AsyncRead, AsyncWrite};
12use tokio::net::TcpListener;
13
14use super::catalog_views::translate_pg_catalog_query;
15use super::protocol::{
16    read_frame, read_startup, write_frame, write_raw_byte, BackendMessage, ColumnDescriptor,
17    DescribeTarget, FrontendMessage, PgWireError, TransactionStatus,
18};
19use super::types::{pg_param_to_param_value, value_to_pg_wire_bytes, PgOid};
20use crate::auth::Role;
21use crate::runtime::query_request::{
22    ParamValue, PreparedId, PreparedRegistry, QueryRequest, QueryRequestExecutor,
23};
24use crate::runtime::RedDBRuntime;
25use crate::storage::query::unified::{UnifiedRecord, UnifiedResult};
26use reddb_rql::ast::QueryExpr;
27use reddb_types::Value;
28
29/// Startup-tuned configuration for the PG wire listener.
30#[derive(Debug, Clone)]
31pub struct PgWireConfig {
32    /// TCP bind address ("host:port"). The caller is responsible for
33    /// keeping this disjoint from the native wire / gRPC / HTTP listeners.
34    pub bind_addr: String,
35    /// PG version string sent back in `ParameterStatus`. Many drivers
36    /// sniff this to enable/disable features. RedDB advertises a
37    /// recent-enough version to get the broadest client support.
38    pub server_version: String,
39    /// Optional TLS material. When set, an `SSLRequest` is answered with
40    /// `'S'` and the connection is upgraded via a rustls handshake before
41    /// the startup flow continues over the encrypted stream. The cert/key
42    /// surface is the *same* [`WireTlsConfig`] the native RedWire listener
43    /// uses — the two transports share one cert config rather than
44    /// inventing a parallel one. `None` leaves the historical behaviour:
45    /// `SSLRequest` is declined with `'N'` and clients continue in
46    /// plaintext.
47    pub tls: Option<crate::wire::tls::WireTlsConfig>,
48}
49
50/// The authenticated identity resolved during the PG-Wire startup
51/// handshake. Installed as the thread-local execution identity for the
52/// duration of each statement so every query dispatched over this
53/// connection flows through the same IAM/policy gates as native
54/// transports. `None` connections (loopback trust) run under the ambient
55/// embedded identity, preserving the pre-auth behaviour.
56struct PgAuthContext {
57    username: String,
58    role: Role,
59    tenant: Option<String>,
60    _lease: crate::auth::store::ConnectionLease,
61}
62
63#[derive(Debug, Clone)]
64struct PgPreparedStatement {
65    sql: String,
66    prepared_id: PreparedId,
67    param_type_oids: Vec<u32>,
68}
69
70#[derive(Debug, Clone)]
71struct PgPortal {
72    sql: String,
73    prepared_id: PreparedId,
74    params: Vec<ParamValue>,
75    #[allow(dead_code)]
76    result_format_codes: Vec<i16>,
77    row_description_sent: bool,
78    result: Option<crate::runtime::OwnedQueryResult>,
79    row_offset: usize,
80}
81
82impl Default for PgWireConfig {
83    fn default() -> Self {
84        Self {
85            bind_addr: "127.0.0.1:5432".to_string(),
86            server_version: "15.0 (RedDB 3.1)".to_string(),
87            tls: None,
88        }
89    }
90}
91
92/// Run a synchronous, possibly long-parking runtime call without
93/// monopolising the async worker thread.
94///
95/// `QUEUE READ … WAIT <budget>` parks the calling thread on a condvar
96/// for up to the wait budget. Doing that directly on a tokio worker
97/// holds the worker for the whole budget, which serialises every other
98/// connection's query behind the parked waiter — a producer's
99/// `QUEUE PUSH` could not run to notify the waiter, so an enqueue during
100/// a WAIT would never be delivered — and it stalls the runtime's timer
101/// driver. `block_in_place` hands the remaining tasks on this worker to
102/// a sibling worker for the duration while keeping the current OS thread
103/// — and therefore the per-connection thread-locals `execute_query`
104/// relies on (current tenant, connection id, transaction context) —
105/// intact, which `spawn_blocking` would not.
106///
107/// `block_in_place` panics on a current-thread runtime, so we fall back
108/// to a direct call there: a single-threaded runtime has no sibling
109/// worker to hand work to and nothing else to starve (e.g. the
110/// `#[tokio::test]` harnesses that drive one connection at a time).
111fn run_runtime_blocking<T>(f: impl FnOnce() -> T) -> T {
112    use tokio::runtime::{Handle, RuntimeFlavor};
113    match Handle::try_current().map(|h| h.runtime_flavor()) {
114        Ok(RuntimeFlavor::MultiThread) => tokio::task::block_in_place(f),
115        _ => f(),
116    }
117}
118
119fn pg_frame_requires_execution(frame: &FrontendMessage) -> bool {
120    matches!(
121        frame,
122        FrontendMessage::Query(_)
123            | FrontendMessage::Parse(_)
124            | FrontendMessage::Describe(_)
125            | FrontendMessage::Execute(_)
126    )
127}
128
129async fn acquire_pg_execution(
130    runtime: &RedDBRuntime,
131    latency_sensitive: bool,
132) -> Result<crate::transport::execution_admission::ExecutionPermit, &'static str> {
133    use crate::transport::execution_admission::ExecutionAdmissionError;
134
135    let admission = runtime.execution_admission();
136    match tokio::time::timeout(
137        runtime.execution_queue_timeout(),
138        admission.acquire_classified(latency_sensitive),
139    )
140    .await
141    {
142        Ok(Ok(permit)) => Ok(permit),
143        Ok(Err(ExecutionAdmissionError::QueueFull)) => {
144            Err("execution_queue_full: engine execution queue is full; retryable=true")
145        }
146        Ok(Err(ExecutionAdmissionError::Closed)) => {
147            Err("execution_admission_closed: engine execution admission is unavailable")
148        }
149        Err(_) => Err(
150            "execution_queue_timeout: deadline expired while waiting to execute; retryable=true",
151        ),
152    }
153}
154
155/// Holds the execution slot only until the response starts. PG handlers do
156/// all synchronous engine work before their first write; releasing at that
157/// boundary prevents a slow client from occupying engine capacity while rows
158/// drain through the socket.
159struct ExecutionResponseWriter<'a, S> {
160    inner: &'a mut S,
161    permit: Option<crate::transport::execution_admission::ExecutionPermit>,
162}
163
164impl<'a, S> ExecutionResponseWriter<'a, S> {
165    fn new(
166        inner: &'a mut S,
167        permit: Option<crate::transport::execution_admission::ExecutionPermit>,
168    ) -> Self {
169        Self { inner, permit }
170    }
171}
172
173impl<S: AsyncWrite + Unpin> AsyncWrite for ExecutionResponseWriter<'_, S> {
174    fn poll_write(
175        mut self: std::pin::Pin<&mut Self>,
176        cx: &mut std::task::Context<'_>,
177        buf: &[u8],
178    ) -> std::task::Poll<Result<usize, std::io::Error>> {
179        drop(self.permit.take());
180        std::pin::Pin::new(&mut *self.inner).poll_write(cx, buf)
181    }
182
183    fn poll_flush(
184        mut self: std::pin::Pin<&mut Self>,
185        cx: &mut std::task::Context<'_>,
186    ) -> std::task::Poll<Result<(), std::io::Error>> {
187        drop(self.permit.take());
188        std::pin::Pin::new(&mut *self.inner).poll_flush(cx)
189    }
190
191    fn poll_shutdown(
192        mut self: std::pin::Pin<&mut Self>,
193        cx: &mut std::task::Context<'_>,
194    ) -> std::task::Poll<Result<(), std::io::Error>> {
195        drop(self.permit.take());
196        std::pin::Pin::new(&mut *self.inner).poll_shutdown(cx)
197    }
198}
199
200/// Run `f` with the authenticated PG-Wire identity installed as the
201/// thread-local execution identity, restoring the prior state afterwards.
202///
203/// The runtime's query dispatch resolves `CURRENT_USER/ROLE/TENANT` and
204/// folds RLS/IAM policies from these thread-locals, so installing them
205/// here is what makes PG-Wire statements transport-invariant with the
206/// native wire. A `None` context leaves the ambient identity untouched.
207fn execute_with_pg_auth_context<T>(
208    auth_context: Option<&PgAuthContext>,
209    f: impl FnOnce() -> T,
210) -> T {
211    let Some(auth_context) = auth_context else {
212        return f();
213    };
214    let _guard = PgAuthContextGuard::install(auth_context);
215    f()
216}
217
218/// RAII guard that installs the PG-Wire auth identity + tenant on the
219/// current thread and restores the previous state on drop, so pooled
220/// runtime threads never leak an identity across statements.
221struct PgAuthContextGuard {
222    previous_principal: Option<crate::auth::UserId>,
223    previous_identity: Option<(String, Role)>,
224    previous_tenant: Option<String>,
225}
226
227impl PgAuthContextGuard {
228    fn install(auth_context: &PgAuthContext) -> Self {
229        let previous_tenant = crate::runtime::execution_context::current_tenant();
230        let previous_principal = crate::runtime::execution_context::current_auth_principal();
231        let previous_identity = crate::runtime::execution_context::current_auth_identity();
232        match &auth_context.tenant {
233            Some(tenant) => crate::runtime::execution_context::set_current_tenant(tenant.clone()),
234            None => crate::runtime::execution_context::clear_current_tenant(),
235        }
236        crate::runtime::execution_context::set_current_auth_principal(
237            crate::auth::UserId::from_parts(auth_context.tenant.as_deref(), &auth_context.username),
238            auth_context.role,
239        );
240        Self {
241            previous_principal,
242            previous_identity,
243            previous_tenant,
244        }
245    }
246}
247
248impl Drop for PgAuthContextGuard {
249    fn drop(&mut self) {
250        match (
251            self.previous_principal.take(),
252            self.previous_identity.take(),
253        ) {
254            (Some(principal), Some((_, role))) => {
255                crate::runtime::execution_context::set_current_auth_principal(principal, role)
256            }
257            _ => crate::runtime::execution_context::clear_current_auth_identity(),
258        }
259        match self.previous_tenant.take() {
260            Some(tenant) => crate::runtime::execution_context::set_current_tenant(tenant),
261            None => crate::runtime::execution_context::clear_current_tenant(),
262        }
263    }
264}
265
266/// Whether `bind_addr` ("host:port") resolves to a loopback host. Trust
267/// authentication survives only for loopback binds with no credentials
268/// configured; every other bind requires a verified password.
269fn is_loopback_bind(bind_addr: &str) -> bool {
270    crate::transport::is_loopback_bind(bind_addr)
271}
272
273/// Extract the cleartext password from a `PasswordMessage` payload (a
274/// single NUL-terminated C-string), returning `None` on malformed input.
275fn password_from_message(payload: &[u8]) -> Option<String> {
276    let nul = payload.iter().position(|&b| b == 0)?;
277    std::str::from_utf8(&payload[..nul])
278        .ok()
279        .map(|password| password.to_string())
280}
281
282/// Spawn the PG wire listener. Blocks until the listener errors out.
283/// Each connection is handled in its own tokio task.
284pub async fn start_pg_wire_listener(
285    config: PgWireConfig,
286    runtime: Arc<RedDBRuntime>,
287) -> Result<(), Box<dyn std::error::Error>> {
288    let listener = TcpListener::bind(&config.bind_addr).await?;
289    start_pg_wire_listener_on(listener, config, runtime).await
290}
291
292/// Serve PostgreSQL wire traffic on a listener bound during node bootstrap.
293pub async fn start_pg_wire_listener_on(
294    listener: TcpListener,
295    config: PgWireConfig,
296    runtime: Arc<RedDBRuntime>,
297) -> Result<(), Box<dyn std::error::Error>> {
298    // Posture: with no auth store enabled, PG-Wire falls back to trust
299    // auth for loopback binds only (see `authenticate_startup`). Surface a
300    // startup warning whenever that fallback is active so an operator never
301    // exposes an unauthenticated listener without noticing.
302    let trust_active = runtime
303        .auth_store()
304        .map(|store| !store.is_enabled())
305        .unwrap_or(true)
306        && is_loopback_bind(&config.bind_addr);
307    if trust_active {
308        tracing::warn!(
309            transport = "pg-wire",
310            bind = %config.bind_addr,
311            "PG-Wire trust authentication is active (no auth store configured); \
312             loopback-only. Configure auth before exposing this listener."
313        );
314    }
315    // Build the shared TLS acceptor once, up front, so a bad cert/key
316    // fails the whole listener rather than every individual connection.
317    // The acceptor is cheap to clone (an `Arc` internally) and is handed
318    // to each connection so `SSLRequest` can be answered with `'S'` and
319    // the rustls handshake performed before the startup flow resumes.
320    let tls_acceptor = match config.tls.as_ref() {
321        Some(tls_cfg) => Some(crate::wire::tls::build_tls_acceptor(tls_cfg)?),
322        None => None,
323    };
324    tracing::info!(
325        transport = "pg-wire",
326        bind = %config.bind_addr,
327        tls = tls_acceptor.is_some(),
328        "listener online"
329    );
330    let cfg = Arc::new(config);
331    let admission = crate::wire::admission::ConnectionAdmission::new("pg-wire");
332    loop {
333        let (stream, peer) = listener.accept().await?;
334        // Bound concurrent sessions. Without this the accept loop spawned a
335        // task per connection with no ceiling, so an unauthenticated peer
336        // could exhaust descriptors before presenting a credential.
337        let Some(permit) = admission.try_admit() else {
338            continue;
339        };
340        // Small result/control frames must not wait for a client's delayed ACK
341        // before the next frame (notably ReadyForQuery) can leave the server.
342        if let Err(error) = stream.set_nodelay(true) {
343            tracing::warn!(transport = "pg-wire", peer = %peer, err = %error,
344                "failed to configure connection");
345            continue;
346        }
347        let rt = Arc::clone(&runtime);
348        let cfg = Arc::clone(&cfg);
349        let acceptor = tls_acceptor.clone();
350        let peer_str = peer.to_string();
351        tokio::spawn(async move {
352            let _permit = permit;
353            if let Err(e) = handle_connection(stream, rt, cfg, acceptor).await {
354                tracing::warn!(
355                    transport = "pg-wire",
356                    peer = %peer_str,
357                    err = %e,
358                    "connection failed"
359                );
360            }
361        });
362    }
363}
364
365/// Drive one connection's lifetime: SSL negotiation → startup →
366/// authentication → query loop.
367///
368/// The first frame may be `SSLRequest` / `GSSENCRequest` (pre-auth
369/// negotiation) or a plain `Startup`. When a TLS acceptor is present an
370/// `SSLRequest` is answered with `'S'` and the socket is upgraded via a
371/// rustls handshake; the rest of the session (a fresh `Startup`,
372/// authentication, and the query loop) then runs over the encrypted
373/// stream. Without an acceptor — or for `GSSENCRequest`, which we never
374/// support — the request is declined with `'N'` and the client continues
375/// in plaintext on the same socket.
376pub(crate) async fn handle_connection<S>(
377    mut stream: S,
378    runtime: Arc<RedDBRuntime>,
379    config: Arc<PgWireConfig>,
380    tls_acceptor: Option<tokio_rustls::TlsAcceptor>,
381) -> Result<(), PgWireError>
382where
383    S: AsyncRead + AsyncWrite + Unpin + Send,
384{
385    // Bound the whole pre-session negotiation. `read_startup` and the rustls
386    // handshake both block on the peer, and neither had a deadline: a client
387    // that connected and sent nothing (or stalled mid-handshake) pinned a
388    // task and a connection slot indefinitely, before any credential was
389    // presented. The loop below can iterate (SSLRequest/GSSENCRequest are
390    // declined and the client retries), so each read is bounded rather than
391    // the loop as a whole.
392    loop {
393        let startup = crate::wire::admission::with_handshake_deadline(read_startup(&mut stream))
394            .await
395            .map_err(PgWireError::from)??;
396        match startup {
397            FrontendMessage::SslRequest => {
398                if let Some(acceptor) = tls_acceptor.as_ref() {
399                    // 'S' = SSL supported. Perform the rustls handshake and
400                    // hand the encrypted stream to the session driver.
401                    write_raw_byte(&mut stream, b'S').await?;
402                    let tls_stream =
403                        crate::wire::admission::with_handshake_deadline(acceptor.accept(stream))
404                            .await??;
405                    return serve_session_after_tls(tls_stream, runtime, config).await;
406                }
407                // 'N' = not supported — client continues in plaintext and
408                // re-sends a normal Startup on the same socket.
409                write_raw_byte(&mut stream, b'N').await?;
410                continue;
411            }
412            FrontendMessage::GssEncRequest => {
413                // GSSAPI encryption is never offered; decline and let the
414                // client retry with SSLRequest or plaintext Startup.
415                write_raw_byte(&mut stream, b'N').await?;
416                continue;
417            }
418            FrontendMessage::Startup(params) => {
419                return run_pg_session(stream, runtime, config, false, params).await;
420            }
421            FrontendMessage::Unknown { .. } => {
422                // CancelRequest: no response expected; drop the socket.
423                return Ok(());
424            }
425            other => {
426                return Err(PgWireError::Protocol(format!(
427                    "unexpected startup frame: {other:?}"
428                )));
429            }
430        }
431    }
432}
433
434/// Continue the startup flow after a successful TLS upgrade. The client
435/// now sends a fresh `Startup` over the encrypted stream; a second
436/// `SSLRequest` / `GSSENCRequest` cannot be honoured (no nested
437/// encryption) and is declined with `'N'`.
438async fn serve_session_after_tls<S>(
439    mut stream: tokio_rustls::server::TlsStream<S>,
440    runtime: Arc<RedDBRuntime>,
441    config: Arc<PgWireConfig>,
442) -> Result<(), PgWireError>
443where
444    S: AsyncRead + AsyncWrite + Unpin + Send,
445{
446    loop {
447        match read_startup(&mut stream).await? {
448            FrontendMessage::SslRequest | FrontendMessage::GssEncRequest => {
449                write_raw_byte(&mut stream, b'N').await?;
450                continue;
451            }
452            FrontendMessage::Startup(params) => {
453                return run_pg_session(stream, runtime, config, true, params).await;
454            }
455            FrontendMessage::Unknown { .. } => return Ok(()),
456            other => {
457                return Err(PgWireError::Protocol(format!(
458                    "unexpected startup frame: {other:?}"
459                )));
460            }
461        }
462    }
463}
464
465/// Authenticate a `Startup` and drive the query loop over `stream`.
466/// `over_tls` records whether the transport is encrypted, which gates the
467/// cleartext-password posture in [`authenticate_startup`].
468async fn run_pg_session<S>(
469    mut stream: S,
470    runtime: Arc<RedDBRuntime>,
471    config: Arc<PgWireConfig>,
472    over_tls: bool,
473    params: super::protocol::StartupParams,
474) -> Result<(), PgWireError>
475where
476    S: AsyncRead + AsyncWrite + Unpin + Send,
477{
478    let auth_context =
479        match authenticate_startup(&mut stream, &runtime, &config, over_tls, &params).await? {
480            Some(context) => context,
481            // Authentication failed: the error frame was already sent and
482            // the socket must close.
483            None => return Ok(()),
484        };
485
486    let mut prepared: HashMap<String, PgPreparedStatement> = HashMap::new();
487    let mut portals: HashMap<String, PgPortal> = HashMap::new();
488    let prepared_registry = PreparedRegistry::new();
489    let mut discard_until_sync = false;
490
491    // Main query loop.
492    loop {
493        let frame = match read_frame(&mut stream).await {
494            Ok(f) => f,
495            Err(PgWireError::Eof) => return Ok(()),
496            Err(e) => return Err(e),
497        };
498        // Keep the Parse error as the only response to this extended-query batch.
499        if discard_until_sync
500            && !matches!(&frame, FrontendMessage::Sync | FrontendMessage::Terminate)
501        {
502            continue;
503        }
504
505        // PG sessions are serial, but every session competes for the same
506        // runtime-wide engine budget as HTTP, gRPC and RedWire. Admission is
507        // taken before any parser/planner/storage work. The response writer
508        // releases it before the first socket write, so a slow client cannot
509        // occupy engine capacity while rows drain.
510        let mut execution_permit = if pg_frame_requires_execution(&frame) {
511            let latency_sensitive = matches!(
512                &frame,
513                FrontendMessage::Query(sql)
514                    if crate::server::is_trivial_scalar_sql(sql)
515            );
516            match acquire_pg_execution(&runtime, latency_sensitive).await {
517                Ok(permit) => Some(permit),
518                Err(message) => {
519                    // SQLSTATE 53000 = insufficient_resources. Keep the stable
520                    // RedDB reason code in the message for clients that expose
521                    // only the PostgreSQL ErrorResponse text.
522                    send_error(&mut stream, "53000", message).await?;
523                    write_frame(
524                        &mut stream,
525                        &BackendMessage::ReadyForQuery(TransactionStatus::Idle),
526                    )
527                    .await?;
528                    continue;
529                }
530            }
531        } else {
532            None
533        };
534
535        match frame {
536            FrontendMessage::Query(sql) => {
537                let mut response =
538                    ExecutionResponseWriter::new(&mut stream, execution_permit.take());
539                handle_simple_query(&mut response, &runtime, auth_context.as_ref(), &sql).await?;
540            }
541            FrontendMessage::Parse(msg) => {
542                let mut response =
543                    ExecutionResponseWriter::new(&mut stream, execution_permit.take());
544                discard_until_sync = !handle_parse(
545                    &mut response,
546                    &runtime,
547                    &prepared_registry,
548                    &mut prepared,
549                    &portals,
550                    msg,
551                )
552                .await?;
553            }
554            FrontendMessage::Bind(msg) => {
555                handle_bind(
556                    &mut stream,
557                    &prepared_registry,
558                    &prepared,
559                    &mut portals,
560                    msg,
561                )
562                .await?;
563            }
564            FrontendMessage::Describe(msg) => {
565                let mut response =
566                    ExecutionResponseWriter::new(&mut stream, execution_permit.take());
567                handle_describe(
568                    &mut response,
569                    &runtime,
570                    auth_context.as_ref(),
571                    &prepared_registry,
572                    &prepared,
573                    &mut portals,
574                    msg,
575                )
576                .await?;
577            }
578            FrontendMessage::Execute(msg) => {
579                let mut response =
580                    ExecutionResponseWriter::new(&mut stream, execution_permit.take());
581                handle_execute(
582                    &mut response,
583                    &runtime,
584                    auth_context.as_ref(),
585                    &prepared_registry,
586                    &mut portals,
587                    msg,
588                )
589                .await?;
590            }
591            FrontendMessage::Close(msg) => {
592                handle_close(
593                    &mut stream,
594                    &prepared_registry,
595                    &mut prepared,
596                    &mut portals,
597                    msg,
598                )
599                .await?;
600            }
601            FrontendMessage::Terminate => return Ok(()),
602            FrontendMessage::Flush => {
603                // Frames are written immediately; no additional marker is
604                // needed. ReadyForQuery belongs to Sync, not Flush.
605                continue;
606            }
607            FrontendMessage::Sync => {
608                discard_until_sync = false;
609                write_frame(
610                    &mut stream,
611                    &BackendMessage::ReadyForQuery(TransactionStatus::Idle),
612                )
613                .await?;
614            }
615            FrontendMessage::PasswordMessage(_) => {
616                // Should only arrive during auth. Ignore post-auth.
617                continue;
618            }
619            FrontendMessage::Unknown { tag, .. } => {
620                send_error(
621                    &mut stream,
622                    "0A000",
623                    &format!("unsupported frame tag 0x{tag:02x}"),
624                )
625                .await?;
626                write_frame(
627                    &mut stream,
628                    &BackendMessage::ReadyForQuery(TransactionStatus::Idle),
629                )
630                .await?;
631            }
632            other => {
633                send_error(
634                    &mut stream,
635                    "0A000",
636                    &format!("unsupported frame {other:?}"),
637                )
638                .await?;
639                write_frame(
640                    &mut stream,
641                    &BackendMessage::ReadyForQuery(TransactionStatus::Idle),
642                )
643                .await?;
644            }
645        }
646    }
647}
648
649async fn handle_parse<S>(
650    stream: &mut S,
651    runtime: &RedDBRuntime,
652    prepared_registry: &PreparedRegistry,
653    prepared: &mut HashMap<String, PgPreparedStatement>,
654    portals: &HashMap<String, PgPortal>,
655    msg: super::protocol::ParseMessage,
656) -> Result<bool, PgWireError>
657where
658    S: AsyncWrite + Unpin,
659{
660    let inferred_param_type_oids = infer_pg_cast_param_type_oids(&msg.query);
661    let sql = rewrite_pg_parameter_casts(&msg.query);
662    let prepared_query = match prepared_registry.prepare(runtime, &sql) {
663        Ok(prepared_query) => prepared_query,
664        Err(err) => {
665            let message = err.to_string();
666            let code = match classify_sqlstate(&message) {
667                "42P10" => "42P10",
668                _ => "42601",
669            };
670            send_error(stream, code, &message).await?;
671            return Ok(false);
672        }
673    };
674    let mut param_type_oids = msg.param_type_oids;
675    if param_type_oids.is_empty() {
676        param_type_oids.resize(prepared_query.parameter_count, PgOid::Unknown.as_u32());
677    }
678    for (idx, oid) in inferred_param_type_oids {
679        if idx >= param_type_oids.len() {
680            param_type_oids.resize(idx + 1, PgOid::Unknown.as_u32());
681        }
682        if param_type_oids[idx] == PgOid::Unknown.as_u32() {
683            param_type_oids[idx] = oid;
684        }
685    }
686    let replaced = prepared.insert(
687        msg.statement,
688        PgPreparedStatement {
689            sql,
690            prepared_id: prepared_query.id,
691            param_type_oids,
692        },
693    );
694    if let Some(replaced) = replaced {
695        release_prepared_if_unreferenced(
696            prepared_registry,
697            replaced.prepared_id,
698            prepared,
699            portals,
700        );
701    }
702    write_frame(stream, &BackendMessage::ParseComplete).await?;
703    Ok(true)
704}
705
706async fn handle_bind<S>(
707    stream: &mut S,
708    prepared_registry: &PreparedRegistry,
709    prepared: &HashMap<String, PgPreparedStatement>,
710    portals: &mut HashMap<String, PgPortal>,
711    msg: super::protocol::BindMessage,
712) -> Result<(), PgWireError>
713where
714    S: AsyncWrite + Unpin,
715{
716    let Some(stmt) = prepared.get(&msg.statement) else {
717        send_error(
718            stream,
719            "26000",
720            &format!("prepared statement {:?} does not exist", msg.statement),
721        )
722        .await?;
723        return Ok(());
724    };
725    let params = match bind_pg_params(stmt, &msg) {
726        Ok(params) => params,
727        Err(err) => {
728            send_error(stream, "22023", &err).await?;
729            return Ok(());
730        }
731    };
732    let replaced = portals.insert(
733        msg.portal,
734        PgPortal {
735            sql: stmt.sql.clone(),
736            prepared_id: stmt.prepared_id,
737            params,
738            result_format_codes: msg.result_format_codes,
739            row_description_sent: false,
740            result: None,
741            row_offset: 0,
742        },
743    );
744    if let Some(replaced) = replaced {
745        release_prepared_if_unreferenced(
746            prepared_registry,
747            replaced.prepared_id,
748            prepared,
749            portals,
750        );
751    }
752    write_frame(stream, &BackendMessage::BindComplete).await
753}
754
755async fn handle_describe<S>(
756    stream: &mut S,
757    runtime: &RedDBRuntime,
758    auth_context: Option<&PgAuthContext>,
759    prepared_registry: &PreparedRegistry,
760    prepared: &HashMap<String, PgPreparedStatement>,
761    portals: &mut HashMap<String, PgPortal>,
762    msg: super::protocol::DescribeMessage,
763) -> Result<(), PgWireError>
764where
765    S: AsyncWrite + Unpin,
766{
767    match msg.target {
768        DescribeTarget::Statement => {
769            let Some(stmt) = prepared.get(&msg.name) else {
770                send_error(
771                    stream,
772                    "26000",
773                    &format!("prepared statement {:?} does not exist", msg.name),
774                )
775                .await?;
776                return Ok(());
777            };
778            write_frame(
779                stream,
780                &BackendMessage::ParameterDescription(stmt.param_type_oids.clone()),
781            )
782            .await?;
783            if is_ask_query(&stmt.sql) {
784                emit_ask_row_description(stream).await
785            } else {
786                write_frame(stream, &BackendMessage::NoData).await
787            }
788        }
789        DescribeTarget::Portal => {
790            let Some(portal) = portals.get_mut(&msg.name) else {
791                send_error(
792                    stream,
793                    "34000",
794                    &format!("portal {:?} does not exist", msg.name),
795                )
796                .await?;
797                return Ok(());
798            };
799            if is_ask_query(&portal.sql) {
800                emit_ask_row_description(stream).await?;
801                portal.row_description_sent = true;
802                Ok(())
803            } else if is_row_returning_query(&portal.sql) {
804                let result = match execute_pg_query_result(
805                    runtime,
806                    auth_context,
807                    prepared_registry,
808                    portal.prepared_id,
809                    &portal.sql,
810                    &portal.params,
811                ) {
812                    Ok(result) => result,
813                    Err(err) => {
814                        let code = classify_sqlstate(&err);
815                        send_error(stream, code, &err).await?;
816                        return Ok(());
817                    }
818                };
819                emit_row_description_for_result(stream, &result).await?;
820                portal.row_description_sent = true;
821                portal.result = Some(result);
822                portal.row_offset = 0;
823                Ok(())
824            } else {
825                write_frame(stream, &BackendMessage::NoData).await
826            }
827        }
828    }
829}
830
831async fn handle_execute<S>(
832    stream: &mut S,
833    runtime: &RedDBRuntime,
834    auth_context: Option<&PgAuthContext>,
835    prepared_registry: &PreparedRegistry,
836    portals: &mut HashMap<String, PgPortal>,
837    msg: super::protocol::ExecuteMessage,
838) -> Result<(), PgWireError>
839where
840    S: AsyncWrite + Unpin,
841{
842    let Some(portal) = portals.get_mut(&msg.portal) else {
843        send_error(
844            stream,
845            "34000",
846            &format!("portal {:?} does not exist", msg.portal),
847        )
848        .await?;
849        return Ok(());
850    };
851    match prepared_registry.ddl_epoch(portal.prepared_id) {
852        Some(epoch) if epoch != runtime.ddl_epoch() => {
853            send_error(stream, "XX000", "prepared_needs_replan").await?;
854            return Ok(());
855        }
856        Some(_) => {}
857        None => {
858            send_error(stream, "26000", "prepared statement does not exist").await?;
859            return Ok(());
860        }
861    }
862    if portal.result.is_none() {
863        match execute_pg_query_result(
864            runtime,
865            auth_context,
866            prepared_registry,
867            portal.prepared_id,
868            &portal.sql,
869            &portal.params,
870        ) {
871            Ok(result) => {
872                portal.result = Some(result);
873                portal.row_offset = 0;
874            }
875            Err(err) => {
876                let code = classify_sqlstate(&err);
877                send_error(stream, code, &err).await?;
878                return Ok(());
879            }
880        }
881    }
882
883    let result = portal.result.as_ref().expect("portal result populated");
884    match emit_portal_execution(
885        stream,
886        result,
887        portal.row_description_sent,
888        portal.row_offset,
889        msg.max_rows,
890    )
891    .await
892    {
893        Ok(PortalExecution::Complete) => {
894            portal.result = None;
895            portal.row_offset = 0;
896            portal.row_description_sent = false;
897            Ok(())
898        }
899        Ok(PortalExecution::Suspended { next_row_offset }) => {
900            portal.row_offset = next_row_offset;
901            portal.row_description_sent = true;
902            Ok(())
903        }
904        Err(err) => {
905            let code = classify_sqlstate(&err);
906            send_error(stream, code, &err).await
907        }
908    }
909}
910
911async fn handle_close<S>(
912    stream: &mut S,
913    prepared_registry: &PreparedRegistry,
914    prepared: &mut HashMap<String, PgPreparedStatement>,
915    portals: &mut HashMap<String, PgPortal>,
916    msg: super::protocol::CloseMessage,
917) -> Result<(), PgWireError>
918where
919    S: AsyncWrite + Unpin,
920{
921    let prepared_id = match msg.target {
922        DescribeTarget::Statement => prepared.remove(&msg.name).map(|stmt| stmt.prepared_id),
923        DescribeTarget::Portal => portals.remove(&msg.name).map(|portal| portal.prepared_id),
924    };
925    if let Some(prepared_id) = prepared_id {
926        release_prepared_if_unreferenced(prepared_registry, prepared_id, prepared, portals);
927    }
928    write_frame(stream, &BackendMessage::CloseComplete).await
929}
930
931fn release_prepared_if_unreferenced(
932    prepared_registry: &PreparedRegistry,
933    prepared_id: PreparedId,
934    prepared: &HashMap<String, PgPreparedStatement>,
935    portals: &HashMap<String, PgPortal>,
936) {
937    let statement_references_id = prepared
938        .values()
939        .any(|statement| statement.prepared_id == prepared_id);
940    let portal_references_id = portals
941        .values()
942        .any(|portal| portal.prepared_id == prepared_id);
943    if !statement_references_id && !portal_references_id {
944        prepared_registry.release(prepared_id);
945    }
946}
947
948fn bind_pg_params(
949    stmt: &PgPreparedStatement,
950    msg: &super::protocol::BindMessage,
951) -> Result<Vec<ParamValue>, String> {
952    if !matches!(msg.param_format_codes.len(), 0 | 1)
953        && msg.param_format_codes.len() != msg.params.len()
954    {
955        return Err("Bind format count must be 0, 1, or match parameter count".to_string());
956    }
957    msg.params
958        .iter()
959        .enumerate()
960        .map(|(idx, param)| {
961            let oid = stmt
962                .param_type_oids
963                .get(idx)
964                .copied()
965                .unwrap_or(PgOid::Unknown.as_u32());
966            let format_code = match msg.param_format_codes.as_slice() {
967                [] => 0,
968                [format] => *format,
969                formats => formats[idx],
970            };
971            pg_param_to_param_value(oid, format_code, param.as_deref())
972        })
973        .collect()
974}
975
976fn execute_pg_query_result(
977    runtime: &RedDBRuntime,
978    auth_context: Option<&PgAuthContext>,
979    prepared_registry: &PreparedRegistry,
980    prepared_id: PreparedId,
981    sql: &str,
982    params: &[ParamValue],
983) -> Result<crate::runtime::OwnedQueryResult, String> {
984    let executor = QueryRequestExecutor::new(runtime, prepared_registry);
985    let bound = executor
986        .bind(QueryRequest::prepared(prepared_id, params.to_vec()))
987        .map_err(|err| err.to_string())?;
988    if pg_scalar_select_param_index(sql).is_some() {
989        let values = params.iter().cloned().map(Value::from).collect::<Vec<_>>();
990        if let Some(result) = try_execute_pg_scalar_select(sql, &values) {
991            return runtime
992                .own_query_result(result)
993                .map_err(|error| error.to_string());
994        }
995    }
996    if params.is_empty() {
997        return match translate_pg_catalog_query(runtime, sql) {
998            Ok(Some(result)) => runtime
999                .own_query_result(crate::runtime::RuntimeQueryResult {
1000                    query: sql.to_string(),
1001                    mode: reddb_rql::modes::QueryMode::Sql,
1002                    statement: "select",
1003                    engine: "pg-catalog",
1004                    result,
1005                    affected_rows: 0,
1006                    statement_type: "select",
1007                    bookmark: None,
1008                    notice: None,
1009                })
1010                .map_err(|error| error.to_string()),
1011            Ok(None) => run_runtime_blocking(|| {
1012                execute_with_pg_auth_context(auth_context, || {
1013                    // Utility statements use the full dispatcher after registry validation.
1014                    // Their zero-parameter SQL can be reparsed without losing bindings;
1015                    // data queries retain the cached prepared shape on repeated Execute.
1016                    if matches!(
1017                        bound.prepared_expr(),
1018                        Some(
1019                            QueryExpr::Function(_)
1020                                | QueryExpr::Table(_)
1021                                | QueryExpr::Graph(_)
1022                                | QueryExpr::Path(_)
1023                                | QueryExpr::Join(_)
1024                                | QueryExpr::Vector(_)
1025                                | QueryExpr::Hybrid(_)
1026                                | QueryExpr::Insert(_)
1027                                | QueryExpr::Update(_)
1028                                | QueryExpr::Delete(_)
1029                                | QueryExpr::QueueCommand(_)
1030                                | QueryExpr::KvCommand(_)
1031                                | QueryExpr::SearchCommand(_)
1032                                | QueryExpr::Ask(_)
1033                        )
1034                    ) {
1035                        executor.execute_bound(bound)
1036                    } else {
1037                        runtime
1038                            .execute_query(sql)
1039                            .and_then(|result| runtime.own_query_result(result))
1040                    }
1041                })
1042            })
1043            .map_err(|err| err.to_string()),
1044            Err(err) => Err(err.to_string()),
1045        };
1046    }
1047
1048    run_runtime_blocking(|| {
1049        execute_with_pg_auth_context(auth_context, || executor.execute_bound(bound))
1050    })
1051    .map_err(|err| err.to_string())
1052}
1053
1054fn try_execute_pg_scalar_select(
1055    sql: &str,
1056    params: &[Value],
1057) -> Option<crate::runtime::RuntimeQueryResult> {
1058    let index = pg_scalar_select_param_index(sql)?;
1059    let value = params.get(index)?.clone();
1060    let mut result = UnifiedResult::with_columns(vec!["?column?".to_string()]);
1061    let mut record = UnifiedRecord::new();
1062    record.set("?column?", value);
1063    result.push(record);
1064    Some(crate::runtime::RuntimeQueryResult {
1065        query: sql.to_string(),
1066        mode: reddb_rql::modes::QueryMode::Sql,
1067        statement: "select",
1068        engine: "pg-wire",
1069        result,
1070        affected_rows: 0,
1071        statement_type: "select",
1072        bookmark: None,
1073        notice: None,
1074    })
1075}
1076
1077fn pg_scalar_select_param_index(sql: &str) -> Option<usize> {
1078    let trimmed = sql.trim().trim_end_matches(';').trim();
1079    let lower = trimmed.to_ascii_lowercase();
1080    let body = lower.strip_prefix("select ")?;
1081    let param = if let Some(inner) = body.strip_prefix("cast(") {
1082        let end = inner.find(" as ")?;
1083        &inner[..end]
1084    } else {
1085        body.split_whitespace().next()?
1086    };
1087    let digits = param.strip_prefix('$')?;
1088    let n = digits.parse::<usize>().ok()?;
1089    n.checked_sub(1)
1090}
1091
1092fn rewrite_pg_parameter_casts(sql: &str) -> String {
1093    let mut out = String::with_capacity(sql.len());
1094    let bytes = sql.as_bytes();
1095    let mut cursor = 0;
1096    let mut pos = 0;
1097    while pos < bytes.len() {
1098        if bytes[pos] != b'$' {
1099            pos += 1;
1100            continue;
1101        }
1102        let param_start = pos;
1103        pos += 1;
1104        let digits_start = pos;
1105        while pos < bytes.len() && bytes[pos].is_ascii_digit() {
1106            pos += 1;
1107        }
1108        if digits_start == pos {
1109            continue;
1110        }
1111        if pos + 2 <= bytes.len() && &bytes[pos..pos + 2] == b"::" {
1112            let param_end = pos;
1113            pos += 2;
1114            let type_start = pos;
1115            while pos < bytes.len()
1116                && (bytes[pos].is_ascii_alphanumeric() || matches!(bytes[pos], b'_' | b'.'))
1117            {
1118                pos += 1;
1119            }
1120            if type_start != pos {
1121                out.push_str(&sql[cursor..param_start]);
1122                out.push_str(&sql[param_start..param_end]);
1123                cursor = pos;
1124                continue;
1125            }
1126        }
1127    }
1128    out.push_str(&sql[cursor..]);
1129    out
1130}
1131
1132fn infer_pg_cast_param_type_oids(sql: &str) -> Vec<(usize, u32)> {
1133    let mut out = Vec::new();
1134    let bytes = sql.as_bytes();
1135    let mut pos = 0;
1136    while pos < bytes.len() {
1137        if bytes[pos] != b'$' {
1138            pos += 1;
1139            continue;
1140        }
1141        pos += 1;
1142        let digits_start = pos;
1143        while pos < bytes.len() && bytes[pos].is_ascii_digit() {
1144            pos += 1;
1145        }
1146        if digits_start == pos {
1147            continue;
1148        }
1149        let Some(param_index) = sql[digits_start..pos]
1150            .parse::<usize>()
1151            .ok()
1152            .and_then(|idx| idx.checked_sub(1))
1153        else {
1154            continue;
1155        };
1156        if pos + 2 > bytes.len() || &bytes[pos..pos + 2] != b"::" {
1157            continue;
1158        }
1159        pos += 2;
1160        let type_start = pos;
1161        while pos < bytes.len()
1162            && (bytes[pos].is_ascii_alphanumeric() || matches!(bytes[pos], b'_' | b'.'))
1163        {
1164            pos += 1;
1165        }
1166        if type_start == pos {
1167            continue;
1168        }
1169        if let Some(oid) = pg_cast_type_oid(&sql[type_start..pos]) {
1170            out.push((param_index, oid));
1171        }
1172    }
1173    out
1174}
1175
1176fn pg_cast_type_oid(ty: &str) -> Option<u32> {
1177    let lower = ty.to_ascii_lowercase();
1178    let short = lower.rsplit('.').next().unwrap_or(lower.as_str());
1179    let oid = match short {
1180        "bool" | "boolean" => PgOid::Bool,
1181        "int2" | "smallint" => PgOid::Int2,
1182        "int" | "int4" | "integer" => PgOid::Int4,
1183        "int8" | "bigint" => PgOid::Int8,
1184        "float4" | "real" => PgOid::Float4,
1185        "float8" | "double" | "doubleprecision" => PgOid::Float8,
1186        "numeric" | "decimal" => PgOid::Numeric,
1187        "bytea" => PgOid::Bytea,
1188        "json" => PgOid::Json,
1189        "jsonb" => PgOid::Jsonb,
1190        "text" => PgOid::Text,
1191        "varchar" | "character varying" => PgOid::Varchar,
1192        "uuid" => PgOid::Uuid,
1193        "timestamp" => PgOid::Timestamp,
1194        "timestamptz" | "timestampz" => PgOid::TimestampTz,
1195        "vector" => PgOid::Vector,
1196        _ => return None,
1197    };
1198    Some(oid.as_u32())
1199}
1200
1201fn is_row_returning_query(sql: &str) -> bool {
1202    let trimmed = sql.trim_start().to_ascii_lowercase();
1203    trimmed.starts_with("select")
1204        || trimmed.starts_with("with")
1205        || trimmed.starts_with("ask")
1206        || trimmed.starts_with("search")
1207        || trimmed.starts_with("vector")
1208        || trimmed.starts_with("hybrid")
1209}
1210
1211fn is_ask_query(sql: &str) -> bool {
1212    sql.trim_start().to_ascii_lowercase().starts_with("ask")
1213}
1214
1215/// Drive the PG-Wire authentication handshake after a `StartupMessage`.
1216///
1217/// Posture:
1218///   * Auth store enabled → request `AuthenticationCleartextPassword`,
1219///     read the client's `PasswordMessage`, and verify it against the same
1220///     auth store the native transports use. Success installs the resolved
1221///     identity; failure emits `28P01` and closes the socket.
1222///   * No auth store enabled + loopback bind → legacy trust: send
1223///     `AuthenticationOk` with no credentials required (`None` context).
1224///   * No auth store enabled + non-loopback bind → refuse with `28P01`;
1225///     an unconfigured listener must never grant unauthenticated access
1226///     off loopback.
1227///
1228/// TLS posture: a cleartext password may only cross an *unencrypted* link
1229/// on a loopback bind. On a non-loopback bind we refuse to even challenge
1230/// for a password unless the connection is already over TLS (`over_tls`),
1231/// so a client using `sslmode=disable` against a remote listener never
1232/// leaks its password in the clear. Loopback and TLS connections are
1233/// challenged as before.
1234///
1235/// Returns `Ok(Some(context))` once the connection is ready for queries
1236/// (`context` is `None` for trust connections), or `Ok(None)` when
1237/// authentication failed and the error frame has already been sent.
1238///
1239/// Failures give the same `28P01` "password authentication failed" for a
1240/// wrong password and a missing user, so there is no user-existence oracle.
1241async fn authenticate_startup<S>(
1242    stream: &mut S,
1243    runtime: &RedDBRuntime,
1244    config: &PgWireConfig,
1245    over_tls: bool,
1246    params: &super::protocol::StartupParams,
1247) -> Result<Option<Option<PgAuthContext>>, PgWireError>
1248where
1249    S: AsyncRead + AsyncWrite + Unpin,
1250{
1251    let auth_store = runtime.auth_store().filter(|store| store.is_enabled());
1252    let Some(auth_store) = auth_store else {
1253        // No credentials configured: trust survives for loopback only.
1254        if is_loopback_bind(&config.bind_addr) {
1255            send_startup_ready(stream, config, params).await?;
1256            return Ok(Some(None));
1257        }
1258        send_error(stream, "28P01", "password authentication failed").await?;
1259        return Ok(None);
1260    };
1261
1262    // Refuse to challenge for a cleartext password over an unencrypted
1263    // non-loopback link: it would traverse the network in the clear.
1264    // Clients must connect with `sslmode=require` (TLS) to authenticate
1265    // against a remote bind.
1266    if !over_tls && !is_loopback_bind(&config.bind_addr) {
1267        send_error(
1268            stream,
1269            "28000",
1270            "cleartext password authentication requires TLS on non-loopback binds",
1271        )
1272        .await?;
1273        return Ok(None);
1274    }
1275
1276    write_frame(stream, &BackendMessage::AuthenticationCleartextPassword).await?;
1277    let password = match read_frame(stream).await? {
1278        FrontendMessage::PasswordMessage(payload) => password_from_message(&payload),
1279        // Anything other than a PasswordMessage is a protocol violation
1280        // here; treat it as an auth failure rather than leaking detail.
1281        _ => None,
1282    };
1283    let username = params.get("user").unwrap_or("");
1284    let tenant = params.get("tenant");
1285    let Some(password) = password else {
1286        send_error(stream, "28P01", "password authentication failed").await?;
1287        return Ok(None);
1288    };
1289    // A missing user and a wrong password both surface as the same error
1290    // class below — no user-existence oracle leaks over the wire.
1291    let (session, lease) = match auth_store.authenticate_connection(tenant, username, &password) {
1292        Ok(authenticated) => authenticated,
1293        Err(_) => {
1294            send_error(stream, "28P01", "password authentication failed").await?;
1295            return Ok(None);
1296        }
1297    };
1298
1299    send_startup_ready(stream, config, params).await?;
1300    Ok(Some(Some(PgAuthContext {
1301        username: session.username,
1302        role: session.role,
1303        tenant: session.tenant_id,
1304        _lease: lease,
1305    })))
1306}
1307
1308async fn send_startup_ready<S>(
1309    stream: &mut S,
1310    config: &PgWireConfig,
1311    params: &super::protocol::StartupParams,
1312) -> Result<(), PgWireError>
1313where
1314    S: AsyncWrite + Unpin,
1315{
1316    // Authentication has succeeded (or trust applies): signal AuthenticationOk.
1317    write_frame(stream, &BackendMessage::AuthenticationOk).await?;
1318
1319    // Standard ParameterStatus frames. Drivers gate capabilities on these.
1320    for (name, value) in [
1321        ("server_version", config.server_version.as_str()),
1322        ("server_encoding", "UTF8"),
1323        ("client_encoding", "UTF8"),
1324        ("DateStyle", "ISO, MDY"),
1325        ("TimeZone", "UTC"),
1326        ("integer_datetimes", "on"),
1327        ("standard_conforming_strings", "on"),
1328        (
1329            "application_name",
1330            params.get("application_name").unwrap_or(""),
1331        ),
1332    ] {
1333        write_frame(
1334            stream,
1335            &BackendMessage::ParameterStatus {
1336                name: name.to_string(),
1337                value: value.to_string(),
1338            },
1339        )
1340        .await?;
1341    }
1342
1343    // BackendKeyData: (pid, secret_key). CancelRequest is not honoured
1344    // yet, but the key is what a future cancel path authenticates on, so
1345    // it is random per connection rather than a constant a client could
1346    // learn once and reuse against every session.
1347    write_frame(
1348        stream,
1349        &BackendMessage::BackendKeyData {
1350            pid: std::process::id(),
1351            key: random_cancel_key(),
1352        },
1353    )
1354    .await?;
1355
1356    write_frame(
1357        stream,
1358        &BackendMessage::ReadyForQuery(TransactionStatus::Idle),
1359    )
1360    .await?;
1361    Ok(())
1362}
1363
1364async fn handle_simple_query<S>(
1365    stream: &mut S,
1366    runtime: &RedDBRuntime,
1367    auth_context: Option<&PgAuthContext>,
1368    sql: &str,
1369) -> Result<(), PgWireError>
1370where
1371    S: AsyncWrite + Unpin,
1372{
1373    // Empty query convention: PG emits EmptyQueryResponse instead of a
1374    // CommandComplete. Some clients (psql `\;`) rely on this.
1375    if sql.trim().is_empty() {
1376        write_frame(stream, &BackendMessage::EmptyQueryResponse).await?;
1377        write_frame(
1378            stream,
1379            &BackendMessage::ReadyForQuery(TransactionStatus::Idle),
1380        )
1381        .await?;
1382        return Ok(());
1383    }
1384
1385    if let Some(tag) = pg_session_compat_command_tag(sql) {
1386        write_frame(stream, &BackendMessage::CommandComplete(tag.to_string())).await?;
1387        write_frame(
1388            stream,
1389            &BackendMessage::ReadyForQuery(TransactionStatus::Idle),
1390        )
1391        .await?;
1392        return Ok(());
1393    }
1394
1395    let query_result = match translate_pg_catalog_query(runtime, sql) {
1396        Ok(Some(result)) => runtime.own_query_result(crate::runtime::RuntimeQueryResult {
1397            query: sql.to_string(),
1398            mode: reddb_rql::modes::QueryMode::Sql,
1399            statement: "select",
1400            engine: "pg-catalog",
1401            result,
1402            affected_rows: 0,
1403            statement_type: "select",
1404            bookmark: None,
1405            notice: None,
1406        }),
1407        Ok(None) => run_runtime_blocking(|| {
1408            execute_with_pg_auth_context(auth_context, || {
1409                runtime
1410                    .execute_query(sql)
1411                    .and_then(|result| runtime.own_query_result(result))
1412            })
1413        }),
1414        Err(err) => Err(err),
1415    };
1416
1417    match query_result {
1418        Ok(result) => {
1419            emit_success_result(stream, &result).await?;
1420        }
1421        Err(err) => {
1422            // PG SQLSTATE class 42 covers syntax / binding errors; we use
1423            // 42P01 (undefined_table) and 42601 (syntax_error) when we can
1424            // detect; otherwise fall back to XX000 (internal error).
1425            let code = classify_sqlstate(&err.to_string());
1426            send_error(stream, code, &crate::api::client_facing_message(&err)).await?;
1427        }
1428    }
1429
1430    write_frame(
1431        stream,
1432        &BackendMessage::ReadyForQuery(TransactionStatus::Idle),
1433    )
1434    .await?;
1435    Ok(())
1436}
1437
1438fn pg_session_compat_command_tag(sql: &str) -> Option<&'static str> {
1439    let lower = sql.trim().trim_end_matches(';').to_ascii_lowercase();
1440    if lower.starts_with("set ") {
1441        return Some("SET");
1442    }
1443    None
1444}
1445
1446async fn emit_success_result<S>(
1447    stream: &mut S,
1448    result: &crate::runtime::RuntimeQueryResult,
1449) -> Result<(), PgWireError>
1450where
1451    S: AsyncWrite + Unpin,
1452{
1453    if result.statement == "ask" {
1454        emit_ask_result_row(stream, result).await?;
1455        write_frame(
1456            stream,
1457            &BackendMessage::CommandComplete("SELECT 1".to_string()),
1458        )
1459        .await?;
1460    } else if result_returns_rows(result) {
1461        emit_result_rows(stream, &result.result).await?;
1462        write_frame(
1463            stream,
1464            &BackendMessage::CommandComplete(format!("SELECT {}", result.result.records.len())),
1465        )
1466        .await?;
1467    } else {
1468        // DDL / DML / config statements: echo the runtime's
1469        // high-level statement tag back. PG format is
1470        // "<CMD> [<OID>] <COUNT>"; we keep the count where
1471        // applicable and fall back to the runtime's message.
1472        let tag = match result.statement_type {
1473            "insert" => format!("INSERT 0 {}", result.affected_rows),
1474            "update" => format!("UPDATE {}", result.affected_rows),
1475            "delete" => format!("DELETE {}", result.affected_rows),
1476            other => other.to_uppercase(),
1477        };
1478        write_frame(stream, &BackendMessage::CommandComplete(tag)).await?;
1479    }
1480    Ok(())
1481}
1482
1483async fn emit_success_result_without_row_description<S>(
1484    stream: &mut S,
1485    result: &crate::runtime::RuntimeQueryResult,
1486) -> Result<(), PgWireError>
1487where
1488    S: AsyncWrite + Unpin,
1489{
1490    if result.statement == "ask" {
1491        let row = ask_query_result_to_pg_wire_row(result)
1492            .ok_or_else(|| PgWireError::Protocol("ASK result missing row body".to_string()))?;
1493        write_frame(stream, &BackendMessage::DataRow(row.cells)).await?;
1494        write_frame(
1495            stream,
1496            &BackendMessage::CommandComplete("SELECT 1".to_string()),
1497        )
1498        .await?;
1499    } else if result_returns_rows(result) {
1500        emit_result_data_rows(stream, &result.result).await?;
1501        write_frame(
1502            stream,
1503            &BackendMessage::CommandComplete(format!("SELECT {}", result.result.records.len())),
1504        )
1505        .await?;
1506    } else {
1507        let tag = match result.statement_type {
1508            "insert" => format!("INSERT 0 {}", result.affected_rows),
1509            "update" => format!("UPDATE {}", result.affected_rows),
1510            "delete" => format!("DELETE {}", result.affected_rows),
1511            other => other.to_uppercase(),
1512        };
1513        write_frame(stream, &BackendMessage::CommandComplete(tag)).await?;
1514    }
1515    Ok(())
1516}
1517
1518enum PortalExecution {
1519    Complete,
1520    Suspended { next_row_offset: usize },
1521}
1522
1523async fn emit_portal_execution<S>(
1524    stream: &mut S,
1525    result: &crate::runtime::RuntimeQueryResult,
1526    row_description_sent: bool,
1527    row_offset: usize,
1528    max_rows: u32,
1529) -> Result<PortalExecution, String>
1530where
1531    S: AsyncWrite + Unpin,
1532{
1533    if result.statement == "ask" && row_description_sent {
1534        emit_success_result_without_row_description(stream, result)
1535            .await
1536            .map_err(|err| err.to_string())?;
1537        Ok(PortalExecution::Complete)
1538    } else if result.statement == "ask" {
1539        emit_success_result(stream, result)
1540            .await
1541            .map_err(|err| err.to_string())?;
1542        Ok(PortalExecution::Complete)
1543    } else if result_returns_rows(result) {
1544        emit_row_returning_portal_execution(
1545            stream,
1546            result,
1547            row_description_sent,
1548            row_offset,
1549            max_rows,
1550        )
1551        .await
1552    } else if row_description_sent {
1553        emit_success_result_without_row_description(stream, result)
1554            .await
1555            .map_err(|err| err.to_string())?;
1556        Ok(PortalExecution::Complete)
1557    } else {
1558        emit_success_result(stream, result)
1559            .await
1560            .map_err(|err| err.to_string())?;
1561        Ok(PortalExecution::Complete)
1562    }
1563}
1564
1565async fn emit_row_returning_portal_execution<S>(
1566    stream: &mut S,
1567    result: &crate::runtime::RuntimeQueryResult,
1568    row_description_sent: bool,
1569    row_offset: usize,
1570    max_rows: u32,
1571) -> Result<PortalExecution, String>
1572where
1573    S: AsyncWrite + Unpin,
1574{
1575    if !row_description_sent {
1576        emit_result_row_description(stream, &result.result)
1577            .await
1578            .map_err(|err| err.to_string())?;
1579    }
1580
1581    let total_rows = result.result.records.len();
1582    let remaining_rows = total_rows.saturating_sub(row_offset);
1583    let rows_to_emit = if max_rows == 0 {
1584        remaining_rows
1585    } else {
1586        remaining_rows.min(max_rows as usize)
1587    };
1588    emit_result_data_rows_range(stream, &result.result, row_offset, rows_to_emit)
1589        .await
1590        .map_err(|err| err.to_string())?;
1591
1592    let next_row_offset = row_offset + rows_to_emit;
1593    if next_row_offset < total_rows {
1594        write_frame(stream, &BackendMessage::PortalSuspended)
1595            .await
1596            .map_err(|err| err.to_string())?;
1597        Ok(PortalExecution::Suspended { next_row_offset })
1598    } else {
1599        write_frame(
1600            stream,
1601            &BackendMessage::CommandComplete(format!("SELECT {}", total_rows)),
1602        )
1603        .await
1604        .map_err(|err| err.to_string())?;
1605        Ok(PortalExecution::Complete)
1606    }
1607}
1608
1609async fn emit_row_description_for_result<S>(
1610    stream: &mut S,
1611    result: &crate::runtime::RuntimeQueryResult,
1612) -> Result<(), PgWireError>
1613where
1614    S: AsyncWrite + Unpin,
1615{
1616    if result.statement == "ask" {
1617        emit_ask_row_description(stream).await
1618    } else if result_returns_rows(result) {
1619        emit_result_row_description(stream, &result.result).await
1620    } else {
1621        write_frame(stream, &BackendMessage::NoData).await
1622    }
1623}
1624
1625fn result_returns_rows(result: &crate::runtime::RuntimeQueryResult) -> bool {
1626    result.statement_type == "select"
1627}
1628
1629async fn emit_result_rows<S>(
1630    stream: &mut S,
1631    result: &crate::storage::query::unified::UnifiedResult,
1632) -> Result<(), PgWireError>
1633where
1634    S: AsyncWrite + Unpin,
1635{
1636    emit_result_row_description(stream, result).await?;
1637    emit_result_data_rows(stream, result).await
1638}
1639
1640async fn emit_result_row_description<S>(
1641    stream: &mut S,
1642    result: &crate::storage::query::unified::UnifiedResult,
1643) -> Result<(), PgWireError>
1644where
1645    S: AsyncWrite + Unpin,
1646{
1647    // RowDescription: derived from the first record's column ordering.
1648    // When `result.columns` is non-empty we honour that order; otherwise
1649    // we synthesise one from the record's field order.
1650    let columns: Vec<String> = if !result.columns.is_empty() {
1651        result.columns.clone()
1652    } else if let Some(first) = result.records.first() {
1653        record_field_names(first)
1654    } else {
1655        Vec::new()
1656    };
1657
1658    // Peek at the first record for per-column type OIDs. When there's no
1659    // data row we fall back to TEXT for every column — clients render
1660    // empty result sets happily.
1661    let type_oids: Vec<PgOid> = columns
1662        .iter()
1663        .map(|col| {
1664            result
1665                .records
1666                .first()
1667                .and_then(|r| record_get(r, col))
1668                .map(PgOid::from_value)
1669                .unwrap_or(PgOid::Text)
1670        })
1671        .collect();
1672
1673    let descriptors: Vec<ColumnDescriptor> = columns
1674        .iter()
1675        .zip(type_oids.iter())
1676        .map(|(name, oid)| ColumnDescriptor {
1677            name: name.clone(),
1678            table_oid: 0,
1679            column_attr: 0,
1680            type_oid: oid.as_u32(),
1681            type_size: -1,
1682            type_mod: -1,
1683            format: 0,
1684        })
1685        .collect();
1686
1687    write_frame(stream, &BackendMessage::RowDescription(descriptors)).await
1688}
1689
1690async fn emit_result_data_rows<S>(
1691    stream: &mut S,
1692    result: &crate::storage::query::unified::UnifiedResult,
1693) -> Result<(), PgWireError>
1694where
1695    S: AsyncWrite + Unpin,
1696{
1697    emit_result_data_rows_range(stream, result, 0, result.records.len()).await
1698}
1699
1700async fn emit_result_data_rows_range<S>(
1701    stream: &mut S,
1702    result: &crate::storage::query::unified::UnifiedResult,
1703    row_offset: usize,
1704    row_count: usize,
1705) -> Result<(), PgWireError>
1706where
1707    S: AsyncWrite + Unpin,
1708{
1709    let columns: Vec<String> = if !result.columns.is_empty() {
1710        result.columns.clone()
1711    } else if let Some(first) = result.records.first() {
1712        record_field_names(first)
1713    } else {
1714        Vec::new()
1715    };
1716    for record in result.records.iter().skip(row_offset).take(row_count) {
1717        let fields: Vec<Option<Vec<u8>>> = columns
1718            .iter()
1719            .map(|col| record_get(record, col).and_then(value_to_pg_wire_bytes))
1720            .collect();
1721        write_frame(stream, &BackendMessage::DataRow(fields)).await?;
1722    }
1723
1724    Ok(())
1725}
1726
1727async fn emit_ask_result_row<S>(
1728    stream: &mut S,
1729    result: &crate::runtime::RuntimeQueryResult,
1730) -> Result<(), PgWireError>
1731where
1732    S: AsyncWrite + Unpin,
1733{
1734    let row = ask_query_result_to_pg_wire_row(result)
1735        .ok_or_else(|| PgWireError::Protocol("ASK result missing row body".to_string()))?;
1736
1737    emit_ask_row_description(stream).await?;
1738    write_frame(stream, &BackendMessage::DataRow(row.cells)).await?;
1739    Ok(())
1740}
1741
1742async fn emit_ask_row_description<S>(stream: &mut S) -> Result<(), PgWireError>
1743where
1744    S: AsyncWrite + Unpin,
1745{
1746    let descriptors: Vec<ColumnDescriptor> = crate::runtime::ai::pg_wire_ask_row_encoder::columns()
1747        .iter()
1748        .map(|col| ColumnDescriptor {
1749            name: col.name.to_string(),
1750            table_oid: 0,
1751            column_attr: 0,
1752            type_oid: col.oid.as_u32(),
1753            type_size: -1,
1754            type_mod: -1,
1755            format: 0,
1756        })
1757        .collect();
1758    write_frame(stream, &BackendMessage::RowDescription(descriptors)).await
1759}
1760
1761fn ask_query_result_to_pg_wire_row(
1762    result: &crate::runtime::RuntimeQueryResult,
1763) -> Option<crate::runtime::ai::pg_wire_ask_row_encoder::AskRow> {
1764    if result.statement != "ask" {
1765        return None;
1766    }
1767    let ask = crate::presentation::query_result::ask_result_from_unified_result(&result.result)?;
1768
1769    Some(crate::runtime::ai::pg_wire_ask_row_encoder::encode(&ask))
1770}
1771
1772/// Best-effort field lookup on a `UnifiedRecord`. The record API lives in
1773/// `storage::query::unified` and today uses `HashMap<String, Value>` under
1774/// the hood — we use `get` if it exists, else fall back to serialised map.
1775fn record_get<'a>(record: &'a UnifiedRecord, key: &str) -> Option<&'a Value> {
1776    record.get(key)
1777}
1778
1779/// Extract column names in iteration order from a single record. When
1780/// the caller didn't supply an explicit `columns` projection we use the
1781/// first record's field ordering as the canonical tuple shape.
1782///
1783/// HashMap iteration order is non-deterministic — for Phase 3.1 we
1784/// accept the shuffle since PG clients receive the ordered header via
1785/// RowDescription and match cells positionally. A stable ordering
1786/// would require keeping an insertion-order index alongside `values`.
1787fn record_field_names(record: &UnifiedRecord) -> Vec<String> {
1788    // `column_names()` merges the columnar scan side-channel with
1789    // the HashMap so scan rows (which populate only columnar) still
1790    // surface their field names in PG wire output.
1791    record
1792        .column_names()
1793        .into_iter()
1794        .map(|k| k.to_string())
1795        .collect()
1796}
1797
1798async fn send_error<S>(stream: &mut S, code: &str, message: &str) -> Result<(), PgWireError>
1799where
1800    S: AsyncWrite + Unpin,
1801{
1802    write_frame(
1803        stream,
1804        &BackendMessage::ErrorResponse {
1805            severity: "ERROR".to_string(),
1806            code: code.to_string(),
1807            message: message.to_string(),
1808        },
1809    )
1810    .await
1811}
1812
1813/// Heuristically map a runtime error message onto a PG SQLSTATE. Full
1814/// coverage would map every `RedDBError` variant; this is enough for the
1815/// common psql / JDBC paths.
1816fn classify_sqlstate(msg: &str) -> &'static str {
1817    let lower = msg.to_ascii_lowercase();
1818    let detail = lower.strip_prefix("query error: ").unwrap_or(&lower);
1819    if detail == "division by zero" {
1820        "22012" // division_by_zero
1821    } else if detail == "arithmetic overflow in div" {
1822        "22003" // numeric_value_out_of_range
1823    } else if detail == "invalid regular expression" {
1824        "2201B" // invalid_regular_expression
1825    } else if detail == "operator ~ requires text operands"
1826        || detail.starts_with("unary neg not defined for ")
1827    {
1828        "42883" // undefined_function
1829    } else if detail.starts_with("join aggregate column ") && detail.ends_with(" is ambiguous") {
1830        "42702" // ambiguous_column
1831    } else if detail.starts_with("join aggregate column ")
1832        && detail.contains(" must appear in group by")
1833    {
1834        "42803" // grouping_error
1835    } else if detail == "having requires a boolean expression"
1836        || lower.contains("filter requires a boolean expression")
1837    {
1838        "42804" // datatype_mismatch
1839    } else if lower.contains("aggregate functions are not allowed in filter")
1840        || detail == "aggregate functions are not allowed in where"
1841        || detail.starts_with("subquery uses ungrouped column ")
1842    {
1843        "42803" // grouping_error
1844    } else if lower.contains("filter requires an aggregate function") {
1845        "42809" // wrong_object_type
1846    } else if detail.starts_with("join aggregate column ") && detail.ends_with(" does not exist") {
1847        "42703" // undefined_column
1848    } else if lower.contains("order by position ") && lower.contains(" is not in the select list") {
1849        "42P10" // invalid_column_reference
1850    } else if detail.starts_with("function ") && detail.ends_with(" does not exist") {
1851        "42883" // undefined_function
1852    } else if lower.contains("not found") || lower.contains("does not exist") {
1853        // 42P01 undefined_table; close enough for collection-not-found.
1854        "42P01"
1855    } else if lower.contains("parse") || lower.contains("expected") || lower.contains("syntax") {
1856        "42601"
1857    } else if lower.contains("already exists") {
1858        "42P07"
1859    } else if lower.contains("permission") || lower.contains("auth") {
1860        "28000"
1861    } else {
1862        "XX000"
1863    }
1864}
1865
1866#[cfg(test)]
1867mod tests {
1868    use super::*;
1869    use crate::api::RedDBOptions;
1870    use crate::auth::{AuthConfig, AuthStore, UserAttributes, UserId};
1871    use crate::runtime::RuntimeQueryResult;
1872    use crate::storage::query::unified::UnifiedResult;
1873    use reddb_rql::modes::QueryMode;
1874    use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
1875
1876    async fn assert_pg_password_rejected(auth: Arc<AuthStore>, username: &str, password: &str) {
1877        let runtime = Arc::new(RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap());
1878        runtime.set_auth_store(auth);
1879        let config = Arc::new(PgWireConfig::default());
1880        let (server_io, mut client_io) = tokio::io::duplex(64 * 1024);
1881        let server = tokio::spawn(async move {
1882            handle_connection(server_io, runtime, config, None)
1883                .await
1884                .unwrap();
1885        });
1886
1887        write_startup_params(&mut client_io, &[("user", username)]).await;
1888        let (tag, body) = read_backend_frame(&mut client_io).await;
1889        assert_eq!(tag, b'R');
1890        assert_eq!(i32::from_be_bytes(body[..4].try_into().unwrap()), 3);
1891        write_frontend_frame(&mut client_io, b'p', cstring_body(password)).await;
1892        let (tag, body) = read_backend_frame(&mut client_io).await;
1893        assert_eq!(tag, b'E');
1894        assert_eq!(error_response_field(&body, b'C'), Some("28P01"));
1895
1896        let mut eof = [0u8; 1];
1897        assert_eq!(client_io.read(&mut eof).await.unwrap(), 0);
1898        server.await.unwrap();
1899    }
1900
1901    #[tokio::test]
1902    async fn response_writer_releases_execution_slot_before_socket_write() {
1903        let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
1904        runtime.configure_execution_admission(1, 0, 100);
1905        let admission = runtime.execution_admission();
1906        let permit = admission.acquire().await.expect("execution permit");
1907        assert_eq!(admission.active(), 1);
1908
1909        let (mut server_io, mut client_io) = tokio::io::duplex(64);
1910        let mut writer = ExecutionResponseWriter::new(&mut server_io, Some(permit));
1911        writer.write_all(b"ok").await.unwrap();
1912        assert_eq!(admission.active(), 0);
1913
1914        let mut received = [0_u8; 2];
1915        client_io.read_exact(&mut received).await.unwrap();
1916        assert_eq!(&received, b"ok");
1917    }
1918
1919    #[tokio::test]
1920    async fn enabled_auth_store_rejects_bad_pgwire_password_with_28p01() {
1921        let runtime = Arc::new(RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap());
1922        let auth = Arc::new(AuthStore::new(AuthConfig {
1923            enabled: true,
1924            require_auth: true,
1925            ..AuthConfig::default()
1926        }));
1927        auth.create_user("alice", "secret", Role::Write).unwrap();
1928        runtime.set_auth_store(auth);
1929
1930        let config = Arc::new(PgWireConfig::default());
1931        let (server_io, mut client_io) = tokio::io::duplex(64 * 1024);
1932        let server = tokio::spawn(async move {
1933            handle_connection(server_io, runtime, config, None)
1934                .await
1935                .unwrap();
1936        });
1937
1938        write_startup_params(&mut client_io, &[("user", "alice")]).await;
1939        // Server must challenge for a cleartext password first.
1940        let (tag, body) = read_backend_frame(&mut client_io).await;
1941        assert_eq!(tag, b'R');
1942        assert_eq!(i32::from_be_bytes(body[..4].try_into().unwrap()), 3);
1943
1944        write_frontend_frame(&mut client_io, b'p', cstring_body("wrong")).await;
1945        let (tag, body) = read_backend_frame(&mut client_io).await;
1946        assert_eq!(tag, b'E');
1947        assert_eq!(error_response_field(&body, b'C'), Some("28P01"));
1948
1949        // The connection is closed after an auth failure.
1950        let mut eof = [0u8; 1];
1951        assert_eq!(client_io.read(&mut eof).await.unwrap(), 0);
1952        server.await.unwrap();
1953    }
1954
1955    #[tokio::test]
1956    async fn pgwire_rejects_expired_accounts() {
1957        let auth = Arc::new(AuthStore::new(AuthConfig {
1958            enabled: true,
1959            require_auth: true,
1960            ..AuthConfig::default()
1961        }));
1962        auth.create_user("alice", "secret", Role::Write).unwrap();
1963        auth.set_user_attributes(
1964            &UserId::platform("alice"),
1965            UserAttributes {
1966                valid_until: Some(1),
1967                ..UserAttributes::default()
1968            },
1969        )
1970        .unwrap();
1971
1972        assert_pg_password_rejected(auth, "alice", "secret").await;
1973    }
1974
1975    #[tokio::test]
1976    async fn pgwire_rejects_accounts_at_connection_limit() {
1977        let auth = Arc::new(AuthStore::new(AuthConfig {
1978            enabled: true,
1979            require_auth: true,
1980            ..AuthConfig::default()
1981        }));
1982        auth.create_user("alice", "secret", Role::Write).unwrap();
1983        let id = UserId::platform("alice");
1984        auth.set_user_attributes(
1985            &id,
1986            UserAttributes {
1987                connection_limit: Some(1),
1988                ..UserAttributes::default()
1989            },
1990        )
1991        .unwrap();
1992        let _held = auth
1993            .acquire_connection_lease(&id)
1994            .expect("occupy the only connection slot");
1995
1996        assert_pg_password_rejected(auth, "alice", "secret").await;
1997    }
1998
1999    #[tokio::test]
2000    async fn pgwire_password_auth_installs_statement_identity() {
2001        let runtime = Arc::new(RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap());
2002        let auth = Arc::new(AuthStore::new(AuthConfig {
2003            enabled: true,
2004            require_auth: true,
2005            ..AuthConfig::default()
2006        }));
2007        auth.create_user_in_tenant(Some("acme"), "alice", "secret", Role::Write)
2008            .unwrap();
2009        runtime.set_auth_store(auth);
2010
2011        let config = Arc::new(PgWireConfig::default());
2012        let (server_io, mut client_io) = tokio::io::duplex(64 * 1024);
2013        let server = tokio::spawn(async move {
2014            handle_connection(server_io, runtime, config, None)
2015                .await
2016                .unwrap();
2017        });
2018
2019        write_startup_params(&mut client_io, &[("user", "alice"), ("tenant", "acme")]).await;
2020        let (tag, body) = read_backend_frame(&mut client_io).await;
2021        assert_eq!(tag, b'R');
2022        assert_eq!(i32::from_be_bytes(body[..4].try_into().unwrap()), 3);
2023        write_frontend_frame(&mut client_io, b'p', cstring_body("secret")).await;
2024        read_until_ready(&mut client_io).await;
2025
2026        // The authenticated identity must drive CURRENT_USER/ROLE/TENANT so
2027        // the simple-query path yields real rows (T,D,C,Z), transport-
2028        // invariant with the native wire.
2029        write_frontend_frame(
2030            &mut client_io,
2031            b'Q',
2032            cstring_body("SELECT CURRENT_USER(), CURRENT_ROLE(), CURRENT_TENANT()"),
2033        )
2034        .await;
2035        let frames = read_until_ready(&mut client_io).await;
2036        assert_eq!(
2037            frames.iter().map(|(tag, _)| *tag).collect::<Vec<_>>(),
2038            b"TDCZ"
2039        );
2040        let cells = decode_data_row(&frames[1].1);
2041        assert_eq!(cells[0].as_deref(), Some(b"alice".as_slice()));
2042        assert_eq!(cells[1].as_deref(), Some(b"write".as_slice()));
2043        assert_eq!(cells[2].as_deref(), Some(b"acme".as_slice()));
2044
2045        write_frontend_frame(&mut client_io, b'X', Vec::new()).await;
2046        server.await.unwrap();
2047    }
2048
2049    #[tokio::test]
2050    async fn extended_parse_bind_execute_returns_rows() {
2051        let runtime = Arc::new(RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap());
2052        let config = Arc::new(PgWireConfig::default());
2053        let (server_io, mut client_io) = tokio::io::duplex(64 * 1024);
2054        let server = tokio::spawn(async move {
2055            handle_connection(server_io, runtime, config, None)
2056                .await
2057                .unwrap();
2058        });
2059
2060        write_startup(&mut client_io).await;
2061        read_until_ready(&mut client_io).await;
2062
2063        write_frontend_frame(
2064            &mut client_io,
2065            b'P',
2066            parse_body("", "SELECT 1 ORDER BY 2", &[]),
2067        )
2068        .await;
2069        write_frontend_frame(&mut client_io, b'B', bind_body("", "", &[], &[], &[])).await;
2070        write_frontend_frame(&mut client_io, b'D', describe_body(b'P', "")).await;
2071        write_frontend_frame(&mut client_io, b'E', execute_body("", 0)).await;
2072        write_frontend_frame(&mut client_io, b'S', Vec::new()).await;
2073        let frames = read_until_ready(&mut client_io).await;
2074        assert_eq!(
2075            frames.iter().map(|(tag, _)| *tag).collect::<Vec<_>>(),
2076            b"EZ"
2077        );
2078        assert!(frames[0].1.windows(7).any(|field| field == b"C42P10\0"));
2079
2080        write_frontend_frame(
2081            &mut client_io,
2082            b'P',
2083            parse_body("", "SELECT $1::int", &[PgOid::Int4.as_u32()]),
2084        )
2085        .await;
2086        write_frontend_frame(
2087            &mut client_io,
2088            b'B',
2089            bind_body("", "", &[0], &[Some(b"42".as_slice())], &[]),
2090        )
2091        .await;
2092        write_frontend_frame(&mut client_io, b'D', describe_body(b'P', "")).await;
2093        write_frontend_frame(&mut client_io, b'E', execute_body("", 0)).await;
2094        write_frontend_frame(&mut client_io, b'S', Vec::new()).await;
2095
2096        let frames = read_until_ready(&mut client_io).await;
2097        assert_eq!(
2098            frames.iter().map(|(tag, _)| *tag).collect::<Vec<_>>(),
2099            b"12TDCZ"
2100        );
2101        let columns = decode_row_description(&frames[2].1);
2102        assert_eq!(columns.len(), 1);
2103        let cells = decode_data_row(&frames[3].1);
2104        assert_eq!(cells.len(), 1);
2105        assert_eq!(cells[0].as_deref(), Some(b"42".as_slice()));
2106        assert_eq!(decode_command_complete(&frames[4].1), "SELECT 1");
2107
2108        write_frontend_frame(&mut client_io, b'X', Vec::new()).await;
2109        server.await.unwrap();
2110    }
2111
2112    #[test]
2113    fn prepared_pg_utility_statements_preserve_ddl_and_transactions() {
2114        let runtime = RedDBRuntime::in_memory().expect("runtime");
2115        let registry = PreparedRegistry::new();
2116        let execute = |sql: &str, params: Vec<ParamValue>| {
2117            let prepared = registry
2118                .prepare(&runtime, sql)
2119                .expect("prepare utility or DML");
2120            execute_pg_query_result(&runtime, None, &registry, prepared.id, sql, &params)
2121                .unwrap_or_else(|error| panic!("{sql}: {error}"))
2122        };
2123        execute("CREATE TABLE pg_utilities (id INT)", Vec::new());
2124        execute("BEGIN", Vec::new());
2125        execute(
2126            "INSERT INTO pg_utilities (id) VALUES ($1)",
2127            vec![ParamValue::Int64(1)],
2128        );
2129        execute("SAVEPOINT before_second", Vec::new());
2130        execute(
2131            "INSERT INTO pg_utilities (id) VALUES ($1)",
2132            vec![ParamValue::Int64(2)],
2133        );
2134        execute("ROLLBACK TO SAVEPOINT before_second", Vec::new());
2135        execute("COMMIT", Vec::new());
2136        let result = execute("SELECT id FROM pg_utilities", Vec::new());
2137        assert_eq!(result.result.records.len(), 1);
2138        assert_eq!(result.result.records[0].get("id"), Some(&Value::Integer(1)));
2139        execute("DROP TABLE pg_utilities", Vec::new());
2140        assert!(runtime
2141            .db()
2142            .store()
2143            .get_collection("pg_utilities")
2144            .is_none());
2145    }
2146
2147    #[tokio::test]
2148    async fn extended_repeated_execute_parses_prepared_shape_once() {
2149        let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap();
2150        runtime
2151            .execute_query("CREATE TABLE pg_parse_once (id INT)")
2152            .unwrap();
2153        runtime
2154            .execute_query("INSERT INTO pg_parse_once (id) VALUES (42)")
2155            .unwrap();
2156        let prepared_registry = PreparedRegistry::new();
2157        let mut prepared = HashMap::new();
2158        let mut portals = HashMap::new();
2159        let (mut server_io, _client_io) = tokio::io::duplex(64 * 1024);
2160
2161        handle_parse(
2162            &mut server_io,
2163            &runtime,
2164            &prepared_registry,
2165            &mut prepared,
2166            &portals,
2167            super::super::protocol::ParseMessage {
2168                statement: "parse_once_stmt".to_string(),
2169                query: "SELECT id FROM pg_parse_once WHERE id = $1".to_string(),
2170                param_type_oids: vec![PgOid::Int4.as_u32()],
2171            },
2172        )
2173        .await
2174        .unwrap();
2175        assert_eq!(prepared_registry.parse_count(), 1);
2176
2177        handle_bind(
2178            &mut server_io,
2179            &prepared_registry,
2180            &prepared,
2181            &mut portals,
2182            super::super::protocol::BindMessage {
2183                portal: "parse_once_portal".to_string(),
2184                statement: "parse_once_stmt".to_string(),
2185                param_format_codes: vec![0],
2186                params: vec![Some(b"42".to_vec())],
2187                result_format_codes: Vec::new(),
2188            },
2189        )
2190        .await
2191        .unwrap();
2192
2193        for _ in 0..2 {
2194            handle_execute(
2195                &mut server_io,
2196                &runtime,
2197                None,
2198                &prepared_registry,
2199                &mut portals,
2200                super::super::protocol::ExecuteMessage {
2201                    portal: "parse_once_portal".to_string(),
2202                    max_rows: 0,
2203                },
2204            )
2205            .await
2206            .unwrap();
2207        }
2208        assert_eq!(prepared_registry.parse_count(), 1);
2209    }
2210
2211    #[tokio::test]
2212    async fn non_loopback_plaintext_refuses_cleartext_password_without_tls() {
2213        // Posture (issue #1653): a cleartext password may not be challenged
2214        // over an unencrypted non-loopback link. The server must refuse
2215        // *before* sending AuthenticationCleartextPassword, so a driver
2216        // using sslmode=disable against a remote bind never leaks its
2217        // password in the clear. `tls_acceptor = None` + no SSLRequest is
2218        // exactly that plaintext, no-TLS path.
2219        let runtime = Arc::new(RedDBRuntime::with_options(RedDBOptions::in_memory()).unwrap());
2220        let auth = Arc::new(AuthStore::new(AuthConfig {
2221            enabled: true,
2222            require_auth: true,
2223            ..AuthConfig::default()
2224        }));
2225        auth.create_user("alice", "secret", Role::Write).unwrap();
2226        runtime.set_auth_store(auth);
2227
2228        // Non-loopback bind: the wildcard address is not a loopback host.
2229        let config = Arc::new(PgWireConfig {
2230            bind_addr: "0.0.0.0:5432".to_string(),
2231            ..PgWireConfig::default()
2232        });
2233        let (server_io, mut client_io) = tokio::io::duplex(64 * 1024);
2234        let server = tokio::spawn(async move {
2235            handle_connection(server_io, runtime, config, None)
2236                .await
2237                .unwrap();
2238        });
2239
2240        write_startup_params(&mut client_io, &[("user", "alice")]).await;
2241        // The refusal arrives directly — never an 'R' cleartext challenge.
2242        let (tag, body) = read_backend_frame(&mut client_io).await;
2243        assert_eq!(tag, b'E', "expected an ErrorResponse, not a challenge");
2244        assert_eq!(error_response_field(&body, b'C'), Some("28000"));
2245
2246        // The connection is closed after the refusal.
2247        let mut eof = [0u8; 1];
2248        assert_eq!(client_io.read(&mut eof).await.unwrap(), 0);
2249        server.await.unwrap();
2250    }
2251
2252    #[test]
2253    fn infer_pg_cast_param_type_oids_from_parameter_casts() {
2254        assert_eq!(
2255            infer_pg_cast_param_type_oids("INSERT INTO t (id, name) VALUES ($1::int, $2::text)"),
2256            vec![(0, PgOid::Int4.as_u32()), (1, PgOid::Text.as_u32())]
2257        );
2258        assert_eq!(
2259            infer_pg_cast_param_type_oids("SEARCH SIMILAR [1.0] COLLECTION v LIMIT $1::int8"),
2260            vec![(0, PgOid::Int8.as_u32())]
2261        );
2262    }
2263
2264    #[test]
2265    fn pg_session_compat_accepts_driver_setup_set_commands() {
2266        assert_eq!(
2267            pg_session_compat_command_tag("SET extra_float_digits = 3"),
2268            Some("SET")
2269        );
2270        assert_eq!(
2271            pg_session_compat_command_tag("SET application_name = 'pgjdbc'"),
2272            Some("SET")
2273        );
2274        assert_eq!(pg_session_compat_command_tag("SELECT 1"), None);
2275    }
2276
2277    #[tokio::test]
2278    async fn ask_success_result_uses_canonical_pg_wire_row_shape() {
2279        let mut result = UnifiedResult::with_columns(vec![
2280            "answer".into(),
2281            "provider".into(),
2282            "model".into(),
2283            "prompt_tokens".into(),
2284            "completion_tokens".into(),
2285            "sources_count".into(),
2286            "sources_flat".into(),
2287            "citations".into(),
2288            "validation".into(),
2289        ]);
2290        let mut record = UnifiedRecord::new();
2291        record.set("answer", Value::text("Deploy failed [^1]."));
2292        record.set("provider", Value::text("openai"));
2293        record.set("model", Value::text("gpt-4o-mini"));
2294        record.set("prompt_tokens", Value::Integer(11));
2295        record.set("completion_tokens", Value::Integer(7));
2296        record.set(
2297            "sources_flat",
2298            Value::Json(
2299                br#"[{"urn":"urn:reddb:row:deployments:1","kind":"row","collection":"deployments","id":"1"}]"#
2300                    .to_vec(),
2301            ),
2302        );
2303        record.set(
2304            "citations",
2305            Value::Json(br#"[{"marker":1,"urn":"urn:reddb:row:deployments:1"}]"#.to_vec()),
2306        );
2307        record.set(
2308            "validation",
2309            Value::Json(br#"{"ok":true,"warnings":[],"errors":[]}"#.to_vec()),
2310        );
2311        result.push(record);
2312
2313        let qr = RuntimeQueryResult {
2314            query: "ASK 'why did deploy fail?'".to_string(),
2315            mode: QueryMode::Sql,
2316            statement: "ask",
2317            engine: "runtime-ai",
2318            result,
2319            affected_rows: 0,
2320            statement_type: "select",
2321            bookmark: None,
2322            notice: None,
2323        };
2324
2325        let mut out = Vec::new();
2326        emit_success_result(&mut out, &qr).await.unwrap();
2327        let frames = decode_frames(&out);
2328
2329        assert_eq!(
2330            frames.iter().map(|(tag, _)| *tag).collect::<Vec<_>>(),
2331            b"TDC"
2332        );
2333
2334        let columns = decode_row_description(frames[0].1);
2335        assert_eq!(
2336            columns,
2337            vec![
2338                ("answer".to_string(), PgOid::Text.as_u32()),
2339                ("cache_hit".to_string(), PgOid::Bool.as_u32()),
2340                ("citations".to_string(), PgOid::Jsonb.as_u32()),
2341                ("completion_tokens".to_string(), PgOid::Int8.as_u32()),
2342                ("cost_usd".to_string(), PgOid::Numeric.as_u32()),
2343                ("mode".to_string(), PgOid::Text.as_u32()),
2344                ("model".to_string(), PgOid::Text.as_u32()),
2345                ("prompt_tokens".to_string(), PgOid::Int8.as_u32()),
2346                ("provider".to_string(), PgOid::Text.as_u32()),
2347                ("retry_count".to_string(), PgOid::Int8.as_u32()),
2348                ("sources_flat".to_string(), PgOid::Jsonb.as_u32()),
2349                ("validation".to_string(), PgOid::Jsonb.as_u32()),
2350            ]
2351        );
2352
2353        let cells = decode_data_row(frames[1].1);
2354        assert_eq!(cells.len(), 12);
2355        assert_eq!(cells[0].as_deref(), Some(b"Deploy failed [^1].".as_slice()));
2356        assert_eq!(cells[1].as_deref(), Some(b"f".as_slice()));
2357        assert_eq!(cells[4].as_deref(), Some(b"0".as_slice()));
2358        assert_eq!(cells[5].as_deref(), Some(b"strict".as_slice()));
2359        assert_eq!(cells[9].as_deref(), Some(b"0".as_slice()));
2360        assert!(std::str::from_utf8(cells[10].as_deref().unwrap())
2361            .unwrap()
2362            .contains(r#""payload""#));
2363        assert_eq!(decode_command_complete(frames[2].1), "SELECT 1");
2364    }
2365
2366    fn decode_frames(bytes: &[u8]) -> Vec<(u8, &[u8])> {
2367        let mut pos = 0;
2368        let mut frames = Vec::new();
2369        while pos < bytes.len() {
2370            let tag = bytes[pos];
2371            let len = u32::from_be_bytes([
2372                bytes[pos + 1],
2373                bytes[pos + 2],
2374                bytes[pos + 3],
2375                bytes[pos + 4],
2376            ]) as usize;
2377            let body_start = pos + 5;
2378            let body_end = pos + 1 + len;
2379            frames.push((tag, &bytes[body_start..body_end]));
2380            pos = body_end;
2381        }
2382        frames
2383    }
2384
2385    fn decode_row_description(body: &[u8]) -> Vec<(String, u32)> {
2386        let count = i16::from_be_bytes([body[0], body[1]]) as usize;
2387        let mut pos = 2;
2388        let mut columns = Vec::with_capacity(count);
2389        for _ in 0..count {
2390            let end = body[pos..].iter().position(|&b| b == 0).unwrap() + pos;
2391            let name = std::str::from_utf8(&body[pos..end]).unwrap().to_string();
2392            pos = end + 1;
2393            pos += 4; // table oid
2394            pos += 2; // column attr
2395            let oid = u32::from_be_bytes([body[pos], body[pos + 1], body[pos + 2], body[pos + 3]]);
2396            pos += 4;
2397            pos += 2; // type size
2398            pos += 4; // type mod
2399            pos += 2; // format
2400            columns.push((name, oid));
2401        }
2402        columns
2403    }
2404
2405    fn decode_data_row(body: &[u8]) -> Vec<Option<Vec<u8>>> {
2406        let count = i16::from_be_bytes([body[0], body[1]]) as usize;
2407        let mut pos = 2;
2408        let mut cells = Vec::with_capacity(count);
2409        for _ in 0..count {
2410            let len = i32::from_be_bytes([body[pos], body[pos + 1], body[pos + 2], body[pos + 3]]);
2411            pos += 4;
2412            if len < 0 {
2413                cells.push(None);
2414            } else {
2415                let len = len as usize;
2416                cells.push(Some(body[pos..pos + len].to_vec()));
2417                pos += len;
2418            }
2419        }
2420        cells
2421    }
2422
2423    fn decode_command_complete(body: &[u8]) -> &str {
2424        let nul = body.iter().position(|&b| b == 0).unwrap_or(body.len());
2425        std::str::from_utf8(&body[..nul]).unwrap()
2426    }
2427
2428    async fn write_startup<W: AsyncWrite + Unpin>(stream: &mut W) {
2429        write_startup_params(stream, &[("user", "reddb")]).await;
2430    }
2431
2432    async fn write_startup_params<W: AsyncWrite + Unpin>(stream: &mut W, params: &[(&str, &str)]) {
2433        let mut payload = Vec::new();
2434        payload.extend_from_slice(&crate::wire::postgres::protocol::PG_PROTOCOL_V3.to_be_bytes());
2435        for (name, value) in params {
2436            push_pg_cstring(&mut payload, name);
2437            push_pg_cstring(&mut payload, value);
2438        }
2439        payload.push(0);
2440        let len = (payload.len() + 4) as u32;
2441        stream.write_all(&len.to_be_bytes()).await.unwrap();
2442        stream.write_all(&payload).await.unwrap();
2443    }
2444
2445    fn cstring_body(value: &str) -> Vec<u8> {
2446        let mut out = Vec::new();
2447        push_pg_cstring(&mut out, value);
2448        out
2449    }
2450
2451    fn error_response_field(body: &[u8], field_tag: u8) -> Option<&str> {
2452        let mut pos = 0;
2453        while pos < body.len() && body[pos] != 0 {
2454            let tag = body[pos];
2455            pos += 1;
2456            let end = body[pos..].iter().position(|&b| b == 0)? + pos;
2457            if tag == field_tag {
2458                return std::str::from_utf8(&body[pos..end]).ok();
2459            }
2460            pos = end + 1;
2461        }
2462        None
2463    }
2464
2465    async fn write_frontend_frame<W: AsyncWrite + Unpin>(
2466        stream: &mut W,
2467        tag: u8,
2468        payload: Vec<u8>,
2469    ) {
2470        stream.write_all(&[tag]).await.unwrap();
2471        stream
2472            .write_all(&((payload.len() + 4) as u32).to_be_bytes())
2473            .await
2474            .unwrap();
2475        stream.write_all(&payload).await.unwrap();
2476    }
2477
2478    async fn read_backend_frame<R: AsyncRead + Unpin>(stream: &mut R) -> (u8, Vec<u8>) {
2479        let mut tag = [0u8; 1];
2480        stream.read_exact(&mut tag).await.unwrap();
2481        let mut len = [0u8; 4];
2482        stream.read_exact(&mut len).await.unwrap();
2483        let len = u32::from_be_bytes(len) as usize;
2484        let mut body = vec![0u8; len - 4];
2485        stream.read_exact(&mut body).await.unwrap();
2486        (tag[0], body)
2487    }
2488
2489    async fn read_until_ready<R: AsyncRead + Unpin>(stream: &mut R) -> Vec<(u8, Vec<u8>)> {
2490        let mut frames = Vec::new();
2491        loop {
2492            let frame = read_backend_frame(stream).await;
2493            let done = frame.0 == b'Z';
2494            frames.push(frame);
2495            if done {
2496                return frames;
2497            }
2498        }
2499    }
2500
2501    fn parse_body(statement: &str, query: &str, oids: &[u32]) -> Vec<u8> {
2502        let mut out = Vec::new();
2503        push_pg_cstring(&mut out, statement);
2504        push_pg_cstring(&mut out, query);
2505        out.extend_from_slice(&(oids.len() as i16).to_be_bytes());
2506        for oid in oids {
2507            out.extend_from_slice(&oid.to_be_bytes());
2508        }
2509        out
2510    }
2511
2512    fn bind_body(
2513        portal: &str,
2514        statement: &str,
2515        formats: &[i16],
2516        params: &[Option<&[u8]>],
2517        result_formats: &[i16],
2518    ) -> Vec<u8> {
2519        let mut out = Vec::new();
2520        push_pg_cstring(&mut out, portal);
2521        push_pg_cstring(&mut out, statement);
2522        out.extend_from_slice(&(formats.len() as i16).to_be_bytes());
2523        for format in formats {
2524            out.extend_from_slice(&format.to_be_bytes());
2525        }
2526        out.extend_from_slice(&(params.len() as i16).to_be_bytes());
2527        for param in params {
2528            match param {
2529                Some(bytes) => {
2530                    out.extend_from_slice(&(bytes.len() as i32).to_be_bytes());
2531                    out.extend_from_slice(bytes);
2532                }
2533                None => out.extend_from_slice(&(-1i32).to_be_bytes()),
2534            }
2535        }
2536        out.extend_from_slice(&(result_formats.len() as i16).to_be_bytes());
2537        for format in result_formats {
2538            out.extend_from_slice(&format.to_be_bytes());
2539        }
2540        out
2541    }
2542
2543    fn describe_body(target: u8, name: &str) -> Vec<u8> {
2544        let mut out = vec![target];
2545        push_pg_cstring(&mut out, name);
2546        out
2547    }
2548
2549    fn execute_body(portal: &str, max_rows: u32) -> Vec<u8> {
2550        let mut out = Vec::new();
2551        push_pg_cstring(&mut out, portal);
2552        out.extend_from_slice(&max_rows.to_be_bytes());
2553        out
2554    }
2555
2556    fn push_pg_cstring(out: &mut Vec<u8>, value: &str) {
2557        out.extend_from_slice(value.as_bytes());
2558        out.push(0);
2559    }
2560}
2561
2562/// A fresh 32-bit cancel key from the OS CSPRNG. Falls back to a
2563/// process/time-derived value only if the CSPRNG is unavailable — the
2564/// key guards nothing yet, so refusing the connection would be the
2565/// wrong trade.
2566fn random_cancel_key() -> u32 {
2567    let mut bytes = [0u8; 4];
2568    if crate::crypto::os_random::fill_bytes(&mut bytes).is_ok() {
2569        return u32::from_le_bytes(bytes);
2570    }
2571    let nanos = std::time::SystemTime::now()
2572        .duration_since(std::time::UNIX_EPOCH)
2573        .map(|d| d.subsec_nanos())
2574        .unwrap_or(0);
2575    std::process::id() ^ nanos
2576}