1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use std::marker::PhantomData;
use crate::SqlTemplate;
use askama::Result;
use futures_core::{Stream, future::BoxFuture, stream::BoxStream};
use futures_util::{FutureExt, StreamExt, TryFutureExt, TryStreamExt, future};
use sqlx_core::{
Either, Error, database::Database, encode::Encode, from_row::FromRow, types::Type,
};
use super::{DatabaseDialect, db_adapter::BackendDB, sql_template_execute::SqlTemplateExecute};
/// Pagination metadata container
#[derive(Debug, PartialEq, Eq)]
pub struct PageInfo {
/// Total number of records
pub total: i64,
/// Records per page
pub page_size: i64,
/// Calculated page count
pub page_count: i64,
}
impl PageInfo {
/// Constructs new PageInfo with automatic page count calculation
///
/// # Arguments
/// * `total` - Total records in dataset
/// * `page_size` - Desired records per page
pub fn new(total: i64, page_size: i64) -> PageInfo {
let mut page_count = total / page_size;
if total % page_size > 0 {
page_count += 1;
}
Self {
total,
page_size,
page_count,
}
}
}
/// Database adapter manager handling SQL rendering and execution
///
/// # Generic Parameters
/// - `'q`: Query lifetime
/// - `DB`: Database type
/// - `T`: SQL template type
pub struct DBAdapterManager<'q, DB, T>
where
DB: Database,
T: SqlTemplate<'q, DB>,
{
pub(crate) sql: String,
pub(crate) template: T,
persistent: bool,
_p: PhantomData<&'q DB>,
page_size: Option<i64>,
page_no: Option<i64>,
}
impl<'q, DB, T> DBAdapterManager<'q, DB, T>
where
DB: Database,
T: SqlTemplate<'q, DB>,
{
/// Creates new adapter with SQL buffer
///
/// # Arguments
/// * `template` - SQL template instance
pub fn new(template: T) -> Self {
Self {
sql: String::new(),
template,
persistent: true,
page_no: None,
page_size: None,
_p: PhantomData,
}
}
pub fn sql(&self) -> &String {
&self.sql
}
}
impl<'q, 'c, 'e, DB, T> DBAdapterManager<'q, DB, T>
where
DB: Database + Sync,
T: SqlTemplate<'q, DB> + Send + 'q,
i64: Encode<'q, DB> + Type<DB>,
DB::Arguments<'q>: 'q,
'q: 'e,
'c: 'e,
{
/// Configures query persistence (default: true)
pub fn set_persistent(mut self, persistent: bool) -> Self {
self.persistent = persistent;
self
}
/// Executes count query for pagination
///
/// # Arguments
/// * `db_adapter` - Database connection adapter
#[inline]
pub fn count<Adapter>(&'q mut self, db_adapter: Adapter) -> BoxFuture<'e, Result<i64, Error>>
where
Adapter: BackendDB<'c, DB> + 'c,
(i64,): for<'r> FromRow<'r, DB::Row>,
{
let template = self.template.clone();
async move {
let (db_type, executor) = db_adapter.backend_db().await?;
let f = db_type.get_encode_placeholder_fn();
let mut sql = String::new();
let arg = template.render_sql_with_encode_placeholder_fn(f, &mut sql)?;
db_type.write_count_sql(&mut sql);
self.sql = sql;
let execute = SqlTemplateExecute::new(&self.sql, arg).set_persistent(self.persistent);
let (count,): (i64,) = execute.fetch_one_as(executor).await?;
Ok(count)
}
.boxed()
}
/// Calculates complete pagination metadata
///
/// # Arguments
/// * `page_size` - Records per page
/// * `db_adapter` - Database connection adapter
#[inline]
pub async fn count_page<Adapter>(
&'q mut self,
page_size: i64,
db_adapter: Adapter,
) -> Result<PageInfo, Error>
where
Adapter: BackendDB<'c, DB> + 'c,
(i64,): for<'r> FromRow<'r, DB::Row>,
{
let count = self.count(db_adapter).await?;
Ok(PageInfo::new(count, page_size))
}
/// Sets pagination parameters
pub fn set_page(mut self, page_size: i64, page_no: i64) -> Self {
self.page_no = Some(page_no);
self.page_size = Some(page_size);
self
}
/// like sqlx::Query::execute
/// Execute the query and return the number of rows affected.
#[inline]
pub async fn execute<Adapter>(
&'q mut self,
db_adapter: Adapter,
) -> Result<DB::QueryResult, Error>
where
Adapter: BackendDB<'c, DB> + 'c,
{
self.execute_many(db_adapter).try_collect().await
}
/// like sqlx::Query::execute_many
/// Execute multiple queries and return the rows affected from each query, in a stream.
#[inline]
pub fn execute_many<Adapter>(
&'q mut self,
db_adapter: Adapter,
) -> impl Stream<Item = Result<DB::QueryResult, Error>>
where
Adapter: BackendDB<'c, DB> + 'c,
{
self.fetch_many(db_adapter)
.try_filter_map(|step| async move {
Ok(match step {
Either::Left(rows) => Some(rows),
Either::Right(_) => None,
})
})
}
/// like sqlx::Query::fetch
/// Execute the query and return the generated results as a stream.
#[inline]
pub fn fetch<Adapter>(
&'q mut self,
db_adapter: Adapter,
) -> impl Stream<Item = Result<DB::Row, Error>>
where
Adapter: BackendDB<'c, DB> + 'c,
{
self.fetch_many(db_adapter)
.try_filter_map(|step| async move {
Ok(match step {
Either::Left(_) => None,
Either::Right(row) => Some(row),
})
})
}
/// like sqlx::Query::fetch_many
/// Execute multiple queries and return the generated results as a stream.
///
/// For each query in the stream, any generated rows are returned first,
/// then the `QueryResult` with the number of rows affected.
#[inline]
#[allow(clippy::type_complexity)]
pub fn fetch_many<Adapter>(
&'q mut self,
db_adapter: Adapter,
) -> BoxStream<'e, Result<Either<DB::QueryResult, DB::Row>, Error>>
where
Adapter: BackendDB<'c, DB> + 'c,
{
let template = self.template.clone();
let page_no = self.page_no;
let page_size = self.page_size;
Box::pin(async_stream::try_stream! {
let (db_type, executor) = db_adapter.backend_db().await?;
let f = db_type.get_encode_placeholder_fn();
let mut sql = String::new();
let mut arg = template.render_sql_with_encode_placeholder_fn(f, &mut sql)?;
if let (Some(page_no), Some(page_size)) = (page_no, page_size) {
let mut args = arg.unwrap_or_default();
db_type.write_page_sql(&mut sql, page_size, page_no, &mut args)?;
arg = Some(args);
}
self.sql = sql;
let execute = SqlTemplateExecute::new(&self.sql, arg).set_persistent(self.persistent);
let mut stream = execute.fetch_many(executor);
while let Some(item) = stream.try_next().await? {
yield item;
}
})
}
/// like sqlx::Query::fetch_all
/// Execute the query and return all the resulting rows collected into a [`Vec`].
///
/// ### Note: beware result set size.
/// This will attempt to collect the full result set of the query into memory.
///
/// To avoid exhausting available memory, ensure the result set has a known upper bound,
/// e.g. using `LIMIT`.
#[inline]
pub async fn fetch_all<Adapter>(
&'q mut self,
db_adapter: Adapter,
) -> Result<Vec<DB::Row>, Error>
where
Adapter: BackendDB<'c, DB> + 'c,
{
self.fetch(db_adapter).try_collect().await
}
/// like sqlx::Query::fetch_one
/// Execute the query, returning the first row or [`Error::RowNotFound`] otherwise.
///
/// ### Note: for best performance, ensure the query returns at most one row.
/// Depending on the driver implementation, if your query can return more than one row,
/// it may lead to wasted CPU time and bandwidth on the database server.
///
/// Even when the driver implementation takes this into account, ensuring the query returns at most one row
/// can result in a more optimal query plan.
///
/// If your query has a `WHERE` clause filtering a unique column by a single value, you're good.
///
/// Otherwise, you might want to add `LIMIT 1` to your query.
#[inline]
pub async fn fetch_one<Adapter>(&'q mut self, db_adapter: Adapter) -> Result<DB::Row, Error>
where
Adapter: BackendDB<'c, DB> + 'c,
{
self.fetch_optional(db_adapter)
.and_then(|row| match row {
Some(row) => future::ok(row),
None => future::err(Error::RowNotFound),
})
.await
}
/// like sqlx::Query::fetch_optional
/// Execute the query, returning the first row or `None` otherwise.
///
/// ### Note: for best performance, ensure the query returns at most one row.
/// Depending on the driver implementation, if your query can return more than one row,
/// it may lead to wasted CPU time and bandwidth on the database server.
///
/// Even when the driver implementation takes this into account, ensuring the query returns at most one row
/// can result in a more optimal query plan.
///
/// If your query has a `WHERE` clause filtering a unique column by a single value, you're good.
///
/// Otherwise, you might want to add `LIMIT 1` to your query.
#[inline]
pub async fn fetch_optional<Adapter>(
&'q mut self,
db_adapter: Adapter,
) -> Result<Option<DB::Row>, Error>
where
Adapter: BackendDB<'c, DB> + 'c,
{
let row = self.fetch_many(db_adapter).try_next().await?;
match row {
Some(Either::Right(row)) => Ok(Some(row)),
Some(Either::Left(_)) => Ok(None),
None => Ok(None),
}
}
/// like sqlx::QueryAs::fetch
/// Execute the query and return the generated results as a stream.
pub async fn fetch_as<Adapter, O>(
&'q mut self,
db_adapter: Adapter,
) -> impl Stream<Item = Result<O, Error>>
where
Adapter: BackendDB<'c, DB> + 'c,
O: Send + Unpin + for<'r> FromRow<'r, DB::Row> + 'e,
{
self.fetch_many_as(db_adapter)
.try_filter_map(|step| async move { Ok(step.right()) })
}
/// like sqlx::QueryAs::fetch_many
/// Execute multiple queries and return the generated results as a stream
/// from each query, in a stream.
pub fn fetch_many_as<Adapter, O>(
&'q mut self,
db_adapter: Adapter,
) -> BoxStream<'e, Result<Either<DB::QueryResult, O>, Error>>
where
Adapter: BackendDB<'c, DB> + 'c,
O: Send + Unpin + for<'r> FromRow<'r, DB::Row> + 'e,
{
let template = self.template.clone();
let page_no = self.page_no;
let page_size = self.page_size;
Box::pin(async_stream::try_stream! {
let (db_type, executor) = db_adapter.backend_db().await?;
let f = db_type.get_encode_placeholder_fn();
let mut sql = String::new();
let mut arg = template.render_sql_with_encode_placeholder_fn(f, &mut sql)?;
if let (Some(page_no), Some(page_size)) = (page_no, page_size) {
let mut args = arg.unwrap_or_default();
db_type.write_page_sql(&mut sql, page_size, page_no, &mut args)?;
arg = Some(args);
}
self.sql = sql;
let execute = SqlTemplateExecute::new(&self.sql, arg).set_persistent(self.persistent);
let mut stream = execute.fetch_many(executor).map(|v| match v {
Ok(Either::Right(row)) => O::from_row(&row).map(Either::Right),
Ok(Either::Left(v)) => Ok(Either::Left(v)),
Err(e) => Err(e),
});
while let Some(item) = stream.try_next().await? {
yield item;
}
})
}
/// like sqlx::QueryAs::fetch_all
/// Execute the query and return all the resulting rows collected into a [`Vec`].
///
/// ### Note: beware result set size.
/// This will attempt to collect the full result set of the query into memory.
///
/// To avoid exhausting available memory, ensure the result set has a known upper bound,
/// e.g. using `LIMIT`.
#[inline]
pub async fn fetch_all_as<Adapter, O>(
&'q mut self,
db_adapter: Adapter,
) -> Result<Vec<O>, Error>
where
Adapter: BackendDB<'c, DB> + 'c,
O: Send + Unpin + for<'r> FromRow<'r, DB::Row> + 'e,
{
self.fetch_as(db_adapter).await.try_collect().await
}
/// like sqlx::QueryAs::fetch_one
/// Execute the query, returning the first row or [`Error::RowNotFound`] otherwise.
///
/// ### Note: for best performance, ensure the query returns at most one row.
/// Depending on the driver implementation, if your query can return more than one row,
/// it may lead to wasted CPU time and bandwidth on the database server.
///
/// Even when the driver implementation takes this into account, ensuring the query returns at most one row
/// can result in a more optimal query plan.
///
/// If your query has a `WHERE` clause filtering a unique column by a single value, you're good.
///
/// Otherwise, you might want to add `LIMIT 1` to your query.
pub async fn fetch_one_as<Adapter, O>(&'q mut self, db_adapter: Adapter) -> Result<O, Error>
where
Adapter: BackendDB<'c, DB> + 'c,
O: Send + Unpin + for<'r> FromRow<'r, DB::Row> + 'e,
{
self.fetch_optional_as(db_adapter)
.and_then(|o| match o {
Some(o) => future::ok(o),
None => future::err(Error::RowNotFound),
})
.await
}
/// like sqlx::QueryAs::fetch_optional
/// Execute the query, returning the first row or `None` otherwise.
///
/// ### Note: for best performance, ensure the query returns at most one row.
/// Depending on the driver implementation, if your query can return more than one row,
/// it may lead to wasted CPU time and bandwidth on the database server.
///
/// Even when the driver implementation takes this into account, ensuring the query returns at most one row
/// can result in a more optimal query plan.
///
/// If your query has a `WHERE` clause filtering a unique column by a single value, you're good.
///
/// Otherwise, you might want to add `LIMIT 1` to your query.
pub async fn fetch_optional_as<Adapter, O>(
&'q mut self,
db_adapter: Adapter,
) -> Result<Option<O>, Error>
where
Adapter: BackendDB<'c, DB> + 'c,
O: Send + Unpin + for<'r> FromRow<'r, DB::Row>,
{
let obj = self.fetch_many_as(db_adapter).try_next().await?;
match obj {
Some(Either::Right(o)) => Ok(Some(o)),
Some(Either::Left(_)) => Ok(None),
None => Ok(None),
}
}
}