ic_dbms_api/dbms/table/
schema.rs

1use std::hash::{Hash as _, Hasher as _};
2
3use candid::CandidType;
4
5use crate::dbms::foreign_fetcher::ForeignFetcher;
6use crate::dbms::table::column_def::ColumnDef;
7use crate::dbms::table::{InsertRecord, TableRecord, UpdateRecord};
8use crate::memory::Encode;
9use crate::prelude::Validate;
10
11/// A type representing a unique fingerprint for a table schema.
12pub type TableFingerprint = u64;
13
14/// Table schema representation.
15///
16/// It is used to define the structure of a database table.
17pub trait TableSchema
18where
19    Self: Encode + CandidType + 'static,
20{
21    /// The [`TableRecord`] type associated with this table schema;
22    /// which is the data returned by a query.
23    type Record: TableRecord<Schema = Self>;
24    /// The [`InsertRecord`] type associated with this table schema.
25    type Insert: InsertRecord<Schema = Self>;
26    /// The [`UpdateRecord`] type associated with this table schema.
27    type Update: UpdateRecord<Schema = Self>;
28    /// The [`ForeignFetcher`] type associated with this table schema.
29    type ForeignFetcher: ForeignFetcher;
30
31    /// Returns the name of the table.
32    fn table_name() -> &'static str;
33
34    /// Returns the column definitions of the table.
35    fn columns() -> &'static [ColumnDef];
36
37    /// Returns the name of the primary key column.
38    fn primary_key() -> &'static str;
39
40    /// Converts itself into a vector of column-value pairs.
41    fn to_values(self) -> Vec<(ColumnDef, crate::dbms::value::Value)>;
42
43    /// Returns the [`Validate`] implementation for the given column name, if any.
44    fn validator(column_name: &'static str) -> Option<Box<dyn Validate>>;
45
46    /// Returns an instance of the [`ForeignFetcher`] for this table schema.
47    fn foreign_fetcher() -> Self::ForeignFetcher {
48        Default::default()
49    }
50
51    /// Returns the fingerprint of the table schema.
52    fn fingerprint() -> TableFingerprint {
53        let mut hasher = std::hash::DefaultHasher::new();
54        std::any::TypeId::of::<Self>().hash(&mut hasher);
55        hasher.finish()
56    }
57}