pg/cmd/pg-lo-demo/main.go

87 lines
1.7 KiB
Go

package main
import (
"bytes"
"context"
"database/sql"
"flag"
"fmt"
"os"
"pg/src/with"
_ "github.com/lib/pq"
)
func main() {
if err := with.Context(run); err != nil {
panic(err)
}
}
func run(ctx context.Context) error {
fs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
c := fs.String("c", "postgresql://pulsegres:pulsegres@localhost:15432", "conn string")
if err := fs.Parse(os.Args[1:]); err != nil {
panic(err)
}
return with.PSQL(ctx, *c, func(pg *sql.DB) error {
cleanup := func() error {
rows, err := pg.QueryContext(ctx, `SELECT oid FROM oids`)
if err != nil {
return nil
}
defer rows.Close()
for rows.Next() {
var oid any
if err := rows.Scan(&oid); err != nil {
return err
}
pg.ExecContext(ctx, `SELECT lo_unlink($1)`, oid)
}
return rows.Err()
}
defer cleanup()
if err := cleanup(); err != nil {
return fmt.Errorf("failed initial cleanup: %w", err)
}
if _, err := pg.ExecContext(ctx, `
DROP TABLE IF EXISTS oids;
CREATE TABLE IF NOT EXISTS oids (id INTEGER PRIMARY KEY, oid OID);
`); err != nil {
return fmt.Errorf("failed initial table setup: %w", err)
}
if _, err := pg.ExecContext(ctx, `
INSERT INTO oids (
id,
oid
)
VALUES (
1,
lo_from_bytea(
0,
$1
)
) ON CONFLICT DO NOTHING
`, []byte("hello world")); err != nil {
return fmt.Errorf("failed lo_from_bytea: %w", err)
}
var got []byte
row := pg.QueryRowContext(ctx, `SELECT lo_get((SELECT oid FROM oids WHERE id=1))`)
if err := row.Err(); err != nil {
return err
} else if err := row.Scan(&got); err != nil {
return err
} else if !bytes.Equal(got, []byte("hello world")) {
return fmt.Errorf("weird lo_get: %q", got)
}
return cleanup()
})
}