Skip to main content

cast_core/
column.rs

1//! Typed column references. Generated by `#[derive(Model)]`.
2//!
3//! The point of `Column<M, T>` is compile-time type safety on the where clause:
4//! `User::query().where_eq(User::columns().email(), 42)` fails because 42 is `i32`,
5//! not `String`.
6
7use std::marker::PhantomData;
8
9use sea_query::DynIden;
10
11#[derive(Debug, Clone, Copy)]
12pub struct Column<M, T> {
13    name: &'static str,
14    _marker: PhantomData<(fn() -> M, fn() -> T)>,
15}
16
17impl<M, T> Column<M, T> {
18    pub const fn new(name: &'static str) -> Self {
19        Self {
20            name,
21            _marker: PhantomData,
22        }
23    }
24
25    pub fn name(&self) -> &'static str {
26        self.name
27    }
28
29    pub fn iden(&self) -> sea_query::Alias {
30        sea_query::Alias::new(self.name)
31    }
32}
33
34/// Untyped column reference for the query builder's internal use.
35#[derive(Debug, Clone)]
36pub struct ColumnRef {
37    pub table: Option<&'static str>,
38    pub name: &'static str,
39}
40
41impl ColumnRef {
42    pub fn new(name: &'static str) -> Self {
43        Self { table: None, name }
44    }
45
46    pub fn qualified(table: &'static str, name: &'static str) -> Self {
47        Self {
48            table: Some(table),
49            name,
50        }
51    }
52
53    pub fn iden(&self) -> DynIden {
54        sea_query::SeaRc::new(sea_query::Alias::new(self.name))
55    }
56}
57
58impl<M, T> From<Column<M, T>> for ColumnRef {
59    fn from(c: Column<M, T>) -> Self {
60        ColumnRef::new(c.name)
61    }
62}