🤖
SQLBoilerのクエリをスッキリ書ける boilscope を作った
はじめに
Go で SQLBoiler を使っていると、クエリの条件を組み立てるコードが煩雑になりがちです。
// よくある光景
users, err := models.Users(
qm.Where("active = ?", true),
qm.Where("role = ?", "admin"),
qm.Where("deleted_at IS NULL"),
qm.OrderBy("created_at DESC"),
qm.Limit(20),
qm.Offset(0),
).All(ctx, db)
これ自体は問題ないのですが、同じような条件を複数箇所で使いたい場合や、条件を動的に組み立てたい場合にコードが散らかりがちです。
そこで boilscope というライブラリを作りました。
boilscope とは
boilscope は SQLBoiler 用の再利用可能なクエリスコープを提供するライブラリです。Rails の scope のような感覚でクエリ条件を定義・合成できます。
インストール
go get github.com/mickamy/boilscope
基本的な使い方
Before: 素の SQLBoiler
func GetActiveAdmins(ctx context.Context, db *sql.DB, page, perPage int) ([]*models.User, error) {
return models.Users(
qm.Where("active = ?", true),
qm.Where("role = ?", "admin"),
qm.OrderBy("created_at DESC"),
qm.Limit(perPage),
qm.Offset((page-1)*perPage),
).All(ctx, db)
}
After: boilscope を使う
func GetActiveAdmins(ctx context.Context, db *sql.DB, page, perPage int) ([]*models.User, error) {
mods := boilscope.Apply(
Active(),
ByRole("admin"),
RecentFirst(),
Paginate(page, perPage),
)
return models.Users(mods...).All(ctx, db)
}
Scope を定義する
Scope は func() []qm.QueryMod 型のシンプルな関数です。
package scopes
import "github.com/mickamy/boilscope"
// アクティブなレコードのみ
func Active() boilscope.Scope {
return boilscope.Where("active = ?", true)
}
// 特定のロールで絞り込み
func ByRole(role string) boilscope.Scope {
return boilscope.Where("role = ?", role)
}
// 作成日時の降順
func RecentFirst() boilscope.Scope {
return boilscope.OrderBy("created_at DESC")
}
// ページネーション
func Paginate(page, perPage int) boilscope.Scope {
return boilscope.Combine(
boilscope.Limit(perPage),
boilscope.Offset((page-1)*perPage),
)
}
条件付きで Scope を適用する
検索フォームのように、入力があるときだけ条件を追加したいケースでは If / Unless が便利です。
func SearchUsers(params SearchParams) []qm.QueryMod {
return boilscope.Apply(
// role が指定されていれば絞り込む
boilscope.If(params.Role != "", boilscope.Where("role = ?", params.Role)),
// name が指定されていれば部分一致検索
boilscope.If(params.Name != "", boilscope.Where("name LIKE ?", "%"+params.Name+"%")),
// onlyActive が false なら削除済みも含める
boilscope.Unless(params.IncludeDeleted, boilscope.Where("deleted_at IS NULL")),
RecentFirst(),
Paginate(params.Page, params.PerPage),
)
}
従来だと以下のように書く必要がありました:
func SearchUsers(params SearchParams) []qm.QueryMod {
var mods []qm.QueryMod
if params.Role != "" {
mods = append(mods, qm.Where("role = ?", params.Role))
}
if params.Name != "" {
mods = append(mods, qm.Where("name LIKE ?", "%"+params.Name+"%"))
}
if !params.IncludeDeleted {
mods = append(mods, qm.Where("deleted_at IS NULL"))
}
mods = append(mods, qm.OrderBy("created_at DESC"))
mods = append(mods, qm.Limit(params.PerPage))
mods = append(mods, qm.Offset((params.Page-1)*params.PerPage))
return mods
}
Scope を合成する
Combine を使うと複数の Scope を1つにまとめられます。
// 管理者用の共通スコープ
func AdminScope() boilscope.Scope {
return boilscope.Combine(
Active(),
ByRole("admin"),
boilscope.Where("verified = ?", true),
)
}
// 使う側
mods := boilscope.Apply(
AdminScope(),
RecentFirst(),
Paginate(1, 20),
)
デバッグ機能
開発中にどの Scope がどんな QueryMod を生成しているか確認したいときは、デバッグ機能が使えます。
// 個別の Scope をデバッグ
debuggedScope := boilscope.Debug(Active())
// Apply 時に全 Scope をログ出力
mods := boilscope.DebugApply(
Active(),
ByRole("admin"),
Paginate(1, 20),
)
// 出力例:
// [boilscope] Scope 1 produced 1 query mod(s)
// [boilscope] Scope 2 produced 1 query mod(s)
// [boilscope] Scope 3 produced 2 query mod(s)
// [boilscope] Total: 4 query mod(s) from 3 scope(s)
ロガーをカスタマイズすることも可能です:
boilscope.Logger = func(format string, args ...any) {
slog.Debug(fmt.Sprintf(format, args...))
}
提供している Query Builder
よく使う qm.* 関数に対応する Builder を用意しています。
| 関数 | 説明 |
|---|---|
Where(clause, args...) |
WHERE 句 |
And(clause, args...) |
AND 条件 |
Or(clause, args...) |
OR 条件 |
OrderBy(clause) |
ORDER BY 句 |
GroupBy(clause) |
GROUP BY 句 |
Having(clause, args...) |
HAVING 句 |
Limit(n) |
LIMIT 句 |
Offset(n) |
OFFSET 句 |
Select(columns...) |
SELECT するカラム |
From(table) |
FROM 句 |
InnerJoin(clause, args...) |
INNER JOIN |
LeftOuterJoin(clause, args...) |
LEFT OUTER JOIN |
Load(rel, mods...) |
リレーションの Eager Loading |
実践的な使用例
リポジトリパターンでの活用
type UserRepository struct {
db *sql.DB
}
func (r *UserRepository) FindAll(ctx context.Context, scopes ...boilscope.Scope) ([]*models.User, error) {
return models.Users(boilscope.Apply(scopes...)...).All(ctx, r.db)
}
func (r *UserRepository) FindOne(ctx context.Context, scopes ...boilscope.Scope) (*models.User, error) {
return models.Users(boilscope.Apply(scopes...)...).One(ctx, r.db)
}
// 使う側
users, err := repo.FindAll(ctx,
scopes.Active(),
scopes.ByRole("admin"),
scopes.Paginate(1, 20),
)
テストでの活用
Scope は単なる関数なのでテストも簡単です。
func TestActiveScope(t *testing.T) {
scope := Active()
mods := scope()
if len(mods) != 1 {
t.Errorf("expected 1 mod, got %d", len(mods))
}
}
func TestPaginateScope(t *testing.T) {
count := boilscope.Count(Paginate(2, 10))
if count != 2 { // Limit + Offset
t.Errorf("expected 2 mods, got %d", count)
}
}
まとめ
boilscope を使うことで:
- ✅ クエリ条件を再利用可能な単位に分割できる
- ✅ 条件の組み立てが宣言的になり可読性が向上する
- ✅
If/Unlessで条件分岐がスッキリ書ける - ✅ テストが書きやすくなる
SQLBoiler を使っている方はぜひ試してみてください。
Issue や PR もお待ちしています!
Discussion