Skip to content

Conversation

cvvergara
Copy link
Member

@cvvergara cvvergara commented Mar 6, 2025

Fixes #2762 .

Changes proposed in this pull request:

  • Documentation: Added new signature and fixed examples
  • SQL: added pgr_degree(text,boolean)
  • pgtap: added new tests for the new signature

@pgRouting/admins

Summary by CodeRabbit

  • New Features
    • Introduced an improved variant for computing node degrees that accepts a streamlined edge data input.
  • Documentation
    • Updated guides and examples to provide clearer insights into graph concepts, including dead ends, linear vertices, and isolated nodes.
  • Refactor
    • Simplified and optimized query logic to enhance performance and reliability in degree calculations.

@cvvergara cvvergara added this to the Release 3.8.0 milestone Mar 6, 2025
@cvvergara cvvergara requested a review from robe2 March 6, 2025 14:45
@cvvergara cvvergara self-assigned this Mar 6, 2025
Copy link
Contributor

coderabbitai bot commented Mar 6, 2025

Walkthrough

The changes introduce a revised signature for the pgr_degree function, now accepting only Edges SQL and a dryrun flag. Documentation in multiple files has been updated to reflect this new signature and clarify parameter usage. SQL queries are refactored to remove temporary tables in favor of a permanent vertices table, streamlining degree calculations. Additionally, test files now include enhanced version checks and detailed edge-case validations for the function. Overall, adjustments were made in documentation, SQL logic, and testing to ensure consistency and clear error handling.

Changes

File(s) Change Summary
NEWS.md, doc/metrics/pgr_degree.rst Updated release notes and documentation to reflect the new pgr_degree signature (Edges SQL only) and enhanced parameter descriptions with reorganized examples.
doc/src/pgRouting-concepts.rst Expanded explanation of dead ends and linear vertices with added details, visual aids, and contextual clarifications regarding graph theory concepts.
docqueries/metrics/degree.pg, docqueries/metrics/degree.result Refactored SQL queries by removing temporary tables, introducing a permanent vertices table, broadening selection criteria, and updating degree calculations.
pgtap/metrics/degree/edge_cases.pg, pgtap/metrics/degree/types_check.pg Enhanced tests with granular, version-specific logic and additional validations for edge cases, argument types, and proper error reporting.
sql/metrics/degree.sql, sql/sigs/pgrouting--3.8.sig Revised the pgr_degree function: removed the Vertex SQL parameter, adjusted error handling, restructured internal queries, and documented the new signature accepting only Edges SQL and a boolean.

Sequence Diagram(s)

sequenceDiagram
    participant U as User/Caller
    participant F as pgr_degree Function
    participant DB as Database (Edges & Vertices Tables)
    
    U->>F: Call pgr_degree(Edges SQL, dryrun flag)
    F->>DB: Validate required columns (id, source, target)
    DB-->>F: Return validation result
    F->>F: Build query using CTEs for degree calculation
    F->>DB: Execute aggregated query on edges data
    DB-->>F: Return node and degree results
    F->>U: Send final results
Loading

Possibly related PRs

  • Pumpup to 3.8.0 #2764: Focuses on version updates and documentation improvements for the pgr_degree function, aligning with the signature and docs changes here.
  • Issue 2770 improve internal functions #2771: Addresses error handling enhancements for the pgr_degree function, directly related to the modifications in the new implementation.

Suggested labels

Enhancement, functionality/official, Topology

Suggested reviewers

  • robe2

Poem

I’m a hopping rabbit, here with some cheer,
Leaping through code with a signature so clear.
Edges and flags now dance in our SQL play,
Clearing out temp tables in a mindful way.
With carrots of queries and tests built to stun,
My code-bound adventure has just begun!
🐰💻


🪧 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.
  • @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: 3

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9c8acfc and 21980c4.

📒 Files selected for processing (9)
  • NEWS.md (1 hunks)
  • doc/metrics/pgr_degree.rst (6 hunks)
  • doc/src/pgRouting-concepts.rst (3 hunks)
  • docqueries/metrics/degree.pg (1 hunks)
  • docqueries/metrics/degree.result (5 hunks)
  • pgtap/metrics/degree/edge_cases.pg (2 hunks)
  • pgtap/metrics/degree/types_check.pg (2 hunks)
  • sql/metrics/degree.sql (5 hunks)
  • sql/sigs/pgrouting--3.8.sig (1 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: cvvergara
PR: pgRouting/pgrouting#2771
File: doc/topology/pgr_degree.rst:28-35
Timestamp: 2025-02-27T23:08:14.497Z
Learning: In the pgRouting documentation, historical version notes should be retained to show the evolution of functions across different versions.
sql/sigs/pgrouting--3.8.sig (2)
Learnt from: cvvergara
PR: pgRouting/pgrouting#2764
File: sql/sigs/pgrouting--3.8.sig:125-136
Timestamp: 2025-02-27T16:33:56.959Z
Learning: The file sql/sigs/pgrouting--*.sig is automatically generated by a command and cannot be manually modified. Comments about naming conventions or other improvements should be directed at the source code that generates these signatures, not at the signature file itself.
Learnt from: cvvergara
PR: pgRouting/pgrouting#2764
File: sql/sigs/pgrouting--3.8.sig:274-275
Timestamp: 2025-02-27T16:34:57.518Z
Learning: The file `sql/sigs/pgrouting--3.8.sig` is auto-generated by a command and should not be modified manually.
sql/metrics/degree.sql (1)
Learnt from: cvvergara
PR: pgRouting/pgrouting#2771
File: doc/topology/pgr_degree.rst:28-35
Timestamp: 2025-02-27T23:08:14.497Z
Learning: In the pgRouting documentation, historical version notes should be retained to show the evolution of functions across different versions.
doc/metrics/pgr_degree.rst (1)
Learnt from: cvvergara
PR: pgRouting/pgrouting#2771
File: doc/topology/pgr_degree.rst:28-35
Timestamp: 2025-02-27T23:08:14.497Z
Learning: In the pgRouting documentation, historical version notes should be retained to show the evolution of functions across different versions.
⏰ Context from checks skipped due to timeout of 90000ms (15)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Ubuntu Boost (86)
  • GitHub Check: Ubuntu Boost (84)
  • GitHub Check: Ubuntu Boost (83)
  • GitHub Check: Ubuntu Boost (80)
  • GitHub Check: Ubuntu Boost (79)
  • GitHub Check: Ubuntu Boost (78)
  • GitHub Check: Ubuntu Boost (77)
  • GitHub Check: Ubuntu Boost (76)
  • GitHub Check: Ubuntu Boost (75)
  • GitHub Check: Ubuntu Boost (68)
  • GitHub Check: macos (macos-14)
  • GitHub Check: Ubuntu Boost (56)
  • GitHub Check: Ubuntu clang
  • GitHub Check: Check queries
🔇 Additional comments (38)
sql/sigs/pgrouting--3.8.sig (1)

104-104: New function signature added correctly.

The new function signature pgr_degree(text,boolean) has been properly added to support the functionality that uses only Edges SQL. This aligns with the PR objectives to add a new overload of the pgr_degree function.

NEWS.md (1)

29-29: Documentation updated properly for new function signature.

The NEWS.md file has been correctly updated to document the new signature for pgr_degree that utilizes only Edges SQL. This change ensures users are informed about the new functionality available in version 3.8.0.

pgtap/metrics/degree/edge_cases.pg (2)

23-23: Version-specific test plan properly updated.

The test plan has been appropriately adjusted to accommodate the additional tests for the new function signature when running on version 3.8.0 or higher.


117-143: Comprehensive tests added for new function signature.

Excellent test coverage for the new function signature that only takes edges_sql. The tests verify:

  1. Compatibility with previous signature results
  2. Proper validation of required columns (id, source, target)
  3. Appropriate error handling

This ensures the new functionality is robust and behaves as expected.

pgtap/metrics/degree/types_check.pg (2)

22-22: Version check enhancement looks good

The addition of the '3.8.0' version check logic improves test organization by handling different versions independently, with a proper progression from newer to older versions.


36-66: Well-structured conditional testing approach

The addition of the CASE statement with version-specific test collection is an excellent approach. The code properly:

  • Checks for function availability with different parameter signatures
  • Verifies function return types
  • Validates parameter names and types with detailed OID tests

The test logic clearly accommodates both the new pgr_degree(text, boolean) signature and preserves testing for the original signature.

doc/src/pgRouting-concepts.rst (2)

837-889: Improved documentation of dead ends with visual examples

The expanded documentation provides a much clearer explanation of what constitutes a dead end in graph theory as applied to pgRouting. The added visual representation and detailed explanation of context-dependent nature of dead ends significantly improves user understanding.

I particularly appreciate the visual example with node 4 and the explanation that whether it's a dead end depends on the application context.


911-953: Better explanation of linear vertices and contraction optimization

The enhanced documentation for linear vertices explains both the concept and practical application clearly. The addition of when linear vertices are correct (speed bumps, stop signals) and how contraction-family functions can optimize processing will help users make better decisions about their graph structures.

sql/metrics/degree.sql (4)

140-147: Clear, simplified function signature

The new function signature that accepts only Edges SQL aligns well with the PR objectives. Removing the requirement for a separate Vertices SQL parameter simplifies usage without losing functionality.


162-171: Improved error checking

The new error checking approach focuses on the essential columns needed for degree calculation (id, source, target). This is more intuitive than the previous approach that required checking for in_edges/out_edges.


183-193: Elegant vertices extraction from edges

This implementation elegantly extracts vertices information directly from the edges data using a UNION ALL approach to combine both source and target vertices. This eliminates the need for a separate vertices table while maintaining correct functionality.


189-197: Efficient degree calculation

The degree calculation is implemented efficiently by simply grouping the extracted nodes and counting occurrences. This direct approach is both easier to understand and likely more performant than the previous implementation that required joins between vertices and edges tables.

doc/metrics/pgr_degree.rst (7)

19-20: Clearer function description

The updated description provides a more precise explanation of what the function does, explicitly stating it returns "the count of edges incident to the vertex" which makes the purpose immediately clear.


32-32: Well-documented new signature

Properly documenting the new signature with only Edges SQL under the Version 3.8.0 section helps users understand when this functionality became available.


42-61: Thorough explanation of degree calculation

The expanded description provides excellent details about:

  • Formal definition of degree in graph theory
  • Special handling of loops (contributing 2 to vertex degree)
  • Treatment of isolated vertices
  • The dryrun functionality

This comprehensive explanation helps users understand both the concept and implementation details.


77-117: Well-structured examples for both signatures

The documentation now clearly separates examples for the Edges-only and Edges-and-Vertices signatures with proper admonitions and explanatory text. This organization makes it easy for users to find the relevant examples for their use case.


151-184: Clear documentation of required columns

The detailed tables for required columns in both signatures provide users with precise information about what their SQL queries need to include. The separation between the two signatures prevents confusion.


239-261: Helpful loop degree example

The addition of a specific example showing how loops contribute to vertex degree is valuable. The visual representation with GraphViz and examples using both signatures provide a complete understanding of this special case.


348-370: Useful sections on dead ends and linear vertices

The additional sections on finding dead ends and linear vertices, with references to the detailed explanations in pgRouting-concepts.rst, provide practical applications of the degree function. This helps users understand how to use the function for common graph analysis tasks.

docqueries/metrics/degree.result (10)

6-6: The function call aligns correctly with the new signature.
No issues are apparent here. This straightforward usage of pgr_degree with the Edges SQL (id, source, target) looks valid and complete.


31-49: Edges & Vertices separated inputs appear consistent with the updated API.
Here the first SQL provides only the id column from edges, and the second SQL relies on pgr_extractVertices for in/out edges. This separation aligns with the new pgr_degree overload that accepts distinct Edges SQL and Vertices SQL. The resulting degrees (e.g., node 2 → degree 1, node 4 → degree 1) seem correct.


56-60: Self-loop example correctly demonstrates a degree of 2.
Defining a single edge where source = target = 2 is a classic self-loop scenario. The reported degree of 2 for node 2 is correct.


63-70: Self-loop calculation works with explicit Vertices SQL.
Using pgr_extractVertices for the loop edge again confirms the function’s handling of self-loops. The degree of 2 is accurately reflected.


73-79: Filtering edges by ID successfully limits computed degrees.
Selecting only edges with IDs 1 and 2 demonstrates partial subgraph degree calculation. The results (nodes 10, 6, and 5) look valid.


81-90: Partial edge usage confirmed with a full vertices table.
Providing a restricted Edges SQL and the entire vertices table is another valid scenario. The results (three nodes) are consistent.


92-99: Recreating vertices is a clean approach.
Dropping and creating the vertices table via pgr_extractVertices ensures a fresh dataset for subsequent queries. This sequence is correct for demonstration purposes.


101-123: Reconfirming degree calculation with the newly created vertices table.
Using the same Edges SQL but the freshly populated vertices table again yields the correct degrees.


125-159: dryrun => true example clarifies the internal processing.
Printing the underlying queries without returning rows is expected when dryrun is enabled. This is a valuable illustration of how the function can be used to preview operations.


164-164: No query content to review.
This final comment block (-- q11) contains no new query or logic.

docqueries/metrics/degree.pg (9)

4-5: Great demonstration of the new pgr_degree signature!

This query properly demonstrates the new pgr_degree function signature that accepts only Edges SQL as described in the PR objectives. The ORDER BY node clause provides a predictable output order, which is good for documentation examples.


8-8: Simplified edges query selection

The query now selects only the id column from edges, which is consistent with the function's requirements. This simpler format is easier to understand.


12-12: Good edge case demonstration

This simple example with literal values is valuable for testing edge cases. It shows how the function behaves with a minimal input where source and target are the same node.


15-17: Consistent with previous example

This query properly aligns with the edge case demonstrated in q3, showing how to use the two-parameter version with the same data.


19-19: Useful filtered edges example

This example demonstrates how to use the new signature with a filtered subset of edges, which is a common use case.


25-25: Good practice to ensure clean creation

Using DROP TABLE IF EXISTS ensures the script can be run multiple times without errors.


27-29: Effective transition to permanent vertices table

This change from temporary tables to a permanent vertices table is a good improvement that aligns with the PR objectives. The table creation is clear and correctly extracts the necessary vertex information.


31-33: Good demonstration of using the permanent vertices table

This query effectively shows how to use the newly created permanent vertices table with the pgr_degree function.


35-37: Valuable dryrun parameter example

This query effectively demonstrates the dryrun parameter with filtered edges and the permanent vertices table, providing good coverage of the function's capabilities.

Comment on lines +209 to +216
COMMENT ON FUNCTION pgr_degree(TEXT, BOOLEAN)
IS 'pgr_degree
- PROPOSED
- Parameters
- Edges SQL with columns: id
- Documentation:
- ${PROJECT_DOC_LINK}/pgr_degree.html
';
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Updated function documentation comment

The COMMENT section has been properly updated for the new function signature. However, the parameter description still mentions only "id" column while the function now requires "id", "source", and "target" columns.

Consider updating the comment to match the actual required columns:

- - Edges SQL with columns: id
+ - Edges SQL with columns: id, source, target
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
COMMENT ON FUNCTION pgr_degree(TEXT, BOOLEAN)
IS 'pgr_degree
- PROPOSED
- Parameters
- Edges SQL with columns: id
- Documentation:
- ${PROJECT_DOC_LINK}/pgr_degree.html
';
COMMENT ON FUNCTION pgr_degree(TEXT, BOOLEAN)
IS 'pgr_degree
- PROPOSED
- Parameters
- Edges SQL with columns: id, source, target
- Documentation:
- ${PROJECT_DOC_LINK}/pgr_degree.html
';

@cvvergara cvvergara merged commit b20b80a into pgRouting:main Mar 6, 2025
26 checks passed
@cvvergara cvvergara deleted the issue-2762-add-overload-of-pgr_degree branch March 6, 2025 15:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add pgr_degree overload with edges SQL parameter
2 participants