Skip to main content

reinhardt_query/query/
foreign_key.rs

1//! Foreign key statement builders.
2//!
3//! This module provides [`ForeignKey`] as an entry point and
4//! [`ForeignKeyCreateStatement`] for building foreign key constraints
5//! compatible with the reinhardt-query builder pattern.
6
7use crate::types::{DynIden, ForeignKeyAction, IntoIden, IntoTableRef, TableRef};
8
9/// Entry point for foreign key operations.
10///
11/// # Example
12///
13/// ```rust,ignore
14/// use reinhardt_query::prelude::*;
15///
16/// let mut fk = ForeignKey::create();
17/// fk.from_tbl(Alias::new("posts"))
18///     .from_col(Alias::new("user_id"))
19///     .to_tbl(Alias::new("users"))
20///     .to_col(Alias::new("id"));
21/// ```
22#[derive(Debug, Clone)]
23pub struct ForeignKey;
24
25impl ForeignKey {
26	/// Create a new foreign key CREATE statement builder.
27	pub fn create() -> ForeignKeyCreateStatement {
28		ForeignKeyCreateStatement::new()
29	}
30}
31
32/// Builder for a CREATE FOREIGN KEY constraint.
33///
34/// This builder collects foreign key metadata (source table/columns,
35/// referenced table/columns, and referential actions) for use in
36/// CREATE TABLE statements.
37#[derive(Debug, Clone, Default)]
38pub struct ForeignKeyCreateStatement {
39	pub(crate) name: Option<DynIden>,
40	pub(crate) from_tbl: Option<TableRef>,
41	pub(crate) from_cols: Vec<DynIden>,
42	pub(crate) to_tbl: Option<TableRef>,
43	pub(crate) to_cols: Vec<DynIden>,
44	pub(crate) on_delete: Option<ForeignKeyAction>,
45	pub(crate) on_update: Option<ForeignKeyAction>,
46}
47
48impl ForeignKeyCreateStatement {
49	/// Create a new empty foreign key builder.
50	pub fn new() -> Self {
51		Self::default()
52	}
53
54	/// Set the constraint name.
55	pub fn name<T>(&mut self, name: T) -> &mut Self
56	where
57		T: IntoIden,
58	{
59		self.name = Some(name.into_iden());
60		self
61	}
62
63	/// Set the source (referencing) table.
64	pub fn from_tbl<T>(&mut self, tbl: T) -> &mut Self
65	where
66		T: IntoTableRef,
67	{
68		self.from_tbl = Some(tbl.into_table_ref());
69		self
70	}
71
72	/// Add a source (referencing) column.
73	pub fn from_col<C>(&mut self, col: C) -> &mut Self
74	where
75		C: IntoIden,
76	{
77		self.from_cols.push(col.into_iden());
78		self
79	}
80
81	/// Set the target (referenced) table.
82	pub fn to_tbl<T>(&mut self, tbl: T) -> &mut Self
83	where
84		T: IntoTableRef,
85	{
86		self.to_tbl = Some(tbl.into_table_ref());
87		self
88	}
89
90	/// Add a target (referenced) column.
91	pub fn to_col<C>(&mut self, col: C) -> &mut Self
92	where
93		C: IntoIden,
94	{
95		self.to_cols.push(col.into_iden());
96		self
97	}
98
99	/// Set the ON DELETE action.
100	pub fn on_delete(&mut self, action: ForeignKeyAction) -> &mut Self {
101		self.on_delete = Some(action);
102		self
103	}
104
105	/// Set the ON UPDATE action.
106	pub fn on_update(&mut self, action: ForeignKeyAction) -> &mut Self {
107		self.on_update = Some(action);
108		self
109	}
110}