forked from survivorbat/gorm-like
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
62 lines (50 loc) · 1.52 KB
/
plugin.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package gormlike
import (
"gorm.io/gorm"
)
// Compile-time interface check
var _ gorm.Plugin = new(gormLike)
// Option can be given to the New() method to tweak its behaviour
type Option func(like *gormLike)
// WithCharacter allows you to specify a replacement character for the % in the LIKE queries
func WithCharacter(character string) Option {
return func(like *gormLike) {
like.replaceCharacter = character
}
}
// TaggedOnly makes it so that only fields with the tag `gormlike` can be turned into LIKE queries,
// useful if you don't want every field to be LIKE-able.
func TaggedOnly() Option {
return func(like *gormLike) {
like.conditionalTag = true
}
}
// SettingOnly makes it so that only queries with the setting 'gormlike' set to true can be turned into LIKE queries.
// This can be configured using db.Set("gormlike", true) on the query.
func SettingOnly() Option {
return func(like *gormLike) {
like.conditionalSetting = true
}
}
// New creates a new instance of the plugin that can be registered in gorm. Without any settings, all queries will be
// LIKE-d.
//
//nolint:ireturn // Acceptable
func New(opts ...Option) gorm.Plugin {
plugin := &gormLike{}
for _, opt := range opts {
opt(plugin)
}
return plugin
}
type gormLike struct {
replaceCharacter string
conditionalTag bool
conditionalSetting bool
}
func (d *gormLike) Name() string {
return "gormlike"
}
func (d *gormLike) Initialize(db *gorm.DB) error {
return db.Callback().Query().Before("gorm:query").Register("gormlike:query", d.queryCallback)
}