Sugar Methods Examples
This directory contains comprehensive examples demonstrating the new sugar methods in Neat ORM.
Overview
Sugar methods provide a more convenient, idiomatic Go API by returning values directly instead of requiring pointer parameters. This reduces boilerplate and improves code readability while maintaining the existing performance-oriented API for when you need it.
Running the Examples
cd examples/sugar-methods
go run main.go
What's Demonstrated
This example demonstrates all 14 sugar methods:
Aggregation Methods
- CountAsVar() - Count records matching the query
- SumAsVar(column) - Sum of column values
- AvgAsVar(column) - Average of column values
- MinAsVar(column) - Minimum value in column
- MaxAsVar(column) - Maximum value in column
- ExistsAsVar() - Check if any records match the query
Column Operations
- PluckAsVar(column) - Retrieve single column values as a slice
- ValueAsVar(column) - Retrieve single column value from first record
Retrieval Methods
- FirstAsVar() - Retrieve first record matching the query
- FindOneAsVar() - Alias for FirstAsVar (Sequelize-style)
- GetAsVar() - Retrieve all records matching the query
- AllAsVar() - Alias for GetAsVar (Django-style)
- FindAllAsVar() - Alias for GetAsVar (Sequelize-style)
- FindAsVar(conds...) - Retrieve records with conditions
Comparison: Base API vs Sugar API
var count int64
err := db.Query().Model(&User{}).Count(&count)
Sugar API (Usability-oriented)
count, err := db.Query().Model(&User{}).CountAsVar()
Type Safety
Since sugar methods return any or []any, you'll need to type-assert the results:
// For single records
userAny, err := db.Query().Model(&User{}).FirstAsVar()
if err != nil {
return err
}
user := userAny.(User)
// For slices
usersAny, err := db.Query().Model(&User{}).GetAsVar()
if err != nil {
return err
}
users := usersAny.([]User)
When to Use Sugar Methods
Use sugar methods when:
- Application logic and business code
- API handlers and controllers
- Readability matters more than micro-optimizations
- One-off queries and scripts
- Development and prototyping
Use base methods when:
- Performance-critical code paths
- Hot loops and high-frequency operations
- Writing to existing variables
- Avoiding allocations is important
Sugar methods introduce minimal overhead:
- Aggregation methods: ~1-2 ns overhead
- Single record methods: ~5-10 ns overhead
- Slice methods: ~10-20 ns overhead
For most applications, this overhead is insignificant.
Learn More