Skip to content

Fix runtime db_column mapping for foreign keys#139

Merged
seapagan merged 5 commits intomainfrom
bugfix/db-column-runtime-issue-138
Feb 25, 2026
Merged

Fix runtime db_column mapping for foreign keys#139
seapagan merged 5 commits intomainfrom
bugfix/db-column-runtime-issue-138

Conversation

@seapagan
Copy link
Owner

@seapagan seapagan commented Feb 23, 2026

Summary

  • implement runtime db_column mapping for foreign keys across SQL generation paths
  • ensure CRUD/query operations continue to use model field names in the API while emitting mapped DB column names in SQL
  • add regression tests for custom FK db_column behavior across insert/get/filter/order/update and relationship query paths
  • update FK docs and ORM demo/docs to cover runtime behavior for custom db_column

Implementation

  • add get_model_field_db_column() in sqliter/model/foreign_key.py
  • use mapping helpers in sqliter/sqliter.py for insert/select/update SQL construction
  • use mapping helpers in sqliter/query/query.py for filters, ordering, joins, projections, and query updates

Closes #138

Summary by CodeRabbit

  • New Features

    • Foreign keys now support custom database column names while keeping model field names for code and queries; new demo illustrates this.
  • Documentation

    • Added/expanded guides and examples across API reference and ORM docs showing db_column usage and its runtime behaviour.
  • Bug Fixes

    • Debug SQL output now consistently quotes identifier names for clearer, safer logging.

@coderabbitai
Copy link

coderabbitai bot commented Feb 23, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 817f578 and 58a1e97.

📒 Files selected for processing (1)
  • docs/guide/foreign-keys/orm.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/guide/foreign-keys/orm.md

📝 Walkthrough

Walkthrough

Adds end-to-end runtime support for custom ForeignKey database column names (db_column). Introduces model-field→DB-column resolution helpers, wires them into QueryBuilder and SqliterDB SQL generation (insert/get/update/join/filter), updates docs, demos and tests to validate behaviour.

Changes

Cohort / File(s) Summary
Documentation
docs/api-reference/orm.md, docs/guide/foreign-keys/explicit.md, docs/guide/foreign-keys/orm.md, docs/tui-demo/orm.md
Add explanations and examples for using db_column on ForeignKey fields; clarify model-level names vs physical DB column names and show query/insert/update examples.
Foreign-key metadata
sqliter/model/foreign_key.py
New public helper get_model_field_db_column(model_class, field_name) to resolve model field → physical DB column using FK metadata.
Query builder
sqliter/query/query.py
Add _model_field_to_db_column and _column_sql; centralise column resolution/quoting and replace direct column references across SELECT, JOIN, WHERE, GROUP BY, HAVING, ORDER BY and projection logic.
SqliterDB CRUD
sqliter/sqliter.py
Add _model_field_to_db_column, _map_data_to_db_columns, _build_model_select_list; map insert/update/select data to DB columns and quote identifiers consistently.
TUI demo
sqliter/tui/demos/orm.py
Add demo _run_custom_fk_db_column and register orm_custom_fk_db_column illustrating runtime behaviour with db_column.
Tests — foreign keys
tests/test_foreign_keys.py, tests/test_foreign_keys_orm.py
Add unit/ runtime tests and ORM models (CustomColAuthor, CustomColBook) exercising CRUD, filter/order, select_related, prefetch and update flows with custom FK db_column.
Tests — queries & logging
tests/test_query.py, tests/test_debug_logging.py
Add test for qualification wrapper; update expected debug SQL to use quoted identifiers (e.g., "age", "name").

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client Code
    participant DB as SqliterDB
    participant QB as QueryBuilder
    participant FK as FK Metadata
    participant SQL as SQLite

    Client->>DB: insert(Book, {'title':'T','author_id':123})
    DB->>FK: get_model_field_db_column(Book, 'author_id')
    FK-->>DB: 'author_ref'
    DB->>QB: Build INSERT with mapped columns
    QB->>SQL: INSERT INTO books ("title","author_ref") VALUES (?, ?)
    SQL-->>QB: OK
    QB-->>DB: result

    Client->>DB: get(Book).filter(author_id=123)
    DB->>QB: Build WHERE clause for 'author_id'
    QB->>FK: resolve 'author_id' -> 'author_ref'
    FK-->>QB: 'author_ref'
    QB->>SQL: SELECT ... WHERE "author_ref" = ?
    SQL-->>QB: rows
    QB->>DB: map DB columns back to model fields
    DB-->>Client: Book instance with .author_id
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested labels

enhancement

Poem

🐇 I hop through fields both near and far,
I map your names to columns with a star —
author_id hides as author_ref below,
The ORM still lets your model names show.
Hooray — the rabbit synced the rows and row!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: implementing runtime db_column mapping for foreign keys across the codebase.
Linked Issues check ✅ Passed The PR fully addresses all coding requirements from issue #138: normalises field-to-column mapping in runtime SQL generation, updates insert/update/select/filter/join paths, adds comprehensive regression tests, and maintains existing API compatibility.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing db_column runtime mapping and related documentation/testing. No unrelated refactoring or feature additions detected beyond issue #138 scope.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch bugfix/db-column-runtime-issue-138

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.

@seapagan seapagan self-assigned this Feb 23, 2026
@seapagan seapagan added the bug Something isn't working label Feb 23, 2026
@codacy-production
Copy link

Coverage summary from Codacy

See diff coverage on Codacy

Coverage variation Diff coverage
+0.00% (target: -1.00%) 100.00%
Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (9cfd607) 4792 4792 100.00%
Head commit (817f578) 4869 (+77) 4869 (+77) 100.00% (+0.00%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#139) 105 105 100.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

See your quality gate settings    Change summary preferences

@codacy-production
Copy link

codacy-production bot commented Feb 23, 2026

Coverage summary from Codacy

See diff coverage on Codacy

Coverage variation Diff coverage
+0.00% (target: -1.00%) 100.00%
Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (9cfd607) 4792 4792 100.00%
Head commit (58a1e97) 4869 (+77) 4869 (+77) 100.00% (+0.00%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#139) 105 105 100.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

See your quality gate settings    Change summary preferences

@seapagan seapagan marked this pull request as ready for review February 24, 2026 19:46
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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/guide/foreign-keys/orm.md`:
- Around line 33-35: The sentence "By default the database column is also
`author_id`, but you can override the physical column name with
`db_column=...`." is missing a comma after "By default"; update the sentence in
the docs to read "By default, the database column is also `author_id` ..." so
the phrase "By default" is properly set off (look for the sentence containing
`author_id` and `db_column=...` in the ORM foreign keys paragraph).

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9cfd607 and 817f578.

📒 Files selected for processing (12)
  • docs/api-reference/orm.md
  • docs/guide/foreign-keys/explicit.md
  • docs/guide/foreign-keys/orm.md
  • docs/tui-demo/orm.md
  • sqliter/model/foreign_key.py
  • sqliter/query/query.py
  • sqliter/sqliter.py
  • sqliter/tui/demos/orm.py
  • tests/test_debug_logging.py
  • tests/test_foreign_keys.py
  • tests/test_foreign_keys_orm.py
  • tests/test_query.py

@seapagan seapagan merged commit 78be73d into main Feb 25, 2026
15 checks passed
@seapagan seapagan deleted the bugfix/db-column-runtime-issue-138 branch February 25, 2026 19:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support db_column across ORM runtime CRUD and query paths

1 participant