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:
|
|
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:
|
|
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
|
|
Fetch a User
|
|
Update a User
|
|
Delete a User
|
|
XORM vs Other ORMs
How does XORM stack up against the competition? Here’s a handy comparison:
Feature | XORM | GORM | SQLBoiler |
---|---|---|---|
Ease of Use | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ |
Performance | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
Auto Migration | Yes | Yes | No |
Raw SQL Support | Yes | Limited | Yes |
Documentation | Good | Excellent | Average |
Transactions in XORM
Transactions are easy in XORM. Here’s how you do it:
|
|
If anything goes wrong, session.Rollback()
will undo the changes.