Skip to content

fix: where type issues #958

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

Merged
merged 6 commits into from
Jan 13, 2025
Merged

fix: where type issues #958

merged 6 commits into from
Jan 13, 2025

Conversation

Yohe-Am
Copy link
Contributor

@Yohe-Am Yohe-Am commented Jan 10, 2025

  • Fixes issues with type counts.

Migration notes


  • The change comes with new or modified tests
  • Hard-to-understand functions have explanatory comments
  • End-user documentation is updated to reflect the change

Summary by CodeRabbit

  • New Features

    • Enhanced duplicate detection mechanism for type graphs.
    • Improved type identification and relationship tracking.
    • Added new root functions for dynamic entity management in type duplication.
  • Refactor

    • Updated model identifier handling in type generation.
    • Modified key management for skip models from type-based to string-based keys.
    • Transitioned from static to dynamic entity definitions for scalability.
  • Bug Fixes

    • Streamlined type duplicate detection logic.
    • Improved error handling for unsupported type scenarios.
    • Adjusted assertions for serialization size and type count limits in tests.

@Yohe-Am Yohe-Am requested a review from a team January 10, 2025 06:40
Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

📝 Walkthrough

Walkthrough

The pull request introduces changes across several files, primarily affecting the handling of model identifiers and duplicate detection. In src/typegraph/core/src/runtimes/prisma/type_generation/where_.rs, the Where struct's skip_models field type is modified from BTreeMap<TypeId, String> to BTreeMap<String, String>, altering how model identifiers are stored. Additionally, the nested and generate methods are updated to use string representations of model names. In tools/list-duplicates.ts, a new function listDuplicatesEnhanced is added to improve duplicate detection logic, while the existing listDuplicates function is modified to utilize this new implementation. The InputType and OutType structs are also updated to use BTreeSet<String> for managing relationships, enhancing uniqueness and ordering.

Changes

File Change Summary
src/typegraph/core/src/runtimes/prisma/type_generation/where_.rs - Changed skip_models field type from BTreeMap<TypeId, String> to BTreeMap<String, String>
- Updated nested method to use model name as key
- Modified generate method to lookup using model type name
- Simplified suffix generation logic in name method
tools/list-duplicates.ts - Added new listDuplicatesEnhanced function for advanced duplicate type detection
- Modified listDuplicates to call listDuplicatesEnhanced
- Enhanced duplicate tracking with reducedSetMap and reducedSet
src/typegraph/core/src/runtimes/prisma/type_generation/input_type.rs - Changed skip_rel field type from Vec<String> to BTreeSet<String>
- Updated methods to use BTreeSet for relationship names
src/typegraph/core/src/runtimes/prisma/type_generation/out_type.rs - Changed skip_rel field type from Vec<String> to BTreeSet<String>
- Updated methods to use BTreeSet for relationship names
tests/runtimes/prisma/type_duplication.ts - Removed static entity definitions; implemented dynamic entity generation based on TYPE_COUNT
- Added new root functions for various operations on entities
tests/runtimes/prisma/type_duplication_test.ts - Updated assertions for serialized size and type counts in tests

Possibly related PRs

  • feat: Unify worker manager #954: The changes in the InputType and OutType structs in the main PR involve modifications to how relationships are stored, which aligns with the unification of the worker manager in the retrieved PR that also focuses on improving the management of tasks and relationships within the runtime environment.

Suggested reviewers

  • Natoandro
  • luckasRanarison

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
tools/list-duplicates.ts (2)

29-30: Remove unused variable 'theWheres' or uncomment the code that uses it

The variable theWheres is populated but not utilized since the code that uses it (lines 248-253) is commented out. This may cause confusion and unnecessary memory usage.

Consider either removing the unused variable and related code if it's no longer needed, or uncommenting and updating the code block to utilize theWheres appropriately.

Also applies to: 248-253


124-142: Clean up commented-out code in 'suffix2' generation

In the name method, there is a block of commented-out code regarding nested_suffix and processing of keys (lines 124-142). Keeping unused code can reduce readability and maintainability.

Consider removing the commented-out code to clean up the method:

            let suffix2 = if !self.skip_models.is_empty() {
-                /* let nested_suffix = if self.aggregates {
-                    "_where_with_aggregates"
-                } else {
-                    "_where"
-                }; */

                let mut keys = self
                    .skip_models
                    .keys()
                    .cloned()
                    .collect::<Vec<_>>();
                keys.sort();
                format!("_excluding_{}", keys.join("_and_"))
            } else {
                "".to_string()
            };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d8dac2 and 2b53581.

⛔ Files ignored due to path filters (20)
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__query_where_expr__tests__Post__QueryWhereExpr.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__query_where_expr__tests__User__QueryWhereExpr.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_many Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_many Post out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_many User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_many User out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_unique Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_unique Post out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_unique User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_unique User out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__group_by Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__group_by Post out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__group_by User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__group_by User out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__update_many Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__update_many User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__update_one Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__update_one User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__where___test__where Post.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__where___test__where User.snap is excluded by !**/*.snap
📒 Files selected for processing (2)
  • src/typegraph/core/src/runtimes/prisma/type_generation/where_.rs (4 hunks)
  • tools/list-duplicates.ts (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: lint-compat (macos-14, aarch64-apple-darwin, false)
  • GitHub Check: lint-compat (macos-13, x86_64-apple-darwin, false)
  • GitHub Check: test-full
  • GitHub Check: pre-commit
🔇 Additional comments (2)
src/typegraph/core/src/runtimes/prisma/type_generation/where_.rs (2)

20-20: Assess the impact of changing 'skip_models' key from 'TypeId' to 'String'

Changing the key type of skip_models from TypeId to String (line 20) may have performance implications due to the costlier string comparisons and potential for key collisions if different models share the same name. In line 64, when accessing skip_models, ensure that the model names are unique and consistent.

Please confirm that model names are unique identifiers in this context and that this change won't introduce unintended side effects. If necessary, consider using a combination of TypeId and String or another unique identifier to maintain performance and correctness.

Also applies to: 64-64


Line range hint 78-83: Ensure 'edges' correctly accumulates dependencies in 'function' case

Similar to the issue in listDuplicatesEnhanced, verify that in the generate method, when constructing edges, the dependencies for 'function' types include both input and output without overwriting. This ensures proper traversal and processing of type relations.

Review the logic around building edges to confirm that both input and output dependencies are accounted for correctly.

@luckasRanarison
Copy link
Contributor

Awesome, the vivavox typegraph size went down to 1.4mb!

Copy link

codecov bot commented Jan 10, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 77.98%. Comparing base (324dffa) to head (835a204).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #958   +/-   ##
=======================================
  Coverage   77.98%   77.98%           
=======================================
  Files         154      154           
  Lines       19082    19082           
  Branches     1929     1929           
=======================================
  Hits        14882    14882           
  Misses       4177     4177           
  Partials       23       23           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

michael-0acf4
michael-0acf4 previously approved these changes Jan 10, 2025
Copy link
Contributor

@michael-0acf4 michael-0acf4 left a comment

Choose a reason for hiding this comment

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

Very good stuff!

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (8)
tests/runtimes/prisma/type_duplication.ts (2)

9-9: Consider renaming noOfTypes to numOfTypes

To improve code readability, consider renaming the variable noOfTypes to numOfTypes or numberOfTypes for clarity.


11-11: Improve error message for invalid TYPE_COUNT

The error message "NAN!" may be unclear. Provide a more descriptive message to indicate that TYPE_COUNT must be a valid number.

Apply this diff to enhance the error message:

-    throw new Error("NAN!");
+    throw new Error("Invalid TYPE_COUNT: Not a Number");
tests/runtimes/prisma/type_duplication_test.ts (1)

16-16: Remove unnecessary console.log statement

Logging raw may produce extensive output and impact performance. Consider removing this statement if it is no longer needed.

Apply this diff to remove the console log:

-  console.log(raw);
src/typegraph/core/src/runtimes/prisma/type_generation/out_type.rs (1)

83-87: Simplify suffix generation in the name function

The mapping over self.skip_rel can be simplified by removing unnecessary slicing.

Apply this diff to streamline the code:

            format!(
                "_excluding_{}",
                self.skip_rel
-                   .iter()
-                   .map(|owned| &owned[..])
+                   .iter()
                    .cloned()
                    .collect::<Vec<_>>()
                    .join("_and_")
            )

Alternatively, you can use as_str for clarity:

            format!(
                "_excluding_{}",
                self.skip_rel
                    .iter()
-                   .map(|owned| &owned[..])
+                   .map(|s| s.as_str())
                    .collect::<Vec<_>>()
                    .join("_and_")
            )
src/typegraph/core/src/runtimes/prisma/type_generation/input_type.rs (1)

221-228: Consider extracting string manipulation logic

The string manipulation logic in the name method could be extracted into a helper function for better readability and reusability.

+fn format_skip_rel_suffix(skip_rel: &BTreeSet<String>) -> String {
+    if skip_rel.is_empty() {
+        "".to_string()
+    } else {
+        format!(
+            "_excluding_{}",
+            skip_rel
+                .iter()
+                .map(|owned| &owned[..])
+                .collect::<Vec<_>>()
+                .join("_and_")
+        )
+    }
+}

 fn name(&self, _context: &PrismaContext) -> Result<String> {
     let model_name = self.model_id.name().unwrap().unwrap();
-    let suffix = if self.skip_rel.is_empty() {
-        "".to_string()
-    } else {
-        format!(
-            "_excluding_{}",
-            self.skip_rel
-                .iter()
-                .map(|owned| &owned[..])
-                .collect::<Vec<_>>()
-                .join("_and_")
-        )
-    };
+    let suffix = format_skip_rel_suffix(&self.skip_rel);
     let op = match self.operation {
         Operation::Create => "create",
         Operation::Update => "update",
     };
     Ok(format!("{model_name}_{op}_input{suffix}"))
 }
tools/list-duplicates.ts (3)

42-49: Consider memoizing edge additions

The addToRevEdges function is called frequently during graph traversal. Consider memoizing the results for frequently accessed nodes to improve performance.

+const memoizedEdges = new Map<number, number[]>();
+
 const addToRevEdges = (of: number, idx: number) => {
+  if (memoizedEdges.has(of)) {
+    const edges = memoizedEdges.get(of)!;
+    edges.push(idx);
+    return;
+  }
   const prev = revEdges.get(of);
   if (prev) {
     prev.push(idx);
+    memoizedEdges.set(of, prev);
   } else {
-    revEdges.set(of, [idx]);
+    const edges = [idx];
+    revEdges.set(of, edges);
+    memoizedEdges.set(of, edges);
   }
 };

155-162: Enhance error reporting

The error message could be more descriptive by including the type information and indices in a structured format.

 const noMatchError = () => {
   console.log("no match on dupe reduction", {
     from: tg.types[from],
     to: tg.types[to],
     target: type,
   });
-  return Error("no match on dupe reduction");
+  return Error(
+    `Failed to reduce duplicate: from=${from}(${tg.types[from].type}) ` +
+    `to=${to}(${tg.types[to].type}) in target=${type.type}`
+  );
 };

271-289: Consider using an enum for type categories

The type categories in incrementKindCount could be defined as an enum to prevent typos and improve maintainability.

enum TypeCategory {
  PrismaWhereFilterRelated = 'prismaWhereFilterRelated',
  PrismaUpdateInputRelated = 'prismaUpdateInputRelated',
  PrismaCreateInputRelated = 'prismaCreateInputRelated',
  PrismaOutputRelated = 'prismaOutputRelated'
}

function incrementKindCount(type: TypeNode, sumMap: Record<string, number>) {
  if (type.title.match(/_where_/)) {
    sumMap[TypeCategory.PrismaWhereFilterRelated] = 
      (sumMap[TypeCategory.PrismaWhereFilterRelated] ?? 0) + 1;
  }
  // ... similar changes for other categories
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2b53581 and 2105a14.

⛔ Files ignored due to path filters (1)
  • deno.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • .ghjk/lock.json (3 hunks)
  • ghjk.ts (1 hunks)
  • src/typegraph/core/src/runtimes/prisma/type_generation/input_type.rs (4 hunks)
  • src/typegraph/core/src/runtimes/prisma/type_generation/out_type.rs (3 hunks)
  • tests/runtimes/prisma/type_duplication.ts (1 hunks)
  • tests/runtimes/prisma/type_duplication_test.ts (1 hunks)
  • tools/list-duplicates.ts (3 hunks)
🔇 Additional comments (6)
ghjk.ts (1)

112-113: LGTM! Memory optimization for Rust builds.

Setting RUST_JOBS=8 is a good practice to prevent memory exhaustion during Rust compilation on systems with many cores.

Let's verify the impact of this change on build times and memory usage:

✅ Verification successful

Verified: RUST_JOBS=8 is the sole and appropriate parallel jobs configuration

The limit is consistently defined only in ghjk.ts, which is ideal for a project with multiple Rust components. This centralized configuration helps maintain predictable build behavior and memory usage across different environments.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check available cores and current memory usage during Rust builds
# Note: This helps validate if the 8-core limit is appropriate for the system

# Check total CPU cores
echo "Available CPU cores:"
nproc

# Check memory info
echo -e "\nMemory information:"
free -h

# Look for any existing parallel job configurations in Rust files
echo -e "\nExisting parallel job configurations:"
rg -g '*.toml' 'jobs|parallel|threads'

Length of output: 447


Script:

#!/bin/bash
# Search for RUST_JOBS configurations across all files
echo "Files containing RUST_JOBS:"
rg "RUST_JOBS" -l

# Look for Rust configuration files
echo -e "\nRust configuration files:"
fd -e toml
fd "rust-toolchain"
fd "rustfmt.toml"
fd "cargo.lock"

# Check for other environment configurations
echo -e "\nOther environment configurations:"
rg "RUST_" -l

Length of output: 3112

.ghjk/lock.json (1)

Line range hint 1989-2025: LGTM! Configuration properly synchronized.

The lock file changes correctly reflect the addition of the RUST_JOBS environment variable in the dev environment configuration.

Also applies to: 2074-2074

tests/runtimes/prisma/type_duplication_test.ts (1)

12-12: Verify increased limits for serialization size and type count

The serialization size limit has been increased eightfold, and the type count limit has been raised from 3,000 to 30,000. Ensure that these changes are intentional and assess their impact on performance and resource usage.

Also applies to: 21-21

src/typegraph/core/src/runtimes/prisma/type_generation/input_type.rs (1)

23-23: Good choice using BTreeSet for skip_rel!

Using BTreeSet instead of Vec is a better choice here as it:

  • Ensures uniqueness of relationship names
  • Maintains sorted order
  • Provides O(log n) lookups for contains checks
tools/list-duplicates.ts (2)

76-78: Edge handling looks good now!

The edge handling in the 'function' case has been fixed to properly store both input and output edges, addressing the issue from the previous review.


36-143: Consider adding a maximum cycle limit

The while loop could potentially run for a long time on complex type graphs. Consider adding a maximum cycle limit with a warning when reached.

+const MAX_CYCLES = 1000;
 while (true) {
   cycleNo += 1;
+  if (cycleNo > MAX_CYCLES) {
+    console.warn(`Warning: Maximum cycle count (${MAX_CYCLES}) reached. The type graph might be too complex.`);
+    break;
+  }
   // ... rest of the code
 }

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/typegraph/core/src/runtimes/prisma/type_generation/where_.rs (1)

20-20: ⚠️ Potential issue

Previous review comment about unwrap calls is still valid.

The code still uses double unwrap calls which could lead to panics. Consider using proper error handling as suggested in the previous review.

Also applies to: 35-35, 64-64

🧹 Nitpick comments (8)
tests/runtimes/prisma/type_duplication.ts (3)

9-12: Improve error message for invalid TYPE_COUNT.

The error message "NAN!" is not descriptive enough. Consider providing more context about the expected value.

-    throw new Error("NAN!");
+    throw new Error(`Invalid TYPE_COUNT value: expected a number but got "${Deno.env.get("TYPE_COUNT")}"`);

13-55: Add documentation for the relationship generation logic.

The relationship generation logic based on even/odd indices is complex and would benefit from detailed documentation explaining:

  • Why even/odd indices are used for relationship types
  • The significance of the relationship patterns
  • The impact of the index-based conditions on the generated schema
+  // Relationship generation rules:
+  // 1. Even-indexed entities have optional relationships with other even-indexed entities
+  // 2. Odd-indexed entities have optional relationships with other odd-indexed entities
+  // 3. Even-indexed entities have list relationships with odd-indexed entities
+  // 4. Odd-indexed entities have single relationships with even-indexed entities
+  // This pattern helps test various relationship combinations systematically
   const entts = Object.fromEntries(enttNames.map(

62-72: Consider grouping related operations for better maintainability.

The root functions could be organized by operation type (read, write, aggregate) for better maintainability.

   for (const [key, type] of Object.entries(entts)) {
+    // Read operations
     rootFns[`find_unique_${key}`] = prisma.findUnique(type);
     rootFns[`find_many_${key}`] = prisma.findMany(type);
+
+    // Write operations
     rootFns[`create_${key}`] = prisma.create(type);
     rootFns[`create_many_${key}`] = prisma.createMany(type);
     rootFns[`update_${key}`] = prisma.update(type);
     rootFns[`update_many_${key}`] = prisma.updateMany(type);
     rootFns[`delete_${key}`] = prisma.delete(type);
     rootFns[`delete_many_${key}`] = prisma.deleteMany(type);
     rootFns[`upsert_${key}`] = prisma.upsert(type);
+
+    // Aggregate operations
     rootFns[`aggregate_${key}`] = prisma.aggregate(type);
     rootFns[`group_by_${key}`] = prisma.groupBy(type);
src/typegraph/core/src/runtimes/prisma/type_generation/where_.rs (1)

124-142: Remove commented-out code for suffix generation.

The old implementation has been replaced with a new one that sorts keys for consistent naming. The commented-out code can be safely removed as it's no longer needed and is tracked in version control.

-            /* let nested_suffix = if self.aggregates {
-                "_where_with_aggregates"
-            } else {
-                "_where"
-            }; */
-
             let mut keys = self
                 .skip_models
                 .keys()
                 .cloned()
-                // .map(|id| id.name().unwrap().unwrap())
-                // .map(|name| {
-                //     name.strip_suffix(nested_suffix)
-                //         .map(|str| str.to_owned())
-                //         .unwrap_or(name)
-                // })
                 .collect::<Vec<_>>();
tools/list-duplicates.ts (4)

22-28: Enhance function documentation structure.

Consider using JSDoc format for better documentation structure and IDE support.

-// Tries to detect structurally equivalent duplicates by iteratively
-// updating composite types to refer to deduped types.
-// I.e. optional<A> and optional<B> should be considered duplicates
-// if A and B are duplicates of each other.
-// This function is not perfect and is not able to detect some
-// forms of structural equivalence. Additions to the TypeNode might
-// break it.
+/**
+ * Detects structurally equivalent duplicates by iteratively updating composite
+ * types to refer to deduped types.
+ * 
+ * @example
+ * optional<A> and optional<B> are considered duplicates if A and B are duplicates
+ * 
+ * @limitations
+ * - Not all forms of structural equivalence can be detected
+ * - Changes to TypeNode structure might break the detection logic
+ * 
+ * @param tg - The type graph to analyze
+ * @param _rootIdx - The starting index for analysis
+ */

74-217: Consider extracting type-specific logic into separate functions.

The switch statement handling different types is quite long and could be more maintainable if split into separate functions.

+    function handleFunctionType(type: TypeNode, idx: number) {
+      edges.set(idx, [type.input, type.output]);
+      addToRevEdges(type.input, idx);
+      addToRevEdges(type.output, idx);
+    }
+
+    function handleObjectType(type: TypeNode, idx: number) {
+      edges.set(idx, Object.values(type.properties));
+      for (const dep of Object.values(type.properties)) {
+        addToRevEdges(dep, idx);
+      }
+    }
+
     switch (structure.type) {
       case "function":
-        edges.set(idx, [structure.input, structure.output]);
-        addToRevEdges(structure.input, idx);
-        addToRevEdges(structure.output, idx);
+        handleFunctionType(structure, idx);
         break;
       case "object":
-        edges.set(idx, Object.values(structure.properties));
-        for (const dep of Object.values(structure.properties)) {
-          addToRevEdges(dep, idx);
-        }
+        handleObjectType(structure, idx);
         break;

232-241: Remove commented-out logging code.

The commented-out logging code can be safely removed as it's tracked in version control.

-        /* const injection = "injection" in fromType
-          // deno-lint-ignore no-explicit-any
-          ? ` (injection ${(fromType.injection as any).source})`
-          : "";
-        console.log(
-          `    ${
-            green(fromIdx.toString())
-          } ${fromType.type}:${fromType.title}${injection}`,
-        ); */

271-289: Extract regex patterns as constants.

Consider extracting the regex patterns into named constants for better maintainability and reusability.

+const PATTERNS = {
+  WHERE_FILTER: /_where_/,
+  UPDATE_INPUT: /_update_input/,
+  CREATE_INPUT: /_create_input/,
+  OUTPUT: /_output/,
+} as const;
+
 function incrementKindCount(type: TypeNode, sumMap: Record<string, number>) {
-  if (type.title.match(/_where_/)) {
+  if (type.title.match(PATTERNS.WHERE_FILTER)) {
     const key = "prismaWhereFilterRelated";
     sumMap[key] = (sumMap[key] ?? 0) + 1;
   }
-  if (type.title.match(/_update_input/)) {
+  if (type.title.match(PATTERNS.UPDATE_INPUT)) {
     const key = "prismaUpdateInputRelated";
     sumMap[key] = (sumMap[key] ?? 0) + 1;
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2105a14 and 34b6f69.

⛔ Files ignored due to path filters (20)
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__query_where_expr__tests__Post__QueryWhereExpr.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__query_where_expr__tests__User__QueryWhereExpr.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_many Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_many Post out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_many User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_many User out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_unique Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_unique Post out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_unique User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__find_unique User out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__group_by Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__group_by Post out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__group_by User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__group_by User out.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__update_many Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__update_many User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__update_one Post inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__test__update_one User inp.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__where___test__where Post.snap is excluded by !**/*.snap
  • src/typegraph/core/src/runtimes/prisma/type_generation/snapshots/typegraph_core__runtimes__prisma__type_generation__where___test__where User.snap is excluded by !**/*.snap
📒 Files selected for processing (8)
  • .ghjk/lock.json (3 hunks)
  • ghjk.ts (1 hunks)
  • src/typegraph/core/src/runtimes/prisma/type_generation/input_type.rs (4 hunks)
  • src/typegraph/core/src/runtimes/prisma/type_generation/out_type.rs (3 hunks)
  • src/typegraph/core/src/runtimes/prisma/type_generation/where_.rs (4 hunks)
  • tests/runtimes/prisma/type_duplication.ts (1 hunks)
  • tests/runtimes/prisma/type_duplication_test.ts (1 hunks)
  • tools/list-duplicates.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • ghjk.ts
  • tests/runtimes/prisma/type_duplication_test.ts
  • src/typegraph/core/src/runtimes/prisma/type_generation/out_type.rs
  • src/typegraph/core/src/runtimes/prisma/type_generation/input_type.rs
  • .ghjk/lock.json
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: lint-compat (macos-14, aarch64-apple-darwin, false)
  • GitHub Check: lint-compat (macos-13, x86_64-apple-darwin, false)
  • GitHub Check: pre-commit

@Yohe-Am Yohe-Am requested a review from Natoandro January 11, 2025 05:31
@Yohe-Am Yohe-Am enabled auto-merge (squash) January 12, 2025 19:00
@Yohe-Am Yohe-Am requested a review from michael-0acf4 January 13, 2025 15:08
@luckasRanarison
Copy link
Contributor

My bad, sorry

@Yohe-Am Yohe-Am enabled auto-merge (squash) January 13, 2025 18:01
@Yohe-Am Yohe-Am disabled auto-merge January 13, 2025 18:44
@Yohe-Am Yohe-Am merged commit dd910d7 into main Jan 13, 2025
9 of 10 checks passed
@Yohe-Am Yohe-Am deleted the fix/where branch January 13, 2025 18:45
Yohe-Am added a commit that referenced this pull request Jan 15, 2025
- Fixes issues with type counts.

---

- [ ] The change comes with new or modified tests
- [ ] Hard-to-understand functions have explanatory comments
- [ ] End-user documentation is updated to reflect the change

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

- **New Features**
  - Enhanced duplicate detection mechanism for type graphs.
  - Improved type identification and relationship tracking.
- Added new root functions for dynamic entity management in type
duplication.

- **Refactor**
  - Updated model identifier handling in type generation.
- Modified key management for skip models from type-based to
string-based keys.
- Transitioned from static to dynamic entity definitions for
scalability.

- **Bug Fixes**
  - Streamlined type duplicate detection logic.
  - Improved error handling for unsupported type scenarios.
- Adjusted assertions for serialization size and type count limits in
tests.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants