Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
[workspace]
members = ["core", "macros"]

[package]
name = "sqlx-conditional-queries"
version = "0.3.2"
Expand All @@ -14,11 +11,14 @@ categories = ["database"]
[package.metadata.docs.rs]
features = ["postgres"]

[dependencies]
futures-core = "0.3.31"
sqlx-conditional-queries-macros = { path = "macros", version = "0.3" }
[workspace]
members = ["core", "macros"]

[features]
mysql = ["sqlx-conditional-queries-macros/mysql"]
postgres = ["sqlx-conditional-queries-macros/postgres"]
sqlite = ["sqlx-conditional-queries-macros/sqlite"]

[dependencies]
futures-core = "0.3.31"
sqlx-conditional-queries-macros = { path = "macros", version = "0.3" }
39 changes: 27 additions & 12 deletions core/src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ use crate::expand::ExpandedConditionalQueryAs;
/// This is the final step of the macro generation pipeline.
/// The match arms and the respective query fragments are now used to generate a giant match
/// statement, which covers all variants of the bindings' match statements' cartesian products.
pub(crate) fn codegen(expanded: ExpandedConditionalQueryAs) -> proc_macro2::TokenStream {
pub(crate) fn codegen(
expanded: ExpandedConditionalQueryAs,
checked: bool,
) -> proc_macro2::TokenStream {
let mut match_arms = Vec::new();
for (idx, arm) in expanded.match_arms.iter().enumerate() {
let patterns = &arm.patterns;
Expand All @@ -20,10 +23,16 @@ pub(crate) fn codegen(expanded: ExpandedConditionalQueryAs) -> proc_macro2::Toke
None => quote!(#name),
});

let query = if checked {
format_ident!("query_as")
} else {
format_ident!("query_as_unchecked")
};

match_arms.push(quote! {
(#(#patterns,)*) => {
ConditionalMap::#variant(
::sqlx::query_as!(
::sqlx::#query!(
#output_type,
#(#query_fragments)+*,
#(#run_time_bindings),*
Expand Down Expand Up @@ -192,10 +201,13 @@ mod tests {
use super::*;

#[rstest::rstest]
#[case(DatabaseType::PostgreSql)]
#[case(DatabaseType::MySql)]
#[case(DatabaseType::Sqlite)]
fn valid_syntax(#[case] database_type: DatabaseType) {
#[case(DatabaseType::PostgreSql, true)]
#[case(DatabaseType::PostgreSql, false)]
#[case(DatabaseType::MySql, true)]
#[case(DatabaseType::MySql, false)]
#[case(DatabaseType::Sqlite, true)]
#[case(DatabaseType::Sqlite, false)]
fn valid_syntax(#[case] database_type: DatabaseType, #[case] checked: bool) {
let parsed = syn::parse_str::<crate::parse::ParsedConditionalQueryAs>(
r#"
SomeType,
Expand All @@ -214,14 +226,17 @@ mod tests {
let analyzed = crate::analyze::analyze(parsed.clone()).unwrap();
let lowered = crate::lower::lower(analyzed);
let expanded = crate::expand::expand(database_type, lowered).unwrap();
let _codegened = codegen(expanded);
let _codegened = codegen(expanded, checked);
}

#[rstest::rstest]
#[case(DatabaseType::PostgreSql)]
#[case(DatabaseType::MySql)]
#[case(DatabaseType::Sqlite)]
fn type_override(#[case] database_type: DatabaseType) {
#[case(DatabaseType::PostgreSql, true)]
#[case(DatabaseType::PostgreSql, false)]
#[case(DatabaseType::MySql, true)]
#[case(DatabaseType::MySql, false)]
#[case(DatabaseType::Sqlite, true)]
#[case(DatabaseType::Sqlite, false)]
fn type_override(#[case] database_type: DatabaseType, #[case] checked: bool) {
let parsed = syn::parse_str::<crate::parse::ParsedConditionalQueryAs>(
r#"
SomeType,
Expand All @@ -232,7 +247,7 @@ mod tests {
let analyzed = crate::analyze::analyze(parsed.clone()).unwrap();
let lowered = crate::lower::lower(analyzed);
let expanded = crate::expand::expand(database_type, lowered).unwrap();
let codegened = codegen(expanded);
let codegened = codegen(expanded, checked);

let stringified = codegened.to_string();
assert!(
Expand Down
3 changes: 2 additions & 1 deletion core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,13 @@ pub enum Error {
pub fn conditional_query_as(
database_type: DatabaseType,
input: proc_macro2::TokenStream,
checked: bool,
) -> Result<proc_macro2::TokenStream, Error> {
let parsed = syn::parse2::<parse::ParsedConditionalQueryAs>(input)?;
let analyzed = analyze::analyze(parsed)?;
let lowered = lower::lower(analyzed);
let expanded = expand::expand(database_type, lowered)?;
let codegened = codegen::codegen(expanded);
let codegened = codegen::codegen(expanded, checked);

Ok(codegened)
}
57 changes: 39 additions & 18 deletions core/src/snapshot_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,18 @@ fn prettyprint(ts: TokenStream) -> String {
}

#[rstest::rstest]
#[case::postgres(DatabaseType::PostgreSql)]
#[case::mysql(DatabaseType::MySql)]
#[case::sqlite(DatabaseType::Sqlite)]
fn only_runtime_bound_parameters(#[case] database_type: DatabaseType) {
set_snapshot_suffix!("{:?}", database_type);
#[case::postgres(DatabaseType::PostgreSql, true)]
#[case::postgres_unchecked(DatabaseType::PostgreSql, false)]
#[case::mysql(DatabaseType::MySql, true)]
#[case::mysql_unchecked(DatabaseType::MySql, false)]
#[case::sqlite(DatabaseType::Sqlite, true)]
#[case::sqlite_unchecked(DatabaseType::Sqlite, false)]
fn only_runtime_bound_parameters(#[case] database_type: DatabaseType, #[case] checked: bool) {
set_snapshot_suffix!(
"{:?}{}",
database_type,
if checked { "" } else { "_unchecked" }
);
let input = quote::quote! {
OutputType,
r#"
Expand All @@ -36,16 +43,23 @@ fn only_runtime_bound_parameters(#[case] database_type: DatabaseType) {
WHERE created_at > {created_at}
"#,
};
let output = crate::conditional_query_as(database_type, input).unwrap();
let output = crate::conditional_query_as(database_type, input, checked).unwrap();
insta::assert_snapshot!(prettyprint(output));
}

#[rstest::rstest]
#[case::postgres(DatabaseType::PostgreSql)]
#[case::mysql(DatabaseType::MySql)]
#[case::sqlite(DatabaseType::Sqlite)]
fn only_compile_time_bound_parameters(#[case] database_type: DatabaseType) {
set_snapshot_suffix!("{:?}", database_type);
#[case::postgres(DatabaseType::PostgreSql, true)]
#[case::postgres_unchecked(DatabaseType::PostgreSql, false)]
#[case::mysql(DatabaseType::MySql, true)]
#[case::mysql_unchecked(DatabaseType::MySql, false)]
#[case::sqlite(DatabaseType::Sqlite, true)]
#[case::sqlite_unchecked(DatabaseType::Sqlite, false)]
fn only_compile_time_bound_parameters(#[case] database_type: DatabaseType, #[case] checked: bool) {
set_snapshot_suffix!(
"{:?}{}",
database_type,
if checked { "" } else { "_unchecked" }
);
let hash = proc_macro2::Punct::new('#', proc_macro2::Spacing::Alone);
let input = quote::quote! {
OutputType,
Expand All @@ -58,16 +72,23 @@ fn only_compile_time_bound_parameters(#[case] database_type: DatabaseType) {
_ => "value",
},
};
let output = crate::conditional_query_as(database_type, input).unwrap();
let output = crate::conditional_query_as(database_type, input, checked).unwrap();
insta::assert_snapshot!(prettyprint(output));
}

#[rstest::rstest]
#[case::postgres(DatabaseType::PostgreSql)]
#[case::mysql(DatabaseType::MySql)]
#[case::sqlite(DatabaseType::Sqlite)]
fn both_parameter_kinds(#[case] database_type: DatabaseType) {
set_snapshot_suffix!("{:?}", database_type);
#[case::postgres(DatabaseType::PostgreSql, true)]
#[case::postgres_unchecked(DatabaseType::PostgreSql, false)]
#[case::mysql(DatabaseType::MySql, true)]
#[case::mysql_unchecked(DatabaseType::MySql, false)]
#[case::sqlite(DatabaseType::Sqlite, true)]
#[case::sqlite_unchecked(DatabaseType::Sqlite, false)]
fn both_parameter_kinds(#[case] database_type: DatabaseType, #[case] checked: bool) {
set_snapshot_suffix!(
"{:?}{}",
database_type,
if checked { "" } else { "_unchecked" }
);
let hash = proc_macro2::Punct::new('#', proc_macro2::Spacing::Alone);
let input = quote::quote! {
OutputType,
Expand All @@ -82,6 +103,6 @@ fn both_parameter_kinds(#[case] database_type: DatabaseType) {
_ => "value",
},
};
let output = crate::conditional_query_as(database_type, input).unwrap();
let output = crate::conditional_query_as(database_type, input, checked).unwrap();
insta::assert_snapshot!(prettyprint(output));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
---
source: core/src/snapshot_tests.rs
expression: prettyprint(output)
---
fn dummy() {
{
enum ConditionalMap<'q, DB: ::sqlx::Database, A, F0> {
Variant0(::sqlx::query::Map<'q, DB, F0, A>),
}
impl<'q, DB, A, O, F0> ConditionalMap<'q, DB, A, F0>
where
DB: ::sqlx::Database,
A: 'q + ::sqlx::IntoArguments<'q, DB> + ::std::marker::Send,
O: ::std::marker::Unpin + ::std::marker::Send,
F0: ::std::ops::FnMut(DB::Row) -> ::sqlx::Result<O> + ::std::marker::Send,
{
/// See [`sqlx::query::Map::fetch`]
pub fn fetch<'e, 'c: 'e, E>(
self,
executor: E,
) -> ::sqlx_conditional_queries::exports::BoxStream<'e, ::sqlx::Result<O>>
where
'q: 'e,
E: 'e + ::sqlx::Executor<'c, Database = DB>,
DB: 'e,
O: 'e,
F0: 'e,
{
match self {
Self::Variant0(map) => map.fetch(executor),
}
}
/// See [`sqlx::query::Map::fetch_many`]
#[deprecated = "Only the SQLite driver supports multiple statements in one prepared statement and that behavior is deprecated. Use `sqlx::raw_sql()` instead. See https://github.com/launchbadge/sqlx/issues/3108 for discussion."]
pub fn fetch_many<'e, 'c: 'e, E>(
mut self,
executor: E,
) -> ::sqlx_conditional_queries::exports::BoxStream<
'e,
::sqlx::Result<::sqlx::Either<DB::QueryResult, O>>,
>
where
'q: 'e,
E: 'e + ::sqlx::Executor<'c, Database = DB>,
DB: 'e,
O: 'e,
F0: 'e,
{
match self {
Self::Variant0(map) => #[allow(deprecated)] map.fetch_many(executor),
}
}
/// See [`sqlx::query::Map::fetch_all`]
pub async fn fetch_all<'e, 'c: 'e, E>(
self,
executor: E,
) -> ::sqlx::Result<::std::vec::Vec<O>>
where
'q: 'e,
E: 'e + ::sqlx::Executor<'c, Database = DB>,
DB: 'e,
O: 'e,
F0: 'e,
{
match self {
Self::Variant0(map) => map.fetch_all(executor).await,
}
}
/// See [`sqlx::query::Map::fetch_one`]
pub async fn fetch_one<'e, 'c: 'e, E>(self, executor: E) -> ::sqlx::Result<O>
where
'q: 'e,
E: 'e + ::sqlx::Executor<'c, Database = DB>,
DB: 'e,
O: 'e,
F0: 'e,
{
match self {
Self::Variant0(map) => map.fetch_one(executor).await,
}
}
/// See [`sqlx::query::Map::fetch_optional`]
pub async fn fetch_optional<'e, 'c: 'e, E>(
self,
executor: E,
) -> ::sqlx::Result<::std::option::Option<O>>
where
'q: 'e,
E: 'e + ::sqlx::Executor<'c, Database = DB>,
DB: 'e,
O: 'e,
F0: 'e,
{
match self {
Self::Variant0(map) => map.fetch_optional(executor).await,
}
}
}
match (value,) {
(_,) => {
ConditionalMap::Variant0(
::sqlx::query_as_unchecked!(
OutputType,
"\n SELECT column\n FROM table\n WHERE\n created_at > "
+ "" + "?" + "\n AND value = " + "value" +
"\n ", created_at
),
)
}
}
}
}
Loading
Loading