(GoLang) panic: sql: Register called twice for driver postgres - postgresql

I have probably spent way to much time on this, so I decided to try here.
I'm having trouble figuring out why my Register is being called twice?
Best I can figure, it seems to be calling once at sql.Register() and again at sqlx.Connect(). But if I remove the sql.Register(), then theres no drivers.
Honestly, I am pretty new to GoLang, I'm hoping for any sort of direction here.
Code - w/o sql.Register
package main
import (
"fmt"
"database/sql"
"github.com/jmoiron/sqlx"
)
const (
host = "localhost"
port = 5432
user = "postgres"
password = "password"
dbname = "sampledb"
)
/*-------------------------------------------*\
|| Functions ||
\*-------------------------------------------*/
// Error Checking Fn
func CheckError(err error, str string) {
if err != nil {
fmt.Printf("Error # : %s\n", str)
panic(err)
}
}
/*-------------------------------------------*\
|| Main() ||
\*-------------------------------------------*/
func main() {
// Open DB Conn
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
// sql.Register("postgres", &pq.Driver{})
fmt.Printf(":: Drivers ::\n%s\n", sql.Drivers())
db, err := sqlx.Connect("postgres", psqlconn)
CheckError(err, "Main: sqlx.connect")
defer db.Close()
}
Error - w/o sql.Register
$ go run name-generator.go
:: Drivers ::
[]
Error # : Main: sqlx.connect
panic: sql: unknown driver "postgres" (forgotten import?)
goroutine 1 [running]:
main.CheckError({0xc84320, 0xc000056680}, {0xc6073f, 0x5})
C:/path/to/program.go:26 +0xa7 <--- Func CheckError(): panic(err)
main.main()
C:/path/to/program.go:40 +0x125 <--- Func Main(): CheckError()
exit status 2
Code - w/ sql.Register
package main
import (
"fmt"
"database/sql"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "postgres"
password = "password"
dbname = "sampledb"
)
/*-------------------------------------------*\
|| Functions ||
\*-------------------------------------------*/
// Error Checking Fn
func CheckError(err error, str string) {
if err != nil {
fmt.Printf("Error # : %s\n", str)
panic(err)
}
}
/*-------------------------------------------*\
|| Main() ||
\*-------------------------------------------*/
func main() {
// Open DB Conn
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
sql.Register("postgres", &pq.Driver{})
fmt.Printf(":: Drivers ::\n%s\n", sql.Drivers())
db, err := sqlx.Connect("postgres", psqlconn)
CheckError(err, "Main: sqlx.connect")
defer db.Close()
}
Error - w/ sql.Register
$ go run name-generator.go
panic: sql: Register called twice for driver postgres
goroutine 1 [running]:
database/sql.Register({0xa98bc9, 0x8}, {0xae6680, 0xc8a950})
C:/Program Files/Go/src/database/sql/sql.go:51 +0x13d
main.main()
C:/path/to/program.go:38 +0x11b
exit status 2
Additional Resources
Similar issue, but doesn't solve my problem Link
SQLX Documentation Link
SQL Documentation Link

The package github.com/lib/pq registers it's driver in an init function.
Remove the direct call to register the driver from the application:
sql.Register("postgres", &pq.Driver{}) <-- delete this line
Import github.com/lib/pq for the side effect of executing the init() function:
package main
import (
"fmt"
"database/sql"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq" // <-- add this line
)

Related

conn closed when trying to make an insert into postgresql

I try to insert a user into postgres database and get three parameters back for futher processing but always get the error 'conn closed':
package db
import (
"context"
"os"
"github.com/jackc/pgx/v4"
)
const (
insertSql = "INSERT into users (name, email, created, status, role, password, activation_code) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING name, email, activation_code;"
)
type userRepository struct {
connect *pgx.Conn
}
func NewUserRepository(c *pgx.Conn) domain.UserRepository {
return &userRepository{
connect: c,
}
}
func (r *userRepository) Save(u *domain.User) (string, string, string, *resterrors.RestErr) {
var name, email, activation_code string
if r.connect == nil {
os.Exit(1)
}
if err := r.connect.QueryRow(context.Background(), insertSql, u.Name, u.Email, u.Created, u.Status, u.Role, u.Password, u.ActivationCode).Scan(&name, &email, &activation_code); err != nil {
logger.Error("error saving user to the database: " + err.Error())
return "", "", "", resterrors.NewIntenalServerError(resterrors.DB_ERROR)
}
return name, email, activation_code, nil
}
connect is inserted in application.go when respository is created
repository := db.NewUserRepository(postgresql.Connect)
userHandler := controller.NewUserHandler(service.NewUserService(repository))
Connect is globally declared in postgresql package
package postgresql
import (
"context"
"fmt"
"net/url"
"github.com/jackc/pgx/v4"
)
var (
Connect *pgx.Conn
username = "postgres"
password = "***********"
host = "127.0.0.1"
port = "5432"
dbName = "test"
)
func init() {
//prepare URL to connect to database
var err error
datasourceName := fmt.Sprintf("postgres://%s:%s#%s:%s/%s", username, password, host, port, dbName)
Connect, err = pgx.Connect(context.Background(), datasourceName)
if err != nil {
logger.Error("unable to connect to database: " + err.Error())
panic(fmt.Errorf("unable to connect to database: %w", err))
}
logger.Info("successsfully connected to postgres database")
// to close DB connection
defer Connect.Close(context.Background())
}
What could be wrong with it?
A single DB Connection is not concurrency safe and has no mechanism for reestablishing connections. Your issue is likely that concurrent access borked the connection, or it was closed for some other reason.
You want a DB Connection Pool so that it can create new connections for concurrent operations (requests for net/http servers handle connections concurrently). From https://pkg.go.dev/github.com/jackc/pgx/v4#hdr-Connection_Pool:
*pgx.Conn represents a single connection to the database and is not concurrency safe. Use sub-package pgxpool for a concurrency safe connection pool.
You should have better results with pgxpool - see https://pkg.go.dev/github.com/jackc/pgx/v4#v4.14.1/pgxpool#hdr-Establishing_a_Connection
The reason for the conn closed error was that the connection was closed within init() function straight after the application start.
defer Connect.Close(context.Background())

Go Mongo DB doesn't connect

I'm trying to connect to my mongo db atlas database, but I'm getting an error that I can't solve it within mongo+go forums.
The code:
package main
import (
"context"
"log"
"time"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/bson"
)
func main(){
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://my-user:<my-pass>#datalake0-lesz0.a.query.mongodb.net/my-db?ssl=true&authSource=admin"))
if err != nil {
log.Fatal(err)
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(ctx)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
}
databases, err := client.ListDatabaseNames(ctx, bson.M{})
if err != nil {
log.Fatal(err)
}
fmt.Println(databases)
}
The error:
connection() error occured during connection handshake: auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) authentication failed, correlationID = 167bc5ba18415510a4144b7a
exit status 1
If the URI in the connect string is verbatim, then this is your problem:
mongodb://my-user:<my-pass> is incorrect, <my-pass> should be substituted with your password
You've probably cut and pasted the provided URI on completion of DB setup but this connect string does not include items like your password, also you gave my-user which, unless you set up the username my-user that also needs changing.

Unable to connect to postgresql using Go and pq

I'm trying to connect a Go application with postgresql.
The app import postgresql driver:
"crypto/tls"
"database/sql"
"fmt"
"log"
"os"
"os/signal"
...
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
and uses like it to connect to the database:
driver, cnxn := dbFromURI(dbURI)
db, err := sql.Open(driver, cnxn)
if err != nil {
panic(err)
}
and the dbFromUri method just split the info
func dbFromURI(uri string) (string, string) {
parts := strings.Split(uri, "://")
return parts[0], parts[1]
}
My URI works locally when i run the command : psql postgresql://user:user#172.20.0.1:5432/lcp
But in go i Go, I got
./lcpserver
2021/03/07 02:00:42 Reading config /root/lcp-server-install/lcp-home/config/config.yaml
panic: pq: SSL is not enabled on the server
I tried this URI for Go without success : psql postgresql://user:user#172.20.0.1:5432/lcp?sslmode=disable
Do you have any idea why i can't connect ?
I tried with my aws rds postgres database, and got same result. Thnaks for the help.
complete code of the server
https://github.com/readium/readium-lcp-server/blob/master/lcpserver/lcpserver.go
I change the typo and the demo provided i succeed the connexion. But in the lcp server i style got the same issue.
postgres://user:user#172.20.0.1:5432/lcp?sslmode=disable
EDIT 2:
The error is due to the fact that the script tries prepare command. I update the minimal example and it fails too.
package main
import (
"database/sql"
"fmt"
"strings"
_ "github.com/lib/pq"
)
func dbFromURI(uri string) (string, string) {
parts := strings.Split(uri, "://")
return parts[0], parts[1]
}
func main() {
driver, cnxn := dbFromURI("postgres://user:user#172.20.0.1:5432/lcp?sslmode=disable")
fmt.Println("The driver " + driver)
fmt.Println("The cnxn " + cnxn)
db, err := sql.Open(driver, cnxn)
_, err = db.Prepare("SELECT id,encryption_key,location,length,sha256,type FROM content WHERE id = ? LIMIT 1")
if err != nil {
fmt.Println("Prepare failed")
fmt.Println(err)
}
if err == nil {
fmt.Println("Successfully connected")
} else {
panic(err)
}
}
I got :
prepare failed
pq: SSL is not enabled on the server
2021/03/07 17:20:13 This panic 3
panic: pq: SSL is not enabled on the server
The first problem is a typo in the connection string: postgresql://user:user#172.20.0.1:5432/lcp?sslmode=disable. In Go code it should be postgres://user:user#172.20.0.1:5432/lcp?sslmode=disable.
We also need to pass the full connection string as the second argument to sql.Open. For now, the dbFromURI function returns user:user#172.20.0.1:5432/lcp?sslmode=disable, but we need postgres://user:user#172.20.0.1:5432/lcp?sslmode=disable, because pq is waiting for this prefix to parse it.
After fixing this, I was able to establish a connection using a minimal postgres client based on your code.
To try this yourself, start the server with the following command:
docker run --rm -p 5432:5432 -e POSTGRES_PASSWORD=some_password postgres
And try to connect using the following client code:
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func main() {
cnxn := "postgres://postgres:some_password#127.0.0.1:5432/lcp?sslmode=disable"
_, err := sql.Open("postgres", cnxn)
if err != nil {
panic(err)
}
_, err = db.Prepare("SELECT id,encryption_key,location,length,sha256,type FROM content WHERE id = ? LIMIT 1")
if err != nil {
fmt.Println("Prepare failed")
panic(err)
}
}

How do I solve «panic: sql: unknown driver "postgres" (forgotten import?)»?

I'm trying to INSERT data into POSTGRES from a .csv (pre-fixed width / tabular ) with GO.
What I've done:
package main
import (
"bufio"
"database/sql"
"encoding/csv"
"encoding/json"
"fmt"
"io"
"log"
"os"
)
type Consumidor struct {
CPF string `json:"CPF"`
Private string `json:"Private"`
Incompleto string `json:"Incompleto"`
Compras *Compras `json:"Compras,omitempty"`
}
type Compras struct {
DataUltimacompra string `json:"DataUltimacompra"`
TicketMedio string `json:"TicketMedio"`
TicketUltimaCompra string `json:"TicketUltimaCompra"`
LojaMaisFrequente string `json:"LojaMaisFrequente"`
LojaUltimaCompra string `json:"LojaUltimaCompra"`
}
const (
host = "localhost"
port = 5432
user = "postgres"
password = ""
dbname = "neoway"
)
func main() {
csvFile, _ := os.Open("data.csv")
reader := csv.NewReader(bufio.NewReader(csvFile))
var dadosinsert []Consumidor
for {
line, error := reader.Read()
if error == io.EOF {
break
} else if error != nil {
log.Fatal(error)
}
dadosinsert = append(dadosinsert, Consumidor{
CPF: line[0],
Private: line[1],
Incompleto: line[2],
Compras: &Compras{
DataUltimacompra: line[3],
TicketMedio: line[4],
TicketUltimaCompra: line[5],
LojaMaisFrequente: line[6],
LojaUltimaCompra: line[7],
},
})
}
peopleJson, _ := json.Marshal(dadosinsert)
fmt.Println(string(peopleJson))
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
sqlStatement := `
INSERT INTO base_teste (CPF,"PRIVATE","INCOMPLETO","DATA DA ÚLTIMA COMPRA","TICKET MÉDIO","TICKET DA ÚLTIMA COMPRA","LOJA MAIS FREQUÊNTE","LOJA DA ÚLTIMA COMPRA")
)
VALUES ($1, $2, $3, $4, $5, $6, 7$, 8$)
RETURNING id`
id := 0
err = db.QueryRow(sqlStatement, 30, "a", "b", "c").Scan(&id)
if err != nil {
panic(err)
}
fmt.Println("New record ID is:", id)
}
when I run, I get this error
[{"CPF":"xxxxx","Private":"TRUE","Incompleto":"FALSE","Compras":{"DataUltimacompra":"12/10/2018","TicketMedio":"200","TicketUltimaCompra":"250","LojaMaisFrequente":"111.111.111-99","LojaUltimaCompra":"111.111.111-88"}}]
panic: sql: unknown driver "postgres" (forgotten import?)
goroutine 1 [running]: main.main() C:/Users/Willian/Desktop/NEOWAY
PROJECT/neoway csv prefixed width importer/main.go:70 +0xbed
Process finished with exit code 2
You imported the sql/database, a package contains generic interface for sql-related operation.
Since it's only generic interface, you need to import the concrete implementation of the interface, and in this context, it's the database driver.
From your code: sql.Open("postgres", psqlInfo), I presume you are using postgresql database. There are some postgresql drivers for golang available, one of them is https://github.com/lib/pq driver. So add it to the import statement.
package main
import (
"bufio"
"database/sql"
"encoding/csv"
"encoding/json"
"fmt"
"io"
"log"
"os"
_ "github.com/lib/pq" // <------------ here
)
The database driver pq must be imported with _ character in front of the import statement. It's because we don't use it explicitly on the code meanwhile it's still required by database/sql package. For more details see this related SO question What does an underscore in front of an import statement mean?.
More information about golang sql: https://pkg.go.dev/database/sql.
.

Golang SSH tunneling connection to a remote postgres DB

I have looked at various resources. I'm not sure how to accomplish this task. I can connect locally no problem, but I cannot connect to the remote easily. I need to pass on an RSA .pem key, and I'm not quite sure how to do this w/o forcing a connection unsecured
package main
import (
"database/sql"
"fmt"
"os"
_ "github.com/lib/pq"
)
var (
dbUser = os.Getenv("DB_USER")
dbPass = os.Getenv("DB_PASS")
dbName = os.Getenv("DB_NAME")
dbHost = os.Getenv("DB_HOST")
dbPort = os.Getenv("DB_PORT")
sslMode = os.Getenv("SSLMODE")
)
// ConnectDb is a short cut function that takes parameters through
// CLI that returns a pointer to a sql.DB connection.
// It takes no arguments.
func ConnectDb() (*sql.DB, error) {
db, err := sql.Open("postgres", getDbInfo())
CheckErr(err, "Unable to connecto tthe DB")
if err := db.Ping(); err != nil {
return nil, err
}
return db, nil
}
func getDbInfo() string {
var dbInfo string
if dbName != "" {
dbInfo += fmt.Sprintf("dbname=%s ", dbName)
} else {
dbInfo += fmt.Sprintf("dbname=%s ", "development")
}
// checks for nil value
if dbUser != "" {
dbInfo += fmt.Sprintf("dbuser=%s ", "user")
}
// checks for nil value
if dbPass != "" {
dbInfo += fmt.Sprintf("dbpass=%s ", dbPass)
}
if sslMode != "" {
dbInfo += fmt.Sprintf("sslmode=%s", sslMode)
} else {
dbInfo += fmt.Sprintf("sslmode=disable")
}
return dbInfo
}
It is my understanding that you need to open connection to postgre database. I don't know if a native postgre ssh tunneling support exists. So, this answer about SSH tunneling to DB machine.
I have not tested postgre this way, but I have had this model used in some proprietary server connections.
The process goes like that:
open ssh connection to db machine
establish tunnel from local port to remote db port
open db connection on local port
You can accomplish #1 and #2 with ssh client like OpenSSH or putty. You should probably do that 1st. If external client works, then you can attempt to put it all into go language code without external SSH client.
In go you would use
"golang.org/x/crypto/ssh"
package.
There are tutorials out there how to use GO ssh tunneling. Below is not a tested sample without error checking:
var buffer []byte
var err error
buffer, err = ioutil.ReadFile(sshKeyFile)
var key ssh.Signer
key, err = ssh.ParsePrivateKey(buffer)
var authMethod ssh.AuthMethod
authMethod = ssh.PublicKeys(key)
sshConfig = &ssh.ClientConfig{
User: "user_id",
Auth: []ssh.AuthMethod{authMethod},
}
conn, err := ssh.Dial("tcp", endpoint, sshConfig)
// open connection on postgre:
dbConn, err = conn.Dial("tcp", dbEndpoint)
The last line above is not exactly tunneling, but an TCP connection open to DB server. You might be able to pass that connection into db library. If not, you would have to setup a tunnel.