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

feat: [#280] Add primary method #712

Merged
merged 11 commits into from
Nov 4, 2024
Merged

feat: [#280] Add primary method #712

merged 11 commits into from
Nov 4, 2024

Conversation

hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Nov 4, 2024

📑 Description

Summary by CodeRabbit

  • New Features

    • Introduced functionality to define primary keys for database tables.
    • Added a configuration structure for indexing to enhance database schema management.
  • Bug Fixes

    • Removed outdated command constant and added a new primary command constant for improved command handling.
  • Tests

    • Expanded testing coverage for primary key and index command functionalities within the Blueprint and Schema components.

✅ Checks

  • Added test cases for my code

@hwbrzzl hwbrzzl requested a review from a team as a code owner November 4, 2024 07:50
Copy link
Contributor

coderabbitai bot commented Nov 4, 2024

Walkthrough

The changes in this pull request enhance the database schema management functionality by introducing new methods and structures to the Blueprint and Grammar interfaces. A method for specifying primary keys, Primary(column ...string), is added to the Blueprint interface, alongside the CompilePrimary method in the Grammar interface for compiling primary key commands. Additionally, a new IndexConfig struct is introduced, and modifications are made to various related structs and methods to support these features. Tests are also added to ensure proper functionality.

Changes

File Change Summary
contracts/database/schema/blueprint.go - Added method Primary(column ...string) to Blueprint interface.
- Added struct IndexConfig with fields Algorithm and Name.
contracts/database/schema/grammar.go - Added method CompilePrimary(blueprint Blueprint, command *Command) string to Grammar interface.
contracts/database/schema/schema.go - Added field Columns []string to Command struct.
database/schema/blueprint.go - Added methods: Primary(columns ...string), createIndexName(ttype string, columns []string), and indexCommand(ttype string, columns []string, config ...schema.IndexConfig).
database/schema/blueprint_test.go - Added test methods: TestCreateIndexName() and TestIndexCommand() to BlueprintTestSuite.
database/schema/constants/constants.go - Removed constant CommandChange and added constant CommandPrimary.
database/schema/grammars/postgres.go - Added method CompilePrimary(blueprint schema.Blueprint, command *schema.Command) string to Postgres.
database/schema/schema_test.go - Added test method TestPrimary() to SchemaSuite.

Possibly related PRs

Suggested reviewers

  • devhaozi

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 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

codecov bot commented Nov 4, 2024

Codecov Report

Attention: Patch coverage is 92.59259% with 2 lines in your changes missing coverage. Please review.

Project coverage is 69.70%. Comparing base (1cc1f60) to head (257e0e8).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
database/schema/grammars/postgres.go 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #712      +/-   ##
==========================================
+ Coverage   69.66%   69.70%   +0.04%     
==========================================
  Files         197      197              
  Lines       15271    15298      +27     
==========================================
+ Hits        10638    10663      +25     
- Misses       4057     4059       +2     
  Partials      576      576              

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

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

🧹 Outside diff range and nitpick comments (10)
contracts/database/schema/blueprint.go (1)

36-39: Add documentation and consider type safety improvements.

While the struct is well-structured, consider these enhancements:

  1. Add documentation comments for the struct and its fields
  2. Consider using a custom type or constants for Algorithm to restrict valid values

Here's a suggested improvement:

+// IndexConfig holds configuration options for database indexes
 type IndexConfig struct {
+	// Algorithm specifies the index algorithm (e.g., "BTREE", "HASH")
 	Algorithm string
+	// Name specifies the custom name for the index
 	Name      string
 }

+// Common index algorithms
+const (
+	IndexAlgorithmBTree = "BTREE"
+	IndexAlgorithmHash  = "HASH"
+)
contracts/database/schema/grammar.go (1)

22-22: Consider enhancing the method documentation.

While the current comment follows the codebase style, consider adding more details about the expected format of the command and what the returned string represents (e.g., the SQL statement format).

-// CompilePrimary Compile a primary key command.
+// CompilePrimary Compile a primary key command.
+// The command's Columns field should contain the column names to be used in the primary key.
+// Returns the SQL statement for adding a primary key constraint.
contracts/database/schema/schema.go (1)

69-69: LGTM! Consider adding field documentation.

The addition of the Columns []string field to the Command struct is well-designed for supporting multiple column operations, particularly useful for composite primary keys. The implementation is clean and consistent with the existing structure.

Consider adding a comment to document the purpose of this field:

 type Command struct {
 	Algorithm  string
 	Column     ColumnDefinition
+	// Columns holds multiple column names for operations like primary keys
 	Columns    []string
 	From       string
database/schema/grammars/postgres.go (1)

61-63: Add column name escaping for SQL safety.

While the basic implementation is correct, the column names should be properly escaped to handle special characters and reserved words in PostgreSQL.

Consider using the existing EscapeNames method:

func (r *Postgres) CompilePrimary(blueprint schema.Blueprint, command *schema.Command) string {
-	return fmt.Sprintf("alter table %s add primary key (%s)", blueprint.GetTableName(), strings.Join(command.Columns, ","))
+	return fmt.Sprintf("alter table %s add primary key (%s)", blueprint.GetTableName(), strings.Join(r.EscapeNames(command.Columns), ","))
}

This change ensures SQL safety when column names contain spaces, special characters, or match PostgreSQL reserved words.

database/schema/blueprint.go (1)

191-197: Consider defining constants for special characters.

The createIndexName method handles special character replacement well, but could benefit from defining constants for the replaceable characters (- and .) to improve maintainability and documentation.

+ const (
+   indexNameHyphenReplacement = "_"
+   indexNameDotReplacement   = "_"
+ )

func (r *Blueprint) createIndexName(ttype string, columns []string) string {
	table := r.GetTableName()
	index := strings.ToLower(table + "_" + strings.Join(columns, "_") + "_" + ttype)
-	index = strings.ReplaceAll(index, "-", "_")
+	index = strings.ReplaceAll(index, "-", indexNameHyphenReplacement)

-	return strings.ReplaceAll(index, ".", "_")
+	return strings.ReplaceAll(index, ".", indexNameDotReplacement)
}
database/schema/schema_test.go (3)

90-107: Enhance test coverage for primary key functionality.

While the test follows the suite's pattern, consider adding these test cases for robustness:

  1. Negative test cases (e.g., non-existent columns)
  2. Single column primary key
  3. Verification of the actual primary key constraint

Here's a suggested enhancement:

 func (s *SchemaSuite) TestPrimary() {
 	for driver, testQuery := range s.driverToTestQuery {
 		s.Run(driver.String(), func() {
 			schema := GetTestSchema(testQuery, s.driverToTestQuery)
-			table := "primaries"
+			
+			// Test composite primary key
+			tableComposite := "primaries_composite"
+			s.NoError(schema.Create(tableComposite, func(table contractsschema.Blueprint) {
+				table.String("name")
+				table.String("age")
+				table.Primary("name", "age")
+			}))
+			s.Require().True(schema.HasTable(tableComposite))
 
-			s.NoError(schema.Create(table, func(table contractsschema.Blueprint) {
+			// Test single column primary key
+			tableSingle := "primaries_single"
+			s.NoError(schema.Create(tableSingle, func(table contractsschema.Blueprint) {
 				table.String("name")
-				table.String("age")
-				table.Primary("name", "age")
+				table.Primary("name")
 			}))
+			s.Require().True(schema.HasTable(tableSingle))
 
-			s.Require().True(schema.HasTable(table))
-			// TODO Open below when implementing index methods
-			//s.Require().True(schema.HasIndex(table, "primaries_pkey"))
+			// Test invalid column
+			tableInvalid := "primaries_invalid"
+			err := schema.Create(tableInvalid, func(table contractsschema.Blueprint) {
+				table.String("name")
+				table.Primary("invalid_column")
+			})
+			s.Error(err)
 		})
 	}
 }

96-101: Maintain consistent error handling pattern.

The error handling could be more consistent with other tests in the suite. Consider using s.Require().NoError() for critical setup steps.

-			s.NoError(schema.Create(table, func(table contractsschema.Blueprint) {
+			s.Require().NoError(schema.Create(table, func(table contractsschema.Blueprint) {
 				table.String("name")
 				table.String("age")
 				table.Primary("name", "age")
 			}))

103-104: Enhance TODO documentation with specific requirements.

The TODO comment could be more descriptive about the dependencies and requirements for implementing index methods.

-			// TODO Open below when implementing index methods
+			// TODO: Implement index verification after adding HasIndex method to the Schema interface
+			// Dependencies:
+			// 1. Implement HasIndex method in Schema interface
+			// 2. Add index information retrieval in the Grammar implementation
+			// Related issue: #280
 			//s.Require().True(schema.HasIndex(table, "primaries_pkey"))
database/schema/blueprint_test.go (2)

139-142: Consider adding more test cases for edge scenarios.

The test correctly verifies the basic index name generation. Consider adding test cases for:

  • Empty column list
  • Column names with other special characters
  • Maximum length handling
 func (s *BlueprintTestSuite) TestCreateIndexName() {
 	name := s.blueprint.createIndexName("index", []string{"id", "name-1", "name.2"})
 	s.Equal("goravel_users_id_name_1_name_2_index", name)
+
+	// Test empty column list
+	name = s.blueprint.createIndexName("index", []string{})
+	s.Equal("goravel_users_index", name)
+
+	// Test special characters
+	name = s.blueprint.createIndexName("index", []string{"user@name", "email#address"})
+	s.Equal("goravel_users_user_name_email_address_index", name)
 }

167-185: Consider adding test cases for error scenarios.

The test effectively covers the happy path for both basic and configured index creation. Consider adding test cases for:

  • Invalid column names
  • Empty column list
  • Other IndexConfig fields (if any)
 func (s *BlueprintTestSuite) TestIndexCommand() {
 	s.blueprint.indexCommand("index", []string{"id", "name"})
 	s.Contains(s.blueprint.commands, &schema.Command{
 		Columns: []string{"id", "name"},
 		Name:    "index",
 		Index:   "goravel_users_id_name_index",
 	})

 	s.blueprint.indexCommand("index", []string{"id", "name"}, schema.IndexConfig{
 		Algorithm: "custom_algorithm",
 		Name:      "custom_name",
 	})
 	s.Contains(s.blueprint.commands, &schema.Command{
 		Algorithm: "custom_algorithm",
 		Columns:   []string{"id", "name"},
 		Name:      "index",
 		Index:     "custom_name",
 	})
+
+	// Test empty column list
+	s.blueprint.indexCommand("index", []string{})
+	s.Contains(s.blueprint.commands, &schema.Command{
+		Columns: []string{},
+		Name:    "index",
+		Index:   "goravel_users_index",
+	})
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1cc1f60 and 257e0e8.

⛔ Files ignored due to path filters (2)
  • mocks/database/schema/Blueprint.go is excluded by !mocks/**
  • mocks/database/schema/Grammar.go is excluded by !mocks/**
📒 Files selected for processing (8)
  • contracts/database/schema/blueprint.go (2 hunks)
  • contracts/database/schema/grammar.go (1 hunks)
  • contracts/database/schema/schema.go (1 hunks)
  • database/schema/blueprint.go (4 hunks)
  • database/schema/blueprint_test.go (2 hunks)
  • database/schema/constants/constants.go (1 hunks)
  • database/schema/grammars/postgres.go (1 hunks)
  • database/schema/schema_test.go (1 hunks)
🔇 Additional comments (8)
database/schema/constants/constants.go (1)

8-8: LGTM! The new constant follows established patterns.

The addition of CommandPrimary is well-structured:

  • Follows the command naming convention
  • Maintains alphabetical ordering
  • Uses appropriate database terminology

Let's verify the removal of CommandChange constant and its usage:

contracts/database/schema/blueprint.go (1)

22-23: LGTM! Verify implementations across concrete types.

The Primary method signature is well-designed, allowing for both single and composite primary keys through variadic parameters.

Let's verify that all concrete types implementing the Blueprint interface have added this method:

✅ Verification successful

Let me try a different search strategy to find Blueprint implementations and Primary method.


Based on the search results, I can now generate the final response:

Primary method is properly implemented in concrete Blueprint type

The verification shows:

  • The concrete implementation exists in database/schema/blueprint.go:110
  • Mock implementation exists for testing in mocks/database/schema/Blueprint.go
  • Supporting grammar implementation for Postgres in database/schema/grammars/postgres.go:61

The method is consistently implemented across the codebase with proper test coverage and database-specific handling.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all types that implement Blueprint interface and verify Primary method implementation

# Find all .go files that might contain Blueprint implementations
echo "Searching for potential Blueprint implementations..."
rg -l "struct.*Blueprint" 

# Find the Primary method implementations
echo -e "\nSearching for Primary method implementations..."
ast-grep --pattern 'func ($x *$type) Primary($params) {
  $$$
}'

Length of output: 320


Script:

#!/bin/bash
# First find the Blueprint interface definition to understand the package
echo "Finding Blueprint interface definition..."
rg -p "type Blueprint interface" -A 5

# Search for files importing the package containing Blueprint
echo -e "\nSearching for files importing Blueprint..."
rg -l "\".*database/schema\""

# Look for Primary method implementations
echo -e "\nSearching for Primary method implementations..."
rg -p "func.*Primary.*string"

Length of output: 2734

contracts/database/schema/grammar.go (1)

22-23: LGTM! Verify implementations across database drivers.

The new CompilePrimary method is a logical addition to the Grammar interface and follows the established pattern of compilation methods.

Let's verify that all database drivers implement this new interface method:

database/schema/grammars/postgres.go (1)

61-63: Verify handling of edge cases.

Consider adding validation for:

  1. Empty columns array to prevent invalid SQL
  2. Existing primary key constraints to avoid errors

Let's check how other implementations handle these cases:

database/schema/blueprint.go (4)

4-5: LGTM!

The addition of the strings package import is appropriate for the new string manipulation functionality.


110-112: LGTM!

The Primary method implementation is clean and follows the single responsibility principle by delegating to the indexCommand method.


146-147: LGTM!

The addition of the primary key compilation case follows the existing pattern and integrates well with the grammar interface.


199-215: LGTM!

The indexCommand method is well-structured with:

  • Clear separation of concerns
  • Proper handling of optional configuration
  • Consistent command structure

Copy link
Member

@kkumar-gcc kkumar-gcc left a comment

Choose a reason for hiding this comment

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

LGTM

@hwbrzzl hwbrzzl merged commit 534a84b into master Nov 4, 2024
12 checks passed
@hwbrzzl hwbrzzl deleted the bowen/#280-16 branch November 4, 2024 08:30
@coderabbitai coderabbitai bot mentioned this pull request Nov 17, 2024
1 task
@coderabbitai coderabbitai bot mentioned this pull request Dec 5, 2024
1 task
@coderabbitai coderabbitai bot mentioned this pull request Dec 25, 2024
1 task
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.

2 participants