How to Build Your Backend with Hasura and PostgreSQL
Building robust backends often involves extensive coding for CRUD operations, authorization, and business logic—a time-consuming process. This article explores how Hasura and PostgreSQL streamline backend development, enabling faster app launches with minimal coding effort.
Hasura, an open-source GraphQL engine, automatically generates GraphQL and REST APIs from your database schema. It supports data modeling, real-time queries, event programming, role-based authorization, and custom business logic execution via GraphQL actions.
PostgreSQL, a powerful open-source relational database, offers enterprise-level features comparable to Oracle and Microsoft SQL Server, making it a reliable choice for large-scale applications. Its use by companies like Netflix and Spotify underscores its capabilities. While Hasura supports other databases, this article focuses on PostgreSQL due to its accessibility and open-source nature. MySQL support is planned.
This guide highlights Hasura's features for building scalable backends for web and mobile apps. It also demonstrates how PostgreSQL's capabilities, accessed via SQL, can perform complex computations and analytics, reducing the need for custom server-side code.
Key Advantages:
- Rapid Backend Development: Hasura's auto-generated APIs significantly reduce coding time.
- PostgreSQL Power: Leverage PostgreSQL's advanced features (table inheritance, concurrency control, JSON/Spatial data types) for enhanced data integrity and performance.
- Real-time Capabilities: Hasura's real-time querying, event programming, and role-based authorization create highly responsive applications.
- Easy Deployment: Deploy Hasura using Docker for local development or Hasura Cloud for scalable, secure, globally distributed applications with features like monitoring and caching.
- Comprehensive Web Console: Manage data modeling, CRUD operations, and complex queries within Hasura's intuitive web console. Integrate with authentication and file storage providers.
- Streamlined Workflows: Utilize Hasura's migration tools and environment staging for seamless transitions between development and production, supporting CI/CD.
Why Choose PostgreSQL?
Relational databases like PostgreSQL offer advantages over other database types, including schema modeling, JOIN operations, and ACID transactions—crucial for data integrity. PostgreSQL further excels with:
- Table Inheritance: Efficient data modeling.
- Advanced Concurrency Control: Handles high-volume data writes effectively in multi-user environments.
- Fault Tolerance and Data Integrity: Reduces data corruption risks.
- Unique Data Types: Supports JSON and Spatial data types, beneficial for various applications.
PostgreSQL also acts as a computation server, executing custom functions and triggers for analytical tasks, eliminating the need for separate server-side code. This is achieved using:
- Views: Simplify complex queries.
- Functions & Operators: Perform date formatting, pattern matching, and arithmetic operations.
- Extensions: Extend PostgreSQL's functionality (e.g., PostGIS).
- Procedural Languages: Write user-defined functions and stored procedures (e.g., PL/pgSQL).
Hasura exposes this PostgreSQL logic via GraphQL, making it readily accessible to frontend applications.
PostgreSQL Examples:
- Example 1 (Online Users View): A view to retrieve currently active users:
CREATE OR REPLACE VIEW "public"."online_users" AS SELECT users.id, users.last_seen FROM users WHERE (users.last_seen >= (now() - '00:00:30'::interval));
- Example 2 (Geolocation with PostGIS): Find stores within a 1000-meter radius:
SELECT id, name, address, geom FROM Seattle_Starbucks WHERE ST_DWithin(geom, ST_MakePoint(-122.325959,47.625138)::geography, 1000);
What is Hasura?
Hasura is an open-source, real-time GraphQL engine that generates APIs for your database. Its web console allows for:
- Schema Modeling: Create tables, define relationships, and manage data.
- CRUD Operations: Perform create, read, update, and delete actions.
- Role-Based Access Control: Implement granular permissions.
- GraphQL/REST Endpoint Creation: Generate APIs for your data.
- SQL Execution: Run custom SQL queries.
- Action & Trigger Definition: Automate tasks and handle events.
Note: Hasura requires integration with a separate authentication provider (e.g., Auth0, Firebase) and file storage service. NHost offers an integrated solution.
Launching Hasura:
- Docker: Recommended for local development, offering easy setup and no rate limiting.
- Hasura Cloud: Simplifies deployment with scalability, security, and global distribution, including monitoring and caching features. A free tier is available with limitations.
Hasura Features (Detailed Overview):
-
Data Manager: Visual schema designer for creating tables, defining relationships, and managing data types (including JSON and custom types).
-
Authorization: Role-based access control with granular permissions for insert, select, update, and delete operations.
-
Queries: Execute various GraphQL queries (simple, nested, aggregation, filtering) directly within the console.
- Mutations: Perform INSERT, UPSERT, UPDATE, and DELETE operations with support for transactions.
- Subscriptions: Implement real-time data updates using GraphQL subscriptions over WebSockets.
- Remote Schemas: Integrate with third-party APIs for data and logic.
- Actions: Execute custom business logic via webhooks using any programming language.
- Event Triggers: Invoke webhooks based on database events (INSERT, UPDATE, DELETE). Supports manual invocation.
-
Scheduled Triggers: Run tasks periodically (CRON) or once (one-off) via webhooks.
- Migrations and Environments: Manage schema changes using migration files for database and Hasura metadata, supporting CI/CD workflows.
Deployment Options:
- Hasura Cloud: Easiest production deployment.
- External Hosting: Heroku, Digital Ocean, Render, Azure, Kubernetes, AWS (more complex).
- NHost: All-in-one BaaS solution including PostgreSQL, Hasura, authentication, and storage.
Summary:
Hasura and PostgreSQL offer a powerful combination for rapid backend development. The reduced coding effort, real-time capabilities, and robust features make it a compelling solution for building scalable and maintainable applications. While not as feature-rich as some alternatives in every aspect, its ease of use, focus on performance, and open-source nature are significant advantages.
Frequently Asked Questions (FAQs): (The provided FAQs are already comprehensive and well-written; no modification needed.)
The above is the detailed content of How to Build Your Backend with Hasura and PostgreSQL. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
