Will this work with pgx
in Go?
func CreateTable(
ctx context.Context,
pgxPool *pgxpool.Pool,
) error {
const tableQuery = `
INSERT INTO table (status)
VALUES ('Active');
INSERT INTO table_updates (status)
VALUES ('Active');
`
err := utilities.PerformExec(ctx, pgxPool, tableQuery, "CreateTable")
if err != nil {
return err
}
return nil
}
And this is the PerformExec
function.
func PerformExec(ctx context.Context, pgxPool *pgxpool.Pool, query, origin string, args ...interface{}) error {
_, err := pgxPool.Exec(ctx, query, args...)
if err != nil {
return err
}
return nil
}
If your reason to do this in single query is to avoid unnecessary network roundtrips then look at pgx.Batch
.
See example here: https://github.com/jackc/pgx/blob/c1b0a01ca75ac9eb3a7dbc1396f583ab5dbf9557/batch_test.go#L34
Apparently you can craft a single postgresql query that inserts into multiple tables - Refer answers here. But IMO pgx.Batch
is much readable solution.