Files
lincodex/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go
T

1382 lines
36 KiB
Go

// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: identity.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const advanceUserRegistration = `-- name: AdvanceUserRegistration :one
WITH updated AS (
UPDATE users
SET
registration_version = registration_version + 1,
last_registered_at = $1,
updated_at = $1,
version = version + 1
WHERE
users.id = $2
AND users.version = $3
AND users.email_verified_at IS NULL
RETURNING
users.id,
users.email,
users.email_normalized,
users.password_hash,
users.scenario,
users.onboarding_step,
users.email_verified_at,
users.registration_version,
users.last_registered_at,
users.version,
users.created_at,
users.updated_at
),
discarded_consent AS (
DELETE FROM consent_records
USING updated
WHERE
consent_records.subject_id = updated.id
AND consent_records.purpose = 'c1'
AND consent_records.source = 'registration'
)
SELECT
updated.id,
updated.email,
updated.email_normalized,
updated.password_hash,
updated.scenario,
updated.onboarding_step,
updated.email_verified_at,
updated.registration_version,
updated.last_registered_at,
updated.version,
updated.created_at,
updated.updated_at
FROM updated
`
type AdvanceUserRegistrationParams struct {
RegisteredAt pgtype.Timestamptz
ID pgtype.UUID
ExpectedVersion int64
}
type AdvanceUserRegistrationRow struct {
ID pgtype.UUID
Email string
EmailNormalized string
PasswordHash string
Scenario string
OnboardingStep string
EmailVerifiedAt pgtype.Timestamptz
RegistrationVersion int64
LastRegisteredAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// 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
// ends every earlier token, and deletes the registration C1 of the earlier
// registrant like UpdateUserRegistration does.
func (q *Queries) AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRegistrationParams) (AdvanceUserRegistrationRow, error) {
row := q.db.QueryRow(ctx, advanceUserRegistration, arg.RegisteredAt, arg.ID, arg.ExpectedVersion)
var i AdvanceUserRegistrationRow
err := row.Scan(
&i.ID,
&i.Email,
&i.EmailNormalized,
&i.PasswordHash,
&i.Scenario,
&i.OnboardingStep,
&i.EmailVerifiedAt,
&i.RegistrationVersion,
&i.LastRegisteredAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const confirmUserEmail = `-- name: ConfirmUserEmail :one
UPDATE users
SET
password_hash = $1,
scenario = $2,
onboarding_step = $3,
email_verified_at = $4,
updated_at = $4,
version = version + 1
WHERE
id = $5
AND registration_version = $6
AND email_verified_at IS NULL
RETURNING
id,
email,
email_normalized,
password_hash,
scenario,
onboarding_step,
email_verified_at,
registration_version,
last_registered_at,
version,
created_at,
updated_at
`
type ConfirmUserEmailParams struct {
PasswordHash string
Scenario string
OnboardingStep string
VerifiedAt pgtype.Timestamptz
ID pgtype.UUID
RegistrationVersion int64
}
// Applies the registration carried by its token and verifies the address in
// one optimistic update. The caller holds the token lock and checks the
// matching C1 in the same transaction.
func (q *Queries) ConfirmUserEmail(ctx context.Context, arg ConfirmUserEmailParams) (User, error) {
row := q.db.QueryRow(ctx, confirmUserEmail,
arg.PasswordHash,
arg.Scenario,
arg.OnboardingStep,
arg.VerifiedAt,
arg.ID,
arg.RegistrationVersion,
)
var i User
err := row.Scan(
&i.ID,
&i.Email,
&i.EmailNormalized,
&i.PasswordHash,
&i.Scenario,
&i.OnboardingStep,
&i.EmailVerifiedAt,
&i.RegistrationVersion,
&i.LastRegisteredAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const consumeEmailToken = `-- name: ConsumeEmailToken :one
WITH candidate AS MATERIALIZED (
SELECT
token.id,
token.user_id,
token.purpose,
token.token_hash,
token.registration_version,
token.created_at,
token.expires_at,
token.pending_password_hash,
token.pending_scenario,
token.pending_onboarding_step
FROM email_tokens AS token
INNER JOIN users AS owner ON owner.id = token.user_id
WHERE
token.token_hash = $1
AND token.purpose = $2
AND token.consumed_at IS NULL
AND token.invalidated_at IS NULL
AND token.expires_at > $3
AND owner.registration_version = token.registration_version
FOR UPDATE OF token
),
consumed AS (
UPDATE email_tokens AS token
SET
consumed_at = $3,
pending_password_hash = NULL,
pending_scenario = NULL,
pending_onboarding_step = NULL,
code_hash = NULL,
code_expires_at = NULL
FROM candidate
WHERE token.id = candidate.id
RETURNING token.id, token.consumed_at, token.invalidated_at
)
SELECT
candidate.id,
candidate.user_id,
candidate.purpose,
candidate.token_hash,
candidate.registration_version,
candidate.created_at,
candidate.expires_at,
consumed.consumed_at,
consumed.invalidated_at,
candidate.pending_password_hash,
candidate.pending_scenario,
candidate.pending_onboarding_step
FROM candidate
INNER JOIN consumed ON consumed.id = candidate.id
`
type ConsumeEmailTokenParams struct {
TokenHash []byte
Purpose string
ConsumedAt pgtype.Timestamptz
}
type ConsumeEmailTokenRow struct {
ID pgtype.UUID
UserID pgtype.UUID
Purpose string
TokenHash []byte
RegistrationVersion int64
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
ConsumedAt pgtype.Timestamptz
InvalidatedAt pgtype.Timestamptz
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
}
// Consumes a token in one statement. Concurrent callers queue on the token
// row lock; under READ COMMITTED each waiter re-checks the WHERE clause
// against the committed row, so exactly one of them updates it. The join
// compares the registration version with the account row as the statement
// reads it, without locking that row, so it rejects a token from an earlier
// registration that already committed but not one that commits afterwards.
// The confirmation guarantee therefore needs MarkUserEmailVerified with the
// returned registration version in the same transaction, rolled back when it
// matches no row.
func (q *Queries) ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error) {
row := q.db.QueryRow(ctx, consumeEmailToken, arg.TokenHash, arg.Purpose, arg.ConsumedAt)
var i ConsumeEmailTokenRow
err := row.Scan(
&i.ID,
&i.UserID,
&i.Purpose,
&i.TokenHash,
&i.RegistrationVersion,
&i.CreatedAt,
&i.ExpiresAt,
&i.ConsumedAt,
&i.InvalidatedAt,
&i.PendingPasswordHash,
&i.PendingScenario,
&i.PendingOnboardingStep,
)
return i, err
}
const deleteUnverifiedUsersRegisteredBefore = `-- name: DeleteUnverifiedUsersRegisteredBefore :execrows
WITH candidate AS (
SELECT stale.id
FROM users AS stale
WHERE
stale.email_verified_at IS NULL
AND stale.last_registered_at < $1
ORDER BY stale.last_registered_at
LIMIT $2
FOR UPDATE SKIP LOCKED
),
locked_token AS (
SELECT token.user_id
FROM email_tokens AS token
WHERE token.user_id IN (SELECT candidate.id FROM candidate)
FOR UPDATE SKIP LOCKED
),
locked_session AS (
SELECT session.user_id
FROM sessions AS session
WHERE session.user_id IN (SELECT candidate.id FROM candidate)
FOR UPDATE SKIP LOCKED
),
locked_mail_request AS (
SELECT request.recipient_user_id
FROM mail_requests AS request
WHERE request.recipient_user_id IN (SELECT candidate.id FROM candidate)
FOR UPDATE SKIP LOCKED
),
locked_delivery AS (
SELECT delivery.recipient_user_id
FROM deliveries AS delivery
WHERE delivery.recipient_user_id IN (SELECT candidate.id FROM candidate)
FOR UPDATE SKIP LOCKED
),
locked_consent AS (
SELECT consent.subject_id
FROM consent_records AS consent
WHERE consent.subject_id IN (SELECT candidate.id FROM candidate)
FOR UPDATE SKIP LOCKED
),
deletable AS (
SELECT candidate.id
FROM candidate
WHERE
(
SELECT count(*) FROM email_tokens AS token
WHERE token.user_id = candidate.id
) = (
SELECT count(*) FROM locked_token
WHERE locked_token.user_id = candidate.id
)
AND (
SELECT count(*) FROM sessions AS session
WHERE session.user_id = candidate.id
) = (
SELECT count(*) FROM locked_session
WHERE locked_session.user_id = candidate.id
)
AND (
SELECT count(*) FROM mail_requests AS request
WHERE request.recipient_user_id = candidate.id
) = (
SELECT count(*) FROM locked_mail_request
WHERE locked_mail_request.recipient_user_id = candidate.id
)
AND (
SELECT count(*) FROM deliveries AS delivery
WHERE delivery.recipient_user_id = candidate.id
) = (
SELECT count(*) FROM locked_delivery
WHERE locked_delivery.recipient_user_id = candidate.id
)
AND (
SELECT count(*) FROM consent_records AS consent
WHERE consent.subject_id = candidate.id
) = (
SELECT count(*) FROM locked_consent
WHERE locked_consent.subject_id = candidate.id
)
),
deleted_consent AS (
DELETE FROM consent_records
USING deletable
WHERE consent_records.subject_id = deletable.id
)
DELETE FROM users
USING deletable
WHERE users.id = deletable.id
`
type DeleteUnverifiedUsersRegisteredBeforeParams struct {
Cutoff pgtype.Timestamptz
BatchLimit int32
}
// 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
// consent records reference the account with ON DELETE RESTRICT, so they are
// deleted explicitly in the same statement: a registration never confirmed
// by its email owner is not kept as consent evidence. Every lock is taken
// with SKIP LOCKED, so the statement never waits: an account whose row is
// locked, for example by a re-registration, a token insert, a delivery
// insert, or a consent insert, is skipped, and so is an account with any
// token, session, mail request, delivery, or consent row locked, for example
// by a confirmation that consumed a token, the delivery consumer, or a
// worker recording an attempt. Skipped accounts stay for the next run.
// Taking the account lock before the token locks is the reverse of the
// documented order, which is safe only because no lock here waits.
// An account qualifies only when every token, session, mail request,
// delivery, and consent row visible to the statement was locked above.
// The restricting foreign key is checked at the end of the statement, after
// these rows are gone.
func (q *Queries) DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) {
result, err := q.db.Exec(ctx, deleteUnverifiedUsersRegisteredBefore, arg.Cutoff, arg.BatchLimit)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const getActiveSessionByTokenHash = `-- name: GetActiveSessionByTokenHash :one
SELECT
id,
user_id,
token_hash,
created_at,
last_seen_at,
expires_at,
revoked_at
FROM sessions
WHERE
token_hash = $1
AND revoked_at IS NULL
AND expires_at > $2
AND last_seen_at > $3
`
type GetActiveSessionByTokenHashParams struct {
TokenHash []byte
At pgtype.Timestamptz
IdleCutoff pgtype.Timestamptz
}
func (q *Queries) GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error) {
row := q.db.QueryRow(ctx, getActiveSessionByTokenHash, arg.TokenHash, arg.At, arg.IdleCutoff)
var i Session
err := row.Scan(
&i.ID,
&i.UserID,
&i.TokenHash,
&i.CreatedAt,
&i.LastSeenAt,
&i.ExpiresAt,
&i.RevokedAt,
)
return i, err
}
const getEmailTokenByHash = `-- name: GetEmailTokenByHash :one
SELECT
id,
user_id,
purpose,
token_hash,
registration_version,
created_at,
expires_at,
consumed_at,
invalidated_at,
code_hash,
code_expires_at,
code_failed_attempts,
pending_password_hash,
pending_scenario,
pending_onboarding_step
FROM email_tokens
WHERE token_hash = $1
AND purpose = $2
`
type GetEmailTokenByHashParams struct {
TokenHash []byte
Purpose string
}
type GetEmailTokenByHashRow struct {
ID pgtype.UUID
UserID pgtype.UUID
Purpose string
TokenHash []byte
RegistrationVersion int64
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
ConsumedAt pgtype.Timestamptz
InvalidatedAt pgtype.Timestamptz
CodeHash []byte
CodeExpiresAt pgtype.Timestamptz
CodeFailedAttempts int16
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
}
// Reads a token before password verification; Consume rechecks it in the
// confirmation transaction and clears pending credentials when it succeeds.
func (q *Queries) GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (GetEmailTokenByHashRow, error) {
row := q.db.QueryRow(ctx, getEmailTokenByHash, arg.TokenHash, arg.Purpose)
var i GetEmailTokenByHashRow
err := row.Scan(
&i.ID,
&i.UserID,
&i.Purpose,
&i.TokenHash,
&i.RegistrationVersion,
&i.CreatedAt,
&i.ExpiresAt,
&i.ConsumedAt,
&i.InvalidatedAt,
&i.CodeHash,
&i.CodeExpiresAt,
&i.CodeFailedAttempts,
&i.PendingPasswordHash,
&i.PendingScenario,
&i.PendingOnboardingStep,
)
return i, err
}
const getEmailTokenState = `-- name: GetEmailTokenState :one
SELECT
token.consumed_at,
token.invalidated_at,
token.expires_at,
owner.registration_version = token.registration_version AS current_registration
FROM email_tokens AS token
INNER JOIN users AS owner ON token.user_id = owner.id
WHERE
token.token_hash = $1
AND token.purpose = $2
`
type GetEmailTokenStateParams struct {
TokenHash []byte
Purpose string
}
type GetEmailTokenStateRow struct {
ConsumedAt pgtype.Timestamptz
InvalidatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
CurrentRegistration bool
}
// Explains why ConsumeEmailToken matched no row.
func (q *Queries) GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error) {
row := q.db.QueryRow(ctx, getEmailTokenState, arg.TokenHash, arg.Purpose)
var i GetEmailTokenStateRow
err := row.Scan(
&i.ConsumedAt,
&i.InvalidatedAt,
&i.ExpiresAt,
&i.CurrentRegistration,
)
return i, err
}
const getLatestPendingRegistration = `-- name: GetLatestPendingRegistration :one
SELECT
pending_password_hash,
pending_scenario,
pending_onboarding_step
FROM email_tokens
WHERE
user_id = $1
AND purpose = $2
AND registration_version = $3
AND pending_password_hash IS NOT NULL
ORDER BY created_at DESC, id DESC
LIMIT 1
`
type GetLatestPendingRegistrationParams struct {
UserID pgtype.UUID
Purpose string
RegistrationVersion int64
}
type GetLatestPendingRegistrationRow struct {
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
}
// The pending credentials of the newest token of a registration, for a
// resend, which issues its token with the same credentials.
func (q *Queries) GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error) {
row := q.db.QueryRow(ctx, getLatestPendingRegistration, arg.UserID, arg.Purpose, arg.RegistrationVersion)
var i GetLatestPendingRegistrationRow
err := row.Scan(&i.PendingPasswordHash, &i.PendingScenario, &i.PendingOnboardingStep)
return i, err
}
const getLiveIdempotencyRecord = `-- name: GetLiveIdempotencyRecord :one
SELECT
scope_hash,
fingerprint,
created_at,
expires_at
FROM idempotency_records
WHERE
scope_hash = $1
AND expires_at > $2
`
type GetLiveIdempotencyRecordParams struct {
ScopeHash []byte
At pgtype.Timestamptz
}
func (q *Queries) GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdempotencyRecordParams) (IdempotencyRecord, error) {
row := q.db.QueryRow(ctx, getLiveIdempotencyRecord, arg.ScopeHash, arg.At)
var i IdempotencyRecord
err := row.Scan(
&i.ScopeHash,
&i.Fingerprint,
&i.CreatedAt,
&i.ExpiresAt,
)
return i, err
}
const getOpenEmailCodeByAddress = `-- name: GetOpenEmailCodeByAddress :one
SELECT
token.id,
token.user_id,
token.purpose,
token.token_hash,
token.registration_version,
token.created_at,
token.expires_at,
token.consumed_at,
token.invalidated_at,
token.code_hash,
token.code_expires_at,
token.code_failed_attempts,
token.pending_password_hash,
token.pending_scenario,
token.pending_onboarding_step
FROM email_tokens AS token
INNER JOIN users AS owner ON owner.id = token.user_id
WHERE
owner.email_normalized = $1
AND owner.email_verified_at IS NULL
AND owner.registration_version = token.registration_version
AND token.purpose = $2
AND token.consumed_at IS NULL
AND token.invalidated_at IS NULL
AND token.code_hash IS NOT NULL
AND token.pending_password_hash IS NOT NULL
ORDER BY token.created_at DESC, token.id DESC
LIMIT 1
`
type GetOpenEmailCodeByAddressParams struct {
EmailNormalized string
Purpose string
}
type GetOpenEmailCodeByAddressRow struct {
ID pgtype.UUID
UserID pgtype.UUID
Purpose string
TokenHash []byte
RegistrationVersion int64
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
ConsumedAt pgtype.Timestamptz
InvalidatedAt pgtype.Timestamptz
CodeHash []byte
CodeExpiresAt pgtype.Timestamptz
CodeFailedAttempts int16
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
}
// Reads the newest open verification token that carries a code for the
// unverified account with this normalized address. The registration version
// must be current, so a code of an earlier registration never matches. The
// row is read before the code is compared; the consumption rechecks it.
func (q *Queries) GetOpenEmailCodeByAddress(ctx context.Context, arg GetOpenEmailCodeByAddressParams) (GetOpenEmailCodeByAddressRow, error) {
row := q.db.QueryRow(ctx, getOpenEmailCodeByAddress, arg.EmailNormalized, arg.Purpose)
var i GetOpenEmailCodeByAddressRow
err := row.Scan(
&i.ID,
&i.UserID,
&i.Purpose,
&i.TokenHash,
&i.RegistrationVersion,
&i.CreatedAt,
&i.ExpiresAt,
&i.ConsumedAt,
&i.InvalidatedAt,
&i.CodeHash,
&i.CodeExpiresAt,
&i.CodeFailedAttempts,
&i.PendingPasswordHash,
&i.PendingScenario,
&i.PendingOnboardingStep,
)
return i, err
}
const getUserByEmailNormalized = `-- name: GetUserByEmailNormalized :one
SELECT
id,
email,
email_normalized,
password_hash,
scenario,
onboarding_step,
email_verified_at,
registration_version,
last_registered_at,
version,
created_at,
updated_at
FROM users
WHERE email_normalized = $1
`
func (q *Queries) GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error) {
row := q.db.QueryRow(ctx, getUserByEmailNormalized, emailNormalized)
var i User
err := row.Scan(
&i.ID,
&i.Email,
&i.EmailNormalized,
&i.PasswordHash,
&i.Scenario,
&i.OnboardingStep,
&i.EmailVerifiedAt,
&i.RegistrationVersion,
&i.LastRegisteredAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getUserByID = `-- name: GetUserByID :one
SELECT
id,
email,
email_normalized,
password_hash,
scenario,
onboarding_step,
email_verified_at,
registration_version,
last_registered_at,
version,
created_at,
updated_at
FROM users
WHERE id = $1
`
func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) {
row := q.db.QueryRow(ctx, getUserByID, id)
var i User
err := row.Scan(
&i.ID,
&i.Email,
&i.EmailNormalized,
&i.PasswordHash,
&i.Scenario,
&i.OnboardingStep,
&i.EmailVerifiedAt,
&i.RegistrationVersion,
&i.LastRegisteredAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertEmailToken = `-- name: InsertEmailToken :exec
INSERT INTO email_tokens (
id,
user_id,
purpose,
token_hash,
registration_version,
created_at,
expires_at,
code_hash,
code_expires_at,
pending_password_hash,
pending_scenario,
pending_onboarding_step
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12
)
`
type InsertEmailTokenParams struct {
ID pgtype.UUID
UserID pgtype.UUID
Purpose string
TokenHash []byte
RegistrationVersion int64
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
CodeHash []byte
CodeExpiresAt pgtype.Timestamptz
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
}
func (q *Queries) InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error {
_, err := q.db.Exec(ctx, insertEmailToken,
arg.ID,
arg.UserID,
arg.Purpose,
arg.TokenHash,
arg.RegistrationVersion,
arg.CreatedAt,
arg.ExpiresAt,
arg.CodeHash,
arg.CodeExpiresAt,
arg.PendingPasswordHash,
arg.PendingScenario,
arg.PendingOnboardingStep,
)
return err
}
const insertSession = `-- name: InsertSession :exec
INSERT INTO sessions (
id,
user_id,
token_hash,
created_at,
last_seen_at,
expires_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6
)
`
type InsertSessionParams struct {
ID pgtype.UUID
UserID pgtype.UUID
TokenHash []byte
CreatedAt pgtype.Timestamptz
LastSeenAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
}
func (q *Queries) InsertSession(ctx context.Context, arg InsertSessionParams) error {
_, err := q.db.Exec(ctx, insertSession,
arg.ID,
arg.UserID,
arg.TokenHash,
arg.CreatedAt,
arg.LastSeenAt,
arg.ExpiresAt,
)
return err
}
const insertUser = `-- name: InsertUser :exec
INSERT INTO users (
id,
email,
email_normalized,
password_hash,
scenario,
onboarding_step,
email_verified_at,
registration_version,
last_registered_at,
version,
created_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12
)
`
type InsertUserParams struct {
ID pgtype.UUID
Email string
EmailNormalized string
PasswordHash string
Scenario string
OnboardingStep string
EmailVerifiedAt pgtype.Timestamptz
RegistrationVersion int64
LastRegisteredAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
func (q *Queries) InsertUser(ctx context.Context, arg InsertUserParams) error {
_, err := q.db.Exec(ctx, insertUser,
arg.ID,
arg.Email,
arg.EmailNormalized,
arg.PasswordHash,
arg.Scenario,
arg.OnboardingStep,
arg.EmailVerifiedAt,
arg.RegistrationVersion,
arg.LastRegisteredAt,
arg.Version,
arg.CreatedAt,
arg.UpdatedAt,
)
return err
}
const invalidateActiveEmailTokens = `-- name: InvalidateActiveEmailTokens :execrows
UPDATE email_tokens
SET
invalidated_at = $1,
-- An invalidated token keeps no password hash or code: it can never be confirmed.
pending_password_hash = NULL,
pending_scenario = NULL,
pending_onboarding_step = NULL,
code_hash = NULL,
code_expires_at = NULL
WHERE
user_id = $2
AND purpose = $3
AND consumed_at IS NULL
AND invalidated_at IS NULL
`
type InvalidateActiveEmailTokensParams struct {
InvalidatedAt pgtype.Timestamptz
UserID pgtype.UUID
Purpose string
}
func (q *Queries) InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error) {
result, err := q.db.Exec(ctx, invalidateActiveEmailTokens, arg.InvalidatedAt, arg.UserID, arg.Purpose)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const markUserEmailVerified = `-- name: MarkUserEmailVerified :one
UPDATE users
SET
email_verified_at = $1,
updated_at = $1,
version = version + 1
WHERE
id = $2
AND registration_version = $3
AND email_verified_at IS NULL
RETURNING
id,
email,
email_normalized,
password_hash,
scenario,
onboarding_step,
email_verified_at,
registration_version,
last_registered_at,
version,
created_at,
updated_at
`
type MarkUserEmailVerifiedParams struct {
VerifiedAt pgtype.Timestamptz
ID pgtype.UUID
RegistrationVersion int64
}
// Verifies the email only for the registration version the consumed token
// was issued for.
func (q *Queries) MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error) {
row := q.db.QueryRow(ctx, markUserEmailVerified, arg.VerifiedAt, arg.ID, arg.RegistrationVersion)
var i User
err := row.Scan(
&i.ID,
&i.Email,
&i.EmailNormalized,
&i.PasswordHash,
&i.Scenario,
&i.OnboardingStep,
&i.EmailVerifiedAt,
&i.RegistrationVersion,
&i.LastRegisteredAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const purgeExpiredIdempotencyRecords = `-- name: PurgeExpiredIdempotencyRecords :execrows
DELETE FROM idempotency_records
WHERE scope_hash IN (
SELECT stale.scope_hash
FROM idempotency_records AS stale
WHERE stale.expires_at <= $1
ORDER BY stale.expires_at
LIMIT $2
FOR UPDATE SKIP LOCKED
)
`
type PurgeExpiredIdempotencyRecordsParams struct {
At pgtype.Timestamptz
BatchLimit int32
}
// Deletes at most batch_limit expired records. Locked rows are skipped, so
// the statement never waits for a concurrent reservation.
func (q *Queries) PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeExpiredIdempotencyRecordsParams) (int64, error) {
result, err := q.db.Exec(ctx, purgeExpiredIdempotencyRecords, arg.At, arg.BatchLimit)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const recordFailedEmailCodeAttempt = `-- name: RecordFailedEmailCodeAttempt :one
UPDATE email_tokens
SET
code_failed_attempts = code_failed_attempts + 1,
invalidated_at = CASE
WHEN code_failed_attempts + 1 >= $1 THEN $2
ELSE invalidated_at
END,
code_hash = CASE
WHEN code_failed_attempts + 1 >= $1 THEN NULL
ELSE code_hash
END,
code_expires_at = CASE
WHEN code_failed_attempts + 1 >= $1 THEN NULL
ELSE code_expires_at
END,
pending_password_hash = CASE
WHEN code_failed_attempts + 1 >= $1 THEN NULL
ELSE pending_password_hash
END,
pending_scenario = CASE
WHEN code_failed_attempts + 1 >= $1 THEN NULL
ELSE pending_scenario
END,
pending_onboarding_step = CASE
WHEN code_failed_attempts + 1 >= $1 THEN NULL
ELSE pending_onboarding_step
END
WHERE
id = $3
AND consumed_at IS NULL
AND invalidated_at IS NULL
AND code_hash IS NOT NULL
AND code_failed_attempts < $1
RETURNING code_failed_attempts >= $1 AS burned
`
type RecordFailedEmailCodeAttemptParams struct {
MaxAttempts int16
AttemptedAt pgtype.Timestamptz
ID pgtype.UUID
}
// Counts one failed code or password attempt against an open code. The
// single UPDATE reads and writes the counter under the row lock, so concurrent
// failures serialize and none is lost. The attempt that reaches the limit
// invalidates the token and drops its code and pending credentials, so the
// code and the link both stop working. A token that is no longer open matches
// no row and is left unchanged.
func (q *Queries) RecordFailedEmailCodeAttempt(ctx context.Context, arg RecordFailedEmailCodeAttemptParams) (bool, error) {
row := q.db.QueryRow(ctx, recordFailedEmailCodeAttempt, arg.MaxAttempts, arg.AttemptedAt, arg.ID)
var burned bool
err := row.Scan(&burned)
return burned, err
}
const reserveIdempotencyRecord = `-- name: ReserveIdempotencyRecord :one
INSERT INTO idempotency_records (
scope_hash,
fingerprint,
created_at,
expires_at
) VALUES (
$1,
$2,
$3,
$4
)
ON CONFLICT (scope_hash) DO UPDATE
SET
fingerprint = excluded.fingerprint,
created_at = excluded.created_at,
expires_at = excluded.expires_at
WHERE idempotency_records.expires_at <= excluded.created_at
RETURNING scope_hash, fingerprint, created_at, expires_at
`
type ReserveIdempotencyRecordParams struct {
ScopeHash []byte
Fingerprint []byte
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
}
// Stores the replay record of a command. A record whose retention has passed
// is replaced, so the key is accepted as new after the retention. A live
// record is left as it is and nothing is returned; the caller then reads it
// with GetLiveIdempotencyRecord. Concurrent callers with the same scope wait
// on the row of the first one until its transaction ends.
func (q *Queries) ReserveIdempotencyRecord(ctx context.Context, arg ReserveIdempotencyRecordParams) (IdempotencyRecord, error) {
row := q.db.QueryRow(ctx, reserveIdempotencyRecord,
arg.ScopeHash,
arg.Fingerprint,
arg.CreatedAt,
arg.ExpiresAt,
)
var i IdempotencyRecord
err := row.Scan(
&i.ScopeHash,
&i.Fingerprint,
&i.CreatedAt,
&i.ExpiresAt,
)
return i, err
}
const revokeSession = `-- name: RevokeSession :execrows
UPDATE sessions
SET revoked_at = $1
WHERE
id = $2
AND revoked_at IS NULL
`
type RevokeSessionParams struct {
RevokedAt pgtype.Timestamptz
ID pgtype.UUID
}
func (q *Queries) RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error) {
result, err := q.db.Exec(ctx, revokeSession, arg.RevokedAt, arg.ID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const revokeUserSessions = `-- name: RevokeUserSessions :execrows
UPDATE sessions
SET revoked_at = $1
WHERE
user_id = $2
AND revoked_at IS NULL
`
type RevokeUserSessionsParams struct {
RevokedAt pgtype.Timestamptz
UserID pgtype.UUID
}
func (q *Queries) RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error) {
result, err := q.db.Exec(ctx, revokeUserSessions, arg.RevokedAt, arg.UserID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const touchSession = `-- name: TouchSession :one
WITH active_session AS (
SELECT candidate.id
FROM sessions AS candidate
WHERE
candidate.id = $1
AND candidate.revoked_at IS NULL
AND candidate.expires_at > $2
AND candidate.last_seen_at > $3
),
touched AS (
UPDATE sessions
SET last_seen_at = $2
WHERE
sessions.id = $1
AND sessions.revoked_at IS NULL
AND sessions.expires_at > $2
AND sessions.last_seen_at > $3
AND sessions.last_seen_at < $4
RETURNING sessions.id
)
SELECT
exists(SELECT 1 FROM active_session) AS active,
exists(SELECT 1 FROM touched) AS touched
`
type TouchSessionParams struct {
ID pgtype.UUID
At pgtype.Timestamptz
IdleCutoff pgtype.Timestamptz
TouchCutoff pgtype.Timestamptz
}
type TouchSessionRow struct {
Active bool
Touched bool
}
// Records activity on an active session and reports whether it is active.
// The row is written only when last_seen_at is older than touch_cutoff, so
// frequent requests do not rewrite it. last_seen_at never moves back, and a
// revoked, expired, or idle session is not revived; the update re-checks
// those conditions against a concurrent change.
func (q *Queries) TouchSession(ctx context.Context, arg TouchSessionParams) (TouchSessionRow, error) {
row := q.db.QueryRow(ctx, touchSession,
arg.ID,
arg.At,
arg.IdleCutoff,
arg.TouchCutoff,
)
var i TouchSessionRow
err := row.Scan(&i.Active, &i.Touched)
return i, err
}
const updateUserRegistration = `-- name: UpdateUserRegistration :one
WITH updated AS (
UPDATE users
SET
email = $1,
password_hash = $2,
scenario = $3,
onboarding_step = $4,
registration_version = registration_version + 1,
last_registered_at = $5,
updated_at = $6,
version = version + 1
WHERE
users.id = $7
AND users.version = $8
AND users.email_verified_at IS NULL
RETURNING
users.id,
users.email,
users.email_normalized,
users.password_hash,
users.scenario,
users.onboarding_step,
users.email_verified_at,
users.registration_version,
users.last_registered_at,
users.version,
users.created_at,
users.updated_at
),
discarded_consent AS (
DELETE FROM consent_records
USING updated
WHERE
consent_records.subject_id = updated.id
AND consent_records.purpose = 'c1'
AND consent_records.source = 'registration'
)
SELECT
updated.id,
updated.email,
updated.email_normalized,
updated.password_hash,
updated.scenario,
updated.onboarding_step,
updated.email_verified_at,
updated.registration_version,
updated.last_registered_at,
updated.version,
updated.created_at,
updated.updated_at
FROM updated
`
type UpdateUserRegistrationParams struct {
Email string
PasswordHash string
Scenario string
OnboardingStep string
LastRegisteredAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
ID pgtype.UUID
ExpectedVersion int64
}
type UpdateUserRegistrationRow struct {
ID pgtype.UUID
Email string
EmailNormalized string
PasswordHash string
Scenario string
OnboardingStep string
EmailVerifiedAt pgtype.Timestamptz
RegistrationVersion int64
LastRegisteredAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// 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
// account never changes. The same statement deletes the C1 that the earlier
// registration of this account recorded, so the consent of an earlier
// registrant never stands for the new one; the new registration records its
// own C1 in the same transaction. A version conflict deletes nothing.
func (q *Queries) UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (UpdateUserRegistrationRow, error) {
row := q.db.QueryRow(ctx, updateUserRegistration,
arg.Email,
arg.PasswordHash,
arg.Scenario,
arg.OnboardingStep,
arg.LastRegisteredAt,
arg.UpdatedAt,
arg.ID,
arg.ExpectedVersion,
)
var i UpdateUserRegistrationRow
err := row.Scan(
&i.ID,
&i.Email,
&i.EmailNormalized,
&i.PasswordHash,
&i.Scenario,
&i.OnboardingStep,
&i.EmailVerifiedAt,
&i.RegistrationVersion,
&i.LastRegisteredAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}