Skip to content

feat: Add support for jsonb columns - #3934

Closed
borutjures wants to merge 42 commits into
serverpod:mainfrom
borutjures:feat-jsonb-support
Closed

borutjures wants to merge 42 commits into
serverpod:mainfrom
borutjures:feat-jsonb-support

Conversation

@borutjures

Copy link
Copy Markdown
Contributor

This PR enables the user to specify whether to use json or jsonb when serializing serializable fields.

This is done by adding a new keyword serialize to models and fields:

class: Greeting
table: greeting
serialize: jsonb
fields:
  author: Author
  tags: List<String>, serialize=json

serialize at the model level means that all serializable fields in the model will use the specified type (jsonb in the above example). This can still be overridden by adding serialize to a field (tags field in the above example).

The implementation adds two experimental features:

  • serializeAsJsonb: allows a use of serialize keyword for models and fields
  • serializeAsJsonbAsDefault: uses jsonb as a default type when serializing

Both experimental features can be used independently:

  • Enable only serializeAsJsonbAsDefault to use jsonb for all serializable fields.
  • Enable only serializeAsJsonb to specify which models/fields should use jsonb.
  • Enable both to use jsonb as default but specify some fields to use json.

Note: There is an existing serialized keyword used for enums. I intentionally use a different keyword since they have different values (EnumSerialization(byName, byIndex vs. CustomSerialization(json, jsonb)).

This PR tries to close #3919

@coderabbitai

coderabbitai Bot commented Aug 29, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Aug 29, 2025 •

Copy link
Copy Markdown

CLA Assistant Lite bot All contributors have signed the CLA ✍️ ✅

@borutjures

Copy link
Copy Markdown
Contributor Author

I have read the CLA Document and I hereby sign the CLA

@borutjures borutjures changed the title feat: add support for jsonb columns Feat: add support for jsonb columns Aug 29, 2025
@borutjures borutjures changed the title Feat: add support for jsonb columns feat: Add support for jsonb columns Aug 29, 2025

@marcelomendoncasoares marcelomendoncasoares 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.

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.

@borutjures

Copy link
Copy Markdown
Contributor Author

@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 jsonb fields are so close to the database layer that the existing integration tests for json already cover jsonb fields too.

Please let me know if I missed anything.

The only thing I would like to change before going further is renaming of JsonSerializationDataType to SerializationDataType (as mentioned in a comment above).

@marcelomendoncasoares marcelomendoncasoares 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 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 marcelomendoncasoares 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.

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.', () {

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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?

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 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.

@borutjures

Copy link
Copy Markdown
Contributor Author

I fixed the dart format errors. Other CI failures seam to be unrelated to this feature.

@marcelomendoncasoares marcelomendoncasoares 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.

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 GeneratorConfig class.
  • Make gin type the default index type for jsonb fields when the type is 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 to gin when the type is missing so we have no surprises for users that expect Postgres btree default - 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!

Comment on lines +1708 to +1780
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);
},
);

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.

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.',

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.

Suggested change
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.',

Comment on lines +4 to +7
indexed0: List<String>
indexed1: List<String>, serializationDataType=jsonb
indexed2: List<String>, serializationDataType=jsonb
indexed3: List<String>, serializationDataType=jsonb

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.

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:

Suggested change
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.

Comment on lines +5 to +7
jsonb1: List<String>
jsonb2: List<String>, serializationDataType=jsonb
json: List<String>, serializationDataType=json

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.

Same as comment above regarding the names of the fields.

Suggested change
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();

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.

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);
});

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 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', () {

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.

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

Comment on lines +140 to +163
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);
},
);

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.

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', () {

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 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.

Comment on lines +66 to +114
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);
},
);

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.

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.dart should only worry about overriding the field level config when it is null and not otherwise.
  • The project_serialization_data_type_test.dart should 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).

@borutjures

Copy link
Copy Markdown
Contributor Author

@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.

@marcelomendoncasoares

Copy link
Copy Markdown
Collaborator

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!

@ancill

ancill commented Oct 4, 2025

Copy link
Copy Markdown

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!

@t-kietzmann

Copy link
Copy Markdown

Will this be in 3.0.0?

@marcelomendoncasoares

Copy link
Copy Markdown
Collaborator

@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 jsonb as default for the framework, but it can get in as an opt-in otherwise.

@FantaMagier

Copy link
Copy Markdown

@marcelomendoncasoares Do you know when the release will be ready? :D

@marcelomendoncasoares

marcelomendoncasoares commented Dec 5, 2025 •

Copy link
Copy Markdown
Collaborator

@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 jsonb feature in.

@ancill

ancill commented Jan 5, 2026

Copy link
Copy Markdown

Hey marcelomendoncasoares thanks for you answer! Do you plan it in January release?

@marcelomendoncasoares

Copy link
Copy Markdown
Collaborator

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.

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.

Support for jsonb indexable columns

5 participants