Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

54.5 KB
Raw Blame
// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.31.1
// source: query.sql

package db

import (
	"context"
	"database/sql"
	"strings"
	"time"
)

const addAccessTokenForUser = `-- name: AddAccessTokenForUser :exec
INSERT INTO user_access_tokens(token, user_id) values(?, ?)
`

type AddAccessTokenForUserParams struct {
	Token  string
	UserID string
}

func (q *Queries) AddAccessTokenForUser(ctx context.Context, arg AddAccessTokenForUserParams) error {
	_, err := q.db.ExecContext(ctx, addAccessTokenForUser, arg.Token, arg.UserID)
	return err
}

const addAuthForUser = `-- name: AddAuthForUser :exec
INSERT INTO auth(user_id, auth_key, type, provider, profile_url, handle, is_public) values(?, ?, ?, ?, ?, ?, ?)
`

type AddAuthForUserParams struct {
	UserID     string
	AuthKey    string
	Type       string
	Provider   string
	ProfileUrl sql.NullString
	Handle     sql.NullString
	IsPublic   bool
}

func (q *Queries) AddAuthForUser(ctx context.Context, arg AddAuthForUserParams) error {
	_, err := q.db.ExecContext(ctx, addAuthForUser,
		arg.UserID,
		arg.AuthKey,
		arg.Type,
		arg.Provider,
		arg.ProfileUrl,
		arg.Handle,
		arg.IsPublic,
	)
	return err
}

const addFederatedServer = `-- name: AddFederatedServer :exec
INSERT INTO federated_servers(iri, name, logo_url, followed_at, pending, username, follow_status) values(?, ?, ?, ?, ?, ?, ?)
`

type AddFederatedServerParams struct {
	Iri          string
	Name         sql.NullString
	LogoUrl      sql.NullString
	FollowedAt   sql.NullTime
	Pending      sql.NullBool
	Username     sql.NullString
	FollowStatus sql.NullString
}

func (q *Queries) AddFederatedServer(ctx context.Context, arg AddFederatedServerParams) error {
	_, err := q.db.ExecContext(ctx, addFederatedServer,
		arg.Iri,
		arg.Name,
		arg.LogoUrl,
		arg.FollowedAt,
		arg.Pending,
		arg.Username,
		arg.FollowStatus,
	)
	return err
}

const addFollower = `-- name: AddFollower :exec
INSERT INTO ap_followers(iri, inbox, shared_inbox, request, request_object, name, username, image, approved_at, directory) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`

type AddFollowerParams struct {
	Iri           string
	Inbox         string
	SharedInbox   sql.NullString
	Request       string
	RequestObject []byte
	Name          sql.NullString
	Username      string
	Image         sql.NullString
	ApprovedAt    sql.NullTime
	Directory     sql.NullBool
}

func (q *Queries) AddFollower(ctx context.Context, arg AddFollowerParams) error {
	_, err := q.db.ExecContext(ctx, addFollower,
		arg.Iri,
		arg.Inbox,
		arg.SharedInbox,
		arg.Request,
		arg.RequestObject,
		arg.Name,
		arg.Username,
		arg.Image,
		arg.ApprovedAt,
		arg.Directory,
	)
	return err
}

const addNotification = `-- name: AddNotification :exec
INSERT INTO notifications (channel, destination) VALUES(?, ?)
`

type AddNotificationParams struct {
	Channel     string
	Destination string
}

func (q *Queries) AddNotification(ctx context.Context, arg AddNotificationParams) error {
	_, err := q.db.ExecContext(ctx, addNotification, arg.Channel, arg.Destination)
	return err
}

const addToAcceptedActivities = `-- name: AddToAcceptedActivities :exec
INSERT INTO ap_accepted_activities(iri, actor, type, timestamp) values(?, ?, ?, ?)
`

type AddToAcceptedActivitiesParams struct {
	Iri       string
	Actor     string
	Type      string
	Timestamp time.Time
}

func (q *Queries) AddToAcceptedActivities(ctx context.Context, arg AddToAcceptedActivitiesParams) error {
	_, err := q.db.ExecContext(ctx, addToAcceptedActivities,
		arg.Iri,
		arg.Actor,
		arg.Type,
		arg.Timestamp,
	)
	return err
}

const addToOutbox = `-- name: AddToOutbox :exec
INSERT INTO ap_outbox(iri, value, type, live_notification) values(?, ?, ?, ?)
`

type AddToOutboxParams struct {
	Iri              string
	Value            []byte
	Type             string
	LiveNotification sql.NullBool
}

func (q *Queries) AddToOutbox(ctx context.Context, arg AddToOutboxParams) error {
	_, err := q.db.ExecContext(ctx, addToOutbox,
		arg.Iri,
		arg.Value,
		arg.Type,
		arg.LiveNotification,
	)
	return err
}

const approveFederationFollower = `-- name: ApproveFederationFollower :exec
UPDATE ap_followers SET approved_at = ?, disabled_at = null WHERE iri = ?
`

type ApproveFederationFollowerParams struct {
	ApprovedAt sql.NullTime
	Iri        string
}

func (q *Queries) ApproveFederationFollower(ctx context.Context, arg ApproveFederationFollowerParams) error {
	_, err := q.db.ExecContext(ctx, approveFederationFollower, arg.ApprovedAt, arg.Iri)
	return err
}

const banIPAddress = `-- name: BanIPAddress :exec
INSERT INTO ip_bans(ip_address, notes) values(?, ?)
`

type BanIPAddressParams struct {
	IpAddress string
	Notes     sql.NullString
}

func (q *Queries) BanIPAddress(ctx context.Context, arg BanIPAddressParams) error {
	_, err := q.db.ExecContext(ctx, banIPAddress, arg.IpAddress, arg.Notes)
	return err
}

const changeDisplayColor = `-- name: ChangeDisplayColor :exec
UPDATE users SET display_color = ? WHERE id = ?
`

type ChangeDisplayColorParams struct {
	DisplayColor int64
	ID           string
}

func (q *Queries) ChangeDisplayColor(ctx context.Context, arg ChangeDisplayColorParams) error {
	_, err := q.db.ExecContext(ctx, changeDisplayColor, arg.DisplayColor, arg.ID)
	return err
}

const changeDisplayName = `-- name: ChangeDisplayName :exec
UPDATE users SET display_name = ?, previous_names = previous_names || ?, namechanged_at = ? WHERE id = ?
`

type ChangeDisplayNameParams struct {
	DisplayName   string
	PreviousNames sql.NullString
	NamechangedAt sql.NullTime
	ID            string
}

func (q *Queries) ChangeDisplayName(ctx context.Context, arg ChangeDisplayNameParams) error {
	_, err := q.db.ExecContext(ctx, changeDisplayName,
		arg.DisplayName,
		arg.PreviousNames,
		arg.NamechangedAt,
		arg.ID,
	)
	return err
}

const claimActivityPubDelivery = `-- name: ClaimActivityPubDelivery :one
UPDATE ap_delivery_queue
SET claimed_until = ?1,
    attempts = attempts + 1
WHERE id = (
    SELECT candidate.id
    FROM ap_delivery_queue AS candidate
    WHERE candidate.failed_at IS NULL
      AND candidate.next_attempt_at <= ?2
      AND (candidate.claimed_until IS NULL OR candidate.claimed_until <= ?2)
    ORDER BY candidate.next_attempt_at, candidate.id
    LIMIT 1
)
RETURNING id, inbox, payload, actor_iri, activity_type, coalesce_key, attempts, revision
`

type ClaimActivityPubDeliveryParams struct {
	ClaimedUntil sql.NullTime
	Now          time.Time
}

type ClaimActivityPubDeliveryRow struct {
	ID           int64
	Inbox        string
	Payload      []byte
	ActorIri     string
	ActivityType string
	CoalesceKey  sql.NullString
	Attempts     int64
	Revision     int64
}

func (q *Queries) ClaimActivityPubDelivery(ctx context.Context, arg ClaimActivityPubDeliveryParams) (ClaimActivityPubDeliveryRow, error) {
	row := q.db.QueryRowContext(ctx, claimActivityPubDelivery, arg.ClaimedUntil, arg.Now)
	var i ClaimActivityPubDeliveryRow
	err := row.Scan(
		&i.ID,
		&i.Inbox,
		&i.Payload,
		&i.ActorIri,
		&i.ActivityType,
		&i.CoalesceKey,
		&i.Attempts,
		&i.Revision,
	)
	return i, err
}

const completeActivityPubDelivery = `-- name: CompleteActivityPubDelivery :execrows
DELETE FROM ap_delivery_queue WHERE id = ? AND revision = ?
`

type CompleteActivityPubDeliveryParams struct {
	ID       int64
	Revision int64
}

func (q *Queries) CompleteActivityPubDelivery(ctx context.Context, arg CompleteActivityPubDeliveryParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, completeActivityPubDelivery, arg.ID, arg.Revision)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const countUserAuthByProvider = `-- name: CountUserAuthByProvider :one
SELECT count(*) FROM auth WHERE user_id = ? AND type = ? AND provider = ?
`

type CountUserAuthByProviderParams struct {
	UserID   string
	Type     string
	Provider string
}

func (q *Queries) CountUserAuthByProvider(ctx context.Context, arg CountUserAuthByProviderParams) (int64, error) {
	row := q.db.QueryRowContext(ctx, countUserAuthByProvider, arg.UserID, arg.Type, arg.Provider)
	var count int64
	err := row.Scan(&count)
	return count, err
}

const countUsers = `-- name: CountUsers :one
SELECT count(*) FROM users
WHERE display_name LIKE '%' || ?1 || '%'
  AND (
    ?2 = '' OR ?2 = 'all'
    OR (?2 = 'active' AND disabled_at IS NULL)
    OR (?2 = 'bots' AND type = 'API')
  )
`

type CountUsersParams struct {
	Search sql.NullString
	Status interface{}
}

// Total number of users matching the same @search/@status filter as GetUsersPaginated.
func (q *Queries) CountUsers(ctx context.Context, arg CountUsersParams) (int64, error) {
	row := q.db.QueryRowContext(ctx, countUsers, arg.Search, arg.Status)
	var count int64
	err := row.Scan(&count)
	return count, err
}

const deferActivityPubDelivery = `-- name: DeferActivityPubDelivery :execrows
UPDATE ap_delivery_queue
SET claimed_until = NULL,
    next_attempt_at = ?,
    attempts = MAX(attempts - 1, 0)
WHERE id = ? AND revision = ?
`

type DeferActivityPubDeliveryParams struct {
	NextAttemptAt time.Time
	ID            int64
	Revision      int64
}

func (q *Queries) DeferActivityPubDelivery(ctx context.Context, arg DeferActivityPubDeliveryParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, deferActivityPubDelivery, arg.NextAttemptAt, arg.ID, arg.Revision)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteUserAccessTokens = `-- name: DeleteUserAccessTokens :exec
DELETE FROM user_access_tokens WHERE user_id = ?
`

func (q *Queries) DeleteUserAccessTokens(ctx context.Context, userID string) error {
	_, err := q.db.ExecContext(ctx, deleteUserAccessTokens, userID)
	return err
}

const deleteUserAuth = `-- name: DeleteUserAuth :exec
DELETE FROM auth WHERE user_id = ?
`

func (q *Queries) DeleteUserAuth(ctx context.Context, userID string) error {
	_, err := q.db.ExecContext(ctx, deleteUserAuth, userID)
	return err
}

const deleteUserByID = `-- name: DeleteUserByID :execrows
DELETE FROM users WHERE id = ?
`

func (q *Queries) DeleteUserByID(ctx context.Context, id string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteUserByID, id)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteUserMessages = `-- name: DeleteUserMessages :exec
DELETE FROM messages WHERE user_id = ?
`

func (q *Queries) DeleteUserMessages(ctx context.Context, userID sql.NullString) error {
	_, err := q.db.ExecContext(ctx, deleteUserMessages, userID)
	return err
}

const doesInboundActivityExist = `-- name: DoesInboundActivityExist :one
SELECT count(*) FROM ap_accepted_activities WHERE iri = ? AND actor = ? AND TYPE = ?
`

type DoesInboundActivityExistParams struct {
	Iri   string
	Actor string
	Type  string
}

func (q *Queries) DoesInboundActivityExist(ctx context.Context, arg DoesInboundActivityExistParams) (int64, error) {
	row := q.db.QueryRowContext(ctx, doesInboundActivityExist, arg.Iri, arg.Actor, arg.Type)
	var count int64
	err := row.Scan(&count)
	return count, err
}

const failActivityPubDelivery = `-- name: FailActivityPubDelivery :execrows
UPDATE ap_delivery_queue
SET claimed_until = NULL,
    last_error = ?,
    failed_at = ?
WHERE id = ? AND revision = ?
`

type FailActivityPubDeliveryParams struct {
	LastError sql.NullString
	FailedAt  sql.NullTime
	ID        int64
	Revision  int64
}

func (q *Queries) FailActivityPubDelivery(ctx context.Context, arg FailActivityPubDeliveryParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, failActivityPubDelivery,
		arg.LastError,
		arg.FailedAt,
		arg.ID,
		arg.Revision,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const getApprovedDirectoryFollowers = `-- name: GetApprovedDirectoryFollowers :many
SELECT iri, inbox, shared_inbox, name, username, image, created_at FROM ap_followers WHERE approved_at IS NOT NULL AND disabled_at IS NULL AND directory IS 1 ORDER BY created_at DESC
`

type GetApprovedDirectoryFollowersRow struct {
	Iri         string
	Inbox       string
	SharedInbox sql.NullString
	Name        sql.NullString
	Username    string
	Image       sql.NullString
	CreatedAt   sql.NullTime
}

// Approved directories that are featuring/listing this server. Shown in the
// admin so the operator can review and remove them.
func (q *Queries) GetApprovedDirectoryFollowers(ctx context.Context) ([]GetApprovedDirectoryFollowersRow, error) {
	rows, err := q.db.QueryContext(ctx, getApprovedDirectoryFollowers)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []GetApprovedDirectoryFollowersRow
	for rows.Next() {
		var i GetApprovedDirectoryFollowersRow
		if err := rows.Scan(
			&i.Iri,
			&i.Inbox,
			&i.SharedInbox,
			&i.Name,
			&i.Username,
			&i.Image,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getAuthForUsers = `-- name: GetAuthForUsers :many
SELECT user_id, type, provider FROM auth WHERE user_id IN (/*SLICE:user_ids*/?)
`

type GetAuthForUsersRow struct {
	UserID   string
	Type     string
	Provider string
}

// External auth identities (type + provider) for the given users, so the admin
// user list can show how each authenticated user signed in.
func (q *Queries) GetAuthForUsers(ctx context.Context, userIds []string) ([]GetAuthForUsersRow, error) {
	query := getAuthForUsers
	var queryParams []interface{}
	if len(userIds) > 0 {
		for _, v := range userIds {
			queryParams = append(queryParams, v)
		}
		query = strings.Replace(query, "/*SLICE:user_ids*/?", strings.Repeat(",?", len(userIds))[1:], 1)
	} else {
		query = strings.Replace(query, "/*SLICE:user_ids*/?", "NULL", 1)
	}
	rows, err := q.db.QueryContext(ctx, query, queryParams...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []GetAuthForUsersRow
	for rows.Next() {
		var i GetAuthForUsersRow
		if err := rows.Scan(&i.UserID, &i.Type, &i.Provider); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getFederatedServer = `-- name: GetFederatedServer :one
SELECT id, iri, name, logo_url, is_online, stream_title, stream_description, stream_tags, thumbnail_url, last_seen_online, last_status_update, added_at, followed_at, pending, username, display_name, summary, accepted_at, rejected_at, follow_status, priority FROM federated_servers WHERE iri = ?
`

func (q *Queries) GetFederatedServer(ctx context.Context, iri string) (FederatedServer, error) {
	row := q.db.QueryRowContext(ctx, getFederatedServer, iri)
	var i FederatedServer
	err := row.Scan(
		&i.ID,
		&i.Iri,
		&i.Name,
		&i.LogoUrl,
		&i.IsOnline,
		&i.StreamTitle,
		&i.StreamDescription,
		&i.StreamTags,
		&i.ThumbnailUrl,
		&i.LastSeenOnline,
		&i.LastStatusUpdate,
		&i.AddedAt,
		&i.FollowedAt,
		&i.Pending,
		&i.Username,
		&i.DisplayName,
		&i.Summary,
		&i.AcceptedAt,
		&i.RejectedAt,
		&i.FollowStatus,
		&i.Priority,
	)
	return i, err
}

const getFederatedServers = `-- name: GetFederatedServers :many

SELECT id, iri, name, logo_url, is_online, stream_title, stream_description, stream_tags, thumbnail_url, last_seen_online, last_status_update, added_at, followed_at, pending, username, display_name, summary, accepted_at, rejected_at, follow_status, priority FROM federated_servers ORDER BY priority ASC, added_at ASC
`

// Federated servers queries
func (q *Queries) GetFederatedServers(ctx context.Context) ([]FederatedServer, error) {
	rows, err := q.db.QueryContext(ctx, getFederatedServers)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []FederatedServer
	for rows.Next() {
		var i FederatedServer
		if err := rows.Scan(
			&i.ID,
			&i.Iri,
			&i.Name,
			&i.LogoUrl,
			&i.IsOnline,
			&i.StreamTitle,
			&i.StreamDescription,
			&i.StreamTags,
			&i.ThumbnailUrl,
			&i.LastSeenOnline,
			&i.LastStatusUpdate,
			&i.AddedAt,
			&i.FollowedAt,
			&i.Pending,
			&i.Username,
			&i.DisplayName,
			&i.Summary,
			&i.AcceptedAt,
			&i.RejectedAt,
			&i.FollowStatus,
			&i.Priority,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getFederationFollowerApprovalRequests = `-- name: GetFederationFollowerApprovalRequests :many
SELECT iri, inbox, shared_inbox, name, username, image, created_at FROM ap_followers WHERE approved_at IS null AND disabled_at is null AND directory IS NOT 1
`

type GetFederationFollowerApprovalRequestsRow struct {
	Iri         string
	Inbox       string
	SharedInbox sql.NullString
	Name        sql.NullString
	Username    string
	Image       sql.NullString
	CreatedAt   sql.NullTime
}

// Regular (fan) follow approval requests only. Featured-streams (Owncast
// server) requests are excluded here and surfaced separately via
// GetPendingFeaturedFollowRequests so they can be approved from the featured
// streams admin instead of the followers admin.
func (q *Queries) GetFederationFollowerApprovalRequests(ctx context.Context) ([]GetFederationFollowerApprovalRequestsRow, error) {
	rows, err := q.db.QueryContext(ctx, getFederationFollowerApprovalRequests)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []GetFederationFollowerApprovalRequestsRow
	for rows.Next() {
		var i GetFederationFollowerApprovalRequestsRow
		if err := rows.Scan(
			&i.Iri,
			&i.Inbox,
			&i.SharedInbox,
			&i.Name,
			&i.Username,
			&i.Image,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getFederationFollowersWithOffset = `-- name: GetFederationFollowersWithOffset :many
SELECT iri, inbox, shared_inbox, name, username, image, created_at FROM ap_followers WHERE approved_at is not null AND directory IS NOT 1 ORDER BY created_at DESC, rowid DESC LIMIT ? OFFSET ?
`

type GetFederationFollowersWithOffsetParams struct {
	Limit  int64
	Offset int64
}

type GetFederationFollowersWithOffsetRow struct {
	Iri         string
	Inbox       string
	SharedInbox sql.NullString
	Name        sql.NullString
	Username    string
	Image       sql.NullString
	CreatedAt   sql.NullTime
}

// Excludes featured-streams (Owncast-server) follows so they don't show up in
// the public or admin followers list; they are tracked as a directory
// relationship, not surfaced as followers.
// rowid breaks created_at ties (second resolution) so pagination order is
// deterministic; without it, same-second follows shift between pages.
func (q *Queries) GetFederationFollowersWithOffset(ctx context.Context, arg GetFederationFollowersWithOffsetParams) ([]GetFederationFollowersWithOffsetRow, error) {
	rows, err := q.db.QueryContext(ctx, getFederationFollowersWithOffset, arg.Limit, arg.Offset)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []GetFederationFollowersWithOffsetRow
	for rows.Next() {
		var i GetFederationFollowersWithOffsetRow
		if err := rows.Scan(
			&i.Iri,
			&i.Inbox,
			&i.SharedInbox,
			&i.Name,
			&i.Username,
			&i.Image,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getFollowerByIRI = `-- name: GetFollowerByIRI :one
SELECT iri, inbox, shared_inbox, name, username, image, request, request_object, created_at, approved_at, disabled_at, directory FROM ap_followers WHERE iri = ?
`

type GetFollowerByIRIRow struct {
	Iri           string
	Inbox         string
	SharedInbox   sql.NullString
	Name          sql.NullString
	Username      string
	Image         sql.NullString
	Request       string
	RequestObject []byte
	CreatedAt     sql.NullTime
	ApprovedAt    sql.NullTime
	DisabledAt    sql.NullTime
	Directory     sql.NullBool
}

func (q *Queries) GetFollowerByIRI(ctx context.Context, iri string) (GetFollowerByIRIRow, error) {
	row := q.db.QueryRowContext(ctx, getFollowerByIRI, iri)
	var i GetFollowerByIRIRow
	err := row.Scan(
		&i.Iri,
		&i.Inbox,
		&i.SharedInbox,
		&i.Name,
		&i.Username,
		&i.Image,
		&i.Request,
		&i.RequestObject,
		&i.CreatedAt,
		&i.ApprovedAt,
		&i.DisabledAt,
		&i.Directory,
	)
	return i, err
}

const getFollowerCount = `-- name: GetFollowerCount :one


SELECT count(*) FROM ap_followers WHERE approved_at is not null AND directory IS NOT 1
`

// Queries added to query.sql must be compiled into Go code with sqlc. Read README.md for details.
// Federation related queries.
// Featured-streams follows (another Owncast server following us so it can show
// our live status in its directory) are excluded: they are a directory
// relationship, not a fan follow, so they must not inflate the follower count.
func (q *Queries) GetFollowerCount(ctx context.Context) (int64, error) {
	row := q.db.QueryRowContext(ctx, getFollowerCount)
	var count int64
	err := row.Scan(&count)
	return count, err
}

const getFollowersToValidate = `-- name: GetFollowersToValidate :many
SELECT iri, inbox, shared_inbox, name, username, image, first_validation_failure_at
FROM ap_followers
WHERE approved_at IS NOT NULL AND disabled_at IS NULL
ORDER BY last_validated_at ASC NULLS FIRST
LIMIT ?
`

type GetFollowersToValidateRow struct {
	Iri                      string
	Inbox                    string
	SharedInbox              sql.NullString
	Name                     sql.NullString
	Username                 string
	Image                    sql.NullString
	FirstValidationFailureAt sql.NullTime
}

func (q *Queries) GetFollowersToValidate(ctx context.Context, limit int64) ([]GetFollowersToValidateRow, error) {
	rows, err := q.db.QueryContext(ctx, getFollowersToValidate, limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []GetFollowersToValidateRow
	for rows.Next() {
		var i GetFollowersToValidateRow
		if err := rows.Scan(
			&i.Iri,
			&i.Inbox,
			&i.SharedInbox,
			&i.Name,
			&i.Username,
			&i.Image,
			&i.FirstValidationFailureAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getIPAddressBans = `-- name: GetIPAddressBans :many
SELECT ip_address, notes, created_at FROM ip_bans
`

func (q *Queries) GetIPAddressBans(ctx context.Context) ([]IpBan, error) {
	rows, err := q.db.QueryContext(ctx, getIPAddressBans)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []IpBan
	for rows.Next() {
		var i IpBan
		if err := rows.Scan(&i.IpAddress, &i.Notes, &i.CreatedAt); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getInboundActivitiesWithOffset = `-- name: GetInboundActivitiesWithOffset :many
SELECT iri, actor, type, timestamp FROM ap_accepted_activities ORDER BY timestamp DESC LIMIT ? OFFSET ?
`

type GetInboundActivitiesWithOffsetParams struct {
	Limit  int64
	Offset int64
}

type GetInboundActivitiesWithOffsetRow struct {
	Iri       string
	Actor     string
	Type      string
	Timestamp time.Time
}

func (q *Queries) GetInboundActivitiesWithOffset(ctx context.Context, arg GetInboundActivitiesWithOffsetParams) ([]GetInboundActivitiesWithOffsetRow, error) {
	rows, err := q.db.QueryContext(ctx, getInboundActivitiesWithOffset, arg.Limit, arg.Offset)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []GetInboundActivitiesWithOffsetRow
	for rows.Next() {
		var i GetInboundActivitiesWithOffsetRow
		if err := rows.Scan(
			&i.Iri,
			&i.Actor,
			&i.Type,
			&i.Timestamp,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getInboundActivityCount = `-- name: GetInboundActivityCount :one
SELECT count(*) FROM ap_accepted_activities
`

func (q *Queries) GetInboundActivityCount(ctx context.Context) (int64, error) {
	row := q.db.QueryRowContext(ctx, getInboundActivityCount)
	var count int64
	err := row.Scan(&count)
	return count, err
}

const getLocalPostCount = `-- name: GetLocalPostCount :one
SELECT count(*) FROM ap_outbox WHERE type = 'Note'
`

// Only posts (Notes) count: the outbox table also stores other
// dereferenceable objects, such as QuoteAuthorization stamps, that are not
// posts and must not inflate the public post count.
func (q *Queries) GetLocalPostCount(ctx context.Context) (int64, error) {
	row := q.db.QueryRowContext(ctx, getLocalPostCount)
	var count int64
	err := row.Scan(&count)
	return count, err
}

const getMaxAcceptedFederatedServerPriority = `-- name: GetMaxAcceptedFederatedServerPriority :one
SELECT CAST(COALESCE(MAX(priority), 0) AS INTEGER) FROM federated_servers WHERE follow_status = 'accepted'
`

func (q *Queries) GetMaxAcceptedFederatedServerPriority(ctx context.Context) (int64, error) {
	row := q.db.QueryRowContext(ctx, getMaxAcceptedFederatedServerPriority)
	var column_1 int64
	err := row.Scan(&column_1)
	return column_1, err
}

const getMessagesFromUser = `-- name: GetMessagesFromUser :many
SELECT id, body, hidden_at, timestamp FROM messages WHERE eventType = 'CHAT' AND user_id = ? ORDER BY TIMESTAMP DESC
`

type GetMessagesFromUserRow struct {
	ID        string
	Body      sql.NullString
	HiddenAt  sql.NullTime
	Timestamp sql.NullTime
}

func (q *Queries) GetMessagesFromUser(ctx context.Context, userID sql.NullString) ([]GetMessagesFromUserRow, error) {
	rows, err := q.db.QueryContext(ctx, getMessagesFromUser, userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []GetMessagesFromUserRow
	for rows.Next() {
		var i GetMessagesFromUserRow
		if err := rows.Scan(
			&i.ID,
			&i.Body,
			&i.HiddenAt,
			&i.Timestamp,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getNoteFromOutboxByIRI = `-- name: GetNoteFromOutboxByIRI :one
SELECT value, live_notification, created_at FROM ap_outbox WHERE iri = ? AND type = 'Note'
`

type GetNoteFromOutboxByIRIRow struct {
	Value            []byte
	LiveNotification sql.NullBool
	CreatedAt        sql.NullTime
}

// Like GetObjectFromOutboxByIRI but only matches posts (Notes). Used to
// decide whether an object may be quoted: stamps and directory pings are
// stored in the same table and are not quotable.
func (q *Queries) GetNoteFromOutboxByIRI(ctx context.Context, iri string) (GetNoteFromOutboxByIRIRow, error) {
	row := q.db.QueryRowContext(ctx, getNoteFromOutboxByIRI, iri)
	var i GetNoteFromOutboxByIRIRow
	err := row.Scan(&i.Value, &i.LiveNotification, &i.CreatedAt)
	return i, err
}

const getNotificationDestinationsForChannel = `-- name: GetNotificationDestinationsForChannel :many
SELECT destination FROM notifications WHERE channel = ?
`

func (q *Queries) GetNotificationDestinationsForChannel(ctx context.Context, channel string) ([]string, error) {
	rows, err := q.db.QueryContext(ctx, getNotificationDestinationsForChannel, channel)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []string
	for rows.Next() {
		var destination string
		if err := rows.Scan(&destination); err != nil {
			return nil, err
		}
		items = append(items, destination)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getObjectFromOutboxByIRI = `-- name: GetObjectFromOutboxByIRI :one
SELECT value, live_notification, created_at FROM ap_outbox WHERE iri = ?
`

type GetObjectFromOutboxByIRIRow struct {
	Value            []byte
	LiveNotification sql.NullBool
	CreatedAt        sql.NullTime
}

func (q *Queries) GetObjectFromOutboxByIRI(ctx context.Context, iri string) (GetObjectFromOutboxByIRIRow, error) {
	row := q.db.QueryRowContext(ctx, getObjectFromOutboxByIRI, iri)
	var i GetObjectFromOutboxByIRIRow
	err := row.Scan(&i.Value, &i.LiveNotification, &i.CreatedAt)
	return i, err
}

const getOutboxWithOffset = `-- name: GetOutboxWithOffset :many
SELECT value FROM ap_outbox WHERE type = 'Note' LIMIT ? OFFSET ?
`

type GetOutboxWithOffsetParams struct {
	Limit  int64
	Offset int64
}

// Only posts (Notes) are listed in the public outbox collection. Other stored
// objects, such as QuoteAuthorization stamps, stay fetchable by IRI but are
// not part of the collection.
func (q *Queries) GetOutboxWithOffset(ctx context.Context, arg GetOutboxWithOffsetParams) ([][]byte, error) {
	rows, err := q.db.QueryContext(ctx, getOutboxWithOffset, arg.Limit, arg.Offset)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items [][]byte
	for rows.Next() {
		var value []byte
		if err := rows.Scan(&value); err != nil {
			return nil, err
		}
		items = append(items, value)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getPendingFeaturedFollowRequests = `-- name: GetPendingFeaturedFollowRequests :many
SELECT iri, inbox, shared_inbox, name, username, image, created_at FROM ap_followers WHERE approved_at IS null AND disabled_at is null AND directory IS 1 ORDER BY created_at DESC
`

type GetPendingFeaturedFollowRequestsRow struct {
	Iri         string
	Inbox       string
	SharedInbox sql.NullString
	Name        sql.NullString
	Username    string
	Image       sql.NullString
	CreatedAt   sql.NullTime
}

// Pending requests from other Owncast servers asking to feature this server's
// stream in their directory. These always require explicit approval.
func (q *Queries) GetPendingFeaturedFollowRequests(ctx context.Context) ([]GetPendingFeaturedFollowRequestsRow, error) {
	rows, err := q.db.QueryContext(ctx, getPendingFeaturedFollowRequests)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []GetPendingFeaturedFollowRequestsRow
	for rows.Next() {
		var i GetPendingFeaturedFollowRequestsRow
		if err := rows.Scan(
			&i.Iri,
			&i.Inbox,
			&i.SharedInbox,
			&i.Name,
			&i.Username,
			&i.Image,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getPendingFederatedServers = `-- name: GetPendingFederatedServers :many
SELECT id, iri, name, logo_url, is_online, stream_title, stream_description, stream_tags, thumbnail_url, last_seen_online, last_status_update, added_at, followed_at, pending, username, display_name, summary, accepted_at, rejected_at, follow_status, priority FROM federated_servers WHERE pending = true ORDER BY added_at DESC
`

func (q *Queries) GetPendingFederatedServers(ctx context.Context) ([]FederatedServer, error) {
	rows, err := q.db.QueryContext(ctx, getPendingFederatedServers)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []FederatedServer
	for rows.Next() {
		var i FederatedServer
		if err := rows.Scan(
			&i.ID,
			&i.Iri,
			&i.Name,
			&i.LogoUrl,
			&i.IsOnline,
			&i.StreamTitle,
			&i.StreamDescription,
			&i.StreamTags,
			&i.ThumbnailUrl,
			&i.LastSeenOnline,
			&i.LastStatusUpdate,
			&i.AddedAt,
			&i.FollowedAt,
			&i.Pending,
			&i.Username,
			&i.DisplayName,
			&i.Summary,
			&i.AcceptedAt,
			&i.RejectedAt,
			&i.FollowStatus,
			&i.Priority,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getRejectedAndBlockedFollowers = `-- name: GetRejectedAndBlockedFollowers :many
SELECT iri, name, username, image, created_at, disabled_at FROM ap_followers WHERE disabled_at is not null
`

type GetRejectedAndBlockedFollowersRow struct {
	Iri        string
	Name       sql.NullString
	Username   string
	Image      sql.NullString
	CreatedAt  sql.NullTime
	DisabledAt sql.NullTime
}

func (q *Queries) GetRejectedAndBlockedFollowers(ctx context.Context) ([]GetRejectedAndBlockedFollowersRow, error) {
	rows, err := q.db.QueryContext(ctx, getRejectedAndBlockedFollowers)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []GetRejectedAndBlockedFollowersRow
	for rows.Next() {
		var i GetRejectedAndBlockedFollowersRow
		if err := rows.Scan(
			&i.Iri,
			&i.Name,
			&i.Username,
			&i.Image,
			&i.CreatedAt,
			&i.DisabledAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getUniqueDeliveryInboxes = `-- name: GetUniqueDeliveryInboxes :many
SELECT COALESCE(shared_inbox, inbox) as delivery_inbox FROM ap_followers WHERE approved_at is not null GROUP BY delivery_inbox
`

func (q *Queries) GetUniqueDeliveryInboxes(ctx context.Context) ([]string, error) {
	rows, err := q.db.QueryContext(ctx, getUniqueDeliveryInboxes)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []string
	for rows.Next() {
		var delivery_inbox string
		if err := rows.Scan(&delivery_inbox); err != nil {
			return nil, err
		}
		items = append(items, delivery_inbox)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getUniqueDirectoryDeliveryInboxes = `-- name: GetUniqueDirectoryDeliveryInboxes :many
SELECT COALESCE(shared_inbox, inbox) as delivery_inbox FROM ap_followers WHERE approved_at is not null AND directory IS 1 GROUP BY delivery_inbox
`

// Approved directory followers only. The Offer/Leave stream pings are delivered
// here, not to fan followers, who only need the go-live Create/Note.
func (q *Queries) GetUniqueDirectoryDeliveryInboxes(ctx context.Context) ([]string, error) {
	rows, err := q.db.QueryContext(ctx, getUniqueDirectoryDeliveryInboxes)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []string
	for rows.Next() {
		var delivery_inbox string
		if err := rows.Scan(&delivery_inbox); err != nil {
			return nil, err
		}
		items = append(items, delivery_inbox)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getUserByAccessToken = `-- name: GetUserByAccessToken :one
SELECT users.id, display_name, display_color, users.created_at, disabled_at, disabled_reason, previous_names, namechanged_at, authenticated_at, scopes, users.type = 'API' AS is_bot FROM users, user_access_tokens WHERE token = ? AND users.id = user_id
`

type GetUserByAccessTokenRow struct {
	ID              string
	DisplayName     string
	DisplayColor    int64
	CreatedAt       sql.NullTime
	DisabledAt      sql.NullTime
	DisabledReason  sql.NullString
	PreviousNames   sql.NullString
	NamechangedAt   sql.NullTime
	AuthenticatedAt sql.NullTime
	Scopes          sql.NullString
	IsBot           bool
}

func (q *Queries) GetUserByAccessToken(ctx context.Context, token string) (GetUserByAccessTokenRow, error) {
	row := q.db.QueryRowContext(ctx, getUserByAccessToken, token)
	var i GetUserByAccessTokenRow
	err := row.Scan(
		&i.ID,
		&i.DisplayName,
		&i.DisplayColor,
		&i.CreatedAt,
		&i.DisabledAt,
		&i.DisabledReason,
		&i.PreviousNames,
		&i.NamechangedAt,
		&i.AuthenticatedAt,
		&i.Scopes,
		&i.IsBot,
	)
	return i, err
}

const getUserByAuth = `-- name: GetUserByAuth :one
SELECT users.id, display_name, display_color, users.created_at, disabled_at, disabled_reason, previous_names, namechanged_at, authenticated_at, scopes FROM auth, users WHERE auth_key = ? AND auth.type = ? AND users.id = auth.user_id
`

type GetUserByAuthParams struct {
	AuthKey string
	Type    string
}

type GetUserByAuthRow struct {
	ID              string
	DisplayName     string
	DisplayColor    int64
	CreatedAt       sql.NullTime
	DisabledAt      sql.NullTime
	DisabledReason  sql.NullString
	PreviousNames   sql.NullString
	NamechangedAt   sql.NullTime
	AuthenticatedAt sql.NullTime
	Scopes          sql.NullString
}

func (q *Queries) GetUserByAuth(ctx context.Context, arg GetUserByAuthParams) (GetUserByAuthRow, error) {
	row := q.db.QueryRowContext(ctx, getUserByAuth, arg.AuthKey, arg.Type)
	var i GetUserByAuthRow
	err := row.Scan(
		&i.ID,
		&i.DisplayName,
		&i.DisplayColor,
		&i.CreatedAt,
		&i.DisabledAt,
		&i.DisabledReason,
		&i.PreviousNames,
		&i.NamechangedAt,
		&i.AuthenticatedAt,
		&i.Scopes,
	)
	return i, err
}

const getUserByID = `-- name: GetUserByID :one
SELECT id, display_name, display_color, created_at, disabled_at, disabled_reason, previous_names, namechanged_at, authenticated_at, scopes, type = 'API' AS is_bot FROM users WHERE id = ?
`

type GetUserByIDRow struct {
	ID              string
	DisplayName     string
	DisplayColor    int64
	CreatedAt       sql.NullTime
	DisabledAt      sql.NullTime
	DisabledReason  sql.NullString
	PreviousNames   sql.NullString
	NamechangedAt   sql.NullTime
	AuthenticatedAt sql.NullTime
	Scopes          sql.NullString
	IsBot           bool
}

func (q *Queries) GetUserByID(ctx context.Context, id string) (GetUserByIDRow, error) {
	row := q.db.QueryRowContext(ctx, getUserByID, id)
	var i GetUserByIDRow
	err := row.Scan(
		&i.ID,
		&i.DisplayName,
		&i.DisplayColor,
		&i.CreatedAt,
		&i.DisabledAt,
		&i.DisabledReason,
		&i.PreviousNames,
		&i.NamechangedAt,
		&i.AuthenticatedAt,
		&i.Scopes,
		&i.IsBot,
	)
	return i, err
}

const getUserByPluginAuth = `-- name: GetUserByPluginAuth :one
SELECT users.id, display_name, display_color, users.created_at, disabled_at, disabled_reason, previous_names, namechanged_at, authenticated_at, scopes FROM auth, users WHERE auth.type = 'plugin.auth' AND auth.provider = ? AND auth.auth_key = ? AND users.id = auth.user_id
`

type GetUserByPluginAuthParams struct {
	Provider string
	AuthKey  string
}

type GetUserByPluginAuthRow struct {
	ID              string
	DisplayName     string
	DisplayColor    int64
	CreatedAt       sql.NullTime
	DisabledAt      sql.NullTime
	DisabledReason  sql.NullString
	PreviousNames   sql.NullString
	NamechangedAt   sql.NullTime
	AuthenticatedAt sql.NullTime
	Scopes          sql.NullString
}

// Plugin-auth lookup keyed on (provider, auth_key). The type literal mirrors
// models.PluginAuth and pins the lookup to the plugin namespace, so a plugin
// slug can never resolve a built-in identity.
func (q *Queries) GetUserByPluginAuth(ctx context.Context, arg GetUserByPluginAuthParams) (GetUserByPluginAuthRow, error) {
	row := q.db.QueryRowContext(ctx, getUserByPluginAuth, arg.Provider, arg.AuthKey)
	var i GetUserByPluginAuthRow
	err := row.Scan(
		&i.ID,
		&i.DisplayName,
		&i.DisplayColor,
		&i.CreatedAt,
		&i.DisabledAt,
		&i.DisabledReason,
		&i.PreviousNames,
		&i.NamechangedAt,
		&i.AuthenticatedAt,
		&i.Scopes,
	)
	return i, err
}

const getUserDisplayNameByToken = `-- name: GetUserDisplayNameByToken :one
SELECT display_name FROM users JOIN user_access_tokens ON users.id = user_access_tokens.user_id WHERE token = ? AND users.disabled_at IS NULL
`

func (q *Queries) GetUserDisplayNameByToken(ctx context.Context, token string) (string, error) {
	row := q.db.QueryRowContext(ctx, getUserDisplayNameByToken, token)
	var display_name string
	err := row.Scan(&display_name)
	return display_name, err
}

const getUsers = `-- name: GetUsers :many
SELECT id, display_name, display_color, created_at, disabled_at, disabled_reason, previous_names, namechanged_at, authenticated_at, scopes, type = 'API' AS is_bot FROM users ORDER BY created_at DESC
`

type GetUsersRow struct {
	ID              string
	DisplayName     string
	DisplayColor    int64
	CreatedAt       sql.NullTime
	DisabledAt      sql.NullTime
	DisabledReason  sql.NullString
	PreviousNames   sql.NullString
	NamechangedAt   sql.NullTime
	AuthenticatedAt sql.NullTime
	Scopes          sql.NullString
	IsBot           bool
}

func (q *Queries) GetUsers(ctx context.Context) ([]GetUsersRow, error) {
	rows, err := q.db.QueryContext(ctx, getUsers)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []GetUsersRow
	for rows.Next() {
		var i GetUsersRow
		if err := rows.Scan(
			&i.ID,
			&i.DisplayName,
			&i.DisplayColor,
			&i.CreatedAt,
			&i.DisabledAt,
			&i.DisabledReason,
			&i.PreviousNames,
			&i.NamechangedAt,
			&i.AuthenticatedAt,
			&i.Scopes,
			&i.IsBot,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getUsersPaginated = `-- name: GetUsersPaginated :many
SELECT id, display_name, display_color, created_at, disabled_at, disabled_reason, previous_names, namechanged_at, authenticated_at, scopes, type = 'API' AS is_bot
FROM users
WHERE display_name LIKE '%' || ?1 || '%'
  AND (
    ?2 = '' OR ?2 = 'all'
    OR (?2 = 'active' AND disabled_at IS NULL)
    OR (?2 = 'bots' AND type = 'API')
  )
ORDER BY created_at DESC
LIMIT ?4 OFFSET ?3
`

type GetUsersPaginatedParams struct {
	Search     sql.NullString
	Status     interface{}
	PageOffset int64
	PageLimit  int64
}

type GetUsersPaginatedRow struct {
	ID              string
	DisplayName     string
	DisplayColor    int64
	CreatedAt       sql.NullTime
	DisabledAt      sql.NullTime
	DisabledReason  sql.NullString
	PreviousNames   sql.NullString
	NamechangedAt   sql.NullTime
	AuthenticatedAt sql.NullTime
	Scopes          sql.NullString
	IsBot           bool
}

// A page of users of every type (chat viewers, authenticated/plugin users, and
// API integrations), newest first, filtered to display names containing
// @search and an optional @status: ” or 'all' = every user; otherwise
// 'active' (not banned) or 'bots' (API users). An empty @search matches every
// user (LIKE '%%'). The complete banned and moderator sets come from
// GetDisabledUsers and GetModeratorUsers instead, since those need every match
// rather than a page. GetUsersPaginatedAsc is the oldest-first counterpart;
// the two exist as separate queries because sqlc can't bind a sort direction
// into ORDER BY.
func (q *Queries) GetUsersPaginated(ctx context.Context, arg GetUsersPaginatedParams) ([]GetUsersPaginatedRow, error) {
	rows, err := q.db.QueryContext(ctx, getUsersPaginated,
		arg.Search,
		arg.Status,
		arg.PageOffset,
		arg.PageLimit,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []GetUsersPaginatedRow
	for rows.Next() {
		var i GetUsersPaginatedRow
		if err := rows.Scan(
			&i.ID,
			&i.DisplayName,
			&i.DisplayColor,
			&i.CreatedAt,
			&i.DisabledAt,
			&i.DisabledReason,
			&i.PreviousNames,
			&i.NamechangedAt,
			&i.AuthenticatedAt,
			&i.Scopes,
			&i.IsBot,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getUsersPaginatedAsc = `-- name: GetUsersPaginatedAsc :many
SELECT id, display_name, display_color, created_at, disabled_at, disabled_reason, previous_names, namechanged_at, authenticated_at, scopes, type = 'API' AS is_bot
FROM users
WHERE display_name LIKE '%' || ?1 || '%'
  AND (
    ?2 = '' OR ?2 = 'all'
    OR (?2 = 'active' AND disabled_at IS NULL)
    OR (?2 = 'bots' AND type = 'API')
  )
ORDER BY created_at ASC
LIMIT ?4 OFFSET ?3
`

type GetUsersPaginatedAscParams struct {
	Search     sql.NullString
	Status     interface{}
	PageOffset int64
	PageLimit  int64
}

type GetUsersPaginatedAscRow struct {
	ID              string
	DisplayName     string
	DisplayColor    int64
	CreatedAt       sql.NullTime
	DisabledAt      sql.NullTime
	DisabledReason  sql.NullString
	PreviousNames   sql.NullString
	NamechangedAt   sql.NullTime
	AuthenticatedAt sql.NullTime
	Scopes          sql.NullString
	IsBot           bool
}

// Oldest-first counterpart to GetUsersPaginated. Same @search/@status filter,
// only the created_at ordering differs.
func (q *Queries) GetUsersPaginatedAsc(ctx context.Context, arg GetUsersPaginatedAscParams) ([]GetUsersPaginatedAscRow, error) {
	rows, err := q.db.QueryContext(ctx, getUsersPaginatedAsc,
		arg.Search,
		arg.Status,
		arg.PageOffset,
		arg.PageLimit,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []GetUsersPaginatedAscRow
	for rows.Next() {
		var i GetUsersPaginatedAscRow
		if err := rows.Scan(
			&i.ID,
			&i.DisplayName,
			&i.DisplayColor,
			&i.CreatedAt,
			&i.DisabledAt,
			&i.DisabledReason,
			&i.PreviousNames,
			&i.NamechangedAt,
			&i.AuthenticatedAt,
			&i.Scopes,
			&i.IsBot,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const isDisplayNameAvailable = `-- name: IsDisplayNameAvailable :one
SELECT count(*) FROM users WHERE display_name = ? AND ( type='API' OR authenticated_at IS NOT NULL ) AND disabled_at IS NULL
`

func (q *Queries) IsDisplayNameAvailable(ctx context.Context, displayName string) (int64, error) {
	row := q.db.QueryRowContext(ctx, isDisplayNameAvailable, displayName)
	var count int64
	err := row.Scan(&count)
	return count, err
}

const isIPAddressBlocked = `-- name: IsIPAddressBlocked :one
SELECT count(*) FROM ip_bans WHERE ip_address = ?
`

func (q *Queries) IsIPAddressBlocked(ctx context.Context, ipAddress string) (int64, error) {
	row := q.db.QueryRowContext(ctx, isIPAddressBlocked, ipAddress)
	var count int64
	err := row.Scan(&count)
	return count, err
}

const queueActivityPubDelivery = `-- name: QueueActivityPubDelivery :one
INSERT INTO ap_delivery_queue (
    inbox,
    payload,
    actor_iri,
    activity_type,
    coalesce_key,
    next_attempt_at
) VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(inbox, coalesce_key) WHERE coalesce_key IS NOT NULL AND failed_at IS NULL
DO UPDATE SET
    payload = excluded.payload,
    actor_iri = excluded.actor_iri,
    activity_type = excluded.activity_type,
    next_attempt_at = excluded.next_attempt_at,
    attempts = 0,
    last_error = NULL,
    revision = ap_delivery_queue.revision + 1
RETURNING id
`

type QueueActivityPubDeliveryParams struct {
	Inbox         string
	Payload       []byte
	ActorIri      string
	ActivityType  string
	CoalesceKey   sql.NullString
	NextAttemptAt time.Time
}

func (q *Queries) QueueActivityPubDelivery(ctx context.Context, arg QueueActivityPubDeliveryParams) (int64, error) {
	row := q.db.QueryRowContext(ctx, queueActivityPubDelivery,
		arg.Inbox,
		arg.Payload,
		arg.ActorIri,
		arg.ActivityType,
		arg.CoalesceKey,
		arg.NextAttemptAt,
	)
	var id int64
	err := row.Scan(&id)
	return id, err
}

const rejectFederationFollower = `-- name: RejectFederationFollower :exec
UPDATE ap_followers SET approved_at = null, disabled_at = ? WHERE iri = ?
`

type RejectFederationFollowerParams struct {
	DisabledAt sql.NullTime
	Iri        string
}

func (q *Queries) RejectFederationFollower(ctx context.Context, arg RejectFederationFollowerParams) error {
	_, err := q.db.ExecContext(ctx, rejectFederationFollower, arg.DisabledAt, arg.Iri)
	return err
}

const releaseSupersededActivityPubDelivery = `-- name: ReleaseSupersededActivityPubDelivery :exec
UPDATE ap_delivery_queue SET claimed_until = NULL WHERE id = ? AND revision != ?
`

type ReleaseSupersededActivityPubDeliveryParams struct {
	ID       int64
	Revision int64
}

func (q *Queries) ReleaseSupersededActivityPubDelivery(ctx context.Context, arg ReleaseSupersededActivityPubDeliveryParams) error {
	_, err := q.db.ExecContext(ctx, releaseSupersededActivityPubDelivery, arg.ID, arg.Revision)
	return err
}

const removeFederatedServer = `-- name: RemoveFederatedServer :exec
DELETE FROM federated_servers WHERE id = ?
`

func (q *Queries) RemoveFederatedServer(ctx context.Context, id int64) error {
	_, err := q.db.ExecContext(ctx, removeFederatedServer, id)
	return err
}

const removeFollowerByIRI = `-- name: RemoveFollowerByIRI :exec
DELETE FROM ap_followers WHERE iri = ?
`

func (q *Queries) RemoveFollowerByIRI(ctx context.Context, iri string) error {
	_, err := q.db.ExecContext(ctx, removeFollowerByIRI, iri)
	return err
}

const removeIPAddressBan = `-- name: RemoveIPAddressBan :exec
DELETE FROM ip_bans WHERE ip_address = ?
`

func (q *Queries) RemoveIPAddressBan(ctx context.Context, ipAddress string) error {
	_, err := q.db.ExecContext(ctx, removeIPAddressBan, ipAddress)
	return err
}

const removeNotificationDestinationForChannel = `-- name: RemoveNotificationDestinationForChannel :exec
DELETE FROM notifications WHERE channel = ? AND destination = ?
`

type RemoveNotificationDestinationForChannelParams struct {
	Channel     string
	Destination string
}

func (q *Queries) RemoveNotificationDestinationForChannel(ctx context.Context, arg RemoveNotificationDestinationForChannelParams) error {
	_, err := q.db.ExecContext(ctx, removeNotificationDestinationForChannel, arg.Channel, arg.Destination)
	return err
}

const retryActivityPubDelivery = `-- name: RetryActivityPubDelivery :execrows
UPDATE ap_delivery_queue
SET claimed_until = NULL,
    next_attempt_at = ?,
    last_error = ?
WHERE id = ? AND revision = ?
`

type RetryActivityPubDeliveryParams struct {
	NextAttemptAt time.Time
	LastError     sql.NullString
	ID            int64
	Revision      int64
}

func (q *Queries) RetryActivityPubDelivery(ctx context.Context, arg RetryActivityPubDeliveryParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, retryActivityPubDelivery,
		arg.NextAttemptAt,
		arg.LastError,
		arg.ID,
		arg.Revision,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const setAccessTokenToOwner = `-- name: SetAccessTokenToOwner :exec
UPDATE user_access_tokens SET user_id = ? WHERE token = ?
`

type SetAccessTokenToOwnerParams struct {
	UserID string
	Token  string
}

func (q *Queries) SetAccessTokenToOwner(ctx context.Context, arg SetAccessTokenToOwnerParams) error {
	_, err := q.db.ExecContext(ctx, setAccessTokenToOwner, arg.UserID, arg.Token)
	return err
}

const setFederatedServerPriority = `-- name: SetFederatedServerPriority :exec
UPDATE federated_servers SET priority = ? WHERE id = ?
`

type SetFederatedServerPriorityParams struct {
	Priority int64
	ID       int64
}

func (q *Queries) SetFederatedServerPriority(ctx context.Context, arg SetFederatedServerPriorityParams) error {
	_, err := q.db.ExecContext(ctx, setFederatedServerPriority, arg.Priority, arg.ID)
	return err
}

const setUserAsAuthenticated = `-- name: SetUserAsAuthenticated :exec
UPDATE users SET authenticated_at = CURRENT_TIMESTAMP WHERE id = ?
`

func (q *Queries) SetUserAsAuthenticated(ctx context.Context, id string) error {
	_, err := q.db.ExecContext(ctx, setUserAsAuthenticated, id)
	return err
}

const updateFederatedServerFollowStatus = `-- name: UpdateFederatedServerFollowStatus :exec
UPDATE federated_servers SET follow_status = ?, pending = ?, accepted_at = ?, rejected_at = ? WHERE iri = ?
`

type UpdateFederatedServerFollowStatusParams struct {
	FollowStatus sql.NullString
	Pending      sql.NullBool
	AcceptedAt   sql.NullTime
	RejectedAt   sql.NullTime
	Iri          string
}

func (q *Queries) UpdateFederatedServerFollowStatus(ctx context.Context, arg UpdateFederatedServerFollowStatusParams) error {
	_, err := q.db.ExecContext(ctx, updateFederatedServerFollowStatus,
		arg.FollowStatus,
		arg.Pending,
		arg.AcceptedAt,
		arg.RejectedAt,
		arg.Iri,
	)
	return err
}

const updateFederatedServerMetadata = `-- name: UpdateFederatedServerMetadata :exec
UPDATE federated_servers SET name = ?, display_name = ?, summary = ?, logo_url = ? WHERE iri = ?
`

type UpdateFederatedServerMetadataParams struct {
	Name        sql.NullString
	DisplayName sql.NullString
	Summary     sql.NullString
	LogoUrl     sql.NullString
	Iri         string
}

func (q *Queries) UpdateFederatedServerMetadata(ctx context.Context, arg UpdateFederatedServerMetadataParams) error {
	_, err := q.db.ExecContext(ctx, updateFederatedServerMetadata,
		arg.Name,
		arg.DisplayName,
		arg.Summary,
		arg.LogoUrl,
		arg.Iri,
	)
	return err
}

const updateFederatedServerOnlineStatus = `-- name: UpdateFederatedServerOnlineStatus :exec
UPDATE federated_servers SET is_online = ?, last_seen_online = ?, last_status_update = ? WHERE iri = ?
`

type UpdateFederatedServerOnlineStatusParams struct {
	IsOnline         sql.NullBool
	LastSeenOnline   sql.NullTime
	LastStatusUpdate sql.NullTime
	Iri              string
}

func (q *Queries) UpdateFederatedServerOnlineStatus(ctx context.Context, arg UpdateFederatedServerOnlineStatusParams) error {
	_, err := q.db.ExecContext(ctx, updateFederatedServerOnlineStatus,
		arg.IsOnline,
		arg.LastSeenOnline,
		arg.LastStatusUpdate,
		arg.Iri,
	)
	return err
}

const updateFederatedServerStatus = `-- name: UpdateFederatedServerStatus :exec
UPDATE federated_servers SET is_online = ?, stream_title = ?, stream_description = ?, stream_tags = ?, thumbnail_url = ?, last_status_update = ? WHERE iri = ?
`

type UpdateFederatedServerStatusParams struct {
	IsOnline          sql.NullBool
	StreamTitle       sql.NullString
	StreamDescription sql.NullString
	StreamTags        sql.NullString
	ThumbnailUrl      sql.NullString
	LastStatusUpdate  sql.NullTime
	Iri               string
}

func (q *Queries) UpdateFederatedServerStatus(ctx context.Context, arg UpdateFederatedServerStatusParams) error {
	_, err := q.db.ExecContext(ctx, updateFederatedServerStatus,
		arg.IsOnline,
		arg.StreamTitle,
		arg.StreamDescription,
		arg.StreamTags,
		arg.ThumbnailUrl,
		arg.LastStatusUpdate,
		arg.Iri,
	)
	return err
}

const updateFollowerByIRI = `-- name: UpdateFollowerByIRI :exec
UPDATE ap_followers SET inbox = ?, shared_inbox = ?, name = ?, username = ?, image = ? WHERE iri = ?
`

type UpdateFollowerByIRIParams struct {
	Inbox       string
	SharedInbox sql.NullString
	Name        sql.NullString
	Username    string
	Image       sql.NullString
	Iri         string
}

func (q *Queries) UpdateFollowerByIRI(ctx context.Context, arg UpdateFollowerByIRIParams) error {
	_, err := q.db.ExecContext(ctx, updateFollowerByIRI,
		arg.Inbox,
		arg.SharedInbox,
		arg.Name,
		arg.Username,
		arg.Image,
		arg.Iri,
	)
	return err
}

const updateFollowerValidationFailure = `-- name: UpdateFollowerValidationFailure :exec
UPDATE ap_followers
SET last_validated_at = ?1, first_validation_failure_at = COALESCE(first_validation_failure_at, ?1)
WHERE iri = ?2
`

type UpdateFollowerValidationFailureParams struct {
	LastValidatedAt sql.NullTime
	Iri             string
}

func (q *Queries) UpdateFollowerValidationFailure(ctx context.Context, arg UpdateFollowerValidationFailureParams) error {
	_, err := q.db.ExecContext(ctx, updateFollowerValidationFailure, arg.LastValidatedAt, arg.Iri)
	return err
}

const updateFollowerValidationSuccess = `-- name: UpdateFollowerValidationSuccess :exec
UPDATE ap_followers
SET last_validated_at = ?, first_validation_failure_at = NULL
WHERE iri = ?
`

type UpdateFollowerValidationSuccessParams struct {
	LastValidatedAt sql.NullTime
	Iri             string
}

func (q *Queries) UpdateFollowerValidationSuccess(ctx context.Context, arg UpdateFollowerValidationSuccessParams) error {
	_, err := q.db.ExecContext(ctx, updateFollowerValidationSuccess, arg.LastValidatedAt, arg.Iri)
	return err
}