db

package
v0.0.0-...-2970e9b Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2021 License: AGPL-3.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const DBVersion = 14

DBVersion is the current database version

View Source
const EmbedColour = 0xd14171

EmbedColour is the embed colour used throughout the bot

Variables

View Source
var (
	ErrorAlreadyBlacklisted = errors.New("channel is already blacklisted")
	ErrorNotBlacklisted     = errors.New("channel is not blacklisted")
)

Errors for setting the blacklist

View Source
var (
	ErrMoreThanOneRow = errors.New("more than one row returned")
	ErrTooManyForms   = errors.New("too many forms given")
	ErrNoForms        = errors.New("no forms given")
)

Errors ...

View Source
var (
	ErrInvalidToken = errors.New("invalid token")
	ErrTokenExpired = errors.New("token has expired")
)

Errors regarding tokens

View Source
var DBVersions []string = []string{
	`alter table public.terms add column flags integer not null default 0;
    update public.info set schema_version = 2;`,

	`alter table public.terms drop column searchtext;
    alter table public.terms add column searchtext tsvector generated always as (
        setweight(to_tsvector('english', "name"), 'A') ||
        setweight(to_tsvector('english', "description"), 'B') ||
        setweight(to_tsvector('english', "source"), 'C') ||
        setweight(array_to_tsvector("aliases"), 'A')
    ) stored;
    update public.info set schema_version = 3;`,

	`alter table public.terms add column content_warnings text not null default '';
    update public.info set schema_version = 4;`,

	`create index term_names_alphabetical on public.terms (name, id);
    update public.info set schema_version = 5;`,

	`alter table public.terms add column last_modified timestamp;
    update public.terms set last_modified = created where last_modified is null;
    alter table public.terms alter column last_modified set default (current_timestamp at time zone 'utc');
    alter table public.terms alter column last_modified set not null;
    update public.info set schema_version = 6;`,

	`create table if not exists admin_tokens (
        user_id     text        primary key,
        token       text        not null,
        expires     timestamp   not null default (now() + interval '30 days')::timestamp
    );
    update public.info set schema_version = 7;`,

	`alter table public.terms add column note text not null default '';
    update public.info set schema_version = 8;`,

	`alter table public.explanations add column as_command boolean not null default false;
    update public.info set schema_version = 9;`,

	`alter table public.terms add column aliases_string text not null default '';
    
    alter table public.terms drop column searchtext;
    alter table public.terms add column searchtext tsvector generated always as (
        setweight(to_tsvector('english', "name"), 'A') ||
        setweight(to_tsvector('english', "description"), 'B') ||
        setweight(to_tsvector('english', "source"), 'C') ||
        setweight(to_tsvector('english', "aliases_string"), 'A')
    ) stored;

    update public.terms set aliases_string = array_to_string(aliases, ', ');

    update public.info set schema_version = 10;`,

	`create table if not exists errors (
        id      uuid        primary key,
        command text        not null,
        user_id bigint      not null,
        channel bigint      not null,
        error   text        not null,
        time    timestamp   not null default (current_timestamp at time zone 'utc')
    );
    
    update public.info set schema_version = 11;`,

	`alter table public.terms add column image_url text not null default '';
    
    update public.info set schema_version = 12;`,

	`create table if not exists pronouns (
        id          serial  primary key,
        subjective  text    not null default '',
        objective   text    not null default '',
        poss_det    text    not null default '',
        poss_pro    text    not null default '',
        reflexive   text    not null default '',

        unique (subjective, objective, poss_det, poss_pro, reflexive)
    );
    
    update public.info set schema_version = 13;`,

	`alter table public.terms add column tags text[] not null default array[]::text[];
    
    update public.info set schema_version = 14;`,
}

DBVersions is a slice of schemas for every database version

View Source
var (
	ErrorNoRowsAffected = errors.New("no rows affected")
)

Errors related to database operations

Functions

func AddCount

func AddCount() uint64

AddCount adds one to the term fetch count

func GenerateToken

func GenerateToken() string

GenerateToken generates a 64-character token

func GetCount

func GetCount() uint64

GetCount ...

func IsOurProblem

func IsOurProblem(e error) bool

IsOurProblem checks if an error is "our problem", as in, should be in the logs and reported to Sentry. Will be expanded eventually once we get more insight into what type of errors we get.

Types

type Category

type Category struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

Category is a single category

type Db

type Db struct {
	Pool       *pgxpool.Pool
	Sugar      *zap.SugaredLogger
	GuildCache *ttlcache.Cache

	Config *structs.BotConfig
	// contains filtered or unexported fields
}

Db ...

func Init

func Init(url string, sugar *zap.SugaredLogger) (db *Db, err error)

Init ...

func (*Db) AddAdmin

func (db *Db) AddAdmin(id string) (err error)

AddAdmin adds an admin to the database

func (*Db) AddCategory

func (db *Db) AddCategory(name string) (id int, err error)

AddCategory ...

func (*Db) AddExplanation

func (db *Db) AddExplanation(e *Explanation) (ex *Explanation, err error)

AddExplanation adds an explanation to the database

func (*Db) AddPronoun

func (db *Db) AddPronoun(p PronounSet) (id int, err error)

AddPronoun adds a pronoun set, returning the ID

func (*Db) AddTerm

func (db *Db) AddTerm(t *Term) (*Term, error)

AddTerm adds a term to the database

func (*Db) AddToBlacklist

func (db *Db) AddToBlacklist(guildID string, channelIDs []string) (err error)

AddToBlacklist adds the given channelID to the blacklist for guildID

func (*Db) CaptureError

func (db *Db) CaptureError(ctx *bcr.Context, e error) *sentry.EventID

CaptureError captures an error with additional context

func (*Db) CategoryFromID

func (db *Db) CategoryFromID(id int) (c *Category)

CategoryFromID ...

func (*Db) CategoryID

func (db *Db) CategoryID(s string) (id int, err error)

CategoryID gets the ID from a category name

func (*Db) CreateServerIfNotExists

func (db *Db) CreateServerIfNotExists(guildID string) (exists bool, err error)

CreateServerIfNotExists returns true if the server exists

func (*Db) CtxInBlacklist

func (db *Db) CtxInBlacklist(ctx *bcr.Context) bool

CtxInBlacklist is a wrapper around IsBlacklisted for bcr

func (*Db) DeleteServer

func (db *Db) DeleteServer(guildID string) (err error)

DeleteServer deletes a server's database entry

func (*Db) Error

func (db *Db) Error(id string) (e *Error, err error)

Error ...

func (*Db) GetAdmins

func (db *Db) GetAdmins() (admins []string, err error)

GetAdmins gets the current admins as a slice of strings

func (*Db) GetAllExplanations

func (db *Db) GetAllExplanations() (e []*Explanation, err error)

GetAllExplanations ...

func (*Db) GetBlacklist

func (db *Db) GetBlacklist(guildID string) (b []string, err error)

GetBlacklist returns the channel blacklist for guildID

func (*Db) GetCategories

func (db *Db) GetCategories() (c []*Category, err error)

GetCategories ...

func (*Db) GetCategoryTerms

func (db *Db) GetCategoryTerms(id int, mask TermFlag) (terms []*Term, err error)

GetCategoryTerms gets terms by category

func (*Db) GetCmdExplanations

func (db *Db) GetCmdExplanations() (e []*Explanation, err error)

GetCmdExplanations ...

func (*Db) GetExplanation

func (db *Db) GetExplanation(s string) (e *Explanation, err error)

GetExplanation ...

func (*Db) GetOrCreateToken

func (db *Db) GetOrCreateToken(userID string) (token string, err error)

GetOrCreateToken gets or creates a token for the given user

func (*Db) GetPronoun

func (db *Db) GetPronoun(forms ...string) (sets []*PronounSet, err error)

GetPronoun gets a pronoun from the database gods this function is shit but idc, if it works it works

func (*Db) GetTerm

func (db *Db) GetTerm(id int) (t *Term, err error)

GetTerm gets a term by ID

func (*Db) GetTerms

func (db *Db) GetTerms(mask TermFlag) (terms []*Term, err error)

GetTerms gets all terms not blocked by the given mask

func (*Db) InternalError

func (db *Db) InternalError(ctx *bcr.Context, e error) error

InternalError sends an error message and logs the error to the database

func (*Db) IsBlacklisted

func (db *Db) IsBlacklisted(guildID, channelID string) (b bool)

IsBlacklisted returns true if a channel is blacklisted

func (*Db) Pronouns

func (db *Db) Pronouns() (p []*PronounSet, err error)

Pronouns ...

func (*Db) RandomTerm

func (db *Db) RandomTerm() (t *Term, err error)

RandomTerm gets a random term from the database

func (*Db) RandomTermCategory

func (db *Db) RandomTermCategory(id int) (t *Term, err error)

RandomTermCategory gets a random term from the database from the specified category

func (*Db) RemoveFromBlacklist

func (db *Db) RemoveFromBlacklist(guildID, channelID string) (err error)

RemoveFromBlacklist removes the given channelID from the blacklist for guildID

func (*Db) RemoveTerm

func (db *Db) RemoveTerm(id int) (err error)

RemoveTerm removes a term from the database

func (*Db) ResetToken

func (db *Db) ResetToken(userID string) (token string, err error)

ResetToken ...

func (*Db) Search

func (db *Db) Search(input string, limit int) (terms []*Term, err error)

Search searches the database for terms

func (*Db) SearchCat

func (db *Db) SearchCat(input string, cat, limit int, showHidden bool) (terms []*Term, err error)

SearchCat searches for terms from a single category

func (*Db) SetAsCommand

func (db *Db) SetAsCommand(id int, b bool) (err error)

SetAsCommand ...

func (*Db) SetCW

func (db *Db) SetCW(id int, text string) (err error)

SetCW sets the content warning for a term

func (*Db) SetFlags

func (db *Db) SetFlags(id int, flags TermFlag) (err error)

SetFlags sets the flags for a term

func (*Db) SetNote

func (db *Db) SetNote(id int, note string) (err error)

SetNote updates the note for a term

func (*Db) SetSentry

func (db *Db) SetSentry(hub *sentry.Hub)

SetSentry ...

func (*Db) TagTerms

func (db *Db) TagTerms(tag string) (t []*Term, err error)

TagTerms ...

func (*Db) Tags

func (db *Db) Tags() (s []string, err error)

Tags gets all tags from the database

func (*Db) TermCount

func (db *Db) TermCount() (count int)

TermCount ...

func (*Db) TermsSince

func (db *Db) TermsSince(d time.Time) (t []*Term, err error)

TermsSince returns all terms added since the specified date

func (*Db) UntaggedTerms

func (db *Db) UntaggedTerms() (t []*Term, err error)

UntaggedTerms ...

func (*Db) UpdateAliases

func (db *Db) UpdateAliases(id int, aliases []string) (err error)

UpdateAliases updates the aliases for a term

func (*Db) UpdateDesc

func (db *Db) UpdateDesc(id int, desc string) (err error)

UpdateDesc updates the description for a term

func (*Db) UpdateImage

func (db *Db) UpdateImage(id int, img string) (err error)

UpdateImage updates the title for a term

func (*Db) UpdateSource

func (db *Db) UpdateSource(id int, source string) (err error)

UpdateSource updates the source for a term

func (*Db) UpdateTags

func (db *Db) UpdateTags(id int, tags []string) (err error)

UpdateTags updates the tags for a term

func (*Db) UpdateTitle

func (db *Db) UpdateTitle(id int, title string) (err error)

UpdateTitle updates the title for a term

func (*Db) ValidateToken

func (db *Db) ValidateToken(token string) (t bool)

ValidateToken checks if a token is valid and not expired

type Error

type Error struct {
	ID      uuid.UUID
	Command string
	UserID  discord.UserID
	Channel discord.ChannelID
	Error   string
	Time    time.Time
}

Error ...

type Explanation

type Explanation struct {
	ID          int       `json:"id"`
	Name        string    `json:"name"`
	Aliases     []string  `json:"aliases"`
	Description string    `json:"description"`
	Created     time.Time `json:"created"`

	AsCommand bool `json:"-"`
}

Explanation is a single explanation

type PronounSet

type PronounSet struct {
	ID         int    `json:"id"`
	Subjective string `json:"subjective"`
	Objective  string `json:"objective"`
	PossDet    string `json:"possessive_determiner"`
	PossPro    string `json:"possessive_pronoun"`
	Reflexive  string `json:"reflexive"`
}

PronounSet is a single set of pronouns

func (PronounSet) String

func (p PronounSet) String() string

type Term

type Term struct {
	ID              int       `json:"id"`
	Category        int       `json:"category_id"`
	CategoryName    string    `json:"category"`
	Name            string    `json:"name"`
	Aliases         []string  `json:"aliases"`
	Description     string    `json:"description"`
	Note            string    `json:"note,omitempty"`
	Source          string    `json:"source"`
	Created         time.Time `json:"created"`
	LastModified    time.Time `json:"last_modified"`
	Tags            []string  `json:"tags,omitempty"`
	ContentWarnings string    `json:"content_warnings,omitempty"`
	ImageURL        string    `json:"image_url,omitempty"`

	Flags TermFlag `json:"flags"`

	// Rank is only populated with db.Search()
	Rank float64 `json:"rank,omitempty"`
	// Headline is only populated with db.Search()
	Headline string `json:"headline,omitempty"`
}

Term holds info on a single term

func (*Term) RandomHidden

func (t *Term) RandomHidden() bool

RandomHidden returns true if the term is hidden from the random command

func (*Term) SearchHidden

func (t *Term) SearchHidden() bool

SearchHidden returns true if the term is hidden from search results

func (*Term) TermEmbed

func (t *Term) TermEmbed(baseURL string) *discord.Embed

TermEmbed creates a Discord embed from a term object

func (*Term) Warning

func (t *Term) Warning() bool

Warning returns true if the term has a warning on its term card

type TermFlag

type TermFlag int

TermFlag ...

const (
	FlagSearchHidden TermFlag = 1 << iota
	FlagRandomHidden
	FlagShowWarning
	FlagListHidden
)

Constants for term flags

Jump to

Keyboard shortcuts

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