feat: persist candidate questionnaires and enforce company quotas

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 15:47:10 +03:00
1 parent 73c7caa225
commit 3a61a8e8bb
51 files changed
+6280 -38

No files matched your search

@@ -0,0 +1,293 @@
package postgres
import (
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"slices"
"sort"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const assessmentCategoryManifestDomain = "lincodex.assessment.category-manifest.v1\x00"
type assessmentCatalogManifestJSONEntry struct {
FamilyKey string `json:"family_key"`
Version int32 `json:"version"`
ContentSHA256 string `json:"content_sha256"`
}
type assessmentCatalogAggregate struct {
grades map[domain.GradeCode]struct{}
taskLanguages map[domain.TaskLanguageCode]struct{}
}
func (repository assessmentBankRepository) BindCategoryCatalog(
ctx context.Context,
opening domain.AssessmentCategoryOpening,
metadata domain.AssessmentCategoryCatalogMetadata,
) error {
const location = "assessmentBankRepository.BindCategoryCatalog"
if opening.ID == uuid.Nil || metadata.IsZero() {
return fmt.Errorf("%s - opening and reviewed metadata must be set: %w", location, domain.ErrInvalidAssessmentFamily)
}
rows, err := repository.queries.ReadPublishedAssessmentCategoryManifest(ctx, string(opening.Category))
if err != nil {
return fmt.Errorf("%s - read published manifest: %w", location, mapAssessmentError(err))
}
entries := make([]domain.AssessmentCategoryManifestEntry, 0, len(rows))
for _, row := range rows {
key, err := domain.ParseAssessmentFamilyKey(row.FamilyKey)
if err != nil || row.Version < 1 || len(row.ContentSha256) != sha256.Size {
return fmt.Errorf("%s - published manifest row is invalid: %w", location, domain.ErrInvalidAssessmentFamily)
}
entries = append(entries, domain.AssessmentCategoryManifestEntry{
FamilyKey: key, Version: row.Version, ContentSHA256: slices.Clone(row.ContentSha256),
})
}
fingerprint, err := assessmentCategoryManifestFingerprint(entries)
if err != nil {
return fmt.Errorf("%s - fingerprint published manifest: %w", location, err)
}
if len(entries) < int(opening.RequiredFamilies) {
return fmt.Errorf("%s - published manifest no longer meets opening coverage: %w", location, outbound.ErrAssessmentCoverageInsufficient)
}
if err := repository.queries.InsertAssessmentCategoryCatalogBinding(ctx, sqlc.InsertAssessmentCategoryCatalogBindingParams{
OpeningID: pgUUID(opening.ID), Specialization: string(metadata.Specialization()),
Grade: string(metadata.Grade()), TaskLanguages: questionnaireTaskLanguageStrings(metadata.TaskLanguages()),
PublishedManifestSha256: fingerprint[:], ReviewedBy: string(opening.OpenedBy),
}); err != nil {
return fmt.Errorf("%s - insert reviewed binding: %w", location, mapAssessmentCatalogError(err))
}
return nil
}
func (repository assessmentBankRepository) ListCurrentSpecializationAvailability(
ctx context.Context,
) ([]domain.SpecializationAvailability, error) {
const location = "assessmentBankRepository.ListCurrentSpecializationAvailability"
rows, err := repository.queries.ListCurrentSpecializationAvailability(ctx)
if err != nil {
return nil, fmt.Errorf("%s - select current bank projection: %w", location, mapAssessmentError(err))
}
aggregates := make(map[domain.SpecializationCode]*assessmentCatalogAggregate)
for _, row := range rows {
metadata, available, err := currentAssessmentCatalogMetadata(row)
if err != nil {
return nil, fmt.Errorf("%s - validate current binding: %w", location, err)
}
if !available {
continue
}
addAssessmentCatalogMetadata(aggregates, metadata)
}
return buildAssessmentCatalogAvailability(aggregates), nil
}
func currentAssessmentCatalogMetadata(
row sqlc.ListCurrentSpecializationAvailabilityRow,
) (domain.AssessmentCategoryCatalogMetadata, bool, error) {
if !row.EffectivePolicyID.Valid || row.EffectivePolicyID.Bytes != row.PolicyVersionID.Bytes ||
row.PublishedCount < row.RequiredFamilies {
return domain.AssessmentCategoryCatalogMetadata{}, false, nil
}
entries, err := decodeAssessmentCategoryManifest(row.PublishedManifest)
if err != nil {
return domain.AssessmentCategoryCatalogMetadata{}, false, fmt.Errorf("decode published manifest: %w", err)
}
if len(entries) != int(row.PublishedCount) {
return domain.AssessmentCategoryCatalogMetadata{}, false, fmt.Errorf("published manifest count is inconsistent: %w", domain.ErrInvalidAssessmentFamily)
}
fingerprint, err := assessmentCategoryManifestFingerprint(entries)
if err != nil {
return domain.AssessmentCategoryCatalogMetadata{}, false, fmt.Errorf("fingerprint published manifest: %w", err)
}
if !slices.Equal(fingerprint[:], row.PublishedManifestSha256) {
return domain.AssessmentCategoryCatalogMetadata{}, false, nil
}
metadata, err := domain.NewAssessmentCategoryCatalogMetadata(
domain.SpecializationCode(row.Specialization), domain.GradeCode(row.Grade), questionnaireTaskLanguages(row.TaskLanguages),
)
if err != nil {
return domain.AssessmentCategoryCatalogMetadata{}, false, fmt.Errorf("restore reviewed catalog binding: %w", err)
}
return metadata, true, nil
}
func addAssessmentCatalogMetadata(
aggregates map[domain.SpecializationCode]*assessmentCatalogAggregate,
metadata domain.AssessmentCategoryCatalogMetadata,
) {
aggregate := aggregates[metadata.Specialization()]
if aggregate == nil {
aggregate = &assessmentCatalogAggregate{
grades: make(map[domain.GradeCode]struct{}), taskLanguages: make(map[domain.TaskLanguageCode]struct{}),
}
aggregates[metadata.Specialization()] = aggregate
}
aggregate.grades[metadata.Grade()] = struct{}{}
for _, language := range metadata.TaskLanguages() {
aggregate.taskLanguages[language] = struct{}{}
}
}
func buildAssessmentCatalogAvailability(
aggregates map[domain.SpecializationCode]*assessmentCatalogAggregate,
) []domain.SpecializationAvailability {
availability := make([]domain.SpecializationAvailability, 0, len(aggregates))
for specialization, aggregate := range aggregates {
grades := make([]domain.GradeCode, 0, len(aggregate.grades))
for grade := range aggregate.grades {
grades = append(grades, grade)
}
sort.Slice(grades, func(i, j int) bool {
return questionnaireGradeRank(grades[i]) < questionnaireGradeRank(grades[j])
})
languages := make([]domain.TaskLanguageCode, 0, len(aggregate.taskLanguages))
for language := range aggregate.taskLanguages {
languages = append(languages, language)
}
sort.Slice(languages, func(i, j int) bool {
return questionnaireTaskLanguageRank(languages[i]) < questionnaireTaskLanguageRank(languages[j])
})
availability = append(availability, domain.SpecializationAvailability{
Specialization: specialization, Grades: grades, TaskLanguages: languages,
})
}
sort.Slice(availability, func(i, j int) bool {
return availability[i].Specialization < availability[j].Specialization
})
return availability
}
func decodeAssessmentCategoryManifest(encoded string) ([]domain.AssessmentCategoryManifestEntry, error) {
var rows []assessmentCatalogManifestJSONEntry
if err := json.Unmarshal([]byte(encoded), &rows); err != nil {
return nil, fmt.Errorf("postgres.decodeAssessmentCategoryManifest - decode JSON: %w", domain.ErrInvalidAssessmentFamily)
}
entries := make([]domain.AssessmentCategoryManifestEntry, 0, len(rows))
for _, row := range rows {
key, err := domain.ParseAssessmentFamilyKey(row.FamilyKey)
if err != nil || row.Version < 1 {
return nil, fmt.Errorf("postgres.decodeAssessmentCategoryManifest - manifest identity is invalid: %w", domain.ErrInvalidAssessmentFamily)
}
digest, err := hex.DecodeString(row.ContentSHA256)
if err != nil || len(digest) != sha256.Size {
return nil, fmt.Errorf("postgres.decodeAssessmentCategoryManifest - content hash is invalid: %w", domain.ErrInvalidAssessmentFamily)
}
entries = append(entries, domain.AssessmentCategoryManifestEntry{
FamilyKey: key, Version: row.Version, ContentSHA256: digest,
})
}
return entries, nil
}
func assessmentCategoryManifestFingerprint(entries []domain.AssessmentCategoryManifestEntry) ([sha256.Size]byte, error) {
const location = "postgres.assessmentCategoryManifestFingerprint"
if len(entries) == 0 {
return [sha256.Size]byte{}, fmt.Errorf("%s - manifest must contain a published family: %w", location, domain.ErrInvalidAssessmentFamily)
}
ordered := slices.Clone(entries)
sort.Slice(ordered, func(i, j int) bool {
if ordered[i].FamilyKey == ordered[j].FamilyKey {
return ordered[i].Version < ordered[j].Version
}
return ordered[i].FamilyKey < ordered[j].FamilyKey
})
canonical := []byte(assessmentCategoryManifestDomain)
for index, entry := range ordered {
if entry.Version < 1 || len(entry.ContentSHA256) != sha256.Size {
return [sha256.Size]byte{}, fmt.Errorf("%s - entry identity or hash is invalid: %w", location, domain.ErrInvalidAssessmentFamily)
}
if index > 0 && ordered[index-1].FamilyKey == entry.FamilyKey {
return [sha256.Size]byte{}, fmt.Errorf("%s - a family appears more than once: %w", location, domain.ErrInvalidAssessmentFamily)
}
key := []byte(entry.FamilyKey)
keyLength := uint64(len(key))
if len(key) > 64 || keyLength > uint64(^uint32(0)) {
return [sha256.Size]byte{}, fmt.Errorf("%s - family key exceeds its validated bound: %w", location, domain.ErrInvalidAssessmentFamily)
}
canonical = binary.BigEndian.AppendUint32(canonical, uint32(keyLength))
canonical = append(canonical, key...)
canonical = binary.BigEndian.AppendUint32(canonical, uint32(entry.Version))
canonical = append(canonical, entry.ContentSHA256...)
}
return sha256.Sum256(canonical), nil
}
func questionnaireTaskLanguageStrings(languages []domain.TaskLanguageCode) []string {
values := make([]string, len(languages))
for index, language := range languages {
values[index] = string(language)
}
return values
}
func questionnaireTaskLanguages(values []string) []domain.TaskLanguageCode {
languages := make([]domain.TaskLanguageCode, len(values))
for index, language := range values {
languages[index] = domain.TaskLanguageCode(language)
}
return languages
}
func questionnaireGradeRank(grade domain.GradeCode) int {
switch grade {
case domain.GradeIntern:
return 0
case domain.GradeJunior:
return 1
case domain.GradeMiddle:
return 2
case domain.GradeSenior:
return 3
default:
return 4
}
}
func questionnaireTaskLanguageRank(language domain.TaskLanguageCode) int {
switch language {
case domain.TaskLanguagePython:
return 0
case domain.TaskLanguageGo:
return 1
default:
return 2
}
}
func mapAssessmentCatalogError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
switch {
case pgError.Code == checkViolationCode && slices.Contains([]string{
"assessment_category_catalog_bindings_specialization", "assessment_category_catalog_bindings_grade",
"assessment_category_catalog_bindings_languages", "assessment_category_catalog_bindings_reviewer",
"assessment_category_catalog_bindings_manifest_hash", "assessment_category_catalog_bindings_current_opening",
"assessment_category_catalog_bindings_policy_current",
"assessment_category_catalog_bindings_coverage",
}, pgError.ConstraintName):
return fmt.Errorf("postgres.mapAssessmentCatalogError - violate constraint %s: %w", pgError.ConstraintName, domain.ErrInvalidAssessmentFamily)
case pgError.Code == foreignKeyViolationCode && slices.Contains([]string{
"assessment_category_catalog_bindings_opening", "assessment_category_catalog_bindings_opening_fkey",
}, pgError.ConstraintName):
return fmt.Errorf("postgres.mapAssessmentCatalogError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrAssessmentCategoryNotOpen)
case pgError.Code == integrityConstraintViolationCode && pgError.ConstraintName == "assessment_category_catalog_bindings_immutable":
return fmt.Errorf("postgres.mapAssessmentCatalogError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrAssessmentCatalogBindingImmutable)
default:
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
}
@@ -0,0 +1,268 @@
package postgres
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"slices"
"time"
"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"
)
var _ outbound.CandidateQuestionnaireRepository = candidateQuestionnaireRepository{}
func (unit *UnitOfWork) CandidateQuestionnaires() outbound.CandidateQuestionnaireRepository {
return candidateQuestionnaireRepository{queries: unit.queries}
}
type candidateQuestionnaireRepository struct {
queries *sqlc.Queries
}
type storedQuestionnaireSpecialization struct {
Ordinal int16 `json:"ordinal"`
Specialization string `json:"specialization"`
SelfAssessedGrade string `json:"self_assessed_grade"`
TaskLanguages []string `json:"task_languages"`
Stack []string `json:"stack"`
CommercialMonths *int32 `json:"commercial_months"`
AcademicMonths *int32 `json:"academic_months"`
}
func (repository candidateQuestionnaireRepository) Get(ctx context.Context, userID uuid.UUID) (domain.CandidateQuestionnaire, error) {
const location = "candidateQuestionnaireRepository.Get"
if userID == uuid.Nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
row, err := repository.queries.ReadCandidateQuestionnaire(ctx, pgUUID(userID))
if errors.Is(err, pgx.ErrNoRows) {
questionnaire, err := domain.EmptyCandidateQuestionnaire(userID)
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - create empty questionnaire: %w", location, err)
}
return questionnaire, nil
}
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - select questionnaire: %w", location, mapCandidateQuestionnaireError(err))
}
answers, err := decodeStoredQuestionnaireSpecializations(row.Specializations)
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - restore stored answers: %w", location, err)
}
stored := domain.StoredCandidateQuestionnaire{
UserID: row.UserID.Bytes, Version: row.Version, Specializations: answers,
WorkFormats: questionnaireWorkFormats(row.WorkFormats), CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
}
questionnaire, err := domain.RestoreCandidateQuestionnaire(stored)
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - restore questionnaire: %w", location, err)
}
return questionnaire, nil
}
func (repository candidateQuestionnaireRepository) Save(
ctx context.Context,
expectedVersion int64,
questionnaire domain.CandidateQuestionnaire,
) (domain.CandidateQuestionnaire, error) {
const location = "candidateQuestionnaireRepository.Save"
if questionnaire.IsZero() || questionnaire.UserID() == uuid.Nil || questionnaire.Version() != expectedVersion ||
expectedVersion < 0 || questionnaire.UpdatedAt().IsZero() {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - questionnaire or expected version is invalid: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
row, err := repository.advanceQuestionnaireVersion(ctx, expectedVersion, questionnaire)
if errors.Is(err, pgx.ErrNoRows) {
return repository.readQuestionnaireWinner(ctx, questionnaire)
}
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - advance version: %w", location, mapCandidateQuestionnaireError(err))
}
return repository.replaceQuestionnaireAnswers(ctx, questionnaire, row)
}
func (repository candidateQuestionnaireRepository) advanceQuestionnaireVersion(
ctx context.Context,
expectedVersion int64,
questionnaire domain.CandidateQuestionnaire,
) (sqlc.CandidateQuestionnaire, error) {
workFormats := questionnaireWorkFormatStrings(questionnaire.WorkFormats())
if expectedVersion == 0 {
return repository.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{
UserID: pgUUID(questionnaire.UserID()), WorkFormats: workFormats, At: pgTime(questionnaire.UpdatedAt()),
})
}
return repository.queries.AdvanceCandidateQuestionnaireVersion(ctx, sqlc.AdvanceCandidateQuestionnaireVersionParams{
UserID: pgUUID(questionnaire.UserID()), ExpectedVersion: expectedVersion,
WorkFormats: workFormats, At: pgTime(questionnaire.UpdatedAt()),
})
}
func (repository candidateQuestionnaireRepository) readQuestionnaireWinner(
ctx context.Context,
questionnaire domain.CandidateQuestionnaire,
) (domain.CandidateQuestionnaire, error) {
const location = "candidateQuestionnaireRepository.readQuestionnaireWinner"
winner, err := repository.Get(ctx, questionnaire.UserID())
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - read winner after compare-and-swap loss: %w", location, err)
}
if !winner.SameContent(questionnaire) {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - another questionnaire content won the version: %w", location, outbound.ErrCandidateQuestionnaireVersionConflict)
}
return winner, nil
}
func (repository candidateQuestionnaireRepository) replaceQuestionnaireAnswers(
ctx context.Context,
questionnaire domain.CandidateQuestionnaire,
row sqlc.CandidateQuestionnaire,
) (domain.CandidateQuestionnaire, error) {
const location = "candidateQuestionnaireRepository.replaceQuestionnaireAnswers"
if err := repository.queries.DeleteCandidateQuestionnaireSpecializations(ctx, pgUUID(questionnaire.UserID())); err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - delete old specialization answers: %w", location, mapCandidateQuestionnaireError(err))
}
answers := questionnaire.Specializations()
for index, answer := range answers {
ordinal, err := questionnaireSpecializationOrdinal(index)
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - encode answer order: %w", location, err)
}
commercialMonths, academicMonths := questionnaireExperienceMonths(answer.Experience)
if err := repository.queries.InsertCandidateQuestionnaireSpecialization(ctx, sqlc.InsertCandidateQuestionnaireSpecializationParams{
UserID: pgUUID(questionnaire.UserID()), Ordinal: ordinal,
Specialization: string(answer.Specialization), SelfAssessedGrade: string(answer.SelfAssessedGrade),
TaskLanguages: questionnaireTaskLanguageStrings(answer.TaskLanguages), Stack: slices.Clone(answer.Stack),
CommercialMonths: commercialMonths, AcademicMonths: academicMonths,
}); err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - insert specialization answer: %w", location, mapCandidateQuestionnaireError(err))
}
}
stored := domain.StoredCandidateQuestionnaire{
UserID: questionnaire.UserID(), Version: row.Version,
Specializations: answers, WorkFormats: questionnaire.WorkFormats(),
CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
}
result, err := domain.RestoreCandidateQuestionnaire(stored)
if err != nil {
return domain.CandidateQuestionnaire{}, fmt.Errorf("%s - restore saved questionnaire: %w", location, err)
}
return result, nil
}
func (repository candidateQuestionnaireRepository) AdvanceOnboarding(ctx context.Context, userID uuid.UUID, at time.Time) error {
const location = "candidateQuestionnaireRepository.AdvanceOnboarding"
if userID == uuid.Nil || at.IsZero() {
return fmt.Errorf("%s - user ID and time must be set: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
if err := repository.queries.AdvanceCandidateOnboardingAfterQuestionnaire(ctx, sqlc.AdvanceCandidateOnboardingAfterQuestionnaireParams{
UserID: pgUUID(userID), At: pgTime(at),
}); err != nil {
return fmt.Errorf("%s - update onboarding: %w", location, mapCandidateQuestionnaireError(err))
}
return nil
}
func decodeStoredQuestionnaireSpecializations(encoded string) ([]domain.QuestionnaireSpecialization, error) {
const location = "postgres.decodeStoredQuestionnaireSpecializations"
decoder := json.NewDecoder(bytes.NewBufferString(encoded))
decoder.DisallowUnknownFields()
var rows []storedQuestionnaireSpecialization
if err := decoder.Decode(&rows); err != nil {
return nil, fmt.Errorf("%s - stored answers have an unexpected shape: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
if err := decoder.Decode(new(any)); !errors.Is(err, io.EOF) {
return nil, fmt.Errorf("%s - stored answers have trailing data: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
answers := make([]domain.QuestionnaireSpecialization, 0, len(rows))
for index, row := range rows {
if int(row.Ordinal) != index || (row.CommercialMonths == nil) != (row.AcademicMonths == nil) {
return nil, fmt.Errorf("%s - stored answer order or experience is invalid: %w", location, domain.ErrInvalidCandidateQuestionnaire)
}
answer := domain.QuestionnaireSpecialization{
Specialization: domain.SpecializationCode(row.Specialization),
SelfAssessedGrade: domain.GradeCode(row.SelfAssessedGrade),
TaskLanguages: questionnaireTaskLanguages(row.TaskLanguages),
Stack: slices.Clone(row.Stack),
}
if row.CommercialMonths != nil {
answer.Experience = &domain.QuestionnaireExperience{
CommercialMonths: *row.CommercialMonths,
AcademicMonths: *row.AcademicMonths,
}
}
answers = append(answers, answer)
}
return answers, nil
}
func questionnaireExperienceMonths(experience *domain.QuestionnaireExperience) (pgtype.Int4, pgtype.Int4) {
if experience == nil {
return pgtype.Int4{}, pgtype.Int4{}
}
return pgtype.Int4{Int32: experience.CommercialMonths, Valid: true},
pgtype.Int4{Int32: experience.AcademicMonths, Valid: true}
}
func questionnaireSpecializationOrdinal(index int) (int16, error) {
if index < 0 || index >= 2 {
return 0, fmt.Errorf("postgres.questionnaireSpecializationOrdinal - order is outside the storage range: %w", domain.ErrInvalidCandidateQuestionnaire)
}
return int16(index), nil
}
func questionnaireWorkFormats(values []string) []domain.QuestionnaireWorkFormat {
formats := make([]domain.QuestionnaireWorkFormat, len(values))
for index, value := range values {
formats[index] = domain.QuestionnaireWorkFormat(value)
}
return formats
}
func questionnaireWorkFormatStrings(values []domain.QuestionnaireWorkFormat) []string {
formats := make([]string, len(values))
for index, value := range values {
formats[index] = string(value)
}
return formats
}
func mapCandidateQuestionnaireError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
switch {
case pgError.Code == foreignKeyViolationCode && slices.Contains([]string{
"candidate_questionnaires_user_fkey", "candidate_questionnaire_specializations_user_fkey",
}, pgError.ConstraintName):
return fmt.Errorf("postgres.mapCandidateQuestionnaireError - violate constraint %s: %w", pgError.ConstraintName, outbound.ErrUserNotFound)
case pgError.Code == checkViolationCode && slices.Contains([]string{
"candidate_questionnaires_version_positive", "candidate_questionnaires_work_formats", "candidate_questionnaires_times_ordered",
"candidate_questionnaire_specializations_ordinal",
"candidate_questionnaire_specializations_code", "candidate_questionnaire_specializations_grade",
"candidate_questionnaire_specializations_languages", "candidate_questionnaire_specializations_stack",
"candidate_questionnaire_specializations_experience",
}, pgError.ConstraintName):
return fmt.Errorf("postgres.mapCandidateQuestionnaireError - violate constraint %s: %w", pgError.ConstraintName, domain.ErrInvalidCandidateQuestionnaire)
case pgError.Code == uniqueViolationCode && slices.Contains([]string{
"candidate_questionnaires_pkey", "candidate_questionnaire_specializations_unique_code",
}, pgError.ConstraintName):
if pgError.ConstraintName == "candidate_questionnaire_specializations_unique_code" {
return fmt.Errorf("postgres.mapCandidateQuestionnaireError - violate constraint %s: %w", pgError.ConstraintName, domain.ErrInvalidCandidateQuestionnaire)
}
return outbound.ErrCandidateQuestionnaireVersionConflict
default:
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
}
@@ -0,0 +1,302 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const companyQuotaViewCleanupBatchSize int32 = 100
func (unit *UnitOfWork) CompanyQuotas() outbound.CompanyQuotaRepository {
return companyQuotaRepository{queries: unit.queries}
}
type companyQuotaRepository struct {
queries *sqlc.Queries
}
var _ outbound.CompanyQuotaRepository = companyQuotaRepository{}
func (repository companyQuotaRepository) ReserveInvitation(
ctx context.Context,
quota domain.CompanyQuota,
invitationID uuid.UUID,
) (outbound.CompanyQuotaDecision, error) {
const location = "companyQuotaRepository.ReserveInvitation"
if err := validateCompanyQuota(location, quota); err != nil {
return outbound.CompanyQuotaDecision{}, err
}
if invitationID == uuid.Nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
}
if err := repository.lockAndCheckSnapshot(ctx, location, quota); err != nil {
return outbound.CompanyQuotaDecision{}, err
}
organizationID := pgUUID(quota.OrganizationID())
invitation, err := repository.queries.FindCompanyInvitationQuotaUsage(ctx, sqlc.FindCompanyInvitationQuotaUsageParams{
OrganizationID: organizationID,
InvitationID: pgUUID(invitationID),
})
if err == nil {
if !invitation.Valid || invitation.Bytes != invitationID {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - existing invitation usage did not match its key", location)
}
return outbound.CompanyQuotaDecision{Allowed: true, Reused: true}, nil
}
if !errors.Is(err, pgx.ErrNoRows) {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read invitation usage: %w", location, mapOrganizationError(err))
}
usage, err := repository.queries.CountCompanyInvitationQuotaWindow(ctx, sqlc.CountCompanyInvitationQuotaWindowParams{
OrganizationID: organizationID,
WindowStart: pgTime(quota.InvitationWindowStart()),
})
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count invitation usage: %w", location, mapOrganizationError(err))
}
if usage.UsageCount < 0 {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - invitation usage count is negative", location)
}
if usage.UsageCount >= quota.InvitationLimit() {
earliest, err := quotaWindowEarliest(usage.EarliestAt)
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest invitation expiry: %w", location, err)
}
return outbound.CompanyQuotaDecision{RetryAt: earliest.Add(quota.InvitationWindow()).UTC()}, nil
}
if err := repository.queries.InsertCompanyInvitationQuotaUsage(ctx, companyInvitationUsageParams(quota, invitationID)); err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - insert invitation usage: %w", location, mapOrganizationError(err))
}
return outbound.CompanyQuotaDecision{Allowed: true}, nil
}
func (repository companyQuotaRepository) ReserveCardView(
ctx context.Context,
quota domain.CompanyQuota,
candidateID uuid.UUID,
) (outbound.CompanyQuotaDecision, error) {
const location = "companyQuotaRepository.ReserveCardView"
if err := validateCompanyQuota(location, quota); err != nil {
return outbound.CompanyQuotaDecision{}, err
}
if candidateID == uuid.Nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCompanyQuota)
}
if err := repository.lockAndCheckSnapshot(ctx, location, quota); err != nil {
return outbound.CompanyQuotaDecision{}, err
}
organizationID := quota.OrganizationID()
decision, handled, err := repository.reserveExistingCardView(ctx, location, quota, organizationID, candidateID)
if err != nil || handled {
return decision, err
}
return repository.reserveNewCardView(ctx, location, quota, candidateID, organizationID)
}
func (repository companyQuotaRepository) reserveExistingCardView(
ctx context.Context,
location string,
quota domain.CompanyQuota,
organizationID uuid.UUID,
candidateID uuid.UUID,
) (outbound.CompanyQuotaDecision, bool, error) {
existing, findErr := repository.queries.FindCompanyCardViewQuotaUsage(ctx, sqlc.FindCompanyCardViewQuotaUsageParams{
OrganizationID: pgUUID(organizationID),
CandidateID: pgUUID(candidateID),
})
if errors.Is(findErr, pgx.ErrNoRows) {
return outbound.CompanyQuotaDecision{}, false, nil
}
if findErr != nil {
return outbound.CompanyQuotaDecision{}, false, fmt.Errorf("%s - read card-view usage: %w", location, mapOrganizationError(findErr))
}
if !existing.Valid {
return outbound.CompanyQuotaDecision{}, false, fmt.Errorf("%s - existing card-view timestamp is invalid", location)
}
if !existing.Time.After(quota.CardViewWindowStart()) {
return outbound.CompanyQuotaDecision{}, false, nil
}
decision, err := repository.refreshActiveCardView(ctx, location, quota, organizationID, candidateID)
return decision, true, err
}
func (repository companyQuotaRepository) refreshActiveCardView(
ctx context.Context,
location string,
quota domain.CompanyQuota,
organizationID uuid.UUID,
candidateID uuid.UUID,
) (outbound.CompanyQuotaDecision, error) {
updated, err := repository.queries.RefreshCompanyCardViewQuotaUsage(ctx, sqlc.RefreshCompanyCardViewQuotaUsageParams{
LastSeenAt: pgTime(quota.At()),
PolicyVersionID: pgUUID(quota.PolicyVersionID().UUID()),
VerificationLevel: string(quota.VerificationLevel()),
VerificationBasis: string(quota.VerificationBasis()),
VerificationChangedAt: pgTime(quota.VerificationChangedAt()),
QuotaTier: string(quota.Tier()),
OrganizationID: pgUUID(organizationID),
CandidateID: pgUUID(candidateID),
WindowStart: pgTime(quota.CardViewWindowStart()),
})
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - refresh card-view usage: %w", location, mapOrganizationError(err))
}
if updated != 1 {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - active card-view usage changed while organization was locked", location)
}
if err := repository.cleanupExpiredCardViews(ctx, location, quota); err != nil {
return outbound.CompanyQuotaDecision{}, err
}
return outbound.CompanyQuotaDecision{Allowed: true, Reused: true}, nil
}
func (repository companyQuotaRepository) reserveNewCardView(
ctx context.Context,
location string,
quota domain.CompanyQuota,
candidateID uuid.UUID,
organizationID uuid.UUID,
) (outbound.CompanyQuotaDecision, error) {
usage, err := repository.queries.CountCompanyCardViewQuotaWindow(ctx, sqlc.CountCompanyCardViewQuotaWindowParams{
OrganizationID: pgUUID(organizationID),
WindowStart: pgTime(quota.CardViewWindowStart()),
})
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - count card-view usage: %w", location, mapOrganizationError(err))
}
if usage.UsageCount < 0 {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - card-view usage count is negative", location)
}
if usage.UsageCount >= quota.CardViewLimit() {
earliest, err := quotaWindowEarliest(usage.EarliestAt)
if err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - read earliest card-view expiry: %w", location, err)
}
return outbound.CompanyQuotaDecision{RetryAt: earliest.Add(quota.CardViewWindow()).UTC()}, nil
}
if err := repository.queries.SaveCompanyCardViewQuotaUsage(ctx, companyCardViewUsageParams(quota, candidateID)); err != nil {
return outbound.CompanyQuotaDecision{}, fmt.Errorf("%s - save card-view usage: %w", location, mapOrganizationError(err))
}
if err := repository.cleanupExpiredCardViews(ctx, location, quota); err != nil {
return outbound.CompanyQuotaDecision{}, err
}
return outbound.CompanyQuotaDecision{Allowed: true}, nil
}
func (repository companyQuotaRepository) lockAndCheckSnapshot(
ctx context.Context,
location string,
quota domain.CompanyQuota,
) error {
organizationID := pgUUID(quota.OrganizationID())
organization, err := repository.queries.LockCompanyQuotaOrganization(ctx, organizationID)
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - organization was removed after quota resolution: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
}
if err != nil {
return fmt.Errorf("%s - lock organization: %w", location, mapOrganizationError(err))
}
if !organization.ID.Valid || organization.ID.Bytes != quota.OrganizationID() ||
!organization.VerificationChangedAt.Valid ||
organization.VerificationLevel != string(quota.VerificationLevel()) ||
organization.VerificationBasis != string(quota.VerificationBasis()) ||
!organization.VerificationChangedAt.Time.Equal(quota.VerificationChangedAt()) {
return fmt.Errorf("%s - stored organization trust changed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
}
policy, err := repository.queries.GetEffectivePolicyVersion(ctx, sqlc.GetEffectivePolicyVersionParams{
PolicyKey: string(domain.ProductPolicyKey),
At: pgTime(quota.At()),
})
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - no effective product policy remains: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
}
if err != nil {
return fmt.Errorf("%s - recheck effective product policy: %w", location, mapPolicyError(err))
}
if !policy.ID.Valid || policy.ID.Bytes != quota.PolicyVersionID().UUID() || policy.PolicyKey != string(domain.ProductPolicyKey) {
return fmt.Errorf("%s - effective product policy changed: %w", location, outbound.ErrCompanyQuotaSnapshotChanged)
}
return nil
}
func (repository companyQuotaRepository) cleanupExpiredCardViews(
ctx context.Context,
location string,
quota domain.CompanyQuota,
) error {
_, err := repository.queries.DeleteExpiredCompanyCardViewQuotaUsage(ctx, sqlc.DeleteExpiredCompanyCardViewQuotaUsageParams{
OrganizationID: pgUUID(quota.OrganizationID()),
WindowStart: pgTime(quota.CardViewWindowStart()),
RowLimit: companyQuotaViewCleanupBatchSize,
})
if err != nil {
return fmt.Errorf("%s - clean expired card-view usage: %w", location, mapOrganizationError(err))
}
return nil
}
func validateCompanyQuota(location string, quota domain.CompanyQuota) error {
if quota.IsZero() || quota.OrganizationID() == uuid.Nil || quota.PolicyVersionID().UUID() == uuid.Nil ||
quota.At().IsZero() || quota.At().Unix() < 0 ||
quota.InvitationWindow() <= 0 || quota.InvitationLimit() <= 0 ||
quota.CardViewWindow() <= 0 || quota.CardViewLimit() <= 0 ||
quota.InvitationWindowStart().IsZero() || quota.CardViewWindowStart().IsZero() {
return fmt.Errorf("%s - quota snapshot was not built from an active policy and stored organization: %w", location, domain.ErrInvalidCompanyQuota)
}
return nil
}
func quotaWindowEarliest(value interface{}) (time.Time, error) {
switch timestamp := value.(type) {
case time.Time:
if timestamp.IsZero() {
return time.Time{}, errors.New("window timestamp is zero")
}
return timestamp.UTC(), nil
case *time.Time:
if timestamp == nil || timestamp.IsZero() {
return time.Time{}, errors.New("window timestamp is missing")
}
return timestamp.UTC(), nil
default:
return time.Time{}, errors.New("window timestamp has an unexpected database value")
}
}
func companyInvitationUsageParams(quota domain.CompanyQuota, invitationID uuid.UUID) sqlc.InsertCompanyInvitationQuotaUsageParams {
return sqlc.InsertCompanyInvitationQuotaUsageParams{
OrganizationID: pgUUID(quota.OrganizationID()),
InvitationID: pgUUID(invitationID),
ReservedAt: pgTime(quota.At()),
PolicyVersionID: pgUUID(quota.PolicyVersionID().UUID()),
VerificationLevel: string(quota.VerificationLevel()),
VerificationBasis: string(quota.VerificationBasis()),
VerificationChangedAt: pgTime(quota.VerificationChangedAt()),
QuotaTier: string(quota.Tier()),
}
}
func companyCardViewUsageParams(quota domain.CompanyQuota, candidateID uuid.UUID) sqlc.SaveCompanyCardViewQuotaUsageParams {
return sqlc.SaveCompanyCardViewQuotaUsageParams{
OrganizationID: pgUUID(quota.OrganizationID()),
CandidateID: pgUUID(candidateID),
LastSeenAt: pgTime(quota.At()),
PolicyVersionID: pgUUID(quota.PolicyVersionID().UUID()),
VerificationLevel: string(quota.VerificationLevel()),
VerificationBasis: string(quota.VerificationBasis()),
VerificationChangedAt: pgTime(quota.VerificationChangedAt()),
QuotaTier: string(quota.Tier()),
}
}
@@ -0,0 +1,323 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: company_quota.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const countCompanyCardViewQuotaWindow = `-- name: CountCompanyCardViewQuotaWindow :one
SELECT
count(*)::bigint AS usage_count,
min(last_seen_at) AS earliest_at
FROM company_card_view_quota_usage
WHERE
organization_id = $1
AND last_seen_at > $2
`
type CountCompanyCardViewQuotaWindowParams struct {
OrganizationID pgtype.UUID
WindowStart pgtype.Timestamptz
}
type CountCompanyCardViewQuotaWindowRow struct {
UsageCount int64
EarliestAt interface{}
}
func (q *Queries) CountCompanyCardViewQuotaWindow(ctx context.Context, arg CountCompanyCardViewQuotaWindowParams) (CountCompanyCardViewQuotaWindowRow, error) {
row := q.db.QueryRow(ctx, countCompanyCardViewQuotaWindow, arg.OrganizationID, arg.WindowStart)
var i CountCompanyCardViewQuotaWindowRow
err := row.Scan(&i.UsageCount, &i.EarliestAt)
return i, err
}
const countCompanyInvitationQuotaWindow = `-- name: CountCompanyInvitationQuotaWindow :one
SELECT
count(*)::bigint AS usage_count,
min(reserved_at) AS earliest_at
FROM company_invitation_quota_usage
WHERE
organization_id = $1
AND reserved_at > $2
`
type CountCompanyInvitationQuotaWindowParams struct {
OrganizationID pgtype.UUID
WindowStart pgtype.Timestamptz
}
type CountCompanyInvitationQuotaWindowRow struct {
UsageCount int64
EarliestAt interface{}
}
func (q *Queries) CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error) {
row := q.db.QueryRow(ctx, countCompanyInvitationQuotaWindow, arg.OrganizationID, arg.WindowStart)
var i CountCompanyInvitationQuotaWindowRow
err := row.Scan(&i.UsageCount, &i.EarliestAt)
return i, err
}
const deleteExpiredCompanyCardViewQuotaUsage = `-- name: DeleteExpiredCompanyCardViewQuotaUsage :execrows
WITH expired AS (
SELECT quota_usage.organization_id, quota_usage.candidate_id
FROM company_card_view_quota_usage AS quota_usage
WHERE
quota_usage.organization_id = $1
AND quota_usage.last_seen_at <= $2
ORDER BY quota_usage.last_seen_at, quota_usage.candidate_id
LIMIT $3::integer
)
DELETE FROM company_card_view_quota_usage AS usage
USING expired
WHERE
usage.organization_id = expired.organization_id
AND usage.candidate_id = expired.candidate_id
`
type DeleteExpiredCompanyCardViewQuotaUsageParams struct {
OrganizationID pgtype.UUID
WindowStart pgtype.Timestamptz
RowLimit int32
}
func (q *Queries) DeleteExpiredCompanyCardViewQuotaUsage(ctx context.Context, arg DeleteExpiredCompanyCardViewQuotaUsageParams) (int64, error) {
result, err := q.db.Exec(ctx, deleteExpiredCompanyCardViewQuotaUsage, arg.OrganizationID, arg.WindowStart, arg.RowLimit)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const findCompanyCardViewQuotaUsage = `-- name: FindCompanyCardViewQuotaUsage :one
SELECT last_seen_at
FROM company_card_view_quota_usage
WHERE
organization_id = $1
AND candidate_id = $2
FOR UPDATE
`
type FindCompanyCardViewQuotaUsageParams struct {
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
}
func (q *Queries) FindCompanyCardViewQuotaUsage(ctx context.Context, arg FindCompanyCardViewQuotaUsageParams) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, findCompanyCardViewQuotaUsage, arg.OrganizationID, arg.CandidateID)
var last_seen_at pgtype.Timestamptz
err := row.Scan(&last_seen_at)
return last_seen_at, err
}
const findCompanyInvitationQuotaUsage = `-- name: FindCompanyInvitationQuotaUsage :one
SELECT invitation_id
FROM company_invitation_quota_usage
WHERE
organization_id = $1
AND invitation_id = $2
FOR UPDATE
`
type FindCompanyInvitationQuotaUsageParams struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
}
func (q *Queries) FindCompanyInvitationQuotaUsage(ctx context.Context, arg FindCompanyInvitationQuotaUsageParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, findCompanyInvitationQuotaUsage, arg.OrganizationID, arg.InvitationID)
var invitation_id pgtype.UUID
err := row.Scan(&invitation_id)
return invitation_id, err
}
const insertCompanyInvitationQuotaUsage = `-- name: InsertCompanyInvitationQuotaUsage :exec
INSERT INTO company_invitation_quota_usage (
organization_id,
invitation_id,
reserved_at,
policy_version_id,
verification_level,
verification_basis,
verification_changed_at,
quota_tier
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8
)
`
type InsertCompanyInvitationQuotaUsageParams struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
ReservedAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
}
func (q *Queries) InsertCompanyInvitationQuotaUsage(ctx context.Context, arg InsertCompanyInvitationQuotaUsageParams) error {
_, err := q.db.Exec(ctx, insertCompanyInvitationQuotaUsage,
arg.OrganizationID,
arg.InvitationID,
arg.ReservedAt,
arg.PolicyVersionID,
arg.VerificationLevel,
arg.VerificationBasis,
arg.VerificationChangedAt,
arg.QuotaTier,
)
return err
}
const lockCompanyQuotaOrganization = `-- name: LockCompanyQuotaOrganization :one
SELECT
id,
verification_level,
verification_basis,
verification_changed_at
FROM organizations
WHERE id = $1
FOR UPDATE
`
type LockCompanyQuotaOrganizationRow struct {
ID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
}
// Writers lock the organization first, then invitation/card-view state, and
// finally usage rows. The organization lock serializes quota decisions for
// the tenant and makes the subsequent count and insert atomic.
func (q *Queries) LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error) {
row := q.db.QueryRow(ctx, lockCompanyQuotaOrganization, organizationID)
var i LockCompanyQuotaOrganizationRow
err := row.Scan(
&i.ID,
&i.VerificationLevel,
&i.VerificationBasis,
&i.VerificationChangedAt,
)
return i, err
}
const refreshCompanyCardViewQuotaUsage = `-- name: RefreshCompanyCardViewQuotaUsage :execrows
UPDATE company_card_view_quota_usage
SET
last_seen_at = greatest(last_seen_at, $1),
policy_version_id = $2,
verification_level = $3,
verification_basis = $4,
verification_changed_at = $5,
quota_tier = $6
WHERE
organization_id = $7
AND candidate_id = $8
AND last_seen_at > $9
`
type RefreshCompanyCardViewQuotaUsageParams struct {
LastSeenAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
WindowStart pgtype.Timestamptz
}
func (q *Queries) RefreshCompanyCardViewQuotaUsage(ctx context.Context, arg RefreshCompanyCardViewQuotaUsageParams) (int64, error) {
result, err := q.db.Exec(ctx, refreshCompanyCardViewQuotaUsage,
arg.LastSeenAt,
arg.PolicyVersionID,
arg.VerificationLevel,
arg.VerificationBasis,
arg.VerificationChangedAt,
arg.QuotaTier,
arg.OrganizationID,
arg.CandidateID,
arg.WindowStart,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const saveCompanyCardViewQuotaUsage = `-- name: SaveCompanyCardViewQuotaUsage :exec
INSERT INTO company_card_view_quota_usage (
organization_id,
candidate_id,
last_seen_at,
policy_version_id,
verification_level,
verification_basis,
verification_changed_at,
quota_tier
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8
)
ON CONFLICT (organization_id, candidate_id)
DO UPDATE SET
last_seen_at = greatest(
company_card_view_quota_usage.last_seen_at,
EXCLUDED.last_seen_at
),
policy_version_id = EXCLUDED.policy_version_id,
verification_level = EXCLUDED.verification_level,
verification_basis = EXCLUDED.verification_basis,
verification_changed_at = EXCLUDED.verification_changed_at,
quota_tier = EXCLUDED.quota_tier
`
type SaveCompanyCardViewQuotaUsageParams struct {
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
LastSeenAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
}
func (q *Queries) SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error {
_, err := q.db.Exec(ctx, saveCompanyCardViewQuotaUsage,
arg.OrganizationID,
arg.CandidateID,
arg.LastSeenAt,
arg.PolicyVersionID,
arg.VerificationLevel,
arg.VerificationBasis,
arg.VerificationChangedAt,
arg.QuotaTier,
)
return err
}
@@ -16,6 +16,16 @@ type AccountDeletionRequest struct {
CompletedAt pgtype.Timestamptz
}
type AssessmentCategoryCatalogBinding struct {
OpeningID pgtype.UUID
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
ReviewedBy string
ReviewedAt pgtype.Timestamptz
}
type AssessmentCategoryOpening struct {
ID pgtype.UUID
Category string
@@ -124,6 +134,25 @@ type CandidatePublication struct {
UpdatedAt pgtype.Timestamptz
}
type CandidateQuestionnaire struct {
UserID pgtype.UUID
Version int64
WorkFormats []string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type CandidateQuestionnaireSpecialization struct {
UserID pgtype.UUID
Ordinal int16
Specialization string
SelfAssessedGrade string
TaskLanguages []string
Stack []string
CommercialMonths pgtype.Int4
AcademicMonths pgtype.Int4
}
type CandidateSearchStatus struct {
UserID pgtype.UUID
Status string
@@ -135,6 +164,28 @@ type CandidateSearchStatus struct {
UpdatedAt pgtype.Timestamptz
}
type CompanyCardViewQuotaUsage struct {
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
LastSeenAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
}
type CompanyInvitationQuotaUsage struct {
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
ReservedAt pgtype.Timestamptz
PolicyVersionID pgtype.UUID
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
QuotaTier string
}
type ConsentRecord struct {
ID pgtype.UUID
SubjectID pgtype.UUID
@@ -17,6 +17,8 @@ type Querier interface {
// Saving a profile advances onboarding only from that exact step. A retry or
// a save after a later step is already stored never regresses onboarding.
AdvanceCandidateOnboardingAfterProfile(ctx context.Context, arg AdvanceCandidateOnboardingAfterProfileParams) error
// A questionnaire save advances onboarding only from its own step.
AdvanceCandidateOnboardingAfterQuestionnaire(ctx context.Context, arg AdvanceCandidateOnboardingAfterQuestionnaireParams) error
// Advances the version over the one the caller read, in the same statement.
// The row lock it takes serializes concurrent saves of one profile. The update
// time never moves back: an application clock behind the stored time (clock
@@ -25,6 +27,9 @@ type Querier interface {
// returns for a stale version or for an account without a profile, which the
// caller answers as a version conflict.
AdvanceCandidateProfileVersion(ctx context.Context, arg AdvanceCandidateProfileVersionParams) (CandidateProfile, error)
// Advances an existing questionnaire only at the version read by the caller.
// The row lock serializes saves for one user; a stale writer returns no row.
AdvanceCandidateQuestionnaireVersion(ctx context.Context, arg AdvanceCandidateQuestionnaireVersionParams) (CandidateQuestionnaire, error)
// Starts a new registration of an unverified account without touching its
// credentials, scenario, or onboarding step: the new registration carries
// them on its verification token. Advances the registration version, which
@@ -110,6 +115,8 @@ type Querier interface {
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error)
// Counts the hiding records of one candidate for the settings read.
CountCandidateHiddenOrganizations(ctx context.Context, userID pgtype.UUID) (int64, error)
CountCompanyCardViewQuotaWindow(ctx context.Context, arg CountCompanyCardViewQuotaWindowParams) (CountCompanyCardViewQuotaWindowRow, error)
CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error)
// Counts the families of a category that have at least one published
// version, however many versions each has.
CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error)
@@ -127,6 +134,10 @@ type Querier interface {
// Replaces the current explicit decisions with those in the new profile.
// The versioned profile row is advanced first in this same transaction.
DeleteCandidateProfileOverlapConfirmations(ctx context.Context, userID pgtype.UUID) error
// Replaces all specialization answers after the version row advanced in the
// same transaction.
DeleteCandidateQuestionnaireSpecializations(ctx context.Context, userID pgtype.UUID) error
DeleteExpiredCompanyCardViewQuotaUsage(ctx context.Context, arg DeleteExpiredCompanyCardViewQuotaUsageParams) (int64, 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,
@@ -165,6 +176,8 @@ type Querier interface {
// NULL retry_at. due_at keeps the deadline. The same guard as the
// completion applies.
FailScheduledJob(ctx context.Context, arg FailScheduledJobParams) (int64, error)
FindCompanyCardViewQuotaUsage(ctx context.Context, arg FindCompanyCardViewQuotaUsageParams) (pgtype.Timestamptz, error)
FindCompanyInvitationQuotaUsage(ctx context.Context, arg FindCompanyInvitationQuotaUsageParams) (pgtype.UUID, error)
// Returns the newest open reservation of a delivery under a provider account
// made at or after reserved_since. A retry of the delivery inside the
// provider's idempotency window reuses it instead of counting again.
@@ -260,6 +273,10 @@ type Querier interface {
GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error)
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
// Stores an explicit mapping against a newly-created immutable opening. The
// insert trigger checks the opening, declared reviewer, current policy, and
// live coverage; the adapter supplies the fingerprint of the published set.
InsertAssessmentCategoryCatalogBinding(ctx context.Context, arg InsertAssessmentCategoryCatalogBindingParams) error
// Stores an opening. The insert trigger derives required_families from the
// policy document and counts the published families, and the coverage CHECK
// refuses the row when they are fewer; both numbers from the caller are
@@ -301,8 +318,13 @@ type Querier interface {
// one is answered as a version conflict. The foreign key refuses a record
// that is not a C2 record of this account.
InsertCandidatePublication(ctx context.Context, arg InsertCandidatePublicationParams) (InsertCandidatePublicationRow, error)
// Creates the first saved questionnaire. A missing row is version zero;
// concurrent first saves race on the primary key and exactly one returns a row.
InsertCandidateQuestionnaire(ctx context.Context, arg InsertCandidateQuestionnaireParams) (CandidateQuestionnaire, error)
InsertCandidateQuestionnaireSpecialization(ctx context.Context, arg InsertCandidateQuestionnaireSpecializationParams) error
// Stores the first status at version 1; no row returns when one exists.
InsertCandidateSearchStatus(ctx context.Context, arg InsertCandidateSearchStatusParams) (InsertCandidateSearchStatusRow, error)
InsertCompanyInvitationQuotaUsage(ctx context.Context, arg InsertCompanyInvitationQuotaUsageParams) error
// Records a grant of C1, C2, C3, or C5. An unrevoked record of the same
// subject, purpose, and text version already exists when no row returns;
// the insert then changes nothing and does not abort the transaction.
@@ -384,6 +406,10 @@ type Querier interface {
// the last record of the previous page.
ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error)
ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error)
// Produces current catalog availability in one PostgreSQL statement snapshot.
// The adapter compares the ordered live family manifest with the pinned
// fingerprint; stale bindings are omitted fail-closed.
ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, 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
@@ -413,6 +439,10 @@ type Querier interface {
// canceled, or reclaimed after the lease expired. While the lock is held,
// other workers skip the row, so the handler never runs twice at once.
LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error)
// Writers lock the organization first, then invitation/card-view state, and
// finally usage rows. The organization lock serializes quota decisions for
// the tenant and makes the subsequent count and insert atomic.
LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error)
// Takes the candidate's current unrevoked C2 record for a publication and
// keeps it locked until the transaction ends. The share lock conflicts with
// the revocation stamp (an UPDATE of the row), so a revocation either commits
@@ -496,6 +526,9 @@ type Querier interface {
// snapshot. The effective state is computed from them: published only while
// consent_revoked_at is NULL. No row means the candidate never published.
ReadCandidatePublication(ctx context.Context, userID pgtype.UUID) (ReadCandidatePublicationRow, error)
// Reads the aggregate and its ordered specializations in one statement so a
// response never pairs a version with another version's answers.
ReadCandidateQuestionnaire(ctx context.Context, userID pgtype.UUID) (ReadCandidateQuestionnaireRow, error)
// No row means the status was never set, which reads as not looking. The
// lapse is computed by the caller from lapses_at and its clock and is never
// written.
@@ -507,6 +540,10 @@ type Querier interface {
// unpublished one. Every organization-facing read of a publication starts
// from this shape.
ReadPublicationVisibleToOrganization(ctx context.Context, arg ReadPublicationVisibleToOrganizationParams) (ReadPublicationVisibleToOrganizationRow, error)
// Lists the exact published bank manifest while the category advisory lock is
// held by OpenCategory. Published families have passed the independent-review
// constraint before this read.
ReadPublishedAssessmentCategoryManifest(ctx context.Context, category string) ([]ReadPublishedAssessmentCategoryManifestRow, error)
// Advances a delivery past one attempt and appends the attempt in one
// statement, so both happen or neither does, inside or outside a
// transaction. The update applies only while the stored version still
@@ -534,6 +571,7 @@ type Querier interface {
RecordDeliveryFailure(ctx context.Context, arg RecordDeliveryFailureParams) (string, error)
// Records the latest settled outcome of a send under the reservation.
RecordMailQuotaOutcome(ctx context.Context, arg RecordMailQuotaOutcomeParams) (int64, error)
RefreshCompanyCardViewQuotaUsage(ctx context.Context, arg RefreshCompanyCardViewQuotaUsageParams) (int64, error)
// Gives a claimed delivery back without changing it, so the next pass may
// claim it. It matches only the lease of lease_owner: a delivery that another
// worker took over after the lease expired is left alone.
@@ -568,6 +606,7 @@ type Querier interface {
RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error)
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error
// Stores the immutable domain snapshot of a successful create command. The
// generic idempotency row and this result are committed with the organization
// and owner membership. A reused expired scope replaces the snapshot in the
@@ -0,0 +1,403 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: questionnaire.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const advanceCandidateOnboardingAfterQuestionnaire = `-- name: AdvanceCandidateOnboardingAfterQuestionnaire :exec
UPDATE users
SET
onboarding_step = 'candidate_assessment',
version = users.version + 1,
updated_at = GREATEST(users.updated_at, $1::timestamptz)
WHERE
users.id = $2
AND users.scenario = 'candidate'
AND users.email_verified_at IS NOT NULL
AND users.onboarding_step = 'candidate_questionnaire'
`
type AdvanceCandidateOnboardingAfterQuestionnaireParams struct {
At pgtype.Timestamptz
UserID pgtype.UUID
}
// A questionnaire save advances onboarding only from its own step.
func (q *Queries) AdvanceCandidateOnboardingAfterQuestionnaire(ctx context.Context, arg AdvanceCandidateOnboardingAfterQuestionnaireParams) error {
_, err := q.db.Exec(ctx, advanceCandidateOnboardingAfterQuestionnaire, arg.At, arg.UserID)
return err
}
const advanceCandidateQuestionnaireVersion = `-- name: AdvanceCandidateQuestionnaireVersion :one
UPDATE candidate_questionnaires
SET
version = candidate_questionnaires.version + 1,
work_formats = $1,
updated_at = GREATEST(candidate_questionnaires.updated_at, $2::timestamptz)
WHERE
candidate_questionnaires.user_id = $3
AND candidate_questionnaires.version = $4
RETURNING user_id, version, work_formats, created_at, updated_at
`
type AdvanceCandidateQuestionnaireVersionParams struct {
WorkFormats []string
At pgtype.Timestamptz
UserID pgtype.UUID
ExpectedVersion int64
}
// Advances an existing questionnaire only at the version read by the caller.
// The row lock serializes saves for one user; a stale writer returns no row.
func (q *Queries) AdvanceCandidateQuestionnaireVersion(ctx context.Context, arg AdvanceCandidateQuestionnaireVersionParams) (CandidateQuestionnaire, error) {
row := q.db.QueryRow(ctx, advanceCandidateQuestionnaireVersion,
arg.WorkFormats,
arg.At,
arg.UserID,
arg.ExpectedVersion,
)
var i CandidateQuestionnaire
err := row.Scan(
&i.UserID,
&i.Version,
&i.WorkFormats,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const deleteCandidateQuestionnaireSpecializations = `-- name: DeleteCandidateQuestionnaireSpecializations :exec
DELETE FROM candidate_questionnaire_specializations
WHERE user_id = $1
`
// Replaces all specialization answers after the version row advanced in the
// same transaction.
func (q *Queries) DeleteCandidateQuestionnaireSpecializations(ctx context.Context, userID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteCandidateQuestionnaireSpecializations, userID)
return err
}
const insertAssessmentCategoryCatalogBinding = `-- name: InsertAssessmentCategoryCatalogBinding :exec
INSERT INTO assessment_category_catalog_bindings (
opening_id,
specialization,
grade,
task_languages,
published_manifest_sha256,
reviewed_by,
reviewed_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
clock_timestamp()
)
`
type InsertAssessmentCategoryCatalogBindingParams struct {
OpeningID pgtype.UUID
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
ReviewedBy string
}
// Stores an explicit mapping against a newly-created immutable opening. The
// insert trigger checks the opening, declared reviewer, current policy, and
// live coverage; the adapter supplies the fingerprint of the published set.
func (q *Queries) InsertAssessmentCategoryCatalogBinding(ctx context.Context, arg InsertAssessmentCategoryCatalogBindingParams) error {
_, err := q.db.Exec(ctx, insertAssessmentCategoryCatalogBinding,
arg.OpeningID,
arg.Specialization,
arg.Grade,
arg.TaskLanguages,
arg.PublishedManifestSha256,
arg.ReviewedBy,
)
return err
}
const insertCandidateQuestionnaire = `-- name: InsertCandidateQuestionnaire :one
INSERT INTO candidate_questionnaires (
user_id,
version,
work_formats,
created_at,
updated_at
) VALUES (
$1,
1,
$2,
$3::timestamptz,
$3::timestamptz
)
ON CONFLICT (user_id) DO NOTHING
RETURNING user_id, version, work_formats, created_at, updated_at
`
type InsertCandidateQuestionnaireParams struct {
UserID pgtype.UUID
WorkFormats []string
At pgtype.Timestamptz
}
// Creates the first saved questionnaire. A missing row is version zero;
// concurrent first saves race on the primary key and exactly one returns a row.
func (q *Queries) InsertCandidateQuestionnaire(ctx context.Context, arg InsertCandidateQuestionnaireParams) (CandidateQuestionnaire, error) {
row := q.db.QueryRow(ctx, insertCandidateQuestionnaire, arg.UserID, arg.WorkFormats, arg.At)
var i CandidateQuestionnaire
err := row.Scan(
&i.UserID,
&i.Version,
&i.WorkFormats,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertCandidateQuestionnaireSpecialization = `-- name: InsertCandidateQuestionnaireSpecialization :exec
INSERT INTO candidate_questionnaire_specializations (
user_id,
ordinal,
specialization,
self_assessed_grade,
task_languages,
stack,
commercial_months,
academic_months
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8
)
`
type InsertCandidateQuestionnaireSpecializationParams struct {
UserID pgtype.UUID
Ordinal int16
Specialization string
SelfAssessedGrade string
TaskLanguages []string
Stack []string
CommercialMonths pgtype.Int4
AcademicMonths pgtype.Int4
}
func (q *Queries) InsertCandidateQuestionnaireSpecialization(ctx context.Context, arg InsertCandidateQuestionnaireSpecializationParams) error {
_, err := q.db.Exec(ctx, insertCandidateQuestionnaireSpecialization,
arg.UserID,
arg.Ordinal,
arg.Specialization,
arg.SelfAssessedGrade,
arg.TaskLanguages,
arg.Stack,
arg.CommercialMonths,
arg.AcademicMonths,
)
return err
}
const listCurrentSpecializationAvailability = `-- name: ListCurrentSpecializationAvailability :many
WITH current_policy AS (
SELECT id
FROM policy_versions
WHERE policy_key = 'product' AND effective_at <= statement_timestamp()
ORDER BY version DESC
LIMIT 1
), current_openings AS (
SELECT DISTINCT ON (category)
id,
category,
policy_version_id,
required_families,
opened_at
FROM assessment_category_openings
ORDER BY category, opened_at DESC, id DESC
)
SELECT
opening.id AS opening_id,
opening.category,
opening.policy_version_id,
opening.required_families,
COALESCE((
SELECT count(DISTINCT family.family_key)::integer
FROM assessment_families AS family
WHERE family.category = opening.category AND family.lifecycle = 'published'
), 0)::integer AS published_count,
policy.id AS effective_policy_id,
binding.specialization,
binding.grade,
binding.task_languages,
binding.published_manifest_sha256,
COALESCE((
SELECT jsonb_agg(
jsonb_build_object(
'family_key', family.family_key,
'version', family.version,
'content_sha256', encode(family.content_sha256, 'hex')
) ORDER BY family.family_key, family.version
)
FROM assessment_families AS family
WHERE family.category = opening.category AND family.lifecycle = 'published'
), '[]'::jsonb)::text AS published_manifest
FROM current_openings AS opening
JOIN assessment_category_catalog_bindings AS binding
ON binding.opening_id = opening.id
LEFT JOIN current_policy AS policy ON true
ORDER BY opening.category
`
type ListCurrentSpecializationAvailabilityRow struct {
OpeningID pgtype.UUID
Category string
PolicyVersionID pgtype.UUID
RequiredFamilies int32
PublishedCount int32
EffectivePolicyID pgtype.UUID
Specialization string
Grade string
TaskLanguages []string
PublishedManifestSha256 []byte
PublishedManifest string
}
// Produces current catalog availability in one PostgreSQL statement snapshot.
// The adapter compares the ordered live family manifest with the pinned
// fingerprint; stale bindings are omitted fail-closed.
func (q *Queries) ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error) {
rows, err := q.db.Query(ctx, listCurrentSpecializationAvailability)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCurrentSpecializationAvailabilityRow
for rows.Next() {
var i ListCurrentSpecializationAvailabilityRow
if err := rows.Scan(
&i.OpeningID,
&i.Category,
&i.PolicyVersionID,
&i.RequiredFamilies,
&i.PublishedCount,
&i.EffectivePolicyID,
&i.Specialization,
&i.Grade,
&i.TaskLanguages,
&i.PublishedManifestSha256,
&i.PublishedManifest,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const readCandidateQuestionnaire = `-- name: ReadCandidateQuestionnaire :one
SELECT
questionnaire.user_id,
questionnaire.version,
questionnaire.work_formats,
questionnaire.created_at,
questionnaire.updated_at,
COALESCE((
SELECT jsonb_agg(
jsonb_build_object(
'ordinal', specialization.ordinal,
'specialization', specialization.specialization,
'self_assessed_grade', specialization.self_assessed_grade,
'task_languages', specialization.task_languages,
'stack', specialization.stack,
'commercial_months', specialization.commercial_months,
'academic_months', specialization.academic_months
) ORDER BY specialization.ordinal
)
FROM candidate_questionnaire_specializations AS specialization
WHERE specialization.user_id = questionnaire.user_id
), '[]'::jsonb)::text AS specializations
FROM candidate_questionnaires AS questionnaire
WHERE questionnaire.user_id = $1
`
type ReadCandidateQuestionnaireRow struct {
UserID pgtype.UUID
Version int64
WorkFormats []string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Specializations string
}
// Reads the aggregate and its ordered specializations in one statement so a
// response never pairs a version with another version's answers.
func (q *Queries) ReadCandidateQuestionnaire(ctx context.Context, userID pgtype.UUID) (ReadCandidateQuestionnaireRow, error) {
row := q.db.QueryRow(ctx, readCandidateQuestionnaire, userID)
var i ReadCandidateQuestionnaireRow
err := row.Scan(
&i.UserID,
&i.Version,
&i.WorkFormats,
&i.CreatedAt,
&i.UpdatedAt,
&i.Specializations,
)
return i, err
}
const readPublishedAssessmentCategoryManifest = `-- name: ReadPublishedAssessmentCategoryManifest :many
SELECT family_key, version, content_sha256
FROM assessment_families
WHERE category = $1 AND lifecycle = 'published'
ORDER BY family_key, version
`
type ReadPublishedAssessmentCategoryManifestRow struct {
FamilyKey string
Version int32
ContentSha256 []byte
}
// Lists the exact published bank manifest while the category advisory lock is
// held by OpenCategory. Published families have passed the independent-review
// constraint before this read.
func (q *Queries) ReadPublishedAssessmentCategoryManifest(ctx context.Context, category string) ([]ReadPublishedAssessmentCategoryManifestRow, error) {
rows, err := q.db.Query(ctx, readPublishedAssessmentCategoryManifest, category)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ReadPublishedAssessmentCategoryManifestRow
for rows.Next() {
var i ReadPublishedAssessmentCategoryManifestRow
if err := rows.Scan(&i.FamilyKey, &i.Version, &i.ContentSha256); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}