Skip to content

feat: option to use UUIDs as primary keys - #3152

Closed
marcelomendoncasoares wants to merge 97 commits into
serverpod:mainfrom
marcelomendoncasoares:uuid-as-primary-key
Closed

marcelomendoncasoares wants to merge 97 commits into
serverpod:mainfrom
marcelomendoncasoares:uuid-as-primary-key

Conversation

@marcelomendoncasoares

Copy link
Copy Markdown
Collaborator

This PR implements the possibility to use UUIDs as primary keys for any table. It addresses a recurrent request that was discussed on the issues #351, #635 and #2641. It is also a pre-requisite for the issue #649. In these discussions, it is suggested to create unique indexes on UUID fields instead of using it as PK, but this only ensures uniqueness through constraints, while relationships between entities remain on sequential fields.

Although the common best practice is to use sequential as PK, there are some use cases where using UUIDs is preferred. In distributed systems, for example, the main advantage is the possibility to create several related entities on the client and feed them to the server without round-trips to get ID's. On offline-first applications, in which local and remote database must be a copy of each other, using UUIDs as PK also simplifies upserts without dealing with unique indexes violations (specially for related entities).

It is known that using UUIDs as PKs have several drawbacks, such as lack of PK sorting, increased storage, index bloat, etc. As alternative to reduce some of the drawbacks, the PR also includes the possibility of using the newly approved UUIDv7 spec, that solves most performance problems by being lexicographically sortable. I thought in separating this to another PR, but it is dependent on this PR and the only use case for using UUIDv7 seems to be as primary key.

Implemented features:

  • New experimental flag changeIdType. All features described below are behind this flag.
  • New model property idType that depends on existing the table property. Admits any valid ID type (currently int, uuidV4 or uuidV7). Changes the type of the ID field for the class table only. Any relation to this table will use this ID as FK if needed.
  • New --defaultIdType option on the serverpod create command that changes the default ID type for all tables from int to the chosen type. Useful in case the majority of the tables will use such ID type. Admits the same options as the idType class property.
  • New defaultIdType key on the generator.yaml file that does the same as the above description. Command line option takes precedence over the value stored by this method.
  • Fields of type UuidValue now have a new possible default value random_v7 that will create UUIDs randomly according to the v7 spec. This was included due to the advantage of using lexicographically sortable UUIDs when working with them as PKs. On the database level, a gen_random_uuid_v7 function was added to support this (in native pgsql, extracted from this gist).

Pre-launch Checklist

  • I read the Contribute page and followed the process outlined there for submitting PRs.
  • This update contains only one single feature or bug fix and nothing else. (If you are submitting multiple fixes, please make multiple PRs.)
  • I read and followed the Dart Style Guide and formatted the code with dart format.
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.
  • I added new tests to check the change I am making.
  • All existing and new tests are passing.
  • Any breaking changes are documented below.

If you need help, consider asking for advice on the discussion board.

Breaking changes

As the Table and TableRow concept classes contains the typed id field, to maintain type safety, those classes had to be turned generic with the id type. In consequence, all Database methods had to be turned generic to the id type together with the TableRow<T_ID>. Because of such changes, all server models had to be re-generated.

However, after a user updates the serverpod version and call serverpod generate, only direct usages of the session.db methods should be broken, because they are now generic of two types instead of one. In such cases, adding the id type to the repository method before the TableRow type fixes the problem (i.e.: change session.db.find<Model> to session.db.find<int, Model>). Calls to regular repository methods are not affected (i.e.: Model.db.find).

It is also necessary to publish new versions of the serverpod_chat and serverpod_auth modules with the re-generated server models.

Major changes on existing code:

To facilitate the revision, below is the logical order of the changes on existing code to support other id types on the database:

  • A new class SupportedIdType concentrate the spec of all available id types. To support a new type in the future, the change must be done only in this class, that is referenced whenever a validation or parsing is needed. The PR implements two UUID types as option, but the feature was designed to allow extension for other types as well. If adding a new type other than int or UuidValue (such as String), the Table constructor must be updated. This is referenced on the SupportedIdType class doc comment.
  • Base column types were rearranged and there is a new public column type ComparableColumn<T>. This is the type of valid id columns and implements equality and inequality comparison. All types that have such comparison options on postgres are now ComparableColunn. With this, the string and uuid types can now be compared using less than/more than (and the equal to variant) operators, as supported by Postgres.
  • The Table and TableRow concept classes are now generic to the type of the ID attribute, with the TableRow<T_ID>.id being of type ComparableColunn<T_ID>. This is why the majority of methods that interact with a table are now generic of two references: <T_ID, T extends TableRow<T_ID>. This change was the responsible for most of the changes on existing code, as Database and DatabaseConnection had several methods updated and all server models had to be re-generated.
  • The ObjectRelationDefinition and ListRelationDefinition objects now store the id type of the table that owns the FK field. This reference is used to pass the T_ID generic reference to build the attach/detach repository methods on the server models.
  • To support the uuidV7 id type, a pgsql function named gen_random_uuid_v7 is declared at the top of definition.sql and migration.sql on all create-migration calls. This function is used as default persist for such id type and any other UuidValue column that declares default as random_v7. As the function was extracted from this gist, its license is properly referenced on the extensions.dart module.

Tests considerations

On all new tests, I tried to follow the practices recommended on the testing-guideline branch of the serverpod_docs repo and the examples of existing tests. The only test abstractions that I used was to make tests robust to all possible id types, including any new types implemented in the future - and to keep such tests maintainable, as copying and pasting all test files for every id type didn't seem to me as a good idea.

Regarding existing tests, the only changes were to fix code that broke due to other changes. All new features are tested on new tests, that I wrote trying to avoid overlap with existing tests.

Final considerations

I tried to keep the changes to the minimum for this implementation, but the primary key as int was a strong premise of the project. If there is anything that I failed to adhere to the practices of the repo, just point it out. I can also help with a PR on the serverpod_docs repo once/if this PR gets approved.

),
Replacement(
slotName: 'defaultIdType: int\n',
slotName: 'defaultIdType: int',

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This change was necessary because on some Window machines the newline is being generated as \r\n (strangely, not in all runs). By removing the newline, in case the user calls the create command with no defaultIdType option, the generator.yaml file will have two empty lines in a row:

  1. Template file:
type: server
defaultIdType: int

client_package_path: ../projectname_client
server_test_tools_path: test/integration/test_tools
  1. Generated file when there is no defaultIdType option:
type: server


client_package_path: ../projectname_client
server_test_tools_path: test/integration/test_tools

To avoid this, we could change the replacement by something like:

// The following replacement must be on a valid string instead of a
// placeholder to avoid generating an invalid file. It includes the EOL
// to avoid leaving two newlines in a row. The EOL loop is necessary
// for Windows, where line endings are generated as '\r\n'.
for (var platformEOL in ['\r\n', '\n'])
  Replacement(
    slotName: 'defaultIdType: int$platformEOL',
    replacement: defaultIdType != null
        ? 'defaultIdType: ${defaultIdType.aliases.first}$platformEOL'
        : '',
  ),

However, I felt it to be too dirty on the code for such a small detail. It is valid to mention that the template must contain a valid default option instead of a template name to avoid breaking existing tests that just copy the file, without calling the create command.

@SandPod, do you have a take on what would be preferred here for the library?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

We would prefer not to have defaultIdType defined at all in the config file. The reason for this is that we try and keep the context as small as possible for new users to Serverpod. We can then document how to change this if that is desired.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The reason why I put this optional key in the file is to allow the configuration to be persistent for the project (configured once as a flag on the create command). So that a --defaultIdType key should not need to be present on all subsequent calls to serverpod generate - as forgetting it once would change everything on the models. However, I implemented it as an optional key in the generator.yaml, making the project default to int if it is missing (as would happen with already existing projects). Do you think that even as an optional key with this behavior it would be a problem?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The config in the generator.yaml is also needed for the language server to understand correctly the id type for the models if they were generated with a different default id type.

@SandPod SandPod Feb 20, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Sorry, my comment was unclear here.

We SHOULD have defaultIdType as an optional key in the generator.yaml file. It should be configurable and persistent for a project if the developer would like that.

But key should not be present in the generator.yaml template, with the above motivation (keep required initial context as small as possible). If we change the default value for this key for Serverpod. This will be listed as a breaking change with a clear migration step.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Ok, think we are aligned on this. With the proposed implementation, the key will only be present on the generator.yaml after project creation if the user adds the defaultIdType option on the create command. Otherwise (which is the default), the key will be removed from the template during the project creation and the file will be the same as it is today.

I only added it to the template to allow the create command to inject the configuration on the correct place (or remove it) using the existing Copier + Replacement mechanism. But it would not need to be there before the create command if we have a better approach to inject a key on this file during the create.

With this behavior (of removing the key when the user does not use it), do you think the small context for the user is preserved? Or should we look for another configuration injection strategy on the generator.yaml file?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Because Serverpod mini is not compatible with --defaultIdTyp I don't think we should add it to the top-level create command as mini is generated without the generator.yaml file.

To still get some visibility around this configurable option, we might want to keep your original implementation of adding the keyword to the generator.yaml but comment it out with an explanation that includes its purpose and valid options.

The context for the user grows a bit, but ideally, it still provides enough value.

@SandPod

SandPod commented Jun 24, 2025

Copy link
Copy Markdown
Contributor

@marcelomendoncasoares - Closing this as this has now been implemented and will be part of the 2.9.0 release.

@SandPod SandPod closed this Jun 24, 2025
@github-actions github-actions Bot locked and limited conversation to collaborators Jun 24, 2025
@marcelomendoncasoares
marcelomendoncasoares deleted the uuid-as-primary-key branch November 26, 2025 04:26
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants