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"

3. conn, err := db.Conn(ctx)
4. if err != nil {
5. panic(err)
6. }
7. defer conn.Close()

9. var buf bytes.Buffer

11. res, err := pgdriver.CopyTo(ctx, conn, &buf, "COPY table_name TO STDOUT")
12. if err != nil {
13. panic(err)
14. }

16. fmt.Println(buf.String())

COPY FROM

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

1. import "github.com/uptrace/bun/driver/pgdriver"

3. conn, err := db.Conn(ctx)
4. if err != nil {
5. panic(err)
6. }
7. defer conn.Close()

9. file, err := os.Open("data.csv")
10. if err != nil {
11. panic(err)
12. }

14. res, err := pgdriver.CopyFrom(ctx, conn, file, "COPY table_name FROM STDIN")
15. if err != nil {
16. panic(err)
17. }