store

package
v1.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: BSD-3-Clause Imports: 33 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package store holds the GORM models, the queries, the migrations and the FTS5 index. It is the only package that knows the database.

Index

Constants

View Source
const (
	// TagNotFound is the tag of a query for one row that found none. The
	// metadata "op" names the store method.
	TagNotFound = "NotFound"
	// TagConflict is the tag of a write that violates a unique or primary key
	// constraint. The metadata "op" names the store method.
	TagConflict = "Conflict"
	// TagQueryFailed is the tag of any other database error. The metadata
	// "op" names the store method.
	TagQueryFailed = "QueryFailed"
)
View Source
const (
	// SearchMarkStart comes before each matched word in SearchHit.Snippet. It
	// is a private-use character, and the index never holds it, so user text
	// cannot fake a match.
	SearchMarkStart = "\ue000"
	// SearchMarkEnd comes after each matched word in SearchHit.Snippet; see
	// SearchMarkStart.
	SearchMarkEnd = "\ue001"
)
View Source
const MaxClientNameRunes = 80

MaxClientNameRunes is the longest ClientName of a session, in characters.

View Source
const NoRoom uint64 = 0

NoRoom is the RoomID of an audit event that belongs to no room, such as the events about an account. No room has the ID 0, and nothing has a foreign key on the column.

View Source
const PostgresTestEnv = "CLOWDER_TEST_POSTGRES"

PostgresTestEnv is the environment variable that makes the tests run on PostgreSQL: the URL of a server where the user may create databases, for example postgres://clowder:clowder@127.0.0.1:5432/postgres?sslmode=disable (SPEC D39). Without it the tests run on SQLite.

View Source
const SSHCodeRetention = 24 * time.Hour

SSHCodeRetention is how long the rows of the codes are kept: IssueSSHCode deletes the older ones.

View Source
const TagBackupVacuumFailed = "BackupVacuumFailed"

TagBackupVacuumFailed is the tag of a VACUUM INTO that failed, or that was asked of a PostgreSQL store. The metadata "path" is the target.

View Source
const UnreadPostsCap = 100

UnreadPostsCap is the largest number of unread posts that the count of a room gives: 100 means 100 or more. The pages show "99+" above 99, so no more is needed, and counting stops at the cap, which keeps the query for a member who has not read a busy room for a long time as cheap as for one who has (step 20.2: 28 ms instead of 6 ms on PostgreSQL for 100 rooms of the large demo with nothing seen).

Variables

This section is empty.

Functions

func BulkCreate

func BulkCreate[T BulkRow](ctx context.Context, s *Store, rows []T) error

BulkCreate inserts rows in batches of 500, in the order they are given. It is for the large demo and for tools that load many rows at once, where one service call per row would take too long. A row with a zero CreatedAt gets the time of the Store's clock; one with a primary key keeps it, which lets the caller link rows to each other before they are written. Call it inside Store.Tx to make the load atomic. It does no work for an empty list, and fails with TagConflict when a unique constraint is violated and with TagQueryFailed for any other database error.

func DirectKeyOf

func DirectKeyOf(a, b uint64) string

DirectKeyOf makes the DirectKey of the direct conversation between two users: the smaller ID first, a colon, the larger ("3:7").

func LatestMigration added in v1.2.0

func LatestMigration() string

LatestMigration returns the ID of the last raw migration that this binary knows, such as "0007_calls_open". The IDs start with a zero-padded number, so a larger ID is a newer schema. A backup records the ID that the database had (SchemaVersion), and a restore refuses a backup whose ID is larger than this one (SPEC D59).

func NewPostgresDatabase added in v1.1.0

func NewPostgresDatabase(ctx context.Context, serverURL string) (string, func() error, error)

NewPostgresDatabase makes a new, empty database on the server at serverURL (postgres:// or postgresql://, any database name: it is only the door) and returns its URL, with the password the caller gave in serverURL, and the function that drops it, ending the sessions that still use it, and closes the connection used to make it. It is for tests and tools that start more than one process on one database, such as the browser tests of the processes of a cluster (SPEC D41); it needs a user that may create and drop databases. The name starts like the copies of a PostgresTemplate, so that the next NewPostgresTemplate drops it if a crash left it behind. The URL holds the password: never log it. It fails with TemplateURLInvalid when serverURL is not one of PostgreSQL, TemplateServerFailed when the server does not answer and TemplateCreateFailed when the database cannot be made; the function fails with TemplateDropFailed.

func NextID

func NextID[T BulkRow](ctx context.Context, s *Store) (uint64, error)

NextID returns the primary key that follows the largest one of the table of T: 1 for an empty table. A caller that writes rows with BulkCreate, giving each its primary key, starts from it.

Types

type Attachment

type Attachment struct {
	ID         uint64
	CreatedAt  time.Time
	PostID     uint64 `gorm:"not null;index:idx_attachments_post_id"`
	UploaderID uint64 `gorm:"not null"`
	// FileName is the name the file had when it was uploaded.
	FileName    string `gorm:"not null"`
	ContentType string `gorm:"not null"`
	// Size is the size in bytes.
	Size int64 `gorm:"not null;check:chk_attachments_size,size >= 0"`
	// StorageKey is the random name of the file in the data directory.
	StorageKey string `gorm:"not null;uniqueIndex:uq_attachments_storage_key"`
	// Width and Height are the size in pixels of an image; nil for any other
	// file.
	Width  *int
	Height *int

	// Relations: declared so that GORM creates the foreign keys.
	Post     *Post `gorm:"foreignKey:PostID;constraint:OnDelete:CASCADE"`
	Uploader *User `gorm:"foreignKey:UploaderID;constraint:OnDelete:RESTRICT"`
}

Attachment is a file uploaded with a post or a comment. The bytes are on disk under StorageKey (SPEC §7.5); this row holds what the page shows.

type AuditAction

type AuditAction string

AuditAction is what an audit event records (SPEC §7.10).

const (
	ActionPostCreated   AuditAction = "post.created"
	ActionPostEdited    AuditAction = "post.edited"
	ActionPostDeleted   AuditAction = "post.deleted"
	ActionTaskCreated   AuditAction = "task.created"
	ActionTaskEdited    AuditAction = "task.edited"
	ActionTaskMoved     AuditAction = "task.moved"
	ActionTaskDeleted   AuditAction = "task.deleted"
	ActionColumnCreated AuditAction = "column.created"
	ActionColumnRenamed AuditAction = "column.renamed"
	ActionColumnMoved   AuditAction = "column.moved"
	ActionColumnDeleted AuditAction = "column.deleted"
	ActionMemberJoined  AuditAction = "member.joined"
	ActionMemberAdded   AuditAction = "member.added"
	ActionMemberLeft    AuditAction = "member.left"
	ActionMemberRemoved AuditAction = "member.removed"
	ActionRoomCreated   AuditAction = "room.created"
	ActionRoomRenamed   AuditAction = "room.renamed"
	ActionRoomDeleted   AuditAction = "room.deleted"
	// ActionUserPasswordChanged is a user who changed their own password
	// (SPEC §7.14).
	ActionUserPasswordChanged AuditAction = "user.password_changed"
	// ActionUserResetLinkCreated is a reset link made for a user by an admin
	// or on the command line (SPEC §7.1, D51).
	ActionUserResetLinkCreated AuditAction = "user.reset_link_created"
	// ActionUserPasswordReset is a user who set a new password with a reset
	// link.
	ActionUserPasswordReset AuditAction = "user.password_reset"
	// ActionUserSSHKeyAdded is a user who registered an SSH key (SPEC §7.16).
	ActionUserSSHKeyAdded AuditAction = "user.ssh_key_added"
	// ActionUserSSHKeyRemoved is a user who removed an SSH key.
	ActionUserSSHKeyRemoved AuditAction = "user.ssh_key_removed"
	// ActionUserSSHCodeEnabled is a user who turned on the SSH code at login
	// (SPEC §7.16).
	ActionUserSSHCodeEnabled AuditAction = "user.ssh_code_enabled"
	// ActionUserSSHCodeDisabled is a user who turned off the SSH code at
	// login.
	ActionUserSSHCodeDisabled AuditAction = "user.ssh_code_disabled"
	// ActionUserSSHCodeRemoved is an admin who turned off the SSH code of
	// another user.
	ActionUserSSHCodeRemoved AuditAction = "user.ssh_code_removed"
)

The actions of SPEC §7.10.

type AuditEvent

type AuditEvent struct {
	// ID orders the log: newer events have larger IDs.
	ID        uint64    `` /* 137-byte string literal not displayed */
	CreatedAt time.Time `gorm:"index:idx_audit_events_created_at"`
	// ActorID is the user who made the change.
	ActorID uint64      `gorm:"not null;index:idx_audit_events_actor,priority:1"`
	Action  AuditAction `gorm:"not null;index:idx_audit_events_action,priority:1"`
	// RoomID is the room of the change. The room may be gone. It is NoRoom for
	// an event about an account.
	RoomID     uint64     `gorm:"not null;index:idx_audit_events_room,priority:1"`
	EntityType EntityType `gorm:"not null;check:chk_audit_events_entity_type,entity_type IN ('room','post','comment','task','column','member','user')"`
	// EntityID is the ID of the entity. The entity may be gone.
	EntityID uint64 `gorm:"not null"`
	// Summary reads on its own after the entity is gone.
	Summary string `gorm:"not null"`
	// Details is a JSON object with the changed fields and their old and new
	// values.
	Details string `gorm:"not null;check:chk_audit_events_details_json,json_valid(details)"`

	// Relation: declared so that GORM creates the foreign key. The only one
	// of the table.
	Actor *User `gorm:"foreignKey:ActorID;constraint:OnDelete:RESTRICT"`
}

AuditEvent records a change to a post, task, column, membership, room or account. It has no foreign key to the room or the entity: the event outlives them. Nothing edits or deletes an event.

type AuditFilter

type AuditFilter struct {
	// RoomID keeps the events of this room. The room may be gone.
	RoomID uint64
	// ActorID keeps the events made by this user.
	ActorID uint64
	// EntityType keeps the events about this kind of entity.
	EntityType EntityType
	// Action keeps the events with this action.
	Action AuditAction
	// From keeps the events created at or after this time.
	From time.Time
	// To keeps the events created before this time.
	To time.Time
}

AuditFilter narrows ListAuditEvents (SPEC §7.10). A zero field does not filter; the filters that are set all have to match.

type BackupCounts added in v1.2.0

type BackupCounts struct {
	// Users, Rooms and Messages are the numbers of those rows.
	Users, Rooms, Messages int64
	// Posts is the number of posts and comments together (they share a table).
	Posts int64
}

BackupCounts are the sizes that the manifest of a backup records.

type BoardColumn

type BoardColumn struct {
	ID        uint64
	CreatedAt time.Time
	RoomID    uint64 `gorm:"not null;index:idx_board_columns_room_position,priority:1"`
	Name      string `gorm:"not null"`
	// Position orders the columns of a room from left to right.
	Position int `gorm:"not null;index:idx_board_columns_room_position,priority:2"`

	// Relation: declared so that GORM creates the foreign key.
	Room *Room `gorm:"foreignKey:RoomID;constraint:OnDelete:CASCADE"`
}

BoardColumn is a column of the board of a room (SPEC §7.6). The application makes three with every room.

type BulkRow

type BulkRow interface {
	User | RoomMember | Post | Tag | PostTag | Attachment | Reaction | Mention |
		Task | TaskAssignee | AuditEvent
}

BulkRow is the set of models that BulkCreate writes and NextID counts. They are the tables that the large demo (SPEC §10, §14) fills in bulk.

type Call added in v1.2.0

type Call struct {
	ID        uint64
	CreatedAt time.Time
	// ConversationID is the direct conversation of the call.
	ConversationID uint64 `gorm:"not null;index:idx_calls_conversation,priority:1"`
	// CallerID started the call and CalleeID was called.
	CallerID uint64 `gorm:"not null"`
	CalleeID uint64 `gorm:"not null"`
	// Video is true when the caller started the call with video.
	Video bool `gorm:"not null"`
	// State is where the call is. Raw migration 0007 allows one open call
	// (ringing or active) per caller and one per callee.
	State CallState `gorm:"not null;check:chk_calls_state,state IN ('ringing','active','ended')"`
	// AnsweredAt is when the callee answered; nil if never.
	AnsweredAt *time.Time
	// EndedAt is when the call ended; nil while it is open.
	EndedAt *time.Time `gorm:"check:chk_calls_ended,(state = 'ended') = (ended_at IS NOT NULL)"`
	// EndReason is how the call ended; empty while it is open.
	EndReason CallEndReason `` /* 173-byte string literal not displayed */
	// EndedBy is the user who ended the call (hung up, cancelled, declined);
	// nil when the system ended it.
	EndedBy *uint64
	// Home is the ID of the process that holds the media of the call (SPEC
	// D65).
	Home string `gorm:"not null"`

	// Relations: declared so that GORM creates the foreign keys.
	Conversation *Conversation `gorm:"foreignKey:ConversationID;constraint:OnDelete:CASCADE"`
	Caller       *User         `gorm:"foreignKey:CallerID;constraint:OnDelete:RESTRICT"`
	Callee       *User         `gorm:"foreignKey:CalleeID;constraint:OnDelete:RESTRICT"`
	Ender        *User         `gorm:"foreignKey:EndedBy;constraint:OnDelete:RESTRICT"`
}

Call is a voice or video call between the two users of a direct conversation (SPEC §7.18, D63). Its row is made when the call starts and changes when it is answered and when it ends; a call that ended leaves its entry in the conversation (a Message of kind call).

func (Call) Open added in v1.2.0

func (c Call) Open() bool

Open reports whether the call is ringing or active.

type CallEndReason added in v1.2.0

type CallEndReason string

CallEndReason says how a call ended.

const (
	// CallHangup is a call that one side ended while it was active.
	CallHangup CallEndReason = "hangup"
	// CallCancelled is a call that the caller ended while it rang.
	CallCancelled CallEndReason = "cancelled"
	// CallDeclined is a call that the callee refused.
	CallDeclined CallEndReason = "declined"
	// CallMissed is a call that nobody answered within the ringing time.
	CallMissed CallEndReason = "missed"
	// CallBusy is a call to someone who was in another call.
	CallBusy CallEndReason = "busy"
	// CallFailed is a call whose media connection failed or was lost.
	CallFailed CallEndReason = "failed"
	// CallDisabled is a call that ended because a participant was disabled.
	CallDisabled CallEndReason = "disabled"
	// CallSessionEnded is a call that ended because a participant's session
	// ended (a logout, a session ended from the list, a password change).
	CallSessionEnded CallEndReason = "session_ended"
	// CallServerStopped is a call that ended because the process that held
	// its media stopped.
	CallServerStopped CallEndReason = "server_stopped"
)

type CallState added in v1.2.0

type CallState string

CallState says where a call is (SPEC §7.18).

const (
	// CallRinging is a call that the callee has not answered yet.
	CallRinging CallState = "ringing"
	// CallActive is a call that the callee answered and that has not ended.
	CallActive CallState = "active"
	// CallEnded is a call that is over; EndReason says how it ended.
	CallEnded CallState = "ended"
)

type Conversation

type Conversation struct {
	ID        uint64
	CreatedAt time.Time
	Kind      ConversationKind `gorm:"not null;check:chk_conversations_kind,kind IN ('direct','group')"`
	// Name is the optional name of a group; empty for none.
	Name      string `gorm:"not null"`
	CreatedBy uint64 `gorm:"not null"`
	// DirectKey identifies a direct conversation: the two user IDs, the
	// smaller first ("3:7"). It is unique, so a pair of users has one direct
	// conversation. Nil for a group.
	DirectKey *string `` /* 126-byte string literal not displayed */

	// Relation: declared so that GORM creates the foreign key.
	Creator *User `gorm:"foreignKey:CreatedBy;constraint:OnDelete:RESTRICT"`
}

Conversation is a stream of private messages between users (D28).

type ConversationKind

type ConversationKind string

ConversationKind says how many people a conversation has (SPEC §7.11).

const (
	// ConversationDirect is a conversation between two users.
	ConversationDirect ConversationKind = "direct"
	// ConversationGroup is a conversation of up to 50 users.
	ConversationGroup ConversationKind = "group"
)

type ConversationListItem

type ConversationListItem struct {
	// Conversation is the conversation.
	Conversation Conversation
	// LastReadMessageID is the last message the user has read; 0 if none.
	LastReadMessageID uint64
	// Unread is true when the conversation has a message of someone else,
	// not deleted, after the last message the user has read.
	Unread bool
	// Muted is true when the user muted the conversation (SPEC §7.15).
	Muted bool
	// LastMessage is the newest message, deleted ones included; nil when the
	// conversation has none.
	LastMessage *MessageRow
	// LastAttachmentNames are the names of the files of the last message, in
	// the order they were attached.
	LastAttachmentNames []string
	// LastCall is the call of the last message when that message is a call
	// entry; nil otherwise.
	LastCall *Call
	// Members are the current members, in the order they joined.
	Members []ConversationMemberRow
}

ConversationListItem is a conversation of the list of a user, with everything the list shows.

type ConversationMember

type ConversationMember struct {
	ID             uint64
	CreatedAt      time.Time
	ConversationID uint64 `gorm:"not null;uniqueIndex:uq_conversation_members_conversation_user,priority:1"`
	UserID         uint64 `gorm:"not null;uniqueIndex:uq_conversation_members_conversation_user,priority:2;index:idx_conversation_members_user_id"`
	// AddedBy is the member who added the user; nil for the member who
	// started the conversation.
	AddedBy *uint64
	// LastReadMessageID is the last message the member has read; nil if none.
	LastReadMessageID *uint64
	// LeftAt is when the member left the group; nil while a member.
	LeftAt *time.Time

	// Relations: declared so that GORM creates the foreign keys.
	Conversation    *Conversation `gorm:"foreignKey:ConversationID;constraint:OnDelete:CASCADE"`
	User            *User         `gorm:"foreignKey:UserID;constraint:OnDelete:RESTRICT"`
	Adder           *User         `gorm:"foreignKey:AddedBy;constraint:OnDelete:RESTRICT"`
	LastReadMessage *Message      `gorm:"foreignKey:LastReadMessageID;constraint:OnDelete:SET NULL"`
}

ConversationMember is a user's membership of a conversation.

type ConversationMemberRow

type ConversationMemberRow struct {
	// ID is the ID of the membership; a smaller ID joined earlier.
	ID uint64
	// ConversationID is the conversation.
	ConversationID uint64
	// UserID is the member.
	UserID uint64
	// AddedBy is the member who added the user; nil for the one who started
	// the conversation.
	AddedBy *uint64
	// LastReadMessageID is the last message the member has read; nil if none.
	LastReadMessageID *uint64
	// LeftAt is when the member left; nil while a member.
	LeftAt *time.Time
	// Username is the username of the member.
	Username string
	// DisplayName is the display name of the member.
	DisplayName string
	// AvatarKey is the avatar key of the member; empty for none.
	AvatarKey string
	// DisabledAt is when the user was disabled; nil for an active user.
	DisabledAt *time.Time
}

ConversationMemberRow is a membership with the user it belongs to.

type EntityType

type EntityType string

EntityType is the kind of thing that an audit event is about (SPEC §7.10).

const (
	// EntityRoom is a room.
	EntityRoom EntityType = "room"
	// EntityPost is a post.
	EntityPost EntityType = "post"
	// EntityComment is a comment: a post with a parent.
	EntityComment EntityType = "comment"
	// EntityTask is a task.
	EntityTask EntityType = "task"
	// EntityColumn is a board column.
	EntityColumn EntityType = "column"
	// EntityMember is a room membership.
	EntityMember EntityType = "member"
	// EntityUser is a user's account (SPEC §7.10, 1.2). Its events belong to
	// no room: their RoomID is NoRoom.
	EntityUser EntityType = "user"
)

type Format

type Format string

Format says how the body of a post is shown (SPEC §7.3).

const (
	// FormatText is a body shown as written: escaped, line breaks kept, links
	// made clickable.
	FormatText Format = "text"
	// FormatMarkdown is a body rendered as markdown.
	FormatMarkdown Format = "markdown"
)

type Invitation

type Invitation struct {
	ID        uint64
	CreatedAt time.Time
	// TokenHash is the SHA-256 of the token in the link; the token itself is
	// never stored.
	TokenHash string `gorm:"not null;uniqueIndex:uq_invitations_token_hash"`
	// Role is the role the new user gets.
	Role Role `gorm:"not null;check:chk_invitations_role,role IN ('admin','member')"`
	// CreatedBy is the admin who made the invitation; nil for one made by
	// "clowder invite" on the command line.
	CreatedBy *uint64
	ExpiresAt time.Time `gorm:"not null"`
	// UsedBy is the user the invitation made; nil until it is used.
	UsedBy *uint64
	// UsedAt is when the invitation was used; nil until then.
	UsedAt *time.Time

	// Relations: declared so that GORM creates the foreign keys. The store
	// never loads or saves them.
	Creator *User `gorm:"foreignKey:CreatedBy;constraint:OnDelete:RESTRICT"`
	User    *User `gorm:"foreignKey:UsedBy;constraint:OnDelete:RESTRICT"`
}

Invitation is a one-use link that lets a person sign up (SPEC §7.1).

type MarkUnread added in v1.2.0

type MarkUnread string

MarkUnread says what the unread count of a room counts (SPEC §7.17).

const (
	// MarkUnreadAll counts every new post; it is the default.
	MarkUnreadAll MarkUnread = "all"
	// MarkUnreadMentions counts only the mentions of the user.
	MarkUnreadMentions MarkUnread = "mentions"
)

type Mention

type Mention struct {
	ID        uint64
	CreatedAt time.Time
	PostID    uint64 `gorm:"not null;uniqueIndex:uq_mentions_post_user,priority:1"`
	UserID    uint64 `gorm:"not null;uniqueIndex:uq_mentions_post_user,priority:2"`
	// Kind says how the user is mentioned; the default is MentionUser.
	Kind MentionKind `gorm:"not null;default:user"`

	// Relations: declared so that GORM creates the foreign keys.
	Post *Post `gorm:"foreignKey:PostID;constraint:OnDelete:CASCADE"`
	User *User `gorm:"foreignKey:UserID;constraint:OnDelete:RESTRICT"`
}

Mention is a user who is mentioned in the body of a post: by "@username", by a group mention or by a keyword (Kind). The application rebuilds a post's mentions when the post is edited.

type MentionKind added in v1.2.0

type MentionKind string

MentionKind says how a user is mentioned in a post (SPEC §7.15): by name, by a group mention, or by one of their keywords.

const (
	// MentionUser is an "@username": it is shown as a link in the body.
	MentionUser MentionKind = "user"
	// MentionGroup is an @room, @all or @here that reached the user.
	MentionGroup MentionKind = "group"
	// MentionKeyword is a keyword of the user found in the body.
	MentionKeyword MentionKind = "keyword"
)

type MentionedUser added in v1.2.0

type MentionedUser struct {
	// UserID is the user.
	UserID uint64
	// Kind says how the user is mentioned.
	Kind MentionKind
}

MentionedUser is a user mentioned in a post, and how.

type Message

type Message struct {
	// ID orders the messages of a conversation.
	ID             uint64 `gorm:"primaryKey;index:idx_messages_conversation,priority:2"`
	CreatedAt      time.Time
	ConversationID uint64 `gorm:"not null;index:idx_messages_conversation,priority:1"`
	AuthorID       uint64 `gorm:"not null"`
	Body           string `gorm:"not null"`
	// Kind says whether the message is text or the entry of a call. The two
	// checks keep Kind and CallID in step: a call entry has a call and a text
	// message has none.
	Kind MessageKind `gorm:"not null;default:text;check:chk_messages_kind,kind IN ('text','call')"`
	// CallID is the call of a call entry; nil for a text message.
	CallID *uint64 `gorm:"index:idx_messages_call_id;check:chk_messages_call,(kind = 'call') = (call_id IS NOT NULL)"`
	// ReplyToID is the earlier message that this one quotes; nil for none, and
	// set to nil when that message is deleted.
	ReplyToID *uint64
	// EditedAt is when the author last edited the message; nil if never.
	EditedAt *time.Time
	// DeletedAt is when the author deleted the message; the row stays so the
	// conversation shows "message deleted". The application sets it.
	DeletedAt *time.Time

	// Relations: declared so that GORM creates the foreign keys.
	Conversation *Conversation `gorm:"foreignKey:ConversationID;constraint:OnDelete:CASCADE"`
	Author       *User         `gorm:"foreignKey:AuthorID;constraint:OnDelete:RESTRICT"`
	ReplyTo      *Message      `gorm:"foreignKey:ReplyToID;constraint:OnDelete:SET NULL"`
	Call         *Call         `gorm:"foreignKey:CallID;constraint:OnDelete:CASCADE"`
}

Message is a message of a conversation. It is plain text, or the entry of a call (Kind).

type MessageAttachment

type MessageAttachment struct {
	ID         uint64
	CreatedAt  time.Time
	MessageID  uint64 `gorm:"not null;index:idx_message_attachments_message_id"`
	UploaderID uint64 `gorm:"not null"`
	// FileName is the name the file had when it was uploaded.
	FileName    string `gorm:"not null"`
	ContentType string `gorm:"not null"`
	// Size is the size in bytes.
	Size int64 `gorm:"not null;check:chk_message_attachments_size,size >= 0"`
	// StorageKey is the random name of the file in the data directory.
	StorageKey string `gorm:"not null;uniqueIndex:uq_message_attachments_storage_key"`
	// Width and Height are the size in pixels of an image; nil for any other
	// file.
	Width  *int
	Height *int

	// Relations: declared so that GORM creates the foreign keys.
	Message  *Message `gorm:"foreignKey:MessageID;constraint:OnDelete:CASCADE"`
	Uploader *User    `gorm:"foreignKey:UploaderID;constraint:OnDelete:RESTRICT"`
}

MessageAttachment is a file uploaded with a message; it has the fields of Attachment.

type MessageKind added in v1.2.0

type MessageKind string

MessageKind says what a message is: text that a person wrote, or the entry that a finished call leaves in the conversation (SPEC §7.18).

const (
	// MessageText is a message that a person wrote; the default.
	MessageText MessageKind = "text"
	// MessageCall is the entry of a finished call: its author is the caller,
	// its body is empty and CallID names the call.
	MessageCall MessageKind = "call"
)

type MessageReaction

type MessageReaction struct {
	ID        uint64
	CreatedAt time.Time
	MessageID uint64 `gorm:"not null;uniqueIndex:uq_message_reactions_message_user_emoji,priority:1"`
	UserID    uint64 `gorm:"not null;uniqueIndex:uq_message_reactions_message_user_emoji,priority:2"`
	Emoji     string `gorm:"not null;uniqueIndex:uq_message_reactions_message_user_emoji,priority:3"`

	// Relations: declared so that GORM creates the foreign keys.
	Message *Message `gorm:"foreignKey:MessageID;constraint:OnDelete:CASCADE"`
	User    *User    `gorm:"foreignKey:UserID;constraint:OnDelete:RESTRICT"`
}

MessageReaction is an emoji that a user put on a message, once per emoji.

type MessageReactionRow

type MessageReactionRow struct {
	// ID is the ID of the reaction; a smaller ID is an older reaction.
	ID uint64
	// MessageID is the message reacted to.
	MessageID uint64
	// UserID is the user who reacted.
	UserID uint64
	// Emoji is the emoji of the reaction.
	Emoji string
	// Username is the username of the user who reacted.
	Username string
	// DisplayName is the display name of the user who reacted.
	DisplayName string
}

MessageReactionRow is one reaction on a message with the display name of the user who made it.

type MessageRow

type MessageRow struct {
	// ID is the ID of the message; a larger ID is a newer message.
	ID uint64
	// CreatedAt is when the message was sent.
	CreatedAt time.Time
	// ConversationID is the conversation of the message.
	ConversationID uint64
	// AuthorID is the author.
	AuthorID uint64
	// Body is the text; empty for a deleted message and for a call entry.
	Body string
	// Kind says whether the message is text or the entry of a call.
	Kind MessageKind
	// CallID is the call of a call entry; nil for a text message.
	CallID *uint64
	// ReplyToID is the message that this one quotes; nil for none.
	ReplyToID *uint64
	// EditedAt is when the author last edited the message; nil if never.
	EditedAt *time.Time
	// DeletedAt is when the author deleted the message; nil if never.
	DeletedAt *time.Time
	// AuthorUsername is the username of the author.
	AuthorUsername string
	// AuthorDisplayName is the display name of the author.
	AuthorDisplayName string
	// AuthorAvatarKey is the avatar key of the author; empty for none.
	AuthorAvatarKey string
}

MessageRow is a message with the user who wrote it.

type MessageSearchHit added in v1.2.0

type MessageSearchHit struct {
	// MessageID is the ID of the message.
	MessageID uint64
	// ConversationID is the conversation of the message.
	ConversationID uint64
	// ConversationKind says whether the conversation is direct or a group.
	ConversationKind ConversationKind
	// ConversationName is the name of a group as set; empty for none and for
	// a direct conversation.
	ConversationName string
	// AuthorID is the author of the message.
	AuthorID uint64
	// AuthorUsername is the username of the author.
	AuthorUsername string
	// AuthorDisplayName is the display name of the author.
	AuthorDisplayName string
	// AuthorAvatarKey is the avatar key of the author; empty for none.
	AuthorAvatarKey string
	// CreatedAt is when the message was sent.
	CreatedAt time.Time
	// Snippet is the matching text, not escaped: a piece of the message with
	// the matches between SearchMarkStart and SearchMarkEnd.
	Snippet string
}

MessageSearchHit is a private message that matches a search.

type MessageSearchQuery added in v1.2.0

type MessageSearchQuery struct {
	// ReaderID is the user who searches: only the messages of the
	// conversations the user is a member of now are searched. It is required.
	ReaderID uint64
	// Terms are the words and phrases; all of them have to match. Without
	// terms nothing matches.
	Terms []SearchTerm
	// Before keeps the messages with a smaller ID; 0 keeps all.
	Before uint64
	// Limit is the most hits returned.
	Limit int
}

MessageSearchQuery is what SearchMessages looks for.

type Notification

type Notification struct {
	ID        uint64 `gorm:"primaryKey;index:idx_notifications_user_read,priority:3"`
	CreatedAt time.Time
	UserID    uint64           `gorm:"not null;index:idx_notifications_user_read,priority:1"`
	Kind      NotificationKind `gorm:"not null;check:chk_notifications_kind,kind IN ('mention','reply','assigned','added_to_room','group_mention','keyword')"`
	// PostID is the post or comment of a mention or a reply.
	PostID *uint64 `gorm:"index:idx_notifications_post_id"`
	// TaskID is the task of an assignment.
	TaskID *uint64 `gorm:"index:idx_notifications_task_id"`
	// RoomID is the room of the notification.
	RoomID *uint64 `gorm:"index:idx_notifications_room_id"`
	// ActorID is the user whose action caused the notification.
	ActorID uint64 `gorm:"not null"`
	// ReadAt is when the user read the notification; nil while unread.
	ReadAt *time.Time `gorm:"index:idx_notifications_user_read,priority:2"`
	// Others is the number of other people who replied in the same burst of
	// one minute, folded into this reply notification (SPEC §7.15); the
	// ActorID is the latest of them. It is 0 for every other notification.
	Others int `gorm:"not null;default:0"`

	// Relations: declared so that GORM creates the foreign keys.
	User  *User `gorm:"foreignKey:UserID;constraint:OnDelete:RESTRICT"`
	Post  *Post `gorm:"foreignKey:PostID;constraint:OnDelete:CASCADE"`
	Task  *Task `gorm:"foreignKey:TaskID;constraint:OnDelete:CASCADE"`
	Room  *Room `gorm:"foreignKey:RoomID;constraint:OnDelete:CASCADE"`
	Actor *User `gorm:"foreignKey:ActorID;constraint:OnDelete:RESTRICT"`
}

Notification is shown to a user in the bell and on the notifications page. It is deleted with the post, task or room it points to.

type NotificationKind

type NotificationKind string

NotificationKind says why a user is notified (SPEC §7.9).

const (
	// NotificationMention is an "@username" in a post or comment.
	NotificationMention NotificationKind = "mention"
	// NotificationReply is a comment under the user's post or comment.
	NotificationReply NotificationKind = "reply"
	// NotificationAssigned is a task assigned to the user.
	NotificationAssigned NotificationKind = "assigned"
	// NotificationAddedToRoom is the user's addition to a private room.
	NotificationAddedToRoom NotificationKind = "added_to_room"
	// NotificationGroupMention is an @room, @all or @here that reached the
	// user (SPEC §7.15).
	NotificationGroupMention NotificationKind = "group_mention"
	// NotificationKeyword is a keyword of the user found in a post or comment
	// (SPEC §7.15).
	NotificationKeyword NotificationKind = "keyword"
)

type NotificationRow

type NotificationRow struct {
	// ID is the ID of the notification; a larger ID is a newer notification.
	ID uint64
	// CreatedAt is when the notification was made.
	CreatedAt time.Time
	// Kind says why the user is notified.
	Kind NotificationKind
	// ActorID, ActorUsername and ActorDisplayName tell who caused it.
	ActorID          uint64
	ActorUsername    string
	ActorDisplayName string
	// ActorAvatarKey is the avatar key of the actor; empty for none.
	ActorAvatarKey string
	// RoomID and RoomName are the room of the notification.
	RoomID   uint64
	RoomName string
	// PostID is the post or comment concerned; RootID is the top-level post of
	// its thread (PostID itself for a top-level post).
	PostID uint64
	RootID uint64
	// TaskID and TaskTitle are the task of an assignment.
	TaskID    uint64
	TaskTitle string
	// Others is the number of other people folded into a reply notification.
	Others int
	// ReadAt is when the user read it; nil while unread.
	ReadAt *time.Time
}

NotificationRow is a notification of a user with what a page needs to show it. The fields that do not apply to the kind are zero.

type NotifyLevel added in v1.2.0

type NotifyLevel string

NotifyLevel says what notifies a user, globally or in one place (SPEC §7.15).

const (
	// NotifyAll notifies about every new post and message.
	NotifyAll NotifyLevel = "all"
	// NotifyMentions notifies about mentions, replies, assignments, additions
	// and (for conversations) every message; it is the global default.
	NotifyMentions NotifyLevel = "mentions"
	// NotifyNothing notifies about nothing.
	NotifyNothing NotifyLevel = "nothing"
)

type PasswordReset added in v1.2.0

type PasswordReset struct {
	ID        uint64
	CreatedAt time.Time
	// UserID is the user who may set a new password with the link.
	UserID uint64 `gorm:"not null;index:idx_password_resets_user_id"`
	// TokenHash is the SHA-256 of the token in the link; the token itself is
	// never stored.
	TokenHash string `gorm:"not null;uniqueIndex:uq_password_resets_token_hash"`
	// CreatedBy is the admin who made the link; nil for one made by
	// "clowder reset-password" on the command line.
	CreatedBy *uint64
	ExpiresAt time.Time `gorm:"not null"`
	// UsedAt is when the link was used; nil until then.
	UsedAt *time.Time

	// Relations: declared so that GORM creates the foreign keys. The store
	// never loads or saves them.
	User    *User `gorm:"foreignKey:UserID;constraint:OnDelete:RESTRICT"`
	Creator *User `gorm:"foreignKey:CreatedBy;constraint:OnDelete:RESTRICT"`
}

PasswordReset is a one-use link that lets a user who forgot their password set a new one (SPEC §7.1, D51). A user has at most one unused link: a newer link replaces the older one.

type PendingLogin added in v1.2.0

type PendingLogin struct {
	ID        uint64
	CreatedAt time.Time
	// TokenHash is the SHA-256 of the 32 random bytes of the token. It is
	// unique.
	TokenHash string `gorm:"not null;uniqueIndex:uq_pending_logins_token_hash"`
	// UserID is the user whose password was right.
	UserID uint64 `gorm:"not null;index:idx_pending_logins_user_id"`
	// ExpiresAt is when the pending login stops working.
	ExpiresAt time.Time `gorm:"not null;index:idx_pending_logins_expires_at"`
	// WrongTries counts the wrong codes typed so far.
	WrongTries int `gorm:"not null;default:0"`
	// Next is the local path to go to after the login, already checked by the
	// web layer; empty for the home page.
	Next string `gorm:"not null;default:''"`

	// Relation: declared so that GORM creates the foreign key.
	User *User `gorm:"foreignKey:UserID;constraint:OnDelete:RESTRICT"`
}

PendingLogin is a login whose password was right and that waits for the SSH sign-in code (SPEC §7.16, D53). Only the SHA-256 of its token is stored; the token is in the cookie clowder_pending. It lasts 5 minutes and goes with a right code, with the fifth wrong one, with a change of the password and with the disabling of the user.

type PlaceKey added in v1.2.0

type PlaceKey struct {
	// RoomID is the room; 0 for a conversation.
	RoomID uint64
	// ConversationID is the conversation; 0 for a room.
	ConversationID uint64
}

PlaceKey names one place: a room or a conversation. Exactly one of the two IDs is not 0.

func ConversationPlace added in v1.2.0

func ConversationPlace(conversationID uint64) PlaceKey

ConversationPlace is the PlaceKey of a conversation.

func RoomPlace added in v1.2.0

func RoomPlace(roomID uint64) PlaceKey

RoomPlace is the PlaceKey of a room.

type PlaceNotify added in v1.2.0

type PlaceNotify string

PlaceNotify is what a user chose to be notified about in one room or conversation (SPEC §7.15). PlaceNotifyDefault leaves the choice to the global setting.

const (
	// PlaceNotifyDefault follows the global setting (for a conversation:
	// every message, unless the global setting is Nothing).
	PlaceNotifyDefault PlaceNotify = "default"
	// PlaceNotifyAll notifies about every new post or message of the place.
	PlaceNotifyAll PlaceNotify = "all"
	// PlaceNotifyMentions notifies only about mentions of the user.
	PlaceNotifyMentions PlaceNotify = "mentions"
	// PlaceNotifyNothing notifies about nothing.
	PlaceNotifyNothing PlaceNotify = "nothing"
)

type PlacePref added in v1.2.0

type PlacePref struct {
	ID        uint64
	CreatedAt time.Time
	// UserID is the user the preferences belong to.
	UserID uint64 `gorm:"not null;uniqueIndex:uq_place_prefs_user_room,priority:1;uniqueIndex:uq_place_prefs_user_conversation,priority:1"`
	// RoomID is the room of the preferences; nil for a conversation.
	RoomID *uint64 `` /* 189-byte string literal not displayed */
	// ConversationID is the conversation of the preferences; nil for a room.
	ConversationID *uint64 `gorm:"uniqueIndex:uq_place_prefs_user_conversation,priority:2"`
	// Notify is what the user is notified about in this place.
	Notify PlaceNotify `gorm:"not null;default:default;check:chk_place_prefs_notify,notify IN ('default','all','mentions','nothing')"`
	// Sound is the choice of the sound in this place.
	Sound PlaceSound `gorm:"not null;default:default;check:chk_place_prefs_sound,sound IN ('default','on','off')"`
	// IgnoreGroupMentions is true when @room, @all and @here are ignored in
	// this place (SPEC §7.15).
	IgnoreGroupMentions bool `gorm:"not null;default:false"`
	// MarkUnread is what the unread count of a room counts; for rooms only.
	MarkUnread MarkUnread `gorm:"not null;default:all;check:chk_place_prefs_mark_unread,mark_unread IN ('all','mentions')"`
	// Muted is true when the place is muted: nothing rings in it.
	Muted bool `gorm:"not null;default:false"`

	// Relations: declared so that GORM creates the foreign keys. The rows go
	// with the room or conversation they belong to.
	User         *User         `gorm:"foreignKey:UserID;constraint:OnDelete:RESTRICT"`
	Room         *Room         `gorm:"foreignKey:RoomID;constraint:OnDelete:CASCADE"`
	Conversation *Conversation `gorm:"foreignKey:ConversationID;constraint:OnDelete:CASCADE"`
}

PlacePref holds the notification preferences of one user in one room or one conversation (SPEC §7.15). Exactly one of RoomID and ConversationID is set. A missing row means all defaults; the row is deleted when the user leaves the place.

func DefaultPlacePref added in v1.2.0

func DefaultPlacePref(userID uint64, place PlaceKey) PlacePref

DefaultPlacePref returns the preferences of a user who changed none in the place: the global notify setting, the global sound, nothing ignored, every new post counted, not muted. It has no ID.

type PlaceSound added in v1.2.0

type PlaceSound string

PlaceSound is the choice of the sound in one place.

const (
	// PlaceSoundDefault follows the global sound setting.
	PlaceSoundDefault PlaceSound = "default"
	// PlaceSoundOn plays the sound in this place whatever the global setting.
	PlaceSoundOn PlaceSound = "on"
	// PlaceSoundOff plays no sound in this place.
	PlaceSoundOff PlaceSound = "off"
)

type Post

type Post struct {
	// ID orders the feed and the threads: newer posts have larger IDs.
	ID        uint64 `gorm:"primaryKey;index:idx_posts_feed,priority:3,sort:desc;index:idx_posts_thread,priority:2"`
	CreatedAt time.Time
	RoomID    uint64 `gorm:"not null;index:idx_posts_feed,priority:1"`
	AuthorID  uint64 `gorm:"not null"`
	// ParentID is the post or comment this comment answers; nil for a post.
	ParentID *uint64 `gorm:"index:idx_posts_feed,priority:2;index:idx_posts_parent_id"`
	// RootID is the post a comment belongs to, at any depth; nil for a post.
	RootID *uint64 `gorm:"index:idx_posts_thread,priority:1;check:chk_posts_root_with_parent,(parent_id IS NULL) = (root_id IS NULL)"`
	Format Format  `gorm:"not null;check:chk_posts_format,format IN ('text','markdown')"`
	Body   string  `gorm:"not null"`
	// EditedAt is when the author last edited the post; nil if never.
	EditedAt *time.Time
	// DeletedAt marks a deleted post that stays because it has replies (D21).
	// The application sets it; it is not GORM's soft delete.
	DeletedAt *time.Time

	// Relations: declared so that GORM creates the foreign keys.
	Room   *Room `gorm:"foreignKey:RoomID;constraint:OnDelete:CASCADE"`
	Author *User `gorm:"foreignKey:AuthorID;constraint:OnDelete:RESTRICT"`
	Parent *Post `gorm:"foreignKey:ParentID;constraint:OnDelete:CASCADE"`
	Root   *Post `gorm:"foreignKey:RootID;constraint:OnDelete:CASCADE"`
}

Post is a post in a room, or a comment: a comment is a post with a parent (D16). Everything that hangs on a post is deleted with it, and so are its comments.

type PostFollow added in v1.2.0

type PostFollow struct {
	ID        uint64
	CreatedAt time.Time
	// UserID is the follower.
	UserID uint64 `gorm:"not null;uniqueIndex:uq_post_follows_user_post,priority:1"`
	// PostID is the top-level post that is followed.
	PostID uint64 `gorm:"not null;uniqueIndex:uq_post_follows_user_post,priority:2;index:idx_post_follows_post"`
	// Unfollowed is true when the user stopped following the post.
	Unfollowed bool `gorm:"not null;default:false"`

	// Relations: declared so that GORM creates the foreign keys.
	User *User `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE"`
	Post *Post `gorm:"foreignKey:PostID;constraint:OnDelete:CASCADE"`
}

PostFollow says that a user follows a top-level post, or that they stopped (SPEC §7.15). The row stays when the user unfollows, with Unfollowed set, so that an automatic follow (writing, commenting, being mentioned) does not bring the follow back. It goes with the post and with the user.

type PostTag

type PostTag struct {
	ID        uint64
	CreatedAt time.Time
	PostID    uint64 `gorm:"not null;uniqueIndex:uq_post_tags_post_tag,priority:1"`
	TagID     uint64 `gorm:"not null;uniqueIndex:uq_post_tags_post_tag,priority:2;index:idx_post_tags_tag_id"`

	// Relations: declared so that GORM creates the foreign keys.
	Post *Post `gorm:"foreignKey:PostID;constraint:OnDelete:CASCADE"`
	Tag  *Tag  `gorm:"foreignKey:TagID;constraint:OnDelete:CASCADE"`
}

PostTag links a post to a tag.

type PostgresTemplate added in v1.1.0

type PostgresTemplate struct {
	// contains filtered or unexported fields
}

PostgresTemplate is the PostgreSQL counterpart of Template, for tests: one migrated database on a server, from which Open makes a fresh database for each test with CREATE DATABASE … TEMPLATE, which copies it at the speed of a file copy instead of migrating again. It needs a user that may create and drop databases. A PostgresTemplate is safe for concurrent use; the copies are made one at a time, because PostgreSQL refuses to copy a database that another session is using, and a concurrent copy is such a session. Leftover databases of a crashed run are dropped, by name prefix and age, when a new PostgresTemplate is made. It is for tests (see package storetest); the template database itself stays until the next run drops it, because the binary that made it has no hook to run at its end.

func NewPostgresTemplate added in v1.1.0

func NewPostgresTemplate(ctx context.Context, serverURL string) (*PostgresTemplate, error)

NewPostgresTemplate connects to the server at serverURL (postgres:// or postgresql://, any database name: it is only the door), drops the leftover databases of earlier runs, makes a template database and migrates it with OpenPostgres. The URL holds the password: it never appears in an error, only with the password replaced by "xxxxx". It fails with TemplateURLInvalid when the URL is not one of PostgreSQL, TemplateServerFailed when the server does not answer, TemplateSweepFailed, TemplateCreateFailed and TemplateDropFailed when a database cannot be listed, made or dropped, and with the tags of OpenPostgres when the migration fails.

func (*PostgresTemplate) Open added in v1.1.0

func (t *PostgresTemplate) Open(ctx context.Context, clk clock.Clock, logger *slog.Logger) (*Store, func() error, error)

Open makes a new database as a copy of the template and opens it like OpenPostgres does, without migrating the models: the copy is current. The time of every row comes from clk. A nil logger discards the log. The returned function closes the Store and drops the database, waiting for at most 30 seconds, and is called once, when the test ends (it does not depend on a context that the end of the test has canceled). It fails with TemplateCreateFailed when the copy cannot be made and with the tags of OpenPostgres when it cannot be opened.

type Reaction

type Reaction struct {
	ID        uint64
	CreatedAt time.Time
	PostID    uint64 `gorm:"not null;uniqueIndex:uq_reactions_post_user_emoji,priority:1"`
	UserID    uint64 `gorm:"not null;uniqueIndex:uq_reactions_post_user_emoji,priority:2"`
	Emoji     string `gorm:"not null;uniqueIndex:uq_reactions_post_user_emoji,priority:3"`

	// Relations: declared so that GORM creates the foreign keys.
	Post *Post `gorm:"foreignKey:PostID;constraint:OnDelete:CASCADE"`
	User *User `gorm:"foreignKey:UserID;constraint:OnDelete:RESTRICT"`
}

Reaction is an emoji that a user put on a post or a comment, once per emoji.

type ReactionRow

type ReactionRow struct {
	// ID is the ID of the reaction; a smaller ID is an older reaction.
	ID uint64
	// PostID is the post or comment reacted to.
	PostID uint64
	// UserID is the user who reacted.
	UserID uint64
	// Emoji is the emoji of the reaction.
	Emoji string
	// Username is the username of the user who reacted.
	Username string
	// DisplayName is the display name of the user who reacted.
	DisplayName string
}

ReactionRow is one reaction with the username and the display name of the user who made it.

type Recipient added in v1.2.0

type Recipient struct {
	// UserID is the user.
	UserID uint64
	// Username is the username of the user, lower case, for the detection of
	// @username mentions.
	Username string
	// Settings are the global settings of the user (the defaults when none
	// are saved).
	Settings UserSettings
	// Place are the preferences of the user in the place (the defaults when
	// none are saved).
	Place PlacePref
}

Recipient is a user who may be notified of an event of a place, with the settings and the preferences that decide how (SPEC §7.15).

type RepliesMode added in v1.2.0

type RepliesMode string

RepliesMode says which comments notify a user (SPEC §7.15).

const (
	// RepliesFollowing notifies about every new comment under a post the user
	// follows; it is the default.
	RepliesFollowing RepliesMode = "following"
	// RepliesDirect notifies only about a comment under the user's own post or
	// comment.
	RepliesDirect RepliesMode = "direct"
)

type Role

type Role string

Role is what a user may do in Clowder (SPEC D14).

const (
	// RoleAdmin is a user who manages users, invitations and rooms.
	RoleAdmin Role = "admin"
	// RoleMember is an ordinary user.
	RoleMember Role = "member"
)

type Room

type Room struct {
	ID        uint64
	CreatedAt time.Time
	// Name is unique without regard to case (the column collates NOCASE).
	Name        string     `gorm:"type:text COLLATE NOCASE;not null;uniqueIndex:uq_rooms_name"`
	Description string     `gorm:"not null"`
	Visibility  Visibility `gorm:"not null;check:chk_rooms_visibility,visibility IN ('visible','private')"`
	CreatedBy   uint64     `gorm:"not null"`

	// Relation: declared so that GORM creates the foreign key.
	Creator *User `gorm:"foreignKey:CreatedBy;constraint:OnDelete:RESTRICT"`
}

Room is a feed of posts with a board. Deleting a room deletes everything that belongs to it, except its audit events (SPEC §7.10).

type RoomMember

type RoomMember struct {
	ID        uint64
	CreatedAt time.Time
	RoomID    uint64 `gorm:"not null;uniqueIndex:uq_room_members_room_user,priority:1"`
	UserID    uint64 `gorm:"not null;uniqueIndex:uq_room_members_room_user,priority:2;index:idx_room_members_user_id"`
	// AddedBy is the member who added the user to the room; nil when the user
	// joined by themselves (or created the room).
	AddedBy *uint64

	// Relations: declared so that GORM creates the foreign keys.
	Room  *Room `gorm:"foreignKey:RoomID;constraint:OnDelete:CASCADE"`
	User  *User `gorm:"foreignKey:UserID;constraint:OnDelete:RESTRICT"`
	Adder *User `gorm:"foreignKey:AddedBy;constraint:OnDelete:RESTRICT"`
}

RoomMember is a user's membership of a room. A member of a visible room posts, reacts and changes the board; a member of a private room also sees it.

type RoomPostCount

type RoomPostCount struct {
	// RoomID is the room.
	RoomID uint64
	// Posts is the number of its posts and comments together.
	Posts int64
}

RoomPostCount is the number of posts and comments of a room.

type RoomRead added in v1.2.0

type RoomRead struct {
	// UserID is the member.
	UserID uint64 `gorm:"primaryKey;autoIncrement:false"`
	// RoomID is the room.
	RoomID uint64 `gorm:"primaryKey;autoIncrement:false;index:idx_room_reads_room_id"`
	// LastSeenID is the highest ID of a post or comment of the room that the
	// member has seen. It only moves forward.
	LastSeenID uint64 `gorm:"not null;default:0"`
	// UpdatedAt is when the row was made or last moved.
	UpdatedAt time.Time

	// Relations: declared so that GORM creates the foreign keys.
	User *User `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE"`
	Room *Room `gorm:"foreignKey:RoomID;constraint:OnDelete:CASCADE"`
}

RoomRead says how far a member has read a room (SPEC §7.17, D55): the highest ID of a post or comment of the room that the member has seen. Posts and comments share one ID sequence, so one number covers both. Every membership of a room has exactly one row: it is made with the membership, at the room's highest ID so far (a new member starts with nothing unread), and deleted with it. The primary key is (UserID, RoomID); the row goes with the room and with the user.

type RoomUnread added in v1.2.0

type RoomUnread struct {
	// RoomID is the room.
	RoomID uint64
	// Posts is the number of top-level posts of the room that are not deleted,
	// were written by someone else and have an ID above the member's mark, up
	// to UnreadPostsCap.
	Posts int
	// Mentions is the number of unread notifications of the member in the room
	// of the kinds mention, group_mention and keyword.
	Mentions int
}

RoomUnread holds the unread counts of one room for one member (SPEC §7.17): the top-level posts of other people that the member has not seen, and their unread mention notifications in the room.

type SSHCode added in v1.2.0

type SSHCode struct {
	ID        uint64
	CreatedAt time.Time `gorm:"not null;index:idx_ssh_codes_created_at"`
	// UserID is the user the code is for.
	UserID uint64 `gorm:"not null;index:idx_ssh_codes_user_id"`
	// KeyID is the key that fetched the code.
	KeyID uint64 `gorm:"not null"`
	// CodeHash is the SHA-256 of the 8 normalised characters of the code.
	CodeHash  string    `gorm:"not null"`
	ExpiresAt time.Time `gorm:"not null"`
	// UsedAt is when the code was used; nil until then.
	UsedAt *time.Time
	// Replaced is true once a newer code of the user made this one useless.
	Replaced bool `gorm:"not null;default:false"`

	// Relations: declared so that GORM creates the foreign keys. A code goes
	// with its key.
	User *User   `gorm:"foreignKey:UserID;constraint:OnDelete:RESTRICT"`
	Key  *SSHKey `gorm:"foreignKey:KeyID;constraint:OnDelete:CASCADE"`
}

SSHCode is a one-time sign-in code that the SSH server handed to a user (SPEC §7.16). Only the SHA-256 of the code is stored. A newer code marks the unused ones of the user as replaced; the rows are kept for a day, so that the limit of codes per user is a count of rows.

type SSHKey added in v1.2.0

type SSHKey struct {
	ID        uint64
	CreatedAt time.Time
	// UserID is the user the key belongs to.
	UserID uint64 `gorm:"not null;index:idx_ssh_keys_user_id"`
	// Name is the name the user gave the key, 1 to 40 characters.
	Name string `gorm:"not null"`
	// Type is the type of the key, such as ssh-ed25519.
	Type string `gorm:"not null"`
	// Fingerprint is the SHA-256 fingerprint of the key, as
	// ssh.FingerprintSHA256 writes it.
	Fingerprint string `gorm:"not null;uniqueIndex:uq_ssh_keys_fingerprint"`
	// PublicKey is the authorized-key line of the key, normalised and without
	// a comment.
	PublicKey string `gorm:"not null"`
	// LastUsedAt is when the key last fetched a code; nil until then.
	LastUsedAt *time.Time

	// Relation: declared so that GORM creates the foreign key. The store
	// never loads or saves it.
	User *User `gorm:"foreignKey:UserID;constraint:OnDelete:RESTRICT"`
}

SSHKey is a public key of a user that may fetch sign-in codes from the SSH server (SPEC §7.16). Its fingerprint is unique over all users: a key belongs to one user only.

type SearchHit

type SearchHit struct {
	// PostID is the ID of the post or comment.
	PostID uint64
	// RootID is the top-level post of a comment; 0 for a top-level post.
	RootID uint64
	// IsComment is true for a comment.
	IsComment bool
	// RoomID is the room of the post.
	RoomID uint64
	// RoomName is the name of the room.
	RoomName string
	// AuthorID is the author of the post.
	AuthorID uint64
	// AuthorUsername is the username of the author.
	AuthorUsername string
	// AuthorDisplayName is the display name of the author.
	AuthorDisplayName string
	// AuthorAvatarKey is the avatar key of the author; empty for none.
	AuthorAvatarKey string
	// CreatedAt is when the post was written.
	CreatedAt time.Time
	// Snippet is the matching text, not escaped: with words, a piece of the
	// indexed text with the matches between SearchMarkStart and
	// SearchMarkEnd; without, the start of it, cut at 200 characters.
	Snippet string
}

SearchHit is a post or comment that matches a search.

type SearchQuery

type SearchQuery struct {
	// ReaderID is the user who searches: only rooms that are visible, or that
	// the user is a member of, are searched. It is required.
	ReaderID uint64
	// Terms are the words and phrases; all of them have to match.
	Terms []SearchTerm
	// Tags are normalized tag names; the post has to carry all of them.
	Tags []string
	// Room keeps the posts of the room with this name (case does not matter).
	Room string
	// Author keeps the posts of the user with this (lower-case) username.
	Author string
	// After keeps the posts created at or after this time.
	After time.Time
	// Before keeps the posts created before this time.
	Before time.Time
	// OnlyPosts keeps the top-level posts.
	OnlyPosts bool
	// OnlyComments keeps the comments.
	OnlyComments bool
	// Limit is the most hits returned.
	Limit int
	// Offset is how many hits to skip.
	Offset int
}

SearchQuery is what SearchPosts looks for. A zero field does not filter.

type SearchTerm

type SearchTerm struct {
	// Text is the word or the phrase, as typed. It is never interpreted as
	// FTS5 syntax: SearchPosts quotes it.
	Text string
	// Phrase is true for an exact phrase; a word matches as a prefix.
	Phrase bool
}

SearchTerm is a word or a phrase of a search.

type Session

type Session struct {
	ID        uint64
	CreatedAt time.Time
	// TokenHash is the SHA-256 of the cookie token; the token is never stored.
	TokenHash string    `gorm:"not null;uniqueIndex:uq_sessions_token_hash"`
	UserID    uint64    `gorm:"not null;index:idx_sessions_user_id"`
	ExpiresAt time.Time `gorm:"not null"`
	// LastSeenAt is when the session was last used; a session lasts a set time
	// from this moment (SPEC §7.1).
	LastSeenAt time.Time `gorm:"not null"`
	// Kind is where the session was made: a session of the pages is a
	// browser session, one of the API an api session. The default makes the
	// sessions of version 1.0 browser sessions.
	Kind SessionKind `gorm:"not null;default:browser"`
	// ClientName names the client of the session: the user agent of a
	// browser, cut to MaxClientNameRunes characters, or the name an API
	// client gave when it logged in. It is empty for the sessions of
	// version 1.0.
	ClientName string `gorm:"not null;default:''"`

	// Relation: declared so that GORM creates the foreign key.
	User *User `gorm:"foreignKey:UserID;constraint:OnDelete:RESTRICT"`
}

Session is a login of a user, found by the SHA-256 of its token.

type SessionKind added in v1.1.0

type SessionKind string

SessionKind says where a session was made and where it is accepted (SPEC D43).

const (
	// SessionBrowser is a session made by the login or sign-up page; its token
	// is the session cookie, accepted by the pages only.
	SessionBrowser SessionKind = "browser"
	// SessionAPI is a session made by the login of the API; its token is a
	// bearer token, accepted by the API only.
	SessionAPI SessionKind = "api"
)

type SoundName added in v1.2.0

type SoundName string

SoundName names one of the four sounds of notify.js (SPEC §7.15).

const (
	// SoundPurr is the default sound: a low, warm rumble.
	SoundPurr SoundName = "purr"
	// SoundChirp is two quick rising notes.
	SoundChirp SoundName = "chirp"
	// SoundBell is one soft bell.
	SoundBell SoundName = "bell"
	// SoundMeow is a sweep up and down.
	SoundMeow SoundName = "meow"
)

type Stats

type Stats struct {
	// Users is the number of users.
	Users int64
	// Rooms is the number of rooms; PrivateRooms counts the private ones.
	Rooms, PrivateRooms int64
	// Members is the number of room memberships.
	Members int64
	// Posts is the number of top-level posts, Comments the number of comments.
	// Deleted ones that are kept for their replies are counted too.
	Posts, Comments int64
	// Tags is the number of tags, PostTags the number of links to posts.
	Tags, PostTags int64
	// Reactions, Mentions and Attachments are the numbers of those rows.
	Reactions, Mentions, Attachments int64
	// Columns is the number of board columns, Tasks the number of tasks and
	// Assignees the number of task assignments.
	Columns, Tasks, Assignees int64
	// Conversations and Messages are the numbers of private conversations and
	// messages.
	Conversations, Messages int64
	// AuditEvents is the number of audit events; PostEvents and TaskEvents
	// count those with the actions post.created and task.created.
	AuditEvents, PostEvents, TaskEvents int64
	// Indexed is the number of rows of the full-text index.
	Indexed int64

	// Unindexed counts posts and comments that are not deleted and have no row
	// in the full-text index.
	Unindexed int64
	// StrayIndexRows counts rows of the full-text index whose post is missing
	// or deleted.
	StrayIndexRows int64
	// UnindexedMessages counts private messages that are not deleted, have a
	// body and have no row in the full-text index of messages.
	UnindexedMessages int64
	// StrayMessageIndexRows counts rows of the full-text index of messages
	// whose message is missing, deleted or has no body.
	StrayMessageIndexRows int64
	// BadComments counts comments whose root is not a top-level post of their
	// room, or whose parent is not in the same thread.
	BadComments int64
	// NonMemberAuthors counts posts and comments whose author is not a member
	// of their room.
	NonMemberAuthors int64
	// BadColumns counts rooms whose board columns are missing or whose
	// positions are not 0, 1, 2, ... without gaps.
	BadColumns int64
	// TasksInForeignColumn counts tasks whose column or post belongs to
	// another room than the task.
	TasksInForeignColumn int64
	// BadTaskPositions counts columns whose tasks do not have the positions
	// 0, 1, 2, ... without gaps.
	BadTaskPositions int64
	// MembersWithoutMark counts memberships of rooms that have no row in
	// room_reads (SPEC §6.3: every membership has one).
	MembersWithoutMark int64
	// StrayMarks counts rows of room_reads that belong to no membership.
	StrayMarks int64
}

Stats are the sizes of the tables and the results of consistency checks, for the report of the large demo (SPEC §14) and for tests. A field of the second group is the number of rows that break the rule it names: 0 is healthy.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is the database of Clowder: the only thing that knows GORM, SQLite and PostgreSQL (SPEC D6, D38). Make it with Open or OpenPostgres and release it with Close. A Store is safe for concurrent use.

func Open

func Open(ctx context.Context, path string, clk clock.Clock, logger *slog.Logger) (*Store, error)

Open opens the SQLite database in the file path, creating it if needed, and brings its schema up to date. The time of every row comes from clk, in UTC. A query slower than 200 ms is logged to logger as a warning, without its arguments. path may also be a SQLite "file:" URI, whose own parameters are kept. The caller closes the Store with Close.

func OpenPostgres added in v1.1.0

func OpenPostgres(ctx context.Context, databaseURL string, clk clock.Clock, logger *slog.Logger) (*Store, error)

OpenPostgres opens the PostgreSQL database at databaseURL (postgres:// or postgresql://), and brings its schema up to date, like Open does for SQLite: the time of every row comes from clk, in UTC; a query slower than 200 ms is logged to logger as a warning, without its arguments; the pool has the same bounds as the pool of a file database (SPEC D34). The URL holds the password: it never appears in an error or a log, only with the password replaced by "xxxxx". The caller closes the Store with Close.

func (*Store) AddPendingLoginWrongTry added in v1.2.0

func (s *Store) AddPendingLoginWrongTry(ctx context.Context, id uint64, max int) (gone bool, err error)

AddPendingLoginWrongTry counts one more wrong code for the pending login and deletes the login when it has max wrong codes. It reports whether the login is gone: deleted now, or deleted before (by a right code, a change of the password or the fifth wrong code of a request that raced this one).

func (*Store) AdvanceLastRead

func (s *Store) AdvanceLastRead(ctx context.Context, conversationID, userID, messageID uint64) (bool, error)

AdvanceLastRead moves the last read message of the membership forward to messageID. It never moves it back: it returns false, and changes nothing, when the member has read that message or a later one already.

func (*Store) Analyze added in v1.1.0

func (s *Store) Analyze(ctx context.Context) error

Analyze makes the database collect the statistics its planner needs, after a bulk load. On PostgreSQL it runs ANALYZE: a table that was just loaded has no statistics until autovacuum gets to it (about a minute later), and until then the planner reads the feed of a room with a bitmap scan of all its posts and a sort instead of the index (step 17.1: 6 ms instead of 0.1 ms for the query, 30 ms instead of 5 ms for the page, in the first minute after the large demo). A database that grows through the services does not need it: autovacuum keeps up. SQLite keeps no such statistics and does nothing. Call it after the load has been committed. It fails with TagQueryFailed.

func (*Store) AttachmentByID

func (s *Store) AttachmentByID(ctx context.Context, id uint64) (Attachment, error)

AttachmentByID returns the attachment with the given ID. It fails with TagNotFound when there is none.

func (*Store) AttachmentKeysOfRoom

func (s *Store) AttachmentKeysOfRoom(ctx context.Context, roomID uint64) ([]string, error)

AttachmentKeysOfRoom returns the storage keys of the attachments of every post and comment of the room, deleted placeholders included.

func (*Store) AttachmentsOfPosts

func (s *Store) AttachmentsOfPosts(ctx context.Context, postIDs []uint64) (map[uint64][]Attachment, error)

AttachmentsOfPosts returns the attachments of each of the posts, oldest first (by ID), with one query. A post without attachments has no key in the map.

func (*Store) AutoFollow added in v1.2.0

func (s *Store) AutoFollow(ctx context.Context, postID uint64, userIDs []uint64) error

AutoFollow makes each of userIDs a follower of the top-level post postID, except those who unfollowed it before: their row is left as it is. It does nothing for no users. It fails with TagQueryFailed when a user or the post does not exist.

func (*Store) BackfillRoomReads added in v1.2.0

func (s *Store) BackfillRoomReads(ctx context.Context) (int, error)

BackfillRoomReads makes a row of room_reads, at the room's highest ID, for every membership that has none. The migration of step 20.2 does it for the memberships that exist; the large demo calls it after it wrote rooms and posts in bulk. It reports how many rows it made.

func (*Store) BackupCounts added in v1.2.0

func (s *Store) BackupCounts(ctx context.Context) (BackupCounts, error)

BackupCounts counts the rows that a backup reports. It reads four counts and nothing else, so unlike Stats it is quick on a large database.

func (*Store) BoardColumnByID

func (s *Store) BoardColumnByID(ctx context.Context, id uint64) (BoardColumn, error)

BoardColumnByID returns the column with the given ID. It fails with TagNotFound when there is none.

func (*Store) CallByID added in v1.2.0

func (s *Store) CallByID(ctx context.Context, id uint64) (Call, error)

CallByID returns the call with the given ID. It fails with TagNotFound when there is none.

func (*Store) CallsByIDs added in v1.2.0

func (s *Store) CallsByIDs(ctx context.Context, ids []uint64) (map[uint64]Call, error)

CallsByIDs returns the calls with these IDs, by ID, with one query. An ID that is no call has no key in the map.

func (*Store) Close

func (s *Store) Close() error

Close closes the database. Call it once, after everything that uses the Store has stopped. On the Store that Tx passes to its function it does nothing.

func (*Store) CommentCounts

func (s *Store) CommentCounts(ctx context.Context, postIDs []uint64) (map[uint64]int, error)

CommentCounts returns the number of comments of each of the posts (the comments whose RootID is the post and that are not deleted), at any depth, with one query. A post without comments has no key in the map.

func (*Store) ConsumeSSHCode added in v1.2.0

func (s *Store) ConsumeSSHCode(ctx context.Context, userID uint64, codeHash string, now time.Time) (SSHCode, error)

ConsumeSSHCode marks the code of the user with the hash as used, and returns it, when it is unused, not replaced and not expired at now. The marking is one conditional update, so that a code is used once even when two requests race: the loser finds no row to change. It fails with TagNotFound when no such code exists. The login with the SSH code (Accounts.LoginClient and Accounts.CompleteLogin) calls it inside the transaction that starts the session.

func (*Store) ConversationByID

func (s *Store) ConversationByID(ctx context.Context, id uint64) (Conversation, error)

ConversationByID returns the conversation with the given ID. It fails with TagNotFound when there is none.

func (*Store) ConversationMemberOf

func (s *Store) ConversationMemberOf(ctx context.Context, conversationID, userID uint64) (ConversationMember, error)

ConversationMemberOf returns the membership of the user in the conversation, one that has left included. It fails with TagNotFound when there is none.

func (*Store) ConversationMembers

func (s *Store) ConversationMembers(ctx context.Context, conversationIDs []uint64, withLeft bool) (map[uint64][]ConversationMemberRow, error)

ConversationMembers returns the members of the conversations with the users they are, in the order they joined, with one query. Members who left are included only when withLeft is true. A conversation without members has no key in the map.

func (*Store) ConversationRecipients added in v1.2.0

func (s *Store) ConversationRecipients(ctx context.Context, conversationID, exceptUserID uint64) ([]Recipient, error)

ConversationRecipients returns, in one query, the current members of the conversation who are not disabled, except exceptUserID, with their settings and their preferences in the conversation.

func (*Store) CountActiveAdmins

func (s *Store) CountActiveAdmins(ctx context.Context) (int64, error)

CountActiveAdmins returns the number of users with the admin role who are not disabled.

func (*Store) CountOpenCallsOfHome added in v1.2.0

func (s *Store) CountOpenCallsOfHome(ctx context.Context, home string) (int64, error)

CountOpenCallsOfHome returns the number of open calls whose media the process home holds.

func (*Store) CountPendingLogins added in v1.2.0

func (s *Store) CountPendingLogins(ctx context.Context) (int64, error)

CountPendingLogins returns the number of pending logins, expired ones included.

func (*Store) CountSSHCodesSince added in v1.2.0

func (s *Store) CountSSHCodesSince(ctx context.Context, userID uint64, since time.Time) (int64, error)

CountSSHCodesSince returns how many codes of the user were made at or after since, replaced and used ones included.

func (*Store) CountSSHKeysOfUser added in v1.2.0

func (s *Store) CountSSHKeysOfUser(ctx context.Context, userID uint64) (int64, error)

CountSSHKeysOfUser returns the number of keys of the user.

func (*Store) CountSessionsOfUser

func (s *Store) CountSessionsOfUser(ctx context.Context, userID uint64) (int64, error)

CountSessionsOfUser returns the number of sessions of the user, expired or not.

func (*Store) CountUnreadConversations

func (s *Store) CountUnreadConversations(ctx context.Context, userID uint64) (int, error)

CountUnreadConversations returns the number of conversations of the user that have a message of someone else, not deleted, after the last message the user read. A conversation the user left or muted is not counted (SPEC §7.15). It is one query.

func (*Store) CountUnreadNotifications

func (s *Store) CountUnreadNotifications(ctx context.Context, userID uint64) (int, error)

CountUnreadNotifications returns the number of unread notifications of the user whose room the user can read.

func (*Store) CountUsedSSHKeysOfUser added in v1.2.0

func (s *Store) CountUsedSSHKeysOfUser(ctx context.Context, userID uint64) (int64, error)

CountUsedSSHKeysOfUser returns how many keys of the user have fetched a code (their last use is set).

func (*Store) CreateAttachments

func (s *Store) CreateAttachments(ctx context.Context, rows []Attachment) error

CreateAttachments inserts the rows and sets their IDs and CreatedAt (the time of the Store's clock). No rows is a no-op. It fails with TagConflict when a storage key is already used by another attachment and with TagQueryFailed when a post or an uploader does not exist.

func (*Store) CreateAuditEvent

func (s *Store) CreateAuditEvent(ctx context.Context, ev *AuditEvent) error

CreateAuditEvent inserts ev and sets its ID and CreatedAt (the time of the Store's clock). Services call it inside the transaction of the change it records. It fails with TagConflict when the ID is taken, and with TagQueryFailed when the actor does not exist or Details is not valid JSON.

func (*Store) CreateBoardColumns

func (s *Store) CreateBoardColumns(ctx context.Context, columns []BoardColumn) error

CreateBoardColumns inserts the columns and sets their IDs.

func (*Store) CreateCall added in v1.2.0

func (s *Store) CreateCall(ctx context.Context, c *Call) error

CreateCall inserts the call and sets its ID and CreatedAt. It fails with TagConflict when the caller or the callee already has an open call: raw migration 0007 makes that a unique violation, the last guard behind the check that Calls.Start makes.

func (*Store) CreateConversation

func (s *Store) CreateConversation(ctx context.Context, c *Conversation) error

CreateConversation inserts the conversation and sets its ID and CreatedAt. It fails with TagConflict when a direct conversation with the same DirectKey exists.

func (*Store) CreateConversationMembers

func (s *Store) CreateConversationMembers(ctx context.Context, rows []ConversationMember) error

CreateConversationMembers inserts the memberships. No rows is a no-op. It fails with TagConflict when a user is already in the conversation.

func (*Store) CreateInvitation

func (s *Store) CreateInvitation(ctx context.Context, inv *Invitation) error

CreateInvitation inserts inv and sets its ID. It fails with TagConflict when the token hash is already taken.

func (*Store) CreateMessage

func (s *Store) CreateMessage(ctx context.Context, m *Message) error

CreateMessage inserts the message, sets its ID and CreatedAt, and adds its body to the full-text index of messages (SPEC D56) in the same transaction when the caller runs it in one.

func (*Store) CreateMessageAttachments

func (s *Store) CreateMessageAttachments(ctx context.Context, rows []MessageAttachment) error

CreateMessageAttachments inserts the rows and sets their IDs and CreatedAt. No rows is a no-op. It fails with TagConflict when a storage key is already used by another attachment.

func (*Store) CreateNotifications

func (s *Store) CreateNotifications(ctx context.Context, rows []Notification) error

CreateNotifications inserts the rows and sets their IDs and CreatedAt (the time of the Store's clock). It does nothing for no rows. It fails with TagQueryFailed when a user, post, task or room does not exist.

func (*Store) CreatePendingLogin added in v1.2.0

func (s *Store) CreatePendingLogin(ctx context.Context, p *PendingLogin, now time.Time) error

CreatePendingLogin deletes the pending logins that have expired at now and inserts p, and sets its ID. Call it inside Tx.

func (*Store) CreatePost

func (s *Store) CreatePost(ctx context.Context, p *Post) error

CreatePost inserts p and sets its ID and CreatedAt (the time of the Store's clock). It fails with TagQueryFailed when the room, the author or the parent does not exist.

func (*Store) CreateRoom

func (s *Store) CreateRoom(ctx context.Context, r *Room) error

CreateRoom inserts r and sets its ID. It fails with TagConflict when the name is taken (the unique index ignores the case of the letters a to z).

func (*Store) CreateRoomMember

func (s *Store) CreateRoomMember(ctx context.Context, m *RoomMember) error

CreateRoomMember inserts m, sets its ID, and makes the member's row in room_reads at the room's highest ID so far, so that a new member starts with nothing unread (SPEC §7.17, D55). Call it inside Store.Tx so that both writes are one: the services do. It fails with TagConflict when the user is a member of the room already.

func (*Store) CreateSSHKey added in v1.2.0

func (s *Store) CreateSSHKey(ctx context.Context, k *SSHKey) error

CreateSSHKey inserts k and sets its ID. It fails with TagConflict when the fingerprint is already registered, by anyone.

func (*Store) CreateSession

func (s *Store) CreateSession(ctx context.Context, sess *Session) error

CreateSession inserts sess and sets its ID. It fails with TagConflict when the token hash is already taken.

func (*Store) CreateTask

func (s *Store) CreateTask(ctx context.Context, t *Task) error

CreateTask inserts t and sets its ID and CreatedAt. It fails with TagQueryFailed when the room, the post or the column does not exist.

func (*Store) CreateUser

func (s *Store) CreateUser(ctx context.Context, u *User) error

CreateUser inserts u and sets its ID. It fails with TagConflict when the username is taken.

func (*Store) DeleteAttachments

func (s *Store) DeleteAttachments(ctx context.Context, ids []uint64) error

DeleteAttachments deletes the rows with these IDs. No IDs is a no-op; an ID that does not exist is ignored.

func (*Store) DeleteBoardColumn

func (s *Store) DeleteBoardColumn(ctx context.Context, id uint64) error

DeleteBoardColumn deletes the column id. The tasks of the column cascade: the application deletes a column only when it has none. It fails with TagNotFound when there is no such column.

func (*Store) DeleteExpiredSessionsOfUser

func (s *Store) DeleteExpiredSessionsOfUser(ctx context.Context, userID uint64, now time.Time) error

DeleteExpiredSessionsOfUser deletes the sessions of the user that expired at or before now (a session is over from its ExpiresAt on). The other sessions of the user and the sessions of other users stay. It is not an error when there are none.

func (*Store) DeleteMessageExtras

func (s *Store) DeleteMessageExtras(ctx context.Context, id uint64) error

DeleteMessageExtras deletes the attachment rows and the reactions of the message. The files on disk are not touched.

func (*Store) DeleteMessageReaction added in v1.1.0

func (s *Store) DeleteMessageReaction(ctx context.Context, messageID, userID uint64, emoji string) (bool, error)

DeleteMessageReaction removes the reaction (message, user, emoji) when it is there and does nothing when it is not. It returns true when it was removed.

func (*Store) DeletePendingLogin added in v1.2.0

func (s *Store) DeletePendingLogin(ctx context.Context, id uint64) (deleted bool, err error)

DeletePendingLogin deletes the pending login with the ID, and reports whether there was one to delete.

func (*Store) DeletePendingLoginsOfUser added in v1.2.0

func (s *Store) DeletePendingLoginsOfUser(ctx context.Context, userID uint64) error

DeletePendingLoginsOfUser deletes every pending login of the user: a change of the password and the disabling of the user end the logins that wait for a code. It is not an error when there are none.

func (*Store) DeletePlacePref added in v1.2.0

func (s *Store) DeletePlacePref(ctx context.Context, userID uint64, place PlaceKey) error

DeletePlacePref deletes the preferences of the user in the place. It does nothing when there are none.

func (*Store) DeletePost

func (s *Store) DeletePost(ctx context.Context, id uint64) error

DeletePost deletes the row of the post id. Everything that hangs on it (tags, reactions, mentions, attachments, tasks and its comments) cascades. It fails with TagNotFound when there is no such post.

func (*Store) DeletePostExtras

func (s *Store) DeletePostExtras(ctx context.Context, id uint64) error

DeletePostExtras deletes the tag links, reactions, mentions, attachments and notifications of the post id and leaves the post itself. It is for a post that stays as a deleted placeholder (D21). It does not touch the tasks of the post: the service deletes them one by one, to audit them and to close the gaps they leave in the columns.

func (*Store) DeleteReaction added in v1.1.0

func (s *Store) DeleteReaction(ctx context.Context, postID, userID uint64, emoji string) (bool, error)

DeleteReaction removes the reaction (post, user, emoji) when it is there and does nothing when it is not. It returns true when it was removed.

func (*Store) DeleteRoom

func (s *Store) DeleteRoom(ctx context.Context, id uint64) error

DeleteRoom deletes the room id with everything that belongs to it (members, columns, posts and the rest cascade). Audit events have no foreign key and stay. It fails with TagNotFound when there is no such room.

func (*Store) DeleteRoomMember

func (s *Store) DeleteRoomMember(ctx context.Context, id uint64) error

DeleteRoomMember deletes the membership id and the member's row in room_reads (SPEC §7.17). Call it inside Store.Tx so that both writes are one: the services do. It fails with TagNotFound when there is no such membership.

func (*Store) DeleteSSHKey added in v1.2.0

func (s *Store) DeleteSSHKey(ctx context.Context, id uint64) error

DeleteSSHKey deletes the key with the ID; its codes go with it. It fails with TagNotFound when there is none.

func (*Store) DeleteSessionByTokenHash

func (s *Store) DeleteSessionByTokenHash(ctx context.Context, tokenHash string) error

DeleteSessionByTokenHash deletes the session with the given token hash, which logs that browser out. It is not an error when there is none.

func (*Store) DeleteSessionOfUser added in v1.1.0

func (s *Store) DeleteSessionOfUser(ctx context.Context, userID, id uint64) error

DeleteSessionOfUser deletes the session id when it belongs to the user. It fails with TagNotFound when there is no such session or it belongs to another user, so that a caller cannot tell the two apart.

func (*Store) DeleteSessionsOfUser

func (s *Store) DeleteSessionsOfUser(ctx context.Context, userID uint64) error

DeleteSessionsOfUser deletes every session of the user, which logs the user out everywhere. It is not an error when there are none.

func (*Store) DeleteSessionsOfUserExcept added in v1.2.0

func (s *Store) DeleteSessionsOfUserExcept(ctx context.Context, userID, keep uint64) (int64, error)

DeleteSessionsOfUserExcept deletes every session of the user but the one with the ID keep, which logs the user out everywhere else. It is not an error when there are none. It returns how many it deleted.

func (*Store) DeleteTasks

func (s *Store) DeleteTasks(ctx context.Context, ids []uint64) error

DeleteTasks deletes the tasks with these IDs and their assignees. IDs that do not exist are ignored.

func (*Store) DirectConversation

func (s *Store) DirectConversation(ctx context.Context, directKey string) (Conversation, error)

DirectConversation returns the direct conversation with the given DirectKey (see DirectKeyOf). It fails with TagNotFound when there is none.

func (*Store) DistinctRepliers added in v1.2.0

func (s *Store) DistinctRepliers(ctx context.Context, rootID, fromPostID, exceptA, exceptB uint64) (int, error)

DistinctRepliers returns how many different users, other than the two given (the follower and the latest actor), wrote a comment that is not deleted in the thread rootID with an ID of fromPostID or more: the people who replied since the burst began.

func (*Store) EnabledReaders

func (s *Store) EnabledReaders(ctx context.Context, roomID uint64, private bool, userIDs []uint64) (map[uint64]bool, error)

EnabledReaders returns, of the users userIDs, the set of those who are not disabled and can read the room: every enabled user for a visible room, only the members when private is true. Users who do not exist are left out.

func (*Store) EnabledUserSet added in v1.2.0

func (s *Store) EnabledUserSet(ctx context.Context, userIDs []uint64) (map[uint64]bool, error)

EnabledUserSet returns, of the users userIDs, the set of those who exist and are not disabled.

func (*Store) EnabledUsersByUsername

func (s *Store) EnabledUsersByUsername(ctx context.Context, roomID uint64, private bool, usernames []string) ([]User, error)

EnabledUsersByUsername returns the users who are not disabled and whose username is one of usernames (already lower-cased), and who can read the room: every one of them for a visible room, only its members when private is true. It is how the mentions of a post are resolved (SPEC D26, D30). The order of the result is by username.

func (*Store) FoldReply added in v1.2.0

func (s *Store) FoldReply(ctx context.Context, id, actorID uint64, others int) error

FoldReply makes the notification id name actorID as its latest actor and count others more people. It does nothing when the notification is gone.

func (*Store) FoldableReply added in v1.2.0

func (s *Store) FoldableReply(ctx context.Context, userID, rootID uint64) (Notification, bool, error)

FoldableReply returns the newest unread reply notification of the user for the thread rootID that was made less than a minute ago (by the Store's clock), and whether there is one. The burst is counted from the creation of that notification.

func (*Store) FollowingPosts added in v1.2.0

func (s *Store) FollowingPosts(ctx context.Context, userID uint64, postIDs []uint64) (map[uint64]bool, error)

FollowingPosts returns, of the top-level posts postIDs, the set of those the user follows.

func (*Store) IndexRows

func (s *Store) IndexRows(ctx context.Context) (map[uint64]string, error)

IndexRows returns the text that the full-text index holds for each post ID. It is for diagnostics and tests: searches go through SearchPosts.

func (*Store) InvitationByTokenHash

func (s *Store) InvitationByTokenHash(ctx context.Context, tokenHash string) (Invitation, error)

InvitationByTokenHash returns the invitation whose token has the given SHA-256 hash. It fails with TagNotFound when there is none.

func (*Store) IsPostgres added in v1.2.0

func (s *Store) IsPostgres() bool

IsPostgres reports whether the Store runs on PostgreSQL.

func (*Store) IsRoomMember

func (s *Store) IsRoomMember(ctx context.Context, roomID, userID uint64) (bool, error)

IsRoomMember reports whether the user is a member of the room.

func (*Store) IssueSSHCode added in v1.2.0

func (s *Store) IssueSSHCode(ctx context.Context, c *SSHCode, olderThan time.Time) error

IssueSSHCode stores the code c and sets its ID. In one go it marks the unused codes of the user as replaced and deletes the codes made before olderThan (SSHCodeRetention before now). Call it inside Tx.

func (*Store) ListAuditEvents

func (s *Store) ListAuditEvents(ctx context.Context, filter AuditFilter, limit, offset int) ([]AuditEvent, error)

ListAuditEvents returns the events that match filter, newest first (by ID), at most limit of them after skipping offset. Each event has its Actor loaded. The room and actor filters use the indexes of the table.

func (*Store) ListBoardColumns

func (s *Store) ListBoardColumns(ctx context.Context, roomID uint64) ([]BoardColumn, error)

ListBoardColumns returns the columns of the room from left to right.

func (*Store) ListConversations

func (s *Store) ListConversations(ctx context.Context, userID uint64) ([]ConversationListItem, error)

ListConversations returns the conversations the user is a member of, with the last message, the unread mark and the members of each, in no particular order. It runs at most four queries, however many conversations there are.

func (*Store) ListFeed

func (s *Store) ListFeed(ctx context.Context, roomID, beforeID uint64, limit int) ([]Post, error)

ListFeed returns the top-level posts of the room, newest first (by ID), at most limit of them, with Author loaded. A beforeID other than 0 keeps only the posts with a smaller ID. Posts kept as deleted placeholders are included. It uses the index idx_posts_feed.

func (*Store) ListNotifications

func (s *Store) ListNotifications(ctx context.Context, userID, beforeID uint64, limit int) ([]NotificationRow, error)

ListNotifications returns the notifications of the user whose room the user can read, newest first (by ID), at most limit of them. A beforeID other than 0 keeps only those with a smaller ID.

func (*Store) ListRoomMembers

func (s *Store) ListRoomMembers(ctx context.Context, roomID uint64) ([]RoomMember, error)

ListRoomMembers returns the memberships of the room, ordered by the display name of the user, with User and Adder loaded.

func (*Store) ListRooms

func (s *Store) ListRooms(ctx context.Context) ([]Room, error)

ListRooms returns every room, ordered by name.

func (*Store) ListRoomsOfUser

func (s *Store) ListRoomsOfUser(ctx context.Context, userID uint64) ([]Room, error)

ListRoomsOfUser returns the rooms the user is a member of, visible and private, ordered by name.

func (*Store) ListTags

func (s *Store) ListTags(ctx context.Context) ([]Tag, error)

ListTags returns every tag, ordered by ID.

func (*Store) ListTasksOfColumn

func (s *Store) ListTasksOfColumn(ctx context.Context, columnID uint64) ([]Task, error)

ListTasksOfColumn returns the tasks of the column from top to bottom.

func (*Store) ListUsers

func (s *Store) ListUsers(ctx context.Context) ([]User, error)

ListUsers returns every user, ordered by username.

func (*Store) ListVisibleRooms

func (s *Store) ListVisibleRooms(ctx context.Context) ([]Room, error)

ListVisibleRooms returns the rooms with visibility visible, ordered by name.

func (*Store) LockAdmins added in v1.1.0

func (s *Store) LockAdmins(ctx context.Context) error

LockAdmins makes the rest of the transaction the only one that changes the admins: another transaction that calls it waits until this one ends. A change that must leave one active admin (SPEC §7.1) calls it first and then reads the admins, so that two of them, in one process or in two, cannot each see the other admin and both remove an admin. Call it inside Tx. On SQLite it does nothing, because a write transaction is already alone (BEGIN IMMEDIATE).

func (*Store) LockUser added in v1.2.0

func (s *Store) LockUser(ctx context.Context, userID uint64) error

LockUser makes the rest of the transaction the only one that changes the keys and codes of the user: another transaction that calls it for the same user waits until this one ends. A change that checks a limit (10 keys, 10 codes in 15 minutes) calls it first. Call it inside Tx. On SQLite it does nothing, because a write transaction is already alone.

func (*Store) LockUsersForCall added in v1.2.0

func (s *Store) LockUsersForCall(ctx context.Context, userIDs ...uint64) error

LockUsersForCall makes the rest of the transaction the only one that starts or answers a call of these users: on PostgreSQL it locks their rows, in the order of their IDs so that two transactions cannot wait for each other, and another transaction that locks one of them waits until this one ends. A start reads the open calls of both users and then writes only after it called this, so that two calls started at the same time cannot both ring. Call it inside Tx. On SQLite it does nothing, because a write transaction is already alone (BEGIN IMMEDIATE).

func (*Store) MarkCallAnswered added in v1.2.0

func (s *Store) MarkCallAnswered(ctx context.Context, id uint64, at time.Time) (bool, error)

MarkCallAnswered moves the call from ringing to active and sets AnsweredAt. It returns false, and changes nothing, when the call is not ringing.

func (*Store) MarkCallEnded added in v1.2.0

func (s *Store) MarkCallEnded(ctx context.Context, id uint64, reason CallEndReason, by *uint64, at time.Time) (bool, error)

MarkCallEnded ends the call: state, time, reason and who ended it (nil when the system did). It returns false, and changes nothing, when the call has ended already.

func (*Store) MarkConversationMemberLeft

func (s *Store) MarkConversationMemberLeft(ctx context.Context, conversationID, userID uint64, at time.Time) error

MarkConversationMemberLeft sets LeftAt of the membership.

func (*Store) MarkInvitationUsed

func (s *Store) MarkInvitationUsed(ctx context.Context, id, userID uint64) error

MarkInvitationUsed records that the user userID used the invitation id, at the time of the Store's clock. It fails with TagNotFound when there is no such invitation or it was used already, so that one invitation never makes two users.

func (*Store) MarkMessageDeleted

func (s *Store) MarkMessageDeleted(ctx context.Context, id uint64, at time.Time) error

MarkMessageDeleted clears the body of the message and sets DeletedAt, and removes the message from the full-text index of messages. The row stays, so that the conversation keeps its shape.

func (*Store) MarkNotificationsRead

func (s *Store) MarkNotificationsRead(ctx context.Context, userID, upToID uint64) (int, error)

MarkNotificationsRead sets ReadAt, to the time of the Store's clock, on the unread notifications of the user with an ID up to upToID, and returns how many it changed. Notifications of other users are never touched.

func (*Store) MarkPasswordResetUsed added in v1.2.0

func (s *Store) MarkPasswordResetUsed(ctx context.Context, id uint64) error

MarkPasswordResetUsed records that the reset link id was used, at the time of the Store's clock. It fails with TagNotFound when there is no such link or it was used already, so that one link never sets two passwords.

func (*Store) MarkPostDeleted

func (s *Store) MarkPostDeleted(ctx context.Context, id uint64, at time.Time) error

MarkPostDeleted keeps the post id as a deleted placeholder (D21): it sets DeletedAt to at and empties the body. It fails with TagNotFound when there is no such post.

func (*Store) MarkRoomMentionsRead added in v1.2.0

func (s *Store) MarkRoomMentionsRead(ctx context.Context, userID, roomID uint64) (int, error)

MarkRoomMentionsRead sets ReadAt, to the time of the Store's clock, on the unread notifications of the user in the room that are mentions (the kinds mention, group_mention and keyword), and returns how many it changed.

func (*Store) MemberUsernames

func (s *Store) MemberUsernames(ctx context.Context, roomID uint64, userIDs []uint64) (map[uint64]string, error)

MemberUsernames returns, for those of the users who are members of the room, their usernames by user ID. A user who is not a member, or does not exist, has no key in the map.

func (*Store) MentionedUsernamesOfPosts

func (s *Store) MentionedUsernamesOfPosts(ctx context.Context, postIDs []uint64) (map[uint64][]string, error)

MentionedUsernamesOfPosts returns the usernames mentioned by "@username" in each of the posts (not those reached by a group mention or a keyword), in the order the mentions were saved, with one query. A post without mentions has no key in the map.

func (*Store) MessageAttachmentByID

func (s *Store) MessageAttachmentByID(ctx context.Context, id uint64) (MessageAttachment, error)

MessageAttachmentByID returns the attachment of a message with the given ID. It fails with TagNotFound when there is none.

func (*Store) MessageAttachmentsOf

func (s *Store) MessageAttachmentsOf(ctx context.Context, messageIDs []uint64) (map[uint64][]MessageAttachment, error)

MessageAttachmentsOf returns the attachments of each of the messages, oldest first (by ID), with one query. A message without attachments has no key in the map.

func (*Store) MessageByID

func (s *Store) MessageByID(ctx context.Context, id uint64) (Message, error)

MessageByID returns the message with the given ID. It fails with TagNotFound when there is none.

func (*Store) MessageIndexRows added in v1.2.0

func (s *Store) MessageIndexRows(ctx context.Context) (map[uint64]string, error)

MessageIndexRows returns the text that the full-text index of private messages holds for each message ID. It is for diagnostics and tests: searches go through SearchMessages.

func (*Store) MessagePage

func (s *Store) MessagePage(ctx context.Context, conversationID, beforeID uint64, limit int) ([]MessageRow, error)

MessagePage returns the messages of the conversation, newest first (by ID), at most limit of them. A beforeID other than 0 keeps only those with a smaller ID.

func (*Store) MessageRowsByIDs

func (s *Store) MessageRowsByIDs(ctx context.Context, ids []uint64) (map[uint64]MessageRow, error)

MessageRowsByIDs returns the messages with these IDs, by ID, with one query. An ID that is no message has no key in the map.

func (*Store) MoveRoomRead added in v1.2.0

func (s *Store) MoveRoomRead(ctx context.Context, userID, roomID, upToID uint64) (bool, error)

MoveRoomRead moves the mark of the user in the room forward to upToID. It never moves it back, and makes the row when the user has none. It reports whether the mark changed. The user must be a member of the room (the row has foreign keys, not a membership check).

func (*Store) OpenCallOfConversation added in v1.2.0

func (s *Store) OpenCallOfConversation(ctx context.Context, conversationID uint64) (Call, error)

OpenCallOfConversation returns the call of the conversation that is ringing or active. It fails with TagNotFound when there is none. A direct conversation has at most one: both its users are in one call at most.

func (*Store) OpenCalls added in v1.2.0

func (s *Store) OpenCalls(ctx context.Context, home string) ([]Call, error)

OpenCalls returns every open call, oldest first. With home set it returns the open calls of that process only.

func (*Store) OpenCallsOfUsers added in v1.2.0

func (s *Store) OpenCallsOfUsers(ctx context.Context, userIDs ...uint64) ([]Call, error)

OpenCallsOfUsers returns the calls, ringing or active, in which any of these users is the caller or the callee, oldest first.

func (*Store) PasswordResetByTokenHash added in v1.2.0

func (s *Store) PasswordResetByTokenHash(ctx context.Context, tokenHash string) (PasswordReset, error)

PasswordResetByTokenHash returns the reset link whose token has the given SHA-256 hash. It fails with TagNotFound when there is none.

func (*Store) PendingLoginByTokenHash added in v1.2.0

func (s *Store) PendingLoginByTokenHash(ctx context.Context, tokenHash string) (PendingLogin, error)

PendingLoginByTokenHash returns the pending login whose token has the hash. It fails with TagNotFound when there is none. It does not look at the expiry.

func (*Store) Ping added in v1.1.0

func (s *Store) Ping(ctx context.Context) error

Ping checks that the database answers, within ctx. It is what the health check of the server asks (SPEC D40).

func (*Store) PlacePrefOf added in v1.2.0

func (s *Store) PlacePrefOf(ctx context.Context, userID uint64, place PlaceKey) (PlacePref, bool, error)

PlacePrefOf returns the preferences of the user in the place, and whether the user has any: without a row it returns the defaults and false. It does not check that the user or the place exists.

func (*Store) PlacePrefsOfUser added in v1.2.0

func (s *Store) PlacePrefsOfUser(ctx context.Context, userID uint64) ([]PlacePref, error)

PlacePrefsOfUser returns every row of preferences of the user, rooms first, then conversations, each by ID.

func (*Store) PoolStats added in v1.2.0

func (s *Store) PoolStats() sql.DBStats

PoolStats returns the statistics of the connection pool: the connections open, in use and idle, and how often and how long a query waited for one (SPEC D60). It is the zero value in the Store of a transaction.

func (*Store) PostByID

func (s *Store) PostByID(ctx context.Context, id uint64) (Post, error)

PostByID returns the post with the given ID, with Author loaded. A deleted post that is kept for its replies is returned too (its DeletedAt is set). It fails with TagNotFound when there is none.

func (*Store) PostHasReplies

func (s *Store) PostHasReplies(ctx context.Context, id uint64) (bool, error)

PostHasReplies reports whether some comment has the post id as its parent.

func (*Store) PostMentions added in v1.2.0

func (s *Store) PostMentions(ctx context.Context, postID uint64) ([]MentionedUser, error)

PostMentions returns the users the post mentions, with how, in the order the mentions were saved.

func (*Store) PutMessageReaction added in v1.1.0

func (s *Store) PutMessageReaction(ctx context.Context, messageID, userID uint64, emoji string) (bool, error)

PutMessageReaction adds the reaction (message, user, emoji) when it is not there and leaves it when it is. It returns true when it was added. It fails with TagQueryFailed when the message or the user does not exist.

func (*Store) PutReaction added in v1.1.0

func (s *Store) PutReaction(ctx context.Context, postID, userID uint64, emoji string) (bool, error)

PutReaction adds the reaction (post, user, emoji) when it is not there and leaves it when it is. It returns true when it was added. It fails with TagQueryFailed when the post or the user does not exist.

func (*Store) ReactionsOfMessages

func (s *Store) ReactionsOfMessages(ctx context.Context, messageIDs []uint64) (map[uint64][]MessageReactionRow, error)

ReactionsOfMessages returns the reactions of each of the messages, oldest first (by ID), with the display names of the users, with one query. A message without reactions has no key in the map.

func (*Store) ReactionsOfPosts

func (s *Store) ReactionsOfPosts(ctx context.Context, postIDs []uint64) (map[uint64][]ReactionRow, error)

ReactionsOfPosts returns the reactions of each of the posts, oldest first (by ID), with the display names of the users, with one query. A post without reactions has no key in the map.

func (*Store) ReaddConversationMember

func (s *Store) ReaddConversationMember(ctx context.Context, conversationID, userID, addedBy uint64) error

ReaddConversationMember lets a member who left come back: LeftAt is cleared and AddedBy is set. The last read message stays.

func (*Store) RebuildMessageSearchIndex added in v1.2.0

func (s *Store) RebuildMessageSearchIndex(ctx context.Context) error

RebuildMessageSearchIndex makes the full-text index of private messages hold every message that is not deleted and has a body, in one statement: it empties the index and fills it again. The large demo calls it after it wrote rows in bulk. Call it in a transaction.

func (*Store) RebuildSearchIndex

func (s *Store) RebuildSearchIndex(ctx context.Context) error

RebuildSearchIndex makes the full-text index hold every post and comment that is not deleted, with the text ReindexPost would give it, in one statement: it empties the index and fills it again. The large demo calls it after BulkCreate wrote posts, attachments and tasks, which would otherwise each need a ReindexPost. Call it in a transaction.

func (*Store) RecipientsOf added in v1.2.0

func (s *Store) RecipientsOf(ctx context.Context, place PlaceKey, userIDs []uint64) ([]Recipient, error)

RecipientsOf returns, in one query, the given users who are not disabled with their settings and their preferences in the place. A user who does not exist is left out. It is what a notification needs.

func (*Store) ReindexMessage added in v1.2.0

func (s *Store) ReindexMessage(ctx context.Context, id uint64) error

ReindexMessage makes the full-text index of private messages hold the current text of the message id: it deletes the row of the message and, when the message exists, is not deleted and has a body, inserts the body. A missing or deleted message is simply removed from the index. CreateMessage, UpdateMessageBody and MarkMessageDeleted call it, so the index follows the message in the transaction they run in.

func (*Store) ReindexPost

func (s *Store) ReindexPost(ctx context.Context, id uint64) error

ReindexPost makes the full-text index hold the current text of the post id: it deletes the row of the post and, when the post exists and is not deleted, inserts its body, attachment names and task titles. A missing or deleted post is simply removed from the index. Call it in the transaction of every change that touches those texts.

func (*Store) ReplacePasswordReset added in v1.2.0

func (s *Store) ReplacePasswordReset(ctx context.Context, pr *PasswordReset) error

ReplacePasswordReset deletes the unused reset links of the user pr.UserID and inserts pr, so that a user has one unused link at most, and sets its ID. Call it inside Tx. It fails with TagConflict when the token hash is already taken.

func (*Store) ReplacePostMentions

func (s *Store) ReplacePostMentions(ctx context.Context, postID uint64, mentioned []MentionedUser) error

ReplacePostMentions makes mentioned the mentions of the post: the mentions of other users are deleted, the missing ones are added and a user who stays gets the new kind. The users must be without duplicates. It fails with TagQueryFailed when a user does not exist.

func (*Store) ReplacePostTags

func (s *Store) ReplacePostTags(ctx context.Context, postID uint64, names []string) error

ReplacePostTags makes names the tags of the post id, in that order: the tags that do not exist yet are created, the links of the post are replaced. The names must be normalized and without duplicates.

func (*Store) ReplaceTaskAssignees

func (s *Store) ReplaceTaskAssignees(ctx context.Context, taskID uint64, userIDs []uint64) error

ReplaceTaskAssignees makes userIDs the assignees of the task, in that order. The IDs must be without duplicates. It fails with TagQueryFailed when a user does not exist.

func (*Store) ResetRoomReads added in v1.2.0

func (s *Store) ResetRoomReads(ctx context.Context) error

ResetRoomReads moves every mark of every member of every room to the room's highest ID, so that nothing is unread. The large demo calls it after the bulk load, so that it starts clean.

func (*Store) RingingCallsBefore added in v1.2.0

func (s *Store) RingingCallsBefore(ctx context.Context, before time.Time) ([]Call, error)

RingingCallsBefore returns the calls that have been ringing since before the time, oldest first: those that Calls.Expire ends as missed.

func (*Store) RoomByID

func (s *Store) RoomByID(ctx context.Context, id uint64) (Room, error)

RoomByID returns the room with the given ID. It fails with TagNotFound when there is none.

func (*Store) RoomIDsOfUser

func (s *Store) RoomIDsOfUser(ctx context.Context, userID uint64) ([]uint64, error)

RoomIDsOfUser returns the IDs of the rooms the user is a member of.

func (*Store) RoomLastSeen added in v1.2.0

func (s *Store) RoomLastSeen(ctx context.Context, userID, roomID uint64) (uint64, bool, error)

RoomLastSeen returns the mark of the user in the room, and false when the user has no row there.

func (*Store) RoomMaxPostID added in v1.2.0

func (s *Store) RoomMaxPostID(ctx context.Context, roomID uint64) (uint64, error)

RoomMaxPostID returns the highest ID of a post or comment of the room, 0 when it has none. A deleted post counts: its ID was handed out.

func (*Store) RoomMemberCounts

func (s *Store) RoomMemberCounts(ctx context.Context, roomIDs []uint64) (map[uint64]int, error)

RoomMemberCounts returns the number of members of each of the rooms. A room without members has no key in the map.

func (*Store) RoomMemberIDs added in v1.2.0

func (s *Store) RoomMemberIDs(ctx context.Context, roomID, exceptUserID uint64) ([]uint64, error)

RoomMemberIDs returns the IDs of the users who are members of the room, except exceptUserID (0 for none), ordered by ID.

func (*Store) RoomMemberOf

func (s *Store) RoomMemberOf(ctx context.Context, roomID, userID uint64) (RoomMember, error)

RoomMemberOf returns the membership of the user in the room. It fails with TagNotFound when the user is not a member.

func (*Store) RoomMemberRecipients added in v1.2.0

func (s *Store) RoomMemberRecipients(ctx context.Context, roomID, exceptUserID uint64) ([]Recipient, error)

RoomMemberRecipients returns, in one query, the members of the room who are not disabled, except exceptUserID, with their settings and their preferences in the room. It is what a new post needs to decide whom it rings.

func (*Store) RoomNameTaken

func (s *Store) RoomNameTaken(ctx context.Context, name string, exceptID uint64) (bool, error)

RoomNameTaken reports whether another room than exceptID has the name, without regard to case. The case of any letter counts, not only a to z (the unique index of the table folds only a to z, so this is the stricter check). Pass 0 as exceptID to look at every room.

func (*Store) RoomPostCounts

func (s *Store) RoomPostCounts(ctx context.Context) ([]RoomPostCount, error)

RoomPostCounts returns, for each room that has posts or comments, how many it has, the busiest room first (a tie goes to the lower room ID). The benchmarks use it to pick the room to measure.

func (*Store) RoomUnreadCounts added in v1.2.0

func (s *Store) RoomUnreadCounts(ctx context.Context, userID uint64) ([]RoomUnread, error)

RoomUnreadCounts returns the unread counts of every room the user is a member of, in one query, ordered by room ID. A membership without a row in room_reads counts every post of others as unread.

func (*Store) RoomUnreadOf added in v1.2.0

func (s *Store) RoomUnreadOf(ctx context.Context, userID, roomID uint64) (RoomUnread, bool, error)

RoomUnreadOf returns the unread counts of the user in one room, and false when the user is not a member of it. It is the query of RoomUnreadCounts for one room.

func (*Store) RoomsOfUnreadMentions added in v1.2.0

func (s *Store) RoomsOfUnreadMentions(ctx context.Context, userID, upToID uint64) ([]uint64, error)

RoomsOfUnreadMentions returns the IDs of the rooms in which the user has an unread mention notification with an ID up to upToID, ordered by room ID. It is what the reading of notifications changes the counts of.

func (*Store) SSHKeyByFingerprint added in v1.2.0

func (s *Store) SSHKeyByFingerprint(ctx context.Context, fingerprint string) (SSHKey, error)

SSHKeyByFingerprint returns the key with the fingerprint. It fails with TagNotFound when there is none.

func (*Store) SSHKeyByID added in v1.2.0

func (s *Store) SSHKeyByID(ctx context.Context, id uint64) (SSHKey, error)

SSHKeyByID returns the key with the ID. It fails with TagNotFound when there is none.

func (*Store) SSHKeysOfUser added in v1.2.0

func (s *Store) SSHKeysOfUser(ctx context.Context, userID uint64) ([]SSHKey, error)

SSHKeysOfUser returns the keys of the user, oldest first.

func (*Store) SavePlacePref added in v1.2.0

func (s *Store) SavePlacePref(ctx context.Context, in *PlacePref) error

SavePlacePref writes the preferences in.UserID has in the place of in: it makes the row or replaces its values. It fails with TagQueryFailed when the user, the room or the conversation does not exist, when a value is not one of its choices, or when in names no place or two.

func (*Store) SaveUserSettings added in v1.2.0

func (s *Store) SaveUserSettings(ctx context.Context, in *UserSettings) error

SaveUserSettings writes the settings of in.UserID: it makes the row or replaces its values. It fails with TagQueryFailed when the user does not exist or a value is not one of its choices.

func (*Store) SchemaVersion added in v1.2.0

func (s *Store) SchemaVersion(ctx context.Context) (string, error)

SchemaVersion returns the ID of the last raw migration applied to the database, or "" when none has run. Open runs them all, so on a Store it is LatestMigration unless a newer binary migrated the database first.

func (*Store) SearchMessages added in v1.2.0

func (s *Store) SearchMessages(ctx context.Context, q MessageSearchQuery) ([]MessageSearchHit, error)

SearchMessages returns the messages that match q, newest first (by ID), in the conversations that q.ReaderID is a member of now, never a deleted one. The membership is part of the query, so a page holds q.Limit hits whenever that many exist: a message of a conversation the reader left, or never joined, is not a candidate. Every member of a conversation reads all its messages, the ones from before they joined included (SPEC §7.11), so those are found too.

func (*Store) SearchPosts

func (s *Store) SearchPosts(ctx context.Context, q SearchQuery) ([]SearchHit, error)

SearchPosts returns the non-deleted posts and comments that match q, in the rooms that q.ReaderID may read. With terms they are ordered by relevance (bm25), then newest first (by ID); without, newest first. The room, author, date, tag and kind filters use parameters only.

func (*Store) SessionByTokenHash

func (s *Store) SessionByTokenHash(ctx context.Context, tokenHash string) (Session, error)

SessionByTokenHash returns the session whose cookie token has the given SHA-256 hash. It fails with TagNotFound when there is none.

func (*Store) SessionsOfUser added in v1.1.0

func (s *Store) SessionsOfUser(ctx context.Context, userID uint64) ([]Session, error)

SessionsOfUser returns the sessions of the user, expired or not, newest first.

func (*Store) SetBoardColumnPosition

func (s *Store) SetBoardColumnPosition(ctx context.Context, id uint64, position int) error

SetBoardColumnPosition sets the position of the column id. It fails with TagNotFound when there is no such column.

func (*Store) SetConversationName

func (s *Store) SetConversationName(ctx context.Context, id uint64, name string) error

SetConversationName sets the name of the conversation; empty for none.

func (*Store) SetFollow added in v1.2.0

func (s *Store) SetFollow(ctx context.Context, userID, postID uint64, following bool) error

SetFollow makes the user follow the post (following true) or not (false), whatever the row said before. Not following keeps a row, so that an automatic follow does not undo it. It fails with TagQueryFailed when the user or the post does not exist.

func (*Store) SetSSHCodeRequired added in v1.2.0

func (s *Store) SetSSHCodeRequired(ctx context.Context, userID uint64, required bool) (changed bool, err error)

SetSSHCodeRequired sets whether the user is asked for an SSH code at login, and reports whether the value changed. It makes the user's settings row when there is none. It does not check that the user exists. Call it inside Tx when the change goes with an audit event.

func (*Store) SetTaskPlacement

func (s *Store) SetTaskPlacement(ctx context.Context, id, columnID uint64, position int) error

SetTaskPlacement puts the task id in the column at the position. It fails with TagNotFound when there is no such task.

func (*Store) SetUserAvatarKey added in v1.2.0

func (s *Store) SetUserAvatarKey(ctx context.Context, id uint64, key string) error

SetUserAvatarKey sets the avatar key of the user id; an empty key removes the avatar. It fails with TagNotFound when there is no such user.

func (*Store) SetUserDisabled

func (s *Store) SetUserDisabled(ctx context.Context, id uint64, disabled bool) error

SetUserDisabled disables the user id, at the time of the Store's clock, or enables it. It fails with TagNotFound when there is no such user.

func (*Store) SetUserDisplayName added in v1.2.0

func (s *Store) SetUserDisplayName(ctx context.Context, id uint64, displayName string) error

SetUserDisplayName sets the display name of the user id. It fails with TagNotFound when there is no such user.

func (*Store) SetUserPasswordHash added in v1.2.0

func (s *Store) SetUserPasswordHash(ctx context.Context, id uint64, hash string) error

SetUserPasswordHash replaces the password hash of the user id. It fails with TagNotFound when there is no such user.

func (*Store) SetUserRole

func (s *Store) SetUserRole(ctx context.Context, id uint64, role Role) error

SetUserRole gives the user id the role. It fails with TagNotFound when there is no such user.

func (*Store) Stats

func (s *Store) Stats(ctx context.Context) (Stats, error)

Stats counts the rows of the main tables and runs the consistency checks of the Stats fields. On a large database it takes a second or two.

func (*Store) StorageKeysInUse

func (s *Store) StorageKeysInUse(ctx context.Context, keys []string) ([]string, error)

StorageKeysInUse returns those of the keys that some attachment row, of a post or of a message, uses, in no particular order.

func (*Store) SuggestTagNames

func (s *Store) SuggestTagNames(ctx context.Context, userID uint64, prefix string, limit int) ([]string, error)

SuggestTagNames returns at most limit tag names that start with prefix and are used on a post in a room that the user may read (a visible room, or a room the user is a member of), ordered by name. The prefix is compared exactly: callers normalize it first.

func (*Store) TagNamesOfPosts

func (s *Store) TagNamesOfPosts(ctx context.Context, postIDs []uint64) (map[uint64][]string, error)

TagNamesOfPosts returns the tag names of each of the posts, in the order they were given to the post, with one query. A post without tags has no key in the map.

func (*Store) TaskByID

func (s *Store) TaskByID(ctx context.Context, id uint64) (Task, error)

TaskByID returns the task with the given ID. It fails with TagNotFound when there is none.

func (*Store) TaskRowsOfPosts

func (s *Store) TaskRowsOfPosts(ctx context.Context, postIDs []uint64) (map[uint64][]TaskRow, error)

TaskRowsOfPosts returns the tasks of each of the posts, oldest first (by ID), with their assignees, with two queries. A post without tasks has no key in the map.

func (*Store) TaskRowsOfRoom

func (s *Store) TaskRowsOfRoom(ctx context.Context, roomID uint64) ([]TaskRow, error)

TaskRowsOfRoom returns the tasks of the room ordered by column, then by position, with their assignees, with three queries. Rows of one column are together.

func (*Store) ThreadComments

func (s *Store) ThreadComments(ctx context.Context, rootID uint64) ([]Post, error)

ThreadComments returns every comment of the thread of the post rootID, at any depth, oldest first (by ID), with Author loaded, with one query on the index idx_posts_thread. Comments kept as deleted placeholders are included. The post itself is not.

func (*Store) ThreadFollowers added in v1.2.0

func (s *Store) ThreadFollowers(ctx context.Context, rootID, exceptUserID uint64) ([]uint64, error)

ThreadFollowers returns the IDs of the users who follow the top-level post rootID, except exceptUserID, who are not disabled and whose setting for replies is "following" (a user who has no settings has the default). Their order is by user ID.

func (*Store) ToggleMessageReaction

func (s *Store) ToggleMessageReaction(ctx context.Context, messageID, userID uint64, emoji string) (bool, error)

ToggleMessageReaction adds the reaction (message, user, emoji) when it is not there and removes it when it is. It returns true when the reaction was added and false when it was removed. It fails with TagConflict when a concurrent write added the same reaction first.

func (*Store) ToggleReaction

func (s *Store) ToggleReaction(ctx context.Context, postID, userID uint64, emoji string) (bool, error)

ToggleReaction adds the reaction (post, user, emoji) when it is not there and removes it when it is. It returns true when the reaction was added and false when it was removed. It fails with TagConflict when a concurrent write added the same reaction first, and with TagQueryFailed when the post or the user does not exist.

func (*Store) TouchSSHKey added in v1.2.0

func (s *Store) TouchSSHKey(ctx context.Context, id uint64, at time.Time) error

TouchSSHKey sets the last use of the key to at. It does nothing for a key that is gone.

func (*Store) TouchSession

func (s *Store) TouchSession(ctx context.Context, id uint64, lastSeenAt, expiresAt time.Time) error

TouchSession sets when the session id was last used and when it expires. It fails with TagNotFound when there is no such session.

func (*Store) Tx

func (s *Store) Tx(ctx context.Context, fn func(tx *Store) error) error

Tx runs fn in one transaction. It commits when fn returns nil. When fn returns an error, Tx rolls back and returns that error as it is, without wrapping it. When fn panics, Tx rolls back and the panic goes on. fn must use the Store it is given, not the one Tx was called on. Called on that Store, Tx nests: the inner transaction is a savepoint.

func (*Store) UnindexRoom

func (s *Store) UnindexRoom(ctx context.Context, roomID uint64) error

UnindexRoom removes every post and comment of the room from the full-text index. Call it in the transaction that deletes the room, before the room goes.

func (*Store) UpdateBoardColumnName

func (s *Store) UpdateBoardColumnName(ctx context.Context, id uint64, name string) error

UpdateBoardColumnName sets the name of the column id. It fails with TagNotFound when there is no such column.

func (*Store) UpdateMessageBody

func (s *Store) UpdateMessageBody(ctx context.Context, id uint64, body string, editedAt time.Time) error

UpdateMessageBody sets the body and EditedAt of the message, and makes the full-text index of messages hold the new body in place of the old one.

func (*Store) UpdatePostContent

func (s *Store) UpdatePostContent(ctx context.Context, id uint64, format Format, body string, editedAt time.Time) error

UpdatePostContent sets the format and the body of the post id and the time of the edit. It fails with TagNotFound when there is no such post.

func (*Store) UpdateRoomText

func (s *Store) UpdateRoomText(ctx context.Context, id uint64, name, description string) error

UpdateRoomText sets the name and the description of the room id. It fails with TagNotFound when there is no such room and with TagConflict when the name is taken.

func (*Store) UpdateTaskFields

func (s *Store) UpdateTaskFields(ctx context.Context, id uint64, title string, dueDate *time.Time) error

UpdateTaskFields sets the title and the due date of the task id; a nil dueDate clears it. It fails with TagNotFound when there is no such task.

func (*Store) UserByID

func (s *Store) UserByID(ctx context.Context, id uint64) (User, error)

UserByID returns the user with the given ID. It fails with TagNotFound when there is none.

func (*Store) UserByUsername

func (s *Store) UserByUsername(ctx context.Context, username string) (User, error)

UserByUsername returns the user with the given username, which the caller has already lower-cased. It fails with TagNotFound when there is none.

func (*Store) UserIDsWithSSHCode added in v1.2.0

func (s *Store) UserIDsWithSSHCode(ctx context.Context) (map[uint64]bool, error)

UserIDsWithSSHCode returns the IDs of the users who turned on the SSH code at login.

func (*Store) UserSettingsOf added in v1.2.0

func (s *Store) UserSettingsOf(ctx context.Context, userID uint64) (UserSettings, error)

UserSettingsOf returns the settings of the user, or the defaults when the user has saved none. It does not check that the user exists.

func (*Store) UsersByIDs

func (s *Store) UsersByIDs(ctx context.Context, ids []uint64) ([]User, error)

UsersByIDs returns the users with these IDs, in no particular order; an ID that is no user is left out.

func (*Store) UsersByPrefix added in v1.1.0

func (s *Store) UsersByPrefix(ctx context.Context, prefix string, limit int) ([]User, error)

UsersByPrefix returns the users who are not disabled and whose username or display name starts with prefix, in any case, ordered by username, at most limit of them. An empty prefix matches every user. The case is ignored by the lower() of the database: SQLite folds only ASCII letters, PostgreSQL what its locale says.

func (*Store) UsersByUsernames

func (s *Store) UsersByUsernames(ctx context.Context, usernames []string) ([]User, error)

UsersByUsernames returns the users with these usernames, which the caller has already lower-cased, in no particular order; a username that is no user is left out.

func (*Store) VacuumInto added in v1.2.0

func (s *Store) VacuumInto(ctx context.Context, path string) error

VacuumInto writes a consistent copy of the SQLite database to path with VACUUM INTO. It reads from one snapshot and, in WAL mode, does not stop the writers of the server meanwhile. path must not exist or must be an empty file. On PostgreSQL it fails: the database is saved with pg_dump.

type Tag

type Tag struct {
	ID        uint64
	CreatedAt time.Time
	Name      string `gorm:"not null;uniqueIndex:uq_tags_name"`
}

Tag is a label on posts. Its name is normalized by the application: lower case, without a leading "#".

type Task

type Task struct {
	ID        uint64
	CreatedAt time.Time
	RoomID    uint64 `gorm:"not null;index:idx_tasks_board,priority:1"`
	PostID    uint64 `gorm:"not null;index:idx_tasks_post_id"`
	ColumnID  uint64 `gorm:"not null;index:idx_tasks_board,priority:2"`
	// Position orders the cards of a column from top to bottom.
	Position int    `gorm:"not null;index:idx_tasks_board,priority:3"`
	Title    string `gorm:"not null"`
	// DueDate is the day the task is due, as midnight UTC of that day; only
	// the date counts. Nil when the task has no due date.
	DueDate *time.Time

	// Relations: declared so that GORM creates the foreign keys.
	Room   *Room        `gorm:"foreignKey:RoomID;constraint:OnDelete:CASCADE"`
	Post   *Post        `gorm:"foreignKey:PostID;constraint:OnDelete:CASCADE"`
	Column *BoardColumn `gorm:"foreignKey:ColumnID;constraint:OnDelete:CASCADE"`
}

Task is a card of the board, written in the editor of a post or comment (D17). Deleting its column deletes it; the application refuses to delete a column that still has cards.

type TaskAssignee

type TaskAssignee struct {
	ID        uint64
	CreatedAt time.Time
	TaskID    uint64 `gorm:"not null;uniqueIndex:uq_task_assignees_task_user,priority:1"`
	UserID    uint64 `gorm:"not null;uniqueIndex:uq_task_assignees_task_user,priority:2;index:idx_task_assignees_user_id"`

	// Relations: declared so that GORM creates the foreign keys.
	Task *Task `gorm:"foreignKey:TaskID;constraint:OnDelete:CASCADE"`
	User *User `gorm:"foreignKey:UserID;constraint:OnDelete:RESTRICT"`
}

TaskAssignee assigns a task to a user.

type TaskAssigneeRow

type TaskAssigneeRow struct {
	// TaskID is the task.
	TaskID uint64
	// UserID is the assigned user.
	UserID uint64
	// Username is the username of the user.
	Username string
	// DisplayName is the display name of the user.
	DisplayName string
}

TaskAssigneeRow is a user assigned to a task.

type TaskRow

type TaskRow struct {
	// ID, RoomID, PostID, ColumnID, Position, Title and DueDate are the fields
	// of the task.
	ID       uint64
	RoomID   uint64
	PostID   uint64
	ColumnID uint64
	Position int
	Title    string
	DueDate  *time.Time
	// ColumnName is the name of the column of the task.
	ColumnName string
	// ColumnLast is true when the column is the last of the board.
	ColumnLast bool
	// RootID is the top-level post of the thread of the task's post: the post
	// itself when it is top-level.
	RootID uint64
	// Assignees are the assigned users, in the order they were assigned.
	Assignees []TaskAssigneeRow `gorm:"-"`
}

TaskRow is a task with what a view of it needs.

type Template

type Template struct {
	// contains filtered or unexported fields
}

Template is the image of an empty database whose schema is up to date. Making the schema (GORM's AutoMigrate, the raw migrations) costs tens of milliseconds, which adds up in a test suite that opens a store per test: NewTemplate pays it once and Open then gives each caller a copy of the file to open, without migrating. It is for tests (see package storetest); the program opens its database with Open. A Template is read-only after NewTemplate, so it is safe for concurrent use.

func NewTemplate

func NewTemplate(ctx context.Context) (*Template, error)

NewTemplate migrates a scratch database in a temporary directory, with the models and migrations of Open, and keeps the bytes of the file. The directory is removed before it returns. It fails with the tags of Open when the migration fails, with TemplateDirFailed when the directory cannot be made and with TemplateReadFailed when the file cannot be read.

func (*Template) Open

func (t *Template) Open(ctx context.Context, path string, clk clock.Clock, logger *slog.Logger) (*Store, error)

Open writes a copy of the template to the file path, which must not be in use, and opens it like Open does, but without migrating: the copy is current. The time of every row comes from clk. A nil logger discards the log. It fails with TemplateWriteFailed when the file cannot be written and with the tags of Open when the copy cannot be opened.

type Theme added in v1.2.0

type Theme string

Theme is the look a user chose (SPEC §7.14, D57).

const (
	// ThemeSystem follows the setting of the user's device; it is the default.
	ThemeSystem Theme = "system"
	// ThemeLight is the light look.
	ThemeLight Theme = "light"
	// ThemeDark is the dark look.
	ThemeDark Theme = "dark"
)

type User

type User struct {
	ID        uint64
	CreatedAt time.Time
	// Username is unique and stored in lower case (the database refuses
	// anything else).
	Username    string `gorm:"not null;uniqueIndex:uq_users_username;check:chk_users_username_lower,username = lower(username)"`
	DisplayName string `gorm:"not null"`
	// PasswordHash is the argon2id hash in the PHC string format.
	PasswordHash string `gorm:"not null"`
	Role         Role   `gorm:"not null;check:chk_users_role,role IN ('admin','member')"`
	// DisabledAt is when an admin disabled the user; nil for an active user.
	DisabledAt *time.Time
	// AvatarKey is the key of the user's avatar in the avatar store (a PNG of
	// 256x256 pixels); empty when the user has none (SPEC §7.14). A new avatar
	// gets a new key, which is what makes its address new.
	AvatarKey string `gorm:"not null;default:''"`
}

User is a person who can log in. Users are never deleted: an admin disables them, so every foreign key to a user restricts its deletion.

type UserSettings added in v1.2.0

type UserSettings struct {
	ID        uint64
	CreatedAt time.Time
	// UserID is the user the settings belong to. It is unique.
	UserID uint64 `gorm:"not null;uniqueIndex:uq_user_settings_user_id"`
	// Theme is the look the user chose.
	Theme Theme `gorm:"not null;check:chk_user_settings_theme,theme IN ('system','light','dark')"`
	// Sound is true when the user wants a sound for what is new (default true).
	Sound bool `gorm:"not null"`
	// BrowserNotifications is true when the user wants notifications of the
	// browser (default false).
	BrowserNotifications bool `gorm:"not null"`
	// Notify is what rings the sound and shows a browser notification: all,
	// mentions (the default) or nothing. The bell is not affected.
	Notify NotifyLevel `gorm:"not null;default:mentions;check:chk_user_settings_notify,notify IN ('all','mentions','nothing')"`
	// SoundName is which sound plays (default purr).
	SoundName SoundName `gorm:"not null;default:purr;check:chk_user_settings_sound_name,sound_name IN ('purr','chirp','bell','meow')"`
	// Replies says which comments notify the user (default following).
	Replies RepliesMode `gorm:"not null;default:following;check:chk_user_settings_replies,replies IN ('following','direct')"`
	// KeywordsJSON is the list of the mention keywords as JSON text (default
	// "[]"); use Keywords and SetKeywords.
	KeywordsJSON string `gorm:"column:keywords;not null;default:[]"`
	// GroupMentionsOff is true when the user turned off @room, @all and @here
	// (default false). It is stored inverted because GORM replaces a false
	// value by the column default when it is true; use GroupMentions.
	GroupMentionsOff bool `gorm:"not null;default:false"`
	// SSHCodeRequired is true when the user turned on "Ask for an SSH code
	// when I log in" (SPEC §7.16, default false). Only SetSSHCodeRequired
	// writes it: SaveUserSettings leaves it alone.
	SSHCodeRequired bool `gorm:"column:ssh_code_required;not null;default:false"`

	// Relation: declared so that GORM creates the foreign key.
	User *User `gorm:"foreignKey:UserID;constraint:OnDelete:RESTRICT"`
}

UserSettings holds the preferences of one user (SPEC D49), which follow the user to every browser and client. A user has no row until they save a setting; UserSettingsOf then returns the defaults.

func DefaultUserSettings added in v1.2.0

func DefaultUserSettings(userID uint64) UserSettings

DefaultUserSettings returns the settings of a user who saved none: the theme System, the sound on (Purr), the browser notifications off, notify about mentions and replies in followed threads.

func (UserSettings) GroupMentions added in v1.2.0

func (u UserSettings) GroupMentions() bool

GroupMentions reports whether @room, @all and @here reach the user (default true).

func (UserSettings) Keywords added in v1.2.0

func (u UserSettings) Keywords() []string

Keywords returns the mention keywords of the user, in the order they were saved. A damaged list is no keywords.

func (*UserSettings) SetGroupMentions added in v1.2.0

func (u *UserSettings) SetGroupMentions(on bool)

SetGroupMentions turns the group mentions on or off.

func (*UserSettings) SetKeywords added in v1.2.0

func (u *UserSettings) SetKeywords(keywords []string)

SetKeywords sets the mention keywords. The caller has checked them.

type Visibility

type Visibility string

Visibility says who sees a room (SPEC §7.2).

const (
	// VisibilityVisible is a room that every user sees and reads (D26).
	VisibilityVisible Visibility = "visible"
	// VisibilityPrivate is a room that only its members see.
	VisibilityPrivate Visibility = "private"
)

Directories

Path Synopsis
Package storetest opens throw-away stores for tests.
Package storetest opens throw-away stores for tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL