← Back to Pull requests

Reject `old_value` inside MariaDB expressions at compile time #5252

Merged
LucaCappelletti94 merged 20 files (1571 lines) on Sep 30, 2026 13:30 UTC
View on GitHub
LucaCappelletti94 LucaCappelletti94 commented on Sep 25, 2026 18:59 UTC
Author

MariaDB 13 only evaluates OLD_VALUE(col) correctly as a whole RETURNING item. As an operand it is a syntax error, and inside a function it silently returns the new value (MDEV-40126). This makes those uses fail to compile, while a plain old_value(col) still loads into the same Rust types.

Builds on #5251 and should land after it. It also rejects the subselect case from #5251 on its own, so that gate may no longer be needed for this shape.

I drafted this with opus 5.5, it seems a reasonable solution overall, I find the macro idea for instance surprisingly succinct.

Diff: 1571 lines (+1512 / -59) across 20 files Reviewer: weiznich Review duration: 6871m
All Vouch review confidence checks passed
Residual risk 0.10 = Change Risk (0.72) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.72 · 1571 lines diff across 20 files
0.72
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.81 · 5 substantive comment(s)
0.81
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
85%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Mass File Touch mass_file_touch
0.080
Real PR Conversation Timeline
15 items
codecov[bot] codecov[bot] commented on Sep 25, 2026 19:17 UTC
Bot

Codecov Report


:white_check_mark: All modified and coverable lines are covered by tests.
:white_check_mark: Project coverage is 81.49%. Comparing base (f18d19e) to head (cb82e6a).
:warning: Report is 16 commits behind head on main.

<details><summary>Additional details and impacted files</summary>

@@            Coverage Diff             @@
##             main    #5252      +/-   ##
==========================================
+ Coverage   81.45%   81.49%   +0.04%     
==========================================
  Files         337      337              
  Lines       36563    36626      +63     
  Branches    36563    36626      +63     
==========================================
+ Hits        29781    29850      +69     
+ Misses       5061     5049      -12     
- Partials     1721     1727       +6     

| Flag | Coverage Δ | |
|---|---|---|
| mariadb | 76.43% <100.00%> (+4.03%) | :arrow_up: |
| mysql | 76.52% <100.00%> (+<0.01%) | :arrow_up: |
| postgres | 80.03% <100.00%> (+<0.01%) | :arrow_up: |
| sqlite | 76.15% <100.00%> (+<0.01%) | :arrow_up: |

Flags with carried forward coverage won't be shown. Click here to find out more.
</details>

:umbrella: View full report in Codecov by Harness.
:loudspeaker: Have feedback on the report? Share it here.
<details><summary> :rocket: New features to boost your workflow: </summary>

  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  • </details>

    weiznich weiznich commented on code on Sep 28, 2026 15:50 UTC
    Code Review
    diesel/src/mariadb/returning/old_impl.rs:1
    @@ -74,27 +80,77 @@ pub fn old_value<C: Column>(col: C) -> old_value<C> {
     impl<C> Expression for OldValue<C>
     where
         C: Column + Expression,
    +    C::SqlType: SingleValue,
     {
    -    type SqlType = <C as Expression>::SqlType;
    +    type SqlType = OldValueOf<C::SqlType>;
     }
     
    +/// SQL type of [`old_value(col)`](old_value()), loaded like `ST` but accepted by
    +/// no literal, column or `ST`-typed function, the positions where
    +/// [MDEV-40126](https://jira.mariadb.org/browse/MDEV-40126) breaks `OLD_VALUE`.
    +/// `.is_null()` and `old_value(a).eq(old_value(b))` still compile, although
    +/// MariaDB rejects `OLD_VALUE` as an operand there too.
    +///
    +/// A type with a hand-written `FromSql<ST, Mariadb>` impl also needs
    +/// `FromSql<OldValueOf<ST>, Mariadb>` to load from `old_value(col)`, which
    +/// `#[derive(Enum)]` already generates.
    +#[derive(Debug, Clone, Copy, Default, QueryId)]

    This type shouldn't be public and this shouldn't require downstream users to implement anything.

    I pushed https://github.com/diesel-rs/diesel/pull/5252/commits/4ee254021e66ae0c1f6646b6513c79dcd1b5ed0a to address this by using CompatibleType (which is exactly for this kind of situation) instead.

    The solution the LLM came up with is just not good in my opinion, as it pushes quite a bit of additional work onto downstream users of custom types.

    This likely still requires a bit of cleanup, as I run out of time finishing this today.

    LucaCappelletti94 LucaCappelletti94 commented on code on Sep 28, 2026 15:53 UTC
    Code Review
    diesel/src/mariadb/returning/old_impl.rs:1
    @@ -74,27 +80,77 @@ pub fn old_value<C: Column>(col: C) -> old_value<C> {
     impl<C> Expression for OldValue<C>
     where
         C: Column + Expression,
    +    C::SqlType: SingleValue,
     {
    -    type SqlType = <C as Expression>::SqlType;
    +    type SqlType = OldValueOf<C::SqlType>;
     }
     
    +/// SQL type of [`old_value(col)`](old_value()), loaded like `ST` but accepted by
    +/// no literal, column or `ST`-typed function, the positions where
    +/// [MDEV-40126](https://jira.mariadb.org/browse/MDEV-40126) breaks `OLD_VALUE`.
    +/// `.is_null()` and `old_value(a).eq(old_value(b))` still compile, although
    +/// MariaDB rejects `OLD_VALUE` as an operand there too.
    +///
    +/// A type with a hand-written `FromSql<ST, Mariadb>` impl also needs
    +/// `FromSql<OldValueOf<ST>, Mariadb>` to load from `old_value(col)`, which
    +/// `#[derive(Enum)]` already generates.
    +#[derive(Debug, Clone, Copy, Default, QueryId)]

    I will look into it tomorrow if I can manage.

    LucaCappelletti94 LucaCappelletti94 commented on Sep 29, 2026 10:11 UTC
    Author

    There were some solver memory shenanigans, and more MariaDB 13 weirdness. I was blissfully ignorant of CompatibleType mapping. I managed to adjust a few things, but some MariaDB syntax that should be supported still is not.

    4ee2540 cleaned away all of the per-type FromSql<OldValueOf<ST>, Mariadb> impls with the CompatibleType mapping, but the ST: CompatibleType<U, DB> bound on the SelectBy impl made the solver recurse through FromSqlRow for every nested tuple, so the clippy CI job ran out of memory. And every Selectable with an old_value field still failed to compile, such as these:

    #[derive(Queryable, Selectable)]
    #[diesel(table_name = users, check_for_backend(Mariadb))]
    struct Renamed {
        #[diesel(select_expression = old_value(users::name))]
        was: String,
        name: String,
    }
    
    update(users::table)
        .set(users::name.eq("Jim"))
        .returning(Renamed::as_select())
        .get_result::<Renamed>(conn);
    
    update(users::table)
        .set(users::name.eq("Jim"))
        .returning(old_value(users::hair_color).nullable())
        .get_result::<Option<String>>(conn);
    

    The SelectBy impl no longer requires SqlType and loads with <ST as SqlTypeLikeMarker>::SqlType, the same one-step mapping the check_for_backend derive now uses, which brings clippy back to the memory it needs on main. OldValueOf got TupleSize, IntoNullable and IntoNotNullable, so it can sit in an embedded struct, .nullable() no longer makes nullable columns twice-nullable, and .assume_not_null() works. New runtime tests cover a hand-written FromSql type and Selectable, an embedded struct and assume_not_null.

    Several shapes are rejected on purpose (and honestly by chance) because MariaDB 13 gets them wrong. Operators such as .is_null() or .eq(..) are a syntax error, and OLD_VALUE inside CAST, CASE or a function returns the new value. MDEV-40126 shows the same with arithmetic, where after updating a from 1 to 2, 0+(OLD_VALUE(a)) returns 2. The issue only calls it the "wrong" value, but it is the new one, which is a more specific type of "wrong". With a plain SqlType these all compiled, and failed or returned wrong data at runtime:

    UPDATE users SET name = 'Jim' WHERE id = 1
    RETURNING OLD_VALUE(name), CASE WHEN id = 1 THEN OLD_VALUE(name) END, COALESCE(OLD_VALUE(name), 'x');
    -- Sean | Jim | Jim on MariaDB 13.0.2
    

    What still fails and should work as MariaDB returns the right values is currently in the form of red cases in the compile test. These are Option<_> embeds of a struct with old_value fields and .nullable() on a tuple of old_values. Both need a nullable tuple, and the tuple impls require every element to be a SqlType, which if re-added would re-enable what I described just above.

    #[derive(Queryable, Selectable)]
    #[diesel(table_name = users)]
    struct PreviousColor {
        #[diesel(select_expression = old_value(users::hair_color).assume_not_null())]
        hair_color: String,
    }
    
    #[derive(Queryable, Selectable)]
    #[diesel(table_name = users)]
    struct Recolored {
        #[diesel(embed)]
        previous: Option<PreviousColor>,
        hair_color: Option<String>,
    }
    

    I guess a possibility would be to relax the SqlType bounds on the tuple nullability impls, but I have not checked the cascading implications of that yet.

    SqlTypeLikeMarker now carries the mapping for both loading and check_for_backend. We could possibly move that to a marker struct or a hidden trait, but I think it is a reasonable extension of that trait.

    LucaCappelletti94 LucaCappelletti94 commented on Sep 30, 2026 09:47 UTC
    Author

    5461d65 broke dynamic_values.rs L297-300, which loads (id, sql::<Untyped>("name, hair_color")), because the tuple CompatibleType impl requires every element to implement SqlTypeLikeMarker and Untyped's conflicts with FromSqlRow<Untyped>.

    7837acd proposes to keeps your mapping routing tuple elements through a doc-hidden CompatibleTupleElement, implemented for every SqlTypeLikeMarker and for Untyped.

    The old_value side now, at least across the queries that I could think of and actively sending Opus on searching queries that are known to break in the MariaDB website were we found the other ones, works on MariaDB 13. To avoid regressions, I added a few runtime tests check the values of the Option<_> embeds, (old_value(a), old_value(b)).nullable(), nested tuples, a tuple select_expression and as_returning().

    The compile test checks that a nullable old_value tuple stays rejected in case_when, assume_not_null, eq, is_null and eq_any.

    While .select((users::name, (Post::as_select(),).nullable())) failed compile in main, it now compiles, and .load() still fails. I added a compile test as a red test for it. I am unsure about how to proceed on this one.

    weiznich weiznich approved these changes on Sep 30, 2026 12:00 UTC
    Approved Reviewer

    Approved these changes.

    LucaCappelletti94 LucaCappelletti94 commented on Sep 30, 2026 12:01 UTC
    Author

    @weiznich wait a sec to merge, maybe Opus (which I left running searching for stuff) found a thing and I am trying to understand whether it is correct or not.

    weiznich weiznich commented on Sep 30, 2026 12:02 UTC
    Contributor

    Thanks for the update

    While .select((users::name, (Post::as_select(),).nullable())) failed compile in main, it now compiles, and .load() still fails. I added a compile test as a red test for it. I am unsure about how to proceed on this one.

    Given that this did not work before I think it's fine to leave it as it is. We can try to make that work later if anyone is actually hitting this.

    weiznich weiznich commented on Sep 30, 2026 12:13 UTC
    Contributor

    wait a sec to merge, maybe Opus (which I left running searching for stuff) found a thing and I am trying to understand whether it is correct or not.

    It's also fine to just dump such findings as comment

    LucaCappelletti94 LucaCappelletti94 commented on Sep 30, 2026 12:19 UTC
    Author

    Ok TLDR: there are other error cases like the ones we encountered, diesel currently refuses to compile all of them, we may want to support them as MariaDB gets fixed, I will add documentation with referenced to them where appropriate.

    weiznich weiznich commented on Sep 30, 2026 12:29 UTC
    Contributor

    Sounds like this is a rather buggy Mariadb feature then :see_no_evil:

    Thanks for adding the documentation. Lets merge this now?

    LucaCappelletti94 LucaCappelletti94 commented on Sep 30, 2026 12:34 UTC
    Author

    Indeed. Yeah let's merge and greenyfy most of the other PRs

    LucaCappelletti94 LucaCappelletti94 commented on Sep 30, 2026 12:35 UTC
    Author

    Why is it back to failing now? 🤦🏻

    weiznich weiznich commented on Sep 30, 2026 12:39 UTC
    Contributor

    Something in the doc comments seems to have changed the formatting of one of the compiler error messages and that was not normalized by the ui-test setup. I will push a quick update for that.

    Reviewers
    Assignees
    LucaCappelletti94 LucaCappelletti94
    Labels
    risk: low confidence: 85.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85.5% · Lower = rushed or shallow review
    85.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 10.3% · Safe to merge
    10.3%