Featured image of post XORM In a Nutshell

XORM In a Nutshell

XORM In a Nutshell


What the Heck is XORM?

XORM is a Go-based ORM that provides a simple way to interact with SQL databases like MySQL, PostgreSQL, and SQLite.

It maps Go structs to database tables, so you don’t have to write raw SQL for every little thing.

With XORM, you can:

  • Define Go structs as database models.
  • Query, insert, update, and delete records easily.
  • Handle transactions and migrations without losing your sanity.

Sounds good? Let’s see it in action!


Installing XORM

First things first, install XORM:

1
2
go get xorm.io/xorm
go get -u github.com/mattn/go-sqlite3  # Example for SQLite support

You might need different drivers depending on your database:

  • MySQL: go get -u github.com/go-sql-driver/mysql
  • PostgreSQL: go get -u github.com/lib/pq
  • SQLite: go get -u github.com/mattn/go-sqlite3

Once that’s done, let’s play with some code!


Defining a Model

In XORM, you define your database tables as Go structs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import (
	"fmt"
	"xorm.io/xorm"
	_ "github.com/mattn/go-sqlite3"
)

type User struct {
	ID    int64  `xorm:"pk autoincr"`
	Name  string `xorm:"unique"`
	Email string
}

func main() {
	db, err := xorm.NewEngine("sqlite3", "test.db")
	if err != nil {
		panic(err)
	}

	db.Sync(new(User)) // Create the table if it doesn’t exist

	fmt.Println("Database ready!")
}

Boom! You now have a User table in your SQLite database.


CRUD Operations with XORM

Now let’s do some basic operations.

Insert a User

1
2
3
4
5
user := User{Name: "Alice", Email: "alice@example.com"}
_, err := db.Insert(&user)
if err != nil {
	fmt.Println("Insert failed:", err)
}

Fetch a User

1
2
3
var user User
db.Where("name = ?", "Alice").Get(&user)
fmt.Println("Fetched user:", user)

Update a User

1
2
user.Email = "newalice@example.com"
db.ID(user.ID).Update(&user)

Delete a User

1
db.ID(user.ID).Delete(&user)

XORM vs Other ORMs

How does XORM stack up against the competition? Here’s a handy comparison:

FeatureXORMGORMSQLBoiler
Ease of Use⭐⭐⭐⭐⭐⭐⭐⭐⭐
Performance⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Auto MigrationYesYesNo
Raw SQL SupportYesLimitedYes
DocumentationGoodExcellentAverage

Transactions in XORM

Transactions are easy in XORM. Here’s how you do it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
session := db.NewSession()
defer session.Close()

if err := session.Begin(); err != nil {
	panic(err)
}

if _, err := session.Insert(&User{Name: "Bob", Email: "bob@example.com"}); err != nil {
	session.Rollback()
	panic(err)
}

session.Commit()

If anything goes wrong, session.Rollback() will undo the changes.