Wrapper for pgx/v5 pool.
scany/v2 is used to provide Select & Get convenience methods.
All basic (i.e. not raw) methods take sqlizer interface as a query, which is provided by squirrel query builder.
Actual data-access methods should take pgsq.Queryable as an argument–this way CreateEntity can be called using a connection pool or a transaction depending on logical requirements.
package database
import (
"context"
"fmt"
"github.com/vaardan/pgsq"
"github.com/Masterminds/squirrel"
)
// CreateEntity creates new entity with the given name and returns its ID.
func CreateEntity(ctx context.Context, q pgsq.Queryable, name string) (int, error) {
query := squirrel.StatementBuilder.
PlaceholderFormat(squirrel.Dollar).
Insert("entity_table").
Columns("name").
Values(name).
Suffix("returning id")
var id int
err := q.Get(ctx, &id, query)
if err != nil {
return 0, fmt.Errorf("insert entity: %w", err)
}
return id, nil
}