sqlxo 0.9.1

sqlxo: small SQL query builder + derives for filterable ORM-ish patterns
Documentation
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
use std::marker::PhantomData;

use sqlx::{
	Executor,
	FromRow,
	Postgres,
};
use sqlxo_traits::{
	Creatable,
	CreateModel,
	JoinNavigationModel,
	QueryContext,
};

use crate::{
	blocks::{
		InsertHead,
		SqlWriter,
	},
	select::{
		self,
		SelectionList,
	},
	Buildable,
	ExecutablePlan,
	FetchablePlan,
	Planable,
	Result,
};

#[allow(dead_code)]
pub trait BuildableInsertQuery<C, Row = <C as QueryContext>::Model>:
	Buildable<C, Row = Row, Plan: Planable<C, Row>>
where
	C: QueryContext,
	Row: Send + Sync + Unpin + for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>,
{
}

pub struct InsertQueryPlan<
	'a,
	C: QueryContext,
	Row = <C as QueryContext>::Model,
> where
	C::Model: Creatable,
{
	pub(crate) table: &'a str,
	pub(crate) create_model: <C::Model as Creatable>::CreateModel,
	pub(crate) insert_marker_field: Option<&'static str>,
	pub(crate) auto_joins: bool,
	pub(crate) include_lazy_relations: bool,
	pub(crate) selection: Option<SelectionList<Row, select::SelectionColumn>>,
	row: PhantomData<Row>,
}

impl<'a, C, Row> InsertQueryPlan<'a, C, Row>
where
	C: QueryContext,
	C::Model: Creatable,
{
	fn to_query_builder(&self) -> sqlx::QueryBuilder<'static, Postgres> {
		let head = InsertHead::new(self.table);
		let mut w = SqlWriter::new(head);

		self.create_model
			.apply_inserts(w.query_builder_mut(), self.insert_marker_field);

		w.into_builder()
	}

	fn push_returning(&self, qb: &mut sqlx::QueryBuilder<'static, Postgres>) {
		select::push_returning(qb, self.table, self.selection.as_ref());
	}

	fn to_execute_with_relations_query_builder(
		&self,
	) -> sqlx::QueryBuilder<'static, Postgres> {
		let mut qb = sqlx::QueryBuilder::<Postgres>::new(
			"WITH affected AS (INSERT INTO ",
		);
		qb.push(self.table);
		self.create_model
			.apply_inserts(&mut qb, self.insert_marker_field);
		qb.push(" RETURNING *)");
		self.create_model.append_relation_ctes(&mut qb, "affected");
		qb.push(" SELECT COUNT(*)::BIGINT AS __sqlxo_count FROM affected");
		qb
	}

	#[cfg(any(test, feature = "test-utils"))]
	pub fn sql(&self) -> String {
		use sqlx::Execute;
		self.to_query_builder().build().sql().to_string()
	}
}

#[async_trait::async_trait]
impl<'a, C, Row> ExecutablePlan<C> for InsertQueryPlan<'a, C, Row>
where
	C: QueryContext,
	C::Model: Creatable,
	Row: Send + Sync + Unpin + for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>,
{
	async fn execute<'e, E>(&self, exec: E) -> Result<u64>
	where
		E: Executor<'e, Database = Postgres>,
	{
		#[derive(sqlx::FromRow)]
		struct CountRow {
			#[sqlx(rename = "__sqlxo_count")]
			count: i64,
		}

		let row: CountRow = self
			.to_execute_with_relations_query_builder()
			.build_query_as::<CountRow>()
			.fetch_one(exec)
			.await?;

		Ok(row.count.max(0) as u64)
	}
}

#[async_trait::async_trait]
impl<'a, C, Row> FetchablePlan<C, Row> for InsertQueryPlan<'a, C, Row>
where
	C: QueryContext,
	C::Model: Creatable,
	Row: Send
		+ Sync
		+ Unpin
		+ for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>
		+ InsertFetchRow<C>,
{
	async fn fetch_one<'e, E>(&self, exec: E) -> Result<Row>
	where
		E: Executor<'e, Database = Postgres>,
	{
		Ok(<Row as InsertFetchRow<C>>::fetch_one(self, exec).await?)
	}

	async fn fetch_all<'e, E>(&self, exec: E) -> Result<Vec<Row>>
	where
		E: Executor<'e, Database = Postgres>,
	{
		Ok(<Row as InsertFetchRow<C>>::fetch_all(self, exec).await?)
	}

	async fn fetch_optional<'e, E>(&self, exec: E) -> Result<Option<Row>>
	where
		E: Executor<'e, Database = Postgres>,
	{
		Ok(<Row as InsertFetchRow<C>>::fetch_optional(self, exec).await?)
	}
}

#[async_trait::async_trait]
trait InsertFetchRow<C: QueryContext>: Sized
where
	C::Model: Creatable,
{
	async fn fetch_one<'a, 'e, E>(
		plan: &InsertQueryPlan<'a, C, Self>,
		exec: E,
	) -> Result<Self>
	where
		E: Executor<'e, Database = Postgres>;

	async fn fetch_all<'a, 'e, E>(
		plan: &InsertQueryPlan<'a, C, Self>,
		exec: E,
	) -> Result<Vec<Self>>
	where
		E: Executor<'e, Database = Postgres>;

	async fn fetch_optional<'a, 'e, E>(
		plan: &InsertQueryPlan<'a, C, Self>,
		exec: E,
	) -> Result<Option<Self>>
	where
		E: Executor<'e, Database = Postgres>;
}

fn push_join_path_inline(
	qb: &mut sqlx::QueryBuilder<'static, Postgres>,
	path: &sqlxo_traits::JoinPath,
	base_table: &str,
) {
	if path.is_empty() {
		return;
	}

	let mut left_alias = base_table.to_string();
	let mut alias_prefix = String::new();

	for segment in path.segments() {
		let join_word = match segment.kind {
			sqlxo_traits::JoinKind::Inner => " INNER JOIN ",
			sqlxo_traits::JoinKind::Left => " LEFT JOIN ",
		};

		if let Some(through) = segment.descriptor.through {
			let mut through_alias = alias_prefix.clone();
			through_alias.push_str(through.alias_segment);
			let clause = format!(
				r#"{join}{table} AS "{alias}" ON "{left}"."{left_field}" = "{alias}"."{right_field}""#,
				join = join_word,
				table = through.table,
				alias = &through_alias,
				left = &left_alias,
				left_field = through.left_field,
				right_field = through.right_field,
			);
			qb.push(clause);
			left_alias = through_alias;
		}

		alias_prefix.push_str(segment.descriptor.alias_segment);
		let right_alias = alias_prefix.clone();

		let clause = format!(
			r#"{join}{table} AS "{alias}" ON "{left}"."{left_field}" = "{alias}"."{right_field}""#,
			join = join_word,
			table = segment.descriptor.right_table,
			alias = &right_alias,
			left = &left_alias,
			left_field = segment.descriptor.left_field,
			right_field = segment.descriptor.right_field,
		);

		qb.push(clause);
		left_alias = right_alias;
	}
}

impl<'a, C> InsertQueryPlan<'a, C, C::Model>
where
	C: QueryContext,
	C::Model: Creatable + JoinNavigationModel,
{
	fn auto_join_paths(&self) -> Vec<sqlxo_traits::JoinPath> {
		if !self.auto_joins {
			return Vec::new();
		}
		C::Model::default_join_paths(self.include_lazy_relations).into_vec()
	}

	fn to_graph_query_builder(
		&self,
		joins: &[sqlxo_traits::JoinPath],
	) -> sqlx::QueryBuilder<'static, Postgres> {
		let mut qb = sqlx::QueryBuilder::<Postgres>::new(
			"WITH affected AS (INSERT INTO ",
		);
		qb.push(self.table);
		self.create_model
			.apply_inserts(&mut qb, self.insert_marker_field);
		qb.push(" RETURNING *)");
		self.create_model.append_relation_ctes(&mut qb, "affected");
		qb.push(" SELECT \"affected\".*");
		self.create_model
			.append_relation_dependency_columns(&mut qb);

		for col in C::Model::collect_join_columns(Some(joins), "") {
			qb.push(", ");
			qb.push(format!(
				r#""{}"."{}" AS "{}""#,
				col.table_alias, col.column, col.alias
			));
		}

		qb.push(" FROM affected");
		for path in joins {
			push_join_path_inline(&mut qb, path, "affected");
		}

		qb
	}

	fn hydrate_graph_rows(
		&self,
		rows: Vec<sqlx::postgres::PgRow>,
		joins: &[sqlxo_traits::JoinPath],
	) -> Result<Vec<C::Model>> {
		let joins_ref = if joins.is_empty() { None } else { Some(joins) };

		let mut models = Vec::with_capacity(rows.len());
		for row in rows {
			let mut model = C::Model::from_row(&row)?;
			model.hydrate_navigations(joins_ref, &row, "")?;
			models.push(model);
		}

		if C::Model::has_collection_joins(joins_ref) {
			return Ok(C::Model::merge_collection_rows(models, joins_ref));
		}

		Ok(models)
	}
}

#[async_trait::async_trait]
impl<C, Row> InsertFetchRow<C> for Row
where
	C: QueryContext,
	C::Model: Creatable,
	Row: Send + Sync + Unpin + for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>,
{
	default async fn fetch_one<'a, 'e, E>(
		plan: &InsertQueryPlan<'a, C, Self>,
		exec: E,
	) -> Result<Self>
	where
		E: Executor<'e, Database = Postgres>,
	{
		let mut qb = plan.to_query_builder();
		plan.push_returning(&mut qb);
		Ok(qb.build_query_as::<Self>().fetch_one(exec).await?)
	}

	default async fn fetch_all<'a, 'e, E>(
		plan: &InsertQueryPlan<'a, C, Self>,
		exec: E,
	) -> Result<Vec<Self>>
	where
		E: Executor<'e, Database = Postgres>,
	{
		let mut qb = plan.to_query_builder();
		plan.push_returning(&mut qb);
		Ok(qb.build_query_as::<Self>().fetch_all(exec).await?)
	}

	default async fn fetch_optional<'a, 'e, E>(
		plan: &InsertQueryPlan<'a, C, Self>,
		exec: E,
	) -> Result<Option<Self>>
	where
		E: Executor<'e, Database = Postgres>,
	{
		let mut qb = plan.to_query_builder();
		plan.push_returning(&mut qb);
		Ok(qb.build_query_as::<Self>().fetch_optional(exec).await?)
	}
}

#[async_trait::async_trait]
impl<C> InsertFetchRow<C> for C::Model
where
	C: QueryContext,
	C::Model: Creatable + JoinNavigationModel + Clone,
{
	async fn fetch_one<'a, 'e, E>(
		plan: &InsertQueryPlan<'a, C, Self>,
		exec: E,
	) -> Result<Self>
	where
		E: Executor<'e, Database = Postgres>,
	{
		if plan.selection.is_some() {
			let mut qb = plan.to_query_builder();
			plan.push_returning(&mut qb);
			return Ok(qb.build_query_as::<Self>().fetch_one(exec).await?);
		}

		let joins = plan.auto_join_paths();
		let rows = plan
			.to_graph_query_builder(&joins)
			.build()
			.fetch_all(exec)
			.await?;
		let mut models = plan.hydrate_graph_rows(rows, &joins)?;
		if let Some(first) = models.first_mut() {
			plan.create_model.apply_relation_payload(first);
		}
		models
			.into_iter()
			.next()
			.ok_or_else(|| sqlx::Error::RowNotFound.into())
	}

	async fn fetch_all<'a, 'e, E>(
		plan: &InsertQueryPlan<'a, C, Self>,
		exec: E,
	) -> Result<Vec<Self>>
	where
		E: Executor<'e, Database = Postgres>,
	{
		if plan.selection.is_some() {
			let mut qb = plan.to_query_builder();
			plan.push_returning(&mut qb);
			return Ok(qb.build_query_as::<Self>().fetch_all(exec).await?);
		}

		let joins = plan.auto_join_paths();
		let rows = plan
			.to_graph_query_builder(&joins)
			.build()
			.fetch_all(exec)
			.await?;
		let mut models = plan.hydrate_graph_rows(rows, &joins)?;
		for model in models.iter_mut() {
			plan.create_model.apply_relation_payload(model);
		}
		Ok(models)
	}

	async fn fetch_optional<'a, 'e, E>(
		plan: &InsertQueryPlan<'a, C, Self>,
		exec: E,
	) -> Result<Option<Self>>
	where
		E: Executor<'e, Database = Postgres>,
	{
		if plan.selection.is_some() {
			let mut qb = plan.to_query_builder();
			plan.push_returning(&mut qb);
			return Ok(qb
				.build_query_as::<Self>()
				.fetch_optional(exec)
				.await?);
		}

		let joins = plan.auto_join_paths();
		let rows = plan
			.to_graph_query_builder(&joins)
			.build()
			.fetch_all(exec)
			.await?;
		let mut models = plan.hydrate_graph_rows(rows, &joins)?;
		if let Some(first) = models.first_mut() {
			plan.create_model.apply_relation_payload(first);
		}
		Ok(models.into_iter().next())
	}
}

impl<'a, C, Row> Planable<C, Row> for InsertQueryPlan<'a, C, Row>
where
	C: QueryContext,
	C::Model: Creatable,
	Row: Send + Sync + Unpin + for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>,
{
}

pub struct InsertQueryBuilder<
	'a,
	C: QueryContext,
	Row = <C as QueryContext>::Model,
> where
	C::Model: Creatable,
{
	pub(crate) table: &'a str,
	pub(crate) create_model: Option<<C::Model as Creatable>::CreateModel>,
	pub(crate) insert_marker_field: Option<&'static str>,
	pub(crate) auto_joins: bool,
	pub(crate) include_lazy_relations: bool,
	pub(crate) selection: Option<SelectionList<Row, select::SelectionColumn>>,
	row: PhantomData<Row>,
}

impl<'a, C, Row> InsertQueryBuilder<'a, C, Row>
where
	C: QueryContext,
	C::Model: Creatable,
{
	pub fn model(
		mut self,
		model: <C::Model as Creatable>::CreateModel,
	) -> Self {
		self.create_model = Some(model);
		self
	}

	pub fn without_auto_joins(mut self) -> Self {
		self.auto_joins = false;
		self
	}

	pub fn include_lazy_relations(mut self) -> Self {
		self.include_lazy_relations = true;
		self
	}
}

impl<'a, C, Row> Buildable<C> for InsertQueryBuilder<'a, C, Row>
where
	C: QueryContext,
	C::Model: Creatable,
	Row: Send + Sync + Unpin + for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>,
{
	type Row = Row;
	type Plan = InsertQueryPlan<'a, C, Row>;

	fn from_ctx() -> Self {
		Self {
			table:                  C::TABLE,
			create_model:           None,
			insert_marker_field:
				<C::Model as Creatable>::INSERT_MARKER_FIELD,
			auto_joins:             true,
			include_lazy_relations: false,
			selection:              None,
			row:                    PhantomData,
		}
	}

	fn build(self) -> Self::Plan {
		let create_model = self
			.create_model
			.expect("create model must be set with .model()");

		InsertQueryPlan {
			table: self.table,
			create_model,
			insert_marker_field: self.insert_marker_field,
			auto_joins: self.auto_joins,
			include_lazy_relations: self.include_lazy_relations,
			selection: self.selection,
			row: PhantomData,
		}
	}
}

impl<'a, C, Row> InsertQueryBuilder<'a, C, Row>
where
	C: QueryContext,
	C::Model: Creatable,
	Row: Send + Sync + Unpin + for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>,
{
	pub fn take<NewRow>(
		self,
		selection: SelectionList<NewRow, select::SelectionEntry>,
	) -> InsertQueryBuilder<'a, C, NewRow>
	where
		NewRow: Send
			+ Sync
			+ Unpin
			+ for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>,
	{
		InsertQueryBuilder {
			table:                  self.table,
			create_model:           self.create_model,
			insert_marker_field:    self.insert_marker_field,
			auto_joins:             self.auto_joins,
			include_lazy_relations: self.include_lazy_relations,
			selection:              Some(selection.expect_columns()),
			row:                    PhantomData,
		}
	}
}

impl<'a, C, Row> BuildableInsertQuery<C, Row> for InsertQueryBuilder<'a, C, Row>
where
	C: QueryContext,
	C::Model: Creatable,
	Row: Send + Sync + Unpin + for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>,
{
}