Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement generator for impl Default #142

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,10 @@ pub struct MainOptions {
/// See `crate::GenerationConfig::diesel_backend` for more details.
#[arg(short = 'b', long = "diesel-backend")]
pub diesel_backend: String,

/// Generate the "default" function in an `impl Default`
#[arg(long)]
pub default_impl: bool,
}

#[derive(Debug, ValueEnum, Clone, PartialEq, Default)]
Expand Down Expand Up @@ -265,6 +269,7 @@ fn actual_main() -> dsync::Result<()> {
once_connection_type: args.once_connection_type,
readonly_prefixes: args.readonly_prefixes,
readonly_suffixes: args.readonly_suffixes,
default_impl: args.default_impl,
},
},
)?;
Expand Down
80 changes: 77 additions & 3 deletions src/code.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use heck::ToPascalCase;
use indoc::formatdoc;
use std::borrow::Cow;

use crate::parser::{ParsedColumnMacro, ParsedTableMacro, FILE_SIGNATURE};
use crate::{get_table_module_name, GenerationConfig, TableOptions};
Expand Down Expand Up @@ -86,7 +85,7 @@ pub struct StructField {

impl StructField {
/// Assemble the current options into a rust type, like `base_type: String, is_optional: true` to `Option<String>`
pub fn to_rust_type(&self) -> Cow<str> {
pub fn to_rust_type(&self) -> std::borrow::Cow<str> {
let mut rust_type = self.base_type.clone();

// order matters!
Expand Down Expand Up @@ -209,6 +208,7 @@ impl<'a> Struct<'a> {
derives::SELECTABLE,
#[cfg(feature = "derive-queryablebyname")]
derives::QUERYABLEBYNAME,
derives::PARTIALEQ,
]);

if !self.table.foreign_keys.is_empty() {
Expand Down Expand Up @@ -761,10 +761,60 @@ fn build_imports(table: &ParsedTableMacro, config: &GenerationConfig) -> String
imports_vec.join("\n")
}

/// Get default for type
fn default_for_type(typ: &str) -> &'static str {
match typ {
"i8" | "u8" | "i16" | "u16" | "i32" | "u32" | "i64" | "u64" | "i128" | "u128" | "isize"
| "usize" => "0",
"f32" | "f64" => "0.0",
// https://doc.rust-lang.org/std/primitive.bool.html#method.default
"bool" => "false",
"String" => "String::new()",
"&str" | "&'static str" => "\"\"",
"Cow<str>" => "Cow::Owned(String::new())",
_ => {
if typ.starts_with("Option<") {
"None"
} else {
"Default::default()"
}
}
}
}

/// Generate default (insides of the `impl Default for StructName { fn default() -> Self {} }`)
fn build_default_impl_fn<'a>(
struct_name: &str,
columns: impl Iterator<Item = &'a ParsedColumnMacro>,
) -> String {
let column_name_type_nullable =
columns.map(|col| (col.name.to_string(), col.ty.as_str(), col.is_nullable));
let fields_to_defaults = column_name_type_nullable
.map(|(name, typ, nullable)| {
format!(
" {name}: {typ_default}",
name = name,
typ_default = if nullable {
"None"
} else {
default_for_type(typ)
}
)
})
.collect::<Vec<String>>()
.join(",\n");
format!(
"impl Default for {struct_name} {{\n fn default() -> Self {{\n Self {{\n{f2d}\n }}\n }}\n}}",
struct_name = struct_name, f2d=fields_to_defaults.as_str()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
struct_name = struct_name, f2d=fields_to_defaults.as_str()
f2d=fields_to_defaults.as_str()

unless i missed something, that shouldnt be required anymore.

i think f2d should also be able to be directly embedded.

)
}

/// Generate a full file for a given diesel table
pub fn generate_for_table(table: &ParsedTableMacro, config: &GenerationConfig) -> String {
// early to ensure the table options are set for the current table
let struct_name = table.struct_name.to_string();
let table_options = config.table(&table.name.to_string());
let generated_columns = table_options.get_autogenerated_columns();

let mut ret_buffer = format!("{FILE_SIGNATURE}\n\n");

Expand All @@ -777,9 +827,24 @@ pub fn generate_for_table(table: &ParsedTableMacro, config: &GenerationConfig) -

let create_struct = Struct::new(StructType::Create, table, config);

let not_generated = |col: &&ParsedColumnMacro| -> bool {
!generated_columns.contains(&col.column_name.as_str())
};

if create_struct.has_code() {
ret_buffer.push('\n');
ret_buffer.push_str(create_struct.code());
if config.options.default_impl {
ret_buffer.push('\n');
ret_buffer.push_str(
build_default_impl_fn(
&StructType::format(&StructType::Create, &struct_name),
create_struct.table.columns.iter().filter(not_generated),
)
.as_str(),
);
}
ret_buffer.push('\n');
}

let update_struct = Struct::new(StructType::Update, table, config);
Expand All @@ -789,11 +854,20 @@ pub fn generate_for_table(table: &ParsedTableMacro, config: &GenerationConfig) -
ret_buffer.push_str(update_struct.code());
}

// third and lastly, push functions - if enabled
// third, push functions - if enabled
if table_options.get_fns() {
ret_buffer.push('\n');
ret_buffer.push_str(build_table_fns(table, config, create_struct, update_struct).as_str());
}

if config.options.default_impl {
ret_buffer.push('\n');
ret_buffer.push_str(
build_default_impl_fn(&struct_name, table.columns.iter().filter(not_generated))
.as_str(),
);
ret_buffer.push('\n');
}

ret_buffer
}
3 changes: 3 additions & 0 deletions src/global.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,8 @@ pub struct GenerationConfigOpts<'a> {
pub readonly_prefixes: Vec<String>,
/// Suffixes to treat tables as readonly
pub readonly_suffixes: Vec<String>,
/// Generate the "default" function in an `impl Default`
pub default_impl: bool,
}

impl GenerationConfigOpts<'_> {
Expand Down Expand Up @@ -363,6 +365,7 @@ impl Default for GenerationConfigOpts<'_> {
once_connection_type: false,
readonly_prefixes: Vec::default(),
readonly_suffixes: Vec::default(),
default_impl: false,
}
}
}
Expand Down
Loading