93 lines
2.0 KiB
Go
93 lines
2.0 KiB
Go
package models
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/uptrace/bun"
|
|
)
|
|
|
|
type Group struct {
|
|
bun.BaseModel `bun:"table:groups"`
|
|
UserID int64
|
|
GroupID int64 `bun:",pk,autoincrement"`
|
|
Name string `bun:"name,type:text" json:"name" yaml:"name"`
|
|
TelegramChatID int64 `bun:"telegram_chat_id,type:bigint" json:"telegram_chat_id" yaml:"telegram_chat_id"`
|
|
Users Users `bun:"m2m:group_to_users,join:Group=User"`
|
|
}
|
|
|
|
type GroupToUser struct {
|
|
GroupID int64 `bun:",pk"`
|
|
Group *Group `bun:"rel:belongs-to,join:group_id=user_id"`
|
|
UserID int64 `bun:",pk"`
|
|
User *User `bun:"rel:belongs-to,join:user_id=group_id"`
|
|
}
|
|
|
|
func NewGroup(j []byte) (*Group, error) {
|
|
g := &Group{}
|
|
return g, nil
|
|
}
|
|
|
|
// Add .
|
|
func (g *Group) Add(db *bun.DB, ctx context.Context) error {
|
|
_, err := db.NewInsert().Model(g).Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Update .
|
|
func (g *Group) Update(db *bun.DB, ctx context.Context) error {
|
|
_, err := db.NewUpdate().Model(g).WherePK().Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Remove .
|
|
func (g *Group) Remove(db *bun.DB, ctx context.Context) error {
|
|
_, err := db.NewDelete().Model(g).WherePK().Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UserAdd .
|
|
func (g *Group) UserAdd(db *bun.DB, ctx context.Context, u int64) error {
|
|
_, err := db.NewInsert().Model(g).Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UserList .
|
|
func (g *Group) UserList(db *bun.DB, ctx context.Context) (Users, error) {
|
|
var users Users
|
|
_, err := db.NewSelect().Model(&users).ScanAndCount(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return users, nil
|
|
}
|
|
|
|
// UserRemove .
|
|
func (g *Group) UserRemove(db *bun.DB, ctx context.Context, u int) error {
|
|
_, err := db.NewInsert().Model(g).Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func GroupExists(db *bun.DB, ctx context.Context, tid int64) bool {
|
|
exists, err := db.NewSelect().Model((*Group)(nil)).Where("telegram_chat_id = ?", tid).Exists(ctx)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
return exists
|
|
}
|