use std::hash::{Hash, Hasher};
use serde::{Deserialize, Serialize};
use crate::{Field, common};
use super::Filter;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Join {
pub table: common::TableName,
pub kind: JoinKind,
pub primary_key: common::ColumnName,
#[serde(default)]
pub nullable: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filters: Option<Vec<Filter>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub order_by: Option<Vec<OrderBy>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<u64>,
pub fields: Vec<Field>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub on: Vec<ColumnPair>,
#[serde(
default = "super::field::enabled",
skip_serializing_if = "super::field::is_enabled"
)]
pub indexed: bool,
}
impl Hash for Join {
fn hash<H: Hasher>(&self, state: &mut H) {
let Self {
table,
kind,
primary_key,
nullable,
filters,
order_by,
limit,
fields,
on,
indexed,
} = self;
table.hash(state);
kind.hash(state);
primary_key.hash(state);
nullable.hash(state);
filters.hash(state);
order_by.hash(state);
limit.hash(state);
fields.hash(state);
if !indexed {
"indexed".hash(state);
}
hash_on("on", on, state);
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ColumnPair {
pub local: common::ColumnName,
pub related: common::ColumnName,
}
pub(super) fn hash_on<H: Hasher>(tag: &str, on: &[ColumnPair], state: &mut H) {
if !on.is_empty() {
tag.hash(state);
on.hash(state);
}
}
#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum JoinKind {
BelongsTo { column: common::ColumnName },
HasOne { foreign_key: common::ColumnName },
HasMany { foreign_key: common::ColumnName },
ManyToMany { through: Through },
}
impl JoinKind {
pub fn is_to_many(&self) -> bool {
matches!(self, JoinKind::HasMany { .. } | JoinKind::ManyToMany { .. })
}
}
#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AggregateKey {
Direct(common::ColumnName),
Through(Through),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Through {
pub table: common::TableName,
pub left_key: common::ColumnName,
pub right_key: common::ColumnName,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filters: Option<Vec<Filter>>,
}
impl Hash for Through {
fn hash<H: Hasher>(&self, state: &mut H) {
let Self {
table,
left_key,
right_key,
filters,
} = self;
table.hash(state);
left_key.hash(state);
right_key.hash(state);
if let Some(filters) = filters.as_deref().filter(|f| !f.is_empty()) {
filters.hash(state);
}
}
}
#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
pub struct OrderBy {
pub column: common::ColumnName,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub direction: Option<Direction>,
}
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Direction {
Asc,
Desc,
}