|
| 1 | +use std::fmt::Debug; |
| 2 | +use std::sync::Arc; |
| 3 | + |
| 4 | +use async_trait::async_trait; |
| 5 | +use futures::stream; |
| 6 | +use pgwire::api::auth::noop::NoopStartupHandler; |
| 7 | +use pgwire::api::query::SimpleQueryHandler; |
| 8 | +use pgwire::api::results::{DataRowEncoder, FieldFormat, FieldInfo, QueryResponse, Response, Tag}; |
| 9 | +use pgwire::api::{ClientInfo, PgWireServerHandlers, Type}; |
| 10 | +use pgwire::error::{PgWireError, PgWireResult}; |
| 11 | +use pgwire::messages::{PgWireBackendMessage, PgWireFrontendMessage}; |
| 12 | +use sqlx::postgres::PgRow; |
| 13 | +use sqlx::{Column, PgPool, Row, TypeInfo}; |
| 14 | + |
| 15 | +use futures::Sink; |
| 16 | + |
| 17 | +/// Handles incoming PostgreSQL wire-protocol queries by forwarding them to a |
| 18 | +/// real PostgreSQL database through sqlx. |
| 19 | +pub struct GitbaseHandler { |
| 20 | + pool: PgPool, |
| 21 | +} |
| 22 | + |
| 23 | +impl GitbaseHandler { |
| 24 | + pub fn new(pool: PgPool) -> Self { |
| 25 | + Self { pool } |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +#[async_trait] |
| 30 | +impl NoopStartupHandler for GitbaseHandler { |
| 31 | + async fn post_startup<C>( |
| 32 | + &self, |
| 33 | + client: &mut C, |
| 34 | + _message: PgWireFrontendMessage, |
| 35 | + ) -> PgWireResult<()> |
| 36 | + where |
| 37 | + C: ClientInfo + Sink<PgWireBackendMessage> + Unpin + Send, |
| 38 | + C::Error: Debug, |
| 39 | + PgWireError: From<<C as Sink<PgWireBackendMessage>>::Error>, |
| 40 | + { |
| 41 | + tracing::info!( |
| 42 | + addr = %client.socket_addr(), |
| 43 | + "client connected" |
| 44 | + ); |
| 45 | + Ok(()) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +#[async_trait] |
| 50 | +impl SimpleQueryHandler for GitbaseHandler { |
| 51 | + async fn do_query<C>(&self, _client: &mut C, query: &str) -> PgWireResult<Vec<Response>> |
| 52 | + where |
| 53 | + C: ClientInfo + Unpin + Send + Sync, |
| 54 | + { |
| 55 | + tracing::debug!(query, "forwarding query to PostgreSQL"); |
| 56 | + |
| 57 | + let trimmed = query.trim().to_uppercase(); |
| 58 | + |
| 59 | + // For SELECT queries, fetch rows and stream them back. |
| 60 | + if trimmed.starts_with("SELECT") { |
| 61 | + let rows: Vec<PgRow> = sqlx::query(query) |
| 62 | + .fetch_all(&self.pool) |
| 63 | + .await |
| 64 | + .map_err(|e| PgWireError::ApiError(Box::new(e)))?; |
| 65 | + |
| 66 | + if rows.is_empty() { |
| 67 | + let schema = Arc::new(vec![]); |
| 68 | + let data_row_stream = stream::empty(); |
| 69 | + return Ok(vec![Response::Query(QueryResponse::new( |
| 70 | + schema, |
| 71 | + data_row_stream, |
| 72 | + ))]); |
| 73 | + } |
| 74 | + |
| 75 | + // Build schema from the first row's columns. |
| 76 | + let columns = rows[0].columns(); |
| 77 | + let field_infos: Vec<FieldInfo> = columns |
| 78 | + .iter() |
| 79 | + .map(|col| { |
| 80 | + let pg_type = sqlx_type_to_pgwire(col.type_info().name()); |
| 81 | + FieldInfo::new( |
| 82 | + col.name().to_string(), |
| 83 | + None, |
| 84 | + None, |
| 85 | + pg_type, |
| 86 | + FieldFormat::Text, |
| 87 | + ) |
| 88 | + }) |
| 89 | + .collect(); |
| 90 | + let schema = Arc::new(field_infos); |
| 91 | + |
| 92 | + // Encode all rows. |
| 93 | + let schema_ref = schema.clone(); |
| 94 | + let encoded_rows: Vec<_> = rows |
| 95 | + .iter() |
| 96 | + .map(|row| { |
| 97 | + let mut encoder = DataRowEncoder::new(schema_ref.clone()); |
| 98 | + for (i, col) in row.columns().iter().enumerate() { |
| 99 | + let value: Option<String> = row.try_get(i).unwrap_or_else(|_| { |
| 100 | + // Fall back: try to get raw bytes and convert |
| 101 | + match col.type_info().name() { |
| 102 | + "INT4" | "INT8" | "INT2" => { |
| 103 | + row.try_get::<i64, _>(i).ok().map(|v| v.to_string()) |
| 104 | + } |
| 105 | + "FLOAT4" | "FLOAT8" => { |
| 106 | + row.try_get::<f64, _>(i).ok().map(|v| v.to_string()) |
| 107 | + } |
| 108 | + "BOOL" => row.try_get::<bool, _>(i).ok().map(|v| v.to_string()), |
| 109 | + _ => row.try_get::<String, _>(i).ok(), |
| 110 | + } |
| 111 | + }); |
| 112 | + encoder.encode_field(&value).unwrap(); |
| 113 | + } |
| 114 | + Ok(encoder.take_row()) |
| 115 | + }) |
| 116 | + .collect(); |
| 117 | + |
| 118 | + let data_row_stream = stream::iter(encoded_rows); |
| 119 | + Ok(vec![Response::Query(QueryResponse::new( |
| 120 | + schema, |
| 121 | + data_row_stream, |
| 122 | + ))]) |
| 123 | + } else { |
| 124 | + // Non-SELECT: execute and return affected rows. |
| 125 | + let result = sqlx::query(query) |
| 126 | + .execute(&self.pool) |
| 127 | + .await |
| 128 | + .map_err(|e| PgWireError::ApiError(Box::new(e)))?; |
| 129 | + Ok(vec![Response::Execution( |
| 130 | + Tag::new("OK").with_rows(result.rows_affected() as usize), |
| 131 | + )]) |
| 132 | + } |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +/// Maps sqlx type names to pgwire Type constants. |
| 137 | +fn sqlx_type_to_pgwire(type_name: &str) -> Type { |
| 138 | + match type_name { |
| 139 | + "INT2" => Type::INT2, |
| 140 | + "INT4" => Type::INT4, |
| 141 | + "INT8" => Type::INT8, |
| 142 | + "FLOAT4" => Type::FLOAT4, |
| 143 | + "FLOAT8" => Type::FLOAT8, |
| 144 | + "BOOL" => Type::BOOL, |
| 145 | + "TEXT" => Type::TEXT, |
| 146 | + "VARCHAR" => Type::VARCHAR, |
| 147 | + "TIMESTAMP" => Type::TIMESTAMP, |
| 148 | + "TIMESTAMPTZ" => Type::TIMESTAMPTZ, |
| 149 | + "DATE" => Type::DATE, |
| 150 | + "UUID" => Type::UUID, |
| 151 | + "JSONB" | "JSON" => Type::JSONB, |
| 152 | + _ => Type::TEXT, |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +/// Factory used by pgwire to obtain handler instances per connection. |
| 157 | +pub struct GitbaseServerFactory { |
| 158 | + handler: Arc<GitbaseHandler>, |
| 159 | +} |
| 160 | + |
| 161 | +impl GitbaseServerFactory { |
| 162 | + pub fn new(pool: PgPool) -> Self { |
| 163 | + Self { |
| 164 | + handler: Arc::new(GitbaseHandler::new(pool)), |
| 165 | + } |
| 166 | + } |
| 167 | +} |
| 168 | + |
| 169 | +impl PgWireServerHandlers for GitbaseServerFactory { |
| 170 | + fn simple_query_handler(&self) -> Arc<impl SimpleQueryHandler> { |
| 171 | + self.handler.clone() |
| 172 | + } |
| 173 | + |
| 174 | + fn startup_handler(&self) -> Arc<impl pgwire::api::auth::StartupHandler> { |
| 175 | + self.handler.clone() |
| 176 | + } |
| 177 | +} |
0 commit comments