Skip to content

✨ add support for deferred foreign keys via -D/--defer-foreign-keys #101

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

Open
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

techouse
Copy link
Owner

This pull request introduces a new feature to defer foreign key constraints during the transfer process from MySQL to SQLite, along with validation for foreign key constraints after the transfer. It also includes related updates to the CLI, transporter logic, and type definitions. Below is a summary of the most important changes:

New Feature: Deferred Foreign Key Constraints

  • Added a new CLI option -D/--defer-foreign-keys to allow deferring foreign key constraints until the end of the transfer. This ensures better handling of foreign key dependencies during the transfer process. (src/mysql_to_sqlite3/cli.py, [1] [2] [3]

  • Updated the transporter logic to support the defer_foreign_keys option. If enabled, foreign keys are marked as DEFERRABLE INITIALLY DEFERRED in the generated SQLite schema, provided the SQLite version supports it. (src/mysql_to_sqlite3/transporter.py, [1] [2]

Validation of Foreign Key Constraints

  • Added validation for foreign key constraints after the transfer is complete. If violations are detected, they are logged with details about the affected tables and rows. (src/mysql_to_sqlite3/transporter.py, src/mysql_to_sqlite3/transporter.pyR770-R795)

Type Definitions and Tests

  • Updated type definitions in MySQLtoSQLiteParams and MySQLtoSQLiteAttributes to include the new defer_foreign_keys attribute. (src/mysql_to_sqlite3/types.py, [1] [2]

  • Updated unit tests to verify the behavior of foreign key validation by replacing the call to PRAGMA foreign_keys=ON with PRAGMA foreign_key_check. (tests/unit/test_transporter.py, tests/unit/test_transporter.pyL153-R153)

@techouse techouse self-assigned this Jul 14, 2025
@techouse techouse added the enhancement New feature or request label Jul 14, 2025
Copy link

coderabbitai bot commented Jul 14, 2025

Walkthrough

A new CLI flag --defer-foreign-keys (-D) was introduced to optionally defer foreign key constraints in the MySQL-to-SQLite conversion process. The transporter logic was updated to support deferrable constraints, validate them post-transfer, and warn about violations. Type definitions and unit tests were extended to cover these changes and additional default value translations.

Changes

File(s) Change Summary
src/mysql_to_sqlite3/cli.py Added --defer-foreign-keys (-D) CLI flag and parameter; updated logic for foreign key handling in the cli function.
src/mysql_to_sqlite3/transporter.py Added _defer_foreign_keys attribute; CREATE TABLE statements now support "DEFERRABLE INITIALLY DEFERRED"; added post-transfer foreign key validation and warnings.
src/mysql_to_sqlite3/types.py Added defer_foreign_keys to MySQLtoSQLiteParams and _defer_foreign_keys to MySQLtoSQLiteAttributes.
tests/unit/test_transporter.py Modified test for foreign key check; added tests for MySQL time function default value translations in the transporter.

Sequence Diagram(s)

sequenceDiagram
    participant User as User
    participant CLI as CLI
    participant Transporter as MySQLtoSQLite
    participant SQLite as SQLite DB

    User->>CLI: Run with --defer-foreign-keys
    CLI->>Transporter: Instantiate with defer_foreign_keys=True
    Transporter->>SQLite: Create tables (DEFERRABLE INITIALLY DEFERRED)
    Transporter->>SQLite: Transfer data
    Transporter->>SQLite: PRAGMA foreign_keys=ON
    Transporter->>SQLite: PRAGMA foreign_key_check
    SQLite-->>Transporter: Return violations (if any)
    Transporter->>CLI: Log warnings/info about violations
Loading

Poem

A bunny hops with careful cheer,
Deferring keys, the path is clear.
Constraints on hold, then checked anew,
With warnings logged for every clue.
Now time defaults translate just right—
The transfer’s safe, the future bright!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab601c3 and 3f33614.

📒 Files selected for processing (4)
  • src/mysql_to_sqlite3/cli.py (3 hunks)
  • src/mysql_to_sqlite3/transporter.py (3 hunks)
  • src/mysql_to_sqlite3/types.py (2 hunks)
  • tests/unit/test_transporter.py (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/unit/test_transporter.py (1)
src/mysql_to_sqlite3/transporter.py (2)
  • MySQLtoSQLite (35-800)
  • _translate_default_from_mysql_to_sqlite (279-380)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (9)
src/mysql_to_sqlite3/types.py (1)

38-38: LGTM: Type definitions are correctly added.

The new defer_foreign_keys parameter in MySQLtoSQLiteParams and corresponding _defer_foreign_keys attribute in MySQLtoSQLiteAttributes are appropriately typed and positioned consistently with the existing foreign key-related attributes.

Also applies to: 75-75

src/mysql_to_sqlite3/cli.py (3)

96-98: LGTM: CLI option correctly defined.

The new -D/--defer-foreign-keys option is properly defined with appropriate help text.


170-170: LGTM: Function signature updated correctly.

The defer_foreign_keys parameter is properly added to the function signature.


219-223: LGTM: Conditional logic for defer_foreign_keys is correct.

The logic appropriately disables deferred foreign keys when:

  • Foreign keys are disabled entirely (without_foreign_keys is True)
  • Specific tables are selected (mysql_tables is specified), which inherently disables foreign keys

This ensures deferred foreign keys are only enabled when it makes sense.

tests/unit/test_transporter.py (2)

153-153: LGTM: Test updated to match new validation logic.

The test correctly verifies that PRAGMA foreign_key_check is executed in the finally block, which aligns with the new foreign key validation step added to the transporter.


229-251: LGTM: Comprehensive test coverage for default value translations.

The new tests thoroughly cover various MySQL time function translations with different case variations, ensuring robustness of the _translate_default_from_mysql_to_sqlite method.

src/mysql_to_sqlite3/transporter.py (3)

98-106: LGTM: Proper initialization of defer_foreign_keys with version check.

The logic correctly:

  • Only enables deferred foreign keys when appropriate conditions are met
  • Includes a SQLite version check for DEFERRABLE support (≥3.6.19)
  • Logs a helpful warning if the SQLite version is too old
  • Forces the feature off when foreign keys are disabled or specific tables are selected

570-576: LGTM: Foreign key SQL generation with deferrable clause.

The code correctly adds the "DEFERRABLE INITIALLY DEFERRED" clause to foreign key constraints when _defer_foreign_keys is enabled. The formatting and placement are appropriate.


770-794: LGTM: Comprehensive foreign key validation implementation.

The validation logic is well-implemented:

  • Executes PRAGMA foreign_key_check after re-enabling foreign keys
  • Provides detailed logging for violations including table, row, referenced table, and constraint information
  • Properly handles both success and error cases
  • Maintains appropriate log levels (warning for violations, info for success)
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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>, please review it.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 using 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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

codecov bot commented Jul 14, 2025

Codecov Report

Attention: Patch coverage is 76.19048% with 5 lines in your changes missing coverage. Please review.

Project coverage is 93.82%. Comparing base (ab601c3) to head (3f33614).

Files with missing lines Patch % Lines
src/mysql_to_sqlite3/transporter.py 72.22% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #101      +/-   ##
==========================================
- Coverage   94.40%   93.82%   -0.58%     
==========================================
  Files           8        8              
  Lines         643      664      +21     
==========================================
+ Hits          607      623      +16     
- Misses         36       41       +5     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…ng of MariaDB-specific default translations (`curtime()`, `curdate()`, `current_timestamp()`, and `now()`)
@techouse techouse mentioned this pull request Jul 16, 2025
@techouse techouse marked this pull request as ready for review July 16, 2025 18:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant