Skip to content

Conversation

@mdroidian
Copy link
Contributor

@mdroidian mdroidian commented Oct 13, 2025

Example DX improvement (one of many options)

Before
image
image

After
image

image image

Summary by CodeRabbit

  • Refactor
    • Updated database query system with structured filtering parameters for improved consistency and maintainability.
    • Added new utility functions to streamline common query patterns and reduce redundancy.

@linear
Copy link

linear bot commented Oct 13, 2025

@supabase
Copy link

supabase bot commented Oct 13, 2025

This pull request has been ignored for the connected project zytfjzqyijgagqxrzbmz because there are no changes detected in packages/database/supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@maparent
Copy link
Collaborator

@mdroidian I made a lot of changes. Ideally you should review them, but it seems I cannot make you a reviewer since you're the author. Should I make another branch?

@maparent maparent marked this pull request as ready for review October 16, 2025 17:24
@mdroidian
Copy link
Contributor Author

@mdroidian I made a lot of changes. Ideally you should review them, but it seems I cannot make you a reviewer since you're the author. Should I make another branch?

Looks like it still shows up in my queue, so we are good.

@maparent maparent force-pushed the eng-960-improve-dx-for-base-dg-queries branch 2 times, most recently from 3a4244c to 745edfc Compare October 17, 2025 13:27
@maparent maparent force-pushed the eng-960-improve-dx-for-base-dg-queries branch from 3c741ae to bffce97 Compare October 18, 2025 12:39
@mdroidian
Copy link
Contributor Author

@coderabbitai full review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 20, 2025

✅ Actions performed

Full review triggered.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 20, 2025

📝 Walkthrough

Walkthrough

This PR refactors the concept querying API from ad-hoc parameters to a unified, scope-based structure. New types and helper functions are introduced to provide structured filtering, field selection, and pagination. Existing call sites are updated to use the new GetConceptsParams shape, replacing individual parameter flags with nested scope, relations, and fields objects.

Changes

Cohort / File(s) Summary
Query API refactoring
packages/database/src/lib/queries.ts
Introduces grouped query API with new types (NodeFilters, RelationFilters, FieldSelection, PaginationOptions, GetConceptsParams) and helper functions (getAllNodes, getNodesByType, getAllRelations, getRelationsFromNodeType, getDiscourseContext). Updates getConcepts signature to accept structured GetConceptsParams. Refactors composeConceptQuery and internal query builders to handle scope, relations, fields, and pagination. Adds CONCEPT_FIELDS_MINIMAL constant.
Component updates
apps/roam/src/components/settings/AdminPanel.tsx
Replaces getConcepts call parameter from schemaLocalIds to scope-based filter with type, ofType, and schemas fields derived from schema comparison.
Test scenario updates
packages/database/features/queryConcepts.feature
Migrates test parameters from individual flags (fetchNodes, schemaLocalIds, nodeAuthor, inRelsOfTypeLocal, etc.) to unified scope object structure with nested relations, ofType, author, and type properties.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

The refactor introduces a new grouped API surface with multiple new types and functions, requiring verification across call sites and test scenarios. While many test updates follow repetitive patterns, the core refactoring in queries.ts is dense with structural logic changes, nested type definitions, and updated internal query composition. The heterogeneous nature of changes—spanning type definitions, function signatures, internal logic, and multiple call sites—adds complexity.

Possibly related PRs

Pre-merge checks

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "ENG-960 Improve DX for base DG queries" directly captures the main objective of the changeset. The primary changes introduce a grouped, structured API for querying concepts with new types (NodeFilters, RelationFilters, FieldSelection, PaginationOptions, GetConceptsParams), new public helper functions (getAllNodes, getNodesByType, getAllRelations, getRelationsFromNodeType, getDiscourseContext), and refactored query logic—all designed to enhance the developer experience when working with base DG queries. The title is concise, clear, and specific enough that a teammate scanning history would understand the intent without being overly broad or vague.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/database/src/lib/queries.ts (2)

391-398: Off-by-one in pagination; Supabase range end is inclusive.

range(offset, offset + limit) returns limit+1 rows.

-    if (offset > 0) {
-      query = query.range(offset, offset + limit);
-    } else if (limit > 0) {
+    if (offset > 0) {
+      const to = Math.max(offset, offset + limit - 1);
+      query = query.range(offset, to);
+    } else if (limit > 0) {
       query = query.limit(limit);
     }

449-506: Cache key collision across spaces for local IDs.

NODE_SCHEMA_CACHE is keyed only by source_local_id. If two spaces share a localId, mapping can resolve to the wrong dbId and yield empty results under space filters.

Suggested direction (no full patch): key by spaceId+localId, e.g., ${spaceId}:${localId}, and adapt getSchemaConcepts/getLocalToDbIdMapping to read/write using that composite key. Alternatively, keep current keys but validate entry.spaceId === requested spaceId before using; treat mismatches as cache miss.

🧹 Nitpick comments (4)
packages/database/src/lib/queries.ts (2)

19-27: Docs reference nonexistent getRelationsFromNode.

Replace with getDiscourseContext or getRelationsFromNodeType (after the fix above).

-// // Query a specific node and its relations
-// const relations = await getRelationsFromNode({
-//   supabase, spaceId, nodeIds: ["node-123"]
-// });
+// // Query a specific node and its relations
+// const context = await getDiscourseContext({
+//   supabase, spaceId, nodeIds: ["node-123"]
+// });

69-73: Use forEach for side effects (tiny nit).

map’s return value is ignored.

-  Object.keys(NODE_SCHEMA_CACHE).map((k) => {
+  Object.keys(NODE_SCHEMA_CACHE).forEach((k) => {
     if (k !== NODE_SCHEMAS) delete NODE_SCHEMA_CACHE[k];
-  });
+  });
apps/roam/src/components/settings/AdminPanel.tsx (1)

163-169: Leverage helper API for clarity.

You can simplify with getNodesByType (and a dedicated helper for schemas if desired), improving readability and consistency with the new DX helpers.

Example:

const fetch = showingSchema.sourceLocalId === nodeSchemaSignature.sourceLocalId
  ? getConcepts({ supabase, spaceId, scope: { schemas: true } })
  : getNodesByType({ supabase, spaceId, ofType: [showingSchema.sourceLocalId] });
packages/database/features/queryConcepts.feature (1)

50-114: Add pagination scenarios to guard against range off-by-one.

Include cases like limit=2, offset=2 to pin the inclusive range semantics and prevent regressions.

You can add:

Scenario: Query with pagination
  And a user logged in space s1 and calling getConcepts with these parameters: '{"scope":{"type":"all"},"pagination":{"limit":2,"offset":2}}'
  Then exactly 2 results are returned
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e386761 and bffce97.

📒 Files selected for processing (3)
  • apps/roam/src/components/settings/AdminPanel.tsx (1 hunks)
  • packages/database/features/queryConcepts.feature (2 hunks)
  • packages/database/src/lib/queries.ts (9 hunks)

Comment on lines 104 to 121
/**
* Defines what type of concepts to query and any specific constraints.
*
* @example
* ```typescript
* // Query all nodes of specific types
* { type: "nodes", ofSchemaLocal: ["page", "note"] }
*
* // Query all relations
* { type: "relations" }
*
* // Query specific nodes by their local IDs
* { type: "nodes", nodeIds: ["node-123", "node-456"] }
*
* // Query relation schemas
* { type: "relations", schemas: true }
* ```
*/
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 | 🟡 Minor

JSDoc example property mismatch (‘ofSchemaLocal’ → ‘ofType’).

Example uses ofSchemaLocal, but the API is ofType: string[].

- * { type: "nodes", ofSchemaLocal: ["page", "note"] }
+ * { type: "nodes", ofType: ["page", "note"] }
📝 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
/**
* Defines what type of concepts to query and any specific constraints.
*
* @example
* ```typescript
* // Query all nodes of specific types
* { type: "nodes", ofSchemaLocal: ["page", "note"] }
*
* // Query all relations
* { type: "relations" }
*
* // Query specific nodes by their local IDs
* { type: "nodes", nodeIds: ["node-123", "node-456"] }
*
* // Query relation schemas
* { type: "relations", schemas: true }
* ```
*/
/**
* Defines what type of concepts to query and any specific constraints.
*
* @example
*
🤖 Prompt for AI Agents
In packages/database/src/lib/queries.ts around lines 104 to 121, the JSDoc
examples reference the non-existent property ofSchemaLocal but the API expects
ofType: string[]; update all examples and any explanatory text to use ofType
instead of ofSchemaLocal, adjust example values to match the ofType shape (e.g.,
ofType: ["page", "note"]) and verify the types described in the comment match
the actual function/type definitions.

Comment on lines 228 to 238
* @example
* ```typescript
* const results = await getConcepts({
* supabase,
* spaceId: 123,
* scope: { type: "nodes", ofTypes: ["page"] },
* relations: { ofType: ["cites"] },
* author: "user123",
* pagination: { limit: 50 }
* });
* ```
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 | 🟡 Minor

JSDoc example typo (‘ofTypes’ → ‘ofType’).

Avoid confusing callers.

- *   scope: { type: "nodes", ofTypes: ["page"] },
+ *   scope: { type: "nodes", ofType: ["page"] },
📝 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
* @example
* ```typescript
* const results = await getConcepts({
* supabase,
* spaceId: 123,
* scope: { type: "nodes", ofTypes: ["page"] },
* relations: { ofType: ["cites"] },
* author: "user123",
* pagination: { limit: 50 }
* });
* ```
* @example
*
🤖 Prompt for AI Agents
In packages/database/src/lib/queries.ts around lines 228 to 238, the JSDoc
example uses the incorrect property name `ofTypes` for the `scope` object (it
should be `ofType`), which can confuse callers; update the example to use
`scope: { type: "nodes", ofType: ["page"] }` so it matches the function's
expected parameter shape and any type definitions or runtime checks.

@mdroidian
Copy link
Contributor Author

@mdroidian I made a lot of changes. Ideally you should review them, but it seems I cannot make you a reviewer since you're the author. Should I make another branch?

@maparent Looks good to me

@maparent maparent merged commit 7fab503 into main Oct 26, 2025
5 checks passed
@github-project-automation github-project-automation bot moved this to Done in General Oct 26, 2025
@maparent maparent deleted the eng-960-improve-dx-for-base-dg-queries branch October 27, 2025 00:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

No open projects
Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants