store

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: BSD-3-Clause Imports: 31 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 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.

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 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"
)

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.
	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')"`
	// 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 or room. 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 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 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
	// 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
	// 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
	// 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"
)

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 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"`

	// 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 an "@username" in the body of a post. The application rebuilds a post's mentions when the post is edited.

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"`
	// 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"`
}

Message is a message of a conversation. It is plain text.

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 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.
	Body string
	// 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
}

MessageRow is a message with the user who wrote it.

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')"`
	// 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"`

	// 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"
)

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
	// 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
	// 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 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 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 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 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
	// 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 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
	// 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
}

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) 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) 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) 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) 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) 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) 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 is not counted. 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) 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) 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 and sets its ID and CreatedAt.

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) 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 and sets its ID. It fails with TagConflict when the user is a member of the room already.

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) 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. 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) 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) 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) 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) 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) 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) 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) 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. 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) 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) 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) MentionedUserIDs

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

MentionedUserIDs returns the IDs of the users the post mentions, in the order the mentions were saved.

func (*Store) MentionedUsernamesOfPosts

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

MentionedUsernamesOfPosts returns the usernames mentioned in each of the posts, 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) 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) 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) 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) 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) 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) 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) ReplacePostMentions

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

ReplacePostMentions makes userIDs the mentions of the post: the mentions of other users are deleted and the missing ones are added; those that stay are not touched. The IDs 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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.

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) 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.

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 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
}

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 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