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
//! JOIN clause types.
use crate::expr::{Dialect, Expr, adjust_placeholder_indices};
use crate::subquery::SelectQuery;
use sqlmodel_core::Value;
/// A JOIN clause.
#[derive(Debug, Clone)]
pub struct Join {
/// Type of join
pub join_type: JoinType,
/// Table to join (table name or subquery SQL)
pub table: String,
/// Optional table alias
pub alias: Option<String>,
/// ON condition
pub on: Expr,
/// Whether this is a LATERAL join (subquery can reference outer query columns).
///
/// Supported by PostgreSQL and MySQL 8.0+. Not supported by SQLite.
pub lateral: bool,
/// Whether the table field contains a subquery (wrapped in parentheses).
pub is_subquery: bool,
/// Parameters from a subquery table expression.
pub subquery_params: Vec<Value>,
/// Deferred subquery builder (dialect-aware).
pub subquery: Option<Box<SelectQuery>>,
}
/// Types of SQL joins.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JoinType {
Inner,
Left,
Right,
Full,
Cross,
}
impl JoinType {
/// Get the SQL keyword for this join type.
pub const fn as_str(&self) -> &'static str {
match self {
JoinType::Inner => "INNER JOIN",
JoinType::Left => "LEFT JOIN",
JoinType::Right => "RIGHT JOIN",
JoinType::Full => "FULL JOIN",
JoinType::Cross => "CROSS JOIN",
}
}
}
impl Join {
/// Create an INNER JOIN.
pub fn inner(table: impl Into<String>, on: Expr) -> Self {
Self {
join_type: JoinType::Inner,
table: table.into(),
alias: None,
on,
lateral: false,
is_subquery: false,
subquery_params: Vec::new(),
subquery: None,
}
}
/// Create a LEFT JOIN.
pub fn left(table: impl Into<String>, on: Expr) -> Self {
Self {
join_type: JoinType::Left,
table: table.into(),
alias: None,
on,
lateral: false,
is_subquery: false,
subquery_params: Vec::new(),
subquery: None,
}
}
/// Create a RIGHT JOIN.
pub fn right(table: impl Into<String>, on: Expr) -> Self {
Self {
join_type: JoinType::Right,
table: table.into(),
alias: None,
on,
lateral: false,
is_subquery: false,
subquery_params: Vec::new(),
subquery: None,
}
}
/// Create a FULL OUTER JOIN.
pub fn full(table: impl Into<String>, on: Expr) -> Self {
Self {
join_type: JoinType::Full,
table: table.into(),
alias: None,
on,
lateral: false,
is_subquery: false,
subquery_params: Vec::new(),
subquery: None,
}
}
/// Create a CROSS JOIN (no ON condition needed, but we require one for uniformity).
pub fn cross(table: impl Into<String>) -> Self {
Self {
join_type: JoinType::Cross,
table: table.into(),
alias: None,
on: Expr::raw("TRUE"), // Dummy condition for cross join
lateral: false,
is_subquery: false,
subquery_params: Vec::new(),
subquery: None,
}
}
/// Create a LATERAL JOIN with a subquery.
///
/// A LATERAL subquery can reference columns from preceding FROM items.
/// Supported by PostgreSQL (9.3+) and MySQL (8.0.14+). Not supported by SQLite.
///
/// # Arguments
///
/// * `join_type` - The join type (typically `JoinType::Inner` or `JoinType::Left`)
/// * `subquery_sql` - The subquery SQL (without parentheses)
/// * `alias` - Required alias for the lateral subquery
/// * `on` - ON condition (use `Expr::raw("TRUE")` for implicit join)
/// * `params` - Parameters for the subquery
pub fn lateral(
join_type: JoinType,
subquery_sql: impl Into<String>,
alias: impl Into<String>,
on: Expr,
params: Vec<Value>,
) -> Self {
Self {
join_type,
table: subquery_sql.into(),
alias: Some(alias.into()),
on,
lateral: true,
is_subquery: true,
subquery_params: params,
subquery: None,
}
}
/// Create a LATERAL JOIN with a deferred subquery builder.
pub fn lateral_query(
join_type: JoinType,
subquery: SelectQuery,
alias: impl Into<String>,
on: Expr,
) -> Self {
Self {
join_type,
table: String::new(),
alias: Some(alias.into()),
on,
lateral: true,
is_subquery: true,
subquery_params: Vec::new(),
subquery: Some(Box::new(subquery)),
}
}
/// Create a LEFT JOIN LATERAL (most common form).
///
/// Shorthand for `Join::lateral(JoinType::Left, ...)`.
pub fn left_lateral(
subquery_sql: impl Into<String>,
alias: impl Into<String>,
on: Expr,
params: Vec<Value>,
) -> Self {
Self::lateral(JoinType::Left, subquery_sql, alias, on, params)
}
/// Create an INNER JOIN LATERAL.
pub fn inner_lateral(
subquery_sql: impl Into<String>,
alias: impl Into<String>,
on: Expr,
params: Vec<Value>,
) -> Self {
Self::lateral(JoinType::Inner, subquery_sql, alias, on, params)
}
/// Create a CROSS JOIN LATERAL (no ON condition).
pub fn cross_lateral(
subquery_sql: impl Into<String>,
alias: impl Into<String>,
params: Vec<Value>,
) -> Self {
Self {
join_type: JoinType::Cross,
table: subquery_sql.into(),
alias: Some(alias.into()),
on: Expr::raw("TRUE"),
lateral: true,
is_subquery: true,
subquery_params: params,
subquery: None,
}
}
/// Set an alias for the joined table.
pub fn alias(mut self, alias: impl Into<String>) -> Self {
self.alias = Some(alias.into());
self
}
/// Mark this join as LATERAL.
pub fn set_lateral(mut self) -> Self {
self.lateral = true;
self
}
/// Generate SQL for this JOIN clause and collect parameters.
///
/// Returns a tuple of (sql, params) since the ON condition may contain
/// literal values that need to be bound as parameters.
pub fn to_sql(&self) -> (String, Vec<Value>) {
let mut params = Vec::new();
let sql = self.build_sql(Dialect::default(), &mut params, 0);
(sql, params)
}
/// Generate SQL for this JOIN clause with a specific dialect.
pub fn to_sql_with_dialect(&self, dialect: Dialect) -> (String, Vec<Value>) {
let mut params = Vec::new();
let sql = self.build_sql(dialect, &mut params, 0);
(sql, params)
}
/// Generate SQL and collect parameters.
pub fn build(&self, params: &mut Vec<Value>, offset: usize) -> String {
self.build_sql(Dialect::default(), params, offset)
}
/// Generate SQL and collect parameters with a specific dialect.
pub fn build_with_dialect(
&self,
dialect: Dialect,
params: &mut Vec<Value>,
offset: usize,
) -> String {
self.build_sql(dialect, params, offset)
}
fn build_sql(&self, dialect: Dialect, params: &mut Vec<Value>, offset: usize) -> String {
let lateral_keyword = if self.lateral { " LATERAL" } else { "" };
let (table_ref, subquery_params) = if let Some(subquery) = &self.subquery {
let start_idx = offset + params.len();
let (subquery_sql, subquery_params) = subquery.build_with_dialect(dialect);
let adjusted_subquery = if subquery_params.is_empty() {
subquery_sql
} else {
adjust_placeholder_indices(&subquery_sql, start_idx, dialect)
};
(format!("({})", adjusted_subquery), subquery_params)
} else if self.is_subquery {
let start_idx = offset + params.len();
let adjusted_subquery = if self.subquery_params.is_empty() {
self.table.clone()
} else {
adjust_placeholder_indices(&self.table, start_idx, dialect)
};
(
format!("({})", adjusted_subquery),
self.subquery_params.clone(),
)
} else {
(self.table.clone(), Vec::new())
};
let mut sql = format!(
" {}{}{}",
self.join_type.as_str(),
lateral_keyword,
if table_ref.is_empty() {
String::new()
} else {
format!(" {}", table_ref)
}
);
// Add subquery params before ON condition params
params.extend(subquery_params);
if let Some(alias) = &self.alias {
sql.push_str(" AS ");
sql.push_str(alias);
}
if self.join_type != JoinType::Cross {
let on_sql = self.on.build_with_dialect(dialect, params, offset);
sql.push_str(" ON ");
sql.push_str(&on_sql);
}
sql
}
}