Copy data between tables and files

PostgreSQL allows to efficiently copy data between tables and files using COPY TO and COPY FROM commands.

COPY TO

To copy data from a table to an io.Writer:

  1. import "github.com/uptrace/bun/driver/pgdriver"
  2. conn, err := db.Conn(ctx)
  3. if err != nil {
  4. panic(err)
  5. }
  6. defer conn.Close()
  7. var buf bytes.Buffer
  8. res, err := pgdriver.CopyTo(ctx, conn, &buf, "COPY table_name TO STDOUT")
  9. if err != nil {
  10. panic(err)
  11. }
  12. fmt.Println(buf.String())

COPY FROM

To copy data from an io.Reader to a table:

  1. import "github.com/uptrace/bun/driver/pgdriver"
  2. conn, err := db.Conn(ctx)
  3. if err != nil {
  4. panic(err)
  5. }
  6. defer conn.Close()
  7. file, err := os.Open("data.csv")
  8. if err != nil {
  9. panic(err)
  10. }
  11. res, err := pgdriver.CopyFrom(ctx, conn, file, "COPY table_name FROM STDIN")
  12. if err != nil {
  13. panic(err)
  14. }