Skip to main content

risingwave_connector/connector_common/
postgres.rs

1// Copyright 2024 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{BTreeMap, HashMap};
16use std::fmt;
17
18use anyhow::{Context, anyhow};
19use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
20use postgres_openssl::MakeTlsConnector;
21use risingwave_common::bail;
22use risingwave_common::catalog::{ColumnDesc, ColumnId};
23use risingwave_common::types::{DataType, ScalarImpl, StructType};
24use sea_schema::postgres::def::{ColumnType as SeaType, TableDef, TableInfo};
25use sea_schema::postgres::discovery::SchemaDiscovery;
26use sea_schema::sea_query::{Alias, IntoIden};
27use serde::Deserialize;
28use sqlx::postgres::{PgConnectOptions, PgSslMode};
29use sqlx::{PgPool, Row};
30use thiserror_ext::AsReport;
31use tokio_postgres::types::Kind as PgKind;
32use tokio_postgres::{Client as PgClient, NoTls};
33
34use super::TcpKeepaliveConfig;
35#[cfg(not(madsim))]
36use super::maybe_tls_connector::MaybeMakeTlsConnector;
37use crate::error::ConnectorResult;
38
39/// SQL query to discover primary key columns directly from PostgreSQL system tables.
40/// This bypasses querying `information_schema.table_constraints` to avoid permission issues.
41/// Match `pg_class` and `pg_namespace` by exact catalog names instead of casting a
42/// constructed string to `regclass`, as unquoted `regclass` input folds mixed-case
43/// table names to lower case.
44/// `pg_constraint.conkey` contains only the constrained columns, excluding non-key
45/// attributes from an `INCLUDE` clause, and is available on PostgreSQL 10.
46const DISCOVER_PRIMARY_KEY_QUERY: &str = r#"
47    SELECT a.attname as column_name
48    FROM pg_constraint con
49    JOIN pg_class c ON c.oid = con.conrelid
50    JOIN pg_namespace n ON n.oid = c.relnamespace
51    JOIN LATERAL unnest(con.conkey) WITH ORDINALITY AS key(attnum, ordinality)
52      ON true
53    JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = key.attnum
54    WHERE n.nspname = $1
55      AND c.relname = $2
56      AND con.contype = 'p'
57    ORDER BY key.ordinality
58"#;
59
60/// Discover pgvector columns with both `atttypmod` (dimension) and `format_type` text.
61/// `vector(n)` is stored as `atttypmod = n`, while dimension-less `vector` uses `-1`.
62/// We rely on this to keep user-defined type modifiers that are not preserved by sea-schema.
63const DISCOVER_PGVECTOR_COLUMNS_QUERY: &str = r#"
64    SELECT
65      a.attname as column_name,
66      a.atttypmod as atttypmod,
67      format_type(a.atttypid, a.atttypmod) as formatted_type
68    FROM pg_attribute a
69    JOIN pg_class c ON c.oid = a.attrelid
70    JOIN pg_namespace n ON n.oid = c.relnamespace
71    JOIN pg_type t ON t.oid = a.atttypid
72    WHERE n.nspname = $1
73      AND c.relname = $2
74      AND t.typname = 'vector'
75      AND a.attnum > 0
76      AND NOT a.attisdropped
77    ORDER BY a.attnum
78"#;
79
80const CHECK_TABLE_PRIVILEGE_QUERY: &str = r#"
81    SELECT
82      current_user::text AS user_name,
83      n.oid IS NOT NULL AS schema_exists,
84      c.oid IS NOT NULL AS table_exists,
85      COALESCE(has_schema_privilege(current_user, n.oid, 'USAGE'), false) AS has_schema_usage,
86      COALESCE(has_table_privilege(current_user, c.oid, $3), false) AS has_table_privilege,
87      COALESCE(has_any_column_privilege(current_user, c.oid, $3), false) AS has_any_column_privilege
88    FROM (SELECT 1) AS one
89    LEFT JOIN pg_namespace n ON n.nspname = $1
90    LEFT JOIN pg_class c ON c.relnamespace = n.oid
91      AND c.relname = $2
92      AND c.relkind IN ('r', 'p')
93    LIMIT 1
94"#;
95
96/// Canonical Postgres connection parameters shared across sink, source CDC, batch
97/// executor, and frontend `postgres_query` table function. Each caller constructs
98/// this from its own user-facing config struct before invoking the shared helpers
99/// like `create_pg_client` or `PostgresExternalTable::connect`.
100#[derive(Debug, Clone)]
101pub struct PgConnectionConfig {
102    pub host: String,
103    pub port: u16,
104    pub user: String,
105    pub password: String,
106    pub database: String,
107    pub ssl_mode: SslMode,
108    pub ssl_root_cert: Option<String>,
109}
110
111impl PgConnectionConfig {
112    fn to_sqlx_connect_options(&self) -> PgConnectOptions {
113        let mut options = PgConnectOptions::new()
114            .username(&self.user)
115            .password(&self.password)
116            .host(&self.host)
117            .port(self.port)
118            .database(&self.database)
119            .ssl_mode(match self.ssl_mode {
120                SslMode::Disabled => PgSslMode::Disable,
121                SslMode::Preferred => PgSslMode::Prefer,
122                SslMode::Required => PgSslMode::Require,
123                SslMode::VerifyCa => PgSslMode::VerifyCa,
124                SslMode::VerifyFull => PgSslMode::VerifyFull,
125            });
126
127        if matches!(self.ssl_mode, SslMode::VerifyCa | SslMode::VerifyFull)
128            && let Some(root_cert) = &self.ssl_root_cert
129        {
130            options = options.ssl_root_cert(root_cert.as_str());
131        }
132
133        options
134    }
135}
136
137pub fn pg_connection_config_from_properties(
138    props: &BTreeMap<String, String>,
139) -> ConnectorResult<PgConnectionConfig> {
140    Ok(PgConnectionConfig {
141        host: props
142            .get("hostname")
143            .context("missing `hostname` in postgres-cdc properties")?
144            .clone(),
145        port: {
146            let raw = props
147                .get("port")
148                .context("missing `port` in postgres-cdc properties")?;
149            raw.parse::<u16>()
150                .with_context(|| format!("invalid postgres port `{}`", raw))?
151        },
152        user: props
153            .get("username")
154            .context("missing `username` in postgres-cdc properties")?
155            .clone(),
156        password: props.get("password").cloned().unwrap_or_default(),
157        database: props
158            .get("database.name")
159            .context("missing `database.name` in postgres-cdc properties")?
160            .clone(),
161        ssl_mode: props
162            .get("ssl.mode")
163            .and_then(|v| v.parse::<SslMode>().ok())
164            .unwrap_or_default(),
165        ssl_root_cert: props.get("ssl.root.cert").cloned(),
166    })
167}
168
169pub async fn create_pg_client_from_properties(
170    props: &BTreeMap<String, String>,
171    tcp_keepalive: Option<TcpKeepaliveConfig>,
172) -> ConnectorResult<PgClient> {
173    let config = pg_connection_config_from_properties(props)?;
174    create_pg_client(&config, tcp_keepalive, None)
175        .await
176        .map_err(Into::into)
177}
178
179pub async fn discover_pgvector_dimensions(
180    client: &PgClient,
181    schema: &str,
182    table: &str,
183) -> ConnectorResult<HashMap<String, usize>> {
184    let rows = client
185        .query(DISCOVER_PGVECTOR_COLUMNS_QUERY, &[&schema, &table])
186        .await?;
187
188    let mut dims = HashMap::new();
189    for row in rows {
190        let col_name: String = row.get("column_name");
191        let atttypmod: i32 = row.get("atttypmod");
192        if atttypmod > 0
193            && let Ok(dim) = usize::try_from(atttypmod)
194        {
195            dims.insert(col_name, dim);
196        }
197    }
198    Ok(dims)
199}
200
201#[derive(Debug, Clone, PartialEq, Deserialize, Default)]
202#[serde(rename_all = "lowercase")]
203pub enum SslMode {
204    #[serde(alias = "disable")]
205    Disabled,
206    #[serde(alias = "prefer")]
207    #[default]
208    Preferred,
209    #[serde(alias = "require")]
210    Required,
211    /// verify that the server is trustworthy by checking the certificate chain
212    /// up to the root certificate stored on the client.
213    #[serde(alias = "verify-ca")]
214    VerifyCa,
215    /// Besides verify the certificate, will also verify that the serverhost name
216    /// matches the name stored in the server certificate.
217    #[serde(alias = "verify-full")]
218    VerifyFull,
219}
220
221pub struct PostgresExternalTable {
222    column_descs: Vec<ColumnDesc>,
223    pk_names: Vec<String>,
224}
225
226struct PostgresTablePrivilege {
227    user_name: String,
228    schema_exists: bool,
229    table_exists: bool,
230    has_schema_usage: bool,
231    has_table_privilege: bool,
232    has_any_column_privilege: bool,
233}
234
235impl PostgresExternalTable {
236    /// Discover primary key columns directly from PostgreSQL system tables.
237    /// This bypasses querying `information_schema.table_constraints` to avoid requiring table owner permissions.
238    async fn discover_primary_key(
239        connection: &PgPool,
240        schema_name: &str,
241        table_name: &str,
242    ) -> ConnectorResult<Vec<String>> {
243        let rows = sqlx::query(DISCOVER_PRIMARY_KEY_QUERY)
244            .bind(schema_name)
245            .bind(table_name)
246            .fetch_all(connection)
247            .await
248            .context("Failed to discover primary key columns")?;
249
250        let pk_columns = rows
251            .into_iter()
252            .map(|row| row.get::<String, _>("column_name"))
253            .collect();
254
255        Ok(pk_columns)
256    }
257
258    /// Discover schema with workaround for primary key discovery
259    /// This method uses direct PostgreSQL system table queries for primary keys
260    /// to avoid permission issues when querying `information_schema.table_constraints`
261    async fn discover_pk_and_full_columns(
262        config: &PgConnectionConfig,
263        schema: &str,
264        table: &str,
265        required_table_privilege: Option<&str>,
266    ) -> ConnectorResult<(Vec<sea_schema::postgres::def::ColumnInfo>, Vec<String>)> {
267        let options = config.to_sqlx_connect_options();
268        let connection = PgPool::connect_with(options).await?;
269
270        // Keep using sea-schema for column discovery, then run targeted access diagnostics below.
271        let schema_discovery = SchemaDiscovery::new(connection.clone(), schema);
272        let empty_map: HashMap<String, Vec<String>> = HashMap::new();
273        let columns = schema_discovery
274            .discover_columns(
275                Alias::new(schema).into_iden(),
276                Alias::new(table).into_iden(),
277                &empty_map,
278            )
279            .await?;
280
281        let pgvector_columns = sqlx::query(DISCOVER_PGVECTOR_COLUMNS_QUERY)
282            .bind(schema)
283            .bind(table)
284            .fetch_all(&connection)
285            .await
286            .context("Failed to discover PostgreSQL pgvector columns")?;
287        let formatted_type_by_column: HashMap<String, String> = pgvector_columns
288            .into_iter()
289            .map(|row| {
290                (
291                    row.get::<String, _>("column_name"),
292                    row.get::<String, _>("formatted_type"),
293                )
294            })
295            .collect();
296
297        // sea-schema reports pgvector as `Unknown("vector")` and drops the dimension.
298        // Patch it with PostgreSQL's formatted type text so we can derive vector(n).
299        let mut columns = columns;
300        if let Some(privilege) = required_table_privilege {
301            Self::ensure_table_privilege(&connection, schema, table, privilege).await?;
302        }
303
304        for col in &mut columns {
305            if let SeaType::Unknown(name) = &col.col_type
306                && name.eq_ignore_ascii_case("vector")
307                && let Some(formatted_type) = formatted_type_by_column.get(&col.name)
308            {
309                col.col_type = SeaType::Unknown(formatted_type.clone());
310            }
311        }
312
313        // Use direct system table query for primary key discovery
314        let pk_columns = Self::discover_primary_key(&connection, schema, table).await?;
315
316        Ok((columns, pk_columns))
317    }
318
319    async fn ensure_table_privilege(
320        connection: &PgPool,
321        schema: &str,
322        table: &str,
323        required_privilege: &str,
324    ) -> ConnectorResult<()> {
325        let row = sqlx::query(CHECK_TABLE_PRIVILEGE_QUERY)
326            .bind(schema)
327            .bind(table)
328            .bind(required_privilege)
329            .fetch_one(connection)
330            .await
331            .context("Failed to check PostgreSQL table privileges")?;
332
333        let privilege_status = PostgresTablePrivilege {
334            user_name: row.get("user_name"),
335            schema_exists: row.get("schema_exists"),
336            table_exists: row.get("table_exists"),
337            has_schema_usage: row.get("has_schema_usage"),
338            has_table_privilege: row.get("has_table_privilege"),
339            has_any_column_privilege: row.get("has_any_column_privilege"),
340        };
341
342        if !privilege_status.schema_exists {
343            return Err(anyhow!("PostgreSQL schema `{schema}` does not exist").into());
344        }
345
346        if !privilege_status.table_exists {
347            return Err(anyhow!("PostgreSQL table `{schema}`.`{table}` does not exist").into());
348        }
349
350        if !privilege_status.has_schema_usage {
351            return Err(anyhow!(
352                "PostgreSQL table {} exists, but the connection user `{}` does not have USAGE privilege on schema `{}`. Grant privileges on the upstream PostgreSQL database: {}",
353                format_pg_table_name(schema, table),
354                privilege_status.user_name,
355                schema,
356                format_grant_usage(schema, &privilege_status.user_name),
357            )
358            .into());
359        }
360
361        if !privilege_status.has_table_privilege {
362            let column_privilege_msg = if privilege_status.has_any_column_privilege {
363                " The user has column-level privilege on at least one column, but RisingWave requires table-level privilege for CDC schema discovery and snapshot reads."
364            } else {
365                ""
366            };
367            return Err(anyhow!(
368                "PostgreSQL table {} exists, but the connection user `{}` does not have {} privilege on it.{} Grant privileges on the upstream PostgreSQL database: {}",
369                format_pg_table_name(schema, table),
370                privilege_status.user_name,
371                required_privilege,
372                column_privilege_msg,
373                format_required_table_grants(
374                    schema,
375                    table,
376                    &privilege_status.user_name,
377                    required_privilege
378                ),
379            )
380            .into());
381        }
382
383        Ok(())
384    }
385
386    async fn discover_schema(
387        config: &PgConnectionConfig,
388        schema: &str,
389        table: &str,
390    ) -> ConnectorResult<TableDef> {
391        let options = config.to_sqlx_connect_options();
392        let connection = PgPool::connect_with(options).await?;
393        let schema_discovery = SchemaDiscovery::new(connection, schema);
394        // fetch column schema and primary key
395        let empty_map = HashMap::new();
396        let table_schema = schema_discovery
397            .discover_table(
398                TableInfo {
399                    name: table.to_owned(),
400                    of_type: None,
401                },
402                &empty_map,
403            )
404            .await?;
405        Ok(table_schema)
406    }
407
408    pub async fn connect(
409        config: &PgConnectionConfig,
410        schema: &str,
411        table: &str,
412        is_append_only: bool,
413        required_table_privilege: Option<&str>,
414    ) -> ConnectorResult<Self> {
415        tracing::debug!("connect to postgres external table");
416
417        let (columns, pk_names) =
418            Self::discover_pk_and_full_columns(config, schema, table, required_table_privilege)
419                .await?;
420
421        let mut column_descs = vec![];
422        for col in &columns {
423            let rw_data_type = sea_type_to_rw_type(&col.col_type)?;
424            let column_desc = if let Some(ref default_expr) = col.default {
425                // parse the value of "column_default" field in information_schema.columns,
426                // non number data type will be stored as "'value'::type"
427                let val_text = default_expr
428                    .0
429                    .split("::")
430                    .map(|s| s.trim_matches('\''))
431                    .next()
432                    .expect("default value expression");
433
434                match ScalarImpl::from_text(val_text, &rw_data_type) {
435                    Ok(scalar) => ColumnDesc::named_with_default_value(
436                        col.name.clone(),
437                        ColumnId::placeholder(),
438                        rw_data_type.clone(),
439                        Some(scalar),
440                    ),
441                    Err(err) => {
442                        tracing::warn!(
443                            error=%err.as_report(),
444                            "failed to parse the PostgreSQL default value expression; only constants are supported",
445                        );
446                        ColumnDesc::named(col.name.clone(), ColumnId::placeholder(), rw_data_type)
447                    }
448                }
449            } else {
450                ColumnDesc::named(col.name.clone(), ColumnId::placeholder(), rw_data_type)
451            };
452            column_descs.push(column_desc);
453        }
454
455        // Check primary key existence using the directly discovered pk_names
456        if !is_append_only && pk_names.is_empty() {
457            return Err(anyhow!(
458                "Postgres table should define the primary key for non-append-only tables"
459            )
460            .into());
461        }
462
463        Ok(Self {
464            column_descs,
465            pk_names,
466        })
467    }
468
469    // return the mapping from column name to pg type, the pg type is used for writing data to postgres
470    pub async fn type_mapping(
471        config: &PgConnectionConfig,
472        schema: &str,
473        table: &str,
474        is_append_only: bool,
475    ) -> ConnectorResult<HashMap<String, tokio_postgres::types::Type>> {
476        tracing::debug!("connect to postgres external table to get type mapping");
477        let table_schema = Self::discover_schema(config, schema, table).await?;
478        let mut column_name_to_pg_type = HashMap::new();
479        for col in &table_schema.columns {
480            let pg_type = sea_type_to_pg_type(&col.col_type)?;
481            column_name_to_pg_type.insert(col.name.clone(), pg_type);
482        }
483        if !is_append_only && table_schema.primary_key_constraints.is_empty() {
484            return Err(anyhow!(
485                "Postgres table should define the primary key for non-append-only tables"
486            )
487            .into());
488        }
489        Ok(column_name_to_pg_type)
490    }
491
492    pub fn column_descs(&self) -> &Vec<ColumnDesc> {
493        &self.column_descs
494    }
495
496    pub fn pk_names(&self) -> &Vec<String> {
497        &self.pk_names
498    }
499}
500
501fn format_pg_table_name(schema: &str, table: &str) -> String {
502    format!(
503        "{}.{}",
504        quote_pg_identifier(schema),
505        quote_pg_identifier(table)
506    )
507}
508
509fn format_grant_usage(schema: &str, user_name: &str) -> String {
510    format!(
511        "GRANT USAGE ON SCHEMA {} TO {};",
512        quote_pg_identifier(schema),
513        quote_pg_identifier(user_name)
514    )
515}
516
517fn format_grant_table_privilege(
518    schema: &str,
519    table: &str,
520    user_name: &str,
521    privilege: &str,
522) -> String {
523    format!(
524        "GRANT {} ON TABLE {} TO {};",
525        privilege,
526        format_pg_table_name(schema, table),
527        quote_pg_identifier(user_name)
528    )
529}
530
531fn format_required_table_grants(
532    schema: &str,
533    table: &str,
534    user_name: &str,
535    privilege: &str,
536) -> String {
537    format!(
538        "{} {}",
539        format_grant_usage(schema, user_name),
540        format_grant_table_privilege(schema, table, user_name, privilege)
541    )
542}
543
544fn quote_pg_identifier(identifier: &str) -> String {
545    format!("\"{}\"", identifier.replace('"', "\"\""))
546}
547
548impl fmt::Display for SslMode {
549    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550        f.write_str(match self {
551            SslMode::Disabled => "disabled",
552            SslMode::Preferred => "preferred",
553            SslMode::Required => "required",
554            SslMode::VerifyCa => "verify-ca",
555            SslMode::VerifyFull => "verify-full",
556        })
557    }
558}
559
560impl std::str::FromStr for SslMode {
561    type Err = serde_json::Error;
562
563    fn from_str(s: &str) -> Result<Self, Self::Err> {
564        serde_json::from_value(serde_json::Value::String(s.to_owned()))
565    }
566}
567
568pub async fn create_pg_client(
569    config: &PgConnectionConfig,
570    tcp_keepalive: Option<TcpKeepaliveConfig>,
571    application_name: Option<&str>,
572) -> anyhow::Result<PgClient> {
573    let mut pg_config = tokio_postgres::Config::new();
574    pg_config
575        .user(&config.user)
576        .password(&config.password)
577        .host(&config.host)
578        .port(config.port)
579        .dbname(&config.database);
580    if let Some(application_name) = application_name {
581        pg_config.application_name(application_name);
582    }
583
584    // Configure TCP keepalive if provided
585    if let Some(keepalive) = tcp_keepalive {
586        pg_config.keepalives(true);
587        pg_config.keepalives_idle(std::time::Duration::from_secs(
588            keepalive.tcp_keepalive_idle as u64,
589        ));
590        #[cfg(not(target_os = "windows"))]
591        {
592            pg_config.keepalives_interval(std::time::Duration::from_secs(
593                keepalive.tcp_keepalive_interval as u64,
594            ));
595            pg_config.keepalives_retries(keepalive.tcp_keepalive_count);
596        }
597        tracing::info!(
598            "TCP keepalive enabled: idle={}s, interval={}s, retries={}",
599            keepalive.tcp_keepalive_idle,
600            keepalive.tcp_keepalive_interval,
601            keepalive.tcp_keepalive_count
602        );
603    }
604
605    let verify_hostname = matches!(config.ssl_mode, SslMode::VerifyFull);
606
607    #[cfg(not(madsim))]
608    let connector = match config.ssl_mode {
609        SslMode::Disabled => {
610            pg_config.ssl_mode(tokio_postgres::config::SslMode::Disable);
611            MaybeMakeTlsConnector::NoTls(NoTls)
612        }
613        SslMode::Preferred => {
614            pg_config.ssl_mode(tokio_postgres::config::SslMode::Prefer);
615            match SslConnector::builder(SslMethod::tls()) {
616                Ok(mut builder) => {
617                    // disable certificate verification for `prefer`
618                    builder.set_verify(SslVerifyMode::NONE);
619                    MaybeMakeTlsConnector::Tls(MakeTlsConnector::new(builder.build()))
620                }
621                Err(e) => {
622                    tracing::warn!(error = %e.as_report(), "SSL connector error");
623                    MaybeMakeTlsConnector::NoTls(NoTls)
624                }
625            }
626        }
627        SslMode::Required => {
628            pg_config.ssl_mode(tokio_postgres::config::SslMode::Require);
629            let mut builder = SslConnector::builder(SslMethod::tls())?;
630            // disable certificate verification for `require`
631            builder.set_verify(SslVerifyMode::NONE);
632            MaybeMakeTlsConnector::Tls(MakeTlsConnector::new(builder.build()))
633        }
634
635        SslMode::VerifyCa | SslMode::VerifyFull => {
636            pg_config.ssl_mode(tokio_postgres::config::SslMode::Require);
637            let mut builder = SslConnector::builder(SslMethod::tls())?;
638            if let Some(ssl_root_cert) = &config.ssl_root_cert {
639                builder.set_ca_file(ssl_root_cert).map_err(|e| {
640                    anyhow!(format!("bad ssl root cert error: {}", e.to_report_string()))
641                })?;
642            }
643            let mut connector = MakeTlsConnector::new(builder.build());
644            if !verify_hostname {
645                connector.set_callback(|c, _| {
646                    c.set_verify_hostname(false);
647                    Ok(())
648                });
649            }
650            MaybeMakeTlsConnector::Tls(connector)
651        }
652    };
653    #[cfg(madsim)]
654    let connector = NoTls;
655
656    let (client, connection) = pg_config.connect(connector).await?;
657
658    tokio::spawn(async move {
659        if let Err(e) = connection.await {
660            tracing::error!(error = %e.as_report(), "postgres connection error");
661        }
662    });
663
664    Ok(client)
665}
666
667pub fn postgres_point_type() -> DataType {
668    DataType::Struct(StructType::new(vec![
669        ("x", DataType::Float64),
670        ("y", DataType::Float64),
671    ]))
672}
673
674// Used for both source and sink connector
675pub fn sea_type_to_rw_type(col_type: &SeaType) -> ConnectorResult<DataType> {
676    let dtype = match col_type {
677        SeaType::SmallInt | SeaType::SmallSerial => DataType::Int16,
678        SeaType::Integer | SeaType::Serial => DataType::Int32,
679        SeaType::BigInt | SeaType::BigSerial => DataType::Int64,
680        SeaType::Money | SeaType::Decimal(_) | SeaType::Numeric(_) => DataType::Decimal,
681        SeaType::Real => DataType::Float32,
682        SeaType::DoublePrecision => DataType::Float64,
683        SeaType::Varchar(_) | SeaType::Char(_) | SeaType::Text => DataType::Varchar,
684        SeaType::Bytea => DataType::Bytea,
685        SeaType::Timestamp(_) => DataType::Timestamp,
686        SeaType::TimestampWithTimeZone(_) => DataType::Timestamptz,
687        SeaType::Date => DataType::Date,
688        SeaType::Time(_) | SeaType::TimeWithTimeZone(_) => DataType::Time,
689        SeaType::Interval(_) => DataType::Interval,
690        SeaType::Boolean => DataType::Boolean,
691        SeaType::Point => postgres_point_type(),
692        SeaType::Uuid => DataType::Varchar,
693        SeaType::Xml => DataType::Varchar,
694        SeaType::Json => DataType::Jsonb,
695        SeaType::JsonBinary => DataType::Jsonb,
696        SeaType::Array(def) => {
697            let item_type = match def.col_type.as_ref() {
698                Some(ty) => sea_type_to_rw_type(ty.as_ref())?,
699                None => {
700                    return Err(anyhow!("ARRAY type missing element type").into());
701                }
702            };
703
704            DataType::list(item_type)
705        }
706        SeaType::PgLsn => DataType::Int64,
707        SeaType::Cidr
708        | SeaType::Inet
709        | SeaType::MacAddr
710        | SeaType::MacAddr8
711        | SeaType::Int4Range
712        | SeaType::Int8Range
713        | SeaType::NumRange
714        | SeaType::TsRange
715        | SeaType::TsTzRange
716        | SeaType::DateRange
717        | SeaType::Enum(_) => DataType::Varchar,
718        SeaType::Line
719        | SeaType::Lseg
720        | SeaType::Box
721        | SeaType::Path
722        | SeaType::Polygon
723        | SeaType::Circle
724        | SeaType::Bit(_)
725        | SeaType::VarBit(_)
726        | SeaType::TsVector
727        | SeaType::TsQuery => {
728            bail!("{:?} data type is not supported", col_type);
729        }
730        SeaType::Unknown(name) => {
731            if let Some(dim) = parse_pgvector_dimension(name)? {
732                DataType::Vector(dim)
733            } else if matches!(name.to_ascii_lowercase().as_str(), "geometry" | "geography") {
734                DataType::Bytea
735            } else {
736                // NOTES: user-defined enum type is classified as `Unknown`
737                tracing::warn!("unknown PostgreSQL data type `{name}`; mapping it to varchar");
738                DataType::Varchar
739            }
740        }
741    };
742
743    Ok(dtype)
744}
745
746fn parse_pgvector_dimension(type_name: &str) -> ConnectorResult<Option<usize>> {
747    let normalized = type_name.trim().to_ascii_lowercase();
748    if normalized == "vector" {
749        bail!("pgvector type `vector` is missing dimension, expected `vector(n)`")
750    }
751    if !normalized.starts_with("vector(") || !normalized.ends_with(')') {
752        return Ok(None);
753    }
754
755    let dim_text = normalized
756        .trim_start_matches("vector(")
757        .trim_end_matches(')')
758        .trim();
759    let dim = dim_text
760        .parse::<usize>()
761        .map_err(|_| anyhow!("invalid pgvector dimension in type `{type_name}`"))?;
762
763    if !(1..=DataType::VEC_MAX_SIZE).contains(&dim) {
764        bail!(
765            "pgvector dimension out of range in type `{}`: expect 1..={}",
766            type_name,
767            DataType::VEC_MAX_SIZE
768        );
769    }
770
771    Ok(Some(dim))
772}
773
774// Used for sink connector
775// We use `sea-schema` for table schema discovery.
776// So we have to map `sea-schema` pg types
777// to `tokio-postgres` pg types (which we use for query binding).
778fn sea_type_to_pg_type(sea_type: &SeaType) -> ConnectorResult<tokio_postgres::types::Type> {
779    use tokio_postgres::types::Type as PgType;
780    match sea_type {
781        SeaType::SmallInt => Ok(PgType::INT2),
782        SeaType::Integer => Ok(PgType::INT4),
783        SeaType::BigInt => Ok(PgType::INT8),
784        SeaType::Decimal(_) => Ok(PgType::NUMERIC),
785        SeaType::Numeric(_) => Ok(PgType::NUMERIC),
786        SeaType::Real => Ok(PgType::FLOAT4),
787        SeaType::DoublePrecision => Ok(PgType::FLOAT8),
788        SeaType::Varchar(_) => Ok(PgType::VARCHAR),
789        SeaType::Char(_) => Ok(PgType::CHAR),
790        SeaType::Text => Ok(PgType::TEXT),
791        SeaType::Bytea => Ok(PgType::BYTEA),
792        SeaType::Timestamp(_) => Ok(PgType::TIMESTAMP),
793        SeaType::TimestampWithTimeZone(_) => Ok(PgType::TIMESTAMPTZ),
794        SeaType::Date => Ok(PgType::DATE),
795        SeaType::Time(_) => Ok(PgType::TIME),
796        SeaType::TimeWithTimeZone(_) => Ok(PgType::TIMETZ),
797        SeaType::Interval(_) => Ok(PgType::INTERVAL),
798        SeaType::Boolean => Ok(PgType::BOOL),
799        SeaType::Point => Ok(PgType::POINT),
800        SeaType::Uuid => Ok(PgType::UUID),
801        SeaType::Json => Ok(PgType::JSON),
802        SeaType::JsonBinary => Ok(PgType::JSONB),
803        SeaType::Array(t) => {
804            let Some(t) = t.col_type.as_ref() else {
805                bail!("missing array type")
806            };
807            match t.as_ref() {
808                // RW only supports 1 level of nesting.
809                SeaType::SmallInt => Ok(PgType::INT2_ARRAY),
810                SeaType::Integer => Ok(PgType::INT4_ARRAY),
811                SeaType::BigInt => Ok(PgType::INT8_ARRAY),
812                SeaType::Decimal(_) => Ok(PgType::NUMERIC_ARRAY),
813                SeaType::Numeric(_) => Ok(PgType::NUMERIC_ARRAY),
814                SeaType::Real => Ok(PgType::FLOAT4_ARRAY),
815                SeaType::DoublePrecision => Ok(PgType::FLOAT8_ARRAY),
816                SeaType::Varchar(_) => Ok(PgType::VARCHAR_ARRAY),
817                SeaType::Char(_) => Ok(PgType::CHAR_ARRAY),
818                SeaType::Text => Ok(PgType::TEXT_ARRAY),
819                SeaType::Bytea => Ok(PgType::BYTEA_ARRAY),
820                SeaType::Timestamp(_) => Ok(PgType::TIMESTAMP_ARRAY),
821                SeaType::TimestampWithTimeZone(_) => Ok(PgType::TIMESTAMPTZ_ARRAY),
822                SeaType::Date => Ok(PgType::DATE_ARRAY),
823                SeaType::Time(_) => Ok(PgType::TIME_ARRAY),
824                SeaType::TimeWithTimeZone(_) => Ok(PgType::TIMETZ_ARRAY),
825                SeaType::Interval(_) => Ok(PgType::INTERVAL_ARRAY),
826                SeaType::Boolean => Ok(PgType::BOOL_ARRAY),
827                SeaType::Point => Ok(PgType::POINT_ARRAY),
828                SeaType::Uuid => Ok(PgType::UUID_ARRAY),
829                SeaType::Json => Ok(PgType::JSON_ARRAY),
830                SeaType::JsonBinary => Ok(PgType::JSONB_ARRAY),
831                SeaType::Array(_) => bail!("nested array type is not supported"),
832                SeaType::Unknown(name) => {
833                    // Treat as enum type
834                    Ok(PgType::new(
835                        name.clone(),
836                        0,
837                        PgKind::Array(PgType::new(
838                            name.clone(),
839                            0,
840                            PgKind::Enum(vec![]),
841                            "".into(),
842                        )),
843                        "".into(),
844                    ))
845                }
846                _ => bail!("unsupported array type: {:?}", t),
847            }
848        }
849        SeaType::Unknown(name) => {
850            // Treat as enum type
851            Ok(PgType::new(
852                name.clone(),
853                0,
854                PgKind::Enum(vec![]),
855                "".into(),
856            ))
857        }
858        _ => bail!("unsupported type: {:?}", sea_type),
859    }
860}
861
862#[cfg(test)]
863mod tests {
864    use super::{
865        format_grant_table_privilege, format_grant_usage, format_pg_table_name,
866        format_required_table_grants, parse_pgvector_dimension,
867    };
868
869    #[test]
870    fn test_parse_pgvector_dimension() {
871        assert_eq!(parse_pgvector_dimension("vector(3)").unwrap(), Some(3));
872        assert_eq!(parse_pgvector_dimension("VECTOR(768)").unwrap(), Some(768));
873        assert_eq!(parse_pgvector_dimension("varchar").unwrap(), None);
874    }
875
876    #[test]
877    fn test_parse_pgvector_dimension_requires_size() {
878        let err = parse_pgvector_dimension("vector").unwrap_err();
879        assert!(err.to_string().contains("missing dimension"));
880    }
881
882    #[test]
883    fn test_format_postgres_privilege_grants_quote_identifiers() {
884        assert_eq!(
885            format_pg_table_name("public", "GlobalBrandContentAnalysis"),
886            r#""public"."GlobalBrandContentAnalysis""#
887        );
888        assert_eq!(
889            format_grant_usage("tenant schema", r#"cdc"user"#),
890            r#"GRANT USAGE ON SCHEMA "tenant schema" TO "cdc""user";"#
891        );
892        assert_eq!(
893            format_grant_table_privilege("tenant schema", "Orders", r#"cdc"user"#, "SELECT"),
894            r#"GRANT SELECT ON TABLE "tenant schema"."Orders" TO "cdc""user";"#
895        );
896        assert_eq!(
897            format_required_table_grants("tenant schema", "Orders", r#"cdc"user"#, "SELECT"),
898            r#"GRANT USAGE ON SCHEMA "tenant schema" TO "cdc""user"; GRANT SELECT ON TABLE "tenant schema"."Orders" TO "cdc""user";"#
899        );
900    }
901}