Skip to main content

spacetimedb_lib/db/
view.rs

1use spacetimedb_sats::{AlgebraicType, AlgebraicTypeRef};
2
3pub const QUERY_VIEW_RETURN_TAG: &str = "__query__";
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum ViewKind {
7    Procedural,
8    Query,
9}
10
11pub fn extract_view_return_product_type_ref(return_type: &AlgebraicType) -> Option<(AlgebraicTypeRef, ViewKind)> {
12    // Query-builder views (`Query<T>`) are encoded as: { __query__: T }.
13    if let Some(product) = return_type.as_product()
14        && product.elements.len() == 1
15        && product.elements[0].name.as_deref() == Some(QUERY_VIEW_RETURN_TAG)
16        && let Some(product_type_ref) = product.elements[0].algebraic_type.as_ref().copied()
17    {
18        return Some((product_type_ref, ViewKind::Query));
19    }
20
21    return_type
22        .as_option()
23        .and_then(AlgebraicType::as_ref)
24        .or_else(|| {
25            return_type
26                .as_array()
27                .map(|array_type| array_type.elem_ty.as_ref())
28                .and_then(AlgebraicType::as_ref)
29        })
30        .copied()
31        .map(|product_type_ref| (product_type_ref, ViewKind::Procedural))
32}