Pass pointer from sql.DB as method parameter

1

I have a struct that has a save method that receives a pointer for access to the database as a parameter;

func (c Call) Save(db *sql.DB) error {
    stmt, err := db.Prepare('
        INSERT INTO calls values($1, $2, $3, $4)
    ')
    if err != nil {
        return err
    }
    // ...
}

However when I pass the pointer as a parameter a panic error is displayed;

  

link

The connection is defined as follows:

import (
    "database/sql"
    _ "github.com/lib/pq"
)

var db *sql.DB

func init() {
    db, _ := sql.Open("postgres", dsn)
    if err := db.Ping(); err != nil {
        log.Fatal(err.Error())
    }
}

Parameter passing occurs as follows:

err := c.Save(db)
// c é a struct que possui o método Save

Even though defining in the method that the parameter is a pointer this nil pointer error happens, because?

    
asked by anonymous 02.11.2018 / 20:09

1 answer

1

I believe the problem is the locally created variable. You're doing something like this:

package main
import "fmt"

var variavel *int

func init() {
    variavel, _ := new(int), new(int)
    fmt.Println("init:", variavel)
}

func main() {
    fmt.Println("main:", variavel)
}

The print will be:

init: 0x416020
main: <nil>

To fix you should use = instead of := . In this case using variavel, _ = new(int), new(int) would solve.

Change db, _ := sql.Open("postgres", dsn) to db, _ = sql.Open("postgres", sn) , so you will make the result in var db *sql.DB and not in a new local variable of init() :

import (
    "database/sql"
    _ "github.com/lib/pq"
)

var db *sql.DB

func init() {
    db, _ = sql.Open("postgres", dsn) // Usando = ao invés de := 
    if err := db.Ping(); err != nil {
        log.Fatal(err.Error())
    }
}

Another solution is to create another variable, such as:

func init() {
    dbX, _ := sql.Open("postgres", dsn) // Use :=
    if err := db.Ping(); err != nil {
        log.Fatal(err.Error())
    }
    db = dbX // Agora seta o db como valor do dbX, criado acima.
}
    
02.11.2018 / 21:08