Skip to content

Commit 9a6d07f

Browse files
authored
feat: QueryBuilder improvements (launchbadge#2005)
* get raw SQL * method to build `QueryAs` instead of `Query`
1 parent a2eceec commit 9a6d07f

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

sqlx-core/src/query_builder.rs

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ use std::marker::PhantomData;
77
use crate::arguments::Arguments;
88
use crate::database::{Database, HasArguments};
99
use crate::encode::Encode;
10+
use crate::from_row::FromRow;
1011
use crate::query::Query;
12+
use crate::query_as::QueryAs;
1113
use crate::types::Type;
1214
use crate::Either;
1315

@@ -392,7 +394,6 @@ where
392394
for tuple in tuples {
393395
separated.push("(");
394396

395-
// use a `Separated` with a separate (hah) internal state
396397
push_tuple(separated.query_builder.separated(", "), tuple);
397398

398399
separated.push_unseparated(")");
@@ -425,6 +426,27 @@ where
425426
}
426427
}
427428

429+
/// Produce an executable query from this builder.
430+
///
431+
/// ### Note: Query is not Checked
432+
/// It is your responsibility to ensure that you produce a syntactically correct query here,
433+
/// this API has no way to check it for you.
434+
///
435+
/// ### Note: Reuse
436+
/// You can reuse this builder afterwards to amortize the allocation overhead of the query
437+
/// string, however you must call [`.reset()`][Self::reset] first, which returns `Self`
438+
/// to the state it was in immediately after [`new()`][Self::new].
439+
///
440+
/// Calling any other method but `.reset()` after `.build()` will panic for sanity reasons.
441+
pub fn build_query_as<'q, T: FromRow<'q, DB::Row>>(
442+
&'q mut self,
443+
) -> QueryAs<'q, DB, T, <DB as HasArguments<'args>>::Arguments> {
444+
QueryAs {
445+
inner: self.build(),
446+
output: PhantomData,
447+
}
448+
}
449+
428450
/// Reset this `QueryBuilder` back to its initial state.
429451
///
430452
/// The query is truncated to the initial fragment provided to [`new()`][Self::new] and
@@ -435,6 +457,16 @@ where
435457

436458
self
437459
}
460+
461+
/// Get the current build SQL; **note**: may not be syntactically correct.
462+
pub fn sql(&self) -> &str {
463+
&self.query
464+
}
465+
466+
/// Deconstruct this `QueryBuilder`, returning the built SQL. May not be syntactically correct.
467+
pub fn into_sql(self) -> String {
468+
self.query
469+
}
438470
}
439471

440472
/// A wrapper around `QueryBuilder` for creating comma(or other token)-separated lists.

0 commit comments

Comments
 (0)