Reject `old_value` inside MariaDB expressions at compile time #5252
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>
</details>
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.
I will look into it tomorrow if I can manage.
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.
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.
Approved these changes.
@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.
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.
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
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.
Sounds like this is a rather buggy Mariadb feature then :see_no_evil:
Thanks for adding the documentation. Lets merge this now?
Indeed. Yeah let's merge and greenyfy most of the other PRs
Why is it back to failing now? 🤦🏻
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.
weiznich
LucaCappelletti94
MariaDB 13 only evaluates
OLD_VALUE(col)correctly as a wholeRETURNINGitem. 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 plainold_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.