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

GO-2969 reorder relation options #1038

Open
wants to merge 8 commits into
base: main
Choose a base branch
from

Conversation

requilence
Copy link
Contributor

@requilence requilence commented Mar 26, 2024

This PR adds an ability for clients to reorder the relation's options.
It's done in a way that default order is the date of creation (based on the BSON ID sorting)

RPC added: RelationMoveOption.

  • in case you are using sorting relationOptionOrder ASC(for select), set the Sort to 0(OlderFirst).
  • in case you are using sorting relationOptionOrder DESC(for multi-select tags), set the Sort to 1(NewerFirst).

Relations added: relationOptionOrder, relationOptionInternalOrder

Client should use relationOptionOrder for sorting because it contains the fallback to the creation date

Under the hood it is using the lexicographical sorting. It allows to change the position of a single element without having a centralised list of options. There is no need for any migration, because we already use BSON ID for option ids, and bson ids are sorted in the chronological way.
When you add the new option it's automatically will be added to the begin or the end (depends on the sort) because of bsons

added RPC and relations: relationOptionOrder/relationOptionInternalOrder
…t into go-2969-reorder-relation-options

# Conflicts:
#	clientlibrary/service/service.pb.go
#	go.mod
#	pb/commands.pb.go
#	pb/service/service.pb.go
…t into go-2969-reorder-relation-options

# Conflicts:
#	clientlibrary/service/service.pb.go
#	go.mod
#	go.sum
#	pb/commands.pb.go
#	pb/service/service.pb.go
#	pkg/lib/bundle/relation.gen.go
#	pkg/lib/bundle/relations.json
Copy link

github-actions bot commented Mar 26, 2024

New Coverage 41.7% of statements
Patch Coverage 0.0% of changed statements (0/68)

Coverage provided by https://github.com/seriousben/go-patch-cover-action

Copy link
Contributor

@fat-fellow fat-fellow left a comment

Choose a reason for hiding this comment

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

Tests

…t into go-2969-reorder-relation-options

# Conflicts:
#	clientlibrary/service/service.pb.go
#	pb/commands.pb.go
#	pb/service/service.pb.go
#	pkg/lib/bundle/relation.gen.go
@@ -685,6 +686,51 @@ func (s *Service) RemoveListOption(optionIds []string, checkInObjects bool) erro
return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Need to extract this code from the block service

…t into go-2969-reorder-relation-options

# Conflicts:
#	clientlibrary/service/service.pb.go
#	go.mod
#	go.sum
#	pb/commands.pb.go
#	pb/service/service.pb.go
#	pkg/lib/bundle/relation.gen.go
#	pkg/lib/bundle/systemRelations.gen.go
Copy link

coderabbitai bot commented Jun 19, 2024

Walkthrough

The updates introduced a mechanism for handling and reordering relation options within smart blocks. This includes adding new methods for moving options, retrieving sort keys, and modifying details related to relation options. The changes span various components, including core logic, protobuf files, and new dependencies for lexicographic sorting.

Changes

File Change Summary
core/block/editor/smartblock/smartblock.go Updated injectDerivedDetails method to handle a new case for smart block types and setting local details.
core/block/service.go Added functions to handle moving and reordering options, with new imports for lexicographic sorting.
core/relations.go Added function RelationMoveOption to handle option movement in relations with swap logic and error handling.
go.mod Added a new dependency on github.com/tolgaOzen/lexicographic-sort version 1.0.0.
pb/protos/commands.proto Added new MoveOption message and OptionsSort enum within Relation message for handling sorting preferences.
pb/protos/service/service.proto Introduced new RPC method RelationMoveOption in ClientCommands service interface.
pkg/lib/bundle/relations.json Added and updated fields related to relation options, including "Relation option order" and "Relation option internal order".
pkg/lib/bundle/systemRelations.json Added new fields for "relationOptionOrder" and "relationOptionInternalOrder".

Sequence Diagrams

sequenceDiagram
    participant Client
    participant Server
    participant Service
    client->>Server: Send MoveOption Request
    Server->>Service: Call MoveOption
    Service->>Service: reorderRelationOption
    activate Service
    Service-->>Server: Return new order
    deactivate Service
    Server-->>Client: Send MoveOption Response
Loading

Poem

In a world of blocks, where options roam,
We sort and move, find them a new home.
With lexicographic grace, they align in place,
Order defined, in this smart space.
From fields and rows, new life grows,
A rabbit's touch, the system knows.
🐇✨🏗️


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

@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: CHILL

Commits

Files that changed from the base of the PR and between 8daa0e6 and 23648e5.

Files ignored due to path filters (7)
  • clientlibrary/service/service.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • docs/proto.md is excluded by !**/proto.md
  • go.sum is excluded by !**/*.sum
  • pb/commands.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • pb/service/service.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • pkg/lib/bundle/relation.gen.go is excluded by !**/*.gen.go
  • pkg/lib/bundle/systemRelations.gen.go is excluded by !**/*.gen.go
Files selected for processing (8)
  • core/block/editor/smartblock/smartblock.go (1 hunks)
  • core/block/service.go (3 hunks)
  • core/relations.go (1 hunks)
  • go.mod (1 hunks)
  • pb/protos/commands.proto (1 hunks)
  • pb/protos/service/service.proto (1 hunks)
  • pkg/lib/bundle/relations.json (1 hunks)
  • pkg/lib/bundle/systemRelations.json (1 hunks)
Files skipped from review due to trivial changes (1)
  • go.mod
Additional context used
GitHub Check: lint
core/block/service.go

[failure] 674-674:
undefined: Do


[failure] 678-678:
assignment mismatch: 3 variables but s.objectStore.Query returns 2 values (typecheck)


[failure] 674-674:
undefined: Do


[failure] 678-678:
assignment mismatch: 3 variables but s.objectStore.Query returns 2 values) (typecheck)


[failure] 674-674:
undefined: Do


[failure] 678-678:
assignment mismatch: 3 variables but s.objectStore.Query returns 2 values) (typecheck)

Additional comments not posted (5)
pkg/lib/bundle/systemRelations.json (1)

38-39: The addition of "relationOptionOrder" and "relationOptionInternalOrder" fields aligns with the PR's objectives of supporting relation option reordering. The fields are correctly placed and maintain the JSON structure integrity.

pb/protos/service/service.proto (1)

129-129: The addition of RelationMoveOption RPC method is well-placed and aligns with the PR objectives.

Verification successful

The addition of the RelationMoveOption RPC method is well-placed and aligns with the PR objectives. The integration and handling of this RPC method are evident in various parts of the codebase, confirming its proper implementation.

  • pb/service/service.pb.go: Definition and usage of RelationMoveOption.
  • pb/commands.pb.go: Related request and response types.
  • core/relations.go: Handling of the RelationMoveOption method.
  • clientlibrary/service/service.pb.go: Client-side handling of the RelationMoveOption method.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify integration of the new RPC method `RelationMoveOption` with the rest of the system.

# Test: Search for usages of `RelationMoveOption` in the codebase. Expect: Proper implementation and handling in related services.
rg --type go 'RelationMoveOption'

Length of output: 14749

pkg/lib/bundle/relations.json (1)

91-100: The new field "relationOptionOrder" has been added correctly with appropriate attributes. It is set to be derived, which aligns with the PR description stating that the order includes a fallback to the creation date.

core/block/editor/smartblock/smartblock.go (1)

1430-1437: Ensure the new relation option ordering logic matches the expected behavior.

pb/protos/commands.proto (1)

2942-2968: The MoveOption message and its nested structures have been added to handle the reordering of options within a relation. Ensure that the OptionsSort enum correctly reflects the intended sorting behavior as described. The error handling within the Response message is standard and aligns with existing patterns in the codebase. However, consider adding more specific error codes related to the move operation to enhance troubleshooting and user feedback.

Comment on lines +101 to +110
{
"description": "Relation option internal order",
"format": "longtext",
"hidden": true,
"key": "relationOptionInternalOrder",
"maxCount": 1,
"name": "Relation option internal order",
"readonly": false,
"source": "details"
},
Copy link

Choose a reason for hiding this comment

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

The addition of "relationOptionInternalOrder" seems to provide internal sorting capabilities. However, it's marked as non-readonly which could imply that clients might modify it directly. This could lead to inconsistencies if not managed properly.

Consider setting "relationOptionInternalOrder" as readonly to prevent direct modifications, ensuring consistency in the sorting mechanism.

Comment on lines +83 to +114
func (mw *Middleware) RelationMoveOption(cctx context.Context, request *pb.RpcRelationMoveOptionRequest) *pb.RpcRelationMoveOptionResponse {
response := func(code pb.RpcRelationMoveOptionResponseErrorCode, err error) *pb.RpcRelationMoveOptionResponse {
if err != nil {
return &pb.RpcRelationMoveOptionResponse{
Error: &pb.RpcRelationMoveOptionResponseError{
Code: code,
Description: err.Error(),
},
}
}

return &pb.RpcRelationMoveOptionResponse{
Error: &pb.RpcRelationMoveOptionResponseError{
Code: code,
},
}
}

err := mw.doBlockService(func(bs *block.Service) error {
var err error
if request.Sort == pb.RpcRelationMoveOptionRequest_NewerFirst {
request.BeforeId, request.AfterId = request.AfterId, request.BeforeId
}
err = bs.MoveOption(request.OptionId, request.AfterId, request.BeforeId)
return err
})
if err != nil {
return response(pb.RpcRelationMoveOptionResponseError_UNKNOWN_ERROR, err)
}

return response(pb.RpcRelationMoveOptionResponseError_NULL, nil)
}
Copy link

Choose a reason for hiding this comment

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

The RelationMoveOption function is implemented to handle the logic for moving relation options. It uses a helper function to swap the IDs based on the sort condition, which aligns with the PR objectives. Consider adding more detailed error descriptions in the response for better clarity and debugging.

-					Description: err.Error(),
+					Description: "Error moving relation option: " + err.Error(),
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
func (mw *Middleware) RelationMoveOption(cctx context.Context, request *pb.RpcRelationMoveOptionRequest) *pb.RpcRelationMoveOptionResponse {
response := func(code pb.RpcRelationMoveOptionResponseErrorCode, err error) *pb.RpcRelationMoveOptionResponse {
if err != nil {
return &pb.RpcRelationMoveOptionResponse{
Error: &pb.RpcRelationMoveOptionResponseError{
Code: code,
Description: err.Error(),
},
}
}
return &pb.RpcRelationMoveOptionResponse{
Error: &pb.RpcRelationMoveOptionResponseError{
Code: code,
},
}
}
err := mw.doBlockService(func(bs *block.Service) error {
var err error
if request.Sort == pb.RpcRelationMoveOptionRequest_NewerFirst {
request.BeforeId, request.AfterId = request.AfterId, request.BeforeId
}
err = bs.MoveOption(request.OptionId, request.AfterId, request.BeforeId)
return err
})
if err != nil {
return response(pb.RpcRelationMoveOptionResponseError_UNKNOWN_ERROR, err)
}
return response(pb.RpcRelationMoveOptionResponseError_NULL, nil)
}
func (mw *Middleware) RelationMoveOption(cctx context.Context, request *pb.RpcRelationMoveOptionRequest) *pb.RpcRelationMoveOptionResponse {
response := func(code pb.RpcRelationMoveOptionResponseErrorCode, err error) *pb.RpcRelationMoveOptionResponse {
if err != nil {
return &pb.RpcRelationMoveOptionResponse{
Error: &pb.RpcRelationMoveOptionResponseError{
Code: code,
Description: "Error moving relation option: " + err.Error(),
},
}
}
return &pb.RpcRelationMoveOptionResponse{
Error: &pb.RpcRelationMoveOptionResponseError{
Code: code,
},
}
}
err := mw.doBlockService(func(bs *block.Service) error {
var err error
if request.Sort == pb.RpcRelationMoveOptionRequest_NewerFirst {
request.BeforeId, request.AfterId = request.AfterId, request.BeforeId
}
err = bs.MoveOption(request.OptionId, request.AfterId, request.BeforeId)
return err
})
if err != nil {
return response(pb.RpcRelationMoveOptionResponseError_UNKNOWN_ERROR, err)
}
return response(pb.RpcRelationMoveOptionResponseError_NULL, nil)
}

Comment on lines +673 to +716
func (s *Service) MoveOption(optionId string, afterId, beforeId string) error {
return Do(s, optionId, func(b smartblock.SmartBlock) error {
st := b.NewState()
relKey := pbtypes.GetString(st.Details(), bundle.RelationKeyRelationKey.String())

records, _, err := s.objectStore.Query(database.Query{
Filters: []*model.BlockContentDataviewFilter{
{
Condition: model.BlockContentDataviewFilter_Equal,
RelationKey: bundle.RelationKeySpaceId.String(),
Value: pbtypes.String(b.SpaceID()),
},
{
Condition: model.BlockContentDataviewFilter_Equal,
RelationKey: bundle.RelationKeyRelationKey.String(),
Value: pbtypes.String(relKey),
},
{
Condition: model.BlockContentDataviewFilter_Equal,
RelationKey: bundle.RelationKeyLayout.String(),
Value: pbtypes.Int64(int64(model.ObjectType_relationOption)),
},
},
Sorts: []*model.BlockContentDataviewSort{
{
RelationKey: bundle.RelationKeyRelationOptionOrder.String(),
},
},
})
if err != nil {
return fmt.Errorf("query options: %w", err)
}

if len(records) == 0 {
return fmt.Errorf("target option not found")
}

newOrder, err := reorderRelationOption(records, optionId, afterId, beforeId)
st.SetDetail(bundle.RelationKeyRelationOptionInternalOrder.String(), pbtypes.String(newOrder))

return b.Apply(st)
},
)
}
Copy link

Choose a reason for hiding this comment

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

The MoveOption function contains several issues:

  • The Do function is undefined. You may need to replace it with the correct function name or define it if missing.
  • There's an assignment mismatch in the Query call on line 678.

Consider the following fixes:

- return Do(s, optionId, func(b smartblock.SmartBlock) error {
+ return s.doBlockService(func(b smartblock.SmartBlock) error {

- records, _, err := s.objectStore.Query(database.Query{
+ records, err := s.objectStore.Query(database.Query{
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
func (s *Service) MoveOption(optionId string, afterId, beforeId string) error {
return Do(s, optionId, func(b smartblock.SmartBlock) error {
st := b.NewState()
relKey := pbtypes.GetString(st.Details(), bundle.RelationKeyRelationKey.String())
records, _, err := s.objectStore.Query(database.Query{
Filters: []*model.BlockContentDataviewFilter{
{
Condition: model.BlockContentDataviewFilter_Equal,
RelationKey: bundle.RelationKeySpaceId.String(),
Value: pbtypes.String(b.SpaceID()),
},
{
Condition: model.BlockContentDataviewFilter_Equal,
RelationKey: bundle.RelationKeyRelationKey.String(),
Value: pbtypes.String(relKey),
},
{
Condition: model.BlockContentDataviewFilter_Equal,
RelationKey: bundle.RelationKeyLayout.String(),
Value: pbtypes.Int64(int64(model.ObjectType_relationOption)),
},
},
Sorts: []*model.BlockContentDataviewSort{
{
RelationKey: bundle.RelationKeyRelationOptionOrder.String(),
},
},
})
if err != nil {
return fmt.Errorf("query options: %w", err)
}
if len(records) == 0 {
return fmt.Errorf("target option not found")
}
newOrder, err := reorderRelationOption(records, optionId, afterId, beforeId)
st.SetDetail(bundle.RelationKeyRelationOptionInternalOrder.String(), pbtypes.String(newOrder))
return b.Apply(st)
},
)
}
func (s *Service) MoveOption(optionId string, afterId, beforeId string) error {
return s.doBlockService(func(b smartblock.SmartBlock) error {
st := b.NewState()
relKey := pbtypes.GetString(st.Details(), bundle.RelationKeyRelationKey.String())
records, err := s.objectStore.Query(database.Query{
Filters: []*model.BlockContentDataviewFilter{
{
Condition: model.BlockContentDataviewFilter_Equal,
RelationKey: bundle.RelationKeySpaceId.String(),
Value: pbtypes.String(b.SpaceID()),
},
{
Condition: model.BlockContentDataviewFilter_Equal,
RelationKey: bundle.RelationKeyRelationKey.String(),
Value: pbtypes.String(relKey),
},
{
Condition: model.BlockContentDataviewFilter_Equal,
RelationKey: bundle.RelationKeyLayout.String(),
Value: pbtypes.Int64(int64(model.ObjectType_relationOption)),
},
},
Sorts: []*model.BlockContentDataviewSort{
{
RelationKey: bundle.RelationKeyRelationOptionOrder.String(),
},
},
})
if err != nil {
return fmt.Errorf("query options: %w", err)
}
if len(records) == 0 {
return fmt.Errorf("target option not found")
}
newOrder, err := reorderRelationOption(records, optionId, afterId, beforeId)
st.SetDetail(bundle.RelationKeyRelationOptionInternalOrder.String(), pbtypes.String(newOrder))
return b.Apply(st)
},
)
}
Tools
GitHub Check: lint

[failure] 674-674:
undefined: Do


[failure] 678-678:
assignment mismatch: 3 variables but s.objectStore.Query returns 2 values (typecheck)


[failure] 674-674:
undefined: Do


[failure] 678-678:
assignment mismatch: 3 variables but s.objectStore.Query returns 2 values) (typecheck)


[failure] 674-674:
undefined: Do


[failure] 678-678:
assignment mismatch: 3 variables but s.objectStore.Query returns 2 values) (typecheck)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants