lqs / sqlingo

💥 A lightweight DSL & ORM which helps you to write SQL in Go.
MIT License
415 stars 28 forks source link

I want to add a Cache-function, Currently like this, is there any other simplified way #4

Closed dulumao closed 4 years ago

dulumao commented 4 years ago

I want to add a Cache-function, Currently like this, is there any other simplified way

var foundCachedErr = errors.New("FoundCachedErr")

    db.SetInterceptor(func(ctx context.Context, sql string, invoker sqlingo.InvokerFunc) error {
        var v = ctx.Value("name").(string)

        if cache.Instance().Exists(v) {
            return foundCachedErr
        }

        return invoker(ctx, sql)
    })

    var member DtbMemberModel
    var cacheName = "DtbMember:ID:1"

    ctx := context.WithValue(context.Background(), "name", cacheName)

    ok, err := db.SelectFrom(DtbMember).Where(
        sqlingo.And(
            DtbMember.Id.Equals(1),
        ),
    ).WithContext(ctx).FetchFirst(&member)

    if errors.Is(err, foundCachedErr) {
        cache.Instance().Get(cacheName)
        // ....
        // return
    }

    if err != nil {
        panic(err)
    }

    // ....

    spew.Dump(ok)
    spew.Dump(member)
lqs commented 4 years ago

可以直接用最普通的缓存方式:

func GetMember(id int64) (member *DtbMemberModel, err error) {
    cacheName := fmt.Sprintf("DtbMember:ID:%d", id)
    if member = cache.Instance().Get(cacheName); member != nil {
        return
    }

    if _, err = db.SelectFrom(DtbMember).
        Where(DtbMember.Id.Equals(id)).
        FetchFirst(&member); err != nil {
        return
    }
    if member != nil {
        cache.Instance().Put(cacheName, member)
    }
    return
}
dulumao commented 4 years ago

谢谢啦