Skip to main content

wasm_dbms_api/dbms/table/
schema.rs

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