Skip to content

Feature/extend data classes - #2710

Merged
Isakdl merged 56 commits into
serverpod:mainfrom
BenAuerDev:feature/extend-data-classes
Sep 20, 2024
Merged

Isakdl merged 56 commits into
serverpod:mainfrom
BenAuerDev:feature/extend-data-classes

Conversation

@BenAuerDev

@BenAuerDev BenAuerDev commented Sep 4, 2024 •

Copy link
Copy Markdown
Contributor

This PR adds the functionality to allow using the extends keyword to create a class based on another.

class: BaseClass
fields: 
  fieldOne: String
class: SubClass
extends: BaseClass
fields: 
  fieldTwo: String

This generates a SubClass that can be used like

SubClass(fieldOne: '...', fieldTwo: '...');

It is not yet possible to add a DB-Table to a base- or sub-class, as a DB-Class extends TableRow and we can't extend two classes. To achieve this like requested in #1618 we would need to make TableRow an interface which can be implemented by the class so the extends property is free to be used for inheritance. New Issue: #2711

connected to: #1873

Review advice

I do recommend going through the changes commit by commit. I tried to make them (somewhat) bite sized.

Review changes

As proposed in the first review, the functionality was also added to not directly expose the functionality to the user when running serverpod generate. To access the functionality the user must run serverpod generate --experimental-features=inheritance

Screenshot from 2024-09-17 08-48-50

Also ClassDefinition and EnumDefintion now have a type field.

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

No breaking changes

@SandPod SandPod left a comment

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.

Awesome work! 🎉

Thanks for some great readable code that has tests included.

I think we should resolve the extended class connection in a different way. I we take inspiration from how we resolve relations we can work with references instead of making lookups in multiple places.

We should also think about how we want to relase this. It would be great if we can merge your work to main but without exposing the new functionality to our users. That would allow us to get more fixes in before we ship it.

@vlidholt

vlidholt commented Sep 6, 2024

Copy link
Copy Markdown
Collaborator

Wow! Great work @BenAuerDev, really looking forward to getting this into Serverpod! 🚀

ClassDefinition now holds two fields related to inheritance `subClasses` and `extendsClass` of type `InheritanceDefinition`

`InheritanceDefintion` was added with 3 classes extending it:
* UnresolvedInheritanceDefinition
* BaseClassInheritanceDefinition (holding a list of subClasses)
* ExtendsClassInheritanceDefinition (holding the fields and path of the class that is extended)

extendsClass is then parsed as `UnresolvedInheritanceDefinition` and in the resolver step, both `extendsClass` and `subClasses` are resolved to hold the needed information

and model-library-generator now takes the necessary information from the inheritance fields of it's ClassDefinition

also the tests and test_utils were updated reflecting the changes made to the resolving workflow
`classNames` and `table` were added to each others `mutuallyExclusiveKeys`.

a new check was introduces checking if the moduleAlias is 'protocol' (if the extended class is from the same project and not from a module or serverpod itself.

expected error-message in test was updated
@BenAuerDev

Copy link
Copy Markdown
Contributor Author

Comment:

I was not able to add a test covering the check for external models to inheritance_test.dart.

as we create the models for the test like

var modelSources = [
        ModelSourceBuilder().withYaml(
          '''
          class: Example
          fields:
            name: String
          ''',
        ).build(),
        ModelSourceBuilder().withFileName('example2').withYaml(
          '''
          class: ExampleSubClass
          extends: Example
          table: example_sub_class
          fields:
            age: int
          ''',
        ).build(),
      ];

and when used like:

var modelSources = [
      ModelSourceBuilder().withFileName('example2').withYaml(
        '''
          class: ExampleSubClass
          extends: ServerHealthMetric
          fields:
            age: int
          ''',
      ).build(),
    ];

the previous restriction

  if (baseClass == null) {
      return [
        SourceSpanSeverityException(
          'The class "$baseClassName" was not found in any model.',
          span,
        )
      ];
    }

is executed as every class not declared within var modelSources = [...]; is null.

But I tested it manually in the command line and the restriction is executed

Screenshot from 2024-09-11 15-21-38

@SandPod SandPod left a comment

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.

Great improvement!
The resolver step will make this implementation a bit more flexible, still have a couple of comments regarding how the linking is built.

I'll also take a look at enabling testing with "serverpod" files. I believe this should be possible since we use the same interface as the code.

definitions where simplified:
- ResolvedInheritanceDefinition - holds ClassDefinition
- UnresolvedInheritanceDefinition - holds ClassName

- classDefinition.subClasses (soon childClasses) is now of type List<ResolvedInheritanceDefinition>

- classDefinition.extendsClass is of type ResolvedInheritanceDefinition

- classDefinitionBuilder also had to be updated.

- inheritance_class_test was updated/improved for both server and client
except in class_definition_builder there i named it "_extendsClass" as it is the same on ClassDefinition
improved readability for `var extendsClass = .....`

and removed part I accepted when merging main
Adds a new multi-option "experimental-features" to the generate command.
Config has new field "experimentalFeatures" which is propagated down to extractModelDefinition, and used in ModelParser to decide when extendsClass should be parsed
A singleton was added which can be instantiated and holds a list of experimental features.

the multiOption on the argParser was moved from the Generate command to ServerpodCommandRunner

another option was added to pass --experimental-features=all which enables all experimental features. This is used in migration_test_utils.dart and util/generate_all

@Isakdl Isakdl left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Good work! Almost there I have one additional request to manage the import URL in the same way as the rest of the code, it is a little annoying but I think it will complete the functionality of our parser.

…arser

As we don't guard in the parser anymore we also don't need to pass enableInheritance, I forgot that when I removed the guard
This adds a new field type (TypeDefinition) to SerializableModelDefinition which is required for ClassDefinition and EnumDefintion.

Also some tests were added to check if the type field is properly set on:
- classes
- enums
- exceptions
this creates a relative import and adds '..' for every subDirPart so it should be the childs subDirParts

@Isakdl Isakdl left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

One small little request and we should be ready.

the type is now non-nullable and final

I also updated the test-utils
- ClassDefinitionBuilder
- EnumDefinitionBuilder

Which now assigns = TypeDefinitionBuilder....

to it but can be otherwise modified if necessary with the .withType() method if needed

@Isakdl Isakdl left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Almost there, the test builders do not produce a valid default state / management.

withType was removed, as it should not be manually overridden.

type.enumDefinition is set to the instance of the enum

ClassDefinitionBuilder.type.className is set dynamically

@Isakdl Isakdl left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I found some unused dead code and some very small nit things. But this should be the final change request!

@Isakdl Isakdl left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Good job @BenAuerDev, LGTM 🚀 🚀 🚀 let's go 😄

@Isakdl
Isakdl merged commit 0133c99 into serverpod:main Sep 20, 2024
@github-actions github-actions Bot locked and limited conversation to collaborators Sep 20, 2024
@BenAuerDev
BenAuerDev deleted the feature/extend-data-classes branch November 25, 2024 14:34
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.

5 participants