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, IndexDef};
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 /// Returns the list of indexes defined on the table, where each index
39 /// is represented by the list of column names it includes.
40 fn indexes() -> &'static [IndexDef] {
41 &[]
42 }
43
44 /// Converts itself into a vector of column-value pairs.
45 fn to_values(self) -> Vec<(ColumnDef, crate::dbms::value::Value)>;
46
47 /// Returns the [`Sanitize`] implementation for the given column name, if any.
48 fn sanitizer(column_name: &'static str) -> Option<Box<dyn Sanitize>>;
49
50 /// Returns the [`Validate`] implementation for the given column name, if any.
51 fn validator(column_name: &'static str) -> Option<Box<dyn Validate>>;
52
53 /// Returns an instance of the [`ForeignFetcher`] for this table schema.
54 fn foreign_fetcher() -> Self::ForeignFetcher {
55 Default::default()
56 }
57
58 /// Returns the fingerprint of the table schema.
59 fn fingerprint() -> TableFingerprint {
60 let mut hasher = std::hash::DefaultHasher::new();
61 std::any::TypeId::of::<Self>().hash(&mut hasher);
62 hasher.finish()
63 }
64}