Skip to content

Commit

Permalink
chore!: prep!() to query!()
Browse files Browse the repository at this point in the history
  • Loading branch information
kumavale committed Dec 31, 2024
1 parent 5b2264c commit 6699f6a
Show file tree
Hide file tree
Showing 18 changed files with 1,431 additions and 876 deletions.
69 changes: 49 additions & 20 deletions concatsql/src/connection.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,51 @@
use std::fmt;
use std::cell::Cell;
use std::borrow::Cow;
use std::cell::Cell;
use std::fmt;

use crate::Result;
use crate::ErrorLevel;
use crate::row::Row;
use crate::wrapstring::{WrapString, IntoWrapString};
use crate::value::Value;
use crate::wrapstring::{IntoWrapString, WrapString};
use crate::ErrorLevel;
use crate::Result;

#[allow(clippy::type_complexity)]
pub(crate) trait ConcatsqlConn {
fn execute_inner<'a>(&self, query: Cow<'a, str>, params: &[Value<'a>], error_level: &crate::ErrorLevel) -> Result<()>;
fn iterate_inner<'a>(&self, query: Cow<'a, str>, params: &[Value<'a>], error_level: &crate::ErrorLevel,
callback: &mut dyn FnMut(&[(&str, Option<&str>)]) -> bool) -> Result<()>;
fn rows_inner<'a, 'r>(&self, query: Cow<'a, str>, params: &[Value<'a>], error_level: &crate::ErrorLevel)
-> Result<Vec<Row<'r>>>;
fn execute_inner<'a>(
&self,
query: Cow<'a, str>,
params: &[Value<'a>],
error_level: &crate::ErrorLevel,
) -> Result<()>;
fn iterate_inner<'a>(
&self,
query: Cow<'a, str>,
params: &[Value<'a>],
error_level: &crate::ErrorLevel,
callback: &mut dyn FnMut(&[(&str, Option<&str>)]) -> bool,
) -> Result<()>;
fn rows_inner<'a, 'r>(
&self,
query: Cow<'a, str>,
params: &[Value<'a>],
error_level: &crate::ErrorLevel,
) -> Result<Vec<Row<'r>>>;
fn close(&self);
fn kind(&self) -> ConnKind;
}

#[doc(hidden)]
pub enum ConnKind {
#[cfg(feature = "sqlite")] SQLite,
#[cfg(feature = "mysql")] MySQL,
#[cfg(feature = "postgres")] PostgreSQL,
#[cfg(feature = "sqlite")]
SQLite,
#[cfg(feature = "mysql")]
MySQL,
#[cfg(feature = "postgres")]
PostgreSQL,
}

/// A database connection.
pub struct Connection {
pub(crate) conn: Box<dyn ConcatsqlConn>,
pub(crate) conn: Box<dyn ConcatsqlConn>,
pub(crate) error_level: Cell<ErrorLevel>,
}

Expand Down Expand Up @@ -67,7 +84,11 @@ impl<'a> Connection {
/// ```
#[inline]
pub fn execute<T: IntoWrapString<'a>>(&self, query: T) -> Result<()> {
self.conn.execute_inner(query.compile(self.conn.kind()), query.params(), &self.error_level.get())
self.conn.execute_inner(
query.compile(self.conn.kind()),
query.params(),
&self.error_level.get(),
)
}

/// Execute a statement and process the resulting rows as plain text.
Expand All @@ -94,10 +115,15 @@ impl<'a> Connection {
/// ```
#[inline]
pub fn iterate<T: IntoWrapString<'a>, F>(&self, query: T, mut callback: F) -> Result<()>
where
F: FnMut(&[(&str, Option<&str>)]) -> bool,
where
F: FnMut(&[(&str, Option<&str>)]) -> bool,
{
self.conn.iterate_inner(query.compile(self.conn.kind()), query.params(), &self.error_level.get(), &mut callback)
self.conn.iterate_inner(
query.compile(self.conn.kind()),
query.params(),
&self.error_level.get(),
&mut callback,
)
}

/// Execute a statement and returns the rows.
Expand All @@ -119,7 +145,11 @@ impl<'a> Connection {
/// ```
#[inline]
pub fn rows<'r, T: IntoWrapString<'a>>(&self, query: T) -> Result<Vec<Row<'r>>> {
self.conn.rows_inner(query.compile(self.conn.kind()), query.params(), &self.error_level.get())
self.conn.rows_inner(
query.compile(self.conn.kind()),
query.params(),
&self.error_level.get(),
)
}

/// Sets the error level.
Expand Down Expand Up @@ -170,4 +200,3 @@ impl Drop for Connection {
pub unsafe fn without_escape<T: ?Sized + ToString>(query: &T) -> WrapString {
WrapString::new(query)
}

53 changes: 31 additions & 22 deletions concatsql/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,28 +41,36 @@ impl Default for ErrorLevel {

impl Error {
#[allow(unused_variables)]
pub(crate) fn new<E1, E2>(error_level: &ErrorLevel, err_msg: E1, detail_msg: E2) -> Result<(), Error>
where
E1: ToString,
E2: ToString,
pub(crate) fn new<E1, E2>(
error_level: &ErrorLevel,
err_msg: E1,
detail_msg: E2,
) -> Result<(), Error>
where
E1: ToString,
E2: ToString,
{
match error_level {
ErrorLevel::AlwaysOk => Ok(()),
ErrorLevel::Release => Err(Error::AnyError),
ErrorLevel::Develop => Err(Error::Message(err_msg.to_string())),
ErrorLevel::Release => Err(Error::AnyError),
ErrorLevel::Develop => Err(Error::Message(err_msg.to_string())),
#[cfg(debug_assertions)]
ErrorLevel::Debug => Err(Error::Message(err_msg.to_string() + ": " + &detail_msg.to_string())),
ErrorLevel::Debug => Err(Error::Message(
err_msg.to_string() + ": " + &detail_msg.to_string(),
)),
}
}
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}",
write!(
f,
"{}",
match self {
Error::Message(s) => s.to_string(),
Error::AnyError => String::from("AnyError"),
Error::ParseError => String::from("ParseError"),
Error::Message(s) => s.to_string(),
Error::AnyError => String::from("AnyError"),
Error::ParseError => String::from("ParseError"),
Error::ColumnNotFound => String::from("ColumnNotFound"),
}
)
Expand All @@ -84,18 +92,19 @@ mod tests {
fn errors() {
assert_eq!(ErrorLevel::default(), ErrorLevel::Develop);
assert_eq!(Error::Message("test".to_string()).to_string(), "test");
assert_eq!(Error::new(&ErrorLevel::AlwaysOk, "test", "test"), Ok(()));
assert_eq!(
Error::new(&ErrorLevel::AlwaysOk, "test", "test"),
Ok(()));
Error::new(&ErrorLevel::Release, "test", "test"),
Err(Error::AnyError)
);
assert_eq!(
Error::new(&ErrorLevel::Release, "test", "test"),
Err(Error::AnyError));
Error::new(&ErrorLevel::Develop, "test", "test"),
Err(Error::Message("test".into()))
);
assert_eq!(
Error::new(&ErrorLevel::Develop, "test", "test"),
Err(Error::Message("test".into())));
assert_eq!(
Error::new(&ErrorLevel::Debug, "test", "test"),
Err(Error::Message("test: test".into())));
Error::new(&ErrorLevel::Debug, "test", "test"),
Err(Error::Message("test: test".into()))
);
}

#[test]
Expand All @@ -110,11 +119,11 @@ mod tests {
conn.execute({
conn.error_level(ErrorLevel::Develop);
"SELECT 1"
}).unwrap();
})
.unwrap();
conn.error_level({
conn.execute("SELECT 1").unwrap();
ErrorLevel::Develop
});
}
}

45 changes: 24 additions & 21 deletions concatsql/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,46 +38,46 @@ mod connection;
mod error;
mod parser;
mod row;
mod wrapstring;
mod value;
mod wrapstring;

#[cfg(feature = "sqlite")]
#[cfg_attr(docsrs, doc(cfg(feature = "sqlite")))]
pub mod sqlite;
#[cfg(feature = "mysql")]
#[cfg_attr(docsrs, doc(cfg(feature = "mysql")))]
pub mod mysql;
#[cfg(feature = "postgres")]
#[cfg_attr(docsrs, doc(cfg(feature = "postgres")))]
pub mod postgres;
#[cfg(feature = "sqlite")]
#[cfg_attr(docsrs, doc(cfg(feature = "sqlite")))]
pub mod sqlite;

pub use crate::connection::{Connection, without_escape};
pub use crate::connection::{without_escape, Connection};
pub use crate::error::{Error, ErrorLevel};
pub use crate::row::{Row, Get, FromSql};
pub use crate::parser::{html_special_chars, _sanitize_like, invalid_literal};
pub use crate::wrapstring::{WrapString, IntoWrapString};
pub use crate::value::{Value, ToValue};
pub use crate::parser::{_sanitize_like, html_special_chars, invalid_literal};
pub use crate::row::{FromSql, Get, Row};
pub use crate::value::{ToValue, Value};
pub use crate::wrapstring::{IntoWrapString, WrapString};

pub use concatsql_macro::query;

pub mod prelude {
//! Re-exports important traits and types.
#[cfg(feature = "sqlite")]
#[cfg_attr(docsrs, doc(cfg(feature = "sqlite")))]
pub use crate::sqlite;
#[cfg(feature = "mysql")]
#[cfg_attr(docsrs, doc(cfg(feature = "mysql")))]
pub use crate::mysql;
#[cfg(feature = "postgres")]
#[cfg_attr(docsrs, doc(cfg(feature = "postgres")))]
pub use crate::postgres;
#[cfg(feature = "sqlite")]
#[cfg_attr(docsrs, doc(cfg(feature = "sqlite")))]
pub use crate::sqlite;

pub use crate::connection::{Connection, without_escape};
pub use crate::row::{Row, Get, FromSql};
pub use crate::{sanitize_like, params};
pub use crate::connection::{without_escape, Connection};
pub use crate::row::{FromSql, Get, Row};
pub use crate::value::{ToValue, Value};
pub use crate::wrapstring::WrapString;
pub use crate::value::{Value, ToValue};
pub use crate::{params, sanitize_like};
pub use concatsql_macro::query;
}

Expand Down Expand Up @@ -120,12 +120,16 @@ pub type Result<T, E = crate::error::Error> = std::result::Result<T, E>;
/// prep!("INSERT INTO msg VALUES (\"I'm cat.\")");
/// prep!("INSERT INTO msg VALUES (") + "I'm cat." + prep!(")");
/// ```
#[deprecated(note="please use `query!` instead")]
#[deprecated(note = "please use `query!` instead")]
#[allow(deprecated)]
#[macro_export]
macro_rules! prep {
() => { $crate::WrapString::null() };
($query:expr) => { $crate::WrapString::init($query) };
() => {
$crate::WrapString::null()
};
($query:expr) => {
$crate::WrapString::init($query)
};
}

/// Prepare a SQL statement for execution.
Expand Down Expand Up @@ -165,7 +169,7 @@ macro_rules! prep {
/// prep("INSERT INTO msg VALUES (") + "I'm cat." + prep(")");
/// ```
#[inline]
#[deprecated(note="please use `query!` instead")]
#[deprecated(note = "please use `query!` instead")]
#[allow(deprecated)]
pub fn prep(query: &'static str) -> WrapString {
WrapString::init(query)
Expand All @@ -188,4 +192,3 @@ macro_rules! params {
&[ $(&$param as &dyn $crate::ToValue),+ ] as &[&dyn $crate::ToValue]
};
}

Loading

0 comments on commit 6699f6a

Please sign in to comment.