PostgreSQL Views in Action

Profile picture of ben

Draft

Nov 18, 2023

·

4 min read

·

1028 Views

While developing DevsForDevs, we often had to deal with complex data management tasks. PostgreSQL views have proven to be instrumental in streamlining these challenges. In this article, we'll dive into the code to illustrate how PostgreSQL views have played a pivotal role in optimizing data handling for DevsForDevs.

How we changed from a big client side code with many reused codes, to a simple and easy to use API, while keeping Supabase with PostgreSQL in the backend.

All that by just using views and fetching these directly!

Navigating Early Development Challenges:

As we embarked on building DevsForDevs, managing dynamic content and interactions presented significant challenges. The need for an efficient data management strategy became apparent, leading us to leverage the power of PostgreSQL views.

Old JavaScript Code

Managing dynamic data and performing joins on the client side using Supabase led to complexity and performance concerns.

Let's examine how the original client-side code looked and the challenges it presented.

// Original client-side code using Supabase.js for retrieving latest articles and their authors

const supabase = createClient('https://your-supabase-url.com', 'your-supabase-key');

async function getLatestArticles() {
  // Fetch latest articles
  const { data: latestArticles, error: articleError } = await supabase
    .from('articles')
    .select('id, title, content, created_at, author_id');

  // Fetch authors for each article
  const articlesWithAuthors = await Promise.all(
    latestArticles.map(async (article) => {
      const { data: author, error: authorError } = await supabase
        .from('authors')
        .select('name')
        .eq('id', article.author_id)
        .single();
      return { ...article, author: author?.name };
    })
  );

  return articlesWithAuthors;
}

// Usage example
getLatestArticles().then((articles) => console.log(articles));

The Efficiency of PostgreSQL Views with Supabase: A Transformation

Acknowledging the challenges posed by the original approach, we transitioned to using PostgreSQL views in conjunction with Supabase to simplify data retrieval and eliminate redundant client-side logic.

-- PostgreSQL view for retrieving latest articles with authors
CREATE VIEW latest_articles_with_authors AS
SELECT a.id, a.title, a.content, a.created_at, au.name as author_name
FROM articles a
JOIN authors au ON a.author_id = au.id
ORDER BY a.created_at DESC
LIMIT 10;

With the introduction of the PostgreSQL view and continued use of Supabase.js, the client-side code becomes significantly more straightforward.

// Simplified client-side code using Supabase.js and PostgreSQL view

const supabase = createClient('https://your-supabase-url.com', 'your-supabase-key');

async function getLatestArticles() {
  // Fetch latest articles with authors from the PostgreSQL view
  const { data: articles, error } = await supabase
    .from('latest_articles_with_authors')
    .select('*');

  return articles;
}

// Usage example
getLatestArticles().then((articles) => console.log(articles));

Now, the client-side code makes a single request to the server using Supabase.js, fetching data from the PostgreSQL view. This eliminates the need for multiple client-side joins and simplifies the overall development process.

PostgreSQL Views: Streamlining Development for DevsForDevs

  1. Simplified Data Retrieval: PostgreSQL views provided a server-side alternative, simplifying data retrieval by creating clear windows into the database. This replaced complex client-side queries with concise views encapsulating the necessary logic.

  2. Centralized Logic for Dynamic Content: In a community platform where content dynamically evolves, PostgreSQL views became a centralized mechanism for managing this dynamism. Views encapsulated logic for fetching the latest articles, popular discussions, and trending topics, adapting seamlessly to the ever-changing user landscape.

  3. Optimizing Performance: As DevsForDevs expanded, some queries posed performance challenges. PostgreSQL views played a vital role in optimizing these queries by predefining joins, filters, and aggregations, resulting in a more responsive user experience.

Exploring DevsForDevs: A Community in the Making

These code examples showcase how PostgreSQL views are actively shaping the development of DevsForDevs. If you're passionate about coding and community, explore the platform, signup and consider joining us on this exciting journey.

Conclusion

The combination of Supabase.js and PostgreSQL views has significantly improved the efficiency of data retrieval in DevsForDevs. By leveraging the simplicity of Supabase.js and centralizing the logic on the server side through PostgreSQL views, we've eliminated redundant code and enhanced the performance of our platform. This strategic optimization has proven to be a transformative step in our development journey.


Profile picture of ben

Written By

Ben Herbst

No bio found