Skip to Content
fusion-orm
Guides

Starter example

One complete, single-file service — models, migration, CRUD endpoints with preloads, soft delete, transactions, and sentinel-based status mapping.

This is the whole service: one Go file that opens a SQLite database, migrates two related models, and serves a small JSON API — users with posts, preloads, soft delete, a transaction on the write path, and errors.Is-based status mapping. Every fusion-orm call below is a verified API; the file is composed from patterns shown throughout these docs.

Demo scope

This is a starter, not a production skeleton — no auth, no validation beyond the schema, and error bodies are raw error text. The interesting part is the shape: chain per request, finish once, branch on sentinels.

The service

package main

import (
	"context"
	"encoding/json"
	"errors"
	"log"
	"net/http"
	"strconv"

	"github.com/kiplagatcollins/fusion-orm"
	"github.com/kiplagatcollins/fusion-orm/dialect/sqlite"
)

type User struct {
	ID        int64  `fusion:"pk,autoincrement"`
	Name      string `fusion:"notnull"`
	Email     string `fusion:"notnull,unique"`
	DeletedAt fusion.DeletedAt
	Posts     []Post `fusion:"rel:has-many,foreignKey:UserID"`
}

type Post struct {
	ID     int64  `fusion:"pk,autoincrement"`
	UserID int64
	Title  string
	Author *User `fusion:"rel:belongs-to,foreignKey:UserID"`
}

type service struct {
	db *fusion.DB
}

func main() {
	db, err := fusion.Open(sqlite.Open("fusion-demo.db"), &fusion.Config{TranslateError: true})
	if err != nil {
		log.Fatal(err)
	}
	m, err := db.Migrator()
	if err != nil {
		log.Fatal(err)
	}
	if err := m.AutoMigrate(context.Background(), &User{}, &Post{}); err != nil {
		log.Fatal(err)
	}

	s := &service{db: db}
	mux := http.NewServeMux()
	mux.HandleFunc("POST /users", s.createUser)
	mux.HandleFunc("GET /users", s.listUsers)
	mux.HandleFunc("POST /users/{id}/posts", s.createPost)
	mux.HandleFunc("GET /posts", s.listPosts)
	mux.HandleFunc("DELETE /users/{id}", s.deleteUser)
	log.Fatal(http.ListenAndServe(":8080", mux))
}

func writeJSON(w http.ResponseWriter, code int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	_ = json.NewEncoder(w).Encode(v)
}

func statusFor(err error) int {
	switch {
	case errors.Is(err, fusion.ErrRecordNotFound):
		return http.StatusNotFound
	case errors.Is(err, fusion.ErrDuplicatedKey):
		return http.StatusConflict
	default:
		return http.StatusInternalServerError
	}
}

func (s *service) createUser(w http.ResponseWriter, r *http.Request) {
	var in struct{ Name, Email string }
	if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	user := User{Name: in.Name, Email: in.Email}
	tx := s.db.WithContext(r.Context()).Create(&user)
	if tx.Error != nil {
		http.Error(w, tx.Error.Error(), statusFor(tx.Error))
		return
	}
	writeJSON(w, http.StatusCreated, user)
}

func (s *service) listUsers(w http.ResponseWriter, r *http.Request) {
	var users []User
	tx := s.db.WithContext(r.Context()).Model(&User{}).Preload("Posts").Order("id").Find(&users)
	if tx.Error != nil {
		http.Error(w, tx.Error.Error(), statusFor(tx.Error))
		return
	}
	writeJSON(w, http.StatusOK, users)
}

func (s *service) createPost(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		http.Error(w, "bad user id", http.StatusBadRequest)
		return
	}
	var in struct{ Title string }
	if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	var post Post
	err = s.db.WithContext(r.Context()).Transaction(func(tx *fusion.DB) error {
		var owner User
		if err := tx.First(&owner, id).Error; err != nil {
			return err // ErrRecordNotFound maps to 404 below
		}
		post = Post{UserID: id, Title: in.Title}
		return tx.Create(&post).Error
	})
	if err != nil {
		http.Error(w, err.Error(), statusFor(err))
		return
	}
	writeJSON(w, http.StatusCreated, post)
}

func (s *service) listPosts(w http.ResponseWriter, r *http.Request) {
	var posts []Post
	tx := s.db.WithContext(r.Context()).Model(&Post{}).Preload("Author").Order("id").Find(&posts)
	if tx.Error != nil {
		http.Error(w, tx.Error.Error(), statusFor(tx.Error))
		return
	}
	writeJSON(w, http.StatusOK, posts)
}

func (s *service) deleteUser(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		http.Error(w, "bad user id", http.StatusBadRequest)
		return
	}
	tx := s.db.WithContext(r.Context()).Delete(&User{}, id)
	if tx.Error != nil {
		http.Error(w, tx.Error.Error(), statusFor(tx.Error))
		return
	}
	if tx.RowsAffected == 0 {
		http.Error(w, fusion.ErrRecordNotFound.Error(), http.StatusNotFound)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

What to notice

  • The root *DB is the only shared state. Handlers chain off it per request with WithContext(r.Context()); the chain is copy-on-write, so concurrent requests never interfere (fusion.go:300).
  • Sentinels drive status codes. statusFor maps ErrRecordNotFound → 404 and ErrDuplicatedKey → 409 with errors.Is. The 409 path only works because Open passed TranslateError: true — the SQLite dialector's constraint error is translated through ErrorTranslator before it reaches the error slot (errors.go:92).
  • The unique index is real. The unique tag makes AutoMigrate issue CREATE UNIQUE INDEX (migrator/migrator.go:249), so a duplicate email fails at the driver and surfaces as 409.
  • The transaction is the write path. createPost checks the owner and inserts the post atomically; returning an error rolls back, and ErrRecordNotFound from inside propagates to a 404 (transaction.go:21).
  • Delete is soft. User embeds fusion.DeletedAt, so Delete rewrites to an UPDATE ... SET deleted_at = ... and every query filters deleted_at IS NULL until you use Unscoped or Restore (soft_delete.go:189). RowsAffected == 0 distinguishes a missing row from a successful delete.
  • Preloads are batched. GET /users loads every user's posts in one IN query, and GET /posts loads each post's author the same way — never one query per row (relations/preload.mdx).

Run it

mkdir fusion-demo && cd fusion-demo
go mod init example.com/fusion-demo
go get github.com/kiplagatcollins/fusion-orm
# save the snippet above as main.go
go run .

Then, in another terminal:

curl -d '{"name":"Ada","email":"ada@example.com"}' localhost:8080/users
curl -d '{"name":"Dup","email":"ada@example.com"}' localhost:8080/users  # 409
curl -d '{"title":"notes"}' localhost:8080/users/1/posts
curl localhost:8080/posts          # posts with their authors preloaded
curl localhost:8080/users          # users with their posts preloaded
curl -X DELETE localhost:8080/users/1
curl localhost:8080/users          # Ada is gone — soft-deleted

Next

On this page