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

Fix some things that were broken #112

Merged
merged 5 commits into from
Nov 19, 2023
Merged
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ cargo install dsync

* `-i`: input argument: path to schema file
* `-o`: output argument: path to directory where generated code should be written
* `-c`: connection type (for example: `diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>`)
* `-c`: connection type (for example: `diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>`)
* `-g`: (optional, repeatable) list of columns that are automatically generated by create/update triggers (for example, `created_at`, `updated_at`)
* `--tsync`: (optional) adds `#[tsync]` attribute to generated structs (see <https://github.com/Wulf/tsync>)
* `--model-path`: (optional) set a custom model import path, default `crate::models::`
Expand Down
11 changes: 9 additions & 2 deletions src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,15 @@ pub struct MainOptions {
#[arg(short = 'g', long = "autogenerated-columns")]
pub autogenerated_columns: Option<Vec<String>>,

/// rust type which describes a connection, for example: "diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>"
#[arg(short = 'c', long = "connection-type")]
/// rust type which describes a connection
///
/// For example:
/// - `diesel::pg::PgConnection`
/// - `diesel::sqlite::SqliteConnection`
/// - `diesel::mysql::MysqlConnection`
/// - `diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>`
/// - or, your custom diesel connection type (struct which implements `diesel::connection::Connection`)
#[arg(short = 'c', long = "connection-type", verbatim_doc_comment)]
pub connection_type: String,

/// Disable generating serde implementations
Expand Down
16 changes: 6 additions & 10 deletions src/code.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use heck::{ToPascalCase, ToSnakeCase};
use heck::ToPascalCase;
use indoc::formatdoc;
use std::borrow::Cow;

use crate::parser::{ParsedColumnMacro, ParsedTableMacro, FILE_SIGNATURE};
use crate::{GenerationConfig, TableOptions};
use crate::{get_table_module_name, GenerationConfig, TableOptions};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StructType {
Expand Down Expand Up @@ -119,8 +119,8 @@ pub mod derives {
pub const CLONE: &str = "Clone";
pub const QUERYABLE: &str = "Queryable";
pub const INSERTABLE: &str = "Insertable";
pub const SERIALIZE: &str = "Serialize";
pub const DESERIALIZE: &str = "Deserialize";
pub const SERIALIZE: &str = "serde::Serialize";
pub const DESERIALIZE: &str = "serde::Deserialize";
pub const ASCHANGESET: &str = "AsChangeset";
pub const SELECTABLE: &str = "Selectable";
pub const IDENTIFIABLE: &str = "Identifiable";
Expand Down Expand Up @@ -599,7 +599,7 @@ pub fn generate_common_structs(table_options: &TableOptions<'_>) -> String {
/// Generate connection-type type
pub fn generate_connection_type(config: &GenerationConfig) -> String {
format!(
"type ConnectionType = {connection_type};",
"pub type ConnectionType = {connection_type};",
connection_type = config.connection_type,
)
}
Expand All @@ -615,7 +615,7 @@ fn build_imports(table: &ParsedTableMacro, config: &GenerationConfig) -> String
imports_vec.extend(table.foreign_keys.iter().map(|fk| {
format!(
"use {model_path}{foreign_table_name_model}::{singular_struct_name};",
foreign_table_name_model = fk.0.to_string().to_snake_case().to_lowercase(),
foreign_table_name_model = get_table_module_name(&fk.0.to_string()),
singular_struct_name = fk.0.to_string().to_pascal_case(),
model_path = config.model_path
)
Expand All @@ -628,10 +628,6 @@ fn build_imports(table: &ParsedTableMacro, config: &GenerationConfig) -> String
// no "::" because that is already included in the schema_path
imports_vec.push(format!("use {}*;", config.schema_path));

if table_options.get_serde() {
imports_vec.push("use serde::{Deserialize, Serialize};".into());
};

if table_options.get_fns() {
imports_vec.push("use diesel::QueryResult;".into());
};
Expand Down
26 changes: 20 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ mod parser;
use error::IOErrorToError;
pub use error::{Error, Result};
use file::MarkedFile;
use heck::ToSnakeCase;
use parser::ParsedTableMacro;
pub use parser::FILE_SIGNATURE;
use std::collections::HashMap;
Expand Down Expand Up @@ -247,7 +248,12 @@ pub struct GenerationConfig<'a> {
pub default_table_options: TableOptions<'a>,
/// Connection type to insert
///
/// Example: `diesel::SqliteConnection`
/// For example:
/// - `diesel::pg::PgConnection`
/// - `diesel::sqlite::SqliteConnection`
/// - `diesel::mysql::MysqlConnection`
/// - `diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>`
/// - or, your custom diesel connection type (struct which implements `diesel::connection::Connection`)
pub connection_type: String,
/// Diesel schema import path
///
Expand Down Expand Up @@ -350,6 +356,14 @@ impl From<&MarkedFile> for FileChange {
}
}

/// Helper function for consistent table module name generation
/// this is used for the rust module path name and for the filename
///
/// input: "tableA", output -> "table_a"
fn get_table_module_name(table_name: &str) -> String {
table_name.to_snake_case().to_lowercase()
}

/// Generate all Models for a given diesel schema file
///
/// Models are saved to disk
Expand Down Expand Up @@ -412,11 +426,12 @@ pub fn generate_files(
return Err(Error::other("Cannot have a table named \"common\" while having option \"once_common_structs\" enabled"));
}
let table_name = table.name.to_string();
let table_filename = get_table_module_name(&table_name);
let table_config = config.table(&table_name);
let table_dir = if table_config.single_model_file {
output_models_dir.to_owned()
} else {
output_models_dir.join(&table_name)
output_models_dir.join(&table_filename)
};

if !table_dir.exists() {
Expand Down Expand Up @@ -451,11 +466,12 @@ pub fn generate_files(
file_changes.push(FileChange::from(&table_mod_rs));
}

mod_rs.ensure_mod_stmt(&table.name.to_string());
mod_rs.ensure_mod_stmt(&table_filename);
}

// pass 2: delete code for removed tables
for item in std::fs::read_dir(output_models_dir).attach_path_err(output_models_dir)? {
// TODO: this does not work with "single-model-file"
let item = item.attach_path_err(output_models_dir)?;

// check if item is a directory
Expand All @@ -482,9 +498,7 @@ pub fn generate_files(
item.path()
)))?;
let found = generated.iter().find(|g| {
g.name
.to_string()
.eq_ignore_ascii_case(associated_table_name)
get_table_module_name(&g.name.to_string()).eq_ignore_ascii_case(associated_table_name)
});
if found.is_some() {
continue;
Expand Down
9 changes: 4 additions & 5 deletions test/autogenerated_all/models/todos/generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

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

type ConnectionType = diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
pub type ConnectionType = diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>;

/// Struct representing a row in table `todos`
#[derive(Debug, Clone, Serialize, Deserialize, Queryable, Selectable, QueryableByName)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Queryable, Selectable, QueryableByName)]
#[diesel(table_name=todos, primary_key(id))]
pub struct Todos {
/// Field representing column `id`
Expand All @@ -18,15 +17,15 @@ pub struct Todos {
}

/// Update Struct for a row in table `todos` for [`Todos`]
#[derive(Debug, Clone, Serialize, Deserialize, AsChangeset, PartialEq, Default)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, AsChangeset, PartialEq, Default)]
#[diesel(table_name=todos)]
pub struct UpdateTodos {
/// Field representing column `created_at`
pub created_at: Option<chrono::NaiveDateTime>,
}

/// Result of a `.paginate` function
#[derive(Debug, Serialize)]
#[derive(Debug, serde::Serialize)]
pub struct PaginationResult<T> {
/// Resulting items that are from the current page
pub items: Vec<T>,
Expand Down
2 changes: 1 addition & 1 deletion test/autogenerated_all/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ 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 -c "diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>"
cargo run -- -i schema.rs -o models -g id -g created_at -c "diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>"
11 changes: 5 additions & 6 deletions test/autogenerated_attributes/models/todos/generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

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

type ConnectionType = diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
pub type ConnectionType = diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>;

/// Struct representing a row in table `todos`
#[derive(Debug, Clone, Serialize, Deserialize, Queryable, Selectable, QueryableByName)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Queryable, Selectable, QueryableByName)]
#[diesel(table_name=todos, primary_key(id))]
pub struct Todos {
/// Field representing column `id`
Expand All @@ -18,23 +17,23 @@ pub struct Todos {
}

/// Create Struct for a row in table `todos` for [`Todos`]
#[derive(Debug, Clone, Serialize, Deserialize, Insertable)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Insertable)]
#[diesel(table_name=todos)]
pub struct CreateTodos {
/// Field representing column `id`
pub id: i32,
}

/// Update Struct for a row in table `todos` for [`Todos`]
#[derive(Debug, Clone, Serialize, Deserialize, AsChangeset, PartialEq, Default)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, AsChangeset, PartialEq, Default)]
#[diesel(table_name=todos)]
pub struct UpdateTodos {
/// Field representing column `created_at`
pub created_at: Option<chrono::NaiveDateTime>,
}

/// Result of a `.paginate` function
#[derive(Debug, Serialize)]
#[derive(Debug, serde::Serialize)]
pub struct PaginationResult<T> {
/// Resulting items that are from the current page
pub items: Vec<T>,
Expand Down
2 changes: 1 addition & 1 deletion test/autogenerated_attributes/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

cd $SCRIPT_DIR

cargo run -- -i schema.rs -o models -g created_at -c "diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>"
cargo run -- -i schema.rs -o models -g created_at -c "diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>"
11 changes: 5 additions & 6 deletions test/autogenerated_primary_keys/models/todos/generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

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

type ConnectionType = diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
pub type ConnectionType = diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>;

/// Struct representing a row in table `todos`
#[derive(Debug, Clone, Serialize, Deserialize, Queryable, Selectable, QueryableByName)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Queryable, Selectable, QueryableByName)]
#[diesel(table_name=todos, primary_key(id))]
pub struct Todos {
/// Field representing column `id`
Expand All @@ -18,23 +17,23 @@ pub struct Todos {
}

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

/// Update Struct for a row in table `todos` for [`Todos`]
#[derive(Debug, Clone, Serialize, Deserialize, AsChangeset, PartialEq, Default)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, AsChangeset, PartialEq, Default)]
#[diesel(table_name=todos)]
pub struct UpdateTodos {
/// Field representing column `text`
pub text: Option<String>,
}

/// Result of a `.paginate` function
#[derive(Debug, Serialize)]
#[derive(Debug, serde::Serialize)]
pub struct PaginationResult<T> {
/// Resulting items that are from the current page
pub items: Vec<T>,
Expand Down
2 changes: 1 addition & 1 deletion test/autogenerated_primary_keys/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

cd $SCRIPT_DIR

cargo run -- -i schema.rs -o models -g id -c "diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>"
cargo run -- -i schema.rs -o models -g id -c "diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>"
11 changes: 5 additions & 6 deletions test/cleanup_generated_content/models/todos/generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

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

type ConnectionType = diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
pub type ConnectionType = diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>;

/// Struct representing a row in table `todos`
#[derive(Debug, Clone, Serialize, Deserialize, Queryable, Selectable, QueryableByName)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Queryable, Selectable, QueryableByName)]
#[diesel(table_name=todos, primary_key(id))]
pub struct Todos {
/// Field representing column `id`
Expand All @@ -24,7 +23,7 @@ pub struct Todos {
}

/// Create Struct for a row in table `todos` for [`Todos`]
#[derive(Debug, Clone, Serialize, Deserialize, Insertable)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Insertable)]
#[diesel(table_name=todos)]
pub struct CreateTodos {
/// Field representing column `id`
Expand All @@ -36,7 +35,7 @@ pub struct CreateTodos {
}

/// Update Struct for a row in table `todos` for [`Todos`]
#[derive(Debug, Clone, Serialize, Deserialize, AsChangeset, PartialEq, Default)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, AsChangeset, PartialEq, Default)]
#[diesel(table_name=todos)]
pub struct UpdateTodos {
/// Field representing column `text`
Expand All @@ -50,7 +49,7 @@ pub struct UpdateTodos {
}

/// Result of a `.paginate` function
#[derive(Debug, Serialize)]
#[derive(Debug, serde::Serialize)]
pub struct PaginationResult<T> {
/// Resulting items that are from the current page
pub items: Vec<T>,
Expand Down
4 changes: 2 additions & 2 deletions test/cleanup_generated_content/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

cd $SCRIPT_DIR

cargo run -- -i schema1.rs -o models -g created_at -g updated_at -c "diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>"
cargo run -- -i schema2.rs -o models -g created_at -g updated_at -c "diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>"
cargo run -- -i schema1.rs -o models -g created_at -g updated_at -c "diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>"
cargo run -- -i schema2.rs -o models -g created_at -g updated_at -c "diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>"
11 changes: 5 additions & 6 deletions test/create_update_str_cow/models/todos/generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

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

type ConnectionType = diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
pub type ConnectionType = diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>;

/// Struct representing a row in table `todos`
#[derive(Debug, Clone, Serialize, Deserialize, Queryable, Selectable, QueryableByName)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Queryable, Selectable, QueryableByName)]
#[diesel(table_name=todos, primary_key(text))]
pub struct Todos {
/// Field representing column `text`
Expand All @@ -22,7 +21,7 @@ pub struct Todos {
}

/// Create Struct for a row in table `todos` for [`Todos`]
#[derive(Debug, Clone, Serialize, Deserialize, Insertable)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Insertable)]
#[diesel(table_name=todos)]
pub struct CreateTodos<'a> {
/// Field representing column `text`
Expand All @@ -36,7 +35,7 @@ pub struct CreateTodos<'a> {
}

/// Update Struct for a row in table `todos` for [`Todos`]
#[derive(Debug, Clone, Serialize, Deserialize, AsChangeset, PartialEq, Default)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, AsChangeset, PartialEq, Default)]
#[diesel(table_name=todos)]
pub struct UpdateTodos<'a> {
/// Field representing column `text_nullable`
Expand All @@ -48,7 +47,7 @@ pub struct UpdateTodos<'a> {
}

/// Result of a `.paginate` function
#[derive(Debug, Serialize)]
#[derive(Debug, serde::Serialize)]
pub struct PaginationResult<T> {
/// Resulting items that are from the current page
pub items: Vec<T>,
Expand Down
2 changes: 1 addition & 1 deletion test/create_update_str_cow/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ 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>>" --create-str=cow --update-str=cow
cargo run -- -i schema.rs -o models -g id -g created_at -g updated_at -c "diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>" --create-str=cow --update-str=cow
Loading