Skip to content

fix: set not null on some columns #930

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

Merged
merged 3 commits into from
May 22, 2025
Merged

fix: set not null on some columns #930

merged 3 commits into from
May 22, 2025

Conversation

gfyrag
Copy link
Contributor

@gfyrag gfyrag commented May 19, 2025

Fixes LX-42

@gfyrag gfyrag requested a review from a team as a code owner May 19, 2025 14:06
Copy link

coderabbitai bot commented May 19, 2025

Walkthrough

This pull request updates two SQL migration scripts. The first script changes trigger creation on the transactions and accounts tables to use CREATE OR REPLACE TRIGGER and adjusts a null check condition. The second script enforces NOT NULL constraints on four columns in the transactions table using a safe, staged approach.

Changes

File(s) Change Summary
internal/storage/bucket/migrations/39-clean-useless-features/up.sql Replaces explicit dropping of triggers with CREATE OR REPLACE TRIGGER and modifies a null check condition.
internal/storage/bucket/migrations/40-refine-columns-types/up.sql Adds NOT NULL constraints to four columns in transactions using a multi-step, non-blocking migration process.

Sequence Diagram(s)

sequenceDiagram
    participant Migration
    participant DB

    Migration->>DB: Set search_path to target schema
    loop For each ledger
        Migration->>DB: CREATE OR REPLACE TRIGGER on transactions/accounts
    end
    Note over Migration,DB: Triggers created or replaced as needed
Loading
sequenceDiagram
    participant Migration
    participant DB

    Migration->>DB: BEGIN TRANSACTION
    loop For each column in [sources, destinations, sources_arrays, destinations_arrays]
        Migration->>DB: ADD CHECK constraint (NOT VALID)
        Migration->>DB: VALIDATE constraint
        Migration->>DB: ALTER COLUMN SET NOT NULL
        Migration->>DB: DROP CHECK constraint
    end
    Migration->>DB: COMMIT
Loading

Assessment against linked issues

Objective Addressed Explanation
Set columns sources, destinations, sources_arrays and destinations_arrays to not null (LX-42)

Possibly related PRs

  • fix: migrations with pg 13 #724: Both PRs address trigger management strategies, with this PR switching to CREATE OR REPLACE TRIGGER while the related PR uses explicit dropping before creation.

Suggested reviewers

  • paul-nicolas
  • flemzord

Poem

A hop and a skip through columns and rows,
Triggers replaced where the data flows.
NULLs are banished, constraints hold tight,
Migrations marching through the night.
With every hop, the schema’s bright—
🐇 SQL dreams tucked in just right!

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 30th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


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.

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 May 19, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 82.38%. Comparing base (307caa3) to head (051f884).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #930      +/-   ##
==========================================
+ Coverage   82.34%   82.38%   +0.03%     
==========================================
  Files         141      141              
  Lines        7823     7823              
==========================================
+ Hits         6442     6445       +3     
+ Misses       1056     1054       -2     
+ Partials      325      324       -1     

☔ 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@gfyrag gfyrag force-pushed the chore/remove-useless-features branch from 9fb2656 to 89f2939 Compare May 21, 2025 07:39
@gfyrag gfyrag force-pushed the feat/set-not-null-columns branch from 6bffbda to 982a5b7 Compare May 21, 2025 07:40
@gfyrag gfyrag force-pushed the chore/remove-useless-features branch from 89f2939 to 13c599c Compare May 21, 2025 07:43
@gfyrag gfyrag force-pushed the feat/set-not-null-columns branch 2 times, most recently from 949c34f to e6d8e93 Compare May 21, 2025 07:46
@gfyrag gfyrag force-pushed the chore/remove-useless-features branch from 13c599c to 692d742 Compare May 21, 2025 09:34
@gfyrag gfyrag force-pushed the feat/set-not-null-columns branch from e6d8e93 to 71f9762 Compare May 21, 2025 09:34
@gfyrag gfyrag force-pushed the feat/set-not-null-columns branch from 1f2ac29 to ffc3cf8 Compare May 22, 2025 07:48
@gfyrag gfyrag force-pushed the chore/remove-useless-features branch from 692d742 to f30eb39 Compare May 22, 2025 09:29
@gfyrag gfyrag force-pushed the feat/set-not-null-columns branch from ffc3cf8 to 66d9fea Compare May 22, 2025 09:30
Base automatically changed from chore/remove-useless-features to main May 22, 2025 10:48
@gfyrag gfyrag enabled auto-merge May 22, 2025 10:48
@gfyrag gfyrag force-pushed the feat/set-not-null-columns branch from 66d9fea to 051f884 Compare May 22, 2025 10:49
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

♻️ Duplicate comments (5)
internal/storage/bucket/migrations/39-clean-useless-features/up.sql (2)

15-15: Duplicate: apply safe dynamic SQL assembly here as well
Same pattern applies to the accounts_set_address_array trigger—use format() with %I/%L instead of manual concatenation.


18-18: Duplicate: apply safe dynamic SQL assembly here too
Also update the transaction_set_addresses_segments trigger to use format() and proper quoting.

internal/storage/bucket/migrations/40-refine-columns-types/up.sql (3)

19-31: Duplicate: consider the same DRY refactor for destinations block
Reapply the loop-based approach and IF EXISTS drop recommendation here.


33-45: Duplicate: consider the same DRY refactor for sources_arrays block
Reapply the loop-based approach and IF EXISTS drop recommendation here.


47-59: Duplicate: consider the same DRY refactor for destinations_arrays block
Reapply the loop-based approach and IF EXISTS drop recommendation here.

🧹 Nitpick comments (1)
internal/storage/bucket/migrations/40-refine-columns-types/up.sql (1)

5-17: DRY repetitive NOT NULL enforcement with a loop and add IF EXISTS on drops
Each column follows the same 4-step pattern. You can reduce duplication by iterating over an array of column names and using format(). Also, make the DROP CONSTRAINT idempotent with IF EXISTS.

Example refactor snippet:

-do $$
-begin
-  set search_path = '{{ .Schema }}';
-  -- short-time exclusive lock
-  alter table transactions
-    add constraint sources_not_null
-    check (sources is not null) not valid;
-  ...
-  alter table transactions drop constraint sources_not_null;
-end
-$$;
+do $$
+declare
+  col text;
+begin
+  set search_path = '{{ .Schema }}';
+  for col in array['sources','destinations','sources_arrays','destinations_arrays'] loop
+    execute format($f$
+      ALTER TABLE transactions ADD CONSTRAINT %I_not_null CHECK (%I IS NOT NULL) NOT VALID;
+      ALTER TABLE transactions VALIDATE CONSTRAINT %I_not_null;
+      ALTER TABLE transactions ALTER COLUMN %I SET NOT NULL;
+      ALTER TABLE transactions DROP CONSTRAINT IF EXISTS %I_not_null;
+    $f$, col, col, col, col, col);
+  end loop;
+end
+$$;
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 307caa3 and 051f884.

⛔ Files ignored due to path filters (1)
  • internal/storage/bucket/migrations/40-refine-columns-types/notes.yaml is excluded by !**/*.yaml
📒 Files selected for processing (2)
  • internal/storage/bucket/migrations/39-clean-useless-features/up.sql (1 hunks)
  • internal/storage/bucket/migrations/40-refine-columns-types/up.sql (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Dirty
  • GitHub Check: Tests

-- recreate trigger but with a check on sources is null for transactions and address_array is null for accounts
-- this way, the 2.2 (which use triggers) continuer to work, and the 2.3 which does not need them can work too
-- todo(next minor / 2.4): remove triggers and associated functions
for ledger in select * from _system.ledgers where bucket = current_schema loop
vsql = 'create trigger "transaction_set_addresses_' || ledger.id || '" before insert on transactions for each row when (new.ledger = ''' || ledger.name || ''' and new.sources is null) execute procedure set_transaction_addresses()';
vsql = 'create or replace trigger "transaction_set_addresses_' || ledger.id || '" before insert on transactions for each row when (new.ledger = ''' || ledger.name || ''' and new.sources is null) execute procedure set_transaction_addresses()';
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use format() with quote_ident/quote_literal for safer dynamic SQL
Concatenating ledger.name directly can break or allow SQL injection if the ledger name contains quotes or special characters. Prefer format() and the %I/%L specifiers:

-   vsql = 'create or replace trigger "transaction_set_addresses_' || ledger.id || 
-          '" before insert on transactions for each row when (new.ledger = ''' || 
-          ledger.name || ''' and new.sources is null) execute procedure set_transaction_addresses()';
+   vsql := format(
+     $f$CREATE OR REPLACE TRIGGER "transaction_set_addresses_%s"
+       BEFORE INSERT ON transactions
+       FOR EACH ROW 
+       WHEN (NEW.ledger = %L AND NEW.sources IS NULL)
+       EXECUTE PROCEDURE set_transaction_addresses()$f$,
+     ledger.id,
+     ledger.name
+   );
📝 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
vsql = 'create or replace trigger "transaction_set_addresses_' || ledger.id || '" before insert on transactions for each row when (new.ledger = ''' || ledger.name || ''' and new.sources is null) execute procedure set_transaction_addresses()';
-- replace manual concatenation with format() for safe quoting
vsql := format(
$f$CREATE OR REPLACE TRIGGER "transaction_set_addresses_%s"
BEFORE INSERT ON transactions
FOR EACH ROW
WHEN (NEW.ledger = %L AND NEW.sources IS NULL)
EXECUTE PROCEDURE set_transaction_addresses()$f$,
ledger.id,
ledger.name
);
🤖 Prompt for AI Agents
In internal/storage/bucket/migrations/39-clean-useless-features/up.sql at line
12, the dynamic SQL concatenates ledger.name directly, risking SQL injection or
syntax errors with special characters. Replace the string concatenation with the
use of the format() function, applying %I for identifiers and %L for literals to
safely quote ledger.id and ledger.name within the trigger creation statement.

@gfyrag gfyrag added this pull request to the merge queue May 22, 2025
Merged via the queue into main with commit 738d6b0 May 22, 2025
10 checks passed
@gfyrag gfyrag deleted the feat/set-not-null-columns branch May 22, 2025 11:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants