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(server): support float fields #1263

Merged
merged 9 commits into from
Oct 23, 2024
Merged

Conversation

yk-eukarya
Copy link
Contributor

@yk-eukarya yk-eukarya commented Oct 16, 2024

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling for unauthorized access and invalid requests.
  • Tests
    • Expanded integration tests for field creation, retrieval, updating, and deletion.
    • Enhanced assertions to verify response structures and metadata consistency.

@yk-eukarya yk-eukarya self-assigned this Oct 16, 2024
Copy link
Contributor

coderabbitai bot commented Oct 16, 2024

Walkthrough

The pull request introduces enhancements to the integration tests for schema and field APIs in the server/e2e/integration_schema_test.go file. It adds new test cases for field creation, retrieval, updating, and deletion, while refining assertions on responses. Improvements include additional error handling scenarios and ensuring consistency in response structures across different field types.

Changes

File Change Summary
server/e2e/integration_schema_test.go - Added tests for field creation with various types (text, bool, number).
- Enhanced retrieval tests to verify field associations and response metadata.
- Expanded update tests to check correct value and type updates.
- Improved deletion tests to confirm successful deletion and error handling for non-existent fields.
- Incorporated additional error handling scenarios for unauthorized access and bad requests.
- Verified consistency in response structure across different field types.

Possibly related PRs

🐇 In the garden where fields grow,
New tests sprout, all in a row.
Creation, update, and deletion too,
Each case checked, as rabbits do!
With consistent responses, we hop with glee,
Robust tests for all, as happy as can be! 🌼


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

netlify bot commented Oct 16, 2024

Deploy Preview for reearth-cms canceled.

Name Link
🔨 Latest commit d5a10fe
🔍 Latest deploy log https://app.netlify.com/sites/reearth-cms/deploys/67189dbd8b90f70008628a6d

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

🧹 Outside diff range and nitpick comments (1)
server/internal/adapter/gql/gqlmodel/convert_schema.go (1)

559-580: LGTM! Consider a minor improvement for consistency.

The implementation of the SchemaFieldTypeNumber case looks correct and consistent with the existing pattern. Good job on maintaining the structure and error handling similar to other cases.

For consistency with the SchemaFieldTypeInteger case, consider renaming the variable tpi to tpn (type property number) in the SchemaFieldTypeNumber case. This small change would make the variable naming more consistent across different field types.

-		tpi, err2 := schema.NewNumber(min, max)
-		if err2 != nil {
-			err = err2
-		}
-		tpRes = tpi.TypeProperty()
+		tpn, err2 := schema.NewNumber(min, max)
+		if err2 != nil {
+			err = err2
+		}
+		tpRes = tpn.TypeProperty()
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between aec7b82 and b4d71c5.

📒 Files selected for processing (12)
  • server/e2e/gql_field_test.go (4 hunks)
  • server/e2e/gql_item_test.go (3 hunks)
  • server/e2e/integration_item_test.go (3 hunks)
  • server/internal/adapter/gql/generated.go (17 hunks)
  • server/internal/adapter/gql/gqlmodel/convert_schema.go (1 hunks)
  • server/internal/adapter/gql/gqlmodel/models_gen.go (5 hunks)
  • server/internal/adapter/integration/item_import.go (2 hunks)
  • server/internal/adapter/integration/schema.go (1 hunks)
  • server/internal/adapter/integration/server.gen.go (1 hunks)
  • server/pkg/integrationapi/types.gen.go (1 hunks)
  • server/schemas/field.graphql (5 hunks)
  • server/schemas/integration.yml (1 hunks)
🧰 Additional context used
🔇 Additional comments (35)
server/schemas/field.graphql (6)

12-12: LGTM: Addition of Number type is appropriate.

The inclusion of Number in the SchemaFieldType enum is a logical extension of the existing types. It provides support for decimal or floating-point numbers, which is distinct from the Integer type. This addition enhances the flexibility of the schema system.


85-85: LGTM: SchemaFieldNumber correctly added to union type.

The addition of SchemaFieldNumber to the SchemaFieldTypeProperty union is consistent with the existing pattern and necessary for the new number type to be fully integrated into the schema system. This change ensures that SchemaFieldNumber can be used wherever SchemaFieldTypeProperty is expected.


243-247: LGTM: SchemaFieldNumberInput is well-defined.

The SchemaFieldNumberInput input type is correctly structured, mirroring the SchemaFieldNumber type. It follows the established pattern for input types in the schema and uses appropriate types for each field. This consistency ensures that the new number field type can be easily integrated into existing mutation operations.


297-297: LGTM: number field correctly added to SchemaFieldTypePropertyInput.

The addition of the number field to SchemaFieldTypePropertyInput is correct and necessary. It allows the new number field type to be used in input operations, maintaining consistency with other field types. The @onlyOne directive on the input type ensures that only one field type can be specified at a time, which is appropriate for this schema design.


147-151: LGTM with a note on type safety.

The SchemaFieldNumber type is well-structured and consistent with other field types, particularly SchemaFieldInteger. The use of Float for min and max is appropriate for handling decimal values.

However, please ensure that there's proper validation for the defaultValue of type Any. While this provides flexibility, it could potentially lead to type inconsistencies if not carefully managed. Consider implementing runtime checks or a more specific type if possible.

To verify the handling of defaultValue, please run the following script:


Line range hint 1-365: Summary: Comprehensive and consistent implementation of Number field type.

The changes in this file successfully introduce support for a new Number field type across the schema. The implementation is thorough, updating all necessary parts of the schema including the SchemaFieldType enum, SchemaFieldTypeProperty union, and corresponding type and input type definitions. The changes follow established patterns in the existing schema, ensuring consistency and ease of integration.

As a final step, it would be beneficial to verify that all parts of the system that interact with schema fields (e.g., resolvers, validators, UI components) have been updated to handle the new Number type correctly.

To perform a final verification, please run the following script:

This will help ensure that the new Number type is properly integrated throughout the system.

server/internal/adapter/integration/schema.go (2)

395-397: LGTM! Enhancement to support number fields.

The addition of the ValueTypeNumber case in the FromSchemaTypeProperty function is a valuable enhancement. It allows for the creation of number fields in the schema, which increases the flexibility of the schema definition process. The implementation is consistent with other numeric types and appears to be correct.


395-397: Verify the impact of adding ValueTypeNumber support.

The addition of ValueTypeNumber support in the FromSchemaTypeProperty function is a significant enhancement. To ensure a smooth integration, please consider the following:

  1. Update any parts of the codebase that interact with schema fields to handle the new number type appropriately.
  2. Verify that data validation, storage, and retrieval processes can accommodate number fields.
  3. Ensure that user interfaces and API endpoints working with schema definitions support the new number type.

To assist with this verification, we can run the following script to identify potential areas that might need updates:

This script will help identify areas of the codebase that might need to be updated to fully support the new ValueTypeNumber. Would you like me to provide more detailed analysis based on the script results?

✅ Verification successful

To further investigate the impact of adding ValueTypeNumber support, we need to search for its specific usage and related number field handling in the codebase. Let's run the following script:

This script will help us identify if ValueTypeNumber is already being used, how number fields are currently handled, and if there are any switch statements that might need to be updated to include the new type.


To gather the final pieces of information needed for our analysis, let's run the following script:

This script will provide more context around ValueTypeNumber usage, help us find type-related logic, and show how FieldNumber is used in the codebase.


The addition of ValueTypeNumber support in the FromSchemaTypeProperty function appears to be properly implemented and integrated into the existing system. After analyzing the codebase, we can conclude that:

  1. ValueTypeNumber is defined and used consistently in the integration API and schema handling.
  2. The implementation of FieldNumber and related structures is extensive and follows the patterns established for other field types.
  3. The new type is properly handled in type assertions and switch statements where field types are concerned.
  4. There are no apparent inconsistencies in how number fields are handled compared to integer fields.

The impact of this change seems to be well-contained within the schema and field handling parts of the codebase, which is exactly what we would expect for this kind of addition.

Given these findings, it appears that the addition of ValueTypeNumber support has been implemented correctly and should not cause any unexpected issues in the rest of the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Identify areas in the codebase that might need updates to support ValueTypeNumber

# Search for uses of ValueTypeInteger as a proxy for number-related logic
echo "Searching for ValueTypeInteger usage:"
rg --type go "ValueTypeInteger"

# Search for switch statements on ValueType to ensure they include the new ValueTypeNumber
echo "\nSearching for switch statements on ValueType:"
rg --type go "switch.*ValueType"

# Search for schema-related functions that might need to handle the new number type
echo "\nSearching for schema-related functions:"
rg --type go "func.*(Schema|Field|Value)"

Length of output: 419907


Script:

#!/bin/bash

echo "Searching for ValueTypeNumber usage:"
rg --type go "ValueTypeNumber"

echo "\nSearching for number field handling:"
rg --type go "FieldNumber|NumberField"

echo "\nSearching for switch statements on field types:"
rg --type go "switch.*\bType\b.*\bcase\b"

Length of output: 15782


Script:

#!/bin/bash

echo "Searching for additional ValueTypeNumber usage:"
rg --type go "ValueTypeNumber" -C 3

echo "\nSearching for type assertions related to field types:"
rg --type go "\\.(Type|FieldType)\\(\\)"

echo "\nSearching for FieldNumber usage:"
rg --type go "FieldNumber" -C 2

Length of output: 38745

server/e2e/gql_item_test.go (2)

415-415: Update in expected field values reflects new behavior.

The change in the expected values for the fields variable now includes a nil value for the asset field. This update correctly reflects the new behavior where the asset field can be empty or unset.


435-435: All fields can now be cleared to nil values.

The updated assertion for the fields variable after the update operation now expects all values to be nil. This change accurately represents the new functionality allowing all fields to be cleared or reset.

server/pkg/integrationapi/types.gen.go (3)

166-166: Impact on existing structs using ValueType

The addition of ValueTypeNumber expands the possible values for the Type field in both SchemaField and Field structs. While no immediate changes are required in these structs, they can now accept the new ValueTypeNumber. Ensure that any code handling these structs is updated to properly handle the new numeric type.

Let's check for any switch statements or type assertions that might need updating:

#!/bin/bash
# Search for switch statements or type assertions involving ValueType
rg --type go "switch.*ValueType|case.*ValueType|\(ValueType\)" --glob '!server/pkg/integrationapi/types.gen.go'

Line range hint 1-1024: Generated file with minimal changes

This file is generated, and only one constant has been added. While the change itself is correct and doesn't introduce any immediate issues, it's important to note:

  1. Ensure that the source of this generated file (likely an API specification) has been updated correspondingly.
  2. Check if any code generation scripts or tools need to be re-run to ensure consistency across the codebase.
  3. Verify that any documentation referring to ValueType is updated to include the new number type.

Let's check for any API specification files that might be the source of this generated code:

#!/bin/bash
# Search for OpenAPI/Swagger specification files
fd -e yaml -e yml -e json | rg -i "openapi|swagger"

166-166: New constant added for numeric value type

A new constant ValueTypeNumber has been added to the ValueType enumeration. This addition expands the capabilities of the API to handle numeric values explicitly.

To ensure this change is consistent with the rest of the codebase, let's check if this new value type is used or referenced elsewhere:

✅ Verification successful

ValueTypeNumber is correctly referenced in server/internal/adapter/integration/schema.go

No further changes required.

  • server/internal/adapter/integration/schema.go line: case integrationapi.ValueTypeNumber:
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any references to ValueTypeNumber in the codebase
rg --type go "ValueTypeNumber|ValueType.*number" --glob '!server/pkg/integrationapi/types.gen.go'

Length of output: 271


Script:

#!/bin/bash
# Search for any references to ValueTypeNumber in the codebase excluding the types.gen.go file
rg --type go "ValueTypeNumber|ValueType.*number" --glob '!server/pkg/integrationapi/types.gen.go'

Length of output: 183

server/schemas/integration.yml (1)

1674-1674: LGTM! Verify implementation across the system.

The addition of 'number' as a value type enhances the API's capability to handle float fields, which aligns with the PR objective. This change improves the flexibility of the data model.

To ensure this change is properly implemented and doesn't cause any unintended side effects, please run the following verification:

Please review the output of these tests and ensure that:

  1. The 'number' type is properly defined in schema definitions where needed.
  2. All switch statements or similar constructs handling value types are updated to include the 'number' type.
  3. Any hardcoded lists of value types are updated to include 'number'.
server/e2e/integration_item_test.go (2)

1576-1576: LGTM! CSV output format updated correctly.

The expected CSV output format has been properly updated to include the new "number" column. This change ensures consistency with the new field structure and maintains the correctness of the CSV export functionality.


1596-1596: LGTM! CSV output format updated consistently.

The expected CSV output format has been correctly updated to include the new "number" column. This change maintains consistency with the new field structure and ensures the correctness of the CSV export functionality when exporting items with project information.

server/internal/adapter/gql/generated.go (15)

691-695: LGTM: Addition of SchemaFieldNumber Structure

The SchemaFieldNumber struct is correctly defined with the necessary fields DefaultValue, Max, and Min, which will help handle numeric fields in the GraphQL schema.


4012-4032: LGTM: Complexity Calculations for SchemaFieldNumber Fields

The complexity functions for SchemaFieldNumber fields defaultValue, max, and min are appropriately added, ensuring proper complexity calculations during query execution.


4788-4788: LGTM: Adding SchemaFieldNumberInput Unmarshaling

The ec.unmarshalInputSchemaFieldNumberInput function is correctly included to handle unmarshaling of SchemaFieldNumberInput.


5190-5190: LGTM: Adding Number to SchemaFieldType Enum

The Number type is properly added to the SchemaFieldType enum, enhancing the schema to support numeric fields.


5263-5263: LGTM: Including SchemaFieldNumber in SchemaFieldTypeProperty Union

The SchemaFieldNumber type is correctly added to the SchemaFieldTypeProperty union, integrating the numeric field into the GraphQL schema.


5475-5475: LGTM: Adding number Field to SchemaFieldTypePropertyInput

The number field is appropriately added to the SchemaFieldTypePropertyInput, allowing users to input numeric field configurations.


28748-28870: LGTM: Resolver Functions for SchemaFieldNumber Fields

The resolver functions _SchemaFieldNumber_defaultValue, _SchemaFieldNumber_min, and _SchemaFieldNumber_max are correctly implemented to handle the new fields in SchemaFieldNumber.


38655-38658: LGTM: Including number in Fields Order for Unmarshaling

The number field is correctly added to the fieldsInOrder array, ensuring it is processed in the correct order during input unmarshaling.


38948-38973: LGTM: Unmarshaling Logic for number Field

The unmarshaling logic for the number field within unmarshalInputSchemaFieldTypePropertyInput is properly implemented, allowing for correct input handling.


40881-40887: LGTM: Handling SchemaFieldNumber in Type Casting

The addition of SchemaFieldNumber cases ensures that objects of this type are correctly handled during type casting.


46836-46875: LGTM: Implementation of _SchemaFieldNumber Field Resolver

The _SchemaFieldNumber resolver function and its implementors are correctly added, enabling proper field resolution for SchemaFieldNumber types.


52416-52431: LGTM: Marshal and Unmarshal Functions for Optional float64

The unmarshalOFloat2ᚖfloat64 and marshalOFloat2ᚖfloat64 functions are correctly implemented to handle optional float64 values, which is essential for fields like min and max.


53149-53155: LGTM: Unmarshaling Optional SchemaFieldNumberInput

The function unmarshalOSchemaFieldNumberInput2ᚖgqlmodel.SchemaFieldNumberInput is properly added to handle optional inputs for SchemaFieldNumberInput.


5421-5425: ⚠️ Potential issue

Update defaultValue Type in SchemaFieldNumberInput

Similarly, in SchemaFieldNumberInput, the defaultValue field should be changed from Any to Float to maintain consistency and ensure proper type validation.

Apply this diff:

 input SchemaFieldNumberInput {
-  defaultValue: Any
+  defaultValue: Float
   min: Float
   max: Float
 }

Likely invalid or redundant comment.


38355-38394: ⚠️ Potential issue

Update Unmarshaling Logic for defaultValue

If the defaultValue type is changed to Float, ensure that the unmarshaling logic in unmarshalInputSchemaFieldNumberInput is updated accordingly.

Apply this diff after updating the schema:

 case "defaultValue":
   ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("defaultValue"))
-  data, err := ec.unmarshalOAny2interface(ctx, v)
+  data, err := ec.unmarshalOFloat2ᚖfloat64(ctx, v)
   if err != nil {
     return it, err
   }
   it.DefaultValue = data

Likely invalid or redundant comment.

server/internal/adapter/integration/item_import.go (1)

254-256: Enhancement in type assignability logic looks good

The modifications in the isAssignable function to allow value.TypeInteger to be assigned to value.TypeNumber enhance the flexibility of type handling. This change is logically sound and correctly implemented.

server/e2e/gql_field_test.go (3)

137-137: LGTM

The addition of numberFId to the fIds struct is appropriate.


274-274: LGTM

Including numberFId in the assertion ensures the new field is included in the test validations.


291-291: LGTM

Returning numberFId in the fIds struct allows access to the new field in subsequent tests.

Comment on lines +395 to +397
case integrationapi.ValueTypeNumber:
tpi, _ := schema.NewNumber(nil, nil)
tpRes = tpi.TypeProperty()
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider improving default value handling and error management.

While the implementation for ValueTypeNumber is correct and consistent with other types, there are a couple of points to consider for future improvements:

  1. Default Value: The function signature includes a return value for a default value (dv *value.Multiple), but it's not being set for most types, including the new Number type. Consider clarifying the intended use of this return value and potentially initializing it appropriately for each type.

  2. Error Handling: The NewNumber function call ignores a potential error (similar to NewInteger). While this is consistent with the current implementation, it might be worth considering a more robust error handling approach in the future.

Would you like assistance in implementing these improvements?

@@ -1450,7 +1450,7 @@ func TestIntegrationModelImportJSONWithJsonInput(t *testing.T) {
mId, _ := createModel(e, pId, "test", "test", "test-1")
createFieldOfEachType(t, e, mId)

jsonContent := `[{"text": "test1", "bool": true, "integer": 1},{"text": "test2", "bool": false, "integer": 2},{"text": "test3", "bool": null, "integer": null}]`
jsonContent := `[{"text": "test1", "bool": true, "number": 1.1},{"text": "test2", "bool": false, "number": 2},{"text": "test3", "bool": null, "number": null}]`
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

Action Required: Update Remaining "integer" References to "number"

The search revealed multiple instances of "integer" across the codebase. To maintain consistency and support for floating-point numbers, please update all relevant occurrences from "integer" to "number". Ensure that these changes are reflected in:

  • Field definitions and type declarations.
  • Context paths and API contracts.
  • Associated test cases and schemas.

This will help prevent potential type mismatches and ensure seamless functionality across the system.

🔗 Analysis chain

LGTM! Consider verifying the impact of the field type change.

The change from "integer" to "number" in the test JSON content is good and reflects the new support for floating-point numbers. This update aligns the test case with the new field structure.

To ensure this change doesn't have unintended consequences, please run the following script to check for any other occurrences of "integer" fields that might need updating:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other occurrences of "integer" fields in the codebase
rg '"integer"' --type go

Length of output: 1553

Comment on lines +5325 to +5329
type SchemaFieldNumber {
defaultValue: Any
min: Float
max: Float
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider Changing defaultValue Type to Float

The defaultValue field in SchemaFieldNumber is currently defined as type Any. For better type safety and clarity, consider changing its type to Float, since it represents a numeric value.

Apply this diff to update the type:

 type SchemaFieldNumber {
-  defaultValue: Any
+  defaultValue: Float
   min: Float
   max: Float
 }

Committable suggestion was skipped due to low confidence.

@@ -282,7 +286,7 @@ func FieldFrom(k string, v any, sp schema.Package) interfaces.CreateFieldParam {
case reflect.Uint64:
case reflect.Float32:
case reflect.Float64:
t = value.TypeInteger
t = value.TypeNumber
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

Impact of Changing value.TypeInteger to value.TypeNumber Confirmed

The mapping of integer types to value.TypeNumber has been identified in multiple parts of the codebase:

  • Schema Definitions: Affects how fields are constructed and validated.
  • Integration APIs: May alter how integer values are processed and returned.
  • Exporters: Changes how data is exported, potentially affecting CSV and GeoJSON outputs.
  • Testing: Existing tests are based on value.TypeInteger and may need updates to accommodate the new type.

Recommendation:

  • Thoroughly review and update all affected areas to ensure compatibility with value.TypeNumber.
  • Update existing tests to reflect the new type mappings and validate the changes comprehensively.
🔗 Analysis chain

Verify the impact of mapping integer types to value.TypeNumber

In the FieldFrom function, all integer types are now mapped to value.TypeNumber instead of value.TypeInteger. This change could affect other parts of the codebase that rely on value.TypeInteger. Please ensure this alteration does not introduce unintended side effects.

Run the following script to identify usages of value.TypeInteger and assess potential impacts:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find usages of 'value.TypeInteger' in the codebase to identify areas potentially affected by the change.

# Expected: Review the occurrences to ensure compatibility with the new type mapping.

rg --type go 'value\.TypeInteger'

Length of output: 3052

Comment on lines +196 to +205
numberFId, _ := createField(e, mId, "number", "number", "number",
false, false, false, false, "Number",
map[string]any{
"number": map[string]any{
"defaultValue": nil,
"min": nil,
"max": nil,
},
})

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding tests for the "number" field's constraints

While the "number" field is properly added, consider adding tests to validate its defaultValue, min, and max properties to ensure it behaves correctly under various conditions.

Comment on lines +1033 to +1046
type SchemaFieldNumber struct {
DefaultValue any `json:"defaultValue,omitempty"`
Min *float64 `json:"min,omitempty"`
Max *float64 `json:"max,omitempty"`
}

func (SchemaFieldNumber) IsSchemaFieldTypeProperty() {}

type SchemaFieldNumberInput struct {
DefaultValue any `json:"defaultValue,omitempty"`
Min *float64 `json:"min,omitempty"`
Max *float64 `json:"max,omitempty"`
}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid modifying generated code directly

The file models_gen.go is auto-generated by gqlgen, as indicated by the comment // Code generated by github.com/99designs/gqlgen, DO NOT EDIT. at the top of the file. Modifying this file directly is not recommended because your changes will be overwritten the next time the code is generated. Please make your changes to the appropriate GraphQL schema definitions or source files used by the code generator.

@@ -1130,6 +1144,7 @@ type SchemaFieldTypePropertyInput struct {
Tag *SchemaFieldTagInput `json:"tag,omitempty"`
Checkbox *SchemaFieldCheckboxInput `json:"checkbox,omitempty"`
Integer *SchemaFieldIntegerInput `json:"integer,omitempty"`
Number *SchemaFieldNumberInput `json:"number,omitempty"`
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Changes to SchemaFieldTypePropertyInput should be made in the schema

The addition of the Number field to SchemaFieldTypePropertyInput should be done in the GraphQL schema definitions, not directly in the generated code. This ensures that the change is preserved and properly reflected when the code is regenerated.

@@ -2430,6 +2445,7 @@ const (
SchemaFieldTypeSelect SchemaFieldType = "Select"
SchemaFieldTypeTag SchemaFieldType = "Tag"
SchemaFieldTypeInteger SchemaFieldType = "Integer"
SchemaFieldTypeNumber SchemaFieldType = "Number"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update the GraphQL schema to include SchemaFieldTypeNumber

The new enum value SchemaFieldTypeNumber and its inclusion in AllSchemaFieldType and the IsValid method should be added to the GraphQL schema files, not directly in models_gen.go. Modifying the generated code can lead to inconsistencies and your changes may be lost on regeneration.

Also applies to: 2468-2468, 2479-2479

Comment on lines +4599 to +4635
"p3H3rbG47ZhgAfdCkhbuxTEDFEYhw/HsSl+dI3aT0DvpqcUziG+u6X0Y5c1UiTbHKqqOQl33szkSZZWN",
"UVK1cWBAVClQJ4a0qxSFApnEmcp4X1ybEr298CHB0vvwOoDAOKYEEulNDWLdenLzZCM+LgpymH82BshP",
"eWuezgYCz/bX+N0NZtsIq4nvLFP+Wo3fWbwgp3Zy3iu3Xaaof+LybK2grKGwDRQdVr70xQoc4oxh8aD0",
"lGbFa0AM2HGmPTm1WkVidbmYdibEQtexMZnQapn5T/iAmJi9O/k8Ds5VHlJ5wMHx5bmcRGr91lH54sLf",
"Dg4PDk0AR9ACh0fh+4PDg/eh9jkV4LoRko8eTePnUgOVglAqRAdPmBLJTKHKpZ/qmyul+H8dHuryZJ4c",
"RYtF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35rRdKcFMAalqcuabMPpmjUQP3L/Ib/DiFOTKGHD7XZEEJihLRXikvmbsfqFU",
"sAwiX4mD3oC/76P268xPuUO+0yo937odfHPlBh+r2H1xLLJCuQQ0SmKL/Rxli5Qi0yzilbhzzjMpcF//",
"/KREDQWKTwNBA/1sfjh7jbB9VaNykdtYMQx6LtgnINPSxxcdoxBnjOuvYm7ScLUc+ODNdrDbPkMJ9/5v",
"lw+gf2q+C6IZ5TWcX1Zh+EbBs4Hk6NF+oXH95iw7Q4/+qn1Bf1/QH6Cpqp6LG9umahuiXn4X1C7SMil1",
"MA3RwLSicbbXg7TXU3s9NUDj0aPzGd5l7vT2yBDlj6z6saZQso107sCJDHfVnTIs1mHx5Fi2m9LNIX1O",
"r7D5yS9UnEkncesnYdWzoutiXlqM9VfljmQ8ye7R5XL53wAAAP//H0uKi7KeAAA=",
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider externalizing the Swagger specification to reduce binary size

Embedding the Swagger specification as a base64-encoded string directly in the code can significantly increase the binary size and may impact performance. Consider externalizing the Swagger specification into a separate file or using the go:embed directive to include it at compile time. This approach can help manage the binary size and improve maintainability.

@yk-eukarya yk-eukarya requested a review from rot1024 as a code owner October 22, 2024 09:52
@github-actions github-actions bot added the ci label Oct 22, 2024
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

🧹 Outside diff range and nitpick comments (1)
.github/workflows/ci_server.yml (1)

Add cache-dependency-path to existing go setup steps

To ensure consistent caching behavior across all jobs, add cache-dependency-path to the go setup steps in the ci-server-lint and ci-server-i18n jobs.

  • .github/workflows/ci_server.yml - Jobs: ci-server-lint, ci-server-i18n
🔗 Analysis chain

Line range hint 1-56: Consider adding cache-dependency-path to other go setup steps

While the addition of cache-dependency-path to the ci-server-test job is beneficial, it's worth checking if this optimization can be applied to other go setup steps in the workflow for consistency and improved performance across all jobs.

Please review the results of the following script to identify other go setup steps that might benefit from this optimization:

If other go setup steps are found without the cache-dependency-path parameter, consider adding it to those steps as well for consistent caching behavior across all jobs.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if other jobs in the workflow could benefit from cache-dependency-path

# Test: Search for other 'go setup' steps in the workflow
rg -A 5 'name: go setup' .github/workflows/ci_server.yml

Length of output: 627

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b4d71c5 and 623882b.

📒 Files selected for processing (1)
  • .github/workflows/ci_server.yml (1 hunks)
🧰 Additional context used

@@ -53,6 +53,7 @@ jobs:
uses: actions/setup-go@v5
with:
go-version: ${{ env.GO_VERSION }}
cache-dependency-path: server/go.mod
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

Apply cache-dependency-path to all go setup steps

To ensure consistent and optimized caching across the workflow, add cache-dependency-path: server/go.mod to the remaining go setup steps.

  • Jobs to update:
    • golangci-lint job
    • check forgotten translations job
🔗 Analysis chain

Approve the addition of cache-dependency-path

The addition of cache-dependency-path: server/go.mod to the go setup step is a good practice. This parameter helps to optimize the caching of Go module dependencies, potentially speeding up the CI process by reusing cached dependencies when the go.mod file hasn't changed.

To ensure this change is consistently applied across the workflow, let's check if similar jobs could benefit from this optimization:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if other jobs in the workflow could benefit from cache-dependency-path

# Test: Search for other 'go setup' steps in the workflow
rg -A 5 'name: go setup' .github/workflows/ci_server.yml

Length of output: 627

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 623882b and 7afadf4.

📒 Files selected for processing (1)
  • server/e2e/integration_schema_test.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
server/e2e/integration_schema_test.go (2)

238-273: LGTM - Test for 'number' field type is correctly implemented

The integration test for creating a field of type number is appropriately implemented and follows the existing testing patterns.


Line range hint 275-304: LGTM - Test for 'geometryObject' field type is correctly implemented

The integration test for creating a field of type geometryObject is appropriately implemented and follows the existing testing patterns.

Comment on lines 238 to 273
//region number
res = e.POST(endpoint, sid1).
WithHeader("authorization", "Bearer "+secret).
WithJSON(map[string]interface{}{
"key": "fKey2",
"type": "number",
"multiple": false,
"required": false,
}).
Expect().
Status(http.StatusOK).
JSON().
Object()

res.ContainsKey("id")

res = e.GET("/api/models/{modelId}", mId1).
WithHeader("authorization", "Bearer "+secret).
Expect().
Status(http.StatusOK).
JSON().
Object()

res.HasValue("id", mId1.String()).
HasValue("name", "m1").
HasValue("description", "m1 desc").
HasValue("public", true).
HasValue("key", ikey1.String()).
HasValue("projectId", pid).
HasValue("schemaId", sid1)

res.Value("schema").Object().Value("fields").Array().Length().IsEqual(5)
res.Value("createdAt").NotNull()
res.Value("updatedAt").NotNull()
res.Value("lastModified").NotNull()
// endregion
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider refactoring repetitive test code into helper functions

The test code for creating fields of different types (number, geometryObject) is repetitive. Consider refactoring the common code into reusable helper functions to improve maintainability and reduce duplication.

Also applies to: 275-304

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

🧹 Outside diff range and nitpick comments (1)
server/e2e/integration_schema_test.go (1)

Line range hint 254-295: Enhance number field type testing

Since the PR objective is to add float field support, consider:

  1. Adding specific test cases for float fields
  2. Validating number-specific properties (min/max values, precision)
  3. Testing edge cases (e.g., decimal places, scientific notation)

Add test cases for float-specific scenarios:

 WithJSON(map[string]interface{}{
   "key":      "fKey2",
   "type":     "number",
   "multiple": false,
   "required": false,
+  "min":      -1.5,
+  "max":      1000.55,
+  "precision": 2
 })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7afadf4 and 65d2313.

📒 Files selected for processing (1)
  • server/e2e/integration_schema_test.go (3 hunks)
🧰 Additional context used
🔇 Additional comments (2)
server/e2e/integration_schema_test.go (2)

Line range hint 210-251: Test structure matches previous pattern

The test follows the same pattern as the text field test.


Line range hint 180-295: Refactor common test patterns into helper functions

The test code for different field types follows similar patterns. As mentioned in the previous review, consider extracting common test patterns into helper functions.

Example refactoring:

func createField(e *httpexpect.Expect, schemaId string, fieldData map[string]interface{}) *httpexpect.Object {
    return e.POST("/api/schemata/{schemaId}/fields", schemaId).
        WithHeader("authorization", "Bearer "+secret).
        WithJSON(fieldData).
        Expect().
        Status(http.StatusOK).
        JSON().
        Object()
}

func verifyFieldInSchema(e *httpexpect.Expect, modelId string, expectedField map[string]interface{}) {
    res := e.GET("/api/models/{modelId}", modelId).
        WithHeader("authorization", "Bearer "+secret).
        Expect().
        Status(http.StatusOK).
        JSON().
        Object()
    
    // Verify model metadata
    res.ContainsSubset(map[string]any{
        "name":        "m1",
        "id":          modelId,
        // ... other fields
    })
    
    // Find and verify the field
    fields := res.Value("schema").Object().Value("fields").Array()
    findFieldByKey(fields, expectedField["key"].(string)).
        ContainsSubset(expectedField)
}

Comment on lines +180 to +208
res = e.GET("/api/models/{modelId}", mId1).
WithHeader("authorization", "Bearer "+secret).
Expect().
Status(http.StatusOK).
JSON().
Object()

res.ContainsSubset(map[string]any{
"name": "m1",
"id": mId1.String(),
"description": "m1 desc",
"public": true,
"key": ikey1.String(),
"projectId": pid,
"schemaId": sid1,
})

res.Value("createdAt").NotNull()
res.Value("updatedAt").NotNull()
res.Value("lastModified").NotNull()
resf := res.Value("schema").Object().Value("fields").Array()
resf.Length().IsEqual(3)
resf.Value(2).Object().ContainsSubset(map[string]any{
// "id": "", // generated
"key": "テスト",
"type": "text",
"required": false,
})
// endregion
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider making field verification more robust

The current test relies on hardcoded array indices (e.g., resf.Value(2)) to verify fields, which could break if the field order changes. Consider using a helper function to find fields by key instead.

- resf.Value(2).Object().ContainsSubset(map[string]any{
-   "key":      "テスト",
-   "type":     "text",
-   "required": false,
- })
+ // Add helper function
+ func findFieldByKey(fields *httpexpect.Array, key string) *httpexpect.Object {
+   for i := 0; i < fields.Length().Raw(); i++ {
+     field := fields.Value(i).Object()
+     if field.Value("key").String().Raw() == key {
+       return field
+     }
+   }
+   return nil
+ }
+ 
+ // Use helper in test
+ findFieldByKey(resf, "テスト").ContainsSubset(map[string]any{
+   "key":      "テスト",
+   "type":     "text",
+   "required": false,
+ })

Committable suggestion was skipped due to low confidence.

@yk-eukarya yk-eukarya merged commit fb598bc into main Oct 23, 2024
14 checks passed
@yk-eukarya yk-eukarya deleted the feat/support-float-fields branch October 23, 2024 06:57
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