vantage-sql 0.6.20

Vantage extension for SQL databases (Postgres, MySQL, SQLite)
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
//! `PostgresTableShell` — owns the typed `Table<PostgresDB, E>` and exposes
//! it through the `TableShell` boundary. The shell is generic in `E` so that
//! `with_expression` closures (parameterized over `E`) survive the wrap;
//! `Vista` erases `E` once at the `Box<dyn TableShell>` boundary.

use async_trait::async_trait;
use ciborium::Value as CborValue;
use indexmap::IndexMap;
use vantage_core::{Result, error};
use vantage_dataset::traits::{InsertableValueSet, ReadableValueSet, WritableValueSet};
use vantage_table::pagination::Pagination;
use vantage_table::sorting::{OrderBy, SortDirection as TableSortDirection};
use vantage_table::table::Table;
use vantage_types::{EmptyEntity, Entity, Record};
use vantage_vista::{
    Column as VistaColumn, ContainedSpec, Reference as VistaReference, SortDirection, TableShell,
    Vista, VistaCapabilities, VistaChange, VistaChangeStream, VistaMetadata,
};

use crate::postgres::PostgresDB;
use crate::postgres::operation::PostgresOperation;
use crate::postgres::types::AnyPostgresType;
use crate::primitives::identifier::ident;
use crate::types::{cbor_to_json, parse_json_host};

pub struct PostgresTableShell<E = EmptyEntity>
where
    E: Entity<AnyPostgresType>,
{
    pub(crate) table: Table<PostgresDB, E>,
    pub(crate) capabilities: VistaCapabilities,
    pub(crate) metadata: VistaMetadata,
}

impl<E> PostgresTableShell<E>
where
    E: Entity<AnyPostgresType>,
{
    pub(crate) fn new(
        table: Table<PostgresDB, E>,
        capabilities: VistaCapabilities,
        metadata: VistaMetadata,
    ) -> Self {
        Self {
            table,
            capabilities,
            metadata,
        }
    }

    /// Whether the application declared `{table}_changed` triggers for this
    /// database (see `PostgresVistaFactory::with_notify`).
    ///
    /// Traversals build a fresh factory, which would otherwise reset the opt-in
    /// and leave every relation target silently unwatchable on a database that
    /// does have triggers. We recover it from our own advertised capability
    /// rather than storing it twice. A query-sourced parent reads back `false`
    /// (it is read-only, so it never advertised), which under-advertises a real
    /// child table — the safe direction: a missed feed degrades to the
    /// consumer's reconcile path, a phantom one degrades to silence.
    fn notify_opt_in(&self) -> bool {
        self.capabilities.can_subscribe
    }
}

fn to_cbor_record(record: Record<AnyPostgresType>) -> Record<CborValue> {
    record
        .into_iter()
        .map(|(k, v)| (k, v.into_value()))
        .collect()
}

fn to_native_record(record: &Record<CborValue>) -> Record<AnyPostgresType> {
    record
        .iter()
        .map(|(k, v)| (k.clone(), AnyPostgresType::untyped(v.clone())))
        .collect()
}

#[async_trait]
impl<E> TableShell for PostgresTableShell<E>
where
    E: Entity<AnyPostgresType> + 'static,
{
    fn columns(&self) -> &IndexMap<String, VistaColumn> {
        &self.metadata.columns
    }

    fn references(&self) -> &IndexMap<String, VistaReference> {
        &self.metadata.references
    }

    fn id_column(&self) -> Option<&str> {
        self.metadata.id_column.as_deref()
    }

    async fn list_vista_values(
        &self,
        _vista: &Vista,
    ) -> Result<IndexMap<String, Record<CborValue>>> {
        let raw = self.table.list_values().await?;
        Ok(raw
            .into_iter()
            .map(|(id, record)| (id, to_cbor_record(record)))
            .collect())
    }

    async fn get_vista_value(
        &self,
        _vista: &Vista,
        id: &String,
    ) -> Result<Option<Record<CborValue>>> {
        let Some(record) = self.table.get_value(id).await? else {
            return Ok(None);
        };
        Ok(Some(to_cbor_record(record)))
    }

    async fn get_vista_some_value(
        &self,
        _vista: &Vista,
    ) -> Result<Option<(String, Record<CborValue>)>> {
        let Some((id, record)) = self.table.get_some_value().await? else {
            return Ok(None);
        };
        Ok(Some((id, to_cbor_record(record))))
    }

    async fn get_vista_count(&self, _vista: &Vista) -> Result<i64> {
        self.table.get_count().await
    }

    async fn fetch_window(
        &self,
        _vista: &Vista,
        offset: usize,
        limit: usize,
    ) -> Result<Vec<(String, Record<CborValue>)>> {
        // Clone the wrapped table so this call's window doesn't disturb the
        // shell's own condition / order / search state.
        let mut window_table = self.table.clone();
        window_table.set_pagination(Some(Pagination::window(offset as i64, limit as i64)));

        let raw = window_table.list_values().await?;
        Ok(raw
            .into_iter()
            .map(|(id, record)| (id, to_cbor_record(record)))
            .collect())
    }

    async fn insert_vista_value(
        &self,
        _vista: &Vista,
        id: &String,
        record: &Record<CborValue>,
    ) -> Result<Record<CborValue>> {
        let inserted = self
            .table
            .insert_value(id, &to_native_record(record))
            .await?;
        Ok(to_cbor_record(inserted))
    }

    async fn replace_vista_value(
        &self,
        _vista: &Vista,
        id: &String,
        record: &Record<CborValue>,
    ) -> Result<Record<CborValue>> {
        let replaced = self
            .table
            .replace_value(id, &to_native_record(record))
            .await?;
        Ok(to_cbor_record(replaced))
    }

    async fn patch_vista_value(
        &self,
        _vista: &Vista,
        id: &String,
        partial: &Record<CborValue>,
    ) -> Result<Record<CborValue>> {
        let patched = self
            .table
            .patch_value(id, &to_native_record(partial))
            .await?;
        Ok(to_cbor_record(patched))
    }

    async fn delete_vista_value(&self, _vista: &Vista, id: &String) -> Result<()> {
        self.table.delete(id).await
    }

    async fn delete_vista_all_values(&self, _vista: &Vista) -> Result<()> {
        self.table.delete_all().await
    }

    async fn insert_vista_return_id_value(
        &self,
        _vista: &Vista,
        record: &Record<CborValue>,
    ) -> Result<String> {
        self.table
            .insert_return_id_value(&to_native_record(record))
            .await
    }

    fn add_eq_condition(&mut self, field: &str, value: &CborValue) -> Result<()> {
        let column = self
            .table
            .columns()
            .get(field)
            .ok_or_else(|| error!("Unknown column for eq condition", field = field))?
            .clone();
        let sql_value = AnyPostgresType::untyped(value.clone());
        self.table.add_condition(column.eq(sql_value));
        Ok(())
    }

    fn add_op_condition(
        &mut self,
        field: &str,
        op: vantage_vista::FilterOp,
        value: &CborValue,
    ) -> Result<()> {
        use vantage_vista::FilterOp;
        let column = self
            .table
            .columns()
            .get(field)
            .ok_or_else(|| error!("Unknown column for condition", field = field))?
            .clone();
        match op {
            FilterOp::InSet | FilterOp::NotInSet => {
                let CborValue::Array(items) = value else {
                    return Err(error!(
                        "in_set/not_in_set requires an array value",
                        field = field
                    ));
                };
                let values: Vec<AnyPostgresType> = items
                    .iter()
                    .map(|v| AnyPostgresType::untyped(v.clone()))
                    .collect();
                let condition = match op {
                    FilterOp::InSet => column.in_list(&values),
                    _ => column.not_in_list(&values),
                };
                self.table.add_condition(condition);
            }
            _ => {
                let sql_value = AnyPostgresType::untyped(value.clone());
                let condition = match op {
                    FilterOp::Eq => column.eq(sql_value),
                    FilterOp::Ne => column.ne(sql_value),
                    FilterOp::Gt => column.gt(sql_value),
                    FilterOp::Gte => column.gte(sql_value),
                    FilterOp::Lt => column.lt(sql_value),
                    FilterOp::Lte => column.lte(sql_value),
                    FilterOp::InSet | FilterOp::NotInSet => unreachable!("handled above"),
                };
                self.table.add_condition(condition);
            }
        }
        Ok(())
    }

    fn add_order(&mut self, field: &str, dir: SortDirection) -> Result<()> {
        if !self.table.columns().contains_key(field) {
            return Err(error!("Unknown column for add_order", field = field));
        }
        // Vista's add_order is replace-semantics — drop any previously-set
        // order before pushing the new one.
        self.table.clear_orders();
        let expr = postgres_expr!("{}", (ident(field)));
        let direction = match dir {
            SortDirection::Ascending => TableSortDirection::Ascending,
            SortDirection::Descending => TableSortDirection::Descending,
        };
        self.table.add_order(OrderBy {
            expression: expr.into(),
            direction,
        });
        Ok(())
    }

    fn clear_orders(&mut self) -> Result<()> {
        self.table.clear_orders();
        Ok(())
    }

    fn get_ref(&self, relation: &str, row: &Record<CborValue>) -> Result<Vista> {
        let native_row = to_native_record(row);
        let target = self
            .table
            .get_ref_from_row::<EmptyEntity>(relation, &native_row)?;
        let factory = crate::postgres::vista::factory::PostgresVistaFactory::new(
            self.table.data_source().clone(),
        )
        .with_notify(self.notify_opt_in());
        factory.from_table(target)
    }

    fn get_ref_target(&self, relation: &str) -> Result<Vista> {
        let target = self.table.get_ref_target_erased(relation)?;
        let factory = crate::postgres::vista::factory::PostgresVistaFactory::new(
            self.table.data_source().clone(),
        )
        .with_notify(self.notify_opt_in());
        factory.from_table(target)
    }

    fn get_ref_kinds(&self) -> Vec<(String, vantage_vista::ReferenceKind)> {
        self.table.ref_kinds()
    }

    fn contained(&self) -> &IndexMap<String, ContainedSpec> {
        &self.metadata.contained
    }

    /// Resolve a contained relation. The collection lives in the host column as
    /// JSON (parsed on read, re-serialized on write); the shared
    /// `Table::get_contained_ref` does the rest.
    fn get_contained_ref(&self, relation: &str, row: &Record<CborValue>) -> Result<Vista> {
        let id_field = self.metadata.id_column.as_deref().unwrap_or("id");
        let parent_id = match row.get(id_field) {
            Some(CborValue::Text(s)) => s.clone(),
            Some(CborValue::Integer(i)) => i128::from(*i).to_string(),
            _ => {
                return Err(error!(
                    "contained traversal requires the parent row's id",
                    relation = relation
                ));
            }
        };
        let db = self.table.data_source().clone();
        let notify = self.notify_opt_in();
        self.table.get_contained_ref(
            relation,
            row,
            parent_id,
            move |t| {
                crate::postgres::vista::factory::PostgresVistaFactory::new(db.clone())
                    .with_notify(notify)
                    .from_table(t)
            },
            parse_json_host,
            |c| CborValue::Text(cbor_to_json(c).to_string()),
        )
    }

    /// Watch the table via Postgres `LISTEN/NOTIFY` and stream a coarse
    /// [`VistaChange::Invalidated`] on every notification.
    ///
    /// Postgres notifications carry no row payload, so this is the
    /// invalidate-and-reconcile end of the spectrum (SurrealDB's LIVE feed emits
    /// the fine-grained variants instead) — the consumer re-reads the set on each
    /// signal. The channel is `{table}_changed` by convention; the application
    /// installs a trigger that `pg_notify`s it on every write (see learn-10's
    /// `db::setup`).
    ///
    /// `LISTEN` succeeds whether or not that trigger exists, and an un-triggered
    /// channel simply never fires — so the capability behind this is opt-in via
    /// [`PostgresVistaFactory::with_notify`](crate::postgres::vista::PostgresVistaFactory::with_notify),
    /// not inferred from the table being writable. Advertised via
    /// [`VistaCapabilities::can_subscribe`].
    async fn watch_vista(&self, _vista: &Vista) -> Result<VistaChangeStream> {
        let channel = format!("{}_changed", self.table.table_name());
        let pool = self.table.data_source().pool().clone();

        let stream = async_stream::try_stream! {
            let mut listener = sqlx::postgres::PgListener::connect_with(&pool)
                .await
                .map_err(|e| error!("open pg listener", details = e.to_string()))?;
            listener
                .listen(&channel)
                .await
                .map_err(|e| error!("LISTEN failed", channel = channel.clone(), details = e.to_string()))?;
            loop {
                listener
                    .recv()
                    .await
                    .map_err(|e| error!("recv notification", details = e.to_string()))?;
                yield VistaChange::Invalidated;
            }
        };
        Ok(Box::pin(stream))
    }

    fn capabilities(&self) -> &VistaCapabilities {
        &self.capabilities
    }

    fn driver_name(&self) -> &'static str {
        "postgres"
    }

    /// The SELECT as it stands: every condition, order and page size applied so
    /// far, rendered with values inline. The executed form binds those values as
    /// `$N` parameters instead — same query, different spelling.
    fn preview_query(&self, _vista: &Vista) -> serde_json::Value {
        serde_json::json!({
            "driver": "postgres",
            "table": self.table.table_name(),
            "sql": self.table.select().preview(),
        })
    }
}