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

Put write_params in map before generating to avoid duplicates #364

Merged
merged 3 commits into from
Jul 13, 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
12 changes: 8 additions & 4 deletions crates/cli/src/generator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,14 @@ impl PrismaGenerator for PrismaClientRustGenerator {
fn generate(self, args: GenerateArgs) -> Result<String, Self::Error> {
let header = header::generate(&args);

let module_path = self
.module_path
.parse()
.map_err(|_| Error::InvalidModulePath)?;
let module_path = {
let provided: TokenStream = self
.module_path
.parse()
.map_err(|_| Error::InvalidModulePath)?;

quote!(#provided::)
};

let models = models::modules(&args, &module_path);
let composite_types = composite_types::modules(&args, &module_path);
Expand Down
2 changes: 1 addition & 1 deletion crates/cli/src/generator/models/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ pub fn model_data(model: ModelWalker) -> ModelModulePart {

typ
}
_ => (field.type_tokens(&quote!(super::))?, None),
_ => (field.type_tokens(&quote!(super::super::))?, None),
}
}
};
Expand Down
18 changes: 9 additions & 9 deletions crates/cli/src/generator/models/include_select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ fn model_macro<'a>(
let model_name_snake_raw = snake_ident_raw(model.name());
let macro_name = format_ident!("_{variant}_{model_name_snake_raw}");

let model_module = quote!(#module_path::#model_name_snake);
let model_module = quote!(#module_path #model_name_snake);

let selection_type = variant.type_trait();
let selection_param = variant.param();
Expand Down Expand Up @@ -89,7 +89,7 @@ fn model_macro<'a>(

quote! {
(@field_module; #field_name_snake #selections_pattern_produce) => {
#module_path::#relation_model_name_snake::#variant_ident!(@definitions; ; $($selections)+);
#module_path #relation_model_name_snake::#variant_ident!(@definitions; ; $($selections)+);
};
}
});
Expand All @@ -103,15 +103,15 @@ fn model_macro<'a>(
RefinedFieldWalker::Relation(relation_field) =>{
let relation_model_name_snake = snake_ident(relation_field.related_model().name());

let relation_model_module = quote!(#module_path::#relation_model_name_snake);
let relation_model_module = quote!(#module_path #relation_model_name_snake);

match relation_field.ast_field().arity {
FieldArity::List => {
quote! {
(@selection_field_to_selection_param; #field_name_snake $(#filters_pattern_produce)? #selections_pattern_produce) => {{
Into::<#model_module::#selection_param>::into(
#field_module::#variant_pascal::$selection_mode(
#relation_model_module::ManyArgs::new(#module_path::#relation_model_name_snake::#variant_ident!(
#relation_model_module::ManyArgs::new(#module_path #relation_model_name_snake::#variant_ident!(
@filters_to_args;
$($($filters)+)?
)) $($(.$arg($($arg_params)*))*)?,
Expand All @@ -125,7 +125,7 @@ fn model_macro<'a>(
(@selection_field_to_selection_param; #field_name_snake $(#filters_pattern_produce)?) => {{
Into::<#model_module::#selection_param>::into(
#field_module::#variant_pascal::Fetch(
#relation_model_module::ManyArgs::new(#module_path::#relation_model_name_snake::#variant_ident!(
#relation_model_module::ManyArgs::new(#module_path #relation_model_name_snake::#variant_ident!(
@filters_to_args;
$($($filters)+)?
)) $($(.$arg($($arg_params)*))*)?
Expand Down Expand Up @@ -173,7 +173,7 @@ fn model_macro<'a>(
let field_type = f.type_tokens(module_path);

let specta_rename = cfg!(feature = "specta").then(|| {
quote!(#[specta(rename_from_path = #module_path::#model_name_snake::#field_name_snake::NAME)])
quote!(#[specta(rename_from_path = #module_path #model_name_snake::#field_name_snake::NAME)])
});

quote! {
Expand Down Expand Up @@ -380,13 +380,13 @@ fn model_macro<'a>(
let selection = {
let scalar_selections = matches!(variant, Variant::Include).then(||
quote! {
<#module_path::#model_name_snake::Types as ::prisma_client_rust::ModelTypes>::scalar_selections()
<#module_path #model_name_snake::Types as ::prisma_client_rust::ModelTypes>::scalar_selections()
}
);

quote!(Selection(
[
#module_path::#model_name_snake::#variant_ident!(
#module_path #model_name_snake::#variant_ident!(
@selections_to_params; : #variant_ident
{ $(#selection_pattern_consume)+ }
)
Expand Down Expand Up @@ -487,7 +487,7 @@ fn model_macro<'a>(
(@selection_field_to_selection_param; $($tokens:tt)*) => { compile_error!(stringify!($($tokens)*)) }; // ::prisma_client_rust::Selection::builder("").build() };

(@selections_to_params; : $macro_name:ident {$(#selection_pattern_produce)+}) => {
[ $(#module_path::#model_name_snake::$macro_name!(@selection_field_to_selection_param; #selection_pattern_consume),)+]
[ $(#module_path #model_name_snake::$macro_name!(@selection_field_to_selection_param; #selection_pattern_consume),)+]
};

(@filters_to_args;) => {
Expand Down
8 changes: 2 additions & 6 deletions crates/cli/src/generator/models/partial_unchecked.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,14 @@ pub fn r#macro(model: ModelWalker, module_path: &TokenStream) -> TokenStream {
let model_name_snake_raw = snake_ident_raw(model.name());
let macro_name = format_ident!("_partial_unchecked_{model_name_snake_raw}");

let model_module = quote!(#module_path::#model_name_snake);
let model_module = quote!(#module_path #model_name_snake);

let struct_fields = model.scalar_fields().map(|scalar_field| {
let field_name_str = scalar_field.name();
let field_name_snake = snake_ident(field_name_str);

let arity = scalar_field.ast_field().arity;

let field_type = scalar_field
.scalar_field_type()
.to_tokens(module_path, &arity, &model.db);

let double_option_attrs = arity.is_optional().then(|| {
quote! {
#[serde(default, with = "::prisma_client_rust::serde::double_option")]
Expand All @@ -28,7 +24,7 @@ pub fn r#macro(model: ModelWalker, module_path: &TokenStream) -> TokenStream {
quote! {
#[serde(rename = #field_name_str)]
#double_option_attrs
pub #field_name_snake: #field_type
pub #field_name_snake: #module_path #model_name_snake::#field_name_snake::Type
}
});

Expand Down
6 changes: 3 additions & 3 deletions crates/cli/src/generator/models/where_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,7 @@ pub fn field_module(
let equals_filter = {
let where_param_variant = format_ident!("{field_name_pascal}Equals");
let content_type =
quote!(Vec<#module_path::#comp_type_snake::WhereParam>);
quote!(Vec<#module_path #comp_type_snake::WhereParam>);

where_param_entries.push(Variant::BaseVariant {
definition: quote!(#where_param_variant(Vec<#content_type>)),
Expand Down Expand Up @@ -537,7 +537,7 @@ pub fn field_module(
let where_param_variant =
format_ident!("{field_name_pascal}{method_pascal}");
let content_type =
quote!(Vec<#module_path::#comp_type_snake::WhereParam>);
quote!(Vec<#module_path #comp_type_snake::WhereParam>);

where_param_entries.push(Variant::BaseVariant {
definition: quote!(#where_param_variant(#content_type)),
Expand Down Expand Up @@ -579,7 +579,7 @@ pub fn field_module(
let where_param_variant =
format_ident!("{field_name_pascal}{method_pascal}");
let content_type =
quote!(Vec<#module_path::#comp_type_snake::WhereParam>);
quote!(Vec<#module_path #comp_type_snake::WhereParam>);

where_param_entries.push(Variant::BaseVariant {
definition: quote!(#where_param_variant(#content_type)),
Expand Down
112 changes: 70 additions & 42 deletions crates/cli/src/generator/write_params.rs
Original file line number Diff line number Diff line change
@@ -1,58 +1,86 @@
use std::collections::BTreeMap;

use prisma_client_rust_sdk::prisma::psl::parser_database::ScalarType;

use super::prelude::*;

pub fn enum_name(filter: &Filter) -> Ident {
format_ident!("{}Param", &filter.name)
}

pub fn generate_module(args: &GenerateArgs) -> TokenStream {
let write_params = args.write_params.iter().map(|write_param| {
let name = enum_name(write_param);

let (method_variants, method_matches): (Vec<_>, Vec<_>) = write_param
.fields
let write_params = {
let write_params_map = args
.write_params
.iter()
.flat_map(|field| {
let typ = field.type_tokens(&quote!(super::super::));
let action = &field.name;

let prisma_value_converter = field.to_prisma_value(&format_ident!("value"));

let method_name_pascal = pascal_ident(&field.name);

// Set doesn't use 'set' as the action name.
let prisma_value = if action == "set" {
prisma_value_converter
} else {
quote! {
::prisma_client_rust::PrismaValue::Object(vec![(
#action.to_string(),
#prisma_value_converter
)])
.map(|write_param| (&write_param.name, write_param))
.collect::<BTreeMap<_, _>>();

write_params_map
.values()
.map(|write_param| {
let name = enum_name(write_param);

let (method_variants, method_matches): (Vec<_>, Vec<_>) = {
if write_param.name == "Json" {
let var = format_ident!("value");
let prisma_value = ScalarType::Json.to_prisma_value(&var);

(
vec![quote!(Set(::prisma_client_rust::serde_json::Value))],
vec![quote!(Self::Set(#var) => #prisma_value)],
)
} else {
write_param
.fields
.iter()
.flat_map(|field| {
let typ = field.type_tokens(&quote!(super::super::));
let action = &field.name;

let prisma_value_converter =
field.to_prisma_value(&format_ident!("value"));

let method_name_pascal = pascal_ident(&field.name);

// Set doesn't use 'set' as the action name.
let prisma_value = if action == "set" {
prisma_value_converter
} else {
quote! {
::prisma_client_rust::PrismaValue::Object(vec![(
#action.to_string(),
#prisma_value_converter
)])
}
};

Some((
quote!(#method_name_pascal(#typ)),
quote!(Self::#method_name_pascal(value) => #prisma_value),
))
})
.unzip()
}
};

Some((
quote!(#method_name_pascal(#typ)),
quote!(Self::#method_name_pascal(value) => #prisma_value),
))
})
.unzip();

quote! {
#[derive(Debug, Clone)]
pub enum #name {
#(#method_variants),*
}

impl Into<::prisma_client_rust::PrismaValue> for #name {
fn into(self) -> ::prisma_client_rust::PrismaValue {
match self {
#(#method_matches),*
quote! {
#[derive(Debug, Clone)]
pub enum #name {
#(#method_variants),*
}

impl Into<::prisma_client_rust::PrismaValue> for #name {
fn into(self) -> ::prisma_client_rust::PrismaValue {
match self {
#(#method_matches),*
}
}
}
}
}
}
});
})
.collect::<Vec<_>>()
};

quote! {
pub mod write_params {
Expand Down
58 changes: 34 additions & 24 deletions crates/sdk/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,15 @@ impl<'a> GenerateArgs<'a> {
let mut filters = vec![];

filters.extend(scalars.iter().flat_map(|scalar| {
if matches!(scalar, ScalarType::Json) {
let mut s = "Json".to_string();

return vec![Filter {
name: s,
fields: vec![],
}];
}

let possible_inputs = [
format!("{}FieldUpdateOperationsInput", scalar.to_dmmf_string()),
format!(
Expand All @@ -146,35 +155,38 @@ impl<'a> GenerateArgs<'a> {
),
];

possible_inputs.into_iter().filter_map(|input| {
let input_type = dmmf.schema.find_input_type(&input)?;
possible_inputs
.into_iter()
.filter_map(|input| {
let input_type = dmmf.schema.find_input_type(&input)?;

let mut s = scalar.as_str().to_string();
let mut s = scalar.as_str().to_string();

if input_type.name.contains("List") {
s += "List";
} else if input_type.name.contains("Nullable") {
s += "Nullable";
}
if input_type.name.contains("List") {
s += "List";
} else if input_type.name.contains("Nullable") {
s += "Nullable";
}

Some(Filter {
name: s,
fields: input_type
.fields
.iter()
.filter_map(|field| {
field.input_types.iter().find(|input_type| {
match input_type.location {
Some(Filter {
name: s,
fields: input_type
.fields
.iter()
.filter_map(|field| {
field.input_types.iter().find(|input_type| match input_type
.location
{
TypeLocation::Scalar if input_type.typ != "Null" => true,
_ => false,
}
})?;
})?;

Some(field)
})
.collect(),
Some(field)
})
.collect(),
})
})
})
.collect()
}));

filters.extend(schema.db.walk_enums().flat_map(|enm| {
Expand Down Expand Up @@ -239,8 +251,6 @@ impl<'a> GenerateArgs<'a> {
_ => {}
}
}

return None;
}

field
Expand Down
8 changes: 8 additions & 0 deletions tests/database/postgres/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ model SomeModel {
enum_list SomeEnum[]
}

model AnotherModel {
id String @id
// https://discord.com/channels/1011665225809924136/1129034041363017848/1129038605294252103
string_array String[]
another_array String[]
json Json
}

enum SomeEnum {
A
B
Expand Down
Loading