Skip to main content

sea_orm/driver/
sqlx_postgres.rs

1use futures_util::lock::Mutex;
2use log::LevelFilter;
3use sea_query::Values;
4use std::{fmt::Write, future::Future, pin::Pin, sync::Arc};
5
6use sqlx::{
7    Connection, Executor, PgPool, Postgres,
8    pool::PoolConnection,
9    postgres::{PgConnectOptions, PgQueryResult, PgRow},
10};
11
12use sea_query_sqlx::SqlxValues;
13use tracing::instrument;
14
15use crate::{
16    AccessMode, ConnectOptions, DatabaseConnection, DatabaseConnectionType, DatabaseTransaction,
17    IsolationLevel, QueryStream, Statement, TransactionError, debug_print, error::*, executor::*,
18};
19
20use super::sqlx_common::*;
21
22/// Defines the [sqlx::postgres] connector
23#[derive(Debug)]
24pub struct SqlxPostgresConnector;
25
26/// Defines a sqlx PostgreSQL pool
27#[derive(Clone)]
28pub struct SqlxPostgresPoolConnection {
29    pub(crate) pool: PgPool,
30    metric_callback: Option<crate::metric::Callback>,
31}
32
33impl std::fmt::Debug for SqlxPostgresPoolConnection {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        write!(f, "SqlxPostgresPoolConnection {{ pool: {:?} }}", self.pool)
36    }
37}
38
39impl From<PgPool> for SqlxPostgresPoolConnection {
40    fn from(pool: PgPool) -> Self {
41        SqlxPostgresPoolConnection {
42            pool,
43            metric_callback: None,
44        }
45    }
46}
47
48impl From<PgPool> for DatabaseConnection {
49    fn from(pool: PgPool) -> Self {
50        DatabaseConnectionType::SqlxPostgresPoolConnection(pool.into()).into()
51    }
52}
53
54impl SqlxPostgresConnector {
55    /// Check if the URI provided corresponds to `postgres://` for a PostgreSQL database
56    pub fn accepts(string: &str) -> bool {
57        string.starts_with("postgres://") && string.parse::<PgConnectOptions>().is_ok()
58    }
59
60    /// Add configuration options for the PostgreSQL database
61    #[instrument(level = "trace")]
62    pub async fn connect(options: ConnectOptions) -> Result<DatabaseConnection, DbErr> {
63        let mut sqlx_opts = options
64            .url
65            .parse::<PgConnectOptions>()
66            .map_err(sqlx_error_to_conn_err)?;
67        use sqlx::ConnectOptions;
68        if !options.sqlx_logging {
69            sqlx_opts = sqlx_opts.disable_statement_logging();
70        } else {
71            sqlx_opts = sqlx_opts.log_statements(options.sqlx_logging_level);
72            if options.sqlx_slow_statements_logging_level != LevelFilter::Off {
73                sqlx_opts = sqlx_opts.log_slow_statements(
74                    options.sqlx_slow_statements_logging_level,
75                    options.sqlx_slow_statements_logging_threshold,
76                );
77            }
78        }
79
80        if let Some(application_name) = &options.application_name {
81            sqlx_opts = sqlx_opts.application_name(application_name);
82        }
83
84        if let Some(f) = &options.pg_opts_fn {
85            sqlx_opts = f(sqlx_opts);
86        }
87
88        let set_search_path_sql = options.schema_search_path.as_ref().map(|schema| {
89            let mut string = "SET search_path = ".to_owned();
90            if schema.starts_with('"') {
91                write!(&mut string, "{schema}").expect("Infallible");
92            } else {
93                for (i, schema) in schema.split(',').enumerate() {
94                    if i > 0 {
95                        write!(&mut string, ",").expect("Infallible");
96                    }
97                    if schema.starts_with('"') {
98                        write!(&mut string, "{schema}").expect("Infallible");
99                    } else {
100                        write!(&mut string, "\"{schema}\"").expect("Infallible");
101                    }
102                }
103            }
104            string
105        });
106
107        let lazy = options.connect_lazy;
108        let after_connect = options.after_connect.clone();
109        let mut pool_options = options.sqlx_pool_options();
110
111        if let Some(sql) = set_search_path_sql {
112            pool_options = pool_options.after_connect(move |conn, _| {
113                let sql = sql.clone();
114                Box::pin(async move {
115                    sqlx::Executor::execute(conn, sql.as_str())
116                        .await
117                        .map(|_| ())
118                })
119            });
120        }
121
122        let pool = if lazy {
123            pool_options.connect_lazy_with(sqlx_opts)
124        } else {
125            pool_options
126                .connect_with(sqlx_opts)
127                .await
128                .map_err(sqlx_error_to_conn_err)?
129        };
130
131        let conn: DatabaseConnection =
132            DatabaseConnectionType::SqlxPostgresPoolConnection(SqlxPostgresPoolConnection {
133                pool,
134                metric_callback: None,
135            })
136            .into();
137
138        if let Some(cb) = after_connect {
139            cb(conn.clone()).await?;
140        }
141
142        Ok(conn)
143    }
144}
145
146impl SqlxPostgresConnector {
147    /// Instantiate a sqlx pool connection to a [DatabaseConnection]
148    pub fn from_sqlx_postgres_pool(pool: PgPool) -> DatabaseConnection {
149        DatabaseConnectionType::SqlxPostgresPoolConnection(SqlxPostgresPoolConnection {
150            pool,
151            metric_callback: None,
152        })
153        .into()
154    }
155}
156
157impl SqlxPostgresPoolConnection {
158    /// Execute a [Statement] on a PostgreSQL backend
159    #[instrument(level = "trace")]
160    pub async fn execute(&self, stmt: Statement) -> Result<ExecResult, DbErr> {
161        debug_print!("{}", stmt);
162
163        let query = sqlx_query(&stmt);
164        let mut conn = self.pool.acquire().await.map_err(sqlx_conn_acquire_err)?;
165        crate::metric::metric!(self.metric_callback, &stmt, {
166            match query.execute(&mut *conn).await {
167                Ok(res) => Ok(res.into()),
168                Err(err) => Err(sqlx_error_to_exec_err(err)),
169            }
170        })
171    }
172
173    /// Execute an unprepared SQL statement on a PostgreSQL backend
174    #[instrument(level = "trace")]
175    pub async fn execute_unprepared(&self, sql: &str) -> Result<ExecResult, DbErr> {
176        debug_print!("{}", sql);
177
178        let conn = &mut self.pool.acquire().await.map_err(sqlx_conn_acquire_err)?;
179        match conn.execute(sql).await {
180            Ok(res) => Ok(res.into()),
181            Err(err) => Err(sqlx_error_to_exec_err(err)),
182        }
183    }
184
185    /// Get one result from a SQL query. Returns [Option::None] if no match was found
186    #[instrument(level = "trace")]
187    pub async fn query_one(&self, stmt: Statement) -> Result<Option<QueryResult>, DbErr> {
188        debug_print!("{}", stmt);
189
190        let query = sqlx_query(&stmt);
191        let mut conn = self.pool.acquire().await.map_err(sqlx_conn_acquire_err)?;
192        crate::metric::metric!(self.metric_callback, &stmt, {
193            match query.fetch_one(&mut *conn).await {
194                Ok(row) => Ok(Some(row.into())),
195                Err(err) => match err {
196                    sqlx::Error::RowNotFound => Ok(None),
197                    _ => Err(sqlx_error_to_query_err(err)),
198                },
199            }
200        })
201    }
202
203    /// Get the results of a query returning them as a Vec<[QueryResult]>
204    #[instrument(level = "trace")]
205    pub async fn query_all(&self, stmt: Statement) -> Result<Vec<QueryResult>, DbErr> {
206        debug_print!("{}", stmt);
207
208        let query = sqlx_query(&stmt);
209        let mut conn = self.pool.acquire().await.map_err(sqlx_conn_acquire_err)?;
210        crate::metric::metric!(self.metric_callback, &stmt, {
211            match query.fetch_all(&mut *conn).await {
212                Ok(rows) => Ok(rows.into_iter().map(|r| r.into()).collect()),
213                Err(err) => Err(sqlx_error_to_query_err(err)),
214            }
215        })
216    }
217
218    /// Stream the results of executing a SQL query
219    #[instrument(level = "trace")]
220    pub async fn stream(&self, stmt: Statement) -> Result<QueryStream, DbErr> {
221        debug_print!("{}", stmt);
222
223        let conn = self.pool.acquire().await.map_err(sqlx_conn_acquire_err)?;
224        Ok(QueryStream::from((
225            conn,
226            stmt,
227            self.metric_callback.clone(),
228        )))
229    }
230
231    /// Bundle a set of SQL statements that execute together.
232    #[instrument(level = "trace")]
233    pub async fn begin(
234        &self,
235        isolation_level: Option<IsolationLevel>,
236        access_mode: Option<AccessMode>,
237    ) -> Result<DatabaseTransaction, DbErr> {
238        let conn = self.pool.acquire().await.map_err(sqlx_conn_acquire_err)?;
239        DatabaseTransaction::new_postgres(
240            conn,
241            self.metric_callback.clone(),
242            isolation_level,
243            access_mode,
244        )
245        .await
246    }
247
248    /// Create a PostgreSQL transaction
249    #[instrument(level = "trace", skip(callback))]
250    pub async fn transaction<F, T, E>(
251        &self,
252        callback: F,
253        isolation_level: Option<IsolationLevel>,
254        access_mode: Option<AccessMode>,
255    ) -> Result<T, TransactionError<E>>
256    where
257        F: for<'b> FnOnce(
258                &'b DatabaseTransaction,
259            ) -> Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'b>>
260            + Send,
261        T: Send,
262        E: std::fmt::Display + std::fmt::Debug + Send,
263    {
264        let conn = self.pool.acquire().await.map_err(sqlx_conn_acquire_err)?;
265        let transaction = DatabaseTransaction::new_postgres(
266            conn,
267            self.metric_callback.clone(),
268            isolation_level,
269            access_mode,
270        )
271        .await
272        .map_err(|e| TransactionError::Connection(e))?;
273        transaction.run(callback).await
274    }
275
276    pub(crate) fn set_metric_callback<F>(&mut self, callback: F)
277    where
278        F: Fn(&crate::metric::Info<'_>) + Send + Sync + 'static,
279    {
280        self.metric_callback = Some(Arc::new(callback));
281    }
282
283    /// Checks if a connection to the database is still valid.
284    pub async fn ping(&self) -> Result<(), DbErr> {
285        let conn = &mut self.pool.acquire().await.map_err(sqlx_conn_acquire_err)?;
286        match conn.ping().await {
287            Ok(_) => Ok(()),
288            Err(err) => Err(sqlx_error_to_conn_err(err)),
289        }
290    }
291
292    /// Explicitly close the Postgres connection.
293    /// See [`Self::close_by_ref`] for usage with references.
294    pub async fn close(self) -> Result<(), DbErr> {
295        self.close_by_ref().await
296    }
297
298    /// Explicitly close the Postgres connection
299    pub async fn close_by_ref(&self) -> Result<(), DbErr> {
300        self.pool.close().await;
301        Ok(())
302    }
303}
304
305impl From<PgRow> for QueryResult {
306    fn from(row: PgRow) -> QueryResult {
307        QueryResult {
308            row: QueryResultRow::SqlxPostgres(row),
309        }
310    }
311}
312
313impl From<PgQueryResult> for ExecResult {
314    fn from(result: PgQueryResult) -> ExecResult {
315        ExecResult {
316            result: ExecResultHolder::SqlxPostgres(result),
317        }
318    }
319}
320
321pub(crate) fn sqlx_query(stmt: &Statement) -> sqlx::query::Query<'_, Postgres, SqlxValues> {
322    let values = stmt
323        .values
324        .as_ref()
325        .map_or(Values(Vec::new()), |values| values.clone());
326    sqlx::query_with(&stmt.sql, SqlxValues(values))
327}
328
329pub(crate) async fn set_transaction_config(
330    conn: &mut PoolConnection<Postgres>,
331    isolation_level: Option<IsolationLevel>,
332    access_mode: Option<AccessMode>,
333) -> Result<(), DbErr> {
334    let mut settings = Vec::new();
335
336    if let Some(isolation_level) = isolation_level {
337        settings.push(format!("ISOLATION LEVEL {isolation_level}"));
338    }
339
340    if let Some(access_mode) = access_mode {
341        settings.push(access_mode.to_string());
342    }
343
344    if !settings.is_empty() {
345        let sql = format!("SET TRANSACTION {}", settings.join(" "));
346        sqlx::query(&sql)
347            .execute(&mut **conn)
348            .await
349            .map_err(sqlx_error_to_exec_err)?;
350    }
351    Ok(())
352}
353
354impl
355    From<(
356        PoolConnection<sqlx::Postgres>,
357        Statement,
358        Option<crate::metric::Callback>,
359    )> for crate::QueryStream
360{
361    fn from(
362        (conn, stmt, metric_callback): (
363            PoolConnection<sqlx::Postgres>,
364            Statement,
365            Option<crate::metric::Callback>,
366        ),
367    ) -> Self {
368        crate::QueryStream::build(
369            stmt,
370            crate::InnerConnection::Postgres(conn),
371            metric_callback,
372        )
373    }
374}
375
376impl crate::DatabaseTransaction {
377    pub(crate) async fn new_postgres(
378        inner: PoolConnection<sqlx::Postgres>,
379        metric_callback: Option<crate::metric::Callback>,
380        isolation_level: Option<IsolationLevel>,
381        access_mode: Option<AccessMode>,
382    ) -> Result<crate::DatabaseTransaction, DbErr> {
383        Self::begin(
384            Arc::new(Mutex::new(crate::InnerConnection::Postgres(inner))),
385            crate::DbBackend::Postgres,
386            metric_callback,
387            isolation_level,
388            access_mode,
389        )
390        .await
391    }
392}
393
394#[cfg(feature = "proxy")]
395pub(crate) fn from_sqlx_postgres_row_to_proxy_row(row: &sqlx::postgres::PgRow) -> crate::ProxyRow {
396    // https://docs.rs/sqlx-postgres/0.7.2/src/sqlx_postgres/type_info.rs.html
397    // https://docs.rs/sqlx-postgres/0.7.2/sqlx_postgres/types/index.html
398    use sea_query::Value;
399    use sqlx::{Column, Row, TypeInfo};
400    crate::ProxyRow {
401        values: row
402            .columns()
403            .iter()
404            .map(|c| {
405                (
406                    c.name().to_string(),
407                    match c.type_info().name() {
408                        "BOOL" => {
409                            Value::Bool(row.try_get(c.ordinal()).expect("Failed to get boolean"))
410                        }
411                        #[cfg(feature = "postgres-array")]
412                        "BOOL[]" => Value::Array(
413                            sea_query::ArrayType::Bool,
414                            row.try_get::<Option<Vec<bool>>, _>(c.ordinal())
415                                .expect("Failed to get boolean array")
416                                .map(|vals| {
417                                    Box::new(
418                                        vals.into_iter()
419                                            .map(|val| Value::Bool(Some(val)))
420                                            .collect(),
421                                    )
422                                }),
423                        ),
424
425                        "\"CHAR\"" => Value::TinyInt(
426                            row.try_get(c.ordinal())
427                                .expect("Failed to get small integer"),
428                        ),
429                        #[cfg(feature = "postgres-array")]
430                        "\"CHAR\"[]" => Value::Array(
431                            sea_query::ArrayType::TinyInt,
432                            row.try_get::<Option<Vec<i8>>, _>(c.ordinal())
433                                .expect("Failed to get small integer array")
434                                .map(|vals: Vec<i8>| {
435                                    Box::new(
436                                        vals.into_iter()
437                                            .map(|val| Value::TinyInt(Some(val)))
438                                            .collect(),
439                                    )
440                                }),
441                        ),
442
443                        "SMALLINT" | "SMALLSERIAL" | "INT2" => Value::SmallInt(
444                            row.try_get(c.ordinal())
445                                .expect("Failed to get small integer"),
446                        ),
447                        #[cfg(feature = "postgres-array")]
448                        "SMALLINT[]" | "SMALLSERIAL[]" | "INT2[]" => Value::Array(
449                            sea_query::ArrayType::SmallInt,
450                            row.try_get::<Option<Vec<i16>>, _>(c.ordinal())
451                                .expect("Failed to get small integer array")
452                                .map(|vals: Vec<i16>| {
453                                    Box::new(
454                                        vals.into_iter()
455                                            .map(|val| Value::SmallInt(Some(val)))
456                                            .collect(),
457                                    )
458                                }),
459                        ),
460
461                        "INT" | "SERIAL" | "INT4" => {
462                            Value::Int(row.try_get(c.ordinal()).expect("Failed to get integer"))
463                        }
464                        #[cfg(feature = "postgres-array")]
465                        "INT[]" | "SERIAL[]" | "INT4[]" => Value::Array(
466                            sea_query::ArrayType::Int,
467                            row.try_get::<Option<Vec<i32>>, _>(c.ordinal())
468                                .expect("Failed to get integer array")
469                                .map(|vals: Vec<i32>| {
470                                    Box::new(
471                                        vals.into_iter().map(|val| Value::Int(Some(val))).collect(),
472                                    )
473                                }),
474                        ),
475
476                        "BIGINT" | "BIGSERIAL" | "INT8" => Value::BigInt(
477                            row.try_get(c.ordinal()).expect("Failed to get big integer"),
478                        ),
479                        #[cfg(feature = "postgres-array")]
480                        "BIGINT[]" | "BIGSERIAL[]" | "INT8[]" => Value::Array(
481                            sea_query::ArrayType::BigInt,
482                            row.try_get::<Option<Vec<i64>>, _>(c.ordinal())
483                                .expect("Failed to get big integer array")
484                                .map(|vals: Vec<i64>| {
485                                    Box::new(
486                                        vals.into_iter()
487                                            .map(|val| Value::BigInt(Some(val)))
488                                            .collect(),
489                                    )
490                                }),
491                        ),
492
493                        "FLOAT4" | "REAL" => {
494                            Value::Float(row.try_get(c.ordinal()).expect("Failed to get float"))
495                        }
496                        #[cfg(feature = "postgres-array")]
497                        "FLOAT4[]" | "REAL[]" => Value::Array(
498                            sea_query::ArrayType::Float,
499                            row.try_get::<Option<Vec<f32>>, _>(c.ordinal())
500                                .expect("Failed to get float array")
501                                .map(|vals| {
502                                    Box::new(
503                                        vals.into_iter()
504                                            .map(|val| Value::Float(Some(val)))
505                                            .collect(),
506                                    )
507                                }),
508                        ),
509
510                        "FLOAT8" | "DOUBLE PRECISION" => {
511                            Value::Double(row.try_get(c.ordinal()).expect("Failed to get double"))
512                        }
513                        #[cfg(feature = "postgres-array")]
514                        "FLOAT8[]" | "DOUBLE PRECISION[]" => Value::Array(
515                            sea_query::ArrayType::Double,
516                            row.try_get::<Option<Vec<f64>>, _>(c.ordinal())
517                                .expect("Failed to get double array")
518                                .map(|vals| {
519                                    Box::new(
520                                        vals.into_iter()
521                                            .map(|val| Value::Double(Some(val)))
522                                            .collect(),
523                                    )
524                                }),
525                        ),
526
527                        "VARCHAR" | "CHAR" | "TEXT" | "NAME" => Value::String(
528                            row.try_get::<Option<String>, _>(c.ordinal())
529                                .expect("Failed to get string"),
530                        ),
531                        #[cfg(feature = "postgres-array")]
532                        "VARCHAR[]" | "CHAR[]" | "TEXT[]" | "NAME[]" => Value::Array(
533                            sea_query::ArrayType::String,
534                            row.try_get::<Option<Vec<String>>, _>(c.ordinal())
535                                .expect("Failed to get string array")
536                                .map(|vals| {
537                                    Box::new(
538                                        vals.into_iter()
539                                            .map(|val| Value::String(Some(val)))
540                                            .collect(),
541                                    )
542                                }),
543                        ),
544
545                        "BYTEA" => Value::Bytes(
546                            row.try_get::<Option<Vec<u8>>, _>(c.ordinal())
547                                .expect("Failed to get bytes"),
548                        ),
549                        #[cfg(feature = "postgres-array")]
550                        "BYTEA[]" => Value::Array(
551                            sea_query::ArrayType::Bytes,
552                            row.try_get::<Option<Vec<Vec<u8>>>, _>(c.ordinal())
553                                .expect("Failed to get bytes array")
554                                .map(|vals| {
555                                    Box::new(
556                                        vals.into_iter()
557                                            .map(|val| Value::Bytes(Some(val)))
558                                            .collect(),
559                                    )
560                                }),
561                        ),
562
563                        #[cfg(feature = "with-bigdecimal")]
564                        "NUMERIC" => Value::BigDecimal(
565                            row.try_get::<Option<bigdecimal::BigDecimal>, _>(c.ordinal())
566                                .expect("Failed to get numeric"),
567                        ),
568                        #[cfg(all(
569                            feature = "with-rust_decimal",
570                            not(feature = "with-bigdecimal")
571                        ))]
572                        "NUMERIC" => {
573                            Value::Decimal(row.try_get(c.ordinal()).expect("Failed to get numeric"))
574                        }
575
576                        #[cfg(all(feature = "with-bigdecimal", feature = "postgres-array"))]
577                        "NUMERIC[]" => Value::Array(
578                            sea_query::ArrayType::BigDecimal,
579                            row.try_get::<Option<Vec<bigdecimal::BigDecimal>>, _>(c.ordinal())
580                                .expect("Failed to get numeric array")
581                                .map(|vals| {
582                                    Box::new(
583                                        vals.into_iter()
584                                            .map(|val| Value::BigDecimal(Some(val)))
585                                            .collect(),
586                                    )
587                                }),
588                        ),
589                        #[cfg(all(
590                            feature = "with-rust_decimal",
591                            not(feature = "with-bigdecimal"),
592                            feature = "postgres-array"
593                        ))]
594                        "NUMERIC[]" => Value::Array(
595                            sea_query::ArrayType::Decimal,
596                            row.try_get::<Option<Vec<rust_decimal::Decimal>>, _>(c.ordinal())
597                                .expect("Failed to get numeric array")
598                                .map(|vals| {
599                                    Box::new(
600                                        vals.into_iter()
601                                            .map(|val| Value::Decimal(Some(val)))
602                                            .collect(),
603                                    )
604                                }),
605                        ),
606
607                        "OID" => {
608                            Value::BigInt(row.try_get(c.ordinal()).expect("Failed to get oid"))
609                        }
610                        #[cfg(feature = "postgres-array")]
611                        "OID[]" => Value::Array(
612                            sea_query::ArrayType::BigInt,
613                            row.try_get::<Option<Vec<i64>>, _>(c.ordinal())
614                                .expect("Failed to get oid array")
615                                .map(|vals| {
616                                    Box::new(
617                                        vals.into_iter()
618                                            .map(|val| Value::BigInt(Some(val)))
619                                            .collect(),
620                                    )
621                                }),
622                        ),
623
624                        "JSON" | "JSONB" => Value::Json(
625                            row.try_get::<Option<serde_json::Value>, _>(c.ordinal())
626                                .expect("Failed to get json")
627                                .map(Box::new),
628                        ),
629                        #[cfg(any(feature = "json-array", feature = "postgres-array"))]
630                        "JSON[]" | "JSONB[]" => Value::Array(
631                            sea_query::ArrayType::Json,
632                            row.try_get::<Option<Vec<serde_json::Value>>, _>(c.ordinal())
633                                .expect("Failed to get json array")
634                                .map(|vals| {
635                                    Box::new(
636                                        vals.into_iter()
637                                            .map(|val| Value::Json(Some(Box::new(val))))
638                                            .collect(),
639                                    )
640                                }),
641                        ),
642
643                        #[cfg(feature = "with-ipnetwork")]
644                        "INET" | "CIDR" => Value::IpNetwork(
645                            row.try_get::<Option<ipnetwork::IpNetwork>, _>(c.ordinal())
646                                .expect("Failed to get ip address"),
647                        ),
648                        #[cfg(feature = "with-ipnetwork")]
649                        "INET[]" | "CIDR[]" => Value::Array(
650                            sea_query::ArrayType::IpNetwork,
651                            row.try_get::<Option<Vec<ipnetwork::IpNetwork>>, _>(c.ordinal())
652                                .expect("Failed to get ip address array")
653                                .map(|vals| {
654                                    Box::new(
655                                        vals.into_iter()
656                                            .map(|val| Value::IpNetwork(Some(val)))
657                                            .collect(),
658                                    )
659                                }),
660                        ),
661
662                        #[cfg(feature = "with-mac_address")]
663                        "MACADDR" | "MACADDR8" => Value::MacAddress(
664                            row.try_get::<Option<mac_address::MacAddress>, _>(c.ordinal())
665                                .expect("Failed to get mac address"),
666                        ),
667                        #[cfg(all(feature = "with-mac_address", feature = "postgres-array"))]
668                        "MACADDR[]" | "MACADDR8[]" => Value::Array(
669                            sea_query::ArrayType::MacAddress,
670                            row.try_get::<Option<Vec<mac_address::MacAddress>>, _>(c.ordinal())
671                                .expect("Failed to get mac address array")
672                                .map(|vals| {
673                                    Box::new(
674                                        vals.into_iter()
675                                            .map(|val| Value::MacAddress(Some(val)))
676                                            .collect(),
677                                    )
678                                }),
679                        ),
680
681                        #[cfg(feature = "with-chrono")]
682                        "TIMESTAMP" => Value::ChronoDateTime(
683                            row.try_get::<Option<chrono::NaiveDateTime>, _>(c.ordinal())
684                                .expect("Failed to get timestamp"),
685                        ),
686                        #[cfg(all(feature = "with-time", not(feature = "with-chrono")))]
687                        "TIMESTAMP" => Value::TimeDateTime(
688                            row.try_get::<Option<time::PrimitiveDateTime>, _>(c.ordinal())
689                                .expect("Failed to get timestamp"),
690                        ),
691
692                        #[cfg(all(feature = "with-chrono", feature = "postgres-array"))]
693                        "TIMESTAMP[]" => Value::Array(
694                            sea_query::ArrayType::ChronoDateTime,
695                            row.try_get::<Option<Vec<chrono::NaiveDateTime>>, _>(c.ordinal())
696                                .expect("Failed to get timestamp array")
697                                .map(|vals| {
698                                    Box::new(
699                                        vals.into_iter()
700                                            .map(|val| Value::ChronoDateTime(Some(val)))
701                                            .collect(),
702                                    )
703                                }),
704                        ),
705                        #[cfg(all(
706                            feature = "with-time",
707                            not(feature = "with-chrono"),
708                            feature = "postgres-array"
709                        ))]
710                        "TIMESTAMP[]" => Value::Array(
711                            sea_query::ArrayType::TimeDateTime,
712                            row.try_get::<Option<Vec<time::PrimitiveDateTime>>, _>(c.ordinal())
713                                .expect("Failed to get timestamp array")
714                                .map(|vals| {
715                                    Box::new(
716                                        vals.into_iter()
717                                            .map(|val| Value::TimeDateTime(Some(val)))
718                                            .collect(),
719                                    )
720                                }),
721                        ),
722
723                        #[cfg(feature = "with-chrono")]
724                        "DATE" => Value::ChronoDate(
725                            row.try_get::<Option<chrono::NaiveDate>, _>(c.ordinal())
726                                .expect("Failed to get date"),
727                        ),
728                        #[cfg(all(feature = "with-time", not(feature = "with-chrono")))]
729                        "DATE" => Value::TimeDate(
730                            row.try_get::<Option<time::Date>, _>(c.ordinal())
731                                .expect("Failed to get date"),
732                        ),
733
734                        #[cfg(all(feature = "with-chrono", feature = "postgres-array"))]
735                        "DATE[]" => Value::Array(
736                            sea_query::ArrayType::ChronoDate,
737                            row.try_get::<Option<Vec<chrono::NaiveDate>>, _>(c.ordinal())
738                                .expect("Failed to get date array")
739                                .map(|vals| {
740                                    Box::new(
741                                        vals.into_iter()
742                                            .map(|val| Value::ChronoDate(Some(val)))
743                                            .collect(),
744                                    )
745                                }),
746                        ),
747                        #[cfg(all(
748                            feature = "with-time",
749                            not(feature = "with-chrono"),
750                            feature = "postgres-array"
751                        ))]
752                        "DATE[]" => Value::Array(
753                            sea_query::ArrayType::TimeDate,
754                            row.try_get::<Option<Vec<time::Date>>, _>(c.ordinal())
755                                .expect("Failed to get date array")
756                                .map(|vals| {
757                                    Box::new(
758                                        vals.into_iter()
759                                            .map(|val| Value::TimeDate(Some(val)))
760                                            .collect(),
761                                    )
762                                }),
763                        ),
764
765                        #[cfg(feature = "with-chrono")]
766                        "TIME" => Value::ChronoTime(
767                            row.try_get::<Option<chrono::NaiveTime>, _>(c.ordinal())
768                                .expect("Failed to get time"),
769                        ),
770                        #[cfg(all(feature = "with-time", not(feature = "with-chrono")))]
771                        "TIME" => Value::TimeTime(
772                            row.try_get::<Option<time::Time>, _>(c.ordinal())
773                                .expect("Failed to get time"),
774                        ),
775
776                        #[cfg(all(feature = "with-chrono", feature = "postgres-array"))]
777                        "TIME[]" => Value::Array(
778                            sea_query::ArrayType::ChronoTime,
779                            row.try_get::<Option<Vec<chrono::NaiveTime>>, _>(c.ordinal())
780                                .expect("Failed to get time array")
781                                .map(|vals| {
782                                    Box::new(
783                                        vals.into_iter()
784                                            .map(|val| Value::ChronoTime(Some(val)))
785                                            .collect(),
786                                    )
787                                }),
788                        ),
789                        #[cfg(all(
790                            feature = "with-time",
791                            not(feature = "with-chrono"),
792                            feature = "postgres-array"
793                        ))]
794                        "TIME[]" => Value::Array(
795                            sea_query::ArrayType::TimeTime,
796                            row.try_get::<Option<Vec<time::Time>>, _>(c.ordinal())
797                                .expect("Failed to get time array")
798                                .map(|vals| {
799                                    Box::new(
800                                        vals.into_iter()
801                                            .map(|val| Value::TimeTime(Some(val)))
802                                            .collect(),
803                                    )
804                                }),
805                        ),
806
807                        #[cfg(feature = "with-chrono")]
808                        "TIMESTAMPTZ" => Value::ChronoDateTimeUtc(
809                            row.try_get::<Option<chrono::DateTime<chrono::Utc>>, _>(c.ordinal())
810                                .expect("Failed to get timestamptz"),
811                        ),
812                        #[cfg(all(feature = "with-time", not(feature = "with-chrono")))]
813                        "TIMESTAMPTZ" => Value::TimeDateTime(
814                            row.try_get::<Option<time::PrimitiveDateTime>, _>(c.ordinal())
815                                .expect("Failed to get timestamptz"),
816                        ),
817
818                        #[cfg(all(feature = "with-chrono", feature = "postgres-array"))]
819                        "TIMESTAMPTZ[]" => Value::Array(
820                            sea_query::ArrayType::ChronoDateTimeUtc,
821                            row.try_get::<Option<Vec<chrono::DateTime<chrono::Utc>>>, _>(
822                                c.ordinal(),
823                            )
824                            .expect("Failed to get timestamptz array")
825                            .map(|vals| {
826                                Box::new(
827                                    vals.into_iter()
828                                        .map(|val| Value::ChronoDateTimeUtc(Some(val)))
829                                        .collect(),
830                                )
831                            }),
832                        ),
833                        #[cfg(all(
834                            feature = "with-time",
835                            not(feature = "with-chrono"),
836                            feature = "postgres-array"
837                        ))]
838                        "TIMESTAMPTZ[]" => Value::Array(
839                            sea_query::ArrayType::TimeDateTime,
840                            row.try_get::<Option<Vec<time::PrimitiveDateTime>>, _>(c.ordinal())
841                                .expect("Failed to get timestamptz array")
842                                .map(|vals| {
843                                    Box::new(
844                                        vals.into_iter()
845                                            .map(|val| Value::TimeDateTime(Some(val)))
846                                            .collect(),
847                                    )
848                                }),
849                        ),
850
851                        #[cfg(feature = "with-chrono")]
852                        "TIMETZ" => Value::ChronoTime(
853                            row.try_get::<Option<chrono::NaiveTime>, _>(c.ordinal())
854                                .expect("Failed to get timetz"),
855                        ),
856                        #[cfg(all(feature = "with-time", not(feature = "with-chrono")))]
857                        "TIMETZ" => {
858                            Value::TimeTime(row.try_get(c.ordinal()).expect("Failed to get timetz"))
859                        }
860
861                        #[cfg(all(feature = "with-chrono", feature = "postgres-array"))]
862                        "TIMETZ[]" => Value::Array(
863                            sea_query::ArrayType::ChronoTime,
864                            row.try_get::<Option<Vec<chrono::NaiveTime>>, _>(c.ordinal())
865                                .expect("Failed to get timetz array")
866                                .map(|vals| {
867                                    Box::new(
868                                        vals.into_iter()
869                                            .map(|val| Value::ChronoTime(Some(val)))
870                                            .collect(),
871                                    )
872                                }),
873                        ),
874                        #[cfg(all(
875                            feature = "with-time",
876                            not(feature = "with-chrono"),
877                            feature = "postgres-array"
878                        ))]
879                        "TIMETZ[]" => Value::Array(
880                            sea_query::ArrayType::TimeTime,
881                            row.try_get::<Option<Vec<time::Time>>, _>(c.ordinal())
882                                .expect("Failed to get timetz array")
883                                .map(|vals| {
884                                    Box::new(
885                                        vals.into_iter()
886                                            .map(|val| Value::TimeTime(Some(val)))
887                                            .collect(),
888                                    )
889                                }),
890                        ),
891
892                        #[cfg(feature = "with-uuid")]
893                        "UUID" => Value::Uuid(
894                            row.try_get::<Option<uuid::Uuid>, _>(c.ordinal())
895                                .expect("Failed to get uuid"),
896                        ),
897
898                        #[cfg(all(feature = "with-uuid", feature = "postgres-array"))]
899                        "UUID[]" => Value::Array(
900                            sea_query::ArrayType::Uuid,
901                            row.try_get::<Option<Vec<uuid::Uuid>>, _>(c.ordinal())
902                                .expect("Failed to get uuid array")
903                                .map(|vals| {
904                                    Box::new(
905                                        vals.into_iter()
906                                            .map(|val| Value::Uuid(Some(val)))
907                                            .collect(),
908                                    )
909                                }),
910                        ),
911
912                        _ => unreachable!("Unknown column type: {}", c.type_info().name()),
913                    },
914                )
915            })
916            .collect(),
917    }
918}