Repository navigation
feat: Add support for jsonb columns - #3934
borutjures wants to merge 42 commits into
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the ✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
CLA Assistant Lite bot All contributors have signed the CLA ✍️ ✅ |
|
I have read the CLA Document and I hereby sign the CLA |
marcelomendoncasoares
left a comment
There was a problem hiding this comment.
Great work on this one, @borutjures! Very clean implementation, with everything in the right places! I made some considerations regarding names used for the feature and other smaller code improvements.
I haven't thoroughly reviewed the tests yet, but I've noticed that you only included unit tests on the serverpod_cli. I suggest taking a look at this merge commit 7979b3d as a reference to other tests that we must cover for this feature.
As you can see in the commit, beside unit tests on the packages, we use the tests/serverpod_test_server to add integration tests with actual models for all of the framework features. So it is good to also create some models with jsonb there and add similar tests.
Let me know if you need any further guidance or if you want to schedule a sync to discuss any implementation detail! I'll keep an eye here as well to iterate with you on the next changes.
…ve serializeAsJsonbAsDefault from experimental feature to CLI config; merge _buildModelTableCustomSerializedFieldTypeReference() into _buildModelTableGeneralFieldExpression()
…pod server models
|
@marcelomendoncasoares I went through the recommended merge commit and looked at the integration tests it added. I added only one integration test. It looks to me that Please let me know if I missed anything. The only thing I would like to change before going further is renaming of |
marcelomendoncasoares
left a comment
There was a problem hiding this comment.
Good suggestion on the naming! You can proceed with the rename for the enum as SerializationDataType and the field/variables as serializationDataType. Also great progress on previous comments! I made a few follow-ups on the changes and will proceed with reviewing the tests later today.
marcelomendoncasoares
left a comment
There was a problem hiding this comment.
Great work! We're mostly done with the feature implementation. I have now reviewed the tests so we can ensure proper coverage according to the repo standards. Let me know if you want to discuss anything!
Beside the comments on the tests, we always include some real world tests using the column type in the serverpod_test_server to ensure it works properly - or catch any edge case we might miss in the other tests. You can use the ObjectWithJsonb class and add a test to tests\serverpod_test_server\test_integration\column_operations.
| indexes = table.indexes; | ||
| }); | ||
|
|
||
| test('then the implicitly declared gin index exists.', () { |
There was a problem hiding this comment.
This test happens on an index with type explicitly declared to gin. It would be good to also include an index on the model with no type declaration and validate that it is implicitly recognized as gin. Then, we should have tests for implicitly and explicitly declared type, such as with vector types.
There was a problem hiding this comment.
I added a test for implicit index type on a jsonb column (the existing two tests are actually for explicit indexes).
As it turns out, the default index type for a jsonb column is btree. The only useful operators are “=”, <, <=, >, >=. This can only be used for whole object comparisons, which has a very limited use case.
I'll leave the test for now but indexes on jsonb columns should always specify gin as their type. Maybe there should be a warning when no type is specified in a model?
There was a problem hiding this comment.
I agree, btree has little usage for jsonb fields and it's counterintuitive to find it as default - as just happened to both of us. I think we could safely define the default on Serverpod for jsonb field indexes to be gin if the type is omitted. Then, if an user wants a btree, it is always possible to explicitly specify.
…e_generation_test; add to index_test
|
I fixed the dart format errors. Other CI failures seam to be unrelated to this feature. |
…eat-jsonb-support
marcelomendoncasoares
left a comment
There was a problem hiding this comment.
Great progress, I think we are close to finish now.
I have fixed the formatting and code generation tests, and also the integration/migration tests due to the jsonb default value. The cause for the failures on the latter was that your fix was on the code generation, which was causing a mismatch on the database state after startup. I have moved the fix to the parsing level, in the same way that we do for vector fields, so that the default value is also present on the definition.json file.
To close this feature, we have mainly three things to address:
- Add tests for the experimental feature flag being required, now that it is no longer being evaluated outside of the
GeneratorConfigclass. - Make
gintype the default index type forjsonbfields when thetypeis omitted. This is what you suggested and I agree that it is a good default. We can show a hint to users during code generation that it will default toginwhen thetypeis missing so we have no surprises for users that expect Postgresbtreedefault - which is unlikely. - Centralize the model and project level configuration on the field type during parse to avoid having the override rules spread across the codebase. This will require refactoring the tests to remove cross-configuration checking, since every configuration will be isolated from the others.
Once we are done with these ones, I think we are in good shape to one last review by Alex and then merge!
| test( | ||
| 'when gin indexes have different operator classes then mismatches include operator class mismatch.', | ||
| () { | ||
| var tableA = TableDefinition( | ||
| name: 'gin_table', | ||
| schema: 'public', | ||
| columns: [ | ||
| ColumnDefinition( | ||
| name: 'jsonDoc', | ||
| columnType: ColumnType.jsonb, | ||
| isNullable: false, | ||
| dartType: 'List<String>', | ||
| ), | ||
| ], | ||
| indexes: [ | ||
| IndexDefinition( | ||
| indexName: 'idx_jsonDoc', | ||
| elements: [ | ||
| IndexElementDefinition( | ||
| type: IndexElementDefinitionType.column, | ||
| definition: 'jsonDoc', | ||
| ), | ||
| ], | ||
| type: 'gin', | ||
| isUnique: false, | ||
| isPrimary: false, | ||
| ginOperatorClass: GinOperatorClass.jsonb, | ||
| ), | ||
| ], | ||
| foreignKeys: [], | ||
| managed: true, | ||
| ); | ||
|
|
||
| var tableB = TableDefinition( | ||
| name: 'gin_table', | ||
| schema: 'public', | ||
| columns: [ | ||
| ColumnDefinition( | ||
| name: 'jsonDoc', | ||
| columnType: ColumnType.jsonb, | ||
| isNullable: false, | ||
| dartType: 'List<String>', | ||
| ), | ||
| ], | ||
| indexes: [ | ||
| IndexDefinition( | ||
| indexName: 'idx_jsonDoc', | ||
| elements: [ | ||
| IndexElementDefinition( | ||
| type: IndexElementDefinitionType.column, | ||
| definition: 'jsonDoc', | ||
| ), | ||
| ], | ||
| type: 'gin', | ||
| isUnique: false, | ||
| isPrimary: false, | ||
| ginOperatorClass: GinOperatorClass.jsonbPath, | ||
| ), | ||
| ], | ||
| foreignKeys: [], | ||
| managed: true, | ||
| ); | ||
|
|
||
| var mismatches = tableA.like(tableB); | ||
|
|
||
| expect(mismatches.length, 1); | ||
| expect(mismatches.first, isA<IndexComparisonWarning>()); | ||
| expect(mismatches.first.subs.length, 1); | ||
| expect(mismatches.first.subs.first.expected, equals('jsonb')); | ||
| expect(mismatches.first.subs.first.found, equals('jsonbPath')); | ||
| expect(mismatches.first.subs.first.isMismatch, isTrue); | ||
| }, | ||
| ); |
There was a problem hiding this comment.
This test seems duplicated with the last one.
| expect(index.elements.first.definition, 'indexed2'); | ||
| }); | ||
|
|
||
| test('then the explicitly declared gin index with operator class exists.', |
There was a problem hiding this comment.
| test('then the explicitly declared gin index with operator class exists.', | |
| test('then the explicitly declared gin index with operator class exists with correct operator class.', | |
| indexed0: List<String> | ||
| indexed1: List<String>, serializationDataType=jsonb | ||
| indexed2: List<String>, serializationDataType=jsonb | ||
| indexed3: List<String>, serializationDataType=jsonb |
There was a problem hiding this comment.
Suggestion: It seems the indexed1 field is not being used on any test, right? It would be nicer if we name the fields after what we are testing on them, such as:
| indexed0: List<String> | |
| indexed1: List<String>, serializationDataType=jsonb | |
| indexed2: List<String>, serializationDataType=jsonb | |
| indexed3: List<String>, serializationDataType=jsonb | |
| notJsonb: List<String> | |
| jsonb: List<String>, serializationDataType=jsonb | |
| jsonbIndexed: List<String>, serializationDataType=jsonb | |
| jsonbIndexedGin: List<String>, serializationDataType=jsonb | |
| jsonbIndexedGinJsonbPath: List<String>, serializationDataType=jsonb |
This way it gets clear on why each field is here and we can also analyze tests easier, without having to come back to the model to see how is each index# field used.
| jsonb1: List<String> | ||
| jsonb2: List<String>, serializationDataType=jsonb | ||
| json: List<String>, serializationDataType=json |
There was a problem hiding this comment.
Same as comment above regarding the names of the fields.
| jsonb1: List<String> | |
| jsonb2: List<String>, serializationDataType=jsonb | |
| json: List<String>, serializationDataType=json | |
| implicitJsonb: List<String> | |
| explicitJsonb: List<String>, serializationDataType=jsonb | |
| json: List<String>, serializationDataType=json |
| void main() { | ||
| var config = GeneratorConfigBuilder().withEnabledExperimentalFeatures( | ||
| [ExperimentalFeature.serializeAsJsonb]).build(); | ||
|
|
There was a problem hiding this comment.
There are a two tests that we could add here (similar to the ones at index_distance_function_test.dart):
- Given a class with a gin index with with non-string operator class, then collect an error about parameter type.
- Given a class with a non-gin index and gin operator class, then collect an error that operator class can only be used with gin indexes.
If we change to make gin default index type for jsonb fields on Serverpod (from previous discussion), we should also add a test here to ensure that indexes with no explicit type are parsed as gin.
|
|
||
| test('then serializationDataType is set to jsonb.', () { | ||
| expect(definition.serializationDataType, SerializationDataType.jsonb); | ||
| }); |
There was a problem hiding this comment.
I suggest we centralize the field configuration only on the field level. It makes understanding the code easier, since the serialization will be evaluated only on the model parsing and just used everywhere else. Any developer can be sure that, after the model is parsed, each field's serialization will be correctly set. And we also avoid having rules spread across the code of how to treat null on field level, precedence of model over project config, etc.
For the CLI package, all definition types (ClassDefinition, EndpointDefinition, TypeDefinition, etc.) are first-class citizens - not implementation details. They are the product of the parsing and the main artifacts that we rely on to build the code generation. So we can build the feature around them and use the tests to ensure their correct building during parse phase.
With this change, tests gets as simple and isolated as my previous comment, because we only need to ensure that the field serialization is being correctly overridden with each configuration setup. Once the field serialization is ensured, we already know it will be applied to the model due to the tests of the field level.
| }); | ||
| }); | ||
|
|
||
| group('Given a valid class definition with serializationDataType set and the default serialization for project is set, the field should be defined to serialize to json when validating', () { |
There was a problem hiding this comment.
After the change from my previous comment to centralize the serialization evaluation (and override) on the parser, we can reorganize the tests and move the model and project level tests to outside of the field folder where they are.
File names can also be shortened to:
.../field/field_serialization_data_type_test.dart.../class_serialization_data_type_test.dart.../project_serialization_data_type_test.dart
| test( | ||
| 'Given a class with set serializationDataType and a field with no serializationDataType set but the default serialization for project is set, then the generated field should be serialized as defined at class level.', | ||
| () { | ||
| var models = [ | ||
| ModelSourceBuilder().withYaml( | ||
| ''' | ||
| class: Example | ||
| table: example | ||
| serializationDataType: json | ||
| fields: | ||
| tags: List<String> | ||
| ''', | ||
| ).build() | ||
| ]; | ||
|
|
||
| var collector = CodeGenerationCollector(); | ||
| var analyzer = StatefulAnalyzer(configWithEnabledSerializeAsJsonbByDefault, models, onErrorsCollector(collector)); | ||
|
|
||
| var definitions = analyzer.validateAll(); | ||
|
|
||
| var definition = definitions.first as ModelClassDefinition; | ||
| expect(definition.fields.last.type.serializationDataType, SerializationDataType.json); | ||
| }, | ||
| ); |
There was a problem hiding this comment.
This is the kind of reduction in complexity (and uncertainty) that centralizing the field serialization definition on the parsing gives us. And we rely on tests to ensure that no optimization inadvertedly skip setting the field level property and break the feature.
| }); | ||
| }); | ||
|
|
||
| group('Given a valid class definition with serializationDataType set and the default serialization for project is set, the field should be defined to serialize to json when validating', () { |
There was a problem hiding this comment.
One general comment on the descriptions after the refactor is that they are now out of the Given [scenario] when [acting] then [result] pattern. All tests are having part of the scenario described on the when, instead of the Given. A good rule of thumb is to avoid with that is not related to parameter values on the when.
The refactor will simplify the test descriptions because we won't need to mention project-level and model-level configs on every test, since each will be scoped to one isolated level.
| test( | ||
| 'Given a class with a field with no serializationDataType set but the class has a serializationDataType set, then the generated field should be serialized as defined at class level.', | ||
| () { | ||
| var models = [ | ||
| ModelSourceBuilder().withYaml( | ||
| ''' | ||
| class: Example | ||
| table: example | ||
| serializationDataType: jsonb | ||
| fields: | ||
| tags: List<String> | ||
| ''', | ||
| ).build() | ||
| ]; | ||
|
|
||
| var collector = CodeGenerationCollector(); | ||
| var analyzer = StatefulAnalyzer(config, models, onErrorsCollector(collector)); | ||
|
|
||
| var definitions = analyzer.validateAll(); | ||
|
|
||
| var definition = definitions.first as ModelClassDefinition; | ||
| expect(definition.fields.last.type.serializationDataType, SerializationDataType.jsonb); | ||
| }, | ||
| ); | ||
|
|
||
| test( | ||
| 'Given a class with class and field with set serializationDataType, then the generated field should be serializationDataType as defined at field level.', | ||
| () { | ||
| var models = [ | ||
| ModelSourceBuilder().withYaml( | ||
| ''' | ||
| class: Example | ||
| table: example | ||
| serializationDataType: jsonb | ||
| fields: | ||
| tags: List<String>, serializationDataType=json | ||
| ''', | ||
| ).build() | ||
| ]; | ||
|
|
||
| var collector = CodeGenerationCollector(); | ||
| var analyzer = StatefulAnalyzer(config, models, onErrorsCollector(collector)); | ||
|
|
||
| var definitions = analyzer.validateAll(); | ||
|
|
||
| var definition = definitions.first as ModelClassDefinition; | ||
| expect(definition.fields.last.type.serializationDataType, SerializationDataType.json); | ||
| }, | ||
| ); |
There was a problem hiding this comment.
This is the separation we are aiming for the tests, which reflects the feature being evaluated in one place only. Each upper level (model and project) is only concerned that it is overriding the below levels:
- The
class_serialization_data_type_test.dartshould only worry about overriding the field level config when it is null and not otherwise. - The
project_serialization_data_type_test.dartshould only worry about overriding the field level config when it is null and model level is not set.
Tests should not worry about upper level configuration (model and project on field tests, project on model tests).
|
@marcelomendoncasoares Thank you for the changes and all the suggestions! You are an equal co-author of this feature! Talking about co-authorship. I’ve run out of time between my client projects. Since I dedicate 100% to their project when I work for clients, I will not be able to work on this for a while. I hope you can implement what you already suggested and bring this PR to a merge. |
|
No problem, @borutjures! We can take it from here and finish the implementation. You have done a great job so far and this will be a valuable addition to the framework! |
|
I’m really struggling with the outbox pattern when the payload is a plain string. Can we agree this feature would make our lives easier. If it’s already done, I hope to see it in a release soon Thanks for your work! |
|
Will this be in 3.0.0? |
|
@ancill @t-kietzmann We can not guarantee that this will be in before 3.0 release, but we will do our best for it! Nevertheless, even if it doesn't make before the release, it will be added very shortly after, since this PR is nearly ready and it does not introduce any breaking change. The neat part of adding it before 3.0 would be the possibility to set |
…eat-jsonb-support
|
@marcelomendoncasoares Do you know when the release will be ready? :D |
@FantaMagier We're aiming for the release until mid-December! Then we will be able to review our backlog and prioritize having this |
|
Hey marcelomendoncasoares thanks for you answer! Do you plan it in January release? |
Unfortunately I can't promise a deadline, but we do want to have this in soon. I'll post an update here once this gets to work. |
This PR enables the user to specify whether to use
jsonorjsonbwhen serializing serializable fields.This is done by adding a new keyword
serializeto models and fields:serializeat the model level means that all serializable fields in the model will use the specified type (jsonbin the above example). This can still be overridden by addingserializeto a field (tagsfield in the above example).The implementation adds two experimental features:
serializekeyword for models and fieldsjsonbas a default type when serializingBoth experimental features can be used independently:
serializeAsJsonbAsDefaultto usejsonbfor all serializable fields.serializeAsJsonbto specify which models/fields should usejsonb.jsonbas default but specify some fields to usejson.Note: There is an existing
serializedkeyword used for enums. I intentionally use a different keyword since they have different values (EnumSerialization(byName, byIndexvs.CustomSerialization(json, jsonb)).This PR tries to close #3919