use crate::schema::{CompositeType, Grant, Index, Role, Table, View};
use std::collections::HashMap;
pub struct CodeGenerator;
impl CodeGenerator {
pub fn generate_table_definitions(&self, tables: &[Table]) -> HashMap<String, String> {
let mut definitions = HashMap::new();
for table in tables {
let table_name = &table.name;
let primary_key = table.primary_key.as_ref();
let columns = &table.columns;
let mut macro_body = String::new();
macro_body.push_str("use ignis_db::table;\n\n");
macro_body.push_str(&format!("table!({} ", table_name));
let default_pk = "id".to_string();
let pk = primary_key.unwrap_or(&default_pk);
if pk.contains(',') {
macro_body.push_str(&format!("({}) {{\n", pk));
} else {
macro_body.push_str(&format!("({}) {{\n", pk));
}
for column in columns {
let column_name = &column.name;
let column_type = self.column_type_to_macro_type(&column.column_type);
macro_body.push_str(&format!(" {} -> {},\n", column_name, column_type));
}
macro_body.push_str("});");
definitions.insert(table_name.to_string(), macro_body);
}
definitions
}
pub fn generate_view_definitions(&self, views: &[View]) -> HashMap<String, String> {
let mut definitions = HashMap::new();
for view in views {
let view_name = &view.name;
let is_materialized = view.materialized;
let default_sql = String::new();
let sql = view.ddl.as_ref().unwrap_or(&default_sql);
let mut macro_body = String::new();
if is_materialized {
macro_body.push_str(&format!("view!({} #[materialized] {{\n", view_name));
} else {
macro_body.push_str(&format!("view!({} {{\n", view_name));
}
macro_body.push_str(&format!(" {}\n", sql));
macro_body.push_str("});");
definitions.insert(view_name.to_string(), macro_body);
}
definitions
}
pub fn generate_composite_definitions(
&self,
types: &[CompositeType],
) -> HashMap<String, String> {
let mut definitions = HashMap::new();
let composite_type_names: std::collections::HashSet<String> =
types.iter().map(|t| self.to_pascal_case(&t.name)).collect();
for composite_type in types {
let type_name = &composite_type.name;
let fields = &composite_type.fields;
let mut struct_body = String::new();
struct_body.push_str("use ignis_derive::PgComposite;\n");
let mut referenced_types = std::collections::HashSet::new();
for field in fields {
let field_type = self.field_type_to_rust_type(&field.field_type);
let base_type = if field_type.starts_with("Option<") && field_type.ends_with(">") {
field_type[7..field_type.len() - 1].to_string() } else {
field_type.clone()
};
if composite_type_names.contains(&base_type)
&& base_type != self.to_pascal_case(type_name)
{
referenced_types.insert(base_type);
}
}
for referenced_type in &referenced_types {
let snake_case_name = self.to_snake_case(referenced_type);
struct_body.push_str(&format!(
"use crate::schema::composite_types::{}::{};\n",
snake_case_name, referenced_type
));
}
struct_body.push_str("\n");
struct_body.push_str(&format!("#[derive(Debug, Clone, PgComposite)]\n"));
struct_body.push_str(&format!("#[pg_composite(name = \"{}\")]\n", type_name));
struct_body.push_str(&format!(
"pub struct {} {{\n",
self.to_pascal_case(type_name)
));
for field in fields {
let field_name = &field.name;
let field_type = self.field_type_to_rust_type(&field.field_type);
let nullable = field.nullable;
let rust_type = if nullable {
format!("Option<{}>", field_type)
} else {
field_type
};
struct_body.push_str(&format!(" pub {}: {},\n", field_name, rust_type));
}
struct_body.push_str("}");
definitions.insert(type_name.to_string(), struct_body);
}
definitions
}
pub fn generate_model_structs(&self, tables: &[Table]) -> HashMap<String, String> {
let mut definitions = HashMap::new();
for table in tables {
let table_name = &table.name;
let columns = &table.columns;
let primary_key = table.primary_key.as_ref();
let mut struct_body = String::new();
struct_body
.push_str("use ignis_db::{IgnisModel, Insertable, Updatable, Deletable};\n\n");
struct_body.push_str(&format!(
"#[derive(Debug, Clone, IgnisModel, Insertable, Updatable, Deletable)]\n"
));
let default_pk = "id".to_string();
let pk = primary_key.unwrap_or(&default_pk);
struct_body.push_str(&format!(
"#[ignis(table = \"{}\", pk = \"{}\")]\n",
table_name, pk
));
struct_body.push_str(&format!(
"pub struct {} {{\n",
self.to_pascal_case(table_name)
));
for column in columns {
let column_name = &column.name;
let column_type = self.column_type_to_rust_type(&column.column_type);
let nullable = column.nullable;
let rust_type = if nullable {
format!("Option<{}>", column_type)
} else {
column_type
};
struct_body.push_str(&format!(" pub {}: {},\n", column_name, rust_type));
}
struct_body.push_str("}");
definitions.insert(table_name.to_string(), struct_body);
}
definitions
}
pub fn generate_misc_definitions(
&self,
indexes: &[Index],
roles: &[Role],
grants: &[Grant],
) -> HashMap<String, String> {
let mut definitions = HashMap::new();
for index in indexes {
let index_name = &index.name;
let table_name = "table_name"; let columns = &index.columns;
let index_type = if index.unique { "Unique" } else { "BTree" };
let mut macro_body = String::new();
macro_body.push_str(&format!("index!({} ON {} {{\n", index_name, table_name));
for column in columns {
macro_body.push_str(&format!(" {},\n", column));
}
macro_body.push_str(&format!("}} #[{:?}]);", index_type));
definitions.insert(format!("index_{}", index_name), macro_body);
}
for role in roles {
let role_name = &role.name;
let can_login = role.login;
let is_superuser = role.superuser;
let mut macro_body = String::new();
macro_body.push_str(&format!("role! {{\n"));
macro_body.push_str(&format!(" {} ", role_name));
if can_login {
macro_body.push_str("#[login] ");
}
if is_superuser {
macro_body.push_str("#[superuser] ");
}
macro_body.push_str("\n}");
definitions.insert(format!("role_{}", role_name), macro_body);
}
for grant in grants {
let grantee = &grant.grantee;
let privilege = grant.privilege_name();
let target = &grant.target;
let object_name = match target {
crate::schema::GrantTarget::Table { table, .. } => table,
crate::schema::GrantTarget::Schema(schema) => schema,
crate::schema::GrantTarget::Database(db) => db,
crate::schema::GrantTarget::Function { function, .. } => function,
crate::schema::GrantTarget::AllTablesInSchema(schema) => schema,
crate::schema::GrantTarget::AllFunctionsInSchema(schema) => schema,
crate::schema::GrantTarget::Role(role) => role,
};
let mut macro_body = String::new();
macro_body.push_str(&format!("grant! {{\n"));
macro_body.push_str(&format!(
" {} ON {} TO {}\n",
privilege, object_name, grantee
));
macro_body.push_str("}");
definitions.insert(
format!("grant_{}_{}_{}", grantee, privilege, object_name),
macro_body,
);
}
definitions
}
pub fn generate_module_structure(
&self,
tables: &[Table],
views: &[View],
composite_types: &[CompositeType],
indexes: &[Index],
roles: &[Role],
grants: &[Grant],
) -> HashMap<String, String> {
let mut modules = HashMap::new();
let schema_mod =
self.generate_schema_module(tables, views, composite_types, indexes, roles, grants);
modules.insert("schema/mod.rs".to_string(), schema_mod);
let models_mod = self.generate_models_module(tables);
modules.insert("models/mod.rs".to_string(), models_mod);
for table in tables {
let table_name = &table.name;
let table_mod = self.generate_table_module(table);
modules.insert(format!("schema/tables/{}.rs", table_name), table_mod);
}
for view in views {
let view_name = &view.name;
let view_mod = self.generate_view_module(view);
modules.insert(format!("schema/views/{}.rs", view_name), view_mod);
}
for composite_type in composite_types {
let type_name = &composite_type.name;
let type_mod = self.generate_composite_type_module(composite_type);
modules.insert(format!("schema/composite_types/{}.rs", type_name), type_mod);
}
modules
}
fn generate_schema_module(
&self,
tables: &[Table],
views: &[View],
composite_types: &[CompositeType],
_indexes: &[Index],
_roles: &[Role],
_grants: &[Grant],
) -> String {
let mut module = String::new();
module.push_str("// Auto-generated schema module\n");
module.push_str("// Generated by ignis-db init\n\n");
module.push_str("pub mod tables;\n");
for table in tables {
module.push_str(&format!("pub use tables::{};\n", table.name));
}
module.push_str("\n");
if !views.is_empty() {
module.push_str("pub mod views;\n");
for view in views {
module.push_str(&format!("pub use views::{};\n", view.name));
}
module.push_str("\n");
}
if !composite_types.is_empty() {
module.push_str("pub mod composite_types;\n");
for composite_type in composite_types {
module.push_str(&format!(
"pub use composite_types::{};\n",
composite_type.name
));
}
module.push_str("\n");
}
module
}
fn generate_models_module(&self, tables: &[Table]) -> String {
let mut module = String::new();
module.push_str("// Auto-generated models module\n");
module.push_str("// Generated by ignis-db init\n\n");
for table in tables {
let table_name = &table.name;
let struct_name = self.to_pascal_case(table_name);
module.push_str(&format!("pub mod {};\n", table_name));
module.push_str(&format!("pub use {}::{};\n", table_name, struct_name));
}
module
}
fn generate_table_module(&self, table: &Table) -> String {
let table_name = &table.name;
let primary_key = table.primary_key.as_ref();
let columns = &table.columns;
let mut module = String::new();
module.push_str(&format!(
"// Auto-generated table module for {}\n",
table_name
));
module.push_str("// Generated by ignis-db init\n\n");
module.push_str("use crate::schema::{Table, Column, ColumnType};\n\n");
let default_pk = "id".to_string();
let pk = primary_key.unwrap_or(&default_pk);
module.push_str(&format!("table!({} ({}) {{\n", table_name, pk));
for column in columns {
let column_name = &column.name;
let column_type = self.column_type_to_macro_type(&column.column_type);
module.push_str(&format!(" {} -> {},\n", column_name, column_type));
}
module.push_str("});\n\n");
module.push_str(&format!("pub fn table() -> Table {{\n"));
module.push_str(&format!(
" let mut table = Table::new(\"{}\");\n",
table_name
));
for column in columns {
let column_name = &column.name;
let column_type = self.column_type_to_macro_type(&column.column_type);
module.push_str(&format!(
" table = table.add_column(Column::new(\"{}\", {}));\n",
column_name, column_type
));
}
module.push_str(&format!(" table = table.set_primary_key(\"{}\");\n", pk));
module.push_str(" table\n");
module.push_str("}\n");
module
}
fn generate_view_module(&self, view: &View) -> String {
let view_name = &view.name;
let is_materialized = view.materialized;
let default_sql = String::new();
let sql = view.ddl.as_ref().unwrap_or(&default_sql);
let mut module = String::new();
module.push_str(&format!(
"// Auto-generated view module for {}\n",
view_name
));
module.push_str("// Generated by ignis-db init\n\n");
if is_materialized {
module.push_str(&format!("view!({} #[materialized] {{\n", view_name));
} else {
module.push_str(&format!("view!({} {{\n", view_name));
}
module.push_str(&format!(" {}\n", sql));
module.push_str("});\n");
module
}
fn generate_composite_type_module(&self, composite_type: &CompositeType) -> String {
let type_name = &composite_type.name;
let fields = &composite_type.fields;
let mut module = String::new();
module.push_str(&format!(
"// Auto-generated composite type module for {}\n",
type_name
));
module.push_str("// Generated by ignis-db init\n\n");
module.push_str(&format!(
"use crate::schema::{{CompositeType, CompositeField}};\n\n"
));
module.push_str(&format!("#[derive(Debug, Clone, PgComposite)]\n"));
module.push_str(&format!("#[pg_composite(name = \"{}\")]\n", type_name));
module.push_str(&format!(
"pub struct {} {{\n",
self.to_pascal_case(type_name)
));
for field in fields {
let field_name = &field.name;
let field_type = self.field_type_to_rust_type(&field.field_type);
let nullable = field.nullable;
let rust_type = if nullable {
format!("Option<{}>", field_type)
} else {
field_type
};
module.push_str(&format!(" pub {}: {},\n", field_name, rust_type));
}
module.push_str("}\n\n");
module.push_str(&format!("pub fn composite_type() -> CompositeType {{\n"));
module.push_str(&format!(
" let mut composite_type = CompositeType::new(\"{}\");\n",
type_name
));
for field in fields {
let field_name = &field.name;
let field_type = &field.field_type;
let nullable = field.nullable;
module.push_str(&format!(" composite_type = composite_type.add_field(\n"));
module.push_str(&format!(
" CompositeField::new(\"{}\", \"{}\")\n",
field_name, field_type
));
if !nullable {
module.push_str(&format!(" .with_nullable(false)\n"));
}
module.push_str(&format!(" );\n"));
}
module.push_str(" composite_type\n");
module.push_str("}\n");
module
}
fn column_type_to_macro_type(&self, column_type: &crate::schema::ColumnType) -> String {
match column_type {
crate::schema::ColumnType::Int4 => "Int4".to_string(),
crate::schema::ColumnType::Int8 => "Int8".to_string(),
crate::schema::ColumnType::Int2 => "Int2".to_string(),
crate::schema::ColumnType::Text => "Text".to_string(),
crate::schema::ColumnType::Varchar(Some(len)) => format!("Varchar({})", len),
crate::schema::ColumnType::Varchar(None) => "Varchar".to_string(),
crate::schema::ColumnType::Char => "Char".to_string(),
crate::schema::ColumnType::Bool => "Bool".to_string(),
crate::schema::ColumnType::Timestamptz => "Timestamptz".to_string(),
crate::schema::ColumnType::Date => "Date".to_string(),
crate::schema::ColumnType::Time => "Time".to_string(),
crate::schema::ColumnType::Uuid => "Uuid".to_string(),
crate::schema::ColumnType::Numeric(Some(p), Some(s)) => {
format!("Numeric({}, {})", p, s)
}
crate::schema::ColumnType::Numeric(Some(p), None) => format!("Numeric({})", p),
crate::schema::ColumnType::Numeric(None, Some(s)) => format!("Numeric(, {})", s),
crate::schema::ColumnType::Numeric(None, None) => "Numeric".to_string(),
crate::schema::ColumnType::Jsonb => "Jsonb".to_string(),
crate::schema::ColumnType::Json => "Json".to_string(),
crate::schema::ColumnType::Bytea => "Bytea".to_string(),
crate::schema::ColumnType::Array(inner) => {
let inner_type = self.column_type_to_macro_type(inner);
format!("Array({})", inner_type)
}
crate::schema::ColumnType::Custom(name) => format!("Custom({})", name),
crate::schema::ColumnType::Serial => "Serial".to_string(),
crate::schema::ColumnType::BigSerial => "BigSerial".to_string(),
crate::schema::ColumnType::SmallSerial => "SmallSerial".to_string(),
}
}
pub fn column_type_to_rust_type(&self, column_type: &crate::schema::ColumnType) -> String {
match column_type {
crate::schema::ColumnType::Int4 => "i32".to_string(),
crate::schema::ColumnType::Int8 => "i64".to_string(),
crate::schema::ColumnType::Int2 => "i16".to_string(),
crate::schema::ColumnType::Text => "String".to_string(),
crate::schema::ColumnType::Varchar(_) => "String".to_string(),
crate::schema::ColumnType::Char => "String".to_string(),
crate::schema::ColumnType::Bool => "bool".to_string(),
crate::schema::ColumnType::Timestamptz => "chrono::DateTime<chrono::Utc>".to_string(),
crate::schema::ColumnType::Date => "chrono::NaiveDate".to_string(),
crate::schema::ColumnType::Time => "chrono::NaiveTime".to_string(),
crate::schema::ColumnType::Uuid => "sqlx::types::Uuid".to_string(),
crate::schema::ColumnType::Numeric(_, _) => "rust_decimal::Decimal".to_string(),
crate::schema::ColumnType::Jsonb => "serde_json::Value".to_string(),
crate::schema::ColumnType::Json => "serde_json::Value".to_string(),
crate::schema::ColumnType::Bytea => "Vec<u8>".to_string(),
crate::schema::ColumnType::Array(inner) => {
let inner_type = self.column_type_to_rust_type(inner);
format!("Vec<{}>", inner_type)
}
crate::schema::ColumnType::Custom(name) => self.to_pascal_case(name),
crate::schema::ColumnType::Serial => "i32".to_string(),
crate::schema::ColumnType::BigSerial => "i64".to_string(),
crate::schema::ColumnType::SmallSerial => "i16".to_string(),
}
}
fn field_type_to_rust_type(&self, field_type: &str) -> String {
match field_type.to_lowercase().as_str() {
"integer" | "int" | "int4" => "i32".to_string(),
"bigint" | "int8" => "i64".to_string(),
"smallint" | "int2" => "i16".to_string(),
"text" => "String".to_string(),
"varchar" | "character varying" => "String".to_string(),
"char" | "character" => "String".to_string(),
"boolean" | "bool" => "bool".to_string(),
"timestamp with time zone" | "timestamptz" => {
"chrono::DateTime<chrono::Utc>".to_string()
}
"timestamp without time zone" | "timestamp" => "chrono::NaiveDateTime".to_string(),
"date" => "chrono::NaiveDate".to_string(),
"time" => "chrono::NaiveTime".to_string(),
"uuid" => "sqlx::types::Uuid".to_string(),
"numeric" | "decimal" => "rust_decimal::Decimal".to_string(),
"jsonb" => "serde_json::Value".to_string(),
"json" => "serde_json::Value".to_string(),
"bytea" => "Vec<u8>".to_string(),
"real" | "float4" => "f32".to_string(),
"double precision" | "float8" => "f64".to_string(),
array_type if array_type.ends_with("[]") => {
let base_type = &array_type[..array_type.len() - 2];
let base_rust_type = self.field_type_to_rust_type(base_type);
format!("Vec<{}>", base_rust_type)
}
custom => self.to_pascal_case(custom),
}
}
pub fn to_pascal_case(&self, s: &str) -> String {
s.split('_')
.map(|word| {
let mut chars = word.chars();
match chars.next() {
None => String::new(),
Some(first) => first.to_uppercase().chain(chars).collect(),
}
})
.collect()
}
pub fn to_snake_case(&self, s: &str) -> String {
let mut result = String::new();
for (i, ch) in s.chars().enumerate() {
if ch.is_uppercase() && i > 0 {
result.push('_');
}
result.push(ch.to_lowercase().next().unwrap_or(ch));
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::{Column, ColumnType};
#[test]
fn test_column_type_to_macro_type() {
let generator = CodeGenerator;
assert_eq!(
generator.column_type_to_macro_type(&ColumnType::Int4),
"Int4"
);
assert_eq!(
generator.column_type_to_macro_type(&ColumnType::Varchar(Some(255))),
"Varchar(255)"
);
assert_eq!(
generator.column_type_to_macro_type(&ColumnType::Text),
"Text"
);
}
#[test]
fn test_column_type_to_rust_type() {
let generator = CodeGenerator;
assert_eq!(generator.column_type_to_rust_type(&ColumnType::Int4), "i32");
assert_eq!(
generator.column_type_to_rust_type(&ColumnType::Text),
"String"
);
assert_eq!(
generator.column_type_to_rust_type(&ColumnType::Timestamptz),
"chrono::DateTime<chrono::Utc>"
);
}
#[test]
fn test_to_pascal_case() {
let generator = CodeGenerator;
assert_eq!(generator.to_pascal_case("user_profile"), "UserProfile");
assert_eq!(generator.to_pascal_case("order_items"), "OrderItems");
assert_eq!(generator.to_pascal_case("id"), "Id");
}
}