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