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