jackc / pgx

PostgreSQL driver and toolkit for Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to call CopyFrom having only a sql.DB object?

sir-farfan opened this issue · comments

Hello
I need to do a bulk insert of thousands of rows using the copy protocol

The problem is, we're opening the DB connection using the stdlib compat db, err := sql.Open("pgx", "...") which returns a generic sql.DB object,.

Is there a way to get a pgx.Conn or Tx object from the sql.DB connection we have already built all the system around?

Had missed it in all the docs

// Given db is a *sql.DB
conn, err := db.Conn(context.Background())
if err != nil {
  // handle error from acquiring connection from DB pool
}

err = conn.Raw(func(driverConn any) error {
  conn := driverConn.(*stdlib.Conn).Conn() // conn is a *pgx.Conn
  // Do pgx specific stuff with conn
  conn.CopyFrom(...)
  return nil
})
if err != nil {
  // handle error that occurred while using *pgx.Conn
}