Repository navigation
feat: option to use UUIDs as primary keys - #3152
marcelomendoncasoares wants to merge 97 commits into
Conversation
| ), | ||
| Replacement( | ||
| slotName: 'defaultIdType: int\n', | ||
| slotName: 'defaultIdType: int', |
There was a problem hiding this comment.
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:
- Template file:
type: server
defaultIdType: int
client_package_path: ../projectname_client
server_test_tools_path: test/integration/test_tools- Generated file when there is no defaultIdType option:
type: server
client_package_path: ../projectname_client
server_test_tools_path: test/integration/test_toolsTo 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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
|
@marcelomendoncasoares - Closing this as this has now been implemented and will be part of the 2.9.0 release. |
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:
changeIdType. All features described below are behind this flag.idTypethat depends on existing thetableproperty. Admits any valid ID type (currentlyint,uuidV4oruuidV7). 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.--defaultIdTypeoption on theserverpod createcommand that changes the default ID type for all tables fromintto the chosen type. Useful in case the majority of the tables will use such ID type. Admits the same options as theidTypeclass property.defaultIdTypekey on thegenerator.yamlfile that does the same as the above description. Command line option takes precedence over the value stored by this method.UuidValuenow have a new possible default valuerandom_v7that 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, agen_random_uuid_v7function was added to support this (in native pgsql, extracted from this gist).Pre-launch Checklist
///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.If you need help, consider asking for advice on the discussion board.
Breaking changes
As the
TableandTableRowconcept classes contains the typedidfield, to maintain type safety, those classes had to be turned generic with the id type. In consequence, allDatabasemethods had to be turned generic to the id type together with theTableRow<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 thesession.dbmethods 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.: changesession.db.find<Model>tosession.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_chatandserverpod_authmodules 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:
SupportedIdTypeconcentrate 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 thanintorUuidValue(such asString), theTableconstructor must be updated. This is referenced on theSupportedIdTypeclass doc comment.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 nowComparableColunn. 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.TableandTableRowconcept classes are now generic to the type of the ID attribute, with theTableRow<T_ID>.idbeing of typeComparableColunn<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, asDatabaseandDatabaseConnectionhad several methods updated and all server models had to be re-generated.ObjectRelationDefinitionandListRelationDefinitionobjects now store the id type of the table that owns the FK field. This reference is used to pass theT_IDgeneric reference to build the attach/detach repository methods on the server models.uuidV7id type, a pgsql function namedgen_random_uuid_v7is declared at the top ofdefinition.sqlandmigration.sqlon allcreate-migrationcalls. This function is used as default persist for such id type and any otherUuidValuecolumn that declares default asrandom_v7. As the function was extracted from this gist, its license is properly referenced on theextensions.dartmodule.Tests considerations
On all new tests, I tried to follow the practices recommended on the
testing-guidelinebranch of theserverpod_docsrepo 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
intwas 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 theserverpod_docsrepo once/if this PR gets approved.