fix(deps): bound SQLx pool maintenance and reserve idle counters

This commit is contained in:
bsodfather committed 2026-10-04 23:57:40 +03:00
1 parent 7aa854de26
commit 284eb8180e
113 files changed
+21092 -2

No files matched your search

+87
View File
@@ -0,0 +1,87 @@
use crate::any::value::AnyValueKind;
use crate::any::{Any, AnyTypeInfoKind};
use crate::arguments::Arguments;
use crate::encode::{Encode, IsNull};
use crate::error::BoxDynError;
use crate::types::Type;
use std::sync::Arc;
#[derive(Default)]
pub struct AnyArguments {
#[doc(hidden)]
pub values: AnyArgumentBuffer,
}
impl Arguments for AnyArguments {
type Database = Any;
fn reserve(&mut self, additional: usize, _size: usize) {
self.values.0.reserve(additional);
}
fn add<'t, T>(&mut self, value: T) -> Result<(), BoxDynError>
where
T: Encode<'t, Self::Database> + Type<Self::Database>,
{
let _: IsNull = value.encode(&mut self.values)?;
Ok(())
}
fn len(&self) -> usize {
self.values.0.len()
}
}
#[derive(Default)]
pub struct AnyArgumentBuffer(#[doc(hidden)] pub Vec<AnyValueKind>);
impl AnyArguments {
#[doc(hidden)]
pub fn convert_into<'a, A: Arguments>(self) -> Result<A, BoxDynError>
where
Option<i32>: Type<A::Database> + Encode<'a, A::Database>,
Option<bool>: Type<A::Database> + Encode<'a, A::Database>,
Option<i16>: Type<A::Database> + Encode<'a, A::Database>,
Option<i32>: Type<A::Database> + Encode<'a, A::Database>,
Option<i64>: Type<A::Database> + Encode<'a, A::Database>,
Option<f32>: Type<A::Database> + Encode<'a, A::Database>,
Option<f64>: Type<A::Database> + Encode<'a, A::Database>,
Option<String>: Type<A::Database> + Encode<'a, A::Database>,
Option<Vec<u8>>: Type<A::Database> + Encode<'a, A::Database>,
bool: Type<A::Database> + Encode<'a, A::Database>,
i16: Type<A::Database> + Encode<'a, A::Database>,
i32: Type<A::Database> + Encode<'a, A::Database>,
i64: Type<A::Database> + Encode<'a, A::Database>,
f32: Type<A::Database> + Encode<'a, A::Database>,
f64: Type<A::Database> + Encode<'a, A::Database>,
Arc<String>: Type<A::Database> + Encode<'a, A::Database>,
Arc<str>: Type<A::Database> + Encode<'a, A::Database>,
Arc<Vec<u8>>: Type<A::Database> + Encode<'a, A::Database>,
{
let mut out = A::default();
for arg in self.values.0 {
match arg {
AnyValueKind::Null(AnyTypeInfoKind::Null) => out.add(Option::<i32>::None),
AnyValueKind::Null(AnyTypeInfoKind::Bool) => out.add(Option::<bool>::None),
AnyValueKind::Null(AnyTypeInfoKind::SmallInt) => out.add(Option::<i16>::None),
AnyValueKind::Null(AnyTypeInfoKind::Integer) => out.add(Option::<i32>::None),
AnyValueKind::Null(AnyTypeInfoKind::BigInt) => out.add(Option::<i64>::None),
AnyValueKind::Null(AnyTypeInfoKind::Real) => out.add(Option::<f64>::None),
AnyValueKind::Null(AnyTypeInfoKind::Double) => out.add(Option::<f32>::None),
AnyValueKind::Null(AnyTypeInfoKind::Text) => out.add(Option::<String>::None),
AnyValueKind::Null(AnyTypeInfoKind::Blob) => out.add(Option::<Vec<u8>>::None),
AnyValueKind::Bool(b) => out.add(b),
AnyValueKind::SmallInt(i) => out.add(i),
AnyValueKind::Integer(i) => out.add(i),
AnyValueKind::BigInt(i) => out.add(i),
AnyValueKind::Real(r) => out.add(r),
AnyValueKind::Double(d) => out.add(d),
AnyValueKind::Text(t) => out.add(t),
AnyValueKind::TextSlice(t) => out.add(t),
AnyValueKind::Blob(b) => out.add(b),
}?
}
Ok(out)
}
}
+31
View File
@@ -0,0 +1,31 @@
use crate::any::{Any, AnyTypeInfo};
use crate::column::Column;
use crate::ext::ustr::UStr;
#[derive(Debug, Clone)]
pub struct AnyColumn {
// NOTE: these fields are semver-exempt. See crate root docs for details.
#[doc(hidden)]
pub ordinal: usize,
#[doc(hidden)]
pub name: UStr,
#[doc(hidden)]
pub type_info: AnyTypeInfo,
}
impl Column for AnyColumn {
type Database = Any;
fn ordinal(&self) -> usize {
self.ordinal
}
fn name(&self) -> &str {
&self.name
}
fn type_info(&self) -> &AnyTypeInfo {
&self.type_info
}
}
+121
View File
@@ -0,0 +1,121 @@
use crate::any::{AnyArguments, AnyQueryResult, AnyRow, AnyStatement, AnyTypeInfo};
use crate::sql_str::SqlStr;
use either::Either;
use futures_core::future::BoxFuture;
use futures_core::stream::BoxStream;
use std::fmt::Debug;
pub trait AnyConnectionBackend: std::any::Any + Debug + Send + 'static {
/// The backend name.
fn name(&self) -> &str;
/// Explicitly close this database connection.
///
/// This method is **not required** for safe and consistent operation. However, it is
/// recommended to call it instead of letting a connection `drop` as the database backend
/// will be faster at cleaning up resources.
fn close(self: Box<Self>) -> BoxFuture<'static, crate::Result<()>>;
/// Immediately close the connection without sending a graceful shutdown.
///
/// This should still at least send a TCP `FIN` frame to let the server know we're dying.
#[doc(hidden)]
fn close_hard(self: Box<Self>) -> BoxFuture<'static, crate::Result<()>>;
/// Checks if a connection to the database is still valid.
fn ping(&mut self) -> BoxFuture<'_, crate::Result<()>>;
/// Begin a new transaction or establish a savepoint within the active transaction.
///
/// If this is a new transaction, `statement` may be used instead of the
/// default "BEGIN" statement.
///
/// If we are already inside a transaction and `statement.is_some()`, then
/// `Error::InvalidSavePoint` is returned without running any statements.
fn begin(&mut self, statement: Option<SqlStr>) -> BoxFuture<'_, crate::Result<()>>;
fn commit(&mut self) -> BoxFuture<'_, crate::Result<()>>;
fn rollback(&mut self) -> BoxFuture<'_, crate::Result<()>>;
fn start_rollback(&mut self);
/// Returns the current transaction depth.
///
/// Transaction depth indicates the level of nested transactions:
/// - Level 0: No active transaction.
/// - Level 1: A transaction is active.
/// - Level 2 or higher: A transaction is active and one or more SAVEPOINTs have been created within it.
fn get_transaction_depth(&self) -> usize {
unimplemented!("get_transaction_depth() is not implemented for this backend. This is a provided method to avoid a breaking change, but it will become a required method in version 0.9 and later.");
}
/// Checks if the connection is currently in a transaction.
///
/// This method returns `true` if the current transaction depth is greater than 0,
/// indicating that a transaction is active. It returns `false` if the transaction depth is 0,
/// meaning no transaction is active.
#[inline]
fn is_in_transaction(&self) -> bool {
self.get_transaction_depth() != 0
}
/// The number of statements currently cached in the connection.
fn cached_statements_size(&self) -> usize {
0
}
/// Removes all statements from the cache, closing them on the server if
/// needed.
fn clear_cached_statements(&mut self) -> BoxFuture<'_, crate::Result<()>> {
Box::pin(async move { Ok(()) })
}
/// Forward to [`Connection::shrink_buffers()`].
///
/// [`Connection::shrink_buffers()`]: method@crate::connection::Connection::shrink_buffers
fn shrink_buffers(&mut self);
#[doc(hidden)]
fn flush(&mut self) -> BoxFuture<'_, crate::Result<()>>;
#[doc(hidden)]
fn should_flush(&self) -> bool;
#[cfg(feature = "migrate")]
fn as_migrate(&mut self) -> crate::Result<&mut (dyn crate::migrate::Migrate + Send + 'static)> {
Err(crate::Error::Configuration(
format!(
"{} driver does not support migrations or `migrate` feature was not enabled",
self.name()
)
.into(),
))
}
fn fetch_many(
&mut self,
query: SqlStr,
persistent: bool,
arguments: Option<AnyArguments>,
) -> BoxStream<'_, crate::Result<Either<AnyQueryResult, AnyRow>>>;
fn fetch_optional(
&mut self,
query: SqlStr,
persistent: bool,
arguments: Option<AnyArguments>,
) -> BoxFuture<'_, crate::Result<Option<AnyRow>>>;
fn prepare_with<'c, 'q: 'c>(
&'c mut self,
sql: SqlStr,
parameters: &[AnyTypeInfo],
) -> BoxFuture<'c, crate::Result<AnyStatement>>;
#[cfg(feature = "offline")]
fn describe(
&mut self,
sql: SqlStr,
) -> BoxFuture<'_, crate::Result<crate::describe::Describe<crate::any::Any>>>;
}
+68
View File
@@ -0,0 +1,68 @@
use crate::any::{Any, AnyConnection, AnyQueryResult, AnyRow, AnyStatement, AnyTypeInfo};
use crate::error::Error;
use crate::executor::{Execute, Executor};
use crate::sql_str::SqlStr;
use either::Either;
use futures_core::future::BoxFuture;
use futures_core::stream::BoxStream;
use futures_util::{stream, FutureExt, StreamExt};
use std::future;
impl<'c> Executor<'c> for &'c mut AnyConnection {
type Database = Any;
fn fetch_many<'e, 'q: 'e, E>(
self,
mut query: E,
) -> BoxStream<'e, Result<Either<AnyQueryResult, AnyRow>, Error>>
where
'c: 'e,
E: 'q + Execute<'q, Any>,
{
let arguments = match query.take_arguments().map_err(Error::Encode) {
Ok(arguments) => arguments,
Err(error) => return stream::once(future::ready(Err(error))).boxed(),
};
let persistent = query.persistent();
self.backend.fetch_many(query.sql(), persistent, arguments)
}
fn fetch_optional<'e, 'q: 'e, E>(
self,
mut query: E,
) -> BoxFuture<'e, Result<Option<AnyRow>, Error>>
where
'c: 'e,
E: 'q + Execute<'q, Self::Database>,
{
let arguments = match query.take_arguments().map_err(Error::Encode) {
Ok(arguments) => arguments,
Err(error) => return future::ready(Err(error)).boxed(),
};
let persistent = query.persistent();
self.backend
.fetch_optional(query.sql(), persistent, arguments)
}
fn prepare_with<'e>(
self,
sql: SqlStr,
parameters: &[AnyTypeInfo],
) -> BoxFuture<'e, Result<AnyStatement, Error>>
where
'c: 'e,
{
self.backend.prepare_with(sql, parameters)
}
#[cfg(feature = "offline")]
fn describe<'e>(
self,
sql: SqlStr,
) -> BoxFuture<'e, Result<crate::describe::Describe<Self::Database>, Error>>
where
'c: 'e,
{
self.backend.describe(sql)
}
}
+151
View File
@@ -0,0 +1,151 @@
use futures_core::future::BoxFuture;
use std::future::Future;
use crate::any::{Any, AnyConnectOptions};
use crate::connection::{ConnectOptions, Connection};
use crate::error::Error;
use crate::config;
use crate::database::Database;
use crate::sql_str::SqlSafeStr;
use crate::transaction::Transaction;
pub use backend::AnyConnectionBackend;
mod backend;
mod executor;
/// A connection to _any_ SQLx database.
///
/// The database driver used is determined by the scheme
/// of the connection url.
///
/// ```text
/// postgres://postgres@localhost/test
/// sqlite://a.sqlite
/// ```
#[derive(Debug)]
pub struct AnyConnection {
pub(crate) backend: Box<dyn AnyConnectionBackend>,
}
impl AnyConnection {
/// Returns the name of the database backend in use (e.g. PostgreSQL, MySQL, SQLite, etc.)
pub fn backend_name(&self) -> &str {
self.backend.name()
}
pub(crate) fn connect(options: &AnyConnectOptions) -> BoxFuture<'_, crate::Result<Self>> {
Box::pin(async {
let driver = crate::any::driver::from_url(&options.database_url)?;
(*driver.connect)(options, None).await
})
}
/// UNSTABLE: for use with `sqlx-cli`
///
/// Connect to the database, and instruct the nested driver to
/// read options from the sqlx.toml file as appropriate.
#[doc(hidden)]
pub async fn connect_with_driver_config(
url: &str,
driver_config: &config::drivers::Config,
) -> Result<Self, Error>
where
Self: Sized,
{
let options: AnyConnectOptions = url.parse()?;
let driver = crate::any::driver::from_url(&options.database_url)?;
(*driver.connect)(&options, Some(driver_config)).await
}
pub(crate) fn connect_with_db<'a, DB: Database>(
options: &'a AnyConnectOptions,
driver_config: Option<&'a config::drivers::Config>,
) -> BoxFuture<'a, crate::Result<Self>>
where
DB::Connection: AnyConnectionBackend,
<DB::Connection as Connection>::Options:
for<'b> TryFrom<&'b AnyConnectOptions, Error = Error>,
{
let res = TryFrom::try_from(options);
Box::pin(async move {
let mut options: <DB::Connection as Connection>::Options = res?;
if let Some(config) = driver_config {
options = options.__unstable_apply_driver_config(config)?;
}
Ok(AnyConnection {
backend: Box::new(options.connect().await?),
})
})
}
#[cfg(feature = "migrate")]
pub(crate) fn get_migrate(
&mut self,
) -> crate::Result<&mut (dyn crate::migrate::Migrate + Send + 'static)> {
self.backend.as_migrate()
}
}
impl Connection for AnyConnection {
type Database = Any;
type Options = AnyConnectOptions;
fn close(self) -> impl Future<Output = Result<(), Error>> + Send + 'static {
self.backend.close()
}
fn close_hard(self) -> impl Future<Output = Result<(), Error>> + Send + 'static {
self.backend.close()
}
fn ping(&mut self) -> impl Future<Output = Result<(), Error>> + Send + '_ {
self.backend.ping()
}
fn begin(
&mut self,
) -> impl Future<Output = Result<Transaction<'_, Self::Database>, Error>> + Send + '_
where
Self: Sized,
{
Transaction::begin(self, None)
}
fn begin_with(
&mut self,
statement: impl SqlSafeStr,
) -> impl Future<Output = Result<Transaction<'_, Self::Database>, Error>> + Send + '_
where
Self: Sized,
{
Transaction::begin(self, Some(statement.into_sql_str()))
}
fn cached_statements_size(&self) -> usize {
self.backend.cached_statements_size()
}
fn clear_cached_statements(&mut self) -> impl Future<Output = crate::Result<()>> + Send + '_ {
self.backend.clear_cached_statements()
}
fn shrink_buffers(&mut self) {
self.backend.shrink_buffers()
}
#[doc(hidden)]
fn flush(&mut self) -> impl Future<Output = Result<(), Error>> + Send + '_ {
self.backend.flush()
}
#[doc(hidden)]
fn should_flush(&self) -> bool {
self.backend.should_flush()
}
}
+39
View File
@@ -0,0 +1,39 @@
use crate::any::{
AnyArgumentBuffer, AnyArguments, AnyColumn, AnyConnection, AnyQueryResult, AnyRow,
AnyStatement, AnyTransactionManager, AnyTypeInfo, AnyValue, AnyValueRef,
};
use crate::database::{Database, HasStatementCache};
/// Opaque database driver. Capable of being used in place of any SQLx database driver. The actual
/// driver used will be selected at runtime, from the connection url.
#[derive(Debug)]
pub struct Any;
impl Database for Any {
type Connection = AnyConnection;
type TransactionManager = AnyTransactionManager;
type Row = AnyRow;
type QueryResult = AnyQueryResult;
type Column = AnyColumn;
type TypeInfo = AnyTypeInfo;
type Value = AnyValue;
type ValueRef<'r> = AnyValueRef<'r>;
type Arguments = AnyArguments;
type ArgumentBuffer = AnyArgumentBuffer;
type Statement = AnyStatement;
const NAME: &'static str = "Any";
const URL_SCHEMES: &'static [&'static str] = &[];
}
// This _may_ be true, depending on the selected database
impl HasStatementCache for Any {}
+155
View File
@@ -0,0 +1,155 @@
use crate::any::connection::AnyConnectionBackend;
use crate::any::{AnyConnectOptions, AnyConnection};
use crate::common::DebugFn;
use crate::connection::Connection;
use crate::database::Database;
use crate::{config, Error};
use futures_core::future::BoxFuture;
use std::fmt::{Debug, Formatter};
use std::sync::OnceLock;
use url::Url;
static DRIVERS: OnceLock<&'static [AnyDriver]> = OnceLock::new();
#[macro_export]
macro_rules! declare_driver_with_optional_migrate {
($name:ident = $db:path) => {
#[cfg(feature = "migrate")]
pub const $name: $crate::any::driver::AnyDriver =
$crate::any::driver::AnyDriver::with_migrate::<$db>();
#[cfg(not(feature = "migrate"))]
pub const $name: $crate::any::driver::AnyDriver =
$crate::any::driver::AnyDriver::without_migrate::<$db>();
};
}
#[non_exhaustive]
pub struct AnyDriver {
pub(crate) name: &'static str,
pub(crate) url_schemes: &'static [&'static str],
pub(crate) connect: DebugFn<
for<'a> fn(
&'a AnyConnectOptions,
Option<&'a config::drivers::Config>,
) -> BoxFuture<'a, crate::Result<AnyConnection>>,
>,
pub(crate) migrate_database: Option<AnyMigrateDatabase>,
}
impl AnyDriver {
pub const fn without_migrate<DB: Database>() -> Self
where
DB::Connection: AnyConnectionBackend,
<DB::Connection as Connection>::Options:
for<'a> TryFrom<&'a AnyConnectOptions, Error = Error>,
{
Self {
name: DB::NAME,
url_schemes: DB::URL_SCHEMES,
connect: DebugFn(AnyConnection::connect_with_db::<DB>),
migrate_database: None,
}
}
#[cfg(not(feature = "migrate"))]
pub const fn with_migrate<DB: Database>() -> Self
where
DB::Connection: AnyConnectionBackend,
<DB::Connection as Connection>::Options:
for<'a> TryFrom<&'a AnyConnectOptions, Error = Error>,
{
Self::without_migrate::<DB>()
}
#[cfg(feature = "migrate")]
pub const fn with_migrate<DB: Database + crate::migrate::MigrateDatabase>() -> Self
where
DB::Connection: AnyConnectionBackend,
<DB::Connection as Connection>::Options:
for<'a> TryFrom<&'a AnyConnectOptions, Error = Error>,
{
Self {
migrate_database: Some(AnyMigrateDatabase {
create_database: DebugFn(|url| Box::pin(DB::create_database(url))),
database_exists: DebugFn(|url| Box::pin(DB::database_exists(url))),
drop_database: DebugFn(|url| Box::pin(DB::drop_database(url))),
force_drop_database: DebugFn(|url| Box::pin(DB::force_drop_database(url))),
}),
..Self::without_migrate::<DB>()
}
}
pub fn get_migrate_database(&self) -> crate::Result<&AnyMigrateDatabase> {
self.migrate_database.as_ref()
.ok_or_else(|| Error::Configuration(format!("{} driver does not support migrations or the `migrate` feature was not enabled for it", self.name).into()))
}
}
impl Debug for AnyDriver {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AnyDriver")
.field("name", &self.name)
.field("url_schemes", &self.url_schemes)
.finish()
}
}
pub struct AnyMigrateDatabase {
create_database: DebugFn<fn(&str) -> BoxFuture<'_, crate::Result<()>>>,
database_exists: DebugFn<fn(&str) -> BoxFuture<'_, crate::Result<bool>>>,
drop_database: DebugFn<fn(&str) -> BoxFuture<'_, crate::Result<()>>>,
force_drop_database: DebugFn<fn(&str) -> BoxFuture<'_, crate::Result<()>>>,
}
impl AnyMigrateDatabase {
pub fn create_database<'a>(&self, url: &'a str) -> BoxFuture<'a, crate::Result<()>> {
(self.create_database)(url)
}
pub fn database_exists<'a>(&self, url: &'a str) -> BoxFuture<'a, crate::Result<bool>> {
(self.database_exists)(url)
}
pub fn drop_database<'a>(&self, url: &'a str) -> BoxFuture<'a, crate::Result<()>> {
(self.drop_database)(url)
}
pub fn force_drop_database<'a>(&self, url: &'a str) -> BoxFuture<'a, crate::Result<()>> {
(self.force_drop_database)(url)
}
}
/// Install the list of drivers for [`AnyConnection`] to use.
///
/// Must be called before an `AnyConnection` or `AnyPool` can be connected.
///
/// ### Errors
/// If called more than once.
pub fn install_drivers(
drivers: &'static [AnyDriver],
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
DRIVERS
.set(drivers)
.map_err(|_| "drivers already installed".into())
}
#[cfg(feature = "migrate")]
pub(crate) fn from_url_str(url: &str) -> crate::Result<&'static AnyDriver> {
from_url(&url.parse().map_err(Error::config)?)
}
pub(crate) fn from_url(url: &Url) -> crate::Result<&'static AnyDriver> {
let scheme = url.scheme();
let drivers: &[AnyDriver] = DRIVERS
.get()
.expect("No drivers installed. Please see the documentation in `sqlx::any` for details.");
drivers
.iter()
.find(|driver| driver.url_schemes.contains(&url.scheme()))
.ok_or_else(|| {
Error::Configuration(format!("no driver found for URL scheme {scheme:?}").into())
})
}
+16
View File
@@ -0,0 +1,16 @@
use std::any::type_name;
use crate::any::type_info::AnyTypeInfo;
use crate::any::Any;
use crate::error::BoxDynError;
use crate::type_info::TypeInfo;
use crate::types::Type;
pub(super) fn mismatched_types<T: Type<Any>>(ty: &AnyTypeInfo) -> BoxDynError {
format!(
"mismatched types; Rust type `{}` is not compatible with SQL type `{}`",
type_name::<T>(),
ty.name()
)
.into()
}
+74
View File
@@ -0,0 +1,74 @@
// Annoying how deprecation warnings trigger in the same module as the deprecated item.
#![allow(deprecated)]
// Cargo features are broken in this file.
// `AnyKind` may return at some point but it won't be a simple enum.
#![allow(unexpected_cfgs)]
use crate::error::Error;
use std::str::FromStr;
#[deprecated = "not used or returned by any API"]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum AnyKind {
#[cfg(feature = "postgres")]
Postgres,
#[cfg(feature = "mysql")]
MySql,
#[cfg(feature = "_sqlite")]
Sqlite,
#[cfg(feature = "mssql")]
Mssql,
}
impl FromStr for AnyKind {
type Err = Error;
fn from_str(url: &str) -> Result<Self, Self::Err> {
match url {
#[cfg(feature = "postgres")]
_ if url.starts_with("postgres:") || url.starts_with("postgresql:") => {
Ok(AnyKind::Postgres)
}
#[cfg(not(feature = "postgres"))]
_ if url.starts_with("postgres:") || url.starts_with("postgresql:") => {
Err(Error::Configuration("database URL has the scheme of a PostgreSQL database but the `postgres` feature is not enabled".into()))
}
#[cfg(feature = "mysql")]
_ if url.starts_with("mysql:") || url.starts_with("mariadb:") => {
Ok(AnyKind::MySql)
}
#[cfg(not(feature = "mysql"))]
_ if url.starts_with("mysql:") || url.starts_with("mariadb:") => {
Err(Error::Configuration("database URL has the scheme of a MySQL database but the `mysql` feature is not enabled".into()))
}
#[cfg(feature = "_sqlite")]
_ if url.starts_with("sqlite:") => {
Ok(AnyKind::Sqlite)
}
#[cfg(not(feature = "_sqlite"))]
_ if url.starts_with("sqlite:") => {
Err(Error::Configuration("database URL has the scheme of a SQLite database but the `sqlite` feature is not enabled".into()))
}
#[cfg(feature = "mssql")]
_ if url.starts_with("mssql:") || url.starts_with("sqlserver:") => {
Ok(AnyKind::Mssql)
}
#[cfg(not(feature = "mssql"))]
_ if url.starts_with("mssql:") || url.starts_with("sqlserver:") => {
Err(Error::Configuration("database URL has the scheme of a MSSQL database but the `mssql` feature is not enabled".into()))
}
_ => Err(Error::Configuration(format!("unrecognized database url: {url:?}").into()))
}
}
}
+110
View File
@@ -0,0 +1,110 @@
use crate::any::driver;
use crate::any::{Any, AnyConnection};
use crate::error::Error;
use crate::migrate::{AppliedMigration, Migrate, MigrateDatabase, MigrateError, Migration};
use futures_core::future::BoxFuture;
use std::time::Duration;
impl MigrateDatabase for Any {
async fn create_database(url: &str) -> Result<(), Error> {
driver::from_url_str(url)?
.get_migrate_database()?
.create_database(url)
.await
}
async fn database_exists(url: &str) -> Result<bool, Error> {
driver::from_url_str(url)?
.get_migrate_database()?
.database_exists(url)
.await
}
async fn drop_database(url: &str) -> Result<(), Error> {
driver::from_url_str(url)?
.get_migrate_database()?
.drop_database(url)
.await
}
async fn force_drop_database(url: &str) -> Result<(), Error> {
driver::from_url_str(url)?
.get_migrate_database()?
.force_drop_database(url)
.await
}
}
impl Migrate for AnyConnection {
fn create_schema_if_not_exists<'e>(
&'e mut self,
schema_name: &'e str,
) -> BoxFuture<'e, Result<(), MigrateError>> {
Box::pin(async {
self.get_migrate()?
.create_schema_if_not_exists(schema_name)
.await
})
}
fn ensure_migrations_table<'e>(
&'e mut self,
table_name: &'e str,
) -> BoxFuture<'e, Result<(), MigrateError>> {
Box::pin(async {
self.get_migrate()?
.ensure_migrations_table(table_name)
.await
})
}
fn dirty_version<'e>(
&'e mut self,
table_name: &'e str,
) -> BoxFuture<'e, Result<Option<i64>, MigrateError>> {
Box::pin(async { self.get_migrate()?.dirty_version(table_name).await })
}
fn list_applied_migrations<'e>(
&'e mut self,
table_name: &'e str,
) -> BoxFuture<'e, Result<Vec<AppliedMigration>, MigrateError>> {
Box::pin(async {
self.get_migrate()?
.list_applied_migrations(table_name)
.await
})
}
fn lock(&mut self) -> BoxFuture<'_, Result<(), MigrateError>> {
Box::pin(async { self.get_migrate()?.lock().await })
}
fn unlock(&mut self) -> BoxFuture<'_, Result<(), MigrateError>> {
Box::pin(async { self.get_migrate()?.unlock().await })
}
fn apply<'e>(
&'e mut self,
table_name: &'e str,
migration: &'e Migration,
) -> BoxFuture<'e, Result<Duration, MigrateError>> {
Box::pin(async { self.get_migrate()?.apply(table_name, migration).await })
}
fn revert<'e>(
&'e mut self,
table_name: &'e str,
migration: &'e Migration,
) -> BoxFuture<'e, Result<Duration, MigrateError>> {
Box::pin(async { self.get_migrate()?.revert(table_name, migration).await })
}
fn skip<'e>(
&'e mut self,
table_name: &'e str,
migration: &'e Migration,
) -> BoxFuture<'e, Result<(), MigrateError>> {
Box::pin(async { self.get_migrate()?.skip(table_name, migration).await })
}
}
+83
View File
@@ -0,0 +1,83 @@
//! **SEE DOCUMENTATION BEFORE USE**. Generic database driver with the specific driver selected at runtime.
//!
//! The underlying database drivers are chosen at runtime from the list set via
//! [`install_drivers`][self::driver::install_drivers]. Any use of `AnyConnection` or `AnyPool`
//! without this will panic.
use crate::executor::Executor;
mod arguments;
pub(crate) mod column;
mod connection;
mod database;
mod error;
mod kind;
mod options;
mod query_result;
pub(crate) mod row;
mod statement;
mod transaction;
pub(crate) mod type_info;
pub mod types;
pub(crate) mod value;
pub mod driver;
#[cfg(feature = "migrate")]
mod migrate;
pub use arguments::{AnyArgumentBuffer, AnyArguments};
pub use column::AnyColumn;
pub use connection::AnyConnection;
// Used internally in `sqlx-macros`
use crate::encode::Encode;
pub use connection::AnyConnectionBackend;
pub use database::Any;
#[allow(deprecated)]
pub use kind::AnyKind;
pub use options::AnyConnectOptions;
pub use query_result::AnyQueryResult;
pub use row::AnyRow;
pub use statement::AnyStatement;
pub use transaction::AnyTransactionManager;
pub use type_info::{AnyTypeInfo, AnyTypeInfoKind};
pub use value::{AnyValue, AnyValueRef};
use crate::types::Type;
#[doc(hidden)]
pub use value::AnyValueKind;
pub type AnyPool = crate::pool::Pool<Any>;
pub type AnyPoolOptions = crate::pool::PoolOptions<Any>;
/// An alias for [`Executor<'_, Database = Any>`][Executor].
pub trait AnyExecutor<'c>: Executor<'c, Database = Any> {}
impl<'c, T: Executor<'c, Database = Any>> AnyExecutor<'c> for T {}
// NOTE: required due to the lack of lazy normalization
impl_into_arguments_for_arguments!(AnyArguments);
// impl_executor_for_pool_connection!(Any, AnyConnection, AnyRow);
// impl_executor_for_transaction!(Any, AnyRow);
impl_acquire!(Any, AnyConnection);
impl_column_index_for_row!(AnyRow);
impl_column_index_for_statement!(AnyStatement);
// impl_into_maybe_pool!(Any, AnyConnection);
// required because some databases have a different handling of NULL
impl<'q, T> Encode<'q, Any> for Option<T>
where
T: Encode<'q, Any> + 'q + Type<Any>,
{
fn encode_by_ref(
&self,
buf: &mut AnyArgumentBuffer,
) -> Result<crate::encode::IsNull, crate::error::BoxDynError> {
if let Some(value) = self {
value.encode_by_ref(buf)
} else {
buf.0.push(AnyValueKind::Null(T::type_info().kind));
Ok(crate::encode::IsNull::Yes)
}
}
}
+67
View File
@@ -0,0 +1,67 @@
use crate::any::AnyConnection;
use crate::connection::{ConnectOptions, LogSettings};
use crate::error::Error;
use log::LevelFilter;
use std::future::Future;
use std::str::FromStr;
use std::time::Duration;
use url::Url;
/// Opaque options for connecting to a database. These may only be constructed by parsing from
/// a connection url.
///
/// ```text
/// postgres://postgres:password@localhost/database
/// mysql://root:password@localhost/database
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct AnyConnectOptions {
pub database_url: Url,
pub log_settings: LogSettings,
}
impl FromStr for AnyConnectOptions {
type Err = Error;
fn from_str(url: &str) -> Result<Self, Self::Err> {
Ok(AnyConnectOptions {
database_url: url
.parse::<Url>()
.map_err(|e| Error::Configuration(e.into()))?,
log_settings: LogSettings::default(),
})
}
}
impl ConnectOptions for AnyConnectOptions {
type Connection = AnyConnection;
fn from_url(url: &Url) -> Result<Self, Error> {
Ok(AnyConnectOptions {
database_url: url.clone(),
log_settings: LogSettings::default(),
})
}
fn to_url_lossy(&self) -> Url {
self.database_url.clone()
}
#[inline]
fn connect(&self) -> impl Future<Output = Result<AnyConnection, Error>> + Send + '_ {
AnyConnection::connect(self)
}
fn log_statements(mut self, level: LevelFilter) -> Self {
self.log_settings.statements_level = level;
self
}
fn log_slow_statements(mut self, level: LevelFilter, duration: Duration) -> Self {
self.log_settings.slow_statements_level = level;
self.log_settings.slow_statements_duration = duration;
self
}
}
impl AnyConnectOptions {}
+28
View File
@@ -0,0 +1,28 @@
use std::iter::{Extend, IntoIterator};
#[derive(Debug, Default)]
pub struct AnyQueryResult {
#[doc(hidden)]
pub rows_affected: u64,
#[doc(hidden)]
pub last_insert_id: Option<i64>,
}
impl AnyQueryResult {
pub fn rows_affected(&self) -> u64 {
self.rows_affected
}
pub fn last_insert_id(&self) -> Option<i64> {
self.last_insert_id
}
}
impl Extend<AnyQueryResult> for AnyQueryResult {
fn extend<T: IntoIterator<Item = AnyQueryResult>>(&mut self, iter: T) {
for elem in iter {
self.rows_affected += elem.rows_affected;
self.last_insert_id = elem.last_insert_id;
}
}
}
+144
View File
@@ -0,0 +1,144 @@
use crate::any::error::mismatched_types;
use crate::any::{Any, AnyColumn, AnyTypeInfo, AnyTypeInfoKind, AnyValue, AnyValueKind};
use crate::column::{Column, ColumnIndex};
use crate::database::Database;
use crate::decode::Decode;
use crate::error::Error;
use crate::ext::ustr::UStr;
use crate::row::Row;
use crate::type_info::TypeInfo;
use crate::types::Type;
use crate::value::{Value, ValueRef};
use std::sync::Arc;
#[derive(Clone)]
pub struct AnyRow {
#[doc(hidden)]
pub column_names: Arc<crate::HashMap<UStr, usize>>,
#[doc(hidden)]
pub columns: Vec<AnyColumn>,
#[doc(hidden)]
pub values: Vec<AnyValue>,
}
impl Row for AnyRow {
type Database = Any;
fn columns(&self) -> &[AnyColumn] {
&self.columns
}
fn try_get_raw<I>(&self, index: I) -> Result<<Self::Database as Database>::ValueRef<'_>, Error>
where
I: ColumnIndex<Self>,
{
let index = index.index(self)?;
Ok(self
.values
.get(index)
.ok_or_else(|| Error::ColumnIndexOutOfBounds {
index,
len: self.columns.len(),
})?
.as_ref())
}
fn try_get<'r, T, I>(&'r self, index: I) -> Result<T, Error>
where
I: ColumnIndex<Self>,
T: Decode<'r, Self::Database> + Type<Self::Database>,
{
let value = self.try_get_raw(&index)?;
let ty = value.type_info();
if !value.is_null() && !ty.is_null() && !T::compatible(&ty) {
Err(mismatched_types::<T>(&ty))
} else {
T::decode(value)
}
.map_err(|source| Error::ColumnDecode {
index: format!("{index:?}"),
source,
})
}
}
impl ColumnIndex<AnyRow> for &'_ str {
fn index(&self, row: &AnyRow) -> Result<usize, Error> {
row.column_names
.get(*self)
.copied()
.ok_or_else(|| Error::ColumnNotFound(self.to_string()))
}
}
impl AnyRow {
// This is not a `TryFrom` impl because trait impls are easy for users to accidentally
// become reliant upon, even if hidden, but we want to be able to change the bounds
// on this function as the `Any` driver gains support for more types.
//
// Also `column_names` needs to be passed by the driver to avoid making deep copies.
#[doc(hidden)]
pub fn map_from<'a, R: Row>(
row: &'a R,
column_names: Arc<crate::HashMap<UStr, usize>>,
) -> Result<Self, Error>
where
usize: ColumnIndex<R>,
AnyTypeInfo: for<'b> TryFrom<&'b <R::Database as Database>::TypeInfo, Error = Error>,
AnyColumn: for<'b> TryFrom<&'b <R::Database as Database>::Column, Error = Error>,
bool: Type<R::Database> + Decode<'a, R::Database>,
i16: Type<R::Database> + Decode<'a, R::Database>,
i32: Type<R::Database> + Decode<'a, R::Database>,
i64: Type<R::Database> + Decode<'a, R::Database>,
f32: Type<R::Database> + Decode<'a, R::Database>,
f64: Type<R::Database> + Decode<'a, R::Database>,
String: Type<R::Database> + Decode<'a, R::Database>,
Vec<u8>: Type<R::Database> + Decode<'a, R::Database>,
{
let mut row_out = AnyRow {
column_names,
columns: Vec::with_capacity(row.columns().len()),
values: Vec::with_capacity(row.columns().len()),
};
for col in row.columns() {
let i = col.ordinal();
let any_col = AnyColumn::try_from(col)?;
let value = row.try_get_raw(i)?;
// Map based on the _value_ type info, not the column type info.
let type_info =
AnyTypeInfo::try_from(&value.type_info()).map_err(|e| Error::ColumnDecode {
index: col.ordinal().to_string(),
source: e.into(),
})?;
let value_kind = match type_info.kind {
k if value.is_null() => AnyValueKind::Null(k),
AnyTypeInfoKind::Null => AnyValueKind::Null(AnyTypeInfoKind::Null),
AnyTypeInfoKind::Bool => AnyValueKind::Bool(decode(value)?),
AnyTypeInfoKind::SmallInt => AnyValueKind::SmallInt(decode(value)?),
AnyTypeInfoKind::Integer => AnyValueKind::Integer(decode(value)?),
AnyTypeInfoKind::BigInt => AnyValueKind::BigInt(decode(value)?),
AnyTypeInfoKind::Real => AnyValueKind::Real(decode(value)?),
AnyTypeInfoKind::Double => AnyValueKind::Double(decode(value)?),
AnyTypeInfoKind::Blob => AnyValueKind::Blob(decode::<_, Vec<u8>>(value)?.into()),
AnyTypeInfoKind::Text => AnyValueKind::Text(decode::<_, String>(value)?.into()),
};
row_out.columns.push(any_col);
row_out.values.push(AnyValue { kind: value_kind });
}
Ok(row_out)
}
}
fn decode<'r, DB: Database, T: Decode<'r, DB>>(
valueref: <DB as Database>::ValueRef<'r>,
) -> crate::Result<T> {
Decode::decode(valueref).map_err(Error::decode)
}
+95
View File
@@ -0,0 +1,95 @@
use crate::any::{Any, AnyArguments, AnyColumn, AnyTypeInfo};
use crate::column::ColumnIndex;
use crate::database::Database;
use crate::error::Error;
use crate::ext::ustr::UStr;
use crate::sql_str::SqlStr;
use crate::statement::Statement;
use crate::HashMap;
use either::Either;
use std::sync::Arc;
#[derive(Clone)]
pub struct AnyStatement {
#[doc(hidden)]
pub sql: SqlStr,
#[doc(hidden)]
pub parameters: Option<Either<Vec<AnyTypeInfo>, usize>>,
#[doc(hidden)]
pub column_names: Arc<HashMap<UStr, usize>>,
#[doc(hidden)]
pub columns: Vec<AnyColumn>,
}
impl Statement for AnyStatement {
type Database = Any;
fn into_sql(self) -> SqlStr {
self.sql
}
fn sql(&self) -> &SqlStr {
&self.sql
}
fn parameters(&self) -> Option<Either<&[AnyTypeInfo], usize>> {
match &self.parameters {
Some(Either::Left(types)) => Some(Either::Left(types)),
Some(Either::Right(count)) => Some(Either::Right(*count)),
None => None,
}
}
fn columns(&self) -> &[AnyColumn] {
&self.columns
}
impl_statement_query!(AnyArguments);
}
impl ColumnIndex<AnyStatement> for &'_ str {
fn index(&self, statement: &AnyStatement) -> Result<usize, Error> {
statement
.column_names
.get(*self)
.ok_or_else(|| Error::ColumnNotFound((*self).into()))
.copied()
}
}
impl AnyStatement {
#[doc(hidden)]
pub fn try_from_statement<S>(
statement: S,
column_names: Arc<HashMap<UStr, usize>>,
) -> crate::Result<Self>
where
S: Statement,
AnyTypeInfo: for<'a> TryFrom<&'a <S::Database as Database>::TypeInfo, Error = Error>,
AnyColumn: for<'a> TryFrom<&'a <S::Database as Database>::Column, Error = Error>,
{
let parameters = match statement.parameters() {
Some(Either::Left(parameters)) => Some(Either::Left(
parameters
.iter()
.map(AnyTypeInfo::try_from)
.collect::<Result<Vec<_>, _>>()?,
)),
Some(Either::Right(count)) => Some(Either::Right(count)),
None => None,
};
let columns = statement
.columns()
.iter()
.map(AnyColumn::try_from)
.collect::<Result<Vec<_>, _>>()?;
Ok(Self {
sql: statement.into_sql(),
columns,
column_names,
parameters,
})
}
}
+36
View File
@@ -0,0 +1,36 @@
use std::future::Future;
use crate::any::{Any, AnyConnection};
use crate::database::Database;
use crate::error::Error;
use crate::sql_str::SqlStr;
use crate::transaction::TransactionManager;
pub struct AnyTransactionManager;
impl TransactionManager for AnyTransactionManager {
type Database = Any;
fn begin(
conn: &mut AnyConnection,
statement: Option<SqlStr>,
) -> impl Future<Output = Result<(), Error>> + Send + '_ {
conn.backend.begin(statement)
}
fn commit(conn: &mut AnyConnection) -> impl Future<Output = Result<(), Error>> + Send + '_ {
conn.backend.commit()
}
fn rollback(conn: &mut AnyConnection) -> impl Future<Output = Result<(), Error>> + Send + '_ {
conn.backend.rollback()
}
fn start_rollback(conn: &mut AnyConnection) {
conn.backend.start_rollback()
}
fn get_transaction_depth(conn: &<Self::Database as Database>::Connection) -> usize {
conn.backend.get_transaction_depth()
}
}
+64
View File
@@ -0,0 +1,64 @@
use std::fmt::{self, Display, Formatter};
use crate::type_info::TypeInfo;
use AnyTypeInfoKind::*;
#[derive(Debug, Clone, PartialEq)]
pub struct AnyTypeInfo {
#[doc(hidden)]
pub kind: AnyTypeInfoKind,
}
impl AnyTypeInfo {
pub fn kind(&self) -> AnyTypeInfoKind {
self.kind
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnyTypeInfoKind {
Null,
Bool,
SmallInt,
Integer,
BigInt,
Real,
Double,
Text,
Blob,
}
impl TypeInfo for AnyTypeInfo {
fn is_null(&self) -> bool {
self.kind == Null
}
fn name(&self) -> &str {
use AnyTypeInfoKind::*;
match self.kind {
Bool => "BOOLEAN",
SmallInt => "SMALLINT",
Integer => "INTEGER",
BigInt => "BIGINT",
Real => "REAL",
Double => "DOUBLE",
Text => "TEXT",
Blob => "BLOB",
Null => "NULL",
}
}
}
impl Display for AnyTypeInfo {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
impl AnyTypeInfoKind {
pub fn is_integer(&self) -> bool {
matches!(self, SmallInt | Integer | BigInt)
}
}
+59
View File
@@ -0,0 +1,59 @@
use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind};
use crate::database::Database;
use crate::decode::Decode;
use crate::encode::{Encode, IsNull};
use crate::error::BoxDynError;
use crate::types::Type;
use std::sync::Arc;
impl Type<Any> for [u8] {
fn type_info() -> AnyTypeInfo {
AnyTypeInfo {
kind: AnyTypeInfoKind::Blob,
}
}
}
impl<'q> Encode<'q, Any> for &'q [u8] {
fn encode_by_ref(
&self,
buf: &mut <Any as Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
buf.0.push(AnyValueKind::Blob(Arc::new(self.to_vec())));
Ok(IsNull::No)
}
}
impl<'r> Decode<'r, Any> for &'r [u8] {
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
match value.kind {
AnyValueKind::Blob(blob) => Ok(blob.as_slice()),
other => other.unexpected(),
}
}
}
impl Type<Any> for Vec<u8> {
fn type_info() -> AnyTypeInfo {
<[u8] as Type<Any>>::type_info()
}
}
impl Encode<'_, Any> for Vec<u8> {
fn encode_by_ref(
&self,
buf: &mut <Any as Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
buf.0.push(AnyValueKind::Blob(Arc::new(self.clone())));
Ok(IsNull::No)
}
}
impl<'r> Decode<'r, Any> for Vec<u8> {
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
match value.kind {
AnyValueKind::Blob(blob) => Ok(blob.as_ref().clone()),
other => other.unexpected(),
}
}
}
+33
View File
@@ -0,0 +1,33 @@
use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind};
use crate::database::Database;
use crate::decode::Decode;
use crate::encode::{Encode, IsNull};
use crate::error::BoxDynError;
use crate::types::Type;
impl Type<Any> for bool {
fn type_info() -> AnyTypeInfo {
AnyTypeInfo {
kind: AnyTypeInfoKind::Bool,
}
}
}
impl Encode<'_, Any> for bool {
fn encode_by_ref(
&self,
buf: &mut <Any as Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
buf.0.push(AnyValueKind::Bool(*self));
Ok(IsNull::No)
}
}
impl<'r> Decode<'r, Any> for bool {
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
match value.kind {
AnyValueKind::Bool(b) => Ok(*b),
other => other.unexpected(),
}
}
}
+59
View File
@@ -0,0 +1,59 @@
use crate::any::{Any, AnyArgumentBuffer, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind, AnyValueRef};
use crate::database::Database;
use crate::decode::Decode;
use crate::encode::{Encode, IsNull};
use crate::error::BoxDynError;
use crate::types::Type;
impl Type<Any> for f32 {
fn type_info() -> AnyTypeInfo {
AnyTypeInfo {
kind: AnyTypeInfoKind::Real,
}
}
}
impl Encode<'_, Any> for f32 {
fn encode_by_ref(&self, buf: &mut AnyArgumentBuffer) -> Result<IsNull, BoxDynError> {
buf.0.push(AnyValueKind::Real(*self));
Ok(IsNull::No)
}
}
impl<'r> Decode<'r, Any> for f32 {
fn decode(value: AnyValueRef<'r>) -> Result<Self, BoxDynError> {
match value.kind {
AnyValueKind::Real(r) => Ok(*r),
other => other.unexpected(),
}
}
}
impl Type<Any> for f64 {
fn type_info() -> AnyTypeInfo {
AnyTypeInfo {
kind: AnyTypeInfoKind::Double,
}
}
}
impl Encode<'_, Any> for f64 {
fn encode_by_ref(
&self,
buf: &mut <Any as Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
buf.0.push(AnyValueKind::Double(*self));
Ok(IsNull::No)
}
}
impl<'r> Decode<'r, Any> for f64 {
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
match value.kind {
// Widening is safe
AnyValueKind::Real(r) => Ok(*r as f64),
AnyValueKind::Double(d) => Ok(*d),
other => other.unexpected(),
}
}
}
+90
View File
@@ -0,0 +1,90 @@
use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind};
use crate::database::Database;
use crate::decode::Decode;
use crate::encode::{Encode, IsNull};
use crate::error::BoxDynError;
use crate::types::Type;
impl Type<Any> for i16 {
fn type_info() -> AnyTypeInfo {
AnyTypeInfo {
kind: AnyTypeInfoKind::SmallInt,
}
}
fn compatible(ty: &AnyTypeInfo) -> bool {
ty.kind().is_integer()
}
}
impl Encode<'_, Any> for i16 {
fn encode_by_ref(
&self,
buf: &mut <Any as Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
buf.0.push(AnyValueKind::SmallInt(*self));
Ok(IsNull::No)
}
}
impl<'r> Decode<'r, Any> for i16 {
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
value.kind.try_integer()
}
}
impl Type<Any> for i32 {
fn type_info() -> AnyTypeInfo {
AnyTypeInfo {
kind: AnyTypeInfoKind::Integer,
}
}
fn compatible(ty: &AnyTypeInfo) -> bool {
ty.kind().is_integer()
}
}
impl Encode<'_, Any> for i32 {
fn encode_by_ref(
&self,
buf: &mut <Any as Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
buf.0.push(AnyValueKind::Integer(*self));
Ok(IsNull::No)
}
}
impl<'r> Decode<'r, Any> for i32 {
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
value.kind.try_integer()
}
}
impl Type<Any> for i64 {
fn type_info() -> AnyTypeInfo {
AnyTypeInfo {
kind: AnyTypeInfoKind::BigInt,
}
}
fn compatible(ty: &AnyTypeInfo) -> bool {
ty.kind().is_integer()
}
}
impl Encode<'_, Any> for i64 {
fn encode_by_ref(
&self,
buf: &mut <Any as Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
buf.0.push(AnyValueKind::BigInt(*self));
Ok(IsNull::No)
}
}
impl<'r> Decode<'r, Any> for i64 {
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
value.kind.try_integer()
}
}
+53
View File
@@ -0,0 +1,53 @@
//! Conversions between Rust and standard **SQL** types.
//!
//! # Types
//!
//! | Rust type | SQL type(s) |
//! |---------------------------------------|------------------------------------------------------|
//! | `bool` | BOOLEAN |
//! | `i16` | SMALLINT |
//! | `i32` | INT |
//! | `i64` | BIGINT |
//! | `f32` | FLOAT |
//! | `f64` | DOUBLE |
//! | `&str`, [`String`] | VARCHAR, CHAR, TEXT |
//!
//! # Nullable
//!
//! In addition, `Option<T>` is supported where `T` implements `Type`. An `Option<T>` represents
//! a potentially `NULL` value from SQL.
mod blob;
mod bool;
mod float;
mod int;
mod str;
#[test]
fn test_type_impls() {
use crate::any::Any;
use crate::decode::Decode;
use crate::encode::Encode;
use crate::types::Type;
fn has_type<T>()
where
T: Type<Any>,
for<'a> T: Encode<'a, Any>,
for<'a> T: Decode<'a, Any>,
{
}
has_type::<bool>();
has_type::<i16>();
has_type::<i32>();
has_type::<i64>();
has_type::<f32>();
has_type::<f64>();
// These imply that there are also impls for the equivalent slice types.
has_type::<Vec<u8>>();
has_type::<String>();
}
+72
View File
@@ -0,0 +1,72 @@
use crate::any::types::str;
use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind};
use crate::database::Database;
use crate::decode::Decode;
use crate::encode::{Encode, IsNull};
use crate::error::BoxDynError;
use crate::types::Type;
use std::sync::Arc;
impl Type<Any> for str {
fn type_info() -> AnyTypeInfo {
AnyTypeInfo {
kind: AnyTypeInfoKind::Text,
}
}
}
impl<'a> Encode<'a, Any> for &'a str {
fn encode(self, buf: &mut <Any as Database>::ArgumentBuffer) -> Result<IsNull, BoxDynError>
where
Self: Sized,
{
buf.0.push(AnyValueKind::Text(Arc::new(self.into())));
Ok(IsNull::No)
}
fn encode_by_ref(
&self,
buf: &mut <Any as Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
(*self).encode(buf)
}
}
impl<'a> Decode<'a, Any> for &'a str {
fn decode(value: <Any as Database>::ValueRef<'a>) -> Result<Self, BoxDynError> {
match value.kind {
AnyValueKind::Text(text) => Ok(text.as_str()),
other => other.unexpected(),
}
}
}
impl Type<Any> for String {
fn type_info() -> AnyTypeInfo {
<str as Type<Any>>::type_info()
}
}
impl Encode<'_, Any> for String {
fn encode(self, buf: &mut <Any as Database>::ArgumentBuffer) -> Result<IsNull, BoxDynError> {
buf.0.push(AnyValueKind::Text(Arc::new(self)));
Ok(IsNull::No)
}
fn encode_by_ref(
&self,
buf: &mut <Any as Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
buf.0.push(AnyValueKind::Text(Arc::new(self.clone())));
Ok(IsNull::No)
}
}
impl<'r> Decode<'r, Any> for String {
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
match value.kind {
AnyValueKind::Text(text) => Ok(text.to_string()),
other => other.unexpected(),
}
}
}
+105
View File
@@ -0,0 +1,105 @@
use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind};
use crate::database::Database;
use crate::error::BoxDynError;
use crate::types::Type;
use crate::value::{Value, ValueRef};
use std::borrow::Cow;
use std::sync::Arc;
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum AnyValueKind {
Null(AnyTypeInfoKind),
Bool(bool),
SmallInt(i16),
Integer(i32),
BigInt(i64),
Real(f32),
Double(f64),
Text(Arc<String>),
TextSlice(Arc<str>),
Blob(Arc<Vec<u8>>),
}
impl AnyValueKind {
fn type_info(&self) -> AnyTypeInfo {
AnyTypeInfo {
kind: match self {
AnyValueKind::Null(_) => AnyTypeInfoKind::Null,
AnyValueKind::Bool(_) => AnyTypeInfoKind::Bool,
AnyValueKind::SmallInt(_) => AnyTypeInfoKind::SmallInt,
AnyValueKind::Integer(_) => AnyTypeInfoKind::Integer,
AnyValueKind::BigInt(_) => AnyTypeInfoKind::BigInt,
AnyValueKind::Real(_) => AnyTypeInfoKind::Real,
AnyValueKind::Double(_) => AnyTypeInfoKind::Double,
AnyValueKind::Text(_) => AnyTypeInfoKind::Text,
AnyValueKind::TextSlice(_) => AnyTypeInfoKind::Text,
AnyValueKind::Blob(_) => AnyTypeInfoKind::Blob,
},
}
}
pub(in crate::any) fn unexpected<Expected: Type<Any>>(&self) -> Result<Expected, BoxDynError> {
Err(format!("expected {}, got {:?}", Expected::type_info(), self).into())
}
pub(in crate::any) fn try_integer<T>(&self) -> Result<T, BoxDynError>
where
T: Type<Any> + TryFrom<i16> + TryFrom<i32> + TryFrom<i64>,
BoxDynError: From<<T as TryFrom<i16>>::Error>,
BoxDynError: From<<T as TryFrom<i32>>::Error>,
BoxDynError: From<<T as TryFrom<i64>>::Error>,
{
Ok(match self {
AnyValueKind::SmallInt(i) => (*i).try_into()?,
AnyValueKind::Integer(i) => (*i).try_into()?,
AnyValueKind::BigInt(i) => (*i).try_into()?,
_ => return self.unexpected(),
})
}
}
#[derive(Clone, Debug)]
pub struct AnyValue {
#[doc(hidden)]
pub kind: AnyValueKind,
}
#[derive(Clone, Debug)]
pub struct AnyValueRef<'a> {
pub(crate) kind: &'a AnyValueKind,
}
impl Value for AnyValue {
type Database = Any;
fn as_ref(&self) -> <Self::Database as Database>::ValueRef<'_> {
AnyValueRef { kind: &self.kind }
}
fn type_info(&self) -> Cow<'_, <Self::Database as Database>::TypeInfo> {
Cow::Owned(self.kind.type_info())
}
fn is_null(&self) -> bool {
matches!(self.kind, AnyValueKind::Null(_))
}
}
impl<'a> ValueRef<'a> for AnyValueRef<'a> {
type Database = Any;
fn to_owned(&self) -> <Self::Database as Database>::Value {
AnyValue {
kind: self.kind.clone(),
}
}
fn type_info(&self) -> Cow<'_, <Self::Database as Database>::TypeInfo> {
Cow::Owned(self.kind.type_info())
}
fn is_null(&self) -> bool {
matches!(self.kind, AnyValueKind::Null(_))
}
}