lib / pq

Pure Go Postgres driver for database/sql
https://pkg.go.dev/github.com/lib/pq
MIT License
8.86k stars 908 forks source link

`postgres_sql_instance` can't get referenced even after I put it into a struct #1108

Open yingshaoxo opened 1 year ago

yingshaoxo commented 1 year ago

Here is the code 1:

package database

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/lib/pq" // add this
)

type FuckTheDatabaseClass struct {
    Postgres_sql *sql.DB
}

type TestUser struct {
    Email      string
    Username   *string
    Head_image *string //base64 string of an image
    Sex        *int32  //AI detect. 0: female, 1: male
    Age        *int32  //AI detect.
}

func (self FuckTheDatabaseClass) Init() error {
    postgres_sql_information := fmt.Sprintf(
        "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
        "127.0.0.1", 5432,
        "yingshaoxo", "yingshaoxo",
        "postgres")
    db, err := sql.Open("postgres", postgres_sql_information)
    if err != nil {
        log.Fatal(err)
    }

    self.Postgres_sql = db
    //*self.Postgres_sql = *db

    return err
}

func (self FuckTheDatabaseClass) Print_all_data_in_a_table(table_name string) error {
    user := TestUser{}

    err := self.Postgres_sql.QueryRow("SELECT 'yingshaoxo', NULL").Scan(&user.Username, &user.Age)
        // error in here

    log.Println(user.Username)
    log.Println(user.Age)

    return err
}

When I call Print_all_data_in_a_table("user"), an error happen.

Error message is:

Exception has occurred: panic
"runtime error: invalid memory address or nil pointer dereference"
Stack:
     2  0x00000001004efe14 in testing.tRunner.func1.2
         at /opt/homebrew/Cellar/go/1.19.3/libexec/src/testing/testing.go:1396
     3  0x00000001004ef710 in testing.tRunner.func1
         at /opt/homebrew/Cellar/go/1.19.3/libexec/src/testing/testing.go:1399
     7  0x0000000100554b8c in database/sql.(*DB).conn
         at /opt/homebrew/Cellar/go/1.19.3/libexec/src/database/sql/sql.go:1288
     8  0x0000000100556174 in database/sql.(*DB).query
         at /opt/homebrew/Cellar/go/1.19.3/libexec/src/database/sql/sql.go:1730
    (truncated)

My questions are:

  1. why the db variable sql.Open() returns are not copyable? If it is copyable, I could simply use it anywhere.
  2. If you guys already implemented the whole PostgreSQL driver logic, why don't you guys make a new package to simplify the SQL development process? I mean, like what I did, to make the sql as an inner variable inside of a struct(class).