Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

clean up json schema post

Coppleb64c917bbca7
diff --git a/apps/www/_blog/2022-08-19-pg_jsonschema.mdx b/apps/www/_blog/2022-08-19-pg_jsonschema.mdx
index d01982ba968..ad11620a027 100644
--- a/apps/www/_blog/2022-08-19-pg_jsonschema.mdx
+++ b/apps/www/_blog/2022-08-19-pg_jsonschema.mdx
@@ -10,11 +10,13 @@ date: '2022-08-19'
toc_depth: 3
---
-Released on the [Supabase](https://supabase.com/) platform today, [supabase/pg_jsonschema](https://github.com/supabase/pg_jsonschema) is a Postgres extension adding [JSON Schema](https://json-schema.org/) validation support for `json` and `jsonb` data types.
+Released on the Supabase platform today, [pg_jsonschema](https://github.com/supabase/pg_jsonschema) is a Postgres extension
+which adds [JSON Schema](https://json-schema.org/) validation support for `json` and `jsonb` data types.
-## Intro
+## The use-case for JSON validation
-Despite Supabase being an SQL shop, even our most zealous relational data model advocates (begrudgingly) recognize some advantages to the document data model. Mainly, if some complex data will always be consumed together, a document data type can be a good fit.
+Despite Supabase being an SQL shop, even our most zealous relational data model advocates (begrudgingly) recognize some advantages to the document data model.
+Mainly, if some complex data will always be consumed together, a document data type can be a good fit.
**For Example**:
@@ -22,24 +24,24 @@ If our application receives data via a webhook:
```json
{
- "status_code": 200,
- "checksum": "89b623f6332d2b9b42b4e17eaf1bcc60"
- "headers": {
- "Content-Type": "application/json",
- "Last-Modified": "Tue, 09 Aug 2022 09:14:10 GMT"
- },
- "payload": {
- {
- "sucess": true,
- "content": {
- "account_id": "d928b484-16bd-4f10-a827-3eb959b4cc14",
- "event": "SUBSCRIBED",
- "subscriptions": [
- {"subscription_id": 481, "exp": 1660050940},
- {"subscription_id": 121, "exp": 1660041852},
- ]
- }
- }
+ "status_code": 200,
+ "checksum": "89b623f6332d2b9b42b4e17eaf1bcc60"
+ "headers": {
+ "Content-Type": "application/json",
+ "Last-Modified": "Tue, 09 Aug 2022 09:14:10 GMT"
+ },
+ "payload": {
+ {
+ "sucess": true,
+ "content": {
+ "account_id": "d928b484-16bd-4f10-a827-3eb959b4cc14",
+ "event": "SUBSCRIBED",
+ "subscriptions": [
+ {"subscription_id": 481, "exp": 1660050940},
+ {"subscription_id": 121, "exp": 1660041852},
+ ]
+ }
+ }
}
}
```
@@ -48,9 +50,10 @@ A reasonable swing at normalizing that data into tables might look like this:
![pg_jsonschema_erd.png](/images/blog/lw5-pg_jsonschema/pg_jsonschema_erd.jpg)
-That’s a lot of architecting! Moreover, the query to recover the original input requires 5 joins!
+That's a lot of architecting! Moreover, the query to recover the original input requires 5 joins!
-A solution that aligns better with our intent would be to persist whatever we receive from the external service so long as it meets a minimum set of requirements. With Postgres’ `json` data type we can achieve half of that goal.
+A solution that aligns better with our intent would be to persist whatever we receive from the external service so long as it meets a minimum set of requirements.
+With Postgres' `json` data type we can achieve half of that goal.
![pg_jsonschema_erd2.png](/images/blog/lw5-pg_jsonschema/pg_jsonschema_erd2.jpg)
@@ -64,14 +67,14 @@ Now what about this part?
The flexibility of document types also comes with some downsides.
-The schema of the json payload from the previous example is a little intense for a blog post so let’s instead say we intend for a table’s `json` column to hold objects with a `string` attribute named `foo` and no additional attributes.
+The schema of the json payload from the previous example is a little intense for a blog post so let's instead say we intend for a table's `json` column to hold objects with a `string` attribute named `foo` and no additional attributes.
Without constraints, the setup would be:
```sql
create table some_table (
- id serial primary key,
- metadata json not null
+ id serial primary key,
+ metadata json not null
);
insert into some_table (metadata)
@@ -81,47 +84,42 @@ values (<SQL Input>);
But the resulting schema is much more permissive than our intent. When inserting a mix of correct and incorrect values:
-![Table 1](/images/blog/lw5-pg_jsonschema/table-1.png)
-
-| SQL input | Inserted | metadata column value (json) | note |
-| ------------------------------- | -------- | ---------------------------- | ----------------------------------- |
-| '{"foo": "bar"}' | Yes | {"foo": "bar"} | expected payload |
-| null | No | | sql null |
-| ‘null’ | Yes | null | json null |
-| to_json('null'::text) | Yes | “null” | json string containing value “null” |
-| to_json('{"foo": "bar"}'::text) | Yes | "{\"foo\": \"bar\"}” | object serialized as a string |
-| '{"fov": "bar"}' | Yes | {"fov": "bar"} | object with typo “fov” vs “foo” |
-| '{"foo": 5}' | Yes | {"foo": 5} | attribute “foo” has wrong type |
-| '{"foo": "bar", “x”: 1}' | Yes | {"foo": "bar", “x”: 1} | extra attribute “x” |
-| | | | |
+![Check constraints](/images/blog/lw5-pg_jsonschema/table-1.png)
Only 2 of our 8 test cases match our target data model.
-A core strength of SQL databases is their ability to constrain data’s [types](https://www.postgresql.org/docs/current/datatype.html), nullability, [referential integrity](https://www.postgresql.org/docs/current/tutorial-fk.html), [uniqueness](https://www.postgresql.org/docs/current/ddl-constraints.html), and even [arbitrary developer-defined rules](https://www.postgresql.org/docs/current/sql-createtrigger.html). Those constraints are a lot to sacrifice to gain the convenience of document types.
+A core strength of SQL databases is their ability to constrain data's [types](https://www.postgresql.org/docs/current/datatype.html), nullability,
+[referential integrity](https://www.postgresql.org/docs/current/tutorial-fk.html), [uniqueness](https://www.postgresql.org/docs/current/ddl-constraints.html),
+and even [arbitrary developer-defined rules](https://www.postgresql.org/docs/current/sql-createtrigger.html).
+Those constraints are a lot to sacrifice to gain the convenience of document types.
-Fortunately, the challenge of validating `json` documents isn’t specific to SQL databases. NoSQL/Document databases, like MongoDB, [optionally enforce data constraints](https://www.mongodb.com/docs/atlas/app-services/schemas/) so there’s plenty of prior art for us to draw from.
+Fortunately, the challenge of validating `json` documents isn't specific to SQL databases. NoSQL/Document databases, like MongoDB,
+[optionally enforce data constraints](https://www.mongodb.com/docs/atlas/app-services/schemas/) so there's plenty of prior art for us to draw from.
## JSON Schema
-[JSON Schema](https://json-schema.org/) is a specification for validating the shape and contents of `json` documents. It can describe constraints for documents similar to those applied by relational databases.
+[JSON Schema](https://json-schema.org/) is a specification for validating the shape and contents of `json` documents.
+It can describe constraints for documents similar to those applied by relational databases.
Translating our constraints from the previous example into a JSON Schema we get:
-```json
-# objects with a string attribute named foo and no additional attributes
+```js
+// objects with a string attribute
+// named foo and no additional attributes
{
- "type": "object",
- "properties": {
- "foo": {
- "type": "string"
- }
- },
- "required": ["foo"],
- "additionalProperties": false
+ "type": "object",
+ "properties": {
+ "foo": {
+ "type": "string"
+ }
+ },
+ "required": ["foo"],
+ "additionalProperties": false
}
```
-Which is a formal and human-readable description of our intent. A tutorial on the JSON Schema language is out-of-scope for this article but you can find a full introduction in [their guide](https://json-schema.org/understanding-json-schema/index.html).
+Which is a formal and human-readable description of our intent. A tutorial on the JSON Schema language is out-of-scope
+for this article but you can find a full introduction in [their guide](https://json-schema.org/understanding-json-schema/index.html).
So now we have:
@@ -133,7 +131,8 @@ So now we have:
## pg_jsonschema
-[supabase/pg_jsonschema](https://github.com/supabase/pg_jsonschema) is a Postgres extension that can validate `json` and `jsonb` data types against a [JSON Schema](https://json-schema.org/). The extension offers two functions:
+[pg_jsonschema](https://github.com/supabase/pg_jsonschema) is a Postgres extension that can validate `json` and `jsonb` data types
+against a [JSON Schema](https://json-schema.org/). The extension offers two functions:
```sql
-- Validates a json *instance* against a JSON Schema *schema*
@@ -147,51 +146,42 @@ We can use those functions in combination with a [check constraint](https://www.
```sql
create table some_table(
- id serial primary key,
- metadata json not null,
-
- check (
- json_matches_schema(
- schema :='{
- "type": "object",
- "properties": {
- "foo": {
- "type": "string"
- }
- },
- "required": ["foo"],
- "additionalProperties": false
- }',
- instance := metadata
- )
- )
+ id serial primary key,
+ metadata json not null,
+
+ check (
+ json_matches_schema(
+ schema :='{
+ "type": "object",
+ "properties": {
+ "foo": {
+ "type": "string"
+ }
+ },
+ "required": ["foo"],
+ "additionalProperties": false
+ }',
+ instance := metadata
+ )
+ )
);
insert into some_table(metadata)
values
- (<SQL input>);
+ (<SQL input>);
```
With that check constraint in place, we re-run the same test cases:
-![Table 2](/images/blog/lw5-pg_jsonschema/table-2.png)
-
-| SQL input | Inserted | metadata column value | note |
-| ------------------------------- | -------- | ---------------------- | ----------------------------------- |
-| '{"foo": "bar"}' | Yes | {"foo": "bar"} | expected payload |
-| null | No | | sql null |
-| ‘null’ | No | null | json null |
-| to_json('null'::text) | No | “null” | json string containing value “null” |
-| to_json('{"foo": "bar"}'::text) | No | "{\"foo\": \"bar\"}” | object serialized as a string |
-| '{"fov": "bar"}' | No | {"fov": "bar"} | object with typo “fov” vs “foo” |
-| '{"foo": 5}' | No | {"foo": 5} | attribute “foo” has wrong type |
-| '{"foo": "bar", “x”: 1}' | No | {"foo": "bar", “x”: 1} | extra attribute “x” |
+![Check constraints 2](/images/blog/lw5-pg_jsonschema/table-2.png)
Now all 8 tests are handled correctly. In cases where records failed to insert, Postgres throws an error referencing the failing constraint.
> ERROR: new row for relation "some_table" violates check constraint "some_table_metadata_check"
+>
> DETAIL: Failing row contains (1, null).
+>
> SQL state: 23514
With these tools you can wield the flexibility of `json`/`jsonb` data types without sacrificing the guarantees of a well specified data model!
@@ -202,4 +192,4 @@ To get started with `pg_jsonschema`, fire up a new supabase project and enable t
create extension pg_jsonschema;
```
-or follow the [Docker Compose instructions](https://github.com/supabase/pg_jsonschema#try-it-out) in the [repo’s README](https://github.com/supabase/pg_jsonschema/blob/master/README.md).
+or follow the [Docker Compose instructions](https://github.com/supabase/pg_jsonschema#try-it-out) in the [repo's README](https://github.com/supabase/pg_jsonschema/blob/master/README.md).
diff --git a/apps/www/public/rss.xml b/apps/www/public/rss.xml
index 35a834520e0..318bb1400f2 100644
--- a/apps/www/public/rss.xml
+++ b/apps/www/public/rss.xml
@@ -11,7 +11,7 @@
<guid>https://supabase.com/blog/supabase-vault</guid>
<title>Supabase Vault</title>
<link>https://supabase.com/blog/supabase-vault</link>
- <description>Today we're pre-releasing Vault,a Postgres extension for managing secrets and encryption inside your database.</description>
+ <description>Today we're announcing Vault, a Postgres extension for managing secrets and encryption inside your database.</description>
<pubDate>Thu, 18 Aug 2022 22:10:00 +0000</pubDate>
</item>
<item>