func (s *Server) Ensure(ctx context.Context, req *tenant.EnsureRequest) (*tenant.EnsureResponse, error) {
	var err error
	if req.Delete {
		err = util.Retry(ctx, func(ctx context.Context) error {
			tag, err := s.DB.Exec(ctx,
				"DELETE FROM tenants WHERE tenant = $1 AND version = $2",
				req.Tenant.ID, req.Tenant.Version)
			if err != nil {
				return err
			}
			if tag.RowsAffected() == 0 {
				return util.ErrVersionSkew
			}
			return nil
		})
	} else {
		err = util.Retry(ctx, func(ctx context.Context) error {
			tx, err := s.DB.Begin(ctx)
			if err != nil {
				return err
			}
			defer tx.Rollback(ctx)
			row := tx.QueryRow(ctx,
				"INSERT INTO tenants (tenant, label, version) "+
					"VALUES ($1, $2, 1) "+
					"ON CONFLICT (tenant) "+
					"DO UPDATE SET (label, version) = ("+
					" IF (length(excluded.label) > 0, excluded.label, tenants.label),"+
					" tenants.version + 1"+
					") RETURNING label, version", req.Tenant.ID, req.Tenant.Label)
			var pendingVersion int64
			if err := row.Scan(&req.Tenant.Label, &pendingVersion); err != nil {
				return err
			}
			if pendingVersion != req.Tenant.Version+1 {
				return util.ErrVersionSkew
			}
			if err := tx.Commit(ctx); err != nil {
				return err
			}
			req.Tenant.Version = pendingVersion
			s.Logger.Debugf("updated tenant %q to version %d", req.Tenant.ID, pendingVersion)
			return nil
		})
	}
	if err != nil {
		return nil, err
	}
	return &tenant.EnsureResponse{Tenant: req.Tenant}, nil
}
Ensure implements TenantsServer.
package tenant
import (
	"context"
	"github.com/Mandala/go-log"
	"github.com/bobvawter/cacheroach/api/tenant"
	"github.com/bobvawter/cacheroach/pkg/store/util"
	"github.com/google/wire"
	"github.com/jackc/pgx/v4"
	"github.com/jackc/pgx/v4/pgxpool"
	"github.com/pkg/errors"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
)
var Set = wire.NewSet(
	wire.Struct(new(Server), "*"),
	wire.Bind(new(tenant.TenantsServer), new(*Server)),
)
type Server struct {
	tenant.UnsafeTenantsServer `wire:"-"`
	DB                         *pgxpool.Pool
	Logger                     *log.Logger
}
var _ tenant.TenantsServer = (*Server)(nil)