1use std::marker::PhantomData;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum ColumnType {
6 Integer,
7 Text,
8 Boolean,
9 DateTime,
10}
11
12pub trait ColumnTypeOf {
14 fn column_type() -> ColumnType;
15 fn nullable() -> bool {
16 false
17 }
18 fn choices() -> Option<Vec<&'static str>> {
19 None
20 }
21}
22
23impl ColumnTypeOf for i64 {
24 fn column_type() -> ColumnType {
25 ColumnType::Integer
26 }
27}
28
29impl ColumnTypeOf for String {
30 fn column_type() -> ColumnType {
31 ColumnType::Text
32 }
33}
34
35impl ColumnTypeOf for bool {
36 fn column_type() -> ColumnType {
37 ColumnType::Boolean
38 }
39}
40
41impl ColumnTypeOf for time::OffsetDateTime {
42 fn column_type() -> ColumnType {
43 ColumnType::DateTime
44 }
45}
46
47impl<T: ColumnTypeOf> ColumnTypeOf for Option<T> {
48 fn column_type() -> ColumnType {
49 T::column_type()
50 }
51 fn nullable() -> bool {
52 true
53 }
54 fn choices() -> Option<Vec<&'static str>> {
55 T::choices()
56 }
57}
58
59pub trait DbEnum: Sized {
61 const VALUES: &'static [&'static str];
62
63 fn as_str(&self) -> &'static str;
64 fn from_str(value: &str) -> Option<Self>;
65}
66
67impl<T: DbEnum> ColumnTypeOf for T {
68 fn column_type() -> ColumnType {
69 ColumnType::Text
70 }
71
72 fn choices() -> Option<Vec<&'static str>> {
73 Some(T::VALUES.to_vec())
74 }
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct ForeignKey {
80 target: String,
81 on_delete: Option<&'static str>,
82}
83
84impl ForeignKey {
85 pub fn new(target: impl Into<String>, on_delete: Option<&'static str>) -> Self {
86 Self {
87 target: target.into(),
88 on_delete,
89 }
90 }
91
92 pub fn target(&self) -> &str {
93 &self.target
94 }
95
96 pub fn on_delete(&self) -> Option<&'static str> {
97 self.on_delete
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct ColumnSchema {
104 pub name: &'static str,
105 pub column_type: ColumnType,
106 pub nullable: bool,
107 pub primary_key: bool,
108 pub unique: bool,
109 pub default: Option<&'static str>,
110 pub check: Option<&'static str>,
111 pub choices: Option<Vec<&'static str>>,
112 pub references: Option<ForeignKey>,
113 pub auto_now_add: bool,
114 pub auto_now: bool,
115}
116
117impl ColumnSchema {
118 pub fn new(name: &'static str, column_type: ColumnType, nullable: bool) -> Self {
119 Self {
120 name,
121 column_type,
122 nullable,
123 primary_key: false,
124 unique: false,
125 default: None,
126 check: None,
127 choices: None,
128 references: None,
129 auto_now_add: false,
130 auto_now: false,
131 }
132 }
133}
134
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct TableSchema {
138 pub name: &'static str,
139 pub columns: Vec<ColumnSchema>,
140 pub unique_constraints: Vec<Vec<&'static str>>,
141 pub indexes: Vec<Vec<&'static str>>,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub enum SchemaError {
147 InvalidIdentifier(String),
148 DuplicateTable(String),
149 DuplicateColumn { table: String, column: String },
150 UnknownColumn { table: String, column: String },
151 InvalidForeignKey(String),
152 InvalidOnDelete(String),
153}
154
155impl TableSchema {
156 pub fn validate(&self) -> Result<(), SchemaError> {
158 validate_identifier(self.name)?;
159 let mut columns = std::collections::HashSet::new();
160 for column in &self.columns {
161 validate_identifier(column.name)?;
162 if !columns.insert(column.name) {
163 return Err(SchemaError::DuplicateColumn {
164 table: self.name.into(),
165 column: column.name.into(),
166 });
167 }
168 if let Some(reference) = &column.references {
169 validate_reference(reference.target())?;
170 if let Some(action) = reference.on_delete() {
171 if !matches!(
172 action.to_ascii_lowercase().as_str(),
173 "cascade" | "restrict" | "no action" | "set null" | "set default"
174 ) {
175 return Err(SchemaError::InvalidOnDelete(action.into()));
176 }
177 }
178 }
179 }
180 for group in self.unique_constraints.iter().chain(self.indexes.iter()) {
181 for column in group {
182 validate_identifier(column)?;
183 if !columns.contains(column) {
184 return Err(SchemaError::UnknownColumn {
185 table: self.name.into(),
186 column: (*column).into(),
187 });
188 }
189 }
190 }
191 Ok(())
192 }
193}
194
195impl SchemaSet {
196 pub fn validate(&self) -> Result<(), SchemaError> {
198 let mut tables = std::collections::HashSet::new();
199 for table in &self.tables {
200 table.validate()?;
201 if !tables.insert(table.name) {
202 return Err(SchemaError::DuplicateTable(table.name.into()));
203 }
204 }
205 for table in &self.tables {
206 for column in &table.columns {
207 let Some(reference) = &column.references else {
208 continue;
209 };
210 let (target_table, target_column) = reference
211 .target
212 .split_once('(')
213 .and_then(|(table, column)| {
214 column.strip_suffix(')').map(|column| (table, column))
215 })
216 .ok_or_else(|| SchemaError::InvalidForeignKey(reference.target().into()))?;
217 let target = self
218 .tables
219 .iter()
220 .find(|candidate| candidate.name == target_table)
221 .ok_or_else(|| SchemaError::InvalidForeignKey(reference.target().into()))?;
222 if !target
223 .columns
224 .iter()
225 .any(|candidate| candidate.name == target_column)
226 {
227 return Err(SchemaError::UnknownColumn {
228 table: target_table.into(),
229 column: target_column.into(),
230 });
231 }
232 }
233 }
234 Ok(())
235 }
236
237 pub fn try_to_sql<D: crate::SqlDialect>(&self) -> Result<String, SchemaError> {
239 self.validate()?;
240 Ok(self.to_sql_unchecked::<D>())
241 }
242}
243
244fn validate_identifier(identifier: &str) -> Result<(), SchemaError> {
245 let mut chars = identifier.chars();
246 let valid_start = chars
247 .next()
248 .is_some_and(|ch| ch == '_' || ch.is_ascii_alphabetic());
249 if valid_start && chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric()) {
250 Ok(())
251 } else {
252 Err(SchemaError::InvalidIdentifier(identifier.into()))
253 }
254}
255
256fn validate_reference(reference: &str) -> Result<(), SchemaError> {
257 let Some((table, column)) = reference.split_once('(') else {
258 return Err(SchemaError::InvalidForeignKey(reference.into()));
259 };
260 let Some(column) = column.strip_suffix(')') else {
261 return Err(SchemaError::InvalidForeignKey(reference.into()));
262 };
263 validate_identifier(table)?;
264 validate_identifier(column)
265}
266
267#[derive(Debug, Default, Clone, PartialEq, Eq)]
269pub struct SchemaSet {
270 tables: Vec<TableSchema>,
271}
272
273impl SchemaSet {
274 pub fn new() -> Self {
276 Self::default()
277 }
278
279 pub fn model<M: crate::Model>(mut self) -> Self {
281 self.tables.push(M::schema());
282 self
283 }
284
285 pub fn merge(mut self, other: Self) -> Self {
287 self.tables.extend(other.tables);
288 self
289 }
290
291 pub fn to_sql<D: crate::SqlDialect>(&self) -> String {
293 self.validate().expect("invalid model schema");
294 self.to_sql_unchecked::<D>()
295 }
296
297 fn to_sql_unchecked<D: crate::SqlDialect>(&self) -> String {
298 let mut statements = Vec::new();
299 for table in &self.tables {
300 let compiled = crate::SqlCompiler::<D>::compile_schema(table);
301 statements.push(compiled.table);
302 statements.extend(compiled.indexes);
303 }
304 statements.join(";\n") + if statements.is_empty() { "" } else { ";\n" }
305 }
306}
307
308pub trait AppConfig {
310 fn name() -> &'static str;
312
313 fn schema() -> SchemaSet;
315}
316
317#[derive(Debug, Default, Clone, PartialEq, Eq)]
319pub struct AppRegistry {
320 apps: Vec<&'static str>,
321 schema: SchemaSet,
322}
323
324impl AppRegistry {
325 pub fn new() -> Self {
327 Self::default()
328 }
329
330 pub fn register<A: AppConfig>(mut self) -> Self {
332 self.apps.push(A::name());
333 self.schema = self.schema.merge(A::schema());
334 self
335 }
336
337 pub fn apps(&self) -> &[&'static str] {
339 &self.apps
340 }
341
342 pub fn schema(&self) -> &SchemaSet {
344 &self.schema
345 }
346
347 pub fn to_sql<D: crate::SqlDialect>(&self) -> String {
349 self.schema.to_sql::<D>()
350 }
351}
352
353#[derive(Debug, Clone)]
354pub struct CreateTableAst {
356 pub schema: TableSchema,
357}
358
359pub struct CreateTableQuery<M> {
361 ast: CreateTableAst,
362 _model: PhantomData<M>,
363}
364
365impl<M> CreateTableQuery<M> {
366 pub fn new(schema: TableSchema) -> Self {
367 Self {
368 ast: CreateTableAst { schema },
369 _model: PhantomData,
370 }
371 }
372
373 pub fn into_ast(self) -> crate::QueryAst {
374 crate::QueryAst::CreateTable(self.ast)
375 }
376}