feat(org): add organization and membership contract and storage

This commit is contained in:
shira committed 2026-10-06 15:55:29 +03:00
1 parent a0551a34b8
commit bdc5855001
90 files changed
+17545 -480

No files matched your search

@@ -0,0 +1,430 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// organizationConstraintErrors maps the organization constraints whose
// violation is a caller-visible outcome to port sentinels by SQLSTATE and
// constraint name, never by text.
var organizationConstraintErrors = map[constraintViolation]error{
{uniqueViolationCode, "memberships_user_id_organization_id_key"}: outbound.ErrMembershipExists,
{foreignKeyViolationCode, "memberships_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
{foreignKeyViolationCode, "memberships_user_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "organization_representatives_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
}
// mapOrganizationError turns a known organization constraint violation into
// its port sentinel and keeps the constraint name. Any other PostgreSQL error
// is replaced by its SQLSTATE and constraint name, because its detail quotes
// the failing row, which holds names of representatives. Deadlocks and
// serialization failures also match ErrTransactionConflict. A connection
// error loses the pgx prefix that names the database user and database.
func mapOrganizationError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
if sentinel, ok := organizationConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok {
return fmt.Errorf("postgres.mapOrganizationError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
var _ outbound.OrganizationRepositories = (*UnitOfWork)(nil)
func (unit *UnitOfWork) Organizations() outbound.OrganizationRepository {
return organizationRepository{queries: unit.queries}
}
func (unit *UnitOfWork) Memberships() outbound.MembershipRepository {
return membershipRepository{queries: unit.queries}
}
type organizationRepository struct {
queries *sqlc.Queries
}
var _ outbound.OrganizationRepository = organizationRepository{}
func (repository organizationRepository) CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error {
const location = "organizationRepository.CreateWithOwner"
switch {
case organization.IsZero():
return fmt.Errorf("%s - organization was not built by domain.NewOrganization: %w", location, domain.ErrInvalidOrganization)
case owner.IsZero():
return fmt.Errorf("%s - owner was not built by domain.NewOwnerMembership: %w", location, domain.ErrInvalidMembership)
case owner.OrganizationID() != organization.ID() || owner.Role() != domain.OrganizationRoleOwner || !owner.GrantsAccess():
return fmt.Errorf("%s - owner must be the active owner membership of the organization: %w", location, domain.ErrInvalidMembership)
}
profile := organization.Profile()
contacts := profile.Contacts()
verification := organization.Verification()
err := repository.queries.InsertOrganization(ctx, sqlc.InsertOrganizationParams{
ID: pgUUID(organization.ID()),
Name: profile.Name(),
Description: pgOptionalText(profile.Description()),
Sphere: pgOptionalText(profile.Sphere()),
ContactWebsite: pgOptionalText(contacts.Website()),
ContactEmail: pgOptionalText(contacts.Email()),
ContactPhone: pgOptionalText(contacts.Phone()),
ContactTelegram: pgOptionalText(contacts.Telegram()),
VerificationLevel: string(verification.Level()),
VerificationBasis: string(verification.Basis()),
VerificationChangedAt: pgTime(verification.ChangedAt()),
Version: organization.Version(),
CreatedAt: pgTime(organization.CreatedAt()),
UpdatedAt: pgTime(organization.UpdatedAt()),
})
if err != nil {
return fmt.Errorf("%s - insert organization: %w", location, mapOrganizationError(err))
}
if err := repository.insertRepresentatives(ctx, organization.ID(), profile.Representatives()); err != nil {
return fmt.Errorf("%s - insert representatives: %w", location, err)
}
if err := insertMembership(ctx, repository.queries, owner); err != nil {
return fmt.Errorf("%s - insert owner membership: %w", location, err)
}
return nil
}
func (repository organizationRepository) insertRepresentatives(
ctx context.Context,
organizationID uuid.UUID,
representatives []domain.OrganizationRepresentative,
) error {
for index, representative := range representatives {
err := repository.queries.InsertOrganizationRepresentative(ctx, sqlc.InsertOrganizationRepresentativeParams{
OrganizationID: pgUUID(organizationID),
Ordinal: int16(index),
Name: representative.Name(),
JobTitle: representative.JobTitle(),
})
if err != nil {
return mapOrganizationError(err)
}
}
return nil
}
func (repository organizationRepository) GetForMember(
ctx context.Context,
organizationID, userID uuid.UUID,
) (domain.Organization, domain.Membership, error) {
const location = "organizationRepository.GetForMember"
row, err := repository.queries.GetOrganizationForMember(ctx, sqlc.GetOrganizationForMemberParams{
OrganizationID: pgUUID(organizationID),
UserID: pgUUID(userID),
})
if err != nil {
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - select organization: %w", location, mapOrganizationNoRows(err, outbound.ErrOrganizationNotFound))
}
representatives, err := decodeRepresentatives(row.Representatives)
if err != nil {
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - decode representatives: %w", location, err)
}
organization, err := organizationFromColumns(organizationColumns{
ID: row.ID, Name: row.Name, Description: row.Description, Sphere: row.Sphere,
ContactWebsite: row.ContactWebsite, ContactEmail: row.ContactEmail,
ContactPhone: row.ContactPhone, ContactTelegram: row.ContactTelegram,
VerificationLevel: row.VerificationLevel, VerificationBasis: row.VerificationBasis,
VerificationChangedAt: row.VerificationChangedAt, Version: row.Version,
CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,
}, representatives)
if err != nil {
return domain.Organization{}, domain.Membership{}, err
}
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: optionalUUID(row.MembershipID),
OrganizationID: organizationID,
UserID: userID,
Role: row.MembershipRole,
State: row.MembershipState,
CreatedAt: row.MembershipCreatedAt.Time,
UpdatedAt: row.MembershipUpdatedAt.Time,
})
if err != nil {
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - restore membership: %w", location, err)
}
return organization, membership, nil
}
// representativeJSON is one element of the representatives column that
// GetOrganizationForMember aggregates in the same statement as the
// organization, so the profile and the list come from one snapshot.
type representativeJSON struct {
Name string `json:"name"`
JobTitle string `json:"job_title"`
}
func decodeRepresentatives(column string) ([]domain.StoredRepresentative, error) {
var decoded []representativeJSON
if err := json.Unmarshal([]byte(column), &decoded); err != nil {
// The error of the decoder can quote the document, which holds names.
return nil, errors.New("postgres.decodeRepresentatives - the representatives column is not a list of name and job title")
}
representatives := make([]domain.StoredRepresentative, 0, len(decoded))
for _, representative := range decoded {
representatives = append(representatives, domain.StoredRepresentative(representative))
}
return representatives, nil
}
func (repository organizationRepository) ListForUser(ctx context.Context, query outbound.OrganizationListQuery) (outbound.OrganizationPage, error) {
const location = "organizationRepository.ListForUser"
if query.UserID == uuid.Nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - user ID must not be nil: %w", location, domain.ErrInvalidMembership)
}
if query.Limit < 1 || query.Limit > outbound.MaxOrganizationPageSize {
return outbound.OrganizationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxOrganizationPageSize, domain.ErrInvalidMembership)
}
params := sqlc.ListOrganizationsForUserParams{
UserID: pgUUID(query.UserID),
// One extra row tells whether another page follows.
RowLimit: query.Limit + 1,
}
if query.After != nil {
if err := requireTime(location, query.After.JoinedAt, domain.ErrInvalidMembership); err != nil {
return outbound.OrganizationPage{}, err
}
if query.After.OrganizationID == uuid.Nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - position organization ID must not be nil: %w", location, domain.ErrInvalidMembership)
}
params.AfterJoinedAt = pgTime(query.After.JoinedAt)
params.AfterOrganizationID = pgUUID(query.After.OrganizationID)
}
rows, err := repository.queries.ListOrganizationsForUser(ctx, params)
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - select organizations: %w", location, mapOrganizationError(err))
}
page := outbound.OrganizationPage{HasMore: len(rows) > int(query.Limit)}
if page.HasMore {
rows = rows[:query.Limit]
}
page.Items = make([]outbound.MemberOrganization, 0, len(rows))
for _, row := range rows {
summary, err := domain.RestoreOrganizationSummary(optionalUUID(row.ID), row.Name, row.VerificationLevel)
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - restore organization: %w", location, err)
}
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: optionalUUID(row.MembershipID),
OrganizationID: summary.ID(),
UserID: query.UserID,
Role: row.MembershipRole,
State: row.MembershipState,
CreatedAt: row.MembershipCreatedAt.Time,
UpdatedAt: row.MembershipUpdatedAt.Time,
})
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - restore membership: %w", location, err)
}
page.Items = append(page.Items, outbound.MemberOrganization{Organization: summary, Membership: membership})
}
return page, nil
}
func (repository organizationRepository) UpdateProfile(
ctx context.Context,
actorID uuid.UUID,
organization domain.Organization,
) (domain.Organization, error) {
const location = "organizationRepository.UpdateProfile"
if organization.IsZero() || actorID == uuid.Nil {
return domain.Organization{}, fmt.Errorf("%s - organization and actor must be set: %w", location, domain.ErrInvalidOrganization)
}
// The generated parameter structs of this repository hold representative
// names and contacts: never log them.
profile := organization.Profile()
contacts := profile.Contacts()
row, err := repository.queries.UpdateOrganizationProfile(ctx, sqlc.UpdateOrganizationProfileParams{
Name: profile.Name(),
Description: pgOptionalText(profile.Description()),
Sphere: pgOptionalText(profile.Sphere()),
ContactWebsite: pgOptionalText(contacts.Website()),
ContactEmail: pgOptionalText(contacts.Email()),
ContactPhone: pgOptionalText(contacts.Phone()),
ContactTelegram: pgOptionalText(contacts.Telegram()),
UpdatedAt: pgTime(organization.UpdatedAt()),
ID: pgUUID(organization.ID()),
ExpectedVersion: organization.Version(),
ActorID: pgUUID(actorID),
ManagerRoles: managerRoleNames(),
})
if errors.Is(err, pgx.ErrNoRows) {
return domain.Organization{}, fmt.Errorf("%s - update organization: %w", location, repository.explainRejectedUpdate(ctx, actorID, organization))
}
if err != nil {
return domain.Organization{}, fmt.Errorf("%s - update organization: %w", location, mapOrganizationError(err))
}
// The row lock of the update holds until the transaction ends, so no
// other writer replaces the list between these statements.
if err := repository.queries.DeleteOrganizationRepresentatives(ctx, row.ID); err != nil {
return domain.Organization{}, fmt.Errorf("%s - delete representatives: %w", location, mapOrganizationError(err))
}
if err := repository.insertRepresentatives(ctx, organization.ID(), profile.Representatives()); err != nil {
return domain.Organization{}, fmt.Errorf("%s - insert representatives: %w", location, err)
}
stored := make([]domain.StoredRepresentative, 0, len(profile.Representatives()))
for _, representative := range profile.Representatives() {
stored = append(stored, domain.StoredRepresentative{Name: representative.Name(), JobTitle: representative.JobTitle()})
}
return organizationFromColumns(organizationColumns(row), stored)
}
// explainRejectedUpdate tells why the update matched no row: an unknown
// organization or an actor without an active membership, a membership whose
// role cannot manage, or a stale version, in that order.
func (repository organizationRepository) explainRejectedUpdate(
ctx context.Context,
actorID uuid.UUID,
organization domain.Organization,
) error {
row, err := repository.queries.GetOrganizationForMember(ctx, sqlc.GetOrganizationForMemberParams{
OrganizationID: pgUUID(organization.ID()),
UserID: pgUUID(actorID),
})
switch {
case errors.Is(err, pgx.ErrNoRows):
return outbound.ErrOrganizationNotFound
case err != nil:
return mapOrganizationError(err)
}
role, err := domain.ParseOrganizationRole(row.MembershipRole)
switch {
case err != nil:
return fmt.Errorf("postgres.explainRejectedUpdate - validate role: %w", err)
case !role.CanManageOrganization():
return outbound.ErrOrganizationManagerRequired
default:
return outbound.ErrOrganizationVersionConflict
}
}
func managerRoleNames() []string {
roles := domain.ManagerRoles()
names := make([]string, 0, len(roles))
for _, role := range roles {
names = append(names, string(role))
}
return names
}
// organizationColumns has the columns of an organization row that every
// organization query returns. The generated row of UpdateOrganizationProfile
// converts to it.
type organizationColumns struct {
ID pgtype.UUID
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
func organizationFromColumns(columns organizationColumns, representatives []domain.StoredRepresentative) (domain.Organization, error) {
organization, err := domain.RestoreOrganization(domain.StoredOrganization{
ID: optionalUUID(columns.ID),
Name: columns.Name,
Description: columns.Description.String,
Sphere: columns.Sphere.String,
Website: columns.ContactWebsite.String,
Email: columns.ContactEmail.String,
Phone: columns.ContactPhone.String,
Telegram: columns.ContactTelegram.String,
Representatives: representatives,
VerificationLevel: columns.VerificationLevel,
VerificationBasis: columns.VerificationBasis,
VerificationChangedAt: columns.VerificationChangedAt.Time,
Version: columns.Version,
CreatedAt: columns.CreatedAt.Time,
UpdatedAt: columns.UpdatedAt.Time,
})
if err != nil {
return domain.Organization{}, fmt.Errorf("postgres.organizationFromColumns - restore organization: %w", err)
}
return organization, nil
}
type membershipRepository struct {
queries *sqlc.Queries
}
var _ outbound.MembershipRepository = membershipRepository{}
func (repository membershipRepository) Insert(ctx context.Context, membership domain.Membership) error {
if membership.IsZero() {
return fmt.Errorf("membershipRepository.Insert - membership was not built by domain.NewMembership: %w", domain.ErrInvalidMembership)
}
if err := insertMembership(ctx, repository.queries, membership); err != nil {
return fmt.Errorf("membershipRepository.Insert - insert membership: %w", err)
}
return nil
}
func insertMembership(ctx context.Context, queries *sqlc.Queries, membership domain.Membership) error {
err := queries.InsertMembership(ctx, sqlc.InsertMembershipParams{
ID: pgUUID(membership.ID()),
OrganizationID: pgUUID(membership.OrganizationID()),
UserID: pgUUID(membership.UserID()),
Role: string(membership.Role()),
State: string(membership.State()),
CreatedAt: pgTime(membership.CreatedAt()),
UpdatedAt: pgTime(membership.UpdatedAt()),
})
if err != nil {
return mapOrganizationError(err)
}
return nil
}
func (repository membershipRepository) Get(ctx context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) {
const location = "membershipRepository.Get"
row, err := repository.queries.GetMembership(ctx, sqlc.GetMembershipParams{
OrganizationID: pgUUID(organizationID),
UserID: pgUUID(userID),
})
if err != nil {
return domain.Membership{}, fmt.Errorf("%s - select membership: %w", location, mapOrganizationNoRows(err, outbound.ErrMembershipNotFound))
}
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: optionalUUID(row.ID),
OrganizationID: optionalUUID(row.OrganizationID),
UserID: optionalUUID(row.UserID),
Role: row.Role,
State: row.State,
CreatedAt: row.CreatedAt.Time,
UpdatedAt: row.UpdatedAt.Time,
})
if err != nil {
return domain.Membership{}, fmt.Errorf("%s - restore membership: %w", location, err)
}
return membership, nil
}
func mapOrganizationNoRows(err, sentinel error) error {
if errors.Is(err, pgx.ErrNoRows) {
return sentinel
}
return mapOrganizationError(err)
}
@@ -0,0 +1,83 @@
package postgres
import (
"context"
"errors"
"strings"
"testing"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// organizationDetailMarker stands for a row value that a PostgreSQL detail
// can quote, such as the name of a representative.
const organizationDetailMarker = "Failing row contains (Анна Тестова, Руководитель)"
func TestMapOrganizationErrorRecognizesOrganizationConstraints(t *testing.T) {
for _, test := range []struct {
code string
constraint string
want error
}{
{code: uniqueViolationCode, constraint: "memberships_user_id_organization_id_key", want: outbound.ErrMembershipExists},
{code: foreignKeyViolationCode, constraint: "memberships_organization_id_fkey", want: outbound.ErrOrganizationNotFound},
{code: foreignKeyViolationCode, constraint: "memberships_user_id_fkey", want: outbound.ErrUserNotFound},
{code: foreignKeyViolationCode, constraint: "organization_representatives_organization_id_fkey", want: outbound.ErrOrganizationNotFound},
} {
err := mapOrganizationError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: organizationDetailMarker})
if !errors.Is(err, test.want) {
t.Fatalf("mapOrganizationError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want)
}
if !strings.Contains(err.Error(), test.constraint) || strings.Contains(err.Error(), "Failing row") {
t.Fatalf("mapOrganizationError(%s) = %v, want the constraint name and no detail", test.constraint, err)
}
}
}
func TestMapOrganizationErrorDropsDetailOfOtherErrors(t *testing.T) {
// A CHECK violation that the domain should have prevented keeps only the
// SQLSTATE and the constraint, never the failing row with its names.
err := mapOrganizationError(&pgconn.PgError{Code: checkViolationCode, ConstraintName: "organization_representatives_name_format", Detail: organizationDetailMarker})
var stateError sqlStateError
if !errors.As(err, &stateError) || stateError.SQLState() != checkViolationCode {
t.Fatalf("mapOrganizationError() = %v, want SQLSTATE %s", err, checkViolationCode)
}
if strings.Contains(err.Error(), "Анна") || strings.Contains(err.Error(), "Failing row") {
t.Fatalf("mapOrganizationError() = %v, want no row values", err)
}
if err := mapOrganizationError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(err, outbound.ErrTransactionConflict) {
t.Fatalf("mapOrganizationError(deadlock) = %v, want ErrTransactionConflict", err)
}
if err := mapOrganizationError(context.Canceled); !errors.Is(err, context.Canceled) {
t.Fatalf("mapOrganizationError(context.Canceled) = %v, want the original error", err)
}
}
func TestOrganizationRepositoriesRejectInvalidInputBeforeQuerying(t *testing.T) {
// A repository without queries proves that no statement runs.
organizations := organizationRepository{}
memberships := membershipRepository{}
ctx := t.Context()
if err := organizations.CreateWithOwner(ctx, domain.Organization{}, domain.Membership{}); !errors.Is(err, domain.ErrInvalidOrganization) {
t.Fatalf("CreateWithOwner(zero organization) error = %v, want ErrInvalidOrganization", err)
}
if err := memberships.Insert(ctx, domain.Membership{}); !errors.Is(err, domain.ErrInvalidMembership) {
t.Fatalf("Insert(zero membership) error = %v, want ErrInvalidMembership", err)
}
if _, err := organizations.UpdateProfile(ctx, uuid.New(), domain.Organization{}); !errors.Is(err, domain.ErrInvalidOrganization) {
t.Fatalf("UpdateProfile(zero organization) error = %v, want ErrInvalidOrganization", err)
}
if _, err := organizations.ListForUser(ctx, outbound.OrganizationListQuery{}); !errors.Is(err, domain.ErrInvalidMembership) {
t.Fatalf("ListForUser(zero query) error = %v, want ErrInvalidMembership", err)
}
}
func TestManagerRoleNamesFollowTheDomainRule(t *testing.T) {
if got := managerRoleNames(); len(got) != 1 || got[0] != string(domain.OrganizationRoleOwner) {
t.Fatalf("managerRoleNames() = %v, want only the owner", got)
}
}
@@ -140,6 +140,40 @@ type MailRequest struct {
CreatedAt pgtype.Timestamptz
}
type Membership struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
UserID pgtype.UUID
Role string
State string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type Organization struct {
ID pgtype.UUID
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type OrganizationRepresentative struct {
OrganizationID pgtype.UUID
Ordinal int16
Name string
JobTitle string
}
type OutboxEvent struct {
Position pgtype.Int8
EventID pgtype.UUID
@@ -0,0 +1,505 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: organizations.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const deleteOrganizationRepresentatives = `-- name: DeleteOrganizationRepresentatives :exec
DELETE FROM organization_representatives
WHERE organization_id = $1
`
func (q *Queries) DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteOrganizationRepresentatives, organizationID)
return err
}
const getMembership = `-- name: GetMembership :one
SELECT
id,
organization_id,
user_id,
role,
state,
created_at,
updated_at
FROM memberships
WHERE
organization_id = $1
AND user_id = $2
`
type GetMembershipParams struct {
OrganizationID pgtype.UUID
UserID pgtype.UUID
}
// Reads the membership of one account in one organization, in any state.
func (q *Queries) GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error) {
row := q.db.QueryRow(ctx, getMembership, arg.OrganizationID, arg.UserID)
var i Membership
err := row.Scan(
&i.ID,
&i.OrganizationID,
&i.UserID,
&i.Role,
&i.State,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getOrganizationForMember = `-- name: GetOrganizationForMember :one
SELECT
organization.id,
organization.name,
organization.description,
organization.sphere,
organization.contact_website,
organization.contact_email,
organization.contact_phone,
organization.contact_telegram,
organization.verification_level,
organization.verification_basis,
organization.verification_changed_at,
organization.version,
organization.created_at,
organization.updated_at,
coalesce((
SELECT
jsonb_agg(
jsonb_build_object('name', representative.name, 'job_title', representative.job_title)
ORDER BY representative.ordinal
)
FROM organization_representatives AS representative
WHERE representative.organization_id = organization.id
), '[]'::jsonb)::text AS representatives,
membership.id AS membership_id,
membership.role AS membership_role,
membership.state AS membership_state,
membership.created_at AS membership_created_at,
membership.updated_at AS membership_updated_at
FROM organizations AS organization
INNER JOIN memberships AS membership ON organization.id = membership.organization_id
WHERE
organization.id = $1
AND membership.user_id = $2
AND membership.state = 'active'
`
type GetOrganizationForMemberParams struct {
OrganizationID pgtype.UUID
UserID pgtype.UUID
}
type GetOrganizationForMemberRow struct {
ID pgtype.UUID
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Representatives string
MembershipID pgtype.UUID
MembershipRole string
MembershipState string
MembershipCreatedAt pgtype.Timestamptz
MembershipUpdatedAt pgtype.Timestamptz
}
// Reads an organization together with the membership of one account in it
// and its representatives in list order, as one statement, so the profile and
// the list come from one snapshot. Only an active membership matches, so an
// unknown organization, an account that is no member, and a suspended,
// removed, or left member all return no row and cannot be told apart.
func (q *Queries) GetOrganizationForMember(ctx context.Context, arg GetOrganizationForMemberParams) (GetOrganizationForMemberRow, error) {
row := q.db.QueryRow(ctx, getOrganizationForMember, arg.OrganizationID, arg.UserID)
var i GetOrganizationForMemberRow
err := row.Scan(
&i.ID,
&i.Name,
&i.Description,
&i.Sphere,
&i.ContactWebsite,
&i.ContactEmail,
&i.ContactPhone,
&i.ContactTelegram,
&i.VerificationLevel,
&i.VerificationBasis,
&i.VerificationChangedAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
&i.Representatives,
&i.MembershipID,
&i.MembershipRole,
&i.MembershipState,
&i.MembershipCreatedAt,
&i.MembershipUpdatedAt,
)
return i, err
}
const insertMembership = `-- name: InsertMembership :exec
INSERT INTO memberships (
id,
organization_id,
user_id,
role,
state,
created_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7
)
`
type InsertMembershipParams struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
UserID pgtype.UUID
Role string
State string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
func (q *Queries) InsertMembership(ctx context.Context, arg InsertMembershipParams) error {
_, err := q.db.Exec(ctx, insertMembership,
arg.ID,
arg.OrganizationID,
arg.UserID,
arg.Role,
arg.State,
arg.CreatedAt,
arg.UpdatedAt,
)
return err
}
const insertOrganization = `-- name: InsertOrganization :exec
INSERT INTO organizations (
id,
name,
description,
sphere,
contact_website,
contact_email,
contact_phone,
contact_telegram,
verification_level,
verification_basis,
verification_changed_at,
version,
created_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13,
$14
)
`
type InsertOrganizationParams struct {
ID pgtype.UUID
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Stores a new organization with the verification level that the domain
// gave it. The deferred constraint organizations_owner_required fails the
// transaction at commit unless an active owner membership was inserted in
// it too.
func (q *Queries) InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error {
_, err := q.db.Exec(ctx, insertOrganization,
arg.ID,
arg.Name,
arg.Description,
arg.Sphere,
arg.ContactWebsite,
arg.ContactEmail,
arg.ContactPhone,
arg.ContactTelegram,
arg.VerificationLevel,
arg.VerificationBasis,
arg.VerificationChangedAt,
arg.Version,
arg.CreatedAt,
arg.UpdatedAt,
)
return err
}
const insertOrganizationRepresentative = `-- name: InsertOrganizationRepresentative :exec
INSERT INTO organization_representatives (
organization_id,
ordinal,
name,
job_title
) VALUES (
$1,
$2,
$3,
$4
)
`
type InsertOrganizationRepresentativeParams struct {
OrganizationID pgtype.UUID
Ordinal int16
Name string
JobTitle string
}
// Stores one representative at its position in the list. The adapter calls it
// once per representative after it deleted the previous list, in the same
// transaction.
func (q *Queries) InsertOrganizationRepresentative(ctx context.Context, arg InsertOrganizationRepresentativeParams) error {
_, err := q.db.Exec(ctx, insertOrganizationRepresentative,
arg.OrganizationID,
arg.Ordinal,
arg.Name,
arg.JobTitle,
)
return err
}
const listOrganizationsForUser = `-- name: ListOrganizationsForUser :many
SELECT
organization.id,
organization.name,
organization.verification_level,
membership.id AS membership_id,
membership.role AS membership_role,
membership.state AS membership_state,
membership.created_at AS membership_created_at,
membership.updated_at AS membership_updated_at
FROM memberships AS membership
INNER JOIN organizations AS organization ON membership.organization_id = organization.id
WHERE
membership.user_id = $1
AND membership.state = 'active'
AND (
$2::timestamptz IS NULL
OR (membership.created_at, membership.organization_id) < (
$2::timestamptz,
$3::uuid
)
)
ORDER BY membership.created_at DESC, membership.organization_id DESC
LIMIT $4
`
type ListOrganizationsForUserParams struct {
UserID pgtype.UUID
AfterJoinedAt pgtype.Timestamptz
AfterOrganizationID pgtype.UUID
RowLimit int32
}
type ListOrganizationsForUserRow struct {
ID pgtype.UUID
Name string
VerificationLevel string
MembershipID pgtype.UUID
MembershipRole string
MembershipState string
MembershipCreatedAt pgtype.Timestamptz
MembershipUpdatedAt pgtype.Timestamptz
}
// Lists the organizations where an account has an active membership,
// newest membership first. The page continues after the (membership
// creation time, organization ID) position of the last item of the
// previous page. Only the active memberships of the given account match.
func (q *Queries) ListOrganizationsForUser(ctx context.Context, arg ListOrganizationsForUserParams) ([]ListOrganizationsForUserRow, error) {
rows, err := q.db.Query(ctx, listOrganizationsForUser,
arg.UserID,
arg.AfterJoinedAt,
arg.AfterOrganizationID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListOrganizationsForUserRow
for rows.Next() {
var i ListOrganizationsForUserRow
if err := rows.Scan(
&i.ID,
&i.Name,
&i.VerificationLevel,
&i.MembershipID,
&i.MembershipRole,
&i.MembershipState,
&i.MembershipCreatedAt,
&i.MembershipUpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const updateOrganizationProfile = `-- name: UpdateOrganizationProfile :one
WITH target AS (
SELECT id FROM organizations
WHERE
id = $9
AND version = $10
FOR UPDATE
),
actor AS (
SELECT memberships.id FROM memberships
INNER JOIN target ON memberships.organization_id = target.id
WHERE
memberships.user_id = $11
AND memberships.state = 'active'
AND memberships.role = any($12::text [])
FOR SHARE OF memberships
)
UPDATE organizations
SET
name = $1,
description = $2,
sphere = $3,
contact_website = $4,
contact_email = $5,
contact_phone = $6,
contact_telegram = $7,
updated_at = $8,
version = organizations.version + 1
FROM actor
WHERE
organizations.id = $9
AND organizations.version = $10
RETURNING
organizations.id,
organizations.name,
organizations.description,
organizations.sphere,
organizations.contact_website,
organizations.contact_email,
organizations.contact_phone,
organizations.contact_telegram,
organizations.verification_level,
organizations.verification_basis,
organizations.verification_changed_at,
organizations.version,
organizations.created_at,
organizations.updated_at
`
type UpdateOrganizationProfileParams struct {
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
UpdatedAt pgtype.Timestamptz
ID pgtype.UUID
ExpectedVersion int64
ActorID pgtype.UUID
ManagerRoles []string
}
// Changes the profile of an organization over the version the caller read
// and advances the version in the same statement. It names no verification
// column, so a profile update cannot move the trust level. The change
// applies only for an account whose active membership has one of the
// manager roles, checked in the statement itself so that a membership that
// ended after the caller's read still stops the write. The statement locks
// the organization row first and then the actor's membership row FOR SHARE,
// so a revocation that commits while the statement waits is seen again
// (EvalPlanQual) and stops the write; the order organizations, then
// memberships, is the lock order of every writer (member management must
// follow it). No row returns for a stale version, an account that is no
// active manager, or an unknown organization; the adapter reads the
// membership to tell them apart.
func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error) {
row := q.db.QueryRow(ctx, updateOrganizationProfile,
arg.Name,
arg.Description,
arg.Sphere,
arg.ContactWebsite,
arg.ContactEmail,
arg.ContactPhone,
arg.ContactTelegram,
arg.UpdatedAt,
arg.ID,
arg.ExpectedVersion,
arg.ActorID,
arg.ManagerRoles,
)
var i Organization
err := row.Scan(
&i.ID,
&i.Name,
&i.Description,
&i.Sphere,
&i.ContactWebsite,
&i.ContactEmail,
&i.ContactPhone,
&i.ContactTelegram,
&i.VerificationLevel,
&i.VerificationBasis,
&i.VerificationChangedAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
@@ -49,6 +49,7 @@ type Querier interface {
// matches no row.
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error)
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
// Deletes one batch of accounts that stayed unverified since before cutoff,
// oldest first, with their tokens, sessions, mail requests, mail deliveries
// (and through the deliveries their attempts), and consent records. The
@@ -112,6 +113,14 @@ type Querier interface {
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
// Reads the usage of the day and the month window without locking.
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
// Reads the membership of one account in one organization, in any state.
GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error)
// Reads an organization together with the membership of one account in it
// and its representatives in list order, as one statement, so the profile and
// the list come from one snapshot. Only an active membership matches, so an
// unknown organization, an account that is no member, and a suspended,
// removed, or left member all return no row and cannot be told apart.
GetOrganizationForMember(ctx context.Context, arg GetOrganizationForMemberParams) (GetOrganizationForMemberRow, error)
// Reads the relay backlog for metrics without locking. Both subqueries use
// the partial index on unpublished positions, so the cost follows the backlog
// size, not the table size. The age comes from the database clock, the same
@@ -153,6 +162,16 @@ type Querier interface {
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error
InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error
InsertMembership(ctx context.Context, arg InsertMembershipParams) error
// Stores a new organization with the verification level that the domain
// gave it. The deferred constraint organizations_owner_required fails the
// transaction at commit unless an active owner membership was inserted in
// it too.
InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error
// Stores one representative at its position in the list. The adapter calls it
// once per representative after it deleted the previous list, in the same
// transaction.
InsertOrganizationRepresentative(ctx context.Context, arg InsertOrganizationRepresentativeParams) error
InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error
// Stores a version and returns the stored row with the publication time and
// effective time set by the stamp trigger. A taken ID or version number
@@ -189,6 +208,11 @@ type Querier interface {
ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error)
ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error)
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
// Lists the organizations where an account has an active membership,
// newest membership first. The page continues after the (membership
// creation time, organization ID) position of the last item of the
// previous page. Only the active memberships of the given account match.
ListOrganizationsForUser(ctx context.Context, arg ListOrganizationsForUserParams) ([]ListOrganizationsForUserRow, error)
// Lists the other accounts of a provider that have usage in a month, so
// startup can warn about a renamed EMAIL_ACCOUNT.
ListOtherMailQuotaAccounts(ctx context.Context, arg ListOtherMailQuotaAccountsParams) ([]string, error)
@@ -304,6 +328,20 @@ type Querier interface {
// the stored version still equals expected_version and returns 0 rows
// otherwise. The trigger refuses a provider change after an attempt.
UpdateDeliveryState(ctx context.Context, arg UpdateDeliveryStateParams) (int64, error)
// Changes the profile of an organization over the version the caller read
// and advances the version in the same statement. It names no verification
// column, so a profile update cannot move the trust level. The change
// applies only for an account whose active membership has one of the
// manager roles, checked in the statement itself so that a membership that
// ended after the caller's read still stops the write. The statement locks
// the organization row first and then the actor's membership row FOR SHARE,
// so a revocation that commits while the statement waits is seen again
// (EvalPlanQual) and stops the write; the order organizations, then
// memberships, is the lock order of every writer (member management must
// follow it). No row returns for a stale version, an account that is no
// active manager, or an unknown organization; the adapter reads the
// membership to tell them apart.
UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error)
// Replaces the registration of an unverified account and advances the
// registration version in the same statement, so no caller can choose it.
// The version check rejects a writer that read an older row; a verified