Skip to content

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

Adding PostgREST post

Copple1e1ac5f5238f
diff --git a/apps/www/_blog/2022-08-19-launch-week-5-community-day.mdx b/apps/www/_blog/2022-08-19-launch-week-5-community-day.mdx
index 11565325d54..4d994733d86 100644
--- a/apps/www/_blog/2022-08-19-launch-week-5-community-day.mdx
+++ b/apps/www/_blog/2022-08-19-launch-week-5-community-day.mdx
@@ -19,13 +19,14 @@ To wrap up Launch Week 5, we're showcasing some of the communities and contribut
## Launch Week 5 - a new era?!
-If you're an avid Launch Week participant, you might have been surprised, because we used to kick off launch week with community day on Mondays. And we used to close out Launch Week with a bunch more things on Friday as well as the kickoff for our virtual Hackathon.
+If you're an avid Launch Week participant, you might have been surprised this time because we usually kick-off with Community Day on Mondays.
+And we previously closed Launch Week with a bunch more things on Friday, and the start of our virtual Hackathon.
-This time, we're switching things around a bit:
+This time, we're switching things around:
-- [Monday to Thursday](https://supabase.com/launch-week) are the big ticket feature launches.
+- [Monday to Thursday](/launch-week) are the big-ticket launches.
- Friday, we highlight all the additional “one more thing(s)” that we've launched, as well as shine a light on our awesome community contributions.
-- As [you might have noticed](https://supabase.com/blog/launch-week-5-hackathon), we now run our virtual Hackathon throughout Launch Week, and as always you can win some awesome limited edition swag, and for the first time ever, there's a $1500 GitHub sponsorship awarded to the best overall project!
+- As you [might have noticed](/blog/launch-week-5-hackathon), we now run our virtual Hackathon throughout Launch Week, and as always you can win some awesome limited edition swag, and for the first time ever, there's a $1500 GitHub sponsorship awarded to the best overall project!
<blockquote class="twitter-tweet" data-theme="dark">
<p lang="en" dir="ltr">
@@ -38,7 +39,8 @@ This time, we're switching things around a bit:
</a>
</p>
&mdash; Daniel Cranney 🇬🇧 (@danielcranney) <a href="https://twitter.com/danielcranney/status/1557249589182447616?ref_src=twsrc%5Etfw">August 10, 2022</a>
-</blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
+</blockquote>
+<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
_Our limited edition swag is approved by professional swag testers like Peanut!_
@@ -57,9 +59,9 @@ _Our limited edition swag is approved by professional swag testers like Peanut!_
We now have a shiny new [Launch Week page](http://supabase.com/launch-week), your one-stop shop for all things Launch Week, where you can find each day's feature as well as highlights from the past Launch Weeks.
-We've also taken a page out of [Vercel's Virtual Events Starter Kit](https://vercel.com/templates/next.js/virtual-event-starter-kit), and generated over 3000 virtual tickets. Thank you all for participating, we love [seeing your tickets on Twitter](https://twitter.com/hashtag/SupaLaunchWeek?src=hashtag_click&f=live)! To make this work, we've adapted the Virtual Events Starter Kit and [added in a Supabase Database provider](https://github.com/vercel/virtual-event-starter-kit/pull/88) as an alternative to the Redis database option.
+We've taken a page out of [Vercel's Virtual Events Starter Kit](https://vercel.com/templates/next.js/virtual-event-starter-kit), and generated over 3000 virtual tickets. Thank you all for participating, we love [seeing your tickets on Twitter](https://twitter.com/hashtag/SupaLaunchWeek?src=hashtag_click&f=live)! To make this work, we've adapted the Virtual Events Starter Kit and [added in a Supabase Database provider](https://github.com/vercel/virtual-event-starter-kit/pull/88) as an alternative to the Redis database option.
-We've also added a Golden Ticket mechanic, distributing some special edition launch week swag to some lucky winners. If you're interested in how we've built this, check out the video above with a brief explanation.
+We've added a Golden Ticket mechanic, distributing some special edition launch week swag to some lucky winners. If you're interested in how we've built this, check out the video above with a brief explanation.
---
@@ -80,7 +82,9 @@ We've also added a Golden Ticket mechanic, distributing some special edition lau
For our Open Source Spotlight we're hearing from [Dmitry Dygalo](https://twitter.com/Stranger6667) from [schemathesis.io](https://schemathesis.io/) who works on a multitude of open-source projects. He's the author and maintainer of [jsonschema-rs](https://github.com/Stranger6667/jsonschema-rs), which is the foundation for our new [pg_jsonschema extension](https://github.com/supabase/pg_jsonschema), a PostgreSQL extension providing JSON Schema validation.
-### [Placeholder] Postgrest v10: Native Types
+### Postgrest v10: Native Types
+
+Lorem ipsum
---
diff --git a/apps/www/_blog/2022-08-19-postgrest-v10.mdx b/apps/www/_blog/2022-08-19-postgrest-v10.mdx
index dfe629f40c4..92696d74fb0 100644
--- a/apps/www/_blog/2022-08-19-postgrest-v10.mdx
+++ b/apps/www/_blog/2022-08-19-postgrest-v10.mdx
@@ -10,4 +10,260 @@ date: '2022-08-19T07:02:00'
toc_depth: 2
---
-Lorem ipsum
+PostgREST turns your PostgreSQL database automatically into a RESTful API. Today, PostgREST v10 was [released](https://github.com/PostgREST/postgrest/releases/tag/v10.0.0). v10 is not available on the Supabase Platform yet, but it is available for [self-hosting](https://supabase.com/docs/guides/hosting/overview) or as a [executable binary](https://github.com/PostgREST/postgrest/releases/tag/v10.0.0).
+
+Let's take a look at some of its new features that go hand in hand with [supabase-js v2](https://supabase.com/blog/supabase-js-v2).
+
+# EXPLAIN
+
+Akin to the [PostgreSQL EXPLAIN](https://www.postgresql.org/docs/current/sql-explain.html) command, you can now get the execution plan of a request through REST or `supabase-js`. This works transparently for reads, writes and RPC because every request to PostgREST generates a single SQL query.
+
+This is only suitable for development environments and is only enabled when the `db-plan-enabled` config is set to `true`.
+
+## Getting the execution plan through REST
+
+The execution plan can be obtained by using a vendor media type on the `Accept` header.
+
+```bash
+$ curl -H 'Accept: application/vnd.pgrst.plan' \
+ 'https://<project>.supabase.co/clients?select=*&id=eq.1'
+
+Aggregate (cost=8.18..8.20 rows=1 width=112)
+ -> Index Scan using clients_pkey on clients (cost=0.15..8.17 rows=1 width=36)
+ Index Cond: (id = 1)
+```
+
+The `text` format is used by default, which gives you the same output you’d get in other SQL clients like `psql`. You can change the format to JSON by using a media type suffix `application/vnd.pgrst.plan+json`.
+
+## Explaining supabase-js queries
+
+For `supabase-js`, you can get the execution plan using the `explain()` method. This works for every `supabase-js` method, including `rpc()`. Here’s an example for `select()`.
+
+```jsx
+const { data, error } = await supabase.from('projects').select('*').eq('id', 1).explain()
+
+console.log(data)
+```
+
+```
+Aggregate (cost=8.18..8.20 rows=1 width=112)
+ -> Index Scan using projects_pkey on projects (cost=0.15..8.17 rows=1 width=40)
+ Index Cond: (id = 1)
+```
+
+Explaining the plan output in detail is beyond the scope of this blog post but basically it’s a tree of operations that PostgreSQL will follow for executing a query. Here we see the “Aggregate” node which corresponds to the `json_agg` function used by the PostgREST generated query(more details on how to find these later) and the “Index Scan” node which means an index on “id” was used for a fast search.
+
+## Explaining RLS policies
+
+The raison d'etre of `explain()` is to provide quicker feedback on the performance of queries, especially in the presence of RLS policies. For instance, let’s say we have this basic policy:
+
+```sql
+create policy "anon can't read"
+on projects for select to anon
+using (
+ false
+);
+```
+
+And we use `explain()` again, this time using the `analyze` option(actually executes the query, same as the EXPLAIN ANALYZE counterpart in SQL) so we can see the execution time of the query.
+
+```jsx
+const { data, error } = await supabase
+ .from('projects')
+ .select('*')
+ .eq('id', 1)
+ .explain({ analyze: true })
+
+console.log(data)
+```
+
+```
+Aggregate (cost=8.18..8.20 rows=1 width=112) (actual time=0.017..0.018 rows=1 loops=1)
+ -> Index Scan using projects_pkey on projects (cost=0.15..8.17 rows=1 width=40) (actual time=0.012..0.012 rows=0 loops=1)
+ Index Cond: (id = 1)
+ Filter: false
+ Rows Removed by Filter: 1
+Planning Time: 0.092 ms
+Execution Time: 0.046 ms
+```
+
+Here you can see the “Filter” node, which is a simple `false` as defined by the above policy, this proves that the RLS policy is getting applied. Also the actual “Execution Time” is shown, which is a fraction of a millisecond. Note that this is only the query execution time, it doesn’t account for the latency for transferring the data from the database to the frontend.
+
+## Getting the Query Identifier
+
+`explain()` is also useful for getting the [pg_stat_statements](https://www.postgresql.org/docs/current/pgstatstatements.html) query identifier, which you can use in the Supabase logs to obtain the generated SQL queries. Here we use the json `format` and the `verbose` option to get it.
+
+```jsx
+const { data, error } = await supabase
+ .from('projects')
+ .select('*')
+ .eq('id', 1)
+ .explain({ format: 'json', verbose: true })
+
+console.log(data[0]['Query Identifier'])
+// 2811722635570756600
+```
+
+For getting more detailed information, you can also use the `settings`, `buffers`, `wal` options with `explain()` .
+
+# Improved Relationship Detection
+
+## One-to-one relationships
+
+To avoid unnecessary JSON arrays in a query result, one-to-one relationships are now automatically detected. For this you can use a:
+
+```sql
+-- A unique constraint on a foreign key
+create table country(
+ id int primary key
+, name text
+);
+
+create table capital(
+ id int primary key
+, name text
+, country_id int unique
+, foreign key (country_id) references country(id)
+);
+
+-- or a primary key on a foreign key
+create table country(
+ id int primary key
+, name text
+);
+
+create table capital(
+ id int primary key
+, name text
+, foreign key (id) references country(id)
+);
+```
+
+Both options should give you a json object when embedding one table with the other.
+
+```sql
+const { data, error } = await supabase
+ .from('country')
+ .select('name,capital(name)')
+ .in('id', [1, 2])
+
+console.log(data)
+
+[
+ {"name":"Afghanistan","capital":{"name":"Kabul"}}
+, {"name":"Algeria","capital":{"name":"Algiers"}}
+]
+```
+
+## Computed relationships
+
+PostgREST uses foreign keys to detect relationships. This poses a problem on database objects that cannot have foreign keys, like views. Though PostgREST tries to infer relationships based on the views’ source tables foreign keys([docs](https://postgrest.org/en/latest/api.html#embedding-views)), this is not infallible - in particular, it fails when views have a complex definition (e.g. multiple UNIONs). For this you can use “computed relationships”, which are “inlinable” SQL functions similar to computed columns.
+
+Let’s assume we have a `players` view, a `scores` materialized view and we want to define a one-to-many relationship on them.
+
+```sql
+create view players as
+select id, name from players_a
+union
+select id, name from players_b;
+
+create materialized view scores as
+select name as lvl_name, compute_score(stats) as total, player_id from level_1;
+union
+select name as lvl_name, compute_score(stats) as total, player_id from level_2;
+```
+
+For this we can define a couple of computed relationships.
+
+```sql
+-- many-to-one relationship on scores -> players
+create function player(scores)
+returns setof players rows 1 -- rows 1 defines a "one" end
+language sql stable
+as $$
+ select *
+ from players
+ where id = $1.player_id;
+$$;
+
+-- one-to-many relationship on players -> scores
+create function scores(players)
+returns setof scores -- there's an implicit rows 1000 here, which is assumed to be "many"
+language sql stable
+as $$
+ select *
+ from scores
+ where player_id = $1.id;
+$$;
+```
+
+And now we can embed both views from one end to the other. Note that the function names are arbitrary, here we named them similar to the views for convenience.
+
+```jsx
+const { data, error } = await supabase
+ .from('scores')
+ .select('lvl_name, player(name)')
+ .eq('lvl_name', "Grand Prix 1")
+ .single()
+
+console.log(data)
+
+{
+ "lvl_name": "Grand Prix 1",
+ "player": { "name": "Ben Richards"}
+}
+
+const { data, error } = await supabase
+ .from('players')
+ .select('name,scores(lvl_name, total)')
+ .eq('id', 1)
+ .single()
+
+console.log(data)
+
+{
+ "name":"Ben Richards",
+ "scores":[
+ {"lvl_name": "Grand Prix 1", "total": 48761.24},
+ {"lvl_name": "Grand Prix 2", "total": -40.25}
+ ]
+}
+```
+
+Computed relationships follow the rules of [Inlining of SQL Functions](https://wiki.postgresql.org/wiki/Inlining_of_SQL_functions), which basically allows them to be injected into PostgREST generated queries, making them efficient to use. You can also use computed relationships to override detected relationships.
+
+## Breaking change on many-to-many relationships
+
+Detecting join tables for many-to-many relationships has been working for many releases. However on complex schemas join tables can be incorrectly detected, causing errors when used in resource embedding. For this the following BREAKING CHANGE had to be made:
+
+```sql
+-- for "books_authors" to be detected as a join table,
+-- the primary key must include the foreign key columns
+-- of the many-to-many ends
+
+create table books(
+ id int primary key
+, name text
+);
+
+create table books_authors(
+ book_id int references books(id)
+, author_id int references authors(id)
+, primary key(book_id, author_id) -- this is now necessary
+);
+
+create table authors(
+ id int primary key
+, name text
+);
+```
+
+If changing the PK is not feasible for a particular case, the alternative would be using computed relationships to define the many-to-many.
+
+One-to-many and many-to-one relationships keep working as always, no change in their detection.
+
+# Closing up
+
+Computed relationships are the first step towards PostgREST extensibility, customizing the aggregate used for the response and custom operators are planned for next releases.
+
+We’ll release PostgREST 10 on the Supabase platform over the next month.