Skip to content
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

Handle encoding binary data separately #16988

Merged
merged 14 commits into from
Oct 23, 2024

Conversation

dbussink
Copy link
Contributor

@dbussink dbussink commented Oct 17, 2024

Binary data should be encoded as such when interpolated, for example in bind variables. Otherwise valuable type information that the value is actually binary is lost.

Also means that we should not mark literals in the parser as binary either. They are strings and there's other introducers like _binary that end up marking things as proper binary.

Related Issue(s)

Fixes #16989

Checklist

  • "Backport to:" labels have been added if this change should be back-ported to release branches
  • If this change is to be back-ported to previous releases, a justification is included in the PR description
  • Tests were added or are not required
  • Did the new or modified tests pass consistently locally and on CI?
  • Documentation was added or is not required

Copy link
Contributor

vitess-bot bot commented Oct 17, 2024

Review Checklist

Hello reviewers! 👋 Please follow this checklist when reviewing this Pull Request.

General

  • Ensure that the Pull Request has a descriptive title.
  • Ensure there is a link to an issue (except for internal cleanup and flaky test fixes), new features should have an RFC that documents use cases and test cases.

Tests

  • Bug fixes should have at least one unit or end-to-end test, enhancement and new features should have a sufficient number of tests.

Documentation

  • Apply the release notes (needs details) label if users need to know about this change.
  • New features should be documented.
  • There should be some code comments as to why things are implemented the way they are.
  • There should be a comment at the top of each new or modified test to explain what the test does.

New flags

  • Is this flag really necessary?
  • Flag names must be clear and intuitive, use dashes (-), and have a clear help text.

If a workflow is added or modified:

  • Each item in Jobs should be named in order to mark it as required.
  • If the workflow needs to be marked as required, the maintainer team must be notified.

Backward compatibility

  • Protobuf changes should be wire-compatible.
  • Changes to _vt tables and RPCs need to be backward compatible.
  • RPC changes should be compatible with vitess-operator
  • If a flag is removed, then it should also be removed from vitess-operator and arewefastyet, if used there.
  • vtctl command output order should be stable and awk-able.

@vitess-bot vitess-bot bot added NeedsBackportReason If backport labels have been applied to a PR, a justification is required NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsIssue A linked issue is missing for this Pull Request NeedsWebsiteDocsUpdate What it says labels Oct 17, 2024
@github-actions github-actions bot added this to the v22.0.0 milestone Oct 17, 2024
@dbussink dbussink force-pushed the dbussink/fix-binary-encoding branch from ec1a3a9 to 2c56bcf Compare October 17, 2024 11:59
Copy link

codecov bot commented Oct 18, 2024

Codecov Report

Attention: Patch coverage is 71.25000% with 23 lines in your changes missing coverage. Please review.

Project coverage is 67.15%. Comparing base (03b93a1) to head (5e82912).
Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
go/mysql/query.go 52.08% 23 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16988      +/-   ##
==========================================
- Coverage   67.15%   67.15%   -0.01%     
==========================================
  Files        1571     1571              
  Lines      251868   251895      +27     
==========================================
+ Hits       169148   169150       +2     
- Misses      82720    82745      +25     

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

@dbussink dbussink force-pushed the dbussink/fix-binary-encoding branch 7 times, most recently from bc7c8f1 to f656471 Compare October 22, 2024 07:48
dbussink added a commit to planetscale/vitess that referenced this pull request Oct 22, 2024
The fix in vitessio#16988 makes a change
here that's not really a breaking change, but it does break the test as
the test matches the exact string output which changes here due to a
binary value.

Signed-off-by: Dirkjan Bussink <[email protected]>
Binary data should be encoded as such when interpolated, for example in
bind variables. Otherwise valuable type information that the value is
actually binary is lost.

Also means that we should not mark literals in the parser as binary
either. They are strings and there's other introducers like `_binary`
that end up marking things as proper binary.

Signed-off-by: Dirkjan Bussink <[email protected]>
This has been using all binary everywhere since day one this was added,
but we are a lot more type aware and handle types correctly now.

This means we also should convert prepared statement values to the
proper types as well when we receive them as inputs for queries. This
way we know we can handle them correctly further down as well.

Signed-off-by: Dirkjan Bussink <[email protected]>
Since we now have proper binary data encoding and these are binary
columsn, we see the data as binary now sent down so we have to match on
that.

WIP, many more tests like this that need to be updated.

Signed-off-by: Dirkjan Bussink <[email protected]>
Signed-off-by: Dirkjan Bussink <[email protected]>
Signed-off-by: Dirkjan Bussink <[email protected]>
Signed-off-by: Dirkjan Bussink <[email protected]>
Signed-off-by: Dirkjan Bussink <[email protected]>
Signed-off-by: Dirkjan Bussink <[email protected]>
This tracks the explicit type for the id column so that we can use that
properly when binding variables. If we don't bind the right type, we end
up depending on implicit MySQL type casting behavior which isn't
something we should do.

Making it explicit here is much more robust.

Signed-off-by: Dirkjan Bussink <[email protected]>
This is an integer column, so we should those as bind variables and not
a string since then we depend on string to integer conversion logic
inside MySQL itself.

Signed-off-by: Dirkjan Bussink <[email protected]>
Using the X'' syntax makes things behave differently, since it makes
MySQL interpret it as a hex number in contexts where it casts it to an
integer, for example in a `where id = 'binary string'` where `id` is a
numerical type.

`_binary` as a prefix more behaves like no prefix at all, so it better
matches how things behave today so we're better backwards compatible.

Signed-off-by: Dirkjan Bussink <[email protected]>
These are not allowed in MySQL as well, so don't allow them in Vitess
either.

Signed-off-by: Dirkjan Bussink <[email protected]>
Signed-off-by: Dirkjan Bussink <[email protected]>
Signed-off-by: Dirkjan Bussink <[email protected]>
@dbussink dbussink force-pushed the dbussink/fix-binary-encoding branch from f656471 to 5e82912 Compare October 22, 2024 20:30
@dbussink dbussink added Type: Bug Component: Query Serving and removed NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsWebsiteDocsUpdate What it says NeedsIssue A linked issue is missing for this Pull Request NeedsBackportReason If backport labels have been applied to a PR, a justification is required labels Oct 22, 2024
@@ -713,7 +713,11 @@ func (c *Conn) parseStmtArgs(data []byte, typ querypb.Type, pos int) (sqltypes.V
}
switch size {
case 0x00:
return sqltypes.NewVarChar(" "), pos, ok
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is a broken value, the protocol definition specifies that a zero size means the zero date / date time and that is represented in a string with all the 0 values as below.

val = strconv.AppendInt(val, int64(month), 10)
val = append(val, '-')
val = strconv.AppendInt(val, int64(day), 10)
if typ != sqltypes.Date {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is so that we don't add a time value if we're a date type.

default:
return sqltypes.NULL, 0, false
}
case sqltypes.Decimal, sqltypes.Text, sqltypes.Blob, sqltypes.VarChar, sqltypes.VarBinary, sqltypes.Year, sqltypes.Char,
sqltypes.Bit, sqltypes.Enum, sqltypes.Set, sqltypes.Geometry, sqltypes.Binary, sqltypes.TypeJSON, sqltypes.Vector:
val, pos, ok := readLenEncStringAsBytesCopy(data, pos)
return sqltypes.MakeTrusted(sqltypes.VarBinary, val), pos, ok
return sqltypes.MakeTrusted(typ, val), pos, ok
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This now returns the actual type instead of marking everything as binary which can break things. That was exposed by the other changes in this PR here where serialization of binary values was changed.

}

func encodeBinarySQLBytes2(val []byte, buf *bytes2.Buffer) {
buf.Write([]byte("_binary"))
Copy link
Contributor Author

Choose a reason for hiding this comment

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

So there are basically 2 ways to do binary strings. One is with the _binary introducer as done here, another approach is using the X'cafe' syntax.

Initially I tried the second approach, so no introducer is needed. There's a problem with that approach though, which is how it is handled in the case of a match on a column of a different type.

In case there's an id column of type int and you query it with select * from t where id = '1' really a binary string (and not a varchar). When using hex style syntax, it would turn into:

select * from t where id = X'31'

This changes behavior then, because in this context MySQL interprets it as a hex numerical, so it really executes select * from t where id = 49 (with 49 being the numerical value for that binary input).

When using _binary it doesn't change behavior. So the final choice is to use the introducer then.

| underscore_charsets column_name_or_offset %prec UNARY
{
$$ = &IntroducerExpr{CharacterSet: $1, Expr: $2}
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Using the introducer for binary values exposed another problem. We were accepting introducers with a column, which is not something that MySQL does.

There was no dependency on this anywhere, except in a test for vplayer filtering where we were using this invalid syntax.

@@ -236,6 +236,9 @@ type messageManager struct {
ackQuery *sqlparser.ParsedQuery
postponeQuery *sqlparser.ParsedQuery
purgeQuery *sqlparser.ParsedQuery

// idType is the type of the id column in the message table.
idType sqltypes.Type
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Before the messager always bound as binary, which is not correct. This is what also exposed originally the problem with the hex syntax, as it would not find rows.

The proper fix here though is to actually look at the real type of the column and use that in the bind variable so we always correctly handle it, independent from whether by accident passing in a binary value to this random type works or not.

@@ -748,7 +748,7 @@ func TestPlayerFilters(t *testing.T) {
Filter: "select id1, val from src5 where val = 'abc'",
}, {
Match: "dst_charset",
Filter: "select id1, concat(substr(_utf8mb4 val collate utf8mb4_bin,1,1),'abcxyz') val, concat(substr(_utf8mb4 val collate utf8mb4_bin,1,1),'abcxyz') val2 from src_charset",
Filter: "select id1, concat(substr(CONVERT(val USING utf8mb4) COLLATE utf8mb4_bin,1,1),'abcxyz') val, concat(substr(CONVERT(val USING utf8mb4) COLLATE utf8mb4_bin,1,1),'abcxyz') val2 from src_charset",
Copy link
Contributor Author

Choose a reason for hiding this comment

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

_utf8mb4 val here is the actual invalid syntax, since you can't use an introducer on a column. Instead, this now properly uses a convert function to force the correct collation for this test.

Copy link
Collaborator

@vmg vmg left a comment

Choose a reason for hiding this comment

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

These fixes all look great 🙇

Comment on lines -628 to +636
expQuery: `update _vt.redo_state set state = 1, message = 'deadline exceeded' where dtid = 'aa'`,
expQuery: `update _vt.redo_state set state = 1, message = 'deadline exceeded' where dtid = _binary'aa'`,
}, {
receivedErr: vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "invalid argument"),
retryable: false,
expQuery: `update _vt.redo_state set state = 0, message = 'invalid argument' where dtid = 'aa'`,
expQuery: `update _vt.redo_state set state = 0, message = 'invalid argument' where dtid = _binary'aa'`,
}, {
receivedErr: sqlerror.NewSQLError(sqlerror.ERLockDeadlock, sqlerror.SSLockDeadlock, "Deadlock found when trying to get lock; try restarting transaction"),
retryable: false,
expQuery: `update _vt.redo_state set state = 0, message = 'Deadlock found when trying to get lock; try restarting transaction (errno 1213) (sqlstate 40001)' where dtid = 'aa'`,
expQuery: `update _vt.redo_state set state = 0, message = 'Deadlock found when trying to get lock; try restarting transaction (errno 1213) (sqlstate 40001)' where dtid = _binary'aa'`,
Copy link
Member

Choose a reason for hiding this comment

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

Is this the side effect or it is necessary to have _binary for all varbinary column types?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This query is generated with a bind var which now always uses _binary for a binary value.

Doing this is required to fix the original bug where variables weren't correctly typed and resulted in broken behavior.

Copy link
Member

@harshit-gangal harshit-gangal left a comment

Choose a reason for hiding this comment

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

Looks great. Just left 1 comment for understanding.

@dbussink dbussink merged commit b0b7981 into vitessio:main Oct 23, 2024
103 of 104 checks passed
@dbussink dbussink deleted the dbussink/fix-binary-encoding branch October 23, 2024 12:38
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.

Bug Report: User defined variables lose binary encoding information
3 participants