Learn Fiber Β· 9/14

Database Integration (Practical CRUD)

8 min read

Database Integration (Practical CRUD) with Fiber πŸ’Ύ

Welcome to the world of databases in your Fiber applications! So far, your application might have been like a brilliant but forgetful person. It can do amazing things, but the moment you restart it, it forgets everything. Not ideal, right? πŸ˜…

In this guide, we're going to give our app a long-term memory by connecting it to a database. We'll learn how to create, read, update, and delete data – the fundamental building blocks of almost any application, collectively known as CRUD.


Choosing an ORM: GORM Setup with Fiber πŸ€–

The Problem: Writing raw SQL queries in your Go code can be a real pain. You have to manually handle things like opening and closing connections, and you are prone to making little mistakes that can lead to big security problems like SQL injection. It's like trying to build a house with just a hammer and some nails – possible, but not very efficient or safe.

The Solution: ORM (Object-Relational Mapping): An ORM is like a magical translator that speaks both Go and SQL. You can work with your database tables as if they were Go structs, and the ORM will handle the messy business of writing and executing the SQL queries for you. It's a game-changer for productivity and security.

For our adventure, we'll be using GORM, one of the most popular ORMs in the Go ecosystem. It's known for being developer-friendly and packed with features.

Getting Started with GORM and Fiber

Let's get our hands dirty and set up GORM. We'll use SQLite for this example because it's super easy to get started with – no separate database server needed!

1. Installation:

First, you'll need to install GORM and the SQLite driver. Open your terminal and run:

bash
go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite

2. Basic Setup in Your Fiber App:

Here's a simple Fiber application with GORM integrated:

go
package main

import (
	"log"

	"github.com/gofiber/fiber/v2"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

// Our data model
type Product struct {
	gorm.Model
	Code  string
	Price uint
}

func main() {
	app := fiber.New()

	// Connect to the database
	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
		log.Fatal("failed to connect database")
	}

	// Migrate the schema
	db.AutoMigrate(&Product{})

	// Your routes will go here

	log.Fatal(app.Listen(":3000"))
}

What's happening here?

  • We define a Product struct. This is our Go representation of a database table. The gorm.Model is a handy built-in that includes fields like ID, CreatedAt, UpdatedAt, and DeletedAt.
  • gorm.Open is used to create a connection to our SQLite database file (test.db). If the file doesn't exist, GORM will create it for you.
  • db.AutoMigrate is a magical GORM feature that automatically creates the products table in your database based on the Product struct. ✨

Fun Fact: The term "ORM" was first used in the late 1990s, but the concept of mapping objects to relational databases has been around since the early days of object-oriented programming. It's a battle-tested idea!


Connecting and Managing Database Connections πŸ”—

The Problem: Imagine you're running a popular coffee shop. Every time a customer wants to order, you have to run to the back, unlock the storeroom (open a database connection), get the coffee beans (fetch data), and then lock the storeroom again (close the connection). This would be incredibly slow and inefficient, especially during the morning rush!

The Solution: Connection Pooling: Instead of opening and closing connections for every single request, we can maintain a "pool" of open connections that are ready to be used. When a request comes in, we grab a connection from the pool, use it, and then return it to the pool when we're done. This is much, much faster.

Thankfully, GORM handles connection pooling for you under the hood! When you use gorm.Open, you're not just getting a single connection; you're getting a database connection pool.

Best Practices for Connection Management

While GORM does a lot of the heavy lifting, here are a few things to keep in mind for a production environment:

  • Don't Open and Close Connections in Handlers: It's a common mistake for beginners to open a database connection inside each route handler. This is very inefficient. Instead, you should create a single database connection when your application starts and share it across your handlers.

    A good way to do this is to make your database connection available through a custom struct or a global variable (though be careful with globals in larger applications).

  • Graceful Shutdown: When your application is shutting down, it's a good practice to close the database connection pool gracefully. This ensures that any ongoing database operations are completed before the application exits.

Here's an example of how you might structure your application to share the database connection:

go
// db.go
package database

import (
	"log"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

var DB *gorm.DB

func Connect() {
	connection, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
		log.Fatal("failed to connect database")
	}

	DB = connection
}

Then in your main.go:

go
// main.go
package main

import (
	"log"
	
	"your-app/database" // Import your database package
	"github.com/gofiber/fiber/v2"
)

// ... (your Product struct)

func main() {
	app := fiber.New()
	database.Connect()

	// Now you can access the database connection via database.DB in your handlers

	log.Fatal(app.Listen(":3000"))
}

Building a CRUD API: Create and Read Operations πŸ› οΈ

Now for the fun part – let's start building our API! We'll begin with the "C" and "R" in CRUD: Create and Read.

Create (POST /api/products)

Let's create an endpoint to add new products to our database.

go
func createProduct(c *fiber.Ctx) error {
	product := new(Product)

	if err := c.BodyParser(product); err != nil {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"error": "cannot parse JSON",
		})
	}

	database.DB.Create(&product)

	return c.JSON(product)
}

Let's break it down:

  • We create a new instance of our Product struct.
  • c.BodyParser(product) is a Fiber helper that automatically parses the incoming JSON request body and fills in our product struct. Pretty neat, right?
  • database.DB.Create(&product) is the GORM magic. It takes our product struct, generates the appropriate INSERT SQL statement, and executes it.
  • Finally, we return the newly created product (now with an ID from the database) as a JSON response.

Read (GET /api/products)

Now, let's create an endpoint to list all our products.

go
func getProducts(c *fiber.Ctx) error {
	var products []Product
	database.DB.Find(&products)
	return c.JSON(products)
}

And another one to get a single product by its ID.

go
func getProduct(c *fiber.Ctx) error {
	id := c.Params("id")
	var product Product

	result := database.DB.First(&product, id)

	if result.Error != nil {
		return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
			"error": "product not found",
		})
	}

	return c.JSON(product)
}

What's going on here?

  • For getProducts, we declare a slice of Products. database.DB.Find(&products) fetches all the records from the products table and populates our slice.
  • For getProduct, we get the id from the URL parameters. database.DB.First(&product, id) finds the first record that matches the given ID.
  • It's important to check for errors. If First doesn't find a record, it will return an error, and we should respond with a 404 Not Found status.

Building a CRUD API: Update and Delete Operations πŸ’₯

Let's complete our CRUD API with the "U" and "D": Update and Delete.

Update (PUT /api/products/:id)

This endpoint will allow us to update an existing product.

go
func updateProduct(c *fiber.Ctx) error {
	id := c.Params("id")
	var product Product

	// First, find the product
	if err := database.DB.First(&product, id).Error; err != nil {
		return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
			"error": "product not found",
		})
	}

	// Then, parse the request body into a temporary struct
	var updatedProduct Product
	if err := c.BodyParser(&updatedProduct); err != nil {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
			"error": "cannot parse JSON",
		})
	}

	// Update the product's fields
	product.Code = updatedProduct.Code
	product.Price = updatedProduct.Price

	// Save the changes
	database.DB.Save(&product)

	return c.JSON(product)
}

Here's the flow:

  1. We find the product we want to update.
  2. We parse the incoming JSON into a new struct.
  3. We update the fields of the original product with the new data.
  4. database.DB.Save(&product) will then update all the fields of the product in the database.

Industry Practice: For more complex updates, you might want to use database.DB.Model(&product).Updates(updatedProduct). This is more efficient as it only updates the fields that have changed.

Delete (DELETE /api/products/:id)

Finally, let's add the ability to delete a product.

go
func deleteProduct(c *fiber.Ctx) error {
	id := c.Params("id")
	var product Product

	result := database.DB.Delete(&product, id)

	if result.RowsAffected == 0 {
		return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
			"error": "product not found",
		})
	}

	return c.SendStatus(fiber.StatusNoContent)
}

The breakdown:

  • database.DB.Delete(&product, id) will find the product with the given ID and delete it.
  • GORM uses a concept called "soft delete" by default if your model includes gorm.Model. This means the record isn't actually removed from the database. Instead, the DeletedAt field is set to the current time. This can be useful for auditing and recovery.
  • We check result.RowsAffected to see if a record was actually deleted. If not, it means the product didn't exist in the first place.
  • A successful deletion usually results in a 204 No Content response.

And there you have it! A complete CRUD API with Fiber and GORM. You've given your application a memory, and now it can store and manage data like a pro. πŸŽ‰

Further Reading & Resources:

Challenge

Challenge Instructions

You are tasked with completing a CRUD API for a To-Do list application built with Fiber and GORM. The basic application structure, database connection, and the Task model are already provided. The routes and handlers for creating a task (POST /api/tasks) and retrieving all tasks (GET /api/tasks) have been implemented for you.

Your goal is to implement the logic for the remaining two handlers: updateTask and deleteTask.

Requirements:

  1. Implement the updateTask handler (for PUT /api/tasks/:id):

    • Retrieve the task id from the URL parameters.
    • Find the corresponding task in the database. If the task does not exist, return a 404 Not Found status with a JSON error message.
    • Parse the incoming JSON request body into a new Task struct to get the updated data.
    • Update the Title and Completed status of the task found in the database with the new data.
    • Save the changes to the database using DB.Save().
    • Respond with the updated task object as JSON and a 200 OK status.
  2. Implement the deleteTask handler (for DELETE /api/tasks/:id):

    • Retrieve the task id from the URL parameters.
    • Use the DB.Delete() method to perform a soft delete on the specified task.
    • Check the result's RowsAffected value. If it is 0, it means the task was not found. In this case, return a 404 Not Found status.
    • If the deletion is successful, return a 204 No Content status code with an empty body.

Expected result

The final code should provide complete and functional implementations for the updateTask and deleteTask functions.

updateTask

  • Correctly parses the id from the URL.
  • Uses DB.First() to retrieve the task and properly handles the gorm.ErrRecordNotFound error by returning a 404 status.
  • Successfully parses the request body into a temporary struct.
  • Updates the fields of the original task struct retrieved from the database.
  • Calls DB.Save() to persist the changes.
  • Returns a 200 OK status with the updated task in the response body.

deleteTask

  • Correctly parses the id from the URL.
  • Calls DB.Delete() with the task model and ID.
  • Checks the RowsAffected property of the *gorm.DB result.
  • If RowsAffected is 0, it returns a 404 Not Found status.
  • If RowsAffected is greater than 0, it returns a 204 No Content status.
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.