1use crate::flavours::types::FlavourCompiler;
2use serde_json::Value;
3use std::collections::{HashMap, HashSet};
4
5#[derive(Clone, Debug, PartialEq, Eq)]
6pub struct PostgresColumnConfig {
7 pub table: String,
8 pub column: String,
9}
10
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct PostgresJoinConfig {
13 pub table: String,
14 pub join_table: String,
15 pub on: String,
16 pub r#type: Option<String>,
17}
18
19#[derive(Clone, Debug, Default, PartialEq, Eq)]
20pub struct PostgreSQLConfig {
21 pub column_mappings: HashMap<String, PostgresColumnConfig>,
22 pub joins: Vec<PostgresJoinConfig>,
23 pub placeholder_start_index: Option<usize>,
24}
25
26pub struct PostgreSQLFilterOutput {
27 pub where_clause: String,
28 pub values: Vec<Value>,
29 pub joins: Vec<String>,
30}
31
32pub struct PostgreSQLCompiler;
33
34impl Default for PostgreSQLCompiler {
35 fn default() -> Self {
36 Self::new()
37 }
38}
39
40struct PostgresCompilationContext {
41 column_mappings: HashMap<String, PostgresColumnConfig>,
42 referenced_tables: HashSet<String>,
43 values: Vec<Value>,
44 placeholder_index: usize,
45}
46
47fn is_operator_object(val: &Value) -> bool {
48 if let Value::Object(map) = val {
49 !map.is_empty() && map.keys().all(|k| k.starts_with('$'))
50 } else {
51 false
52 }
53}
54
55fn resolve_sql_field(field_path: &str, context: &mut PostgresCompilationContext) -> String {
56 let parts: Vec<&str> = field_path.split('.').collect();
57 if parts.is_empty() {
58 return field_path.to_string();
59 }
60 let first_part = parts[0];
61
62 if let Some(mapping) = context.column_mappings.get(first_part) {
63 context.referenced_tables.insert(mapping.table.clone());
64
65 if parts.len() > 1 {
66 let mut path_expr = format!("{}.{}", mapping.table, mapping.column);
67 let json_parts = &parts[1..];
68 for (i, p) in json_parts.iter().enumerate() {
69 let is_last = i == json_parts.len() - 1;
70 let op = if is_last { "->>" } else { "->" };
71 path_expr = format!("{}{}'{}'", path_expr, op, p);
72 }
73 path_expr
74 } else {
75 format!("{}.{}", mapping.table, mapping.column)
76 }
77 } else {
78 field_path.to_string()
79 }
80}
81
82fn get_sql_placeholder(val: Value, context: &mut PostgresCompilationContext) -> String {
83 context.values.push(val);
84 let index = context.placeholder_index;
85 context.placeholder_index += 1;
86 format!("${}", index)
87}
88
89impl PostgreSQLCompiler {
90 pub fn new() -> Self {
91 Self
92 }
93
94 fn compile_selector(
95 &self,
96 selector: &Value,
97 context: &mut PostgresCompilationContext,
98 ) -> Result<String, String> {
99 let map = match selector {
100 Value::Object(m) => m,
101 _ => return Ok("".to_string()),
102 };
103
104 if map.is_empty() {
105 return Ok("".to_string());
106 }
107
108 let mut expressions = Vec::new();
109
110 for (key, value) in map {
111 if key == "$and" {
112 if let Value::Array(arr) = value {
113 let mut sub_exprs = Vec::new();
114 for sub in arr {
115 let expr = self.compile_selector(sub, context)?;
116 if !expr.is_empty() {
117 sub_exprs.push(expr);
118 }
119 }
120 if !sub_exprs.is_empty() {
121 expressions.push(format!("({})", sub_exprs.join(" AND ")));
122 }
123 }
124 } else if key == "$or" {
125 if let Value::Array(arr) = value {
126 let mut sub_exprs = Vec::new();
127 for sub in arr {
128 let expr = self.compile_selector(sub, context)?;
129 if !expr.is_empty() {
130 sub_exprs.push(expr);
131 }
132 }
133 if !sub_exprs.is_empty() {
134 expressions.push(format!("({})", sub_exprs.join(" OR ")));
135 }
136 }
137 } else if key == "$nor" {
138 if let Value::Array(arr) = value {
139 let mut sub_exprs = Vec::new();
140 for sub in arr {
141 let expr = self.compile_selector(sub, context)?;
142 if !expr.is_empty() {
143 sub_exprs.push(expr);
144 }
145 }
146 if !sub_exprs.is_empty() {
147 expressions.push(format!("(NOT ({}))", sub_exprs.join(" OR ")));
148 }
149 }
150 } else if key == "$not" {
151 let expr = self.compile_selector(value, context)?;
152 if !expr.is_empty() {
153 expressions.push(format!("(NOT ({}))", expr));
154 }
155 } else if key.starts_with('$') {
156 return Err(format!(
157 "PostgreSQL compiler: Operator '{}' is not supported at the root of a selector.",
158 key
159 ));
160 } else {
161 expressions.push(self.compile_field_condition(key, value, context)?);
162 }
163 }
164
165 Ok(expressions.join(" AND "))
166 }
167
168 fn compile_field_condition(
169 &self,
170 field: &str,
171 value: &Value,
172 context: &mut PostgresCompilationContext,
173 ) -> Result<String, String> {
174 if value.is_object() && !is_operator_object(value) {
175 let map = value.as_object().unwrap();
176 let mut expressions = Vec::new();
177 for (key, val) in map {
178 let nested_field = format!("{}.{}", field, key);
179 expressions.push(self.compile_field_condition(&nested_field, val, context)?);
180 }
181 return Ok(expressions.join(" AND "));
182 }
183
184 let column_expr = resolve_sql_field(field, context);
185
186 if value.is_null() {
187 return Ok(format!("{} IS NULL", column_expr));
188 }
189
190 if !value.is_object() || value.is_array() {
191 let placeholder = get_sql_placeholder(value.clone(), context);
192 return Ok(format!("{} = {}", column_expr, placeholder));
193 }
194
195 let map = value.as_object().unwrap();
196 let mut op_expressions = Vec::new();
197
198 for (op_key, op_value) in map {
199 match op_key.as_str() {
200 "$eq" => {
201 if op_value.is_null() {
202 op_expressions.push(format!("{} IS NULL", column_expr));
203 } else {
204 let placeholder = get_sql_placeholder(op_value.clone(), context);
205 op_expressions.push(format!("{} = {}", column_expr, placeholder));
206 }
207 }
208 "$ne" => {
209 if op_value.is_null() {
210 op_expressions.push(format!("{} IS NOT NULL", column_expr));
211 } else {
212 let placeholder = get_sql_placeholder(op_value.clone(), context);
213 op_expressions.push(format!("{} <> {}", column_expr, placeholder));
214 }
215 }
216 "$gt" => {
217 let placeholder = get_sql_placeholder(op_value.clone(), context);
218 op_expressions.push(format!("{} > {}", column_expr, placeholder));
219 }
220 "$gte" => {
221 let placeholder = get_sql_placeholder(op_value.clone(), context);
222 op_expressions.push(format!("{} >= {}", column_expr, placeholder));
223 }
224 "$lt" => {
225 let placeholder = get_sql_placeholder(op_value.clone(), context);
226 op_expressions.push(format!("{} < {}", column_expr, placeholder));
227 }
228 "$lte" => {
229 let placeholder = get_sql_placeholder(op_value.clone(), context);
230 op_expressions.push(format!("{} <= {}", column_expr, placeholder));
231 }
232 "$exists" => {
233 if let Value::Bool(b) = op_value {
234 if *b {
235 op_expressions.push(format!("{} IS NOT NULL", column_expr));
236 } else {
237 op_expressions.push(format!("{} IS NULL", column_expr));
238 }
239 } else {
240 return Err(
241 "PostgreSQL compiler: $exists operator requires a boolean value."
242 .to_string(),
243 );
244 }
245 }
246 "$beginsWith" => {
247 if let Value::String(s) = op_value {
248 let like_value = format!("{}%", s);
249 let placeholder = get_sql_placeholder(Value::String(like_value), context);
250 op_expressions.push(format!("{} LIKE {}", column_expr, placeholder));
251 } else {
252 return Err(
253 "PostgreSQL compiler: $beginsWith operator requires a string value."
254 .to_string(),
255 );
256 }
257 }
258 "$regex" => {
259 let placeholder = get_sql_placeholder(op_value.clone(), context);
260 op_expressions.push(format!("{} ~ {}", column_expr, placeholder));
261 }
262 "$in" => {
263 if let Value::Array(arr) = op_value {
264 if arr.is_empty() {
265 op_expressions.push("FALSE".to_string());
266 } else {
267 let placeholders: Vec<String> = arr
268 .iter()
269 .map(|v| get_sql_placeholder(v.clone(), context))
270 .collect();
271 op_expressions.push(format!(
272 "{} IN ({})",
273 column_expr,
274 placeholders.join(", ")
275 ));
276 }
277 } else {
278 return Err("PostgreSQL compiler: $in operator requires an array value."
279 .to_string());
280 }
281 }
282 "$nin" => {
283 if let Value::Array(arr) = op_value {
284 if arr.is_empty() {
285 op_expressions.push("TRUE".to_string());
286 } else {
287 let placeholders: Vec<String> = arr
288 .iter()
289 .map(|v| get_sql_placeholder(v.clone(), context))
290 .collect();
291 op_expressions.push(format!(
292 "{} NOT IN ({})",
293 column_expr,
294 placeholders.join(", ")
295 ));
296 }
297 } else {
298 return Err(
299 "PostgreSQL compiler: $nin operator requires an array value."
300 .to_string(),
301 );
302 }
303 }
304 "$mod" => {
305 if let Value::Array(arr) = op_value {
306 if arr.len() == 2 {
307 let div_placeholder = get_sql_placeholder(arr[0].clone(), context);
308 let rem_placeholder = get_sql_placeholder(arr[1].clone(), context);
309 op_expressions.push(format!(
310 "CAST({} AS INTEGER) % {} = {}",
311 column_expr, div_placeholder, rem_placeholder
312 ));
313 } else {
314 return Err("PostgreSQL compiler: $mod operator requires an array of [divisor, remainder].".to_string());
315 }
316 } else {
317 return Err(
318 "PostgreSQL compiler: $mod operator requires an array value."
319 .to_string(),
320 );
321 }
322 }
323 _ => {
324 return Err(format!(
325 "PostgreSQL compiler: Operator '{}' is not supported for field conditions.",
326 op_key
327 ));
328 }
329 }
330 }
331
332 Ok(op_expressions.join(" AND "))
333 }
334}
335
336impl FlavourCompiler<PostgreSQLFilterOutput, PostgreSQLConfig> for PostgreSQLCompiler {
337 fn compile(
338 &self,
339 query: &Value,
340 config: Option<PostgreSQLConfig>,
341 ) -> Result<PostgreSQLFilterOutput, String> {
342 let selector = if let Some(sel) = query.get("selector") {
343 sel
344 } else {
345 query
346 };
347
348 let conf = config.unwrap_or_default();
349
350 let mut context = PostgresCompilationContext {
351 column_mappings: conf.column_mappings,
352 referenced_tables: HashSet::new(),
353 values: Vec::new(),
354 placeholder_index: conf.placeholder_start_index.unwrap_or(1),
355 };
356
357 let where_clause = self.compile_selector(selector, &mut context)?;
358
359 let mut join_strings = Vec::new();
360 for join in conf.joins {
361 if context.referenced_tables.contains(&join.table) {
362 let join_type = join.r#type.unwrap_or_else(|| "LEFT".to_string());
363 join_strings.push(format!("{} JOIN {} ON {}", join_type, join.table, join.on));
364 }
365 }
366
367 Ok(PostgreSQLFilterOutput {
368 where_clause,
369 values: context.values,
370 joins: join_strings,
371 })
372 }
373}