Donald Feury

databases

Total Control

Odysee YouTube

Check out the video for some more elaboration on the topics below.


If you liked it and want to know when I post more videos, be sure to subscribe

Time to start looking at some ORMs for go, today we're gonna start with gorm. Gorm is a code first ORM, meaning we can use go code to define our database scheme, run the migrations, and also interact with the database with the same code.

Connect to the Database

In order to connect to a database using gorm, we simply use the following:

db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
  // Handle error
}
defer db.Close()

We are opening a sqlite3 file, because I didn't want to fiddle with something like MySQL for this.

We handle an error if one occurred, and defer a call to db.Close() to ensure the connection is cleaned up afterwards

Defining Schema with Structs

We have the following structs:

type Channel struct {
	gorm.Model
	Name        string
	Description string
}

type User struct {
	gorm.Model
	Email    string
	Username string
}

type Message struct {
	gorm.Model
	Content   string
	UserID    uint
	ChannelID uint
	User      User
	Channel   Channel
}

Each of these structs will have a corresponding table in our database, with the same columns as the structs have properties.

The gorm.Model struct has some standard properties commonly used in SQL database, check out the docs to see more about it.

You'll notice the Message struct has properties that reference other structs. These are used to map the table relations, read more about how gorm does relationship mapping here.

Migrations

The easiest way to sync up our schema to our structs it to use the AutoMigration method defined on the db instance:

db.AutoMigrate(&Channel{}, &User{}, &Message{})

We pass in an instance of each struct and gorm does some reflection under the hood to make any schema changes, generate the queries, and run them.

Keep in mind, AutoMigrate will only add missing tables, columns, and indexes. It will not remove unused ones, read why here.

Adding Data

To create a new row in our database, we simply create in instance of one of our structs, set the values on its properties, and pass it to the Create method on our database connection:

channel := Channel{Name: "General", Description: "General banter"}

db.Create(&channel)

Tada, data has been inserted into our table!

Finding Data

If you want to grab something from the database, the docs has alot of examples but some notable ones are as follows:

// give me all the channels and unmarshal them into my variable channels, which is of type []Channel
db.Find(&channels)

// give me the first record by primary key, in the channels table and unmarshal it into my variable channel, which is of type Channel
db.First(&channel)

// same as db.First() but gets the last record by primary key
db.Last(&channel)

You can also build where clauses using the Where method:

// Adds a 'where name = "General"' clause to the select query
db.Where("Name = ?", "General").Find(&channels)

// You can pass in structs to act as the where clause source.
// Here it will take the field 'Name' from our channel struct and add it into the where clause
db.Where(&Channel{Name: "General"}).First(&channel)

Error Handling

Gorm handles errors in a way that is a little different than idiomatic go.

After you run a gorm query, it will set a value to the Error variable in the gorm package, if an error occurred while running the query.

Here is an example of checking if the method ended up returning an error:

if err := db.Where("Name = ?", "MissingName").First(&channel).Error; err != nil {
  // Handle error
}

Summary

Gorm makes it fairly easy to manage your database schema and acts as an abstraction over your database backend.

Thank you for reading

#go #golang #orm #gorm #databases

Maps those objects

Odysee YouTube

Check out the video for some more elaboration on the topics below.


If you liked it and want to know when I post more videos, be sure to subscribe

I'm about to do a few videos on a some Go ORM packages and thought it wouldn't hurt to do a dedicated segment on just talking about what ORMs are and why you should or shouldn't use them.

What does ORM stand for?

ORM stands for Object Relation Mapping. Typically this means communicating with a system using a language other than the native language is expects.

An example of this would be a SQL database. A SQL database is expecting, well, a SQL query to interact with it, but what if we wanted to interact with it with something like a Golang program?

What does an ORM do?

An ORM library gives us the mechanism by which to perform Object Relation Mapping. This means we end up with structs or classes that represent something like a table in our database

In golang, we would get something like this:

user := models.Users().ByID(1)

Which would generate the following SQL query:

SELECT * FROM Users WHERE id = 1;

Pros & Cons of ORMs

Pros:

  • Much less time spent to interact with a database in your program
  • Abstracts away the database being used, which makes it easier to swap to another backend
  • If you have weak SQL skills, the generated queries are at least as good as if you wrote them, if not more performant.

Cons:

  • If you need a very highly optimized query and you can write said query, it may perform better than the generated ones.
  • There is some amount of mental overhead related to learning an ORM library
  • Most ORMs require some amount of configuration
  • May not help you developer stronger database and/or SQL skills

What kinds of ORM libraries exist?

From my experience, there are two primary types of ORM libaries

Code-First ORM

A code first ORM uses the code written or generated by the user to generate the database schema and applies the schema to the database.

Some examples of code first ORMs:

  • Gorm (Go)
  • Basically every ORM in most mainstream framework
    • Eloquent (Laravel)
    • ActiveRecord (RoR)
    • Whatever Django uses

Schema-First ORM

A schema first ORM reads the already defined schema from the database and generates from it, all the code necessary to interact with the database.

Some examples of schema first ORMs:

When to choose which?

Code-First ORM

  • Most ORM libraries in my experience are code first, so a lot of choices
  • These tend to do alot, some code generation, acts as abstraction, and manages migrations (schema changes)

Schema First ORM

  • Need to get up and running quickly with an existing database (legacy data)
  • Almost ALL of the code will be generated, vs just some being boilerplated like most code first ORMs I've used
  • You prefer a more unix approach, as most schema first ORMs I've seen don't handle migrations. You'll need to use a seperate tool or library to manage migrations.

#databases #orm

Using MySQL with Go

Youtube Video

Code can be found here

Time to start integrating some other tools with our go programs.

I figured a good place to start would be with a SQL database, since its very common to work with one. I chose MySQL for this example, as I have a lot of background with it from my PHP days.

We don't do anything crazy here, just demonstrate how to load the driver, connect to the database, and perform simple queries and prepared statements.

Check it out and let me know what ya'll think. Any feedback is greatly appreciated.

If you liked it and want to know when I post more, be sure to subscribe and thank ya'll again for your time!

#databases #go #golang #mysql