2026-03-04 13:13:34 +00:00
---
layout: doc
title: Data Model
permalink: /docs/model.html
2026-03-05 11:21:41 +00:00
description: "Structured data model layer with CRUD operations, queries, and pluggable backends"
2026-03-04 13:13:34 +00:00
---
# Data Model
2026-06-10 08:24:49 +01:00
<img src="/images/generated/data-model.jpg" alt="Go Micro data model" style="width: 100%; border-radius: 8px; margin-bottom: 1.5rem;" />
2026-05-29 15:16:05 +01:00
2026-03-05 11:21:41 +00:00
The `model` package provides a structured data model layer for Go Micro services. Define Go structs, tag your fields, and get CRUD operations with queries, filtering, ordering, and pagination.
2026-03-04 13:13:34 +00:00
## Quick Start
```go
package main
import (
"context"
2026-06-18 11:55:35 +01:00
"go-micro.dev/v6"
"go-micro.dev/v6/model"
2026-03-04 13:13:34 +00:00
)
type Task struct {
ID string `json:"id" model:"key"`
Title string `json:"title"`
Done bool `json:"done"`
Owner string `json:"owner" model:"index"`
}
func main () {
2026-06-18 11:55:35 +01:00
service := micro . NewService ( "tasks" )
2026-03-04 13:13:34 +00:00
2026-03-05 11:21:41 +00:00
// Register your type with the service's model backend
db := service . Model ()
db . Register ( & Task {})
2026-03-04 13:13:34 +00:00
ctx := context . Background ()
// Create a record
2026-03-05 11:21:41 +00:00
db . Create ( ctx , & Task { ID : "1" , Title : "Ship it" , Owner : "alice" })
2026-03-04 13:13:34 +00:00
// Read by key
2026-03-05 11:21:41 +00:00
task := & Task {}
db . Read ( ctx , "1" , task )
2026-03-04 13:13:34 +00:00
// Update
task . Done = true
2026-03-05 11:21:41 +00:00
db . Update ( ctx , task )
2026-03-04 13:13:34 +00:00
// List with filters
2026-03-05 11:21:41 +00:00
var aliceTasks [] * Task
db . List ( ctx , & aliceTasks , model . Where ( "owner" , "alice" ))
2026-03-04 13:13:34 +00:00
// Delete
2026-03-05 11:21:41 +00:00
db . Delete ( ctx , "1" , & Task {})
2026-03-04 13:13:34 +00:00
}
```
## Defining Models
Models are plain Go structs. Use struct tags to control storage behavior:
| Tag | Purpose | Example |
|-----|---------|---------|
| `model:"key"` | Primary key field | `ID string \` model:"key"\`` |
| ` model:"index"` | Create an index on this field | ` Email string \`model:"index"\`` |
| ` json:"name"` | Column name in the database | ` Name string \`json:"name"\`` |
If no ` model:"key"` tag is found, the package defaults to a field with ` json:"id"` or a field named ` ID`.
Table names are auto-derived from the struct name (lowercased + "s"), e.g. ` User` → ` users`. Override with ` model.WithTable("custom_name")`.
` ``go
type User struct {
ID string ` json:"id" model:"key"`
Name string ` json:"name"`
Email string ` json:"email" model:"index"`
Age int ` json:"age"`
CreatedAt string ` json:"created_at"`
}
2026-03-05 11:21:41 +00:00
// Register with auto-derived table: "users"
db.Register(&User{})
2026-03-04 13:13:34 +00:00
// Custom table name
2026-03-05 11:21:41 +00:00
db.Register(&User{}, model.WithTable("app_users"))
2026-03-04 13:13:34 +00:00
` ``
## CRUD Operations
` ``go
// Create — inserts a new record (returns ErrDuplicateKey if key exists)
2026-03-05 11:21:41 +00:00
err := db.Create(ctx, &User{ID: "1", Name: "Alice"})
2026-03-04 13:13:34 +00:00
// Read — retrieves by primary key (returns ErrNotFound if missing)
2026-03-05 11:21:41 +00:00
user := &User{}
err = db.Read(ctx, "1", user)
2026-03-04 13:13:34 +00:00
// Update — modifies an existing record (returns ErrNotFound if missing)
user.Name = "Alice Smith"
2026-03-05 11:21:41 +00:00
err = db.Update(ctx, user)
2026-03-04 13:13:34 +00:00
// Delete — removes by primary key (returns ErrNotFound if missing)
2026-03-05 11:21:41 +00:00
err = db.Delete(ctx, "1", &User{})
2026-03-04 13:13:34 +00:00
` ``
## Queries
Use query options to filter, order, and paginate results:
### Filters
` ``go
2026-03-05 11:21:41 +00:00
var results []*User
2026-03-04 13:13:34 +00:00
// Equality
2026-03-05 11:21:41 +00:00
db.List(ctx, &results, model.Where("email", "alice@example.com"))
2026-03-04 13:13:34 +00:00
// Operators: =, !=, <, >, <=, >=, LIKE
2026-03-05 11:21:41 +00:00
db.List(ctx, &results, model.WhereOp("age", ">=", 18))
db.List(ctx, &results, model.WhereOp("name", "LIKE", "Ali%"))
2026-03-04 13:13:34 +00:00
// Multiple filters (AND)
2026-03-05 11:21:41 +00:00
db.List(ctx, &results,
2026-03-04 13:13:34 +00:00
model.Where("owner", "alice"),
model.WhereOp("age", ">", 25),
)
` ``
### Ordering
` ``go
2026-03-05 11:21:41 +00:00
db.List(ctx, &results, model.OrderAsc("name"))
db.List(ctx, &results, model.OrderDesc("created_at"))
2026-03-04 13:13:34 +00:00
` ``
### Pagination
` ``go
2026-03-05 11:21:41 +00:00
db.List(ctx, &results,
2026-03-04 13:13:34 +00:00
model.Limit(10),
model.Offset(20),
)
` ``
### Counting
` ``go
2026-03-05 11:21:41 +00:00
total, _ := db.Count(ctx, &User{})
active, _ := db.Count(ctx, &User{}, model.Where("active", true))
2026-03-04 13:13:34 +00:00
` ``
## Backends
2026-03-05 11:21:41 +00:00
The model layer uses Go Micro's pluggable interface pattern. All backends implement ` model.Model`.
2026-03-04 13:13:34 +00:00
### Memory (Default)
Zero-config, in-memory storage. Data doesn't persist across restarts. Ideal for development and testing.
` ``go
2026-06-18 11:55:35 +01:00
service := micro.NewService("myservice")
2026-03-05 11:21:41 +00:00
db := service.Model() // memory backend by default
db.Register(&Task{})
2026-03-04 13:13:34 +00:00
` ``
Or create directly:
` ``go
2026-06-18 11:55:35 +01:00
import "go-micro.dev/v6/model"
2026-03-04 13:13:34 +00:00
2026-03-05 11:21:41 +00:00
db := model.NewModel()
db.Register(&Task{})
2026-03-04 13:13:34 +00:00
` ``
### SQLite
File-based database. Good for local development or single-node production.
` ``go
2026-06-18 11:55:35 +01:00
import "go-micro.dev/v6/model/sqlite"
2026-03-04 13:13:34 +00:00
2026-03-05 11:21:41 +00:00
db := sqlite.New("app.db")
2026-06-18 11:55:35 +01:00
service := micro.NewService("myservice", micro.Model(db))
2026-03-04 13:13:34 +00:00
` ``
### Postgres
Production-grade with connection pooling.
` ``go
2026-06-18 11:55:35 +01:00
import "go-micro.dev/v6/model/postgres"
2026-03-04 13:13:34 +00:00
2026-03-05 11:21:41 +00:00
db := postgres.New("postgres://user:pass@localhost/myapp?sslmode=disable")
2026-06-18 11:55:35 +01:00
service := micro.NewService("myservice", micro.Model(db))
2026-03-04 13:13:34 +00:00
` ``
## Service Integration
The ` Service` interface provides ` Model()` alongside ` Client()` and ` Server()`:
` ``go
2026-06-18 11:55:35 +01:00
service := micro.NewService("users", micro.Address(":9001"))
2026-03-04 13:13:34 +00:00
// Access the three core components
client := service.Client() // Call other services
server := service.Server() // Handle requests
db := service.Model() // Data persistence
2026-03-05 11:21:41 +00:00
// Register your types
db.Register(&User{})
db.Register(&Post{})
2026-03-04 13:13:34 +00:00
// Use in your handler
2026-03-05 11:21:41 +00:00
service.Handle(&UserHandler{db: db})
2026-03-04 13:13:34 +00:00
service.Run()
` ``
A handler that uses all three:
` ``go
type OrderHandler struct {
2026-03-05 11:21:41 +00:00
db model.Model
client client.Client
2026-03-04 13:13:34 +00:00
}
// CreateOrder saves an order and notifies the shipping service
func (h *OrderHandler) CreateOrder(ctx context.Context, req *CreateReq, rsp *CreateRsp) error {
// Save to database via Model
order := &Order{ID: req.ID, Item: req.Item, Status: "pending"}
2026-03-05 11:21:41 +00:00
if err := h.db.Create(ctx, order); err != nil {
2026-03-04 13:13:34 +00:00
return err
}
// Call another service via Client
shipClient := proto.NewShippingService("shipping", h.client)
_, err := shipClient.Ship(ctx, &proto.ShipRequest{OrderID: order.ID})
return err
}
` ``
## Error Handling
2026-03-05 11:21:41 +00:00
The model package returns sentinel errors:
2026-03-04 13:13:34 +00:00
` ``go
2026-06-18 11:55:35 +01:00
import "go-micro.dev/v6/model"
2026-03-04 13:13:34 +00:00
// Check for not found
2026-03-05 11:21:41 +00:00
err := db.Read(ctx, "missing", &User{})
2026-03-04 13:13:34 +00:00
if errors.Is(err, model.ErrNotFound) {
// record doesn't exist
}
// Check for duplicate key
2026-03-05 11:21:41 +00:00
err = db.Create(ctx, &User{ID: "1", Name: "Alice"})
err = db.Create(ctx, &User{ID: "1", Name: "Bob"})
2026-03-04 13:13:34 +00:00
if errors.Is(err, model.ErrDuplicateKey) {
// key "1" already exists
}
` ``
## Swapping Backends
Follow the standard Go Micro pattern — use in-memory for development, swap to a real database for production:
` ``go
func main() {
2026-03-05 11:21:41 +00:00
var db model.Model
2026-03-04 13:13:34 +00:00
if os.Getenv("ENV") == "production" {
2026-03-05 11:21:41 +00:00
db = postgres.New(os.Getenv("DATABASE_URL"))
2026-03-04 13:13:34 +00:00
} else {
2026-03-05 11:21:41 +00:00
db = model.NewModel()
2026-03-04 13:13:34 +00:00
}
2026-06-18 11:55:35 +01:00
service := micro.NewService("myservice", micro.Model(db))
2026-03-04 13:13:34 +00:00
// ... same application code regardless of backend
}
` ``