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:
go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite2. Basic Setup in Your Fiber App:
Here's a simple Fiber application with GORM integrated:
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
Productstruct. This is our Go representation of a database table. Thegorm.Modelis a handy built-in that includes fields likeID,CreatedAt,UpdatedAt, andDeletedAt. gorm.Openis 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.AutoMigrateis a magical GORM feature that automatically creates theproductstable in your database based on theProductstruct. β¨
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:
// 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:
// 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.
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
Productstruct. c.BodyParser(product)is a Fiber helper that automatically parses the incoming JSON request body and fills in ourproductstruct. Pretty neat, right?database.DB.Create(&product)is the GORM magic. It takes ourproductstruct, generates the appropriateINSERTSQL statement, and executes it.- Finally, we return the newly created product (now with an
IDfrom the database) as a JSON response.
Read (GET /api/products)
Now, let's create an endpoint to list all our products.
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.
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 ofProducts.database.DB.Find(&products)fetches all the records from theproductstable and populates our slice. - For
getProduct, we get theidfrom 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
Firstdoesn'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.
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:
- We find the product we want to update.
- We parse the incoming JSON into a new struct.
- We update the fields of the original product with the new data.
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.
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, theDeletedAtfield is set to the current time. This can be useful for auditing and recovery. - We check
result.RowsAffectedto 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 Contentresponse.
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:
- GORM Documentation: https://gorm.io/docs/
- Fiber Documentation: https://docs.gofiber.io/
- Go-SQLite3 Driver: https://github.com/mattn/go-sqlite3
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:
Implement the
updateTaskhandler (forPUT /api/tasks/:id):- Retrieve the task
idfrom the URL parameters. - Find the corresponding task in the database. If the task does not exist, return a
404 Not Foundstatus with a JSON error message. - Parse the incoming JSON request body into a new
Taskstruct to get the updated data. - Update the
TitleandCompletedstatus 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 OKstatus.
- Retrieve the task
Implement the
deleteTaskhandler (forDELETE /api/tasks/:id):- Retrieve the task
idfrom the URL parameters. - Use the
DB.Delete()method to perform a soft delete on the specified task. - Check the result's
RowsAffectedvalue. If it is0, it means the task was not found. In this case, return a404 Not Foundstatus. - If the deletion is successful, return a
204 No Contentstatus code with an empty body.
- Retrieve the task
Expected result
The final code should provide complete and functional implementations for the updateTask and deleteTask functions.
updateTask
- Correctly parses the
idfrom the URL. - Uses
DB.First()to retrieve the task and properly handles thegorm.ErrRecordNotFounderror 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 OKstatus with the updated task in the response body.
deleteTask
- Correctly parses the
idfrom the URL. - Calls
DB.Delete()with the task model and ID. - Checks the
RowsAffectedproperty of the*gorm.DBresult. - If
RowsAffectedis 0, it returns a404 Not Foundstatus. - If
RowsAffectedis greater than 0, it returns a204 No Contentstatus.