1#![warn(missing_docs)]
2
3mod oid_cache;
15mod statement_cache;
16#[cfg(feature = "tls")]
17mod tls;
18mod r#type;
19mod value;
20
21pub(crate) use value::Value;
22
23use async_trait::async_trait;
24use std::{borrow::Cow, sync::Arc};
25use toasty_core::{
26 Result, Schema,
27 driver::{
28 Capability, ConnectContext, ConnectionUrl, Driver, ExecResponse, Operation, QueryLogConfig,
29 log::QueryLog,
30 operation::{RawSqlRet, Transaction, TransactionMode, TypedValue},
31 },
32 schema::db::{self, Table},
33 stmt,
34 stmt::ValueRecord,
35};
36use toasty_sql::{self as sql};
37use tokio_postgres::{Client, Config, Socket, tls::MakeTlsConnect, types::ToSql};
38
39enum SqlReturn {
40 Count,
41 Infer,
42 Types(Vec<stmt::Type>),
43}
44
45use crate::{oid_cache::OidCache, statement_cache::StatementCache};
46
47fn classify_pg_error(e: tokio_postgres::Error) -> toasty_core::Error {
58 if let Some(db_err) = e.as_db_error() {
59 match db_err.code().code() {
60 "40001" => toasty_core::Error::serialization_failure(db_err.message()),
61 "25006" => toasty_core::Error::read_only_transaction(db_err.message()),
62 _ => toasty_core::Error::driver_operation_failed(e),
63 }
64 } else {
65 toasty_core::Error::connection_lost(e)
66 }
67}
68
69pub struct PostgreSQL {
79 url: String,
80 config: Config,
81 #[cfg(feature = "tls")]
82 tls: Option<tokio_postgres_rustls::MakeRustlsConnect>,
83}
84
85impl std::fmt::Debug for PostgreSQL {
86 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87 let Self {
88 url,
89 config,
90 #[cfg(feature = "tls")]
91 tls,
92 } = self;
93 let mut s = f.debug_struct("PostgreSQL");
94 s.field("url", url);
95 s.field("config", config);
96 #[cfg(feature = "tls")]
97 s.field("tls", &tls.as_ref().map(|_| "MakeRustlsConnect"));
98 s.finish()
99 }
100}
101
102impl PostgreSQL {
103 pub fn new(url: impl Into<String>) -> Result<Self> {
115 let url_str = url.into();
116 let url = ConnectionUrl::parse(&url_str)?;
117
118 if !(url.has_scheme("postgresql") || url.has_scheme("postgres")) {
119 return Err(toasty_core::Error::invalid_connection_url(format!(
120 "connection URL does not have a `postgresql` scheme; url={}",
121 url.as_str()
122 )));
123 }
124
125 if url.path().is_empty() {
126 return Err(toasty_core::Error::invalid_connection_url(format!(
127 "no database specified - missing path in connection URL; url={}",
128 url.as_str()
129 )));
130 }
131
132 let mut config = Config::new();
133
134 let dbname = url.decoded_path().map_err(|_| {
135 toasty_core::Error::invalid_connection_url("database name is not valid UTF-8")
136 })?;
137 config.dbname(dbname.trim_start_matches('/'));
138
139 if let Some(user) = url.username()?.filter(|user| !user.is_empty()) {
140 config.user(&*user);
141 }
142
143 if let Some(password) = url.password() {
144 config.password(&*password);
145 }
146
147 let mut host: Option<String> = None;
156 let mut port: Option<u16> = None;
157
158 for (key, value) in url.query_pairs() {
159 match key.as_ref() {
160 "host" => host = Some(value.into_owned()),
161 "port" => {
162 port = Some(value.parse::<u16>().map_err(|_| {
163 toasty_core::Error::invalid_connection_url(format!(
164 "invalid port in connection URL query parameter: {value}"
165 ))
166 })?);
167 }
168 "user" => {
169 config.user(&*value);
170 }
171 "password" => {
172 config.password(value.as_bytes());
173 }
174 "dbname" => {
175 config.dbname(&*value);
176 }
177 "application_name" => {
178 config.application_name(&*value);
179 }
180 "options" => {
181 config.options(&*value);
182 }
183 _ => {}
184 }
185 }
186
187 let host = host.or(url.host()?.map(String::from)).ok_or_else(|| {
188 toasty_core::Error::invalid_connection_url(format!(
189 "missing host in connection URL; url={}",
190 url.as_str()
191 ))
192 })?;
193 config.host(&host);
194
195 if let Some(port) = port.or(url.port()?) {
196 config.port(port);
197 }
198
199 #[cfg(feature = "tls")]
200 let tls = tls::configure_tls(&url, &mut config)?;
201
202 #[cfg(not(feature = "tls"))]
203 for (key, value) in url.query_pairs() {
204 if key == "sslmode" && value != "disable" {
205 return Err(toasty_core::Error::invalid_connection_url(
206 "TLS not available: compile with the `tls` feature",
207 ));
208 }
209 }
210
211 Ok(Self {
212 url: url_str,
213 config,
214 #[cfg(feature = "tls")]
215 tls,
216 })
217 }
218
219 async fn connect_with_config(&self, config: Config) -> Result<Connection> {
220 #[cfg(feature = "tls")]
221 if let Some(ref tls) = self.tls {
222 return Connection::connect(config, tls.clone()).await;
223 }
224 Connection::connect(config, tokio_postgres::NoTls).await
225 }
226}
227
228#[async_trait]
229impl Driver for PostgreSQL {
230 fn url(&self) -> Cow<'_, str> {
231 Cow::Borrowed(&self.url)
232 }
233
234 fn capability(&self) -> &'static Capability {
235 &Capability::POSTGRESQL
236 }
237
238 async fn connect(
239 &self,
240 cx: &ConnectContext,
241 ) -> toasty_core::Result<Box<dyn toasty_core::driver::Connection>> {
242 let mut connection = self.connect_with_config(self.config.clone()).await?;
243 connection.query_log = cx.query_log;
244 Ok(Box::new(connection))
245 }
246
247 async fn reset_db(&self) -> toasty_core::Result<()> {
248 let dbname = self
249 .config
250 .get_dbname()
251 .ok_or_else(|| {
252 toasty_core::Error::invalid_connection_url("no database name configured")
253 })?
254 .to_string();
255
256 let temp_dbname = "__toasty_reset_temp";
258
259 let connect = |dbname: &str| {
260 let mut config = self.config.clone();
261 config.dbname(dbname);
262 self.connect_with_config(config)
263 };
264
265 let conn = connect(&dbname).await?;
267 conn.client
268 .execute(&format!("DROP DATABASE IF EXISTS \"{}\"", temp_dbname), &[])
269 .await
270 .map_err(classify_pg_error)?;
271 conn.client
272 .execute(&format!("CREATE DATABASE \"{}\"", temp_dbname), &[])
273 .await
274 .map_err(classify_pg_error)?;
275 drop(conn);
276
277 let conn = connect(temp_dbname).await?;
279 conn.client
280 .execute(
281 "SELECT pg_terminate_backend(pid) \
282 FROM pg_stat_activity \
283 WHERE datname = $1 AND pid <> pg_backend_pid()",
284 &[&dbname],
285 )
286 .await
287 .map_err(classify_pg_error)?;
288 conn.client
289 .execute(&format!("DROP DATABASE IF EXISTS \"{}\"", dbname), &[])
290 .await
291 .map_err(classify_pg_error)?;
292 conn.client
293 .execute(&format!("CREATE DATABASE \"{}\"", dbname), &[])
294 .await
295 .map_err(classify_pg_error)?;
296 drop(conn);
297
298 let conn = connect(&dbname).await?;
300 conn.client
301 .execute(&format!("DROP DATABASE IF EXISTS \"{}\"", temp_dbname), &[])
302 .await
303 .map_err(classify_pg_error)?;
304
305 Ok(())
306 }
307}
308
309#[derive(Debug)]
311pub struct Connection {
312 client: Client,
313 statement_cache: StatementCache,
314 oid_cache: OidCache,
315 query_log: QueryLogConfig,
316}
317
318impl Connection {
319 pub fn new(client: Client) -> Self {
321 Self {
322 client,
323 statement_cache: StatementCache::new(100),
324 oid_cache: OidCache::new(),
325 query_log: QueryLogConfig::default(),
326 }
327 }
328
329 pub async fn connect<T>(config: Config, tls: T) -> Result<Self>
333 where
334 T: MakeTlsConnect<Socket> + 'static,
335 T::Stream: Send,
336 {
337 let (client, connection) = config.connect(tls).await.map_err(classify_pg_error)?;
338
339 tokio::spawn(async move {
340 if let Err(e) = connection.await {
341 eprintln!("connection error: {e}");
342 }
343 });
344
345 Ok(Self::new(client))
346 }
347
348 async fn exec_sql(
349 &mut self,
350 sql_as_str: &str,
351 typed_params: Vec<TypedValue>,
352 ret: SqlReturn,
353 ) -> Result<ExecResponse> {
354 let mut log = QueryLog::sql(
355 &self.query_log,
356 "postgresql",
357 sql_as_str,
358 typed_params.iter().map(|tv| &tv.value),
359 );
360 let result = self
361 .exec_sql_inner(sql_as_str, typed_params, ret, &mut log)
362 .await;
363 log.finish(&result);
364 result
365 }
366
367 async fn exec_sql_inner(
368 &mut self,
369 sql_as_str: &str,
370 typed_params: Vec<TypedValue>,
371 ret: SqlReturn,
372 log: &mut QueryLog<'_>,
373 ) -> Result<ExecResponse> {
374 self.oid_cache
375 .preload(&self.client, typed_params.iter().map(|tv| &tv.ty))
376 .await?;
377 let param_types: Vec<_> = typed_params
378 .iter()
379 .map(|tv| self.oid_cache.get(&tv.ty).clone())
380 .collect();
381
382 let values: Vec<_> = typed_params
383 .into_iter()
384 .map(|tv| Value::from(tv.value))
385 .collect();
386 let params = values
387 .iter()
388 .map(|param| param as &(dyn ToSql + Sync))
389 .collect::<Vec<_>>();
390
391 let statement = self
392 .statement_cache
393 .prepare_typed(&mut self.client, sql_as_str, ¶m_types)
394 .await
395 .map_err(classify_pg_error)?;
396
397 if matches!(ret, SqlReturn::Count) {
398 let count = self
399 .client
400 .execute(&statement, ¶ms)
401 .await
402 .map_err(classify_pg_error)?;
403 return Ok(ExecResponse::count(count));
404 }
405
406 let rows = self
407 .client
408 .query(&statement, ¶ms)
409 .await
410 .map_err(classify_pg_error)?;
411
412 log.rows(rows.len() as u64);
413
414 let results = rows.into_iter().map(move |row| {
415 let mut results = Vec::new();
416
417 match &ret {
418 SqlReturn::Count => unreachable!(),
419 SqlReturn::Infer => {
420 for (i, column) in row.columns().iter().enumerate() {
421 results.push(Value::from_sql_infer(i, &row, column).into_inner());
422 }
423 }
424 SqlReturn::Types(ret_tys) => {
425 for (i, column) in row.columns().iter().enumerate() {
426 results.push(Value::from_sql(i, &row, column, &ret_tys[i]).into_inner());
427 }
428 }
429 }
430
431 Ok(ValueRecord::from_vec(results))
432 });
433
434 Ok(ExecResponse::value_stream(stmt::ValueStream::from_iter(
435 results,
436 )))
437 }
438
439 pub async fn create_table(&mut self, schema: &db::Schema, table: &Table) -> Result<()> {
441 let serializer = sql::Serializer::postgresql(schema);
442
443 let sql = serializer.serialize(&sql::Statement::create_table(
444 table,
445 &Capability::POSTGRESQL,
446 ));
447
448 self.client
449 .execute(&sql, &[])
450 .await
451 .map_err(classify_pg_error)?;
452
453 for index in &table.indices {
454 if index.primary_key {
455 continue;
456 }
457
458 let sql = serializer.serialize(&sql::Statement::create_index(index));
459
460 self.client
461 .execute(&sql, &[])
462 .await
463 .map_err(classify_pg_error)?;
464 }
465
466 Ok(())
467 }
468}
469
470impl From<Client> for Connection {
471 fn from(client: Client) -> Self {
472 Self::new(client)
473 }
474}
475
476#[async_trait]
477impl toasty_core::driver::Connection for Connection {
478 async fn exec(&mut self, schema: &Arc<Schema>, op: Operation) -> Result<ExecResponse> {
479 tracing::trace!(driver = "postgresql", op = %op.name(), "driver exec");
480
481 if let Operation::Transaction(ref t) = op {
482 if let Transaction::Start {
486 mode: mode @ (TransactionMode::Immediate | TransactionMode::Exclusive),
487 ..
488 } = t
489 {
490 return Err(toasty_core::Error::unsupported_feature(format!(
491 "PostgreSQL does not support TransactionMode::{mode:?}"
492 )));
493 }
494 let sql = sql::Serializer::postgresql(&schema.db).serialize_transaction(t);
495 self.client
496 .batch_execute(&sql)
497 .await
498 .map_err(classify_pg_error)?;
499 return Ok(ExecResponse::count(0));
500 }
501
502 let (sql, typed_params, ret_tys) = match op {
503 Operation::Insert(op) => (sql::Statement::from(op.stmt), op.params, op.ret),
504 Operation::QuerySql(query) => {
505 (sql::Statement::from(query.stmt), query.params, query.ret)
506 }
507 Operation::RawSql(op) => {
508 let ret = match op.ret {
509 RawSqlRet::None => SqlReturn::Count,
510 RawSqlRet::Infer => SqlReturn::Infer,
511 RawSqlRet::Types(types) => SqlReturn::Types(types),
512 };
513 return self.exec_sql(&op.sql, op.params, ret).await;
514 }
515 op => todo!("op={:#?}", op),
516 };
517
518 let sql_as_str = sql::Serializer::postgresql(&schema.db).serialize(&sql);
519
520 let ret = if sql.returning_len().is_some() {
521 SqlReturn::Types(ret_tys.unwrap())
522 } else {
523 SqlReturn::Count
524 };
525
526 self.exec_sql(&sql_as_str, typed_params, ret).await
527 }
528
529 async fn push_schema(&mut self, schema: &Schema) -> Result<()> {
530 let serializer = sql::Serializer::postgresql(&schema.db);
531
532 let mut created_enum_types = hashbrown::HashSet::new();
535 for table in &schema.db.tables {
536 for column in &table.columns {
537 if let Some(type_enum) = column.storage_ty.named_enum()
538 && created_enum_types.insert(type_enum.name.clone())
539 {
540 let sql = serializer.serialize(&sql::Statement::create_enum_type(type_enum));
541
542 tracing::debug!(enum_type = ?type_enum.name, "creating enum type");
543 self.client
544 .execute(&sql, &[])
545 .await
546 .map_err(classify_pg_error)?;
547 }
548 }
549 }
550
551 for table in &schema.db.tables {
552 tracing::debug!(table = %table.name, "creating table");
553 self.create_table(&schema.db, table).await?;
554 }
555 Ok(())
556 }
557
558 async fn applied_migrations(
559 &mut self,
560 ) -> Result<Vec<toasty_core::schema::db::AppliedMigration>> {
561 self.client
563 .execute(
564 "CREATE TABLE IF NOT EXISTS __toasty_migrations (
565 id BIGINT PRIMARY KEY,
566 name TEXT NOT NULL,
567 applied_at TIMESTAMP NOT NULL
568 )",
569 &[],
570 )
571 .await
572 .map_err(classify_pg_error)?;
573
574 let rows = self
576 .client
577 .query(
578 "SELECT id FROM __toasty_migrations ORDER BY applied_at",
579 &[],
580 )
581 .await
582 .map_err(classify_pg_error)?;
583
584 Ok(rows
585 .iter()
586 .map(|row| {
587 let id: i64 = row.get(0);
588 toasty_core::schema::db::AppliedMigration::new(id as u64)
589 })
590 .collect())
591 }
592
593 async fn apply_migration(
594 &mut self,
595 id: u64,
596 name: &str,
597 migration: &toasty_core::schema::db::Migration,
598 ) -> Result<()> {
599 tracing::info!(id = id, name = %name, "applying migration");
600 self.client
602 .execute(
603 "CREATE TABLE IF NOT EXISTS __toasty_migrations (
604 id BIGINT PRIMARY KEY,
605 name TEXT NOT NULL,
606 applied_at TIMESTAMP NOT NULL
607 )",
608 &[],
609 )
610 .await
611 .map_err(classify_pg_error)?;
612
613 let transaction = self.client.transaction().await.map_err(classify_pg_error)?;
615
616 for statement in migration.statements() {
618 if let Err(e) = transaction
619 .batch_execute(statement)
620 .await
621 .map_err(classify_pg_error)
622 {
623 transaction.rollback().await.map_err(classify_pg_error)?;
624 return Err(e);
625 }
626 }
627
628 if let Err(e) = transaction
630 .execute(
631 "INSERT INTO __toasty_migrations (id, name, applied_at) VALUES ($1, $2, NOW())",
632 &[&(id as i64), &name],
633 )
634 .await
635 .map_err(classify_pg_error)
636 {
637 transaction.rollback().await.map_err(classify_pg_error)?;
638 return Err(e);
639 }
640
641 transaction.commit().await.map_err(classify_pg_error)?;
643 Ok(())
644 }
645
646 fn is_valid(&self) -> bool {
647 !self.client.is_closed()
648 }
649
650 async fn ping(&mut self) -> Result<()> {
651 self.client
656 .simple_query("")
657 .await
658 .map(|_| ())
659 .map_err(toasty_core::Error::connection_lost)
660 }
661}
662
663#[cfg(test)]
664mod tests {
665 use super::*;
666 use tokio_postgres::config::Host;
667
668 fn cfg(url: &str) -> Config {
669 PostgreSQL::new(url).expect("valid URL").config
670 }
671
672 #[test]
673 fn host_in_url_authority() {
674 let c = cfg("postgresql://example.com/mydb");
675 assert_eq!(c.get_hosts(), &[Host::Tcp("example.com".into())]);
676 assert_eq!(c.get_dbname(), Some("mydb"));
677 }
678
679 #[cfg(unix)]
684 mod unix_socket {
685 use super::*;
686 use std::path::PathBuf;
687
688 #[test]
689 fn unix_socket_via_host_query_param() {
690 let c = cfg("postgresql:///mydb?host=/tmp&user=myuser");
694 assert_eq!(c.get_hosts(), &[Host::Unix(PathBuf::from("/tmp"))]);
695 assert_eq!(c.get_user(), Some("myuser"));
696 assert_eq!(c.get_dbname(), Some("mydb"));
697 }
698
699 #[test]
700 fn query_param_host_overrides_url_authority() {
701 let c = cfg("postgresql://example.com/mydb?host=/var/run/postgresql");
707 assert_eq!(
708 c.get_hosts(),
709 &[Host::Unix(PathBuf::from("/var/run/postgresql"))]
710 );
711 }
712
713 #[test]
714 fn query_param_port_user_password_dbname() {
715 let c = cfg(
716 "postgresql:///placeholder?host=/tmp&port=5433&user=alice&password=s3cret&dbname=real",
717 );
718 assert_eq!(c.get_hosts(), &[Host::Unix(PathBuf::from("/tmp"))]);
719 assert_eq!(c.get_ports(), &[5433]);
720 assert_eq!(c.get_user(), Some("alice"));
721 assert_eq!(c.get_password(), Some(&b"s3cret"[..]));
722 assert_eq!(c.get_dbname(), Some("real"));
723 }
724 }
725
726 #[test]
727 fn query_param_port_overrides_url_port() {
728 let c = cfg("postgresql://example.com:5432/mydb?port=5433");
731 assert_eq!(c.get_ports(), &[5433]);
732 }
733
734 #[test]
735 fn application_name_query_param() {
736 let c = cfg("postgresql://localhost/mydb?application_name=my_app");
737 assert_eq!(c.get_application_name(), Some("my_app"));
738 }
739
740 #[test]
741 fn options_query_param() {
742 let c = cfg("postgresql://localhost/mydb?options=-c%20search_path%3Dtenant_a%2Cpublic");
746 assert_eq!(c.get_options(), Some("-c search_path=tenant_a,public"));
747 }
748
749 #[test]
750 fn missing_host_rejected() {
751 let err = PostgreSQL::new("postgresql:///mydb").unwrap_err();
752 assert!(
753 err.to_string().contains("missing host"),
754 "expected missing-host error, got: {err}"
755 );
756 }
757
758 #[test]
759 fn invalid_port_query_param_rejected() {
760 let err = PostgreSQL::new("postgresql:///mydb?host=/tmp&port=not-a-number").unwrap_err();
761 assert!(
762 err.to_string().contains("invalid port"),
763 "expected invalid-port error, got: {err}"
764 );
765 }
766}