Created
March 21, 2014 13:43
-
-
Save karlseguin/9686555 to your computer and use it in GitHub Desktop.
A wrapper about lib/pq that auto-prepares queries and caches them.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type PgAutoPrepare struct { | |
driver.Conn | |
cache map[string]driver.Stmt | |
} | |
func (pap *PgAutoPrepare) Open(name string) (driver.Conn, error) { | |
conn, err := pq.Open(name) | |
if err != nil { | |
return nil, err | |
} | |
return &PgAutoPrepare{ | |
Conn: conn, | |
cache: make(map[string]driver.Stmt), | |
}, nil | |
} | |
func (pap *PgAutoPrepare) Query(query string, args []driver.Value) (driver.Rows, error) { | |
stmt, ok := pap.cache[query] | |
if ok == false { | |
var err error | |
stmt, err = pap.Conn.Prepare(query) | |
if err != nil { | |
return nil, err | |
} | |
pap.cache[query] = stmt | |
} | |
return stmt.Query(args) | |
} | |
func init() { | |
sql.Register("pgautoprepare", &PgAutoPrepare{}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you're worried about it getting crazy, when you add an item to the cache, do: