Skip to content
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
90 changes: 39 additions & 51 deletions src/code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,9 @@ impl<'a> Struct<'a> {
derives_vec.push(derives::PARTIALEQ);
}

derives_vec.push(derives::DEFAULT);
if !self.config.options.default_impl {
derives_vec.push(derives::DEFAULT);
}
}
StructType::Create => derives_vec.extend_from_slice(&[derives::INSERTABLE]),
}
Expand Down Expand Up @@ -297,7 +299,7 @@ impl<'a> Struct<'a> {
.collect::<Vec<String>>()
.join(" ");

let fields = self.fields();
let mut fields = self.fields();

if fields.is_empty() {
self.has_fields = Some(false);
Expand Down Expand Up @@ -330,18 +332,18 @@ impl<'a> Struct<'a> {
};

let mut lines = Vec::with_capacity(fields.len());
for mut f in fields.into_iter() {
for f in fields.iter_mut() {
let field_name = &f.name;

if f.base_type == "String" {
f.base_type = match self.ty {
StructType::Read => f.base_type,
StructType::Read => f.base_type.clone(),
StructType::Update => self.opts.get_update_str_type().as_str().to_string(),
StructType::Create => self.opts.get_create_str_type().as_str().to_string(),
}
} else if f.base_type == "Vec<u8>" {
f.base_type = match self.ty {
StructType::Read => f.base_type,
StructType::Read => f.base_type.clone(),
StructType::Update => self.opts.get_update_bytes_type().as_str().to_string(),
StructType::Create => self.opts.get_create_bytes_type().as_str().to_string(),
}
Expand Down Expand Up @@ -380,7 +382,7 @@ impl<'a> Struct<'a> {
),
};

let struct_code = formatdoc!(
let mut struct_code = formatdoc!(
r#"
{doccomment}
{tsync_attr}{derive_attr}
Expand All @@ -407,6 +409,15 @@ impl<'a> Struct<'a> {
lines = lines.join("\n"),
);

if self.config.options.default_impl {
struct_code.push('\n');
struct_code.push_str(&build_default_impl_fn(
self.ty,
&ty.format(&table.struct_name),
&fields,
));
}

self.has_fields = Some(true);
self.rendered_code = Some(struct_code);
}
Expand Down Expand Up @@ -784,42 +795,43 @@ fn default_for_type(typ: &str) -> &'static str {

/// Generate default (insides of the `impl Default for StructName { fn default() -> Self {} }`)
fn build_default_impl_fn<'a>(
struct_type: StructType,
struct_name: &str,
columns: impl Iterator<Item = &'a ParsedColumnMacro>,
fields: &[StructField],
) -> 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)| {
let fields: Vec<String> = fields
.iter()
.map(|name_typ_nullable| {
format!(
" {name}: {typ_default}",
name = name,
typ_default = if nullable {
"{name}: {typ_default},",
name = name_typ_nullable.name,
typ_default = if name_typ_nullable.is_optional || struct_type == StructType::Update
{
"None"
} else {
default_for_type(typ)
default_for_type(&name_typ_nullable.base_type)
}
)
})
.collect::<Vec<String>>()
.join(",\n");
format!(
r#"impl Default for {struct_name} {{
fn default() -> Self {{
Self {{
{fields_to_defaults}
}}
}}
}}"#
.collect();
formatdoc!(
r#"
impl Default for {struct_name} {{
fn default() -> Self {{
Self {{
{fields}
}}
}}
}}
"#,
fields = fields.join("\n ")
)
}

/// 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 @@ -832,24 +844,9 @@ 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 @@ -865,14 +862,5 @@ pub fn generate_for_table(table: &ParsedTableMacro, config: &GenerationConfig) -
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
}
18 changes: 18 additions & 0 deletions test/default_impl/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[lib]
path = "lib.rs"

[package]
name = "default_impl"
version = "0.1.0"
edition = "2021"

[dependencies]
diesel = { version = "*", default-features = false, features = [
"sqlite",
"r2d2",
"chrono",
"returning_clauses_for_sqlite_3_35",
] }
r2d2.workspace = true
chrono.workspace = true
serde.workspace = true
6 changes: 6 additions & 0 deletions test/default_impl/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
pub mod models;
pub mod schema;

pub mod diesel {
pub use diesel::*;
}
1 change: 1 addition & 0 deletions test/default_impl/models/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod todos;
151 changes: 151 additions & 0 deletions test/default_impl/models/todos/generated.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
/* @generated and managed by dsync */

#[allow(unused)]
use crate::diesel::*;
use crate::schema::*;

pub type ConnectionType = diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::sqlite::SqliteConnection>>;

/// Struct representing a row in table `todos`
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::Queryable, diesel::Selectable, diesel::QueryableByName, PartialEq, diesel::Identifiable)]
#[diesel(table_name=todos, primary_key(id))]
pub struct Todos {
/// Field representing column `id`
pub id: i32,
/// Field representing column `text`
pub text: String,
/// Field representing column `completed`
pub completed: bool,
/// Field representing column `type`
pub type_: String,
/// Field representing column `smallint`
pub smallint: i16,
/// Field representing column `bigint`
pub bigint: i64,
/// Field representing column `created_at`
pub created_at: chrono::NaiveDateTime,
/// Field representing column `updated_at`
pub updated_at: chrono::NaiveDateTime,
}

impl Default for Todos {
fn default() -> Self {
Self {
id: 0,
text: String::new(),
completed: false,
type_: String::new(),
smallint: 0,
bigint: 0,
created_at: Default::default(),
updated_at: Default::default(),
}
}
}

/// Create Struct for a row in table `todos` for [`Todos`]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::Insertable)]
#[diesel(table_name=todos)]
pub struct CreateTodos {
/// Field representing column `text`
pub text: String,
/// Field representing column `completed`
pub completed: bool,
/// Field representing column `type`
pub type_: String,
/// Field representing column `smallint`
pub smallint: i16,
/// Field representing column `bigint`
pub bigint: i64,
}

impl Default for CreateTodos {
fn default() -> Self {
Self {
text: String::new(),
completed: false,
type_: String::new(),
smallint: 0,
bigint: 0,
}
}
}

/// Update Struct for a row in table `todos` for [`Todos`]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsChangeset, PartialEq)]
#[diesel(table_name=todos)]
pub struct UpdateTodos {
/// Field representing column `text`
pub text: Option<String>,
/// Field representing column `completed`
pub completed: Option<bool>,
/// Field representing column `type`
pub type_: Option<String>,
/// Field representing column `smallint`
pub smallint: Option<i16>,
/// Field representing column `bigint`
pub bigint: Option<i64>,
/// Field representing column `created_at`
pub created_at: Option<chrono::NaiveDateTime>,
/// Field representing column `updated_at`
pub updated_at: Option<chrono::NaiveDateTime>,
}

impl Default for UpdateTodos {
fn default() -> Self {
Self {
text: String::new(),
completed: false,
type_: String::new(),
smallint: 0,
bigint: 0,
created_at: Default::default(),
updated_at: Default::default(),
}
}
}
Comment on lines +94 to +106
Copy link
Collaborator

Choose a reason for hiding this comment

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

The tests need to be updated.


/// Result of a `.paginate` function
#[derive(Debug, serde::Serialize)]
pub struct PaginationResult<T> {
/// Resulting items that are from the current page
pub items: Vec<T>,
/// The count of total items there are
pub total_items: i64,
/// Current page, 0-based index
pub page: i64,
/// Size of a page
pub page_size: i64,
/// Number of total possible pages, given the `page_size` and `total_items`
pub num_pages: i64,
}

impl Todos {
/// Insert a new row into `todos` with a given [`CreateTodos`]
pub fn create(db: &mut ConnectionType, item: &CreateTodos) -> diesel::QueryResult<Self> {
use crate::schema::todos::dsl::*;

diesel::insert_into(todos).values(item).get_result::<Self>(db)
}

/// Get a row from `todos`, identified by the primary key
pub fn read(db: &mut ConnectionType, param_id: i32) -> diesel::QueryResult<Self> {
use crate::schema::todos::dsl::*;

todos.filter(id.eq(param_id)).first::<Self>(db)
}

/// Update a row in `todos`, identified by the primary key with [`UpdateTodos`]
pub fn update(db: &mut ConnectionType, param_id: i32, item: &UpdateTodos) -> diesel::QueryResult<Self> {
use crate::schema::todos::dsl::*;

diesel::update(todos.filter(id.eq(param_id))).set(item).get_result(db)
}

/// Delete a row in `todos`, identified by the primary key
pub fn delete(db: &mut ConnectionType, param_id: i32) -> diesel::QueryResult<usize> {
use crate::schema::todos::dsl::*;

diesel::delete(todos.filter(id.eq(param_id))).execute(db)
}
}
2 changes: 2 additions & 0 deletions test/default_impl/models/todos/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub use generated::*;
pub mod generated;
16 changes: 16 additions & 0 deletions test/default_impl/schema.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
diesel::table! {
todos (id) {
id -> Int4,
// unsigned -> Unsigned<Integer>,
// unsigned_nullable -> Nullable<Unsigned<Integer>>,
text -> Text,
completed -> Bool,
#[sql_name = "type"]
#[max_length = 255]
type_ -> Varchar,
smallint -> Int2,
bigint -> Int8,
created_at -> Timestamp,
updated_at -> Timestamp,
}
}
8 changes: 8 additions & 0 deletions test/default_impl/test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/bin/bash

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

cd $SCRIPT_DIR

cargo run --manifest-path ../../Cargo.toml -- \
-i schema.rs -o models -g id -g created_at -g updated_at --default-impl -c "diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::sqlite::SqliteConnection>>"
Loading