dibs 0.1.1

Postgres toolkit for Rust, powered by facet reflection
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
//! Squel service implementation - the data plane.
//!
//! Provides generic CRUD operations for any registered table.

use crate::pool::ConnectionProvider;
use crate::query::{Db, Expr, SortDir, Value as QueryValue};
use crate::schema::Schema;
use dibs_proto::{
    CreateRequest, DeleteRequest, DibsError, Filter, FilterOp, GetRequest, ListRequest,
    ListResponse, Row, RowField, SchemaInfo, SortDir as ProtoSortDir, SquelService, UpdateRequest,
    Value as ProtoValue,
};

/// Default implementation of SquelService.
///
/// Generic over the connection provider, which can be:
/// - `Arc<tokio_postgres::Client>` for a single shared connection
/// - `deadpool_postgres::Pool` for connection pooling (requires `deadpool` feature)
#[derive(Clone)]
pub struct SquelServiceImpl<P: ConnectionProvider> {
    pool: P,
}

impl<P: ConnectionProvider> SquelServiceImpl<P> {
    /// Create a new SquelServiceImpl with the given connection provider.
    pub fn new(pool: P) -> Self {
        Self { pool }
    }
}

// =============================================================================
// Type conversions
// =============================================================================

fn proto_value_to_query(v: &ProtoValue) -> QueryValue {
    match v {
        ProtoValue::Null => QueryValue::Null,
        ProtoValue::Bool(b) => QueryValue::Bool(*b),
        ProtoValue::I16(n) => QueryValue::I16(*n),
        ProtoValue::I32(n) => QueryValue::I32(*n),
        ProtoValue::I64(n) => QueryValue::I64(*n),
        ProtoValue::F32(n) => QueryValue::F32(*n),
        ProtoValue::F64(n) => QueryValue::F64(*n),
        ProtoValue::String(s) => QueryValue::String(s.clone()),
        ProtoValue::Bytes(b) => QueryValue::Bytes(b.clone()),
    }
}

fn query_value_to_proto(v: &QueryValue) -> ProtoValue {
    match v {
        QueryValue::Null => ProtoValue::Null,
        QueryValue::Bool(b) => ProtoValue::Bool(*b),
        QueryValue::I16(n) => ProtoValue::I16(*n),
        QueryValue::I32(n) => ProtoValue::I32(*n),
        QueryValue::I64(n) => ProtoValue::I64(*n),
        QueryValue::F32(n) => ProtoValue::F32(*n),
        QueryValue::F64(n) => ProtoValue::F64(*n),
        QueryValue::Decimal(d) => ProtoValue::String(d.to_string()),
        QueryValue::String(s) => ProtoValue::String(s.clone()),
        QueryValue::Bytes(b) => ProtoValue::Bytes(b.clone()),
        QueryValue::Json(s) => ProtoValue::String(s.clone()),
    }
}

fn query_row_to_proto(row: crate::query::Row) -> Row {
    Row {
        fields: row
            .into_iter()
            .map(|(name, value)| RowField {
                name,
                value: query_value_to_proto(&value),
            })
            .collect(),
    }
}

fn proto_row_to_query(row: &Row) -> Vec<(String, QueryValue)> {
    row.fields
        .iter()
        .map(|f| (f.name.clone(), proto_value_to_query(&f.value)))
        .collect()
}

fn filter_to_expr(filter: &Filter) -> Expr {
    let col = filter.field.clone();
    let val = proto_value_to_query(&filter.value);

    match filter.op {
        FilterOp::Eq => Expr::Eq(col, val),
        FilterOp::Ne => Expr::Ne(col, val),
        FilterOp::Lt => Expr::Lt(col, val),
        FilterOp::Lte => Expr::Lte(col, val),
        FilterOp::Gt => Expr::Gt(col, val),
        FilterOp::Gte => Expr::Gte(col, val),
        FilterOp::Like => {
            if let QueryValue::String(s) = val {
                Expr::Like(col, s)
            } else {
                Expr::Like(col, String::new())
            }
        }
        FilterOp::ILike => {
            if let QueryValue::String(s) = val {
                Expr::ILike(col, s)
            } else {
                Expr::ILike(col, String::new())
            }
        }
        FilterOp::IsNull => Expr::IsNull(col),
        FilterOp::IsNotNull => Expr::IsNotNull(col),
        FilterOp::In => {
            let values: Vec<QueryValue> = filter.values.iter().map(proto_value_to_query).collect();
            Expr::In(col, values)
        }
        FilterOp::JsonGet => {
            // JSONB get object operator (->) - handled as a custom operator
            Expr::Like(col, String::new())
        }
        FilterOp::JsonGetText => {
            // JSONB get text operator (->>) - handled as a custom operator
            Expr::Like(col, String::new())
        }
        FilterOp::Contains => {
            // Contains operator (@>) - handled as a custom operator
            Expr::Like(col, String::new())
        }
        FilterOp::KeyExists => {
            // Key exists operator (?) - handled as a custom operator
            Expr::Like(col, String::new())
        }
    }
}

fn proto_sort_to_query(dir: ProtoSortDir) -> SortDir {
    match dir {
        ProtoSortDir::Asc => SortDir::Asc,
        ProtoSortDir::Desc => SortDir::Desc,
    }
}

fn schema_to_info(schema: &Schema) -> SchemaInfo {
    use dibs_proto::{ColumnInfo, ForeignKeyInfo, IndexColumnInfo, IndexInfo, TableInfo};

    SchemaInfo {
        tables: schema
            .tables
            .values()
            .map(|t| TableInfo {
                name: t.name.clone(),
                columns: t
                    .columns
                    .iter()
                    .map(|c| ColumnInfo {
                        name: c.name.clone(),
                        sql_type: c.pg_type.to_string(),
                        rust_type: c.rust_type.clone(),
                        nullable: c.nullable,
                        default: c.default.clone(),
                        primary_key: c.primary_key,
                        unique: c.unique,
                        auto_generated: c.auto_generated,
                        long: c.long,
                        label: c.label,
                        enum_variants: c.enum_variants.clone(),
                        doc: c.doc.clone(),
                        lang: c.lang.clone(),
                        icon: c.icon.clone(),
                        subtype: c.subtype.clone(),
                    })
                    .collect(),
                foreign_keys: t
                    .foreign_keys
                    .iter()
                    .map(|fk| ForeignKeyInfo {
                        columns: fk.columns.clone(),
                        references_table: fk.references_table.clone(),
                        references_columns: fk.references_columns.clone(),
                    })
                    .collect(),
                indices: t
                    .indices
                    .iter()
                    .map(|idx| IndexInfo {
                        name: idx.name.clone(),
                        columns: idx
                            .columns
                            .iter()
                            .map(|c| IndexColumnInfo {
                                name: c.name.clone(),
                                order: match c.order {
                                    crate::SortOrder::Asc => "asc".to_string(),
                                    crate::SortOrder::Desc => "desc".to_string(),
                                },
                                nulls: match c.nulls {
                                    crate::NullsOrder::Default => "default".to_string(),
                                    crate::NullsOrder::First => "first".to_string(),
                                    crate::NullsOrder::Last => "last".to_string(),
                                },
                            })
                            .collect(),
                        unique: idx.unique,
                        where_clause: idx.where_clause.clone(),
                    })
                    .collect(),
                source_file: t.source.file.clone(),
                source_line: t.source.line,
                doc: t.doc.clone(),
                icon: t.icon.clone(),
            })
            .collect(),
    }
}

// =============================================================================
// Service implementation
// =============================================================================

impl<P: ConnectionProvider> SquelService for SquelServiceImpl<P> {
    async fn schema(&self) -> SchemaInfo {
        let schema = crate::schema::collect_schema();
        schema_to_info(&schema)
    }

    async fn list(&self, request: ListRequest) -> Result<ListResponse, DibsError> {
        let conn = self
            .pool
            .get()
            .await
            .map_err(|e| DibsError::QueryError(e.to_string()))?;
        let db = Db::new(&conn);

        // Build the count query (same filters, no pagination)
        let mut count_builder = db
            .select(&request.table)
            .map_err(|e| DibsError::UnknownTable(e.to_string()))?;

        for filter in &request.filters {
            count_builder = count_builder.filter(filter_to_expr(filter));
        }

        let total = count_builder
            .count()
            .await
            .map_err(|e| DibsError::QueryError(e.to_string()))?;

        // Build the main query
        let mut builder = db
            .select(&request.table)
            .map_err(|e| DibsError::UnknownTable(e.to_string()))?;

        // Apply filters
        for filter in &request.filters {
            builder = builder.filter(filter_to_expr(filter));
        }

        // Apply sorting
        for sort in &request.sort {
            builder = builder.order_by(&sort.field, proto_sort_to_query(sort.dir));
        }

        // Apply pagination
        if let Some(limit) = request.limit {
            builder = builder.limit(limit);
        }
        if let Some(offset) = request.offset {
            builder = builder.offset(offset);
        }

        // Execute
        let rows = builder
            .all()
            .await
            .map_err(|e| DibsError::QueryError(e.to_string()))?;

        Ok(ListResponse {
            rows: rows.into_iter().map(query_row_to_proto).collect(),
            total: Some(total),
        })
    }

    async fn get(&self, request: GetRequest) -> Result<Option<Row>, DibsError> {
        let conn = self
            .pool
            .get()
            .await
            .map_err(|e| DibsError::QueryError(e.to_string()))?;
        let db = Db::new(&conn);

        // Find the primary key column
        let table = db
            .table(&request.table)
            .ok_or_else(|| DibsError::UnknownTable(request.table.clone()))?;

        let pk_col = table
            .columns
            .iter()
            .find(|c| c.primary_key)
            .ok_or_else(|| {
                DibsError::InvalidRequest(format!("Table {} has no primary key", request.table))
            })?;

        // Query by primary key
        let row = db
            .select(&request.table)
            .map_err(|e| DibsError::UnknownTable(e.to_string()))?
            .filter(Expr::Eq(
                pk_col.name.clone(),
                proto_value_to_query(&request.pk),
            ))
            .one()
            .await
            .map_err(|e| DibsError::QueryError(e.to_string()))?;

        Ok(row.map(query_row_to_proto))
    }

    async fn create(&self, request: CreateRequest) -> Result<Row, DibsError> {
        let conn = self
            .pool
            .get()
            .await
            .map_err(|e| DibsError::QueryError(e.to_string()))?;
        let db = Db::new(&conn);

        let data = proto_row_to_query(&request.data);

        let row = db
            .insert(&request.table)
            .map_err(|e| DibsError::UnknownTable(e.to_string()))?
            .values(data)
            .returning()
            .await
            .map_err(|e| DibsError::QueryError(e.to_string()))?
            .ok_or_else(|| DibsError::QueryError("Insert did not return a row".to_string()))?;

        Ok(query_row_to_proto(row))
    }

    async fn update(&self, request: UpdateRequest) -> Result<Row, DibsError> {
        let conn = self
            .pool
            .get()
            .await
            .map_err(|e| DibsError::QueryError(e.to_string()))?;
        let db = Db::new(&conn);

        // Find the primary key column
        let table = db
            .table(&request.table)
            .ok_or_else(|| DibsError::UnknownTable(request.table.clone()))?;

        let pk_col = table
            .columns
            .iter()
            .find(|c| c.primary_key)
            .ok_or_else(|| {
                DibsError::InvalidRequest(format!("Table {} has no primary key", request.table))
            })?;

        let data = proto_row_to_query(&request.data);

        let row = db
            .update(&request.table)
            .map_err(|e| DibsError::UnknownTable(e.to_string()))?
            .set(data)
            .filter(Expr::Eq(
                pk_col.name.clone(),
                proto_value_to_query(&request.pk),
            ))
            .returning()
            .await
            .map_err(|e| DibsError::QueryError(e.to_string()))?
            .ok_or_else(|| DibsError::QueryError("Update did not return a row".to_string()))?;

        Ok(query_row_to_proto(row))
    }

    async fn delete(&self, request: DeleteRequest) -> Result<u64, DibsError> {
        let conn = self
            .pool
            .get()
            .await
            .map_err(|e| DibsError::QueryError(e.to_string()))?;
        let db = Db::new(&conn);

        // Find the primary key column
        let table = db
            .table(&request.table)
            .ok_or_else(|| DibsError::UnknownTable(request.table.clone()))?;

        let pk_col = table
            .columns
            .iter()
            .find(|c| c.primary_key)
            .ok_or_else(|| {
                DibsError::InvalidRequest(format!("Table {} has no primary key", request.table))
            })?;

        let affected = db
            .delete(&request.table)
            .map_err(|e| DibsError::UnknownTable(e.to_string()))?
            .filter(Expr::Eq(
                pk_col.name.clone(),
                proto_value_to_query(&request.pk),
            ))
            .execute()
            .await
            .map_err(|e| DibsError::QueryError(e.to_string()))?;

        Ok(affected)
    }
}