在Go语言中,可以通过接口来共享conn指针。

huangapple go评论88阅读模式
英文:

Sharing of conn pointer between interfaces in golang

问题

我试图实现的目标是在多个函数之间共享db.sqlx的指针,除了说要传递指针的帖子之外,其他都可以,但是如何在接口中实现呢?我找不到任何说明如何使用它的地方。基本上,我有一个Datastore类型的接口。我还有实现Datastore类型的mysql和pgsql。接口本身工作正常,但问题是我试图创建一个用于在实现的接口中所有函数之间共享*sqlx.DB的单个连接函数。我认为问题是我在如何在接口的函数之间共享指针或者在哪里共享它方面搞混了。主要接口如下所示:

var (
storage Datastore
db *sqlx.DB
)

type Datastore interface {
Insert(db *sqlx.DB, table string, item DataItem) bool
CheckEmpty(db *sqlx.DB, table string) bool
FetchAll(db *sqlx.DB, table string) []DataItem
DBInit(db *sqlx.DB)
initDB()
}

在我的实现接口中(简化的mysql示例)我有一个名为initDB的函数,它看起来像这样:

type MySQLDB struct {
config *config.Configuration
}

func (my *MySQLDB) initDB() {
log.Println("Getting DB Connection")
tempdb, err := sqlx.Connect("mysql", my.config.Database.Dsn+"&parseTime=True")
if err != nil {
log.Println(err.Error())
}
db = tempdb
defer db.Close()
}

func (my *MySQLDB) FetchAll(db *sqlx.DB, table string) []DataItem {
dTable := []DataItem{}
query := "SELECT foo, bar FROM " + table + " ORDER BY last_update ASC"
err := db.Select(&dTable, query)
if err != nil{
panic(err)
}
return dTable
}

到目前为止,我知道连接最初是打开的,但是下次调用函数时,我会得到db已关闭的错误。那么,我如何正确地在函数之间共享db连接,或者我真的必须在每个函数中运行一个连接打开吗?

英文:

What I'm trying to accomplish is sharing a pointer of db.sqlx between multiple functions, except for posts saying pass along the pointer, which is fine but how to do that in an interface? I cannot find anything that illustrates the use of this anywhere. Basically what I have is an interface of type Datastore. I also have mysql & pgsql that implements the Datastore type. The interface by itself works fine however the issue is I'm trying to create a single connect function for *sqlx.DB to be shared across all functions within the implemented interface. I think the issue is I've confused myself on how to share the pointer between functions of the interface or even "where" to share it. The main interface looks like below:

var (
    storage Datastore
    db * sqlx.DB
)

type Datastore interface {
    Insert(db *sqlx.DB, table string, item DataItem) bool
    CheckEmpty(db *sqlx.DB, table string) bool
    FetchAll(db *sqlx.DB, table string) []DataItem
    DBInit(db *sqlx.DB)
    initDB()
}

Within my implemented interface (simplified mysql example) I have the initDB function which looks like this:

type MySQLDB struct {
    config *config.Configuration
}


func (my *MySQLDB) initDB() {
    log.Println("Getting DB Connection")
    tempdb, err := sqlx.Connect("mysql", my.config.Database.Dsn+"&parseTime=True")
    if err != nil {
        log.Println(err.Error())
    }
    db = tempdb
    defer db.Close()
}

func (my *MySQLDB) FetchAll(db *sqlx.DB, table string) []DataItem {
	dTable := []DataItem{}
	query := "SELECT foo, bar FROM " + table + " ORDER BY last_update ASC"
	err := db.Select(&dTable, query)
	if err != nil{
        panic(err)
    }
	return dTable
}

At this point I know the connection is initially opened but the next time a function is called I get db is closed error. So how do I properly share the db connection between functions, or do I really have to run a connection open in every function?

答案1

得分: 2

不要在你的initDB函数中调用defer db.Close()。在该函数执行后,db也会关闭!所以当你调用你的方法时,会得到关闭的错误。
也许你需要重新设计你的接口,例如:

type Datastore interface {
    Insert(table string, item DataItem) bool
    CheckEmpty(table string) bool
    FetchAll(table string) []DataItem
    Close() error // 当你想关闭连接时调用这个方法
    initDB()
}

你的MySQLDB实现现在看起来像这样:

type MySQLDB struct {
    config *config.Configuration
    db *sqlx.DB
}


func (my *MySQLDB) initDB() {
    log.Println("Getting DB Connection")
    tempdb, err := sqlx.Connect("mysql", my.config.Database.Dsn+"&parseTime=True")
    if err != nil {
        log.Println(err.Error())
    }
    my.db = tempdb
}

func (my *MySQLDB) Close() error {
    return my.db.Close()
}

func (my *MySQLDB) FetchAll(table string) []DataItem {
    dTable := []DataItem{}
    query := "SELECT foo, bar FROM " + table + " ORDER BY last_update ASC"
    err := my.db.Select(&dTable, query)
    if err != nil{
        panic(err)
    }
    return dTable
}
英文:

Don't call defer db.Close() in your initDB function. After that function executed, db will close too! So when you call your method you get the closed error.
Maybe you need to re-desgin your interface, for example:

type Datastore interface {
    Insert(table string, item DataItem) bool
    CheckEmpty(table string) bool
    FetchAll(table string) []DataItem
    Close() error // call this method when you want to close the connection
    initDB()
}

Your MySQLDB implement now look like:

type MySQLDB struct {
    config *config.Configuration
    db *sqlx.DB
}


func (my *MySQLDB) initDB() {
    log.Println("Getting DB Connection")
    tempdb, err := sqlx.Connect("mysql", my.config.Database.Dsn+"&parseTime=True")
    if err != nil {
        log.Println(err.Error())
    }
    my.db = tempdb
}

func (my *MySQLDB) Close() error {
    return my.db.Close()
}

func (my *MySQLDB) FetchAll(table string) []DataItem {
    dTable := []DataItem{}
    query := "SELECT foo, bar FROM " + table + " ORDER BY last_update ASC"
    err := my.db.Select(&dTable, query)
    if err != nil{
        panic(err)
    }
    return dTable
}

huangapple
  • 本文由 发表于 2015年3月3日 01:09:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/28815555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定