Skip to content

Commit

Permalink
...
Browse files Browse the repository at this point in the history
  • Loading branch information
wubin1989 committed Dec 10, 2023
1 parent 7ff1737 commit 9faf4b3
Show file tree
Hide file tree
Showing 17 changed files with 1,511 additions and 0 deletions.
21 changes: 21 additions & 0 deletions toolkit/caches/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023-NOW Kristian Tsivkov <ktsivkov.eu>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
235 changes: 235 additions & 0 deletions toolkit/caches/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
# Gorm Caches

Gorm Caches plugin using database request reductions (easer), and response caching mechanism provide you an easy way to optimize database performance.

## Features

- Database request reduction. If three identical requests are running at the same time, only the first one is going to be executed, and its response will be returned for all.
- Database response caching. By implementing the Cacher interface, you can easily setup a caching mechanism for your database queries.
- Supports all databases that are supported by gorm itself.

## Install

```bash
go get -u github.com/go-gorm/caches/v2
```

## Usage

Configure the `easer`, and the `cacher`, and then load the plugin to gorm.

```go
package main

import (
"fmt"
"sync"

"github.com/go-gorm/caches"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)

func main() {
db, _ := gorm.Open(
mysql.Open("DATABASE_DSN"),
&gorm.Config{},
)
cachesPlugin := &caches.Caches{Conf: &caches.Config{
Easer: true,
Cacher: &yourCacherImplementation{},
}}
_ = db.Use(cachesPlugin)
}
```

## Easer Example

```go
package main

import (
"fmt"
"sync"
"time"

"github.com/go-gorm/caches"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)

type UserRoleModel struct {
gorm.Model
Name string `gorm:"unique"`
}

type UserModel struct {
gorm.Model
Name string
RoleId uint
Role *UserRoleModel `gorm:"foreignKey:role_id;references:id"`
}

func main() {
db, _ := gorm.Open(
mysql.Open("DATABASE_DSN"),
&gorm.Config{},
)

cachesPlugin := &caches.Caches{Conf: &caches.Config{
Easer: true,
}}

_ = db.Use(cachesPlugin)

_ = db.AutoMigrate(&UserRoleModel{})

_ = db.AutoMigrate(&UserModel{})

adminRole := &UserRoleModel{
Name: "Admin",
}
db.FirstOrCreate(adminRole, "Name = ?", "Admin")

guestRole := &UserRoleModel{
Name: "Guest",
}
db.FirstOrCreate(guestRole, "Name = ?", "Guest")

db.Save(&UserModel{
Name: "ktsivkov",
Role: adminRole,
})
db.Save(&UserModel{
Name: "anonymous",
Role: guestRole,
})

var (
q1Users []UserModel
q2Users []UserModel
)
wg := &sync.WaitGroup{}
wg.Add(2)
go func() {
db.Model(&UserModel{}).Joins("Role").Find(&q1Users, "Role.Name = ? AND Sleep(1) = false", "Admin")
wg.Done()
}()
go func() {
time.Sleep(500 * time.Millisecond)
db.Model(&UserModel{}).Joins("Role").Find(&q2Users, "Role.Name = ? AND Sleep(1) = false", "Admin")
wg.Done()
}()
wg.Wait()

fmt.Println(fmt.Sprintf("%+v", q1Users))
fmt.Println(fmt.Sprintf("%+v", q2Users))
}
```

## Cacher Example

```go
package main

import (
"fmt"
"sync"

"github.com/go-gorm/caches"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)

type UserRoleModel struct {
gorm.Model
Name string `gorm:"unique"`
}

type UserModel struct {
gorm.Model
Name string
RoleId uint
Role *UserRoleModel `gorm:"foreignKey:role_id;references:id"`
}

type dummyCacher struct {
store *sync.Map
}

func (c *dummyCacher) init() {
if c.store == nil {
c.store = &sync.Map{}
}
}

func (c *dummyCacher) Get(key string) *caches.Query {
c.init()
val, ok := c.store.Load(key)
if !ok {
return nil
}

return val.(*caches.Query)
}

func (c *dummyCacher) Store(key string, val *caches.Query) error {
c.init()
c.store.Store(key, val)
return nil
}

func main() {
db, _ := gorm.Open(
mysql.Open("DATABASE_DSN"),
&gorm.Config{},
)

cachesPlugin := &caches.Caches{Conf: &caches.Config{
Cacher: &dummyCacher{},
}}

_ = db.Use(cachesPlugin)

_ = db.AutoMigrate(&UserRoleModel{})

_ = db.AutoMigrate(&UserModel{})

adminRole := &UserRoleModel{
Name: "Admin",
}
db.FirstOrCreate(adminRole, "Name = ?", "Admin")

guestRole := &UserRoleModel{
Name: "Guest",
}
db.FirstOrCreate(guestRole, "Name = ?", "Guest")

db.Save(&UserModel{
Name: "ktsivkov",
Role: adminRole,
})
db.Save(&UserModel{
Name: "anonymous",
Role: guestRole,
})

var (
q1Users []UserModel
q2Users []UserModel
)

db.Model(&UserModel{}).Joins("Role").Find(&q1Users, "Role.Name = ? AND Sleep(1) = false", "Admin")
fmt.Println(fmt.Sprintf("%+v", q1Users))

db.Model(&UserModel{}).Joins("Role").Find(&q2Users, "Role.Name = ? AND Sleep(1) = false", "Admin")
fmt.Println(fmt.Sprintf("%+v", q2Users))
}
```

## License

MIT license.

## Easer
The easer is an adjusted version of the [ServantGo](https://github.com/ktsivkov/servantgo) library to fit the needs of this plugin.
7 changes: 7 additions & 0 deletions toolkit/caches/cacher.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package caches

type Cacher interface {
Get(key string) *Query
Store(key string, val *Query) error
Delete(tag string, tags ...string) error
}
66 changes: 66 additions & 0 deletions toolkit/caches/cacher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package caches

import (
"errors"
"sync"
)

type cacherMock struct {
store *sync.Map
}

func (c *cacherMock) Delete(tag string, tags ...string) error {
//TODO implement me
panic("implement me")
}

func (c *cacherMock) init() {
if c.store == nil {
c.store = &sync.Map{}
}
}

func (c *cacherMock) Get(key string) *Query {
c.init()
val, ok := c.store.Load(key)
if !ok {
return nil
}

return val.(*Query)
}

func (c *cacherMock) Store(key string, val *Query) error {
c.init()
c.store.Store(key, val)
return nil
}

type cacherStoreErrorMock struct {
store *sync.Map
}

func (c *cacherStoreErrorMock) Delete(tag string, tags ...string) error {
//TODO implement me
panic("implement me")
}

func (c *cacherStoreErrorMock) init() {
if c.store == nil {
c.store = &sync.Map{}
}
}

func (c *cacherStoreErrorMock) Get(key string) *Query {
c.init()
val, ok := c.store.Load(key)
if !ok {
return nil
}

return val.(*Query)
}

func (c *cacherStoreErrorMock) Store(string, *Query) error {
return errors.New("store-error")
}
Loading

0 comments on commit 9faf4b3

Please sign in to comment.