Skip to content

Foreign Key Navigation

Temp edited this page Nov 4, 2025 · 1 revision

Foreign Key Navigation

Foreign Key Navigation is a powerful feature in D1 Database Manager that allows you to seamlessly navigate between related tables by clicking on foreign key values. This feature dramatically improves workflow efficiency when exploring relational data.

Overview

When viewing table data, columns that are foreign keys are automatically detected and displayed as clickable links with visual indicators. Clicking a foreign key value instantly navigates to the referenced table with an automatic filter applied to show only the related records.

Key Features

πŸ”— Clickable Foreign Key Values

  • Foreign key columns are automatically identified using PRAGMA foreign_key_list()
  • FK values display as interactive buttons with a link icon (πŸ”—)
  • Hover tooltips show the referenced table and column (e.g., "References customers.id")
  • NULL foreign key values are not clickable and display as regular NULL values

🍞 Breadcrumb Trail

The breadcrumb navigation appears at the top of the table view when you've navigated via foreign keys:

Database > orders > customers > addresses
  • Home Icon: Click the database name to return to the database table list
  • Table Segments: Each table in your navigation path is clickable
  • Current Table: The current table is highlighted and non-clickable
  • Overflow Handling: Only the last 5 tables are shown; earlier tables are indicated with "..."

πŸ” Auto-Filtering

When you navigate via a foreign key:

  1. The target table automatically opens
  2. A filter is applied to the referenced column matching the clicked value
  3. The filter bar shows automatically with the applied filter
  4. You see only the relevant records related to your starting point

Example: Click customer_id = 42 in the orders table:

  • Navigates to the customers table
  • Automatically filters to WHERE id = 42
  • Shows only the customer with ID 42

⌨️ Keyboard Shortcuts

  • Alt + Left Arrow: Navigate back to the previous table in your history
  • Works at any depth in your navigation history
  • Preserves filters from each navigation step

🎨 Visual Indicators

Foreign key columns are visually distinct:

  • Link Icon (πŸ”—): Indicates the column is a foreign key
  • Blue Border: FK values have a subtle blue border
  • Hover Effect: Highlights on hover to indicate clickability
  • Primary Color: FK values use the primary theme color

How It Works

1. Automatic Detection

When you open a table view:

PRAGMA foreign_key_list("table_name")

This query returns all foreign key relationships for the table, which the UI uses to identify FK columns.

2. Navigation Flow

Example Scenario: E-commerce database

products (id, category_id, supplier_id)
  β”œβ”€ category_id β†’ categories(id)
  └─ supplier_id β†’ suppliers(id)

orders (id, customer_id, product_id)
  β”œβ”€ customer_id β†’ customers(id)
  └─ product_id β†’ products(id)

User Action: View the orders table and click customer_id = 15

  1. Detects: customer_id is FK to customers.id
  2. Navigates: To customers table
  3. Filters: WHERE id = 15
  4. Updates History: orders β†’ customers
  5. Shows Breadcrumb: Database > orders > customers

Next: From customers, click address_id = 203

  1. Navigates: To addresses table
  2. Filters: WHERE id = 203
  3. Updates History: orders β†’ customers β†’ addresses
  4. Shows Breadcrumb: Database > orders > customers > addresses

3. Back Navigation

You can navigate back using:

  • Breadcrumb Segments: Click any table name in the breadcrumb
  • Back Button: Arrow icon in the breadcrumb bar
  • Keyboard: Alt + Left Arrow
  • Header Back Button: Returns to the database table list (clears history)

Use Cases

Data Exploration

Navigate through related records without writing queries:

orders β†’ customers β†’ addresses β†’ countries

Track a full customer journey from order to their location.

Debugging Relationships

Verify foreign key relationships are correct:

  1. View an order with customer_id = 99
  2. Click the FK to see if customer 99 exists
  3. Verify the customer data is correct

Data Auditing

Follow data trails for auditing purposes:

invoices β†’ orders β†’ line_items β†’ products β†’ categories

Trace an invoice back to its product categories.

Customer Support

When investigating a customer issue:

support_tickets β†’ customers β†’ orders β†’ payments

Quickly access all related information about a customer.

Edge Cases and Limitations

NULL Foreign Keys

  • Behavior: NULL FK values are not clickable
  • Display: Shows as gray italic "NULL" text
  • Reason: No target record to navigate to

Composite Foreign Keys

  • Current Support: Each column in a composite FK is clickable individually
  • Future: May add grouped navigation for composite FKs

Self-Referential Foreign Keys

  • Support: Works correctly (e.g., employees.manager_id β†’ employees.id)
  • Navigation: Can navigate from employee to their manager in the same table
  • Cycle Detection: Not currently implemented

Circular Dependencies

  • Current: No automatic cycle detection
  • Behavior: You can navigate in circles indefinitely
  • Workaround: Use breadcrumbs to return to a previous point

Maximum History Depth

  • Breadcrumb Display: Last 5 tables only
  • Internal History: Up to 20 tables stored (prevents memory issues)
  • Overflow: Older entries automatically removed

Tips and Best Practices

1. Use Breadcrumbs for Quick Navigation

Instead of clicking back multiple times, click directly on the table you want in the breadcrumb trail.

2. Clear Filters When Needed

After navigating via FK, you may want to see the entire target table:

  • Click "Clear All" in the filter bar
  • The breadcrumb history remains intact

3. Combine with Regular Filters

FK filters and regular filters work together:

  • Navigate via FK to get initial filter
  • Add additional filters to narrow results further

4. Keyboard Efficiency

Use Alt+Left repeatedly to quickly navigate back through your entire history.

5. Watch the Status Indicator

The table subtitle shows: β€’ Navigated from FK when you're in FK navigation mode.

API Endpoints

The feature uses these endpoints:

Get Foreign Keys for a Table

GET /api/tables/:dbId/foreign-keys/:tableName

Response:

{
  "result": {
    "foreignKeys": [
      {
        "column": "customer_id",
        "refTable": "customers",
        "refColumn": "id",
        "onDelete": "CASCADE",
        "onUpdate": "NO ACTION"
      }
    ]
  },
  "success": true
}

Get Table Data with FK Filter

GET /api/tables/:dbId/data/:tableName?fkFilter=id:42

The fkFilter parameter format: column:value

Troubleshooting

Foreign Keys Not Clickable

Possible Causes:

  1. Foreign key constraints not defined in the database
  2. Table has no foreign keys
  3. Value is NULL

Check: Run PRAGMA foreign_key_list("table_name") in the Query Console

Navigation Not Working

Check:

  1. Referenced table exists in the database
  2. You have permissions to view the target table
  3. Browser console for JavaScript errors

Breadcrumbs Not Showing

Expected: Breadcrumbs only appear when navigationHistory has entries

  • First table you view: No breadcrumb (starting point)
  • After first FK navigation: Breadcrumb appears

Filter Not Auto-Applying

Check:

  1. fkFilter parameter in URL
  2. Column name matches in target table
  3. Filter bar is enabled

Performance Considerations

Foreign Key Detection

  • Timing: Runs once when table loads
  • Caching: FK metadata is cached per table
  • Impact: Minimal (<50ms typically)

Navigation Speed

  • Instant UI Update: Navigation state changes immediately
  • Data Load: Standard table data fetch time
  • Filter Application: Server-side WHERE clause (efficient)

Memory Usage

  • History Limit: Max 20 tables prevents memory leaks
  • Cleanup: Automatic removal of old entries
  • Browser Storage: Not persisted (clears on page reload)

Security

SQL Injection Protection

  • Column Names: Sanitized using sanitizeIdentifier()
  • Filter Values: Properly escaped in WHERE clauses
  • Validation: All inputs validated before query execution

Permission Checking

  • Table Access: Standard table permissions apply
  • No Bypass: FK navigation doesn't grant additional permissions
  • Auth Required: Same authentication as regular table access

Future Enhancements

Planned improvements to FK Navigation:

  1. Circular Dependency Detection: Warn users when navigating in cycles
  2. Composite FK Grouping: Navigate using multiple columns together
  3. Reverse Navigation: Quick links to see all records referencing current row
  4. Navigation History Export: Save navigation paths for documentation
  5. Smart Breadcrumb Shortcuts: Jump to commonly visited tables

Related Features

Examples

E-Commerce Example

Database schema:

CREATE TABLE customers (
  id INTEGER PRIMARY KEY,
  name TEXT
);

CREATE TABLE orders (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER,
  FOREIGN KEY (customer_id) REFERENCES customers(id)
);

CREATE TABLE order_items (
  id INTEGER PRIMARY KEY,
  order_id INTEGER,
  product_id INTEGER,
  FOREIGN KEY (order_id) REFERENCES orders(id),
  FOREIGN KEY (product_id) REFERENCES products(id)
);

Navigation Path:

  1. View orders table
  2. Click customer_id = 5 β†’ Navigates to customers filtered to ID 5
  3. View customer details
  4. Use breadcrumb to return to orders
  5. Click different customer_id to explore another customer

Social Network Example

CREATE TABLE users (
  id INTEGER PRIMARY KEY,
  name TEXT
);

CREATE TABLE posts (
  id INTEGER PRIMARY KEY,
  user_id INTEGER,
  FOREIGN KEY (user_id) REFERENCES users(id)
);

CREATE TABLE comments (
  id INTEGER PRIMARY KEY,
  post_id INTEGER,
  user_id INTEGER,
  FOREIGN KEY (post_id) REFERENCES posts(id),
  FOREIGN KEY (user_id) REFERENCES users(id)
);

Workflow: Investigate a comment

  1. Start at comments table
  2. Click user_id β†’ See who wrote the comment
  3. Back to comments
  4. Click post_id β†’ See the original post
  5. From posts, click user_id β†’ See post author
  6. Breadcrumb shows: Database > comments > posts > users

Conclusion

Foreign Key Navigation transforms the way you explore relational data in D1 Database Manager. By making foreign keys clickable and maintaining a breadcrumb trail, you can quickly traverse complex database relationships without writing a single SQL query.

Key Benefits:

  • ⚑ Faster data exploration
  • 🎯 Better understanding of relationships
  • πŸ” Easier debugging and auditing
  • πŸ“Š More intuitive user experience
  • ⌨️ Keyboard-friendly workflow

For questions or issues, visit the GitHub Issues page.

Clone this wiki locally