Skip to content

Commit

Permalink
feat: add "once-connection-type"
Browse files Browse the repository at this point in the history
  • Loading branch information
hasezoey committed Oct 8, 2023
1 parent 5c07810 commit ac206e5
Show file tree
Hide file tree
Showing 19 changed files with 335 additions and 10 deletions.
5 changes: 5 additions & 0 deletions src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ pub struct MainOptions {
/// Generate common structs only once in a "common.rs" file
#[arg(long = "once-common-structs")]
pub once_common_structs: bool,

/// Generate the "ConnectionType" type only once in a "common.rs" file
#[arg(long = "once-connection-type")]
pub once_connection_type: bool,
}

#[derive(Debug, ValueEnum, Clone, PartialEq, Default)]
Expand Down Expand Up @@ -198,6 +202,7 @@ fn actual_main() -> dsync::Result<()> {
schema_path: args.schema_path,
model_path: args.model_path,
once_common_structs: args.once_common_structs,
once_connection_type: args.once_connection_type,
},
)?;

Expand Down
17 changes: 11 additions & 6 deletions src/code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,14 @@ pub struct PaginationResult<T> {{
)
}

/// Generate connection-type type
pub fn generate_connection_type(config: &GenerationConfig) -> String {
format!(
"\ntype ConnectionType = {connection_type};",
connection_type = config.connection_type,
)
}

/// Generate all imports for the struct file that are required
fn build_imports(table: &ParsedTableMacro, config: &GenerationConfig) -> String {
let table_options = config.table(&table.name.to_string());
Expand Down Expand Up @@ -547,16 +555,13 @@ fn build_imports(table: &ParsedTableMacro, config: &GenerationConfig) -> String
""
};

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

let common_structs_imports = if config.once_common_structs {
let common_structs_imports = if config.once_common_structs || config.once_connection_type {
format!("\nuse {}common::*;", config.model_path)
} else {
"".into()
Expand Down
15 changes: 11 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,8 @@ pub struct GenerationConfig<'a> {
pub model_path: String,
/// Generate common structs only once in a "common.rs" file
pub once_common_structs: bool,
/// Generate the "ConnectionType" type only once in a "common.rs" file
pub once_connection_type: bool,
}

impl GenerationConfig<'_> {
Expand Down Expand Up @@ -336,14 +338,19 @@ pub fn generate_files(
// check that the mod.rs file exists
let mut mod_rs = MarkedFile::new(output_models_dir.join("mod.rs"))?;

if config.once_common_structs {
if config.once_common_structs || config.once_connection_type {
let mut common_file = MarkedFile::new(output_models_dir.join("common.rs"))?;
common_file.ensure_file_signature()?;
common_file.change_file_contents({
let mut tmp = String::from(FILE_SIGNATURE);
tmp.push_str(&code::generate_common_structs(
&config.default_table_options,
));
if config.once_common_structs {
tmp.push_str(&code::generate_common_structs(
&config.default_table_options,
));
}
if config.once_connection_type {
tmp.push_str(&code::generate_connection_type(&config));
}
tmp
});
common_file.write()?;
Expand Down
12 changes: 12 additions & 0 deletions test/once_common_structs_once_connection_type/models/common.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/* @generated and managed by dsync */
#[derive(Debug, Serialize)]
pub struct PaginationResult<T> {
pub items: Vec<T>,
pub total_items: i64,
/// 0-based index
pub page: i64,
pub page_size: i64,
pub num_pages: i64,
}

type ConnectionType = diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
3 changes: 3 additions & 0 deletions test/once_common_structs_once_connection_type/models/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod common;
pub mod table1;
pub mod table2;
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/* @generated and managed by dsync */

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

#[derive(Debug, Serialize, Deserialize, Clone, Queryable, Insertable, Selectable)]
#[diesel(table_name=table1, primary_key(id))]
pub struct Table1 {
pub id: crate::schema::sql_types::Int,
}




impl Table1 {

pub fn create(db: &mut ConnectionType) -> QueryResult<Self> {
use crate::schema::table1::dsl::*;

insert_into(table1).default_values().get_result::<Self>(db)
}

pub fn read(db: &mut ConnectionType, param_id: crate::schema::sql_types::Int) -> QueryResult<Self> {
use crate::schema::table1::dsl::*;

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

/// Paginates through the table where page is a 0-based index (i.e. page 0 is the first page)
pub fn paginate(db: &mut ConnectionType, page: i64, page_size: i64) -> QueryResult<PaginationResult<Self>> {
use crate::schema::table1::dsl::*;

let page_size = if page_size < 1 { 1 } else { page_size };
let total_items = table1.count().get_result(db)?;
let items = table1.limit(page_size).offset(page * page_size).load::<Self>(db)?;

Ok(PaginationResult {
items,
total_items,
page,
page_size,
/* ceiling division of integers */
num_pages: total_items / page_size + i64::from(total_items % page_size != 0)
})
}

pub fn delete(db: &mut ConnectionType, param_id: crate::schema::sql_types::Int) -> QueryResult<usize> {
use crate::schema::table1::dsl::*;

diesel::delete(table1.filter(id.eq(param_id))).execute(db)
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod generated;
pub use generated::*;
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/* @generated and managed by dsync */

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

#[derive(Debug, Serialize, Deserialize, Clone, Queryable, Insertable, Selectable)]
#[diesel(table_name=table2, primary_key(id))]
pub struct Table2 {
pub id: crate::schema::sql_types::Int,
}




impl Table2 {

pub fn create(db: &mut ConnectionType) -> QueryResult<Self> {
use crate::schema::table2::dsl::*;

insert_into(table2).default_values().get_result::<Self>(db)
}

pub fn read(db: &mut ConnectionType, param_id: crate::schema::sql_types::Int) -> QueryResult<Self> {
use crate::schema::table2::dsl::*;

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

/// Paginates through the table where page is a 0-based index (i.e. page 0 is the first page)
pub fn paginate(db: &mut ConnectionType, page: i64, page_size: i64) -> QueryResult<PaginationResult<Self>> {
use crate::schema::table2::dsl::*;

let page_size = if page_size < 1 { 1 } else { page_size };
let total_items = table2.count().get_result(db)?;
let items = table2.limit(page_size).offset(page * page_size).load::<Self>(db)?;

Ok(PaginationResult {
items,
total_items,
page,
page_size,
/* ceiling division of integers */
num_pages: total_items / page_size + i64::from(total_items % page_size != 0)
})
}

pub fn delete(db: &mut ConnectionType, param_id: crate::schema::sql_types::Int) -> QueryResult<usize> {
use crate::schema::table2::dsl::*;

diesel::delete(table2.filter(id.eq(param_id))).execute(db)
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod generated;
pub use generated::*;
11 changes: 11 additions & 0 deletions test/once_common_structs_once_connection_type/schema.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
diesel::table! {
table1 (id) {
id -> Int,
}
}

diesel::table! {
table2 (id) {
id -> Int,
}
}
7 changes: 7 additions & 0 deletions test/once_common_structs_once_connection_type/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>>" --once-common-structs --once-connection-type
2 changes: 2 additions & 0 deletions test/once_connection_type/models/common.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/* @generated and managed by dsync */
type ConnectionType = diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::PgConnection>>;
3 changes: 3 additions & 0 deletions test/once_connection_type/models/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod common;
pub mod table1;
pub mod table2;
66 changes: 66 additions & 0 deletions test/once_connection_type/models/table1/generated.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/* @generated and managed by dsync */

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

#[derive(Debug, Serialize, Deserialize, Clone, Queryable, Insertable, Selectable)]
#[diesel(table_name=table1, primary_key(id))]
pub struct Table1 {
pub id: crate::schema::sql_types::Int,
}




#[derive(Debug, Serialize)]
pub struct PaginationResult<T> {
pub items: Vec<T>,
pub total_items: i64,
/// 0-based index
pub page: i64,
pub page_size: i64,
pub num_pages: i64,
}

impl Table1 {

pub fn create(db: &mut ConnectionType) -> QueryResult<Self> {
use crate::schema::table1::dsl::*;

insert_into(table1).default_values().get_result::<Self>(db)
}

pub fn read(db: &mut ConnectionType, param_id: crate::schema::sql_types::Int) -> QueryResult<Self> {
use crate::schema::table1::dsl::*;

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

/// Paginates through the table where page is a 0-based index (i.e. page 0 is the first page)
pub fn paginate(db: &mut ConnectionType, page: i64, page_size: i64) -> QueryResult<PaginationResult<Self>> {
use crate::schema::table1::dsl::*;

let page_size = if page_size < 1 { 1 } else { page_size };
let total_items = table1.count().get_result(db)?;
let items = table1.limit(page_size).offset(page * page_size).load::<Self>(db)?;

Ok(PaginationResult {
items,
total_items,
page,
page_size,
/* ceiling division of integers */
num_pages: total_items / page_size + i64::from(total_items % page_size != 0)
})
}

pub fn delete(db: &mut ConnectionType, param_id: crate::schema::sql_types::Int) -> QueryResult<usize> {
use crate::schema::table1::dsl::*;

diesel::delete(table1.filter(id.eq(param_id))).execute(db)
}

}
2 changes: 2 additions & 0 deletions test/once_connection_type/models/table1/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod generated;
pub use generated::*;
66 changes: 66 additions & 0 deletions test/once_connection_type/models/table2/generated.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/* @generated and managed by dsync */

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

#[derive(Debug, Serialize, Deserialize, Clone, Queryable, Insertable, Selectable)]
#[diesel(table_name=table2, primary_key(id))]
pub struct Table2 {
pub id: crate::schema::sql_types::Int,
}




#[derive(Debug, Serialize)]
pub struct PaginationResult<T> {
pub items: Vec<T>,
pub total_items: i64,
/// 0-based index
pub page: i64,
pub page_size: i64,
pub num_pages: i64,
}

impl Table2 {

pub fn create(db: &mut ConnectionType) -> QueryResult<Self> {
use crate::schema::table2::dsl::*;

insert_into(table2).default_values().get_result::<Self>(db)
}

pub fn read(db: &mut ConnectionType, param_id: crate::schema::sql_types::Int) -> QueryResult<Self> {
use crate::schema::table2::dsl::*;

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

/// Paginates through the table where page is a 0-based index (i.e. page 0 is the first page)
pub fn paginate(db: &mut ConnectionType, page: i64, page_size: i64) -> QueryResult<PaginationResult<Self>> {
use crate::schema::table2::dsl::*;

let page_size = if page_size < 1 { 1 } else { page_size };
let total_items = table2.count().get_result(db)?;
let items = table2.limit(page_size).offset(page * page_size).load::<Self>(db)?;

Ok(PaginationResult {
items,
total_items,
page,
page_size,
/* ceiling division of integers */
num_pages: total_items / page_size + i64::from(total_items % page_size != 0)
})
}

pub fn delete(db: &mut ConnectionType, param_id: crate::schema::sql_types::Int) -> QueryResult<usize> {
use crate::schema::table2::dsl::*;

diesel::delete(table2.filter(id.eq(param_id))).execute(db)
}

}
2 changes: 2 additions & 0 deletions test/once_connection_type/models/table2/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod generated;
pub use generated::*;
Loading

0 comments on commit ac206e5

Please sign in to comment.