1use crate::schema::{CompositeType, Grant, Index, Role, Table, View};
2use std::collections::HashMap;
3
4pub struct CodeGenerator;
6
7impl CodeGenerator {
8 pub fn generate_table_definitions(&self, tables: &[Table]) -> HashMap<String, String> {
10 let mut definitions = HashMap::new();
11
12 for table in tables {
13 let table_name = &table.name;
14 let primary_key = table.primary_key.as_ref();
15 let columns = &table.columns;
16
17 let mut macro_body = String::new();
18 macro_body.push_str("use ignis_db::table;\n\n");
19 macro_body.push_str(&format!("table!({} ", table_name));
20
21 let default_pk = "id".to_string();
23 let pk = primary_key.unwrap_or(&default_pk);
24 if pk.contains(',') {
25 macro_body.push_str(&format!("({}) {{\n", pk));
27 } else {
28 macro_body.push_str(&format!("({}) {{\n", pk));
30 }
31
32 for column in columns {
34 let column_name = &column.name;
35 let column_type = self.column_type_to_macro_type(&column.column_type);
36 macro_body.push_str(&format!(" {} -> {},\n", column_name, column_type));
37 }
38
39 macro_body.push_str("});");
40
41 definitions.insert(table_name.to_string(), macro_body);
42 }
43
44 definitions
45 }
46
47 pub fn generate_view_definitions(&self, views: &[View]) -> HashMap<String, String> {
49 let mut definitions = HashMap::new();
50
51 for view in views {
52 let view_name = &view.name;
53 let is_materialized = view.materialized;
54 let default_sql = String::new();
55 let sql = view.ddl.as_ref().unwrap_or(&default_sql);
56
57 let mut macro_body = String::new();
58 if is_materialized {
59 macro_body.push_str(&format!("view!({} #[materialized] {{\n", view_name));
60 } else {
61 macro_body.push_str(&format!("view!({} {{\n", view_name));
62 }
63
64 macro_body.push_str(&format!(" {}\n", sql));
65 macro_body.push_str("});");
66
67 definitions.insert(view_name.to_string(), macro_body);
68 }
69
70 definitions
71 }
72
73 pub fn generate_composite_definitions(
75 &self,
76 types: &[CompositeType],
77 ) -> HashMap<String, String> {
78 let mut definitions = HashMap::new();
79
80 let composite_type_names: std::collections::HashSet<String> =
82 types.iter().map(|t| self.to_pascal_case(&t.name)).collect();
83
84 for composite_type in types {
85 let type_name = &composite_type.name;
86 let fields = &composite_type.fields;
87
88 let mut struct_body = String::new();
89 struct_body.push_str("use ignis_derive::PgComposite;\n");
90
91 let mut referenced_types = std::collections::HashSet::new();
93 for field in fields {
94 let field_type = self.field_type_to_rust_type(&field.field_type);
95 let base_type = if field_type.starts_with("Option<") && field_type.ends_with(">") {
97 field_type[7..field_type.len() - 1].to_string() } else {
99 field_type.clone()
100 };
101
102 if composite_type_names.contains(&base_type)
103 && base_type != self.to_pascal_case(type_name)
104 {
105 referenced_types.insert(base_type);
106 }
107 }
108
109 for referenced_type in &referenced_types {
111 let snake_case_name = self.to_snake_case(referenced_type);
112 struct_body.push_str(&format!(
113 "use crate::schema::composite_types::{}::{};\n",
114 snake_case_name, referenced_type
115 ));
116 }
117
118 struct_body.push_str("\n");
119 struct_body.push_str(&format!("#[derive(Debug, Clone, PgComposite)]\n"));
120 struct_body.push_str(&format!("#[pg_composite(name = \"{}\")]\n", type_name));
121 struct_body.push_str(&format!(
122 "pub struct {} {{\n",
123 self.to_pascal_case(type_name)
124 ));
125
126 for field in fields {
127 let field_name = &field.name;
128 let field_type = self.field_type_to_rust_type(&field.field_type);
129 let nullable = field.nullable;
130
131 let rust_type = if nullable {
132 format!("Option<{}>", field_type)
133 } else {
134 field_type
135 };
136
137 struct_body.push_str(&format!(" pub {}: {},\n", field_name, rust_type));
138 }
139
140 struct_body.push_str("}");
141
142 definitions.insert(type_name.to_string(), struct_body);
143 }
144
145 definitions
146 }
147
148 pub fn generate_model_structs(&self, tables: &[Table]) -> HashMap<String, String> {
150 let mut definitions = HashMap::new();
151
152 for table in tables {
153 let table_name = &table.name;
154 let columns = &table.columns;
155 let primary_key = table.primary_key.as_ref();
156
157 let mut struct_body = String::new();
158 struct_body
159 .push_str("use ignis_db::{IgnisModel, Insertable, Updatable, Deletable};\n\n");
160 struct_body.push_str(&format!(
161 "#[derive(Debug, Clone, IgnisModel, Insertable, Updatable, Deletable)]\n"
162 ));
163
164 let default_pk = "id".to_string();
166 let pk = primary_key.unwrap_or(&default_pk);
167 struct_body.push_str(&format!(
168 "#[ignis(table = \"{}\", pk = \"{}\")]\n",
169 table_name, pk
170 ));
171 struct_body.push_str(&format!(
172 "pub struct {} {{\n",
173 self.to_pascal_case(table_name)
174 ));
175
176 for column in columns {
177 let column_name = &column.name;
178 let column_type = self.column_type_to_rust_type(&column.column_type);
179 let nullable = column.nullable;
180
181 let rust_type = if nullable {
182 format!("Option<{}>", column_type)
183 } else {
184 column_type
185 };
186
187 struct_body.push_str(&format!(" pub {}: {},\n", column_name, rust_type));
188 }
189
190 struct_body.push_str("}");
191
192 definitions.insert(table_name.to_string(), struct_body);
193 }
194
195 definitions
196 }
197
198 pub fn generate_misc_definitions(
200 &self,
201 indexes: &[Index],
202 roles: &[Role],
203 grants: &[Grant],
204 ) -> HashMap<String, String> {
205 let mut definitions = HashMap::new();
206
207 for index in indexes {
209 let index_name = &index.name;
210 let table_name = "table_name"; let columns = &index.columns;
212 let index_type = if index.unique { "Unique" } else { "BTree" };
213
214 let mut macro_body = String::new();
215 macro_body.push_str(&format!("index!({} ON {} {{\n", index_name, table_name));
216
217 for column in columns {
218 macro_body.push_str(&format!(" {},\n", column));
219 }
220
221 macro_body.push_str(&format!("}} #[{:?}]);", index_type));
222
223 definitions.insert(format!("index_{}", index_name), macro_body);
224 }
225
226 for role in roles {
228 let role_name = &role.name;
229 let can_login = role.login;
230 let is_superuser = role.superuser;
231
232 let mut macro_body = String::new();
233 macro_body.push_str(&format!("role! {{\n"));
234 macro_body.push_str(&format!(" {} ", role_name));
235
236 if can_login {
237 macro_body.push_str("#[login] ");
238 }
239 if is_superuser {
240 macro_body.push_str("#[superuser] ");
241 }
242
243 macro_body.push_str("\n}");
244
245 definitions.insert(format!("role_{}", role_name), macro_body);
246 }
247
248 for grant in grants {
250 let grantee = &grant.grantee;
251 let privilege = grant.privilege_name();
252 let target = &grant.target;
253 let object_name = match target {
254 crate::schema::GrantTarget::Table { table, .. } => table,
255 crate::schema::GrantTarget::Schema(schema) => schema,
256 crate::schema::GrantTarget::Database(db) => db,
257 crate::schema::GrantTarget::Function { function, .. } => function,
258 crate::schema::GrantTarget::AllTablesInSchema(schema) => schema,
259 crate::schema::GrantTarget::AllFunctionsInSchema(schema) => schema,
260 crate::schema::GrantTarget::Role(role) => role,
261 };
262
263 let mut macro_body = String::new();
264 macro_body.push_str(&format!("grant! {{\n"));
265 macro_body.push_str(&format!(
266 " {} ON {} TO {}\n",
267 privilege, object_name, grantee
268 ));
269 macro_body.push_str("}");
270
271 definitions.insert(
272 format!("grant_{}_{}_{}", grantee, privilege, object_name),
273 macro_body,
274 );
275 }
276
277 definitions
278 }
279
280 pub fn generate_module_structure(
282 &self,
283 tables: &[Table],
284 views: &[View],
285 composite_types: &[CompositeType],
286 indexes: &[Index],
287 roles: &[Role],
288 grants: &[Grant],
289 ) -> HashMap<String, String> {
290 let mut modules = HashMap::new();
291
292 let schema_mod =
294 self.generate_schema_module(tables, views, composite_types, indexes, roles, grants);
295 modules.insert("schema/mod.rs".to_string(), schema_mod);
296
297 let models_mod = self.generate_models_module(tables);
299 modules.insert("models/mod.rs".to_string(), models_mod);
300
301 for table in tables {
303 let table_name = &table.name;
304 let table_mod = self.generate_table_module(table);
305 modules.insert(format!("schema/tables/{}.rs", table_name), table_mod);
306 }
307
308 for view in views {
310 let view_name = &view.name;
311 let view_mod = self.generate_view_module(view);
312 modules.insert(format!("schema/views/{}.rs", view_name), view_mod);
313 }
314
315 for composite_type in composite_types {
317 let type_name = &composite_type.name;
318 let type_mod = self.generate_composite_type_module(composite_type);
319 modules.insert(format!("schema/composite_types/{}.rs", type_name), type_mod);
320 }
321
322 modules
323 }
324
325 fn generate_schema_module(
327 &self,
328 tables: &[Table],
329 views: &[View],
330 composite_types: &[CompositeType],
331 _indexes: &[Index],
332 _roles: &[Role],
333 _grants: &[Grant],
334 ) -> String {
335 let mut module = String::new();
336 module.push_str("// Auto-generated schema module\n");
337 module.push_str("// Generated by ignis-db init\n\n");
338
339 module.push_str("pub mod tables;\n");
341 for table in tables {
342 module.push_str(&format!("pub use tables::{};\n", table.name));
343 }
344 module.push_str("\n");
345
346 if !views.is_empty() {
348 module.push_str("pub mod views;\n");
349 for view in views {
350 module.push_str(&format!("pub use views::{};\n", view.name));
351 }
352 module.push_str("\n");
353 }
354
355 if !composite_types.is_empty() {
357 module.push_str("pub mod composite_types;\n");
358 for composite_type in composite_types {
359 module.push_str(&format!(
360 "pub use composite_types::{};\n",
361 composite_type.name
362 ));
363 }
364 module.push_str("\n");
365 }
366
367 module
368 }
369
370 fn generate_models_module(&self, tables: &[Table]) -> String {
372 let mut module = String::new();
373 module.push_str("// Auto-generated models module\n");
374 module.push_str("// Generated by ignis-db init\n\n");
375
376 for table in tables {
377 let table_name = &table.name;
378 let struct_name = self.to_pascal_case(table_name);
379 module.push_str(&format!("pub mod {};\n", table_name));
380 module.push_str(&format!("pub use {}::{};\n", table_name, struct_name));
381 }
382
383 module
384 }
385
386 fn generate_table_module(&self, table: &Table) -> String {
388 let table_name = &table.name;
389 let primary_key = table.primary_key.as_ref();
390 let columns = &table.columns;
391
392 let mut module = String::new();
393 module.push_str(&format!(
394 "// Auto-generated table module for {}\n",
395 table_name
396 ));
397 module.push_str("// Generated by ignis-db init\n\n");
398
399 module.push_str("use crate::schema::{Table, Column, ColumnType};\n\n");
400
401 let default_pk = "id".to_string();
403 let pk = primary_key.unwrap_or(&default_pk);
404 module.push_str(&format!("table!({} ({}) {{\n", table_name, pk));
405
406 for column in columns {
407 let column_name = &column.name;
408 let column_type = self.column_type_to_macro_type(&column.column_type);
409 module.push_str(&format!(" {} -> {},\n", column_name, column_type));
410 }
411
412 module.push_str("});\n\n");
413
414 module.push_str(&format!("pub fn table() -> Table {{\n"));
416 module.push_str(&format!(
417 " let mut table = Table::new(\"{}\");\n",
418 table_name
419 ));
420
421 for column in columns {
422 let column_name = &column.name;
423 let column_type = self.column_type_to_macro_type(&column.column_type);
424 module.push_str(&format!(
425 " table = table.add_column(Column::new(\"{}\", {}));\n",
426 column_name, column_type
427 ));
428 }
429
430 module.push_str(&format!(" table = table.set_primary_key(\"{}\");\n", pk));
432
433 module.push_str(" table\n");
434 module.push_str("}\n");
435
436 module
437 }
438
439 fn generate_view_module(&self, view: &View) -> String {
441 let view_name = &view.name;
442 let is_materialized = view.materialized;
443 let default_sql = String::new();
444 let sql = view.ddl.as_ref().unwrap_or(&default_sql);
445
446 let mut module = String::new();
447 module.push_str(&format!(
448 "// Auto-generated view module for {}\n",
449 view_name
450 ));
451 module.push_str("// Generated by ignis-db init\n\n");
452
453 if is_materialized {
455 module.push_str(&format!("view!({} #[materialized] {{\n", view_name));
456 } else {
457 module.push_str(&format!("view!({} {{\n", view_name));
458 }
459
460 module.push_str(&format!(" {}\n", sql));
461 module.push_str("});\n");
462
463 module
464 }
465
466 fn generate_composite_type_module(&self, composite_type: &CompositeType) -> String {
468 let type_name = &composite_type.name;
469 let fields = &composite_type.fields;
470
471 let mut module = String::new();
472 module.push_str(&format!(
473 "// Auto-generated composite type module for {}\n",
474 type_name
475 ));
476 module.push_str("// Generated by ignis-db init\n\n");
477
478 module.push_str(&format!(
479 "use crate::schema::{{CompositeType, CompositeField}};\n\n"
480 ));
481
482 module.push_str(&format!("#[derive(Debug, Clone, PgComposite)]\n"));
484 module.push_str(&format!("#[pg_composite(name = \"{}\")]\n", type_name));
485 module.push_str(&format!(
486 "pub struct {} {{\n",
487 self.to_pascal_case(type_name)
488 ));
489
490 for field in fields {
491 let field_name = &field.name;
492 let field_type = self.field_type_to_rust_type(&field.field_type);
493 let nullable = field.nullable;
494
495 let rust_type = if nullable {
496 format!("Option<{}>", field_type)
497 } else {
498 field_type
499 };
500
501 module.push_str(&format!(" pub {}: {},\n", field_name, rust_type));
502 }
503
504 module.push_str("}\n\n");
505
506 module.push_str(&format!("pub fn composite_type() -> CompositeType {{\n"));
508 module.push_str(&format!(
509 " let mut composite_type = CompositeType::new(\"{}\");\n",
510 type_name
511 ));
512
513 for field in fields {
514 let field_name = &field.name;
515 let field_type = &field.field_type;
516 let nullable = field.nullable;
517
518 module.push_str(&format!(" composite_type = composite_type.add_field(\n"));
519 module.push_str(&format!(
520 " CompositeField::new(\"{}\", \"{}\")\n",
521 field_name, field_type
522 ));
523 if !nullable {
524 module.push_str(&format!(" .with_nullable(false)\n"));
525 }
526 module.push_str(&format!(" );\n"));
527 }
528
529 module.push_str(" composite_type\n");
530 module.push_str("}\n");
531
532 module
533 }
534
535 fn column_type_to_macro_type(&self, column_type: &crate::schema::ColumnType) -> String {
537 match column_type {
538 crate::schema::ColumnType::Int4 => "Int4".to_string(),
539 crate::schema::ColumnType::Int8 => "Int8".to_string(),
540 crate::schema::ColumnType::Int2 => "Int2".to_string(),
541 crate::schema::ColumnType::Text => "Text".to_string(),
542 crate::schema::ColumnType::Varchar(Some(len)) => format!("Varchar({})", len),
543 crate::schema::ColumnType::Varchar(None) => "Varchar".to_string(),
544 crate::schema::ColumnType::Char => "Char".to_string(),
545 crate::schema::ColumnType::Bool => "Bool".to_string(),
546 crate::schema::ColumnType::Timestamptz => "Timestamptz".to_string(),
547 crate::schema::ColumnType::Date => "Date".to_string(),
549 crate::schema::ColumnType::Time => "Time".to_string(),
550 crate::schema::ColumnType::Uuid => "Uuid".to_string(),
551 crate::schema::ColumnType::Numeric(Some(p), Some(s)) => {
552 format!("Numeric({}, {})", p, s)
553 }
554 crate::schema::ColumnType::Numeric(Some(p), None) => format!("Numeric({})", p),
555 crate::schema::ColumnType::Numeric(None, Some(s)) => format!("Numeric(, {})", s),
556 crate::schema::ColumnType::Numeric(None, None) => "Numeric".to_string(),
557 crate::schema::ColumnType::Jsonb => "Jsonb".to_string(),
558 crate::schema::ColumnType::Json => "Json".to_string(),
559 crate::schema::ColumnType::Bytea => "Bytea".to_string(),
560 crate::schema::ColumnType::Array(inner) => {
562 let inner_type = self.column_type_to_macro_type(inner);
563 format!("Array({})", inner_type)
564 }
565 crate::schema::ColumnType::Custom(name) => format!("Custom({})", name),
566 crate::schema::ColumnType::Serial => "Serial".to_string(),
568 crate::schema::ColumnType::BigSerial => "BigSerial".to_string(),
569 crate::schema::ColumnType::SmallSerial => "SmallSerial".to_string(),
570 }
571 }
572
573 pub fn column_type_to_rust_type(&self, column_type: &crate::schema::ColumnType) -> String {
575 match column_type {
576 crate::schema::ColumnType::Int4 => "i32".to_string(),
577 crate::schema::ColumnType::Int8 => "i64".to_string(),
578 crate::schema::ColumnType::Int2 => "i16".to_string(),
579 crate::schema::ColumnType::Text => "String".to_string(),
580 crate::schema::ColumnType::Varchar(_) => "String".to_string(),
581 crate::schema::ColumnType::Char => "String".to_string(),
582 crate::schema::ColumnType::Bool => "bool".to_string(),
583 crate::schema::ColumnType::Timestamptz => "chrono::DateTime<chrono::Utc>".to_string(),
584 crate::schema::ColumnType::Date => "chrono::NaiveDate".to_string(),
586 crate::schema::ColumnType::Time => "chrono::NaiveTime".to_string(),
587 crate::schema::ColumnType::Uuid => "sqlx::types::Uuid".to_string(),
588 crate::schema::ColumnType::Numeric(_, _) => "rust_decimal::Decimal".to_string(),
589 crate::schema::ColumnType::Jsonb => "serde_json::Value".to_string(),
590 crate::schema::ColumnType::Json => "serde_json::Value".to_string(),
591 crate::schema::ColumnType::Bytea => "Vec<u8>".to_string(),
592 crate::schema::ColumnType::Array(inner) => {
594 let inner_type = self.column_type_to_rust_type(inner);
595 format!("Vec<{}>", inner_type)
596 }
597 crate::schema::ColumnType::Custom(name) => self.to_pascal_case(name),
598 crate::schema::ColumnType::Serial => "i32".to_string(),
600 crate::schema::ColumnType::BigSerial => "i64".to_string(),
601 crate::schema::ColumnType::SmallSerial => "i16".to_string(),
602 }
603 }
604
605 fn field_type_to_rust_type(&self, field_type: &str) -> String {
607 match field_type.to_lowercase().as_str() {
608 "integer" | "int" | "int4" => "i32".to_string(),
609 "bigint" | "int8" => "i64".to_string(),
610 "smallint" | "int2" => "i16".to_string(),
611 "text" => "String".to_string(),
612 "varchar" | "character varying" => "String".to_string(),
613 "char" | "character" => "String".to_string(),
614 "boolean" | "bool" => "bool".to_string(),
615 "timestamp with time zone" | "timestamptz" => {
616 "chrono::DateTime<chrono::Utc>".to_string()
617 }
618 "timestamp without time zone" | "timestamp" => "chrono::NaiveDateTime".to_string(),
619 "date" => "chrono::NaiveDate".to_string(),
620 "time" => "chrono::NaiveTime".to_string(),
621 "uuid" => "sqlx::types::Uuid".to_string(),
622 "numeric" | "decimal" => "rust_decimal::Decimal".to_string(),
623 "jsonb" => "serde_json::Value".to_string(),
624 "json" => "serde_json::Value".to_string(),
625 "bytea" => "Vec<u8>".to_string(),
626 "real" | "float4" => "f32".to_string(),
627 "double precision" | "float8" => "f64".to_string(),
628 array_type if array_type.ends_with("[]") => {
630 let base_type = &array_type[..array_type.len() - 2];
631 let base_rust_type = self.field_type_to_rust_type(base_type);
632 format!("Vec<{}>", base_rust_type)
633 }
634 custom => self.to_pascal_case(custom),
636 }
637 }
638
639 pub fn to_pascal_case(&self, s: &str) -> String {
641 s.split('_')
642 .map(|word| {
643 let mut chars = word.chars();
644 match chars.next() {
645 None => String::new(),
646 Some(first) => first.to_uppercase().chain(chars).collect(),
647 }
648 })
649 .collect()
650 }
651
652 pub fn to_snake_case(&self, s: &str) -> String {
653 let mut result = String::new();
654 for (i, ch) in s.chars().enumerate() {
655 if ch.is_uppercase() && i > 0 {
656 result.push('_');
657 }
658 result.push(ch.to_lowercase().next().unwrap_or(ch));
659 }
660 result
661 }
662}
663
664#[cfg(test)]
665mod tests {
666 use super::*;
667 use crate::schema::{Column, ColumnType};
668
669 #[test]
670 fn test_column_type_to_macro_type() {
671 let generator = CodeGenerator;
672
673 assert_eq!(
674 generator.column_type_to_macro_type(&ColumnType::Int4),
675 "Int4"
676 );
677 assert_eq!(
678 generator.column_type_to_macro_type(&ColumnType::Varchar(Some(255))),
679 "Varchar(255)"
680 );
681 assert_eq!(
682 generator.column_type_to_macro_type(&ColumnType::Text),
683 "Text"
684 );
685 }
686
687 #[test]
688 fn test_column_type_to_rust_type() {
689 let generator = CodeGenerator;
690
691 assert_eq!(generator.column_type_to_rust_type(&ColumnType::Int4), "i32");
692 assert_eq!(
693 generator.column_type_to_rust_type(&ColumnType::Text),
694 "String"
695 );
696 assert_eq!(
697 generator.column_type_to_rust_type(&ColumnType::Timestamptz),
698 "chrono::DateTime<chrono::Utc>"
699 );
700 }
701
702 #[test]
703 fn test_to_pascal_case() {
704 let generator = CodeGenerator;
705
706 assert_eq!(generator.to_pascal_case("user_profile"), "UserProfile");
707 assert_eq!(generator.to_pascal_case("order_items"), "OrderItems");
708 assert_eq!(generator.to_pascal_case("id"), "Id");
709 }
710}