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
use crate::{
ColumnDef, Context, Dataset, Driver, DynQuery, Error, Executor, Expression, Query,
QueryBuilder, RawQuery, Result, Row, RowValues, RowsAffected, TableRef, future::Either,
stream::Stream, truncate_long, writer::SqlWriter,
};
use futures::{FutureExt, StreamExt};
use log::Level;
use std::{
future::{self, Future},
pin::pin,
sync::Arc,
};
/// Database entity mapping.
///
/// Use `#[derive(Entity)]` to implement this trait.
pub trait Entity {
/// Primary key type. A tuple of field types (or single type) forming the PK.
type PrimaryKey<'a>
where
Self: 'a;
/// Table reference matching the `#[tank(...)]` attributes.
fn table() -> &'static TableRef;
/// All column definitions in declaration order.
fn columns() -> &'static [ColumnDef];
/// Primary key column definitions. Empty if no PK defined.
fn primary_key_def() -> &'static [&'static ColumnDef];
/// Extract PK value(s) from `self`.
fn primary_key(&self) -> Self::PrimaryKey<'_>;
/// Build an expression matching the PK of `self`.
fn primary_key_expr(&self) -> impl Expression;
/// Unique constraint definitions.
fn unique_defs()
-> impl ExactSizeIterator<Item = impl ExactSizeIterator<Item = &'static ColumnDef>>;
/// Full row representation including all persisted columns.
fn row_values(&self) -> RowValues;
/// Full row representation with column labels.
fn row(&self) -> Row {
Row {
labels: Self::columns()
.into_iter()
.map(|v| v.name().to_string())
.collect::<Arc<[String]>>(),
values: self.row_values(),
}
}
/// Reconstruct `Self` from a labeled row.
///
/// Fails if columns are missing or type conversion fails.
fn from_row(row: Row) -> Result<Self>
where
Self: Sized;
/// Create table (and optional schema).
///
/// - `if_not_exists`: Emits `IF NOT EXISTS` if supported.
/// - `create_schema`: Attempts schema creation first.
fn create_table(
executor: &mut impl Executor,
if_not_exists: bool,
create_schema: bool,
) -> impl Future<Output = Result<()>> + Send
where
Self: Sized,
{
async move {
let mut query = DynQuery::with_capacity(2048);
let writer = executor.driver().sql_writer();
if create_schema && !Self::table().schema.is_empty() {
writer.write_create_schema::<Self>(&mut query, true);
}
if !executor.accepts_multiple_statements() && !query.is_empty() {
let mut q = query.into_query(executor.driver());
executor.execute(&mut q).await?;
// To reuse the allocated buffer
query = q.into();
query.clear();
}
writer.write_create_table::<Self>(&mut query, if_not_exists);
executor.execute(query).await.map(|_| ())
}
}
/// Drop the table (and optional schema).
///
/// - `if_exists`: Emits `IF EXISTS` if supported.
/// - `drop_schema`: Drops schema *after* table removal (if empty).
fn drop_table(
executor: &mut impl Executor,
if_exists: bool,
drop_schema: bool,
) -> impl Future<Output = Result<()>> + Send
where
Self: Sized,
{
async move {
let mut query = DynQuery::with_capacity(256);
let writer = executor.driver().sql_writer();
writer.write_drop_table::<Self>(&mut query, if_exists);
if drop_schema && !Self::table().schema.is_empty() {
if !executor.accepts_multiple_statements() {
let mut q = query.into_query(executor.driver());
executor.execute(&mut q).await?;
// To reuse the allocated buffer
query = q.into();
query.clear();
}
writer.write_drop_schema::<Self>(&mut query, true);
}
executor.execute(query).await.map(|_| ())
}
}
/// Insert a single entity.
fn insert_one(
executor: &mut impl Executor,
entity: &impl Entity,
) -> impl Future<Output = Result<RowsAffected>> + Send {
let mut query = DynQuery::with_capacity(128);
executor
.driver()
.sql_writer()
.write_insert(&mut query, [entity], false);
executor.execute(query)
}
/// Bulk insert entities.
fn insert_many<'a, It>(
executor: &mut impl Executor,
items: It,
) -> impl Future<Output = Result<RowsAffected>> + Send
where
Self: Sized + 'a,
It: IntoIterator<Item = &'a Self> + Send,
<It as IntoIterator>::IntoIter: Send,
{
executor.append(items)
}
/// Prepare (but do not yet run) a SQL select query.
///
/// Returns the prepared statement.
fn prepare_find<Exec: Executor>(
executor: &mut Exec,
condition: impl Expression,
limit: Option<u32>,
) -> impl Future<Output = Result<Query<Exec::Driver>>> {
let builder = QueryBuilder::new()
.select(Self::columns())
.from(Self::table())
.where_expr(condition)
.limit(limit);
let writer = executor.driver().sql_writer();
let mut query = DynQuery::default();
writer.write_select(&mut query, &builder);
async {
if let DynQuery::Raw(RawQuery(sql)) = query {
executor.prepare(sql).await
} else {
Ok(query.into())
}
}
}
/// Finds the first entity matching a condition expression.
///
/// Returns `Ok(None)` if no row matches.
fn find_one(
executor: &mut impl Executor,
condition: impl Expression,
) -> impl Future<Output = Result<Option<Self>>> + Send
where
Self: Sized,
{
let stream = Self::find_many(executor, condition, Some(1));
async move { pin!(stream).into_future().map(|(v, _)| v).await.transpose() }
}
/// Streams entities matching a condition.
///
/// `limit` restricts the maximum number of rows returned at a database level if `Some`
/// (if supported by the driver, unlimited otherwise).
fn find_many(
executor: &mut impl Executor,
condition: impl Expression,
limit: Option<u32>,
) -> impl Stream<Item = Result<Self>> + Send
where
Self: Sized,
{
let builder = QueryBuilder::new()
.select(Self::columns())
.from(Self::table())
.where_expr(condition)
.limit(limit);
executor
.fetch(builder.build(&executor.driver()))
.map(|result| result.and_then(Self::from_row))
}
/// Deletes all entities matching a condition.
///
/// Returns the number of deleted rows.
fn delete_many(
executor: &mut impl Executor,
condition: impl Expression,
) -> impl Future<Output = Result<RowsAffected>> + Send
where
Self: Sized,
{
let mut query = DynQuery::with_capacity(128);
executor
.driver()
.sql_writer()
.write_delete::<Self>(&mut query, condition);
executor.execute(query)
}
/// Saves the entity (insert or update if available) based on primary key presence.
///
/// Errors:
/// - Missing PK in the table.
/// - Execution failures from underlying driver.
fn save(&self, executor: &mut impl Executor) -> impl Future<Output = Result<()>> + Send
where
Self: Sized,
{
if Self::primary_key_def().len() == 0 {
let error = Error::msg(
"Cannot save an entity without a primary key, it would always result in an insert",
);
log::error!("{:#}", error);
return Either::Left(future::ready(Err(error)));
}
let mut query = DynQuery::with_capacity(512);
executor
.driver()
.sql_writer()
.write_insert(&mut query, [self], true);
let sql = query.as_str();
let context = format!("While saving using the query {}", truncate_long!(sql));
Either::Right(executor.execute(query).map(|mut v| {
if let Ok(result) = v
&& let Some(affected) = result.rows_affected
&& affected > 2
{
v = Err(Error::msg(format!(
"The driver returned affected rows: {affected} (expected <= 2)"
)));
}
match v {
Ok(_) => Ok(()),
Err(e) => {
let e = e.context(context);
Err(e)
}
}
}))
}
/// Deletes this entity instance via its primary key.
///
/// Errors:
/// - Missing PK in the table.
/// - If not exactly one row was deleted.
/// - Execution failures from underlying driver.
fn delete(&self, executor: &mut impl Executor) -> impl Future<Output = Result<()>> + Send
where
Self: Sized,
{
if Self::primary_key_def().len() == 0 {
let error = Error::msg(
"Cannot delete an entity without a primary key, it would delete nothing",
);
log::error!("{:#}", error);
return Either::Left(future::ready(Err(error)));
}
Either::Right(
Self::delete_many(executor, self.primary_key_expr()).map(|v| {
v.and_then(|v| {
if let Some(affected) = v.rows_affected {
if affected != 1 {
let error = Error::msg(format!(
"The query deleted {affected} rows instead of the expected 1"
));
log::log!(
if affected == 0 {
Level::Info
} else {
Level::Error
},
"{error}",
);
return Err(error);
}
}
Ok(())
})
}),
)
}
}
impl<E: Entity> Dataset for E {
/// Indicates whether column names should be fully qualified with schema and table name.
///
/// For entities this returns `false` to keep queries concise, for joins it returns `true`.
fn qualified_columns() -> bool
where
Self: Sized,
{
false
}
/// Writes the table reference into the out string.
fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut DynQuery) {
Self::table().write_query(writer, context, out);
}
fn table_ref(&self) -> TableRef {
Self::table().clone()
}
}