Skip to content

Store UUIDs as binary in MySQL #10542

Open

Description

@rondonjon

Feature Description

Since I cannot reopen #3187 myself, I am knowingly creating this ticket as a duplicate and apologize in advance.

The original request is from 2018. At the time, the answer from @pleerock was that ...

We were considering this before, but decided to go simple way because of complexity of implementation and the fact that only mysql 8 support uuid functions.

Perhaps it would make sense to reconsider this from today's perspective. MySQL 8 has been around for more than 5 years now, and the version number is actually only relevant if we want to use the native functions of the database to convert textual UUIDs into binary data and back; but the real decisive factor is that the database can handle binary columns, which has been the case for much longer. The complexity of the feature also seems manageable to me - from a layman's perspective, of course. The workarounds that have been proposed so far seem to be flawed.

The Solution

To avoid problems with existing applications, we should probably start by adding feature flag preferBinaryUuidsOverVarchar to MysqlConnectionOptions.ts that defaults to false for now and true from the next major release.

It seems that the existing driver already implements special treatment of UUIDs, but currently only for MariaDB, which has a native uuid column type:

/** MariaDB supports uuid type for version 10.7.0 and up */
private uuidColumnTypeSuported = false    // <---- has a typo, btw

The support of UUIDs from MySQL 8 is limited to data transformation functions. There is still no dedicated column type for UUIDs. MySQL uses binary(16) instead. So the column type normalization should be changed as follows:

          } else if (column.type === "uuid") {
            if (this.uuidColumnTypeSupported) { // MariaDB
              return "uuid"
            } else if (this.config.preferBinaryUuidsOverVarchar) { // MySQL with feature flag
              return "binary(16)" // here (+)
            } else { // legacy support
              return "varchar"

MariaDB handles the needed text/binary conversions internally, so that the driver doesn't have to transform values. MySQL on the other hand would require an explicit transformation.

The existing functions in MysqlDriver.ts already transform a number of other column types and could be extended as follows:

        if (columnMetadata.type === Boolean) {
            return value === true ? 1 : 0
        } else if (!this.uuidColumnTypeSupported && this.config.preferBinaryUuidsOverVarchar) {
            return uuidTextToBinary(value) // here (+)

and

        if (
            columnMetadata.type === Boolean ||
            columnMetadata.type === "bool" ||
            columnMetadata.type === "boolean"
        ) {
            value = value ? true : false
        } else if (!this.uuidColumnTypeSupported && this.config.preferBinaryUuidsOverVarchar) {
            return uuidBinaryToText(value) // here (+)

In an ideal world, we would use the native MySQL UUID functions for these transformations. But it doesn't look like the surrounding SQL statement can be changed at this point in the code. The native functions are also only available in MySQL versions 8 and later. Although it can of course be assumed that these are now widely used, this would limit the solution to "relatively" new databases. In principle, nobody is forcing us to use the native functions, and UUID conversions between text and binary in JavaScript are actually quite simple, and the added computational effort is probably negligible.

I would hence suggest to implement uuidTextToBinary() and uuidBinaryToText() in TypeORM, maybe based on prior solutions here or here. The actual conversion from hex strings to binary is more or less a one-liner, after the dashes have been removed:

new Uint8Array('AA5504B10000B5'.match(/../g).map(h=>parseInt(h,16))).buffer

Considered Alternatives

No response

Additional Context

No response

Relevant Database Driver(s)

  • aurora-mysql
  • aurora-postgres
  • better-sqlite3
  • cockroachdb
  • cordova
  • expo
  • mongodb
  • mysql
  • nativescript
  • oracle
  • postgres
  • react-native
  • sap
  • spanner
  • sqlite
  • sqlite-abstract
  • sqljs
  • sqlserver

Are you willing to resolve this issue by submitting a Pull Request?

I would be happy to provide a PR with the required code changes if someone else could help me with the needed adjustments of the tests? I suppose the effort of setting up a working environment for these tests will be higher for me than that of the implementation 😖

Could some core members maybe share their opinions on this request and the outlined solution?

Activity

  1. jsshapiro commented on Mar 30, 2025

    @jsshapiro

    A few observations about this:

    Schema Breaking Change: It is a mistake to handle this by changing the default treatment of UUIDs with a driver option, because it breaks existing tables and existing comparisons within the database of UUID-valued fields (notably including foreign keys). Changing the representation of of a UUID column is a schema update requiring a migration, and it needs to be treated as such. This probably means that a new decorator is required to distinguish binary-formatted vs text-formatted UUIDs.

    The same is not true when changing the UUID type used by the generator. Changing the value of the UUID type sub-field does not change the representation of the column, and it does not violate the uniqueness properties required for indices.

    This leads to a suggestion for when UUID support is broadened: Add a field to UUIDOptions giving the desired UUID version number (a.k.a. the UUID type) so that we don't have to do this again in the future.

    Accuracy Issue: When @pleerock writes that "only mysql 8 support uuid functions", he is not correct. UUID implementations exist for Postgres, MS SQL Server, and any number of other SQL databases. In fact, they can be supplied by the database admin. A more accurate statement is that some of these databases do not provide native implementations by default as part of their standard libraries. This does not in any way preclude the use of UUID functions. It merely introduces a requirement that database initialization include some function definitions.

    But a different issue does exist: we probably want the in-memory (really in-model) representation of a UUID to be common across all database drivers. In my opinion this should have been an instance of a distinct UUID type, but string was chosen for this when UUID support was initially added to TypeORM. The point is: we need some sort of transformer to convert back and forth between the form used by the database's query language and the string value used in the model.

    Strictly speaking this is database-specific behavior that doesn't require a general transformer mechanism, but I think there's a compelling reason to add that capability if it hasn't already been merged - see below under "blind inserts". That said, the database-level representation of binary UUIDs isn't universal (MSSQL uses a goofy byte order), so maybe its best to canonicalize the in-model form and keep the transformer in the driver.

    Performance Issue: @nolawnchairs seems to feel that binary vs text isn't important and one should focus on functionality. It turns out that the size (in bytes) of a key makes an enormous efficiency difference, because it determines how many index values can be held in an index page. Naively, the 16 byte binary representation is less than half the size of the 36 byte text representation, but when internal metadata (like the string size prefix) are added to the indexing pages that difference is magnified. And if the hyphens are not discarded in the index you end up with extra padding.

    The impact of this can be large, because it alters the size of the index on both the disk and the in-memory cache. When benchmarks show how much less efficient UUIDs are than bigints, this is the primary reason!

    Which, as an aside, probably means that one or two new strategies should be introduced - a lot of modern databases have moved to 64 bits as the default integer key size, and in some cases are moving to 128 bit integer keys. In both cases these are functionally necessary at scale, but they aren't especially convenient for JavaScript code.

    Blind Inserts I tend to think that a different approach is worth considering, which is to add an option interface for primary key value generation in the model. One of the problems with generated unique key values (including, but not limited to UUIDs) using database functions is that inserts can no longer be performed "blind" - you have to re-read in order to find out what unique key value was generated. But this is largely an artifact of using [mostly] sequential sequences of indices for the sake of index insert efficiency.

    Newer UUID forms, along with alternatives like ULID, preserve efficient index construction while allowing the values to be generated by the query builder on the database client. Some forms are guaranteed unique while others are probabilistically unique. In the first case, inserts can be blind. In the second case, inserts can be mostly blind with an occasional [rare] retry.

    Closing: I get that other issues may be higher priority. I wanted to put these thoughts out there to try to document why this issue actually does matter in real-world use cases. It's been seven years since #3817 was opened, and the impediments originally suggested by @pleerock. Maybe it's time?

  2. jsshapiro commented on Mar 30, 2025

    @jsshapiro

    A small thing: Perhaps this issue should be renamed to "Store UUIDs as binary"? It isn't just a MySQL issue.

  3. alumni commented on Mar 30, 2025

    @alumni
    Collaborator

    It's not just MySQL, SAP HANA also has two UID functions (SYSUUID / NEWUID, see #8218) which both generate a VARBINARY(16) output (that cannot be formatted as a UUID string with any built-in functions).

    Implementing this functionality would require changing the column data type (or adding a new generationStrategy, e.g. "binary-uuid").

    I was actually just looking at this today for the SAP driver and realized it's quite some work to do. Also, SAP recommends against using binary UUIDs and their own ORM also uses string ones. I'm actually thinking to provide the functionality for SAP via asExpression (already available in MySQL AFAIK).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions