feat: add models path arg

This commit is contained in:
Matthieu Bessat 2025-06-02 11:39:05 +02:00
parent e4f6c0f12d
commit 21c1f2e069
2 changed files with 13 additions and 5 deletions

View file

@ -26,7 +26,6 @@ fn gen_get_all_method(model: &Model) -> TokenStream {
fn gen_get_by_id_method(model: &Model) -> TokenStream {
let resource_ident = format_ident!("{}", &model.name);
let error_msg = format!("Failed to fetch resource {:?}", model.name.clone());
let primary_key = &model.fields.iter()
.find(|f| f.is_primary)
.expect("A model must have at least one primary key")
@ -36,12 +35,11 @@ fn gen_get_by_id_method(model: &Model) -> TokenStream {
let func_name_ident = format_ident!("get_by_{}", primary_key);
quote! {
pub async fn #func_name_ident(&self, item_id: &str) -> Result<#resource_ident> {
pub async fn #func_name_ident(&self, item_id: &str) -> Result<#resource_ident, sqlx::Error> {
sqlx::query_as::<_, #resource_ident>(#select_query)
.bind(item_id)
.fetch_one(&self.db.0)
.await
.context(#error_msg)
}
}
}
@ -186,7 +184,7 @@ fn generate_repository_file(model: &Model) -> Result<SourceNodeContainer> {
let base_repository_code: TokenStream = quote! {
use crate::models::#resource_module_ident::#resource_ident;
use crate::services::database::Database;
use crate::db::Database;
use anyhow::{Result, Context};
pub struct #repository_ident {

View file

@ -38,6 +38,9 @@ struct GenerateMigration {
/// Generate Rust SQLx repositories code
#[argh(subcommand, name = "gen-repositories")]
struct GenerateRepositories {
/// path of the directory that contains repositories
#[argh(option, short = 'o')]
output: Option<String>
}
#[derive(FromArgs, PartialEq, Debug)]
@ -57,6 +60,10 @@ struct GeneratorArgs {
/// path where to find Cargo.toml
#[argh(option)]
project_root: Option<String>,
/// path of the directory containing models
#[argh(option, short = 'm')]
models_path: Option<String>,
#[argh(subcommand)]
nested: GeneratorArgsSubCommands
@ -97,6 +104,9 @@ pub fn main() -> Result<()> {
// search for a models modules
let models_mod_location = "src/models.rs";
let mut models_mod_path = project_root_path.join(models_mod_location);
if let Some(models_path) = args.models_path {
models_mod_path = project_root_path.join(models_path);
}
if !models_mod_path.exists() {
let models_mod_location = "src/models/mod.rs";
models_mod_path = project_root_path.join(models_mod_location);
@ -115,7 +125,7 @@ pub fn main() -> Result<()> {
GeneratorArgsSubCommands::GenerateRepositories(opts) => {
eprintln!("Generating repositories…");
// search for a repository module
let repositories_mod_location = "src/repositories";
let repositories_mod_location = opts.output.unwrap_or("src/repositories".to_string());
let repositories_mod_path = project_root_path.join(repositories_mod_location);
if !repositories_mod_path.exists() {
return Err(anyhow!("Could not resolve repositories modules."));