real-rs 0.1.0

Universal query engine with relational algebra - compile the same query to PostgreSQL, SQLite, MongoDB, and YottaDB
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
//! PostgreSQL backend - production relational database
//!
//! Full-featured SQL backend with advanced PostgreSQL capabilities including:
//! - JSONB support for nested documents
//! - Array types
//! - CTEs (Common Table Expressions)
//! - Window functions
//! - Advanced aggregations

use crate::algebra::{AggregateType, CompareOp, Expr, JoinCondition, Operand, Predicate, SortOrder};
use crate::backends::Backend;
use crate::schema::{Column, DataType, ResultSet, Row, Schema, Value};
use crate::{RealError, Result};

pub struct PostgresBackend;

/// Compiled PostgreSQL query
#[derive(Debug, Clone)]
pub struct PostgresQuery {
    pub sql: String,
    pub params: Vec<Value>,
    pub result_schema: Schema,
}

impl PostgresBackend {
    pub fn new() -> Self {
        Self
    }

    fn compile_predicate(&self, pred: &Predicate, params: &mut Vec<Value>) -> Result<String> {
        match pred {
            Predicate::Compare { left, op, right } => {
                let left_sql = format!("{}", left.name);
                let op_sql = match op {
                    CompareOp::Eq => "=",
                    CompareOp::NotEq => "!=",
                    CompareOp::Lt => "<",
                    CompareOp::Lte => "<=",
                    CompareOp::Gt => ">",
                    CompareOp::Gte => ">=",
                };
                let right_sql = match right {
                    Operand::Column(col) => col.name.clone(),
                    Operand::Literal(val) => {
                        params.push(val.clone());
                        format!("${}", params.len())
                    }
                };
                Ok(format!("{} {} {}", left_sql, op_sql, right_sql))
            }
            Predicate::And(left, right) => {
                let left_sql = self.compile_predicate(left, params)?;
                let right_sql = self.compile_predicate(right, params)?;
                Ok(format!("({} AND {})", left_sql, right_sql))
            }
            Predicate::Or(left, right) => {
                let left_sql = self.compile_predicate(left, params)?;
                let right_sql = self.compile_predicate(right, params)?;
                Ok(format!("({} OR {})", left_sql, right_sql))
            }
            Predicate::Not(inner) => {
                let inner_sql = self.compile_predicate(inner, params)?;
                Ok(format!("NOT ({})", inner_sql))
            }
            Predicate::In { column, values } => {
                let placeholders = values
                    .iter()
                    .map(|v| {
                        params.push(v.clone());
                        format!("${}", params.len())
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                Ok(format!("{} IN ({})", column.name, placeholders))
            }
            Predicate::Like { column, pattern } => {
                params.push(Value::String(pattern.clone()));
                Ok(format!("{} LIKE ${}", column.name, params.len()))
            }
            Predicate::IsNull(column) => Ok(format!("{} IS NULL", column.name)),
            Predicate::Between { column, low, high } => {
                params.push(low.clone());
                let low_idx = params.len();
                params.push(high.clone());
                let high_idx = params.len();
                Ok(format!(
                    "{} BETWEEN ${} AND ${}",
                    column.name, low_idx, high_idx
                ))
            }
        }
    }
}

impl Default for PostgresBackend {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "backend-postgres")]
impl Backend for PostgresBackend {
    type Connection = postgres::Client;
    type CompiledQuery = PostgresQuery;

    fn compile(&self, expr: &Expr) -> Result<Self::CompiledQuery> {
        let mut params = Vec::new();

        let query = match expr {
            Expr::Relation { name, schema } => PostgresQuery {
                sql: format!("SELECT * FROM {}", name),
                params: vec![],
                result_schema: schema.clone(),
            },

            Expr::Select { input, predicate } => {
                let inner = self.compile(input)?;
                let where_clause = self.compile_predicate(predicate, &mut params)?;

                PostgresQuery {
                    sql: format!("SELECT * FROM ({}) AS t WHERE {}", inner.sql, where_clause),
                    params,
                    result_schema: inner.result_schema,
                }
            }

            Expr::Project { input, columns } => {
                let inner = self.compile(input)?;
                let cols = columns.join(", ");

                PostgresQuery {
                    sql: format!("SELECT {} FROM ({}) AS t", cols, inner.sql),
                    params: inner.params,
                    result_schema: expr.infer_schema(),
                }
            }

            Expr::Join { left, right, condition } => {
                let left_query = self.compile(left)?;
                let right_query = self.compile(right)?;

                let join_clause = match condition {
                    JoinCondition::Using(cols) => format!("USING ({})", cols.join(", ")),
                    JoinCondition::On(pred) => {
                        format!("ON {}", self.compile_predicate(pred, &mut params)?)
                    }
                };

                params.extend(left_query.params);
                params.extend(right_query.params);

                PostgresQuery {
                    sql: format!(
                        "SELECT * FROM ({}) AS l JOIN ({}) AS r {}",
                        left_query.sql, right_query.sql, join_clause
                    ),
                    params,
                    result_schema: Schema::new("join_result"),
                }
            }

            Expr::Aggregate {
                input,
                group_by,
                aggregates,
            } => {
                let inner = self.compile(input)?;

                // Build aggregate function calls
                let agg_exprs: Vec<String> = aggregates
                    .iter()
                    .map(|agg| {
                        let func_name = match agg.func {
                            AggregateType::Count => "COUNT",
                            AggregateType::Sum => "SUM",
                            AggregateType::Avg => "AVG",
                            AggregateType::Min => "MIN",
                            AggregateType::Max => "MAX",
                        };
                        format!("{}({}) AS {}", func_name, agg.input, agg.name)
                    })
                    .collect();

                let select_list = if group_by.is_empty() {
                    agg_exprs.join(", ")
                } else {
                    format!("{}, {}", group_by.join(", "), agg_exprs.join(", "))
                };

                let sql = if group_by.is_empty() {
                    format!("SELECT {} FROM ({}) AS t", select_list, inner.sql)
                } else {
                    format!(
                        "SELECT {} FROM ({}) AS t GROUP BY {}",
                        select_list,
                        inner.sql,
                        group_by.join(", ")
                    )
                };

                PostgresQuery {
                    sql,
                    params: inner.params,
                    result_schema: expr.infer_schema(),
                }
            }

            Expr::Union { left, right } => {
                let left_query = self.compile(left)?;
                let right_query = self.compile(right)?;

                params.extend(left_query.params);
                params.extend(right_query.params);

                PostgresQuery {
                    sql: format!("({}) UNION ({})", left_query.sql, right_query.sql),
                    params,
                    result_schema: left_query.result_schema,
                }
            }

            Expr::Intersect { left, right } => {
                let left_query = self.compile(left)?;
                let right_query = self.compile(right)?;

                params.extend(left_query.params);
                params.extend(right_query.params);

                PostgresQuery {
                    sql: format!("({}) INTERSECT ({})", left_query.sql, right_query.sql),
                    params,
                    result_schema: left_query.result_schema,
                }
            }

            Expr::Difference { left, right } => {
                let left_query = self.compile(left)?;
                let right_query = self.compile(right)?;

                params.extend(left_query.params);
                params.extend(right_query.params);

                PostgresQuery {
                    sql: format!("({}) EXCEPT ({})", left_query.sql, right_query.sql),
                    params,
                    result_schema: left_query.result_schema,
                }
            }

            Expr::Rename { input, from, to } => {
                let inner = self.compile(input)?;

                PostgresQuery {
                    sql: format!("SELECT * FROM ({}) AS t", inner.sql),
                    params: inner.params,
                    result_schema: expr.infer_schema(),
                }
            }

            Expr::Sort { input, columns } => {
                let inner = self.compile(input)?;

                let order_by = columns
                    .iter()
                    .map(|(col, order)| {
                        let order_str = match order {
                            SortOrder::Asc => "ASC",
                            SortOrder::Desc => "DESC",
                        };
                        format!("{} {}", col, order_str)
                    })
                    .collect::<Vec<_>>()
                    .join(", ");

                PostgresQuery {
                    sql: format!("SELECT * FROM ({}) AS t ORDER BY {}", inner.sql, order_by),
                    params: inner.params,
                    result_schema: inner.result_schema,
                }
            }

            Expr::Limit { input, count } => {
                let inner = self.compile(input)?;

                PostgresQuery {
                    sql: format!("SELECT * FROM ({}) AS t LIMIT {}", inner.sql, count),
                    params: inner.params,
                    result_schema: inner.result_schema,
                }
            }

            Expr::Offset { input, count } => {
                let inner = self.compile(input)?;

                PostgresQuery {
                    sql: format!("SELECT * FROM ({}) AS t OFFSET {}", inner.sql, count),
                    params: inner.params,
                    result_schema: inner.result_schema,
                }
            }

            _ => {
                return Err(RealError::Backend(format!(
                    "PostgreSQL backend does not yet support: {:?}",
                    expr
                )))
            }
        };

        Ok(query)
    }

    fn execute(
        &self,
        conn: &mut Self::Connection,
        query: &Self::CompiledQuery,
    ) -> Result<ResultSet> {
        // Convert Value params to postgres-compatible types
        let params: Vec<&(dyn postgres::types::ToSql + Sync)> = query
            .params
            .iter()
            .map(|v| v as &(dyn postgres::types::ToSql + Sync))
            .collect();

        let rows = conn
            .query(&query.sql, &params[..])
            .map_err(|e| RealError::Backend(e.to_string()))?;

        let mut result_set = Vec::new();
        for row in rows {
            let mut values = Vec::new();
            for i in 0..row.len() {
                // Try to extract value based on type
                let value = if let Ok(v) = row.try_get::<_, i64>(i) {
                    Value::Integer(v)
                } else if let Ok(v) = row.try_get::<_, f64>(i) {
                    Value::Float(v)
                } else if let Ok(v) = row.try_get::<_, String>(i) {
                    Value::String(v)
                } else if let Ok(v) = row.try_get::<_, bool>(i) {
                    Value::Boolean(v)
                } else if let Ok(v) = row.try_get::<_, Vec<u8>>(i) {
                    Value::Bytes(v)
                } else {
                    Value::Null
                };
                values.push(value);
            }
            result_set.push(values);
        }

        Ok(result_set)
    }

    fn get_schema(&self, conn: &mut Self::Connection, relation: &str) -> Result<Schema> {
        let query = "SELECT column_name, data_type, is_nullable
                     FROM information_schema.columns
                     WHERE table_name = $1
                     ORDER BY ordinal_position";

        let rows = conn
            .query(query, &[&relation])
            .map_err(|e| RealError::Backend(e.to_string()))?;

        let mut schema = Schema::new(relation);

        for row in rows {
            let name: String = row.get(0);
            let type_name: String = row.get(1);
            let nullable: String = row.get(2);

            let data_type = match type_name.to_lowercase().as_str() {
                "integer" | "int" | "int4" | "smallint" | "bigint" => DataType::Integer,
                "real" | "float4" | "double precision" | "float8" | "numeric" | "decimal" => {
                    DataType::Float
                }
                "text" | "varchar" | "character varying" | "char" | "character" => {
                    DataType::String
                }
                "bytea" => DataType::Bytes,
                "boolean" | "bool" => DataType::Boolean,
                "timestamp" | "timestamptz" | "date" | "time" => DataType::Timestamp,
                "json" | "jsonb" => DataType::Json,
                _ if type_name.starts_with("_") => {
                    // Array type
                    DataType::Array(Box::new(DataType::String))
                }
                _ => DataType::String, // Default to string for unknown types
            };

            schema.columns.push(Column {
                name,
                data_type,
                nullable: nullable.to_lowercase() == "yes",
            });
        }

        Ok(schema)
    }
}

#[cfg(not(feature = "backend-postgres"))]
impl Backend for PostgresBackend {
    type Connection = ();
    type CompiledQuery = PostgresQuery;

    fn compile(&self, _expr: &Expr) -> Result<Self::CompiledQuery> {
        Err(RealError::Backend(
            "PostgreSQL backend not enabled. Enable 'backend-postgres' feature.".into(),
        ))
    }

    fn execute(
        &self,
        _conn: &mut Self::Connection,
        _query: &Self::CompiledQuery,
    ) -> Result<ResultSet> {
        Err(RealError::Backend(
            "PostgreSQL backend not enabled. Enable 'backend-postgres' feature.".into(),
        ))
    }

    fn get_schema(&self, _conn: &mut Self::Connection, _relation: &str) -> Result<Schema> {
        Err(RealError::Backend(
            "PostgreSQL backend not enabled. Enable 'backend-postgres' feature.".into(),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::algebra::{ColumnRef, Predicate};

    #[test]
    fn test_postgres_compile_relation() {
        let backend = PostgresBackend::new();
        let schema = Schema::new("users").with_column("id", DataType::Integer);
        let expr = Expr::relation("users", schema);

        let query = backend.compile(&expr).unwrap();
        assert_eq!(query.sql, "SELECT * FROM users");
    }

    #[test]
    fn test_postgres_compile_select() {
        let backend = PostgresBackend::new();
        let schema = Schema::new("users")
            .with_column("id", DataType::Integer)
            .with_column("age", DataType::Integer);

        let expr = Expr::relation("users", schema).select(Predicate::Compare {
            left: ColumnRef::new("age"),
            op: CompareOp::Gt,
            right: Operand::Literal(Value::Integer(25)),
        });

        let query = backend.compile(&expr).unwrap();
        assert!(query.sql.contains("WHERE"));
        assert!(query.sql.contains("age >"));
        assert_eq!(query.params.len(), 1);
    }

    #[test]
    fn test_postgres_compile_aggregate() {
        let backend = PostgresBackend::new();
        let schema = Schema::new("sales")
            .with_column("region", DataType::String)
            .with_column("amount", DataType::Float);

        let expr = Expr::Aggregate {
            input: Box::new(Expr::relation("sales", schema)),
            group_by: vec!["region".to_string()],
            aggregates: vec![crate::algebra::AggregateFunc {
                name: "total".to_string(),
                func: AggregateType::Sum,
                input: "amount".to_string(),
            }],
        };

        let query = backend.compile(&expr).unwrap();
        assert!(query.sql.contains("GROUP BY"));
        assert!(query.sql.contains("SUM(amount)"));
    }
}