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: sqlserver driver supports setting schema #786

Merged
merged 3 commits into from
Dec 25, 2024

Conversation

hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Dec 24, 2024

📑 Description

Summary by CodeRabbit

  • New Features

    • Introduced new test functions for SQL Server schema management.
    • Added a new Schema type to represent schemas in the database.
    • Enhanced schema management functionality in testing utilities.
  • Bug Fixes

    • Improved handling of schema-qualified table names in the HasTable method.
  • Documentation

    • Updated test function names for clarity and consistency.
  • Tests

    • Expanded test coverage for schema management across PostgreSQL and SQL Server.
    • Renamed existing test functions for better clarity.

✅ Checks

  • Added test cases for my code

Copy link
Contributor

coderabbitai bot commented Dec 24, 2024

Walkthrough

The pull request introduces enhancements to schema management across various database systems, particularly focusing on SQL Server. Key changes include the addition of new test functions for SQL Server and PostgreSQL, the refinement of existing test methods, and improvements to schema-related functionality. New types and methods are introduced to support these changes, ensuring consistent behavior in handling schemas and migrations across different database types.

Changes

File Change Summary
database/gorm/query_test.go - Renamed TestSchema to TestPostgresSchema
- Added TestSqlserverSchema test function
database/gorm/test_models.go - Added new Schema struct
- Implemented TableName() method for Schema
database/gorm/test_utils.go - Added TestTableSchema constant
- Added schema() method to testTables
- Modified NewTestQueryWithSchema function
database/migration/default_migrator_test.go - Renamed TestDefaultMigratorWithWithSchema to TestDefaultMigratorWithPostgresSchema
- Added TestDefaultMigratorWithSqlserverSchema
- Added TestMigrationWithSqlserverSchema type
database/schema/grammars/wrap.go - Modified Table method logic for handling table names with schemas
database/schema/grammars/wrap_test.go - Consolidated and renamed multiple test methods for clarity
database/schema/schema.go - Enhanced HasTable method to handle schema-qualified table names
database/schema/schema_test.go - Renamed TestSpecificSchema to TestPostgresSchema
- Added TestSqlserverSchema test function

Sequence Diagram

sequenceDiagram
    participant Client
    participant SchemaManager
    participant Database
    
    Client->>SchemaManager: Create Schema
    SchemaManager->>Database: Verify Schema Existence
    Database-->>SchemaManager: Schema Check Result
    SchemaManager->>Database: Create Tables in Schema
    Database-->>SchemaManager: Table Creation Confirmation
    SchemaManager-->>Client: Schema and Tables Ready
Loading

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

codecov bot commented Dec 24, 2024

Codecov Report

Attention: Patch coverage is 55.55556% with 36 lines in your changes missing coverage. Please review.

Project coverage is 69.68%. Comparing base (c409ce8) to head (8b4943d).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
database/gorm/test_utils.go 47.82% 35 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #786      +/-   ##
==========================================
- Coverage   69.72%   69.68%   -0.05%     
==========================================
  Files         215      215              
  Lines       18456    18523      +67     
==========================================
+ Hits        12869    12907      +38     
- Misses       4882     4911      +29     
  Partials      705      705              

☔ 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: 4

🧹 Nitpick comments (6)
database/schema/grammars/wrap_test.go (3)

24-30: Unify Aliased and Non-Aliased Column Logic Cleanly
These unified test assertions are clear and comprehensive. However, consider using sub-tests (e.g., t.Run("alias", ...), t.Run("no_alias", ...)) for improved organization and clarity.


39-45: Good Consolidation of Quote Tests
Combining non-empty and empty quote checks into a single method is efficient, but consider clarifying function-level comments to distinguish these scenarios if the test logic grows more complex in the future.


63-73: Extended Table Wrapping for Schema and Alias
The test covers multiple scenarios (alias, schema, no alias) under a single function. This approach is succinct. If more table-specific scenarios are added, splitting into sub-tests may further improve maintainability.

database/schema/schema.go (1)

221-227: Schema-Aware Table Detection
The updated HasTable method now correctly parses schema-qualified table names by splitting on the dot (if present). This is a sensible enhancement for multi-schema support.

Consider logging or validating the extracted schema name if future usage might require more robust error handling (e.g., blank or unexpected schema substrings).

Also applies to: 238-240

database/gorm/test_utils.go (1)

1264-1277: MySQL schema creation
Defining a table called goravel.schemas can be confusing in MySQL. MySQL doesn’t typically use “schema.table” naming. Verify if you actually need a “.” in the table name for MySQL.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 1266-1276: database/gorm/test_utils.go#L1266-L1276
Added lines #L1266 - L1276 were not covered by tests

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

92-92: Split and wrap multi-part table names
If the table string contains a dot, the code now separates and wraps the left side and the prefix-plus-right side. For more complex scenarios (multiple dots), consider validating or handling additional segments.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6b30537 and 5dcc21d.

📒 Files selected for processing (8)
  • database/gorm/query_test.go (2 hunks)
  • database/gorm/test_models.go (1 hunks)
  • database/gorm/test_utils.go (6 hunks)
  • database/migration/default_migrator_test.go (5 hunks)
  • database/schema/grammars/wrap.go (1 hunks)
  • database/schema/grammars/wrap_test.go (2 hunks)
  • database/schema/schema.go (3 hunks)
  • database/schema/schema_test.go (3 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
database/gorm/test_utils.go

[warning] 233-233: database/gorm/test_utils.go#L233
Added line #L233 was not covered by tests


[warning] 584-588: database/gorm/test_utils.go#L584-L588
Added lines #L584 - L588 were not covered by tests


[warning] 1266-1276: database/gorm/test_utils.go#L1266-L1276
Added lines #L1266 - L1276 were not covered by tests


[warning] 1278-1285: database/gorm/test_utils.go#L1278-L1285
Added lines #L1278 - L1285 were not covered by tests


[warning] 1287-1294: database/gorm/test_utils.go#L1287-L1294
Added lines #L1287 - L1294 were not covered by tests


[warning] 1306-1307: database/gorm/test_utils.go#L1306-L1307
Added lines #L1306 - L1307 were not covered by tests

🔇 Additional comments (26)
database/schema/grammars/wrap_test.go (2)

34-34: Columnize Implementation Looks Good
This change is straightforward and aligns well with the unified test structure.


77-88: Value Wrapping Enhanced
Combining asterisk, non-asterisk, and MySQL driver checks is helpful. The commentary block is nicely separated. Everything looks good.

database/schema/schema.go (1)

6-6: New Import for Handling Schema Logic
Importing strings is necessary here for detecting schema dots. This is adequately justified by the changes below.

database/gorm/test_models.go (1)

423-431: New Schema Type Definition
Adding the Schema struct and TableName method is a straightforward way to group schema data under a standardized table. This fosters better organization for test or production use.

database/migration/default_migrator_test.go (4)

165-167: Renamed Postgres Schema Test
Renaming the test function improves clarity on its specific database target. Looks good.


185-187: Explicit Rollback Verification
Verifying that the users table no longer exists after rollback is essential for robust tests. Good inclusion.


189-210: Added SQL Server Schema Test
Introducing TestDefaultMigratorWithSqlserverSchema significantly improves coverage for SQL Server support. Ensuring the table name is prefixed with goravel. and validating rollback further ensures correctness.


966-987: Dedicated SQL Server Migration and Rollback
The TestMigrationWithSqlserverSchema structure is clean and clearly demonstrates the creation and removal of [schema].[table]. Validations appear comprehensive.

database/gorm/test_utils.go (13)

31-31: Add new enum constant
The addition of TestTableSchema is clear and aligns with the new schema table logic.


219-219: Check driver configuration call
Switching to mockDriver.Common() may remove prefix/singular logic. Ensure that this is intentional and doesn't introduce regressions for schema usage.


229-229: Initialization looks good
Assigning query is standard practice. This snippet is straightforward.


236-239: Return early for SQL Server
Skipping WithSchema for SQL Server is consistent with the approach of building the schema connection differently. The fallback logic is acceptable.


240-253: Build new query with schema
Re-initializing mocks and calling WithSchema is a solid approach for applying the schema logic to Postgres (and other drivers that support it).


260-260: Avoid creating TestTableSchema by default
Skipping the schema table unless explicitly requested helps prevent extraneous table creation in tests.


584-588: User-provided schema in WithSchema
Allowing a custom schema is good, but the fallback "public" is questionable for SQL Server. Consider clarifying the correct default for that driver.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 584-588: database/gorm/test_utils.go#L584-L588
Added lines #L584 - L588 were not covered by tests


634-634: Map TestTableSchema to schema creation
Including the new TestTableSchema logic in All() ensures that schema creation is fully supported in tests.


1278-1286: Postgres table name
goravel.schemas in Postgres might conflict with the notion of “schema.tablename.” If the intent is to store everything in the default schema while referencing “schemas” as a table name, this is okay, but be aware of potential confusion.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 1278-1285: database/gorm/test_utils.go#L1278-L1285
Added lines #L1278 - L1285 were not covered by tests


1287-1295: SQLite table creation
The structure for a new goravel.schemas table is consistent with SQLite’s schema. Nothing obviously problematic here.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 1287-1294: database/gorm/test_utils.go#L1287-L1294
Added lines #L1287 - L1294 were not covered by tests


1296-1305: SQL Server table creation
Similarly, goravel.schemas is fine for naming, but ensure naming does not conflict with established patterns.


1306-1307: Default case
Returning an empty string is consistent with not creating a table on unsupported drivers.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 1306-1307: database/gorm/test_utils.go#L1306-L1307
Added lines #L1306 - L1307 were not covered by tests


1309-1309: Function closing bracket
No issue with the function’s closure.

database/schema/schema_test.go (3)

4-4: Added import for “fmt”
This likely supports formatted output in new tests. That’s appropriate.


Line range hint 2335-2361: Renamed TestSpecificSchema → TestPostgresSchema
This rename clarifies the target driver. The new test focuses specifically on Postgres, which increases clarity.


2363-2387: New TestSqlserverSchema function
Introducing a dedicated test for SQL Server schemas significantly improves coverage for that driver. Good addition.

database/gorm/query_test.go (2)

3941-3941: Added PostgreSQL schema test
Using NewTestQueryWithSchema for the “goravel” schema is an effective way to confirm schema-based logic in Postgres.


3961-3979: Added SQL Server schema test
This test parallels the Postgres test and ensures that schema creation and lookups work as expected on SQL Server. Good for cross-database consistency.

database/gorm/test_utils.go Outdated Show resolved Hide resolved
database/gorm/test_utils.go Outdated Show resolved Hide resolved
database/gorm/test_utils.go Outdated Show resolved Hide resolved
database/gorm/test_utils.go Outdated Show resolved Hide resolved
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 (2)
database/gorm/test_utils.go (2)

236-238: Document SQL Server schema behavior.

The early return for SQL Server needs documentation explaining why the schema configuration is skipped, as this behavior differs from PostgreSQL.

Add a comment explaining the SQL Server schema behavior:

 if docker.Driver() == contractsdatabase.DriverSqlserver {
+  // SQL Server schemas are handled differently from PostgreSQL
+  // as they don't require explicit search_path configuration
   return testQuery
 }

1264-1309: Review hardcoded schema name in table definitions.

The schema table definitions use a hardcoded "goravel" schema prefix. Consider making this configurable to support different test scenarios.

Consider parameterizing the schema name:

-CREATE TABLE goravel.schemas (
+CREATE TABLE %s.schemas (

Then update the schema() method to accept and use the schema parameter:

-func (r *testTables) schema() string {
+func (r *testTables) schema(schemaName string) string {
   switch r.driver {
   case contractsdatabase.DriverMysql:
-    return `CREATE TABLE goravel.schemas ...`
+    return fmt.Sprintf(`CREATE TABLE %s.schemas ...`, schemaName)
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 1266-1276: database/gorm/test_utils.go#L1266-L1276
Added lines #L1266 - L1276 were not covered by tests


[warning] 1278-1285: database/gorm/test_utils.go#L1278-L1285
Added lines #L1278 - L1285 were not covered by tests


[warning] 1287-1294: database/gorm/test_utils.go#L1287-L1294
Added lines #L1287 - L1294 were not covered by tests


[warning] 1306-1307: database/gorm/test_utils.go#L1306-L1307
Added lines #L1306 - L1307 were not covered by tests

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5dcc21d and 7202c41.

📒 Files selected for processing (1)
  • database/gorm/test_utils.go (6 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
database/gorm/test_utils.go

[warning] 233-233: database/gorm/test_utils.go#L233
Added line #L233 was not covered by tests


[warning] 584-588: database/gorm/test_utils.go#L584-L588
Added lines #L584 - L588 were not covered by tests


[warning] 1266-1276: database/gorm/test_utils.go#L1266-L1276
Added lines #L1266 - L1276 were not covered by tests


[warning] 1278-1285: database/gorm/test_utils.go#L1278-L1285
Added lines #L1278 - L1285 were not covered by tests


[warning] 1287-1294: database/gorm/test_utils.go#L1287-L1294
Added lines #L1287 - L1294 were not covered by tests


[warning] 1306-1307: database/gorm/test_utils.go#L1306-L1307
Added lines #L1306 - L1307 were not covered by tests

🔇 Additional comments (3)
database/gorm/test_utils.go (3)

31-31: LGTM: New test table constant follows convention.

The addition of TestTableSchema constant follows the existing enumeration pattern.


232-234: Schema creation uses proper identifier quoting.

The schema creation SQL properly quotes the schema name to prevent SQL injection and handle special characters.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 233-233: database/gorm/test_utils.go#L233
Added line #L233 was not covered by tests


553-554: LGTM: SQL Server uses correct default schema.

The mock driver correctly uses "dbo" as the default schema for SQL Server, which follows SQL Server conventions.

Also applies to: 569-570, 577-578

}

mockDriver.WithSchema(schema)
if _, err := query.Exec(fmt.Sprintf(`CREATE SCHEMA "%s"`, schema)); err != nil {
panic(fmt.Sprintf("create schema %s failed: %v", schema, err))
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Test coverage for schema operations is adequate, but error scenarios need attention

Based on the verification results, I found that:

  1. Schema creation and basic operations are well-tested for both PostgreSQL and SQL Server in:

    • database/schema/schema_test.go
    • database/gorm/query_test.go
  2. However, error scenarios are not adequately covered:

    • The panic in NewTestQueryWithSchema for unsupported drivers is tested implicitly
    • Schema creation error handling (line 233) lacks explicit test coverage
    • SQL Server schema configuration (lines 584-588) has basic tests but no error scenarios
    • Schema table definitions (lines 1266-1307) have functional tests but lack edge cases

Recommendations:

  • Add test cases for schema creation failures
  • Include error scenarios for SQL Server schema operations
  • Add edge cases for schema table definitions with invalid inputs
🔗 Analysis chain

Improve test coverage for schema operations.

Several critical code paths lack test coverage:

  1. Schema creation error handling
  2. SQL Server schema configuration
  3. Schema table definitions for different databases

Let's verify the existing test coverage:

Would you like me to help create additional test cases to cover these scenarios?

Also applies to: 584-588, 1266-1307


Let's gather more information about the test coverage for schema operations.


Let's check the actual test implementations to verify the coverage of error scenarios.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for existing schema-related tests
# Look for test files that might contain schema-related tests
rg -l "TestSchema|test.*Schema|schema.*Test" --type go

Length of output: 349


Script:

#!/bin/bash
# Check for test cases related to schema creation and error handling
rg "func.*Test.*Schema.*" --type go -A 5

# Check for specific schema creation error tests
rg "TestSchema.*Error|TestCreate.*Schema.*Error" --type go -A 5

# Look for SQL Server schema configuration tests
rg "TestWithSchema|TestSQLServer.*Schema" --type go -A 5

# Check schema table definition tests
rg "TestSchema.*Table|TestCreateTable" --type go -A 5

Length of output: 6846


Script:

#!/bin/bash
# Check the content of schema-related tests
rg "TestPostgresSchema|TestSqlserverSchema" --type go -B 2 -A 20

# Look for panic handling in tests
rg "panic.*schema" --type go -B 2 -A 2

# Check schema creation error handling in tests
rg "create.*schema.*error|schema.*create.*error" --type go -i -B 2 -A 2

Length of output: 7973

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 233-233: database/gorm/test_utils.go#L233
Added line #L233 was not covered by tests

@hwbrzzl hwbrzzl merged commit 8c0a04a into master Dec 25, 2024
10 of 12 checks passed
@hwbrzzl hwbrzzl deleted the bowen/sqlserver-schema branch December 25, 2024 02:52
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.

1 participant