Pg: Is it can cache query data at memory ?

Created on 11 Sep 2017  路  5Comments  路  Source: go-pg/pg

Can pg ORM setup to cache the query data at memory or other ?

Most helpful comment

It would be really interesting to "redis" Cache(id, object, interval) upon getter result success. Having it baked into go-pg would give the library a unique advantage.

All 5 comments

No, nothing like that at the moment.

It would be really interesting to "redis" Cache(id, object, interval) upon getter result success. Having it baked into go-pg would give the library a unique advantage.

I tried to play with the DB.Query() to achieve this but there is currently no way to modify Query.model. Here is an example:

package main

import (
    "time"
    "github.com/go-pg/pg"
    "github.com/go-pg/pg/orm"
)

type PgDb struct {
    *pg.DB
}

type cacheResult struct {
    result orm.Result
    models []interface{}
    query  interface{}
}

var (
    queryCache = make(map[string]cacheResult)
)

func (db *PgDb) Query(model, query interface{}, params ...interface{}) (res orm.Result, err error) {
    q, ok := query.(interface{ AppendQuery(b []byte) ([]byte, error) })
    if !ok {
        return db.DB.Query(model, query, params...)
    }

    var formattedQuery []byte
    formattedQuery, err = q.AppendQuery(nil)
    if err != nil {
        return
    }
    hash := string(formattedQuery)
    if cache, exists := queryCache[hash]; exists {
        //@todo need to get the models pointers (params in this case) and switch it to cache.models
        return cache.result, nil
    }
    res, err = db.DB.Query(model, query, params...)
    if err != nil {
        return
    }
    queryCache[hash] = cacheResult{result: res, models: params, query: query}

    return
}

func (db *PgDb) Model(model ...interface{}) *orm.Query {
    return orm.NewQuery(db, model...)
}

func (db *PgDb) Select(model interface{}) error {
    return orm.Select(db, model)
}

I suggest to look at https://github.com/dgraph-io/ristretto which is used by dgraph database for caching.

Any more thoughts/progress on this? I think ristretto is a promising avenue...

Was this page helpful?
0 / 5 - 0 ratings

Related issues

noggan picture noggan  路  5Comments

Alireza-Ta picture Alireza-Ta  路  3Comments

jayschwa picture jayschwa  路  4Comments

owentran picture owentran  路  6Comments

rhymes picture rhymes  路  5Comments