Skip to content

Commit

Permalink
Merge pull request #48 from longsleep-io/longsleep-optional-functions
Browse files Browse the repository at this point in the history
Add --no-crud option to skip generating CRUD functions
  • Loading branch information
Wulf authored Sep 3, 2023
2 parents a2fd847 + 55fc2e7 commit b783ab8
Show file tree
Hide file tree
Showing 9 changed files with 110 additions and 12 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ cargo install dsync
* `--model-path`: (optional) set a custom model import path, default `crate::models::`
* `--schema-path`: (optional) set a custom schema import path, default `crate::schema::`
* `--no-serde`: (optional) if set, does not output any serde related code
* `--no-crud`: (optional) Do not generate the CRUD functions for generated models
* note: the CLI has fail-safes to prevent accidental file overwriting
```sh
Expand Down
11 changes: 10 additions & 1 deletion src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ struct Args {
help = "Optional; Disable generating serde implementations"
)]
no_serde: bool,
#[structopt(
long = "no-crud",
help = "Optional; Do not generate the CRUD functions for generated models"
)]
no_crud: bool,
}

fn main() {
Expand All @@ -89,7 +94,7 @@ fn main() {
);
} else {
eprintln!("{}", backtrace);
}
}
}
#[cfg(not(feature = "backtrace"))]
{
Expand Down Expand Up @@ -120,6 +125,10 @@ fn actual_main() -> dsync::Result<()> {
default_table_options = default_table_options.disable_serde();
}

if args.no_crud {
default_table_options = default_table_options.disable_fns();
}

dsync::generate_files(
args.input,
args.output,
Expand Down
37 changes: 29 additions & 8 deletions src/code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -488,25 +488,42 @@ fn build_imports(table: &ParsedTableMacro, config: &GenerationConfig) -> String
""
};

let fns_imports = if table_options.get_fns() {
"\nuse diesel::QueryResult;"
} else {
""
};

let connection_type_alias = if table_options.get_fns() {
format!(
"\ntype Connection = {connection_type};",
connection_type = config.connection_type,
)
} else {
"".to_string()
};

format!(
indoc! {"
use crate::diesel::*;
use {schema_path};
use diesel::QueryResult;
use {schema_path};{fns_imports}
{serde_imports}{async_imports}
{belongs_imports}
type Connection = {connection_type};
{connection_type_alias}
"},
connection_type = config.connection_type,
belongs_imports = belongs_imports,
async_imports = async_imports,
schema_path = schema_path,
serde_imports = serde_imports
serde_imports = serde_imports,
fns_imports = fns_imports,
connection_type_alias = connection_type_alias,
)
.trim_end()
.to_string()
}

pub fn generate_for_table(table: ParsedTableMacro, config: &GenerationConfig) -> String {
let table_options = config.table(&table.name.to_string());
// first, we generate struct code
let read_struct = Struct::new(StructType::Read, &table, config);
let update_struct = Struct::new(StructType::Update, &table, config);
Expand All @@ -519,8 +536,12 @@ pub fn generate_for_table(table: ParsedTableMacro, config: &GenerationConfig) ->
structs.push('\n');
structs.push_str(update_struct.code());

let functions = build_table_fns(&table, config, create_struct, update_struct);
let functions = if table_options.get_fns() {
build_table_fns(&table, config, create_struct, update_struct)
} else {
"".to_string()
};
let imports = build_imports(&table, config);

format!("{FILE_SIGNATURE}\n\n{imports}\n{structs}\n{functions}")
format!("{FILE_SIGNATURE}\n\n{imports}\n\n{structs}\n{functions}")
}
18 changes: 15 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mod code;
pub mod error;
mod file;
mod parser;
pub mod error;

use error::IOErrorToError;
pub use error::{Error, Result};
Expand All @@ -27,6 +27,9 @@ pub struct TableOptions<'a> {

/// Generates serde::Serialize and serde::Deserialize derive implementations
use_serde: bool,

/// Generates the CRUD functions for generated models
fns: bool,
}

impl<'a> TableOptions<'a> {
Expand All @@ -48,6 +51,10 @@ impl<'a> TableOptions<'a> {
self.use_serde
}

pub fn get_fns(&self) -> bool {
self.fns
}

pub fn get_autogenerated_columns(&self) -> &[&'_ str] {
self.autogenerated_columns.as_deref().unwrap_or_default()
}
Expand Down Expand Up @@ -82,6 +89,10 @@ impl<'a> TableOptions<'a> {
}
}

pub fn disable_fns(self) -> Self {
Self { fns: false, ..self }
}

pub fn autogenerated_columns(self, cols: Vec<&'a str>) -> Self {
Self {
autogenerated_columns: Some(cols.clone()),
Expand All @@ -103,6 +114,7 @@ impl<'a> TableOptions<'a> {
.or_else(|| other.autogenerated_columns.clone()),

use_serde: self.use_serde || other.use_serde,
fns: self.fns || other.fns,
}
}
}
Expand All @@ -117,6 +129,7 @@ impl<'a> Default for TableOptions<'a> {
#[cfg(feature = "async")]
use_async: Default::default(),
use_serde: true,
fns: true,
}
}
}
Expand Down Expand Up @@ -200,8 +213,7 @@ pub fn generate_files(
}

// pass 2: delete code for removed tables
for item in std::fs::read_dir(&output_dir).attach_path_err(&output_dir)?
{
for item in std::fs::read_dir(&output_dir).attach_path_err(&output_dir)? {
let item = item.attach_path_err(&output_dir)?;

// check if item is a directory
Expand Down
1 change: 1 addition & 0 deletions test/simple_table_no_crud/models/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod todos;
35 changes: 35 additions & 0 deletions test/simple_table_no_crud/models/todos/generated.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/* This file is generated and managed by dsync */

use crate::diesel::*;
use crate::schema::*;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, Clone, Queryable, Insertable, AsChangeset, Selectable)]
#[diesel(table_name=todos, primary_key(id))]
pub struct Todo {
pub id: i32,
pub unsigned: u32,
pub text: String,
pub completed: bool,
pub created_at: chrono::DateTime<chrono::Utc>,
pub updated_at: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Serialize, Deserialize, Clone, Queryable, Insertable, AsChangeset)]
#[diesel(table_name=todos)]
pub struct CreateTodo {
pub unsigned: u32,
pub text: String,
pub completed: bool,
}

#[derive(Debug, Serialize, Deserialize, Clone, Queryable, Insertable, AsChangeset)]
#[diesel(table_name=todos)]
pub struct UpdateTodo {
pub unsigned: Option<u32>,
pub text: Option<String>,
pub completed: Option<bool>,
pub created_at: Option<chrono::DateTime<chrono::Utc>>,
pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
}

2 changes: 2 additions & 0 deletions test/simple_table_no_crud/models/todos/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub use generated::*;
pub mod generated;
10 changes: 10 additions & 0 deletions test/simple_table_no_crud/schema.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
diesel::table! {
todos (id) {
id -> Int4,
unsigned -> Unsigned<Integer>,
text -> Text,
completed -> Bool,
created_at -> Timestamptz,
updated_at -> Timestamptz,
}
}
7 changes: 7 additions & 0 deletions test/simple_table_no_crud/test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/bin/bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

cd $SCRIPT_DIR

cargo run -- -i schema.rs -o models -g id -g created_at -g updated_at -c "diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>" --no-crud

0 comments on commit b783ab8

Please sign in to comment.