use crate::alloc_prelude::*;
#[cfg(feature = "serde")]
use crate::serde_helpers::cow_from_string;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TableDef {
pub name: &'static str,
pub strict: bool,
pub without_rowid: bool,
}
impl TableDef {
#[must_use]
pub const fn new(name: &'static str) -> Self {
Self {
name,
strict: false,
without_rowid: false,
}
}
#[must_use]
pub const fn strict(self) -> Self {
Self {
name: self.name,
strict: true,
without_rowid: self.without_rowid,
}
}
#[must_use]
pub const fn without_rowid(self) -> Self {
Self {
name: self.name,
strict: self.strict,
without_rowid: true,
}
}
#[must_use]
pub const fn into_table(self) -> Table {
Table {
name: Cow::Borrowed(self.name),
strict: self.strict,
without_rowid: self.without_rowid,
}
}
}
impl Default for TableDef {
fn default() -> Self {
Self::new("")
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Table {
#[cfg_attr(feature = "serde", serde(deserialize_with = "cow_from_string"))]
pub name: Cow<'static, str>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "core::ops::Not::not")
)]
pub strict: bool,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "core::ops::Not::not")
)]
pub without_rowid: bool,
}
impl Table {
#[must_use]
pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
Self {
name: name.into(),
strict: false,
without_rowid: false,
}
}
#[must_use]
pub const fn strict(mut self) -> Self {
self.strict = true;
self
}
#[must_use]
pub const fn without_rowid(mut self) -> Self {
self.without_rowid = true;
self
}
#[inline]
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
}
impl Default for Table {
fn default() -> Self {
Self::new("")
}
}
impl From<TableDef> for Table {
fn from(def: TableDef) -> Self {
def.into_table()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_const_table_def() {
const TABLE: TableDef = TableDef::new("users").strict().without_rowid();
assert_eq!(TABLE.name, "users");
const {
assert!(TABLE.strict);
}
const {
assert!(TABLE.without_rowid);
}
}
#[test]
fn test_table_def_to_table() {
const DEF: TableDef = TableDef::new("users").strict();
let table = DEF.into_table();
assert_eq!(table.name(), "users");
assert!(table.strict);
}
#[test]
fn test_runtime_table() {
let table = Table::new("posts").strict();
assert_eq!(table.name(), "posts");
assert!(table.strict);
assert!(!table.without_rowid);
}
#[cfg(feature = "serde")]
#[test]
fn test_serde_roundtrip() {
let table = Table::new("users").strict();
let json = serde_json::to_string(&table).unwrap();
let parsed: Table = serde_json::from_str(&json).unwrap();
assert_eq!(parsed.name(), "users");
assert!(parsed.strict);
}
}