use crate::schema::Table;
use anyhow::{Context, Result};
use std::path::Path;
pub struct TableMacroParser {
source_dir: String,
}
impl TableMacroParser {
pub fn new(source_dir: impl Into<String>) -> Self {
Self {
source_dir: source_dir.into(),
}
}
pub fn parse_table_macros(&self) -> Result<Vec<ParsedTable>> {
let mut tables = Vec::new();
let source_path = Path::new(&self.source_dir);
if !source_path.exists() {
return Err(anyhow::anyhow!("Source directory does not exist: {}", self.source_dir));
}
self.walk_directory(source_path, &mut tables)?;
Ok(tables)
}
fn walk_directory(&self, dir: &Path, tables: &mut Vec<ParsedTable>) -> Result<()> {
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() && !self.should_skip_directory(&path) {
self.walk_directory(&path, tables)?;
} else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
if let Ok(file_tables) = self.parse_rust_file(&path) {
tables.extend(file_tables);
}
}
}
Ok(())
}
fn should_skip_directory(&self, path: &Path) -> bool {
let dir_name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
matches!(dir_name, "target" | "node_modules" | ".git" | ".cargo")
}
fn parse_rust_file(&self, file_path: &Path) -> Result<Vec<ParsedTable>> {
let content = std::fs::read_to_string(file_path)
.with_context(|| format!("Failed to read file: {}", file_path.display()))?;
self.parse_rust_content(&content, file_path)
}
fn parse_rust_content(&self, content: &str, file_path: &Path) -> Result<Vec<ParsedTable>> {
let mut tables = Vec::new();
let lines: Vec<&str> = content.lines().collect();
let mut i = 0;
while i < lines.len() {
let line = lines[i].trim();
if line.contains("table!") {
let start_line = i + 1;
let mut macro_content = String::new();
let mut brace_count = 0;
let mut in_macro = false;
for j in i..lines.len() {
let current_line = lines[j];
if current_line.contains("{") && !in_macro {
in_macro = true;
macro_content.push_str(current_line);
brace_count = current_line.matches('{').count() - current_line.matches('}').count();
} else if in_macro {
macro_content.push_str(" ");
macro_content.push_str(current_line);
brace_count += current_line.matches('{').count();
brace_count -= current_line.matches('}').count();
if brace_count == 0 {
if let Some(table) = self.parse_table_macro_content(¯o_content, start_line, file_path)? {
tables.push(table);
}
i = j;
break;
}
}
i = j;
}
}
i += 1;
}
Ok(tables)
}
fn parse_table_macro_content(&self, content: &str, line_num: usize, file_path: &Path) -> Result<Option<ParsedTable>> {
let start = content.find('{').ok_or_else(|| {
anyhow::anyhow!("Invalid table! macro syntax at line {}: missing opening brace", line_num)
})?;
let end = content.rfind('}').ok_or_else(|| {
anyhow::anyhow!("Invalid table! macro syntax at line {}: missing closing brace", line_num)
})?;
let inner_content = &content[start + 1..end];
let (table_name, primary_key, columns) = self.parse_table_definition(inner_content, line_num)?;
Ok(Some(ParsedTable {
name: table_name,
primary_key,
columns,
file_path: file_path.to_path_buf(),
line_number: line_num,
}))
}
fn parse_table_macro_line(&self, line: &str, line_num: usize, file_path: &Path) -> Result<Option<ParsedTable>> {
let trimmed = line.trim();
if !trimmed.starts_with("table!") {
return Ok(None);
}
let start = trimmed.find('(').ok_or_else(|| {
anyhow::anyhow!("Invalid table! macro syntax at line {}: missing opening parenthesis", line_num)
})?;
let macro_content = &trimmed[start + 1..];
let end = self.find_matching_paren(macro_content).ok_or_else(|| {
anyhow::anyhow!("Invalid table! macro syntax at line {}: missing closing parenthesis", line_num)
})?;
let inner_content = ¯o_content[..end];
let (table_name, primary_key, columns) = self.parse_table_definition(inner_content, line_num)?;
Ok(Some(ParsedTable {
name: table_name,
primary_key,
columns,
file_path: file_path.to_path_buf(),
line_number: line_num,
}))
}
fn find_matching_paren(&self, content: &str) -> Option<usize> {
let mut depth = 0;
for (i, ch) in content.char_indices() {
match ch {
'(' => depth += 1,
')' => {
if depth == 0 {
return Some(i);
}
depth -= 1;
}
_ => {}
}
}
None
}
fn parse_table_definition(&self, content: &str, line_num: usize) -> Result<(String, String, Vec<ColumnDef>)> {
let parts: Vec<&str> = content.split_whitespace().collect();
if parts.len() < 3 {
return Err(anyhow::anyhow!(
"Invalid table! macro syntax at line {}: expected 'table_name (pk) {{ columns }}'",
line_num
));
}
let table_name = parts[0].to_string();
let pk_start = content.find('(').ok_or_else(|| {
anyhow::anyhow!("Invalid table! macro syntax at line {}: missing primary key", line_num)
})?;
let pk_end = content[pk_start..].find(')').ok_or_else(|| {
anyhow::anyhow!("Invalid table! macro syntax at line {}: missing closing parenthesis for primary key", line_num)
})?;
let primary_key = content[pk_start + 1..pk_start + pk_end].trim().to_string();
let brace_start = content.find('{').ok_or_else(|| {
anyhow::anyhow!("Invalid table! macro syntax at line {}: missing opening brace for columns", line_num)
})?;
let brace_end = content[brace_start..].rfind('}').ok_or_else(|| {
anyhow::anyhow!("Invalid table! macro syntax at line {}: missing closing brace for columns", line_num)
})?;
let columns_content = &content[brace_start + 1..brace_start + brace_end];
let columns = self.parse_columns(columns_content, line_num)?;
Ok((table_name, primary_key, columns))
}
fn parse_columns(&self, content: &str, line_num: usize) -> Result<Vec<ColumnDef>> {
let mut columns = Vec::new();
let mut current = String::new();
let mut depth = 0;
for ch in content.chars() {
match ch {
',' if depth == 0 => {
if !current.trim().is_empty() {
if let Some(column) = self.parse_single_column(current.trim(), line_num)? {
columns.push(column);
}
}
current.clear();
}
'{' | '(' => {
depth += 1;
current.push(ch);
}
'}' | ')' => {
depth -= 1;
current.push(ch);
}
_ => {
current.push(ch);
}
}
}
if !current.trim().is_empty() {
if let Some(column) = self.parse_single_column(current.trim(), line_num)? {
columns.push(column);
}
}
Ok(columns)
}
fn parse_single_column(&self, content: &str, line_num: usize) -> Result<Option<ColumnDef>> {
let content = content.trim();
if content.is_empty() {
return Ok(None);
}
if let Some(arrow_pos) = content.find("->") {
let name = content[..arrow_pos].trim().to_string();
let type_def = content[arrow_pos + 2..].trim().to_string();
Ok(Some(ColumnDef {
name,
type_definition: type_def,
}))
} else {
Err(anyhow::anyhow!(
"Invalid column definition at line {}: expected 'name -> type', got '{}'",
line_num, content
))
}
}
}
#[derive(Debug, Clone)]
pub struct ParsedTable {
pub name: String,
pub primary_key: String,
pub columns: Vec<ColumnDef>,
pub file_path: std::path::PathBuf,
pub line_number: usize,
}
#[derive(Debug, Clone)]
pub struct ColumnDef {
pub name: String,
pub type_definition: String,
}
impl ParsedTable {
pub fn to_table(&self) -> Result<Table> {
use crate::builders::TableBuilder;
use crate::builders::SchemaBuilder;
let mut builder = TableBuilder::new(&self.name);
builder = builder.add_column(&self.primary_key, "SERIAL PRIMARY KEY");
for column in &self.columns {
if column.name != self.primary_key {
let sql_type = self.convert_type_to_sql(&column.type_definition);
builder = builder.add_column(&column.name, &sql_type);
}
}
builder.build().map_err(|e| anyhow::anyhow!("Failed to build table from parsed definition: {}", e))
}
fn convert_type_to_sql(&self, rust_type: &str) -> String {
match rust_type {
"String" => "TEXT".to_string(),
"i32" => "INTEGER".to_string(),
"i64" => "BIGINT".to_string(),
"bool" => "BOOLEAN".to_string(),
"chrono::DateTime<chrono::Utc>" => "TIMESTAMPTZ".to_string(),
"uuid::Uuid" => "UUID".to_string(),
"serde_json::Value" => "JSONB".to_string(),
"Option<String>" => "TEXT".to_string(),
"Option<i32>" => "INTEGER".to_string(),
"Option<bool>" => "BOOLEAN".to_string(),
_ => {
if rust_type.starts_with("Option<") && rust_type.ends_with('>') {
let inner_type = &rust_type[7..rust_type.len()-1];
self.convert_type_to_sql(inner_type)
} else {
"TEXT".to_string()
}
}
}
}
}