mod row;
#[cfg(test)]
mod tests;
pub mod types;
use std::future::Future;
use std::marker::PhantomData;
use std::ops::Deref;
use std::sync::{Arc, OnceLock};
use bytes::Buf;
use encore_sdk_core::postgres::Access as CoreAccess;
use encore_sdk_core::postgres::IsolationLevel as CoreIsolationLevel;
use encore_sdk_core::postgres::{self, Pool, QuerySpan, TransactionOptions};
use crate::runtime::core;
use crate::testing;
use self::row::{ConnId, StatementRef};
use self::types::{BorrowToSql, Param, ToSql, Type};
pub use self::row::{Column, Row, RowIndex, RowStream, Statement, ToStatement};
pub use encore_sdk_core::postgres::{DatabaseError, ErrorCode, ErrorDetails};
pub use tokio_postgres::{
CopyInSink, CopyOutStream, IsolationLevel, SimpleColumn, SimpleQueryMessage, SimpleQueryRow,
};
pub struct Database {
name: &'static str,
#[allow(dead_code)]
migrations: Option<&'static str>,
pool: OnceLock<Arc<Pool>>,
}
impl Database {
pub const fn new(name: &'static str) -> Self {
Self {
name,
migrations: None,
pool: OnceLock::new(),
}
}
pub const fn named(name: &'static str) -> Self {
Self::new(name)
}
pub const fn migrations(mut self, path: &'static str) -> Self {
self.migrations = Some(path);
self
}
pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
self
}
pub const fn admin(&'static self) -> DatabaseRef {
DatabaseRef {
db: self,
access: Access::Admin,
}
}
pub const fn write(&'static self) -> DatabaseRef {
DatabaseRef {
db: self,
access: Access::Write,
}
}
pub const fn read(&'static self) -> DatabaseRef {
DatabaseRef {
db: self,
access: Access::Read { primary: false },
}
}
pub const fn read_primary(&'static self) -> DatabaseRef {
DatabaseRef {
db: self,
access: Access::Read { primary: true },
}
}
fn pool(&self) -> Result<Arc<Pool>, Error> {
if let Some(test) = testing::active().map_err(test_err)? {
return test.database_pool(self.name).map_err(test_err);
}
if let Some(pool) = self.pool.get() {
return Ok(pool.clone());
}
let pool = core()
.postgres()
.database(&self.name.into())
.new_pool()
.map_err(db_err)?;
let _ = self.pool.set(Arc::new(pool));
Ok(self.pool.get().expect("pool just set").clone())
}
pub async fn transaction(&self) -> Result<Transaction<'static>, Error> {
self.begin(CoreAccess::ReadWrite, &TransactionOptions::default())
.await
}
pub fn build_transaction(&self) -> TransactionBuilder<'_> {
TransactionBuilder::new(Target::Database(self, CoreAccess::ReadWrite))
}
fn pool_for(&self, access: CoreAccess) -> Result<Pool, Error> {
self.pool()?.with_access(access).map_err(db_err)
}
async fn begin(
&self,
access: CoreAccess,
options: &TransactionOptions,
) -> Result<Transaction<'static>, Error> {
let pool = self.pool_for(access)?;
check_options(options, pool.is_read_only())?;
let inner = pool.begin_with_options(options).await.map_err(db_err)?;
Ok(Transaction::new(inner, ConnId::new()))
}
pub async fn acquire(&self) -> Result<Connection, Error> {
self.acquire_as(CoreAccess::ReadWrite).await
}
async fn acquire_as(&self, access: CoreAccess) -> Result<Connection, Error> {
let inner = self.pool_for(access)?.acquire().await.map_err(db_err)?;
Ok(Connection {
inner,
id: ConnId::new(),
})
}
pub fn connection_string(&self) -> Result<String, Error> {
self.connection_string_as(CoreAccess::ReadWrite)
}
fn connection_string_as(&self, access: CoreAccess) -> Result<String, Error> {
if let Some(test) = testing::active().map_err(test_err)? {
return test
.database_connection_string(self.name, access)
.map_err(test_err);
}
Ok(core()
.postgres()
.database(&self.name.into())
.proxy_conn_string(access))
}
}
#[derive(Clone, Copy)]
enum Access {
Admin,
Write,
Read { primary: bool },
}
impl Access {
fn core(self) -> CoreAccess {
match self {
Access::Admin | Access::Write => CoreAccess::ReadWrite,
Access::Read { primary: false } => CoreAccess::Read,
Access::Read { primary: true } => CoreAccess::ReadPrimary,
}
}
}
#[derive(Clone, Copy)]
pub struct DatabaseRef {
db: &'static Database,
access: Access,
}
impl DatabaseRef {
pub async fn transaction(&self) -> Result<Transaction<'static>, Error> {
self.db
.begin(self.access.core(), &TransactionOptions::default())
.await
}
pub fn build_transaction(&self) -> TransactionBuilder<'static> {
TransactionBuilder::new(Target::Database(self.db, self.access.core()))
}
pub async fn acquire(&self) -> Result<Connection, Error> {
self.db.acquire_as(self.access.core()).await
}
pub fn connection_string(&self) -> Result<String, Error> {
self.db.connection_string_as(self.access.core())
}
}
pub struct Connection {
inner: postgres::Connection,
id: ConnId,
}
impl Connection {
pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
self.begin(&TransactionOptions::default()).await
}
pub fn build_transaction(&mut self) -> TransactionBuilder<'_> {
TransactionBuilder::new(Target::Connection(self))
}
async fn begin(&mut self, options: &TransactionOptions) -> Result<Transaction<'_>, Error> {
check_options(options, self.inner.is_read_only())?;
let inner = self
.inner
.begin_with_options(options)
.await
.map_err(db_err)?;
Ok(Transaction::new(inner, self.id))
}
pub fn is_closed(&self) -> bool {
self.inner.is_closed()
}
pub async fn close(self) {
self.inner.close().await;
}
}
pub struct Transaction<'c> {
inner: postgres::Transaction,
id: ConnId,
conn: PhantomData<&'c mut Connection>,
}
impl Transaction<'_> {
fn new(inner: postgres::Transaction, id: ConnId) -> Self {
Self {
inner,
id,
conn: PhantomData,
}
}
pub async fn commit(self) -> Result<(), Error> {
self.inner.commit().await.map_err(db_err)
}
pub async fn rollback(self) -> Result<(), Error> {
self.inner.rollback().await.map_err(db_err)
}
}
fn check_options(options: &TransactionOptions, read_only: bool) -> Result<(), Error> {
if read_only && options.read_only == Some(false) {
return Err(Error::other(
"a read handle's transactions are read-only: read_only(false) is not allowed",
));
}
Ok(())
}
enum Target<'a> {
Database(&'a Database, CoreAccess),
Connection(&'a mut Connection),
}
pub struct TransactionBuilder<'a> {
target: Target<'a>,
isolation_level: Option<IsolationLevel>,
read_only: Option<bool>,
deferrable: Option<bool>,
}
impl<'a> TransactionBuilder<'a> {
fn new(target: Target<'a>) -> Self {
Self {
target,
isolation_level: None,
read_only: None,
deferrable: None,
}
}
pub fn isolation_level(mut self, isolation_level: IsolationLevel) -> Self {
self.isolation_level = Some(isolation_level);
self
}
pub fn read_only(mut self, read_only: bool) -> Self {
self.read_only = Some(read_only);
self
}
pub fn deferrable(mut self, deferrable: bool) -> Self {
self.deferrable = Some(deferrable);
self
}
pub async fn start(self) -> Result<Transaction<'a>, Error> {
let options = self.options()?;
match self.target {
Target::Database(db, access) => db.begin(access, &options).await,
Target::Connection(conn) => conn.begin(&options).await,
}
}
fn options(&self) -> Result<TransactionOptions, Error> {
let isolation = self
.isolation_level
.map(|level| match level {
IsolationLevel::ReadUncommitted => Ok(CoreIsolationLevel::ReadUncommitted),
IsolationLevel::ReadCommitted => Ok(CoreIsolationLevel::ReadCommitted),
IsolationLevel::RepeatableRead => Ok(CoreIsolationLevel::RepeatableRead),
IsolationLevel::Serializable => Ok(CoreIsolationLevel::Serializable),
_ => Err(Error::other("unsupported isolation level")),
})
.transpose()?;
Ok(TransactionOptions {
isolation,
read_only: self.read_only,
deferrable: self.deferrable,
})
}
}
#[derive(Clone, Copy)]
enum On<'a> {
Database(&'a Database, CoreAccess),
Connection(&'a Connection),
Transaction(&'a postgres::Transaction, ConnId),
}
enum Client<'a> {
Pooled(postgres::PooledClient),
Connection(postgres::ConnClient<'a>),
Transaction(&'a postgres::Transaction),
}
impl Deref for Client<'_> {
type Target = tokio_postgres::Client;
fn deref(&self) -> &Self::Target {
match self {
Client::Pooled(client) => client,
Client::Connection(client) => client,
Client::Transaction(tx) => tx.client(),
}
}
}
impl<'a> On<'a> {
async fn client(self, statement: &str) -> Result<Client<'a>, Error> {
let client = match self {
On::Database(db, access) => db.pool_for(access)?.client().await.map(Client::Pooled),
On::Connection(conn) => conn.inner.client().await.map(Client::Connection),
On::Transaction(tx, _) => Ok(Client::Transaction(tx)),
}
.map_err(db_err)?;
match &client {
Client::Pooled(client) => client.will_run(statement),
Client::Connection(client) => client.will_run(statement),
Client::Transaction(tx) => tx.will_run(statement),
}
Ok(client)
}
fn span(self, query: &str) -> Result<QuerySpan, Error> {
Ok(match self {
On::Database(db, _) => db.pool()?.query_span(query),
On::Connection(conn) => conn.inner.query_span(query),
On::Transaction(tx, _) => tx.query_span(query),
})
}
fn conn(self) -> Option<ConnId> {
match self {
On::Database(..) => None,
On::Connection(conn) => Some(conn.id),
On::Transaction(_, id) => Some(id),
}
}
}
impl Database {
fn on(&self) -> On<'_> {
On::Database(self, CoreAccess::ReadWrite)
}
}
impl DatabaseRef {
fn on(&self) -> On<'_> {
On::Database(self.db, self.access.core())
}
}
impl Connection {
fn on(&self) -> On<'_> {
On::Connection(self)
}
}
impl Transaction<'_> {
fn on(&self) -> On<'_> {
On::Transaction(&self.inner, self.id)
}
}
mod ops {
use super::*;
pub type Params<'a> = Vec<Param<&'a (dyn ToSql + Sync)>>;
pub fn params<'a>(params: &[&'a (dyn ToSql + Sync)]) -> Params<'a> {
params.iter().map(|p| Param(*p)).collect()
}
fn finish<T>(span: QuerySpan, result: Result<T, Error>) -> Result<T, Error> {
span.end(result.as_ref().err());
result
}
async fn resolve(
on: On<'_>,
client: &tokio_postgres::Client,
statement: StatementRef<'_>,
) -> Result<tokio_postgres::Statement, Error> {
match statement {
StatementRef::Query(query) => client.prepare(query).await.map_err(db_err),
StatementRef::Statement(statement) if on.conn() == Some(statement.conn) => {
Ok(statement.inner.clone())
}
StatementRef::Statement(_) => Err(Error::other(
"a prepared statement can only be used on the connection that prepared it, \
or in a transaction on that connection",
)),
}
}
pub async fn query_raw<T, P, I>(
on: On<'_>,
statement: &T,
params: I,
) -> Result<RowStream, Error>
where
T: ?Sized + ToStatement,
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
let statement = statement.__convert();
let span = on.span(statement.text())?;
let result = async {
let client = on.client(statement.text()).await?;
let statement = resolve(on, &client, statement).await?;
client
.query_raw(&statement, params.into_iter().map(Param))
.await
.map(RowStream::new)
.map_err(db_err)
}
.await;
finish(span, result)
}
async fn query_stream(
on: On<'_>,
statement: StatementRef<'_>,
params: Params<'_>,
) -> Result<RowStream, Error> {
let span = on.span(statement.text())?;
let result = async {
let client = on.client(statement.text()).await?;
let statement = resolve(on, &client, statement).await?;
client
.query_raw(&statement, params)
.await
.map(RowStream::new)
.map_err(db_err)
}
.await;
finish(span, result)
}
async fn collect(mut stream: RowStream) -> Result<Vec<Row>, Error> {
let mut rows = Vec::new();
while let Some(row) = stream.next().await {
rows.push(row?);
}
Ok(rows)
}
pub async fn query(
on: On<'_>,
statement: StatementRef<'_>,
params: Params<'_>,
) -> Result<Vec<Row>, Error> {
collect(query_stream(on, statement, params).await?).await
}
pub async fn query_opt(
on: On<'_>,
statement: StatementRef<'_>,
params: Params<'_>,
) -> Result<Option<Row>, Error> {
let mut stream = query_stream(on, statement, params).await?;
let Some(first) = stream.next().await.transpose()? else {
return Ok(None);
};
if stream.next().await.transpose()?.is_some() {
return Err(Error::TooManyRows);
}
Ok(Some(first))
}
pub async fn query_one(
on: On<'_>,
statement: StatementRef<'_>,
params: Params<'_>,
) -> Result<Row, Error> {
query_opt(on, statement, params).await?.ok_or(Error::NoRows)
}
pub async fn query_typed_raw<P, I>(
on: On<'_>,
query: &str,
params: I,
) -> Result<RowStream, Error>
where
P: BorrowToSql,
I: IntoIterator<Item = (P, Type)>,
{
let span = on.span(query)?;
let result = async {
let client = on.client(query).await?;
client
.query_typed_raw(query, params.into_iter().map(|(p, ty)| (Param(p), ty)))
.await
.map(RowStream::new)
.map_err(db_err)
}
.await;
finish(span, result)
}
pub async fn query_typed(
on: On<'_>,
query: &str,
params: Vec<(Param<&(dyn ToSql + Sync)>, Type)>,
) -> Result<Vec<Row>, Error> {
let span = on.span(query)?;
let result = async {
let client = on.client(query).await?;
client
.query_typed_raw(query, params)
.await
.map(RowStream::new)
.map_err(db_err)
}
.await;
collect(finish(span, result)?).await
}
pub async fn execute_raw<T, P, I>(on: On<'_>, statement: &T, params: I) -> Result<u64, Error>
where
T: ?Sized + ToStatement,
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
let statement = statement.__convert();
let span = on.span(statement.text())?;
let result = async {
let client = on.client(statement.text()).await?;
let statement = resolve(on, &client, statement).await?;
client
.execute_raw(&statement, params.into_iter().map(Param))
.await
.map_err(db_err)
}
.await;
finish(span, result)
}
pub async fn execute(
on: On<'_>,
statement: StatementRef<'_>,
params: Params<'_>,
) -> Result<u64, Error> {
let span = on.span(statement.text())?;
let result = async {
let client = on.client(statement.text()).await?;
let statement = resolve(on, &client, statement).await?;
client.execute_raw(&statement, params).await.map_err(db_err)
}
.await;
finish(span, result)
}
pub async fn simple_query(on: On<'_>, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
let span = on.span(query)?;
let result = async {
let client = on.client(query).await?;
client.simple_query(query).await.map_err(db_err)
}
.await;
finish(span, result)
}
pub async fn batch_execute(on: On<'_>, query: &str) -> Result<(), Error> {
let span = on.span(query)?;
let result = async {
let client = on.client(query).await?;
client.batch_execute(query).await.map_err(db_err)
}
.await;
finish(span, result)
}
pub async fn prepare(on: On<'_>, query: &str, types: &[Type]) -> Result<Statement, Error> {
let conn = on.conn().expect("only a connection prepares statements");
let client = on.client(query).await?;
let inner = client.prepare_typed(query, types).await.map_err(db_err)?;
Ok(Statement {
inner,
conn,
query: query.into(),
})
}
pub async fn copy_in<U>(on: On<'_>, statement: StatementRef<'_>) -> Result<CopyInSink<U>, Error>
where
U: Buf + 'static + Send,
{
let span = on.span(statement.text())?;
let result = async {
let client = on.client(statement.text()).await?;
let statement = resolve(on, &client, statement).await?;
client.copy_in(&statement).await.map_err(db_err)
}
.await;
finish(span, result)
}
pub async fn copy_out(on: On<'_>, statement: StatementRef<'_>) -> Result<CopyOutStream, Error> {
let span = on.span(statement.text())?;
let result = async {
let client = on.client(statement.text()).await?;
let statement = resolve(on, &client, statement).await?;
client.copy_out(&statement).await.map_err(db_err)
}
.await;
finish(span, result)
}
}
pub trait Queryable: Send + Sync {
fn execute<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<u64, Error>> + Send
where
T: ?Sized + ToStatement;
fn execute_raw<T, P, I>(
&self,
statement: &T,
params: I,
) -> impl Future<Output = Result<u64, Error>> + Send
where
T: ?Sized + ToStatement,
P: BorrowToSql + Send,
I: IntoIterator<Item = P> + Send,
I::IntoIter: ExactSizeIterator + Send;
fn query<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
where
T: ?Sized + ToStatement;
fn query_one<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<Row, Error>> + Send
where
T: ?Sized + ToStatement;
fn query_opt<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<Option<Row>, Error>> + Send
where
T: ?Sized + ToStatement;
fn query_raw<T, P, I>(
&self,
statement: &T,
params: I,
) -> impl Future<Output = Result<RowStream, Error>> + Send
where
T: ?Sized + ToStatement,
P: BorrowToSql + Send,
I: IntoIterator<Item = P> + Send,
I::IntoIter: ExactSizeIterator + Send;
fn query_typed(
&self,
query: &str,
params: &[(&(dyn ToSql + Sync), Type)],
) -> impl Future<Output = Result<Vec<Row>, Error>> + Send;
fn query_typed_raw<P, I>(
&self,
query: &str,
params: I,
) -> impl Future<Output = Result<RowStream, Error>> + Send
where
P: BorrowToSql + Send,
I: IntoIterator<Item = (P, Type)> + Send,
I::IntoIter: Send;
fn simple_query(
&self,
query: &str,
) -> impl Future<Output = Result<Vec<SimpleQueryMessage>, Error>> + Send;
fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send;
}
macro_rules! query_methods {
($ty:ty) => {
impl $ty {
pub async fn query<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> Result<Vec<Row>, Error>
where
T: ?Sized + ToStatement,
{
ops::query(self.on(), statement.__convert(), ops::params(params)).await
}
pub async fn query_one<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> Result<Row, Error>
where
T: ?Sized + ToStatement,
{
ops::query_one(self.on(), statement.__convert(), ops::params(params)).await
}
pub async fn query_opt<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> Result<Option<Row>, Error>
where
T: ?Sized + ToStatement,
{
ops::query_opt(self.on(), statement.__convert(), ops::params(params)).await
}
pub async fn query_raw<T, P, I>(
&self,
statement: &T,
params: I,
) -> Result<RowStream, Error>
where
T: ?Sized + ToStatement,
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
ops::query_raw(self.on(), statement, params).await
}
pub async fn query_typed(
&self,
query: &str,
params: &[(&(dyn ToSql + Sync), Type)],
) -> Result<Vec<Row>, Error> {
let params = params
.iter()
.map(|(p, ty)| (Param(*p), ty.clone()))
.collect();
ops::query_typed(self.on(), query, params).await
}
pub async fn query_typed_raw<P, I>(
&self,
query: &str,
params: I,
) -> Result<RowStream, Error>
where
P: BorrowToSql,
I: IntoIterator<Item = (P, Type)>,
{
ops::query_typed_raw(self.on(), query, params).await
}
pub async fn execute<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> Result<u64, Error>
where
T: ?Sized + ToStatement,
{
ops::execute(self.on(), statement.__convert(), ops::params(params)).await
}
pub async fn execute_raw<T, P, I>(&self, statement: &T, params: I) -> Result<u64, Error>
where
T: ?Sized + ToStatement,
P: BorrowToSql,
I: IntoIterator<Item = P>,
I::IntoIter: ExactSizeIterator,
{
ops::execute_raw(self.on(), statement, params).await
}
pub async fn simple_query(
&self,
query: &str,
) -> Result<Vec<SimpleQueryMessage>, Error> {
ops::simple_query(self.on(), query).await
}
pub async fn batch_execute(&self, query: &str) -> Result<(), Error> {
ops::batch_execute(self.on(), query).await
}
}
};
}
macro_rules! queryable {
($ty:ty) => {
impl Queryable for $ty {
fn execute<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<u64, Error>> + Send
where
T: ?Sized + ToStatement,
{
<$ty>::execute(self, statement, params)
}
fn execute_raw<T, P, I>(
&self,
statement: &T,
params: I,
) -> impl Future<Output = Result<u64, Error>> + Send
where
T: ?Sized + ToStatement,
P: BorrowToSql + Send,
I: IntoIterator<Item = P> + Send,
I::IntoIter: ExactSizeIterator + Send,
{
<$ty>::execute_raw(self, statement, params)
}
fn query<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
where
T: ?Sized + ToStatement,
{
<$ty>::query(self, statement, params)
}
fn query_one<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<Row, Error>> + Send
where
T: ?Sized + ToStatement,
{
<$ty>::query_one(self, statement, params)
}
fn query_opt<T>(
&self,
statement: &T,
params: &[&(dyn ToSql + Sync)],
) -> impl Future<Output = Result<Option<Row>, Error>> + Send
where
T: ?Sized + ToStatement,
{
<$ty>::query_opt(self, statement, params)
}
fn query_raw<T, P, I>(
&self,
statement: &T,
params: I,
) -> impl Future<Output = Result<RowStream, Error>> + Send
where
T: ?Sized + ToStatement,
P: BorrowToSql + Send,
I: IntoIterator<Item = P> + Send,
I::IntoIter: ExactSizeIterator + Send,
{
<$ty>::query_raw(self, statement, params)
}
fn query_typed(
&self,
query: &str,
params: &[(&(dyn ToSql + Sync), Type)],
) -> impl Future<Output = Result<Vec<Row>, Error>> + Send {
<$ty>::query_typed(self, query, params)
}
fn query_typed_raw<P, I>(
&self,
query: &str,
params: I,
) -> impl Future<Output = Result<RowStream, Error>> + Send
where
P: BorrowToSql + Send,
I: IntoIterator<Item = (P, Type)> + Send,
I::IntoIter: Send,
{
<$ty>::query_typed_raw(self, query, params)
}
fn simple_query(
&self,
query: &str,
) -> impl Future<Output = Result<Vec<SimpleQueryMessage>, Error>> + Send {
<$ty>::simple_query(self, query)
}
fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send {
<$ty>::batch_execute(self, query)
}
}
};
}
macro_rules! connection_methods {
($ty:ty) => {
impl $ty {
pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
ops::prepare(self.on(), query, &[]).await
}
pub async fn prepare_typed(
&self,
query: &str,
parameter_types: &[Type],
) -> Result<Statement, Error> {
ops::prepare(self.on(), query, parameter_types).await
}
pub async fn copy_in<T, U>(&self, statement: &T) -> Result<CopyInSink<U>, Error>
where
T: ?Sized + ToStatement,
U: Buf + 'static + Send,
{
ops::copy_in(self.on(), statement.__convert()).await
}
pub async fn copy_out<T>(&self, statement: &T) -> Result<CopyOutStream, Error>
where
T: ?Sized + ToStatement,
{
ops::copy_out(self.on(), statement.__convert()).await
}
}
};
}
query_methods!(Database);
query_methods!(DatabaseRef);
query_methods!(Connection);
query_methods!(Transaction<'_>);
queryable!(DatabaseRef);
queryable!(Connection);
queryable!(Transaction<'_>);
connection_methods!(Connection);
connection_methods!(Transaction<'_>);
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Database(#[from] DatabaseError),
#[error("query returned no rows")]
NoRows,
#[error("query returned more than one row")]
TooManyRows,
#[error(transparent)]
Other(Box<dyn std::error::Error + Send + Sync>),
}
impl Error {
pub fn database_error(&self) -> Option<&DatabaseError> {
match self {
Error::Database(err) => Some(err),
_ => None,
}
}
fn other(message: impl Into<String>) -> Self {
Error::Other(message.into().into())
}
}
fn db_err(err: impl Into<DbFailure>) -> Error {
match err.into() {
DbFailure::Client(err) => match DatabaseError::from_client_error(&err) {
Some(db) => db.into(),
None => Error::Other(Box::new(err)),
},
DbFailure::Core(err) => match err.database_error() {
Some(db) => db.into(),
None => Error::other(err.to_string()),
},
DbFailure::Config(err) => DatabaseError::connection_failure(format!("{err:#}")).into(),
}
}
fn test_err(err: crate::Error) -> Error {
Error::Other(Box::new(err))
}
enum DbFailure {
Client(tokio_postgres::Error),
Core(postgres::Error),
Config(anyhow::Error),
}
impl From<tokio_postgres::Error> for DbFailure {
fn from(err: tokio_postgres::Error) -> Self {
DbFailure::Client(err)
}
}
impl From<postgres::Error> for DbFailure {
fn from(err: postgres::Error) -> Self {
DbFailure::Core(err)
}
}
impl From<anyhow::Error> for DbFailure {
fn from(err: anyhow::Error) -> Self {
DbFailure::Config(err)
}
}