Repository navigation
fix: unable to get owner in chat and search - #17244
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughChat and search listings now return enriched list-item models, support owner-based filtering, and expose owner nickname and tenant avatar fields. Chat filtering is restricted to accessible tenant memberships, with pagination applied after owner-based retrieval. ChangesListing enrichment and owner filtering
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant ChatHandler
participant ChatService
participant ChatDAO
ChatHandler->>ChatService: ListChats with ownerIDs
ChatService->>ChatService: Filter accessible owner IDs
ChatService->>ChatDAO: ListByOwnerIDs
ChatDAO-->>ChatService: ChatListItem results
ChatService-->>ChatHandler: Enriched chat response
sequenceDiagram
participant SearchHandler
participant SearchService
participant SearchDAO
SearchHandler->>SearchService: ListSearches with ownerIDs
SearchService->>SearchDAO: ListByTenantIDs or ListByOwnerIDs
SearchDAO-->>SearchService: SearchListItem results
SearchService-->>SearchHandler: Response with nickname and tenant_avatar
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (7)
internal/dao/chat.go (4)
1-1: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winDead OR branch in
ListByOwnerIDs's owner filter, duplicated across chat and search DAOs. Both files AND a(tenant_id IN ownerIDs OR tenant_id = userID)clause with a latertenant_id IN ownerIDsclause, which algebraically collapses to justtenant_id IN ownerIDs— theOR ... = userIDbranch is unreachable in both.
internal/dao/chat.go#L119-128: drop theOR dialog.tenant_id = ?branch (and the now-redundant secondWhereat line 128), collapsing to a singledialog.tenant_id IN ? AND dialog.status = ?clause.internal/dao/search.go#L111-119: apply the same simplification tosearch.tenant_id IN ? AND search.status = ?.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/dao/chat.go` at line 1, In ListByOwnerIDs, simplify the chat DAO owner filter to one dialog.tenant_id IN ownerIDs condition combined with dialog.status, removing the OR dialog.tenant_id = userID branch and redundant second Where; apply the same change to the corresponding search DAO filter using search.tenant_id and search.status.Source: Coding guidelines
1-1: 🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy liftOwner-filtered listing has no DB-level pagination; the full match set is loaded and sliced in Go, in four places.
ListByOwnerIDsin both DAOs runsScanwith noCount()/Offset()/Limit(), then the corresponding services computetotal := len(...)and manually slice[start:end]. This is unbounded per request for owners/tenants with many chats/searches, unlike the tenant-scoped path which paginates in SQL.
internal/dao/chat.go#L109-145: add aCount()call and applyOffset(...).Limit(...)inListByOwnerIDs, mirroringListByTenantIDs.internal/dao/search.go#L100-136: apply the same DB-level pagination toListByOwnerIDs.internal/service/chat.go#L81-152: once the DAO paginates, drop the manualstart/endslicing inListChats.internal/service/search.go#L82-121: drop the equivalent manual slicing inListSearches.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/dao/chat.go` at line 1, Implement database-level pagination for owner-filtered listings: update ListByOwnerIDs in the chat and search DAOs to count matching rows and apply Offset and Limit before scanning, matching the tenant-scoped implementations. Then update ListChats and ListSearches to use the DAO’s paginated results directly and remove their manual start/end slicing while preserving the returned total count.
119-128: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winDead OR branch in the owner filter.
Line 120's
(dialog.tenant_id IN ? OR dialog.tenant_id = ?)is ANDed with line 128'sdialog.tenant_id IN ?(sameownerIDs). The combined condition is(A OR B) AND C AND A, which reduces toA AND C— theOR dialog.tenant_id = userIDbranch never contributes. This looks like leftover from copy-pastingListByTenantIDs's pattern, where the OR is actually meaningful.As per coding guidelines, `**/*` guidance to "Remove dead tests, commented-out code, stale documentation" applies equally to dead SQL predicates.🧹 Proposed fix to remove the dead branch
query := DB.Model(&entity.Chat{}). Select(` dialog.*, user.nickname, user.avatar as tenant_avatar `). Joins("LEFT JOIN user ON dialog.tenant_id = user.id"). - Where("(dialog.tenant_id IN ? OR dialog.tenant_id = ?) AND dialog.status = ?", ownerIDs, userID, "1") + Where("dialog.tenant_id IN ? AND dialog.status = ?", ownerIDs, "1") // Apply keyword filter if keywords != "" { query = query.Where("LOWER(dialog.name) LIKE ?", "%"+strings.ToLower(keywords)+"%") } - // Filter by owner IDs (additional filter to ensure tenant_id is in ownerIDs) - query = query.Where("dialog.tenant_id IN ?", ownerIDs) -🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/dao/chat.go` around lines 119 - 128, Remove the redundant “OR dialog.tenant_id = userID” branch from the owner predicate in the query-building flow, since the later “dialog.tenant_id IN ownerIDs” filter already constrains the same column. Preserve the keyword filter, status condition, and ownerIDs filtering behavior.Source: Coding guidelines
109-145: 🚀 Performance & Scalability | 🟠 Major
ListByOwnerIDsfetches every matching row before pagination.Unlike
ListByTenantIDs(Count + Offset/Limit at the DB level),ListByOwnerIDshas noCount()/Offset()/Limit()— it scans every row matching the owner filter, then the service slices in memory. For an owner/tenant with many chats this is an unbounded per-request load. This is new code in this PR; worth fixing before it's copied further.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/dao/chat.go` around lines 109 - 145, Update ListByOwnerIDs to perform pagination at the database level, matching ListByTenantIDs: count matching records separately, apply the request’s offset and limit to the query before scanning, and return the database count rather than len(chats). Preserve the existing filters, ordering, and error handling.internal/dao/search.go (2)
128-134: 🚀 Performance & Scalability | 🟠 MajorSame missing-DB-pagination issue as
chat.go'sListByOwnerIDs.No
Count()/Offset()/Limit()here either — all owner-matching searches are loaded before the service slices a page. Pre-existing, but this PR now replicates the pattern into chat listing too — see consolidated comment.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/dao/search.go` around lines 128 - 134, Update the search query flow around the matching-record Scan to apply database-level pagination with Count, Offset, and Limit before loading results, while retaining the total matching count separately for pagination metadata. Use the existing pagination inputs and preserve the current return behavior for query errors.
111-119: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winSame dead OR branch as
chat.go'sListByOwnerIDs.Line 111's
(search.tenant_id IN ? OR search.tenant_id = ?)is ANDed with line 119'ssearch.tenant_id IN ?(sameownerIDs), making theOR ... = userIDbranch unreachable. Pre-existing in this file, but now duplicated intointernal/dao/chat.go's newListByOwnerIDs— see consolidated comment.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/dao/search.go` around lines 111 - 119, The search query’s owner filter contains a dead userID OR branch because it is subsequently constrained by the same ownerIDs set. Update the relevant query construction in the search listing method to remove the unreachable “OR search.tenant_id = ?” condition and its userID argument, while retaining the keyword and ownerIDs filtering behavior.internal/service/search.go (1)
109-120: 🚀 Performance & Scalability | 🟠 MajorSame manual in-memory pagination pattern duplicated into
chat.go.This pre-existing slicing logic (loads all owner-matching rows, then slices) is now mirrored verbatim in
internal/service/chat.go(121-132). See consolidated comment for the shared fix (push pagination to the DB layer in both DAOs).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/search.go` around lines 109 - 120, Replace the in-memory pagination block in the relevant search service flow with database-level pagination, and apply the same change to the duplicated logic in chat.go. Update both DAOs and their callers to pass page and pageSize into the query, returning only the requested rows while preserving total-count handling and empty results for out-of-range pages.
🧹 Nitpick comments (1)
internal/service/chat.go (1)
1-1: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
filterAccessibleChatOwnerIDsandfilterAccessibleSearchOwnerIDsare duplicate implementations of the same owner-access-filtering logic. Both trim/dedupe requested owner IDs against an "allowed" set built fromuserID+GetTenantIDsByUserID(userID). This PR introduces the chat copy verbatim from the pre-existing search helper.
internal/service/chat.go#L154-185: extract a single shared helper (e.g., on a common service/util type) and haveChatServicecall it instead of keeping its own copy.internal/service/search.go#L135-166: haveSearchServicecall the same shared helper, removing its private copy.As per coding guidelines,
**/*direction to "reduce public surface area... and keep refactors centered on the owning abstraction" and to converge duplicate implementations into one path.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/chat.go` at line 1, Extract the shared owner-access filtering logic from filterAccessibleChatOwnerIDs and filterAccessibleSearchOwnerIDs into one private helper on the appropriate common service or utility abstraction. Update ChatService and SearchService to call that helper, preserving trimming, deduplication, and the allowed-ID set derived from userID plus GetTenantIDsByUserID(userID), then remove both private duplicate implementations.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/service/chat.go`:
- Around line 81-89: Change ChatService.ListChats to accept ownerIDs as a
regular []string parameter, remove the variadic ownerIDs[0] unwrapping and use
the parameter directly, then update all callers that currently omit owner IDs to
pass nil explicitly, matching SearchService.ListSearches.
---
Outside diff comments:
In `@internal/dao/chat.go`:
- Line 1: In ListByOwnerIDs, simplify the chat DAO owner filter to one
dialog.tenant_id IN ownerIDs condition combined with dialog.status, removing the
OR dialog.tenant_id = userID branch and redundant second Where; apply the same
change to the corresponding search DAO filter using search.tenant_id and
search.status.
- Line 1: Implement database-level pagination for owner-filtered listings:
update ListByOwnerIDs in the chat and search DAOs to count matching rows and
apply Offset and Limit before scanning, matching the tenant-scoped
implementations. Then update ListChats and ListSearches to use the DAO’s
paginated results directly and remove their manual start/end slicing while
preserving the returned total count.
- Around line 119-128: Remove the redundant “OR dialog.tenant_id = userID”
branch from the owner predicate in the query-building flow, since the later
“dialog.tenant_id IN ownerIDs” filter already constrains the same column.
Preserve the keyword filter, status condition, and ownerIDs filtering behavior.
- Around line 109-145: Update ListByOwnerIDs to perform pagination at the
database level, matching ListByTenantIDs: count matching records separately,
apply the request’s offset and limit to the query before scanning, and return
the database count rather than len(chats). Preserve the existing filters,
ordering, and error handling.
In `@internal/dao/search.go`:
- Around line 128-134: Update the search query flow around the matching-record
Scan to apply database-level pagination with Count, Offset, and Limit before
loading results, while retaining the total matching count separately for
pagination metadata. Use the existing pagination inputs and preserve the current
return behavior for query errors.
- Around line 111-119: The search query’s owner filter contains a dead userID OR
branch because it is subsequently constrained by the same ownerIDs set. Update
the relevant query construction in the search listing method to remove the
unreachable “OR search.tenant_id = ?” condition and its userID argument, while
retaining the keyword and ownerIDs filtering behavior.
In `@internal/service/search.go`:
- Around line 109-120: Replace the in-memory pagination block in the relevant
search service flow with database-level pagination, and apply the same change to
the duplicated logic in chat.go. Update both DAOs and their callers to pass page
and pageSize into the query, returning only the requested rows while preserving
total-count handling and empty results for out-of-range pages.
---
Nitpick comments:
In `@internal/service/chat.go`:
- Line 1: Extract the shared owner-access filtering logic from
filterAccessibleChatOwnerIDs and filterAccessibleSearchOwnerIDs into one private
helper on the appropriate common service or utility abstraction. Update
ChatService and SearchService to call that helper, preserving trimming,
deduplication, and the allowed-ID set derived from userID plus
GetTenantIDsByUserID(userID), then remove both private duplicate
implementations.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e2ccf40a-a729-4deb-b6fb-e9510f61b6d9
📒 Files selected for processing (10)
internal/dao/chat.gointernal/dao/search.gointernal/entity/chat.gointernal/entity/search.gointernal/handler/chat.gointernal/handler/search.gointernal/service/chat.gointernal/service/chat_list_test.gointernal/service/search.gointernal/service/search_test.go
Summary
As title