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