How to Use CRUDA: A Minimalistic Relational Database Library for Go

Aug 25, 2024 | Programming

Welcome to your guide on using CRUDA, an elegant and minimalist relational database library designed for Go developers. This library simplifies the process of database interactions by providing core functionalities such as Create, Read, Update, and Delete (CRUD) with ease.

Table of Contents

Install

To get started, install the library by running:

bash
$ go get github.com/azer/crud/v2

Initialize

To initialize the database connection, you will need to import the necessary packages and set up your database connection as follows:

go
import (
  "github.com/azer/crud/v2"
  _ "github.com/go-sql-driver/mysql"
)

var DB *crud.DB

func init() {
  var err error
  DB, err = crud.Connect("mysql", os.Getenv("DATABASE_URL"))
  err = DB.Ping()
}

Think of this part like preparing your canvas before painting; this sets up the environment so you can start working smoothly.

Define

Now, let’s define the database structures. For example, you can create a User and Profile struct:

go
type User struct {
  Id        int `sql:"auto-increment,primary-key"`
  FirstName string
  LastName  string
  ProfileId int
}

type Profile struct {
  Id   int `sql:"auto-increment,primary-key"`
  Bio  string `sql:"text"`
}

CRUDA automatically translates the field names, like converting FirstName to first_name. It’s like translating your work into a different language but still keeping the essence!

Create

To create the tables in the database, you can use:

go
err := DB.CreateTables(User, Profile)

If you need to drop and recreate tables, utilize:

go
err := DB.DropTables(User, Profile)
err := DB.CreateTables(User, Profile)

CreateAndRead

This method allows you to create a row and then immediately read it back from the database:

go
user := &User{FirstName: "Foo"}
err := DB.CreateAndRead(user)

It’s like planting a seed (the user) and then checking immediately if your little sprout has taken root!

Read

Reading data from your database allows you to retrieve rows easily.

Reading a single row:

go
user := &User{}
err := DB.Read(user, "SELECT * FROM users WHERE id = ?", 1)
fmt.Println(user.FirstName)

Reading multiple rows:

go
users := []*User{}
err := DB.Read(&users, "SELECT * FROM users")
fmt.Println(len(users))

Scanning to custom values:

go
names := []string{}
err := DB.Read(&names, "SELECT name FROM users")

Update

To update a row, read it first and then modify its fields:

go
user := &User{}
err := DB.Read(user, "SELECT * FROM users WHERE id = ?", 1)
user.FirstName = "Yolo"
err := DB.Update(user)

It’s like polishing a finished sculpture to unveil a more refined piece of art!

Delete

To remove an entry, simply call:

go
err := DB.Delete(&User{Id: 1})

This can be equated to erasing a mistake from a canvas, ensuring cleanliness in your artwork!

Contexts

Integrate context for time-management or cancellation purposes:

go
godb := DB.WithContext(context.Background())

Transactions

Using transactions can help manage safer data changes:

go
tx, err := DB.Begin(context.Background())
err := tx.Create(&User{Name: "Yolo"})
err := tx.Commit()

Transactions are like rehearsing a play; everything must go perfectly before the final performance!

Logs

If you want to debug and view internal actions, set up environment logging:

bash
$ LOG=crud go run myapp.go

Custom Queries

Execute your raw SQL commands as needed:

go
result, err := DB.Query("DROP DATABASE yolo")

What’s Missing?

  • Hooks: Consider the inclusion of hooks for additional events.
  • Foreign Keys: The functionality may need to be added for enhanced relations.
  • Make UTF-8 Default: Ensure charset consistency across your database.

LICENSE

This project is licensed under the MIT License.

Troubleshooting Ideas

  • Make sure that your DATABASE_URL is configured correctly.
  • Check whether the required drivers are properly installed.
  • For verbose output and debugging, remember to enable logs!

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Thank you for diving into CRUDA with us; happy coding!

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox