github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/db/telegram_chat.go (about) 1 // This file is part of the Smart Home 2 // Program complex distribution https://github.com/e154/smart-home 3 // Copyright (C) 2016-2023, Filippov Alex 4 // 5 // This library is free software: you can redistribute it and/or 6 // modify it under the terms of the GNU Lesser General Public 7 // License as published by the Free Software Foundation; either 8 // version 3 of the License, or (at your option) any later version. 9 // 10 // This library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 // Library General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public 16 // License along with this library. If not, see 17 // <https://www.gnu.org/licenses/>. 18 19 package db 20 21 import ( 22 "context" 23 "fmt" 24 "time" 25 26 "github.com/e154/smart-home/common/apperr" 27 28 "github.com/e154/smart-home/common" 29 "github.com/pkg/errors" 30 "gorm.io/gorm" 31 ) 32 33 // TelegramChats ... 34 type TelegramChats struct { 35 Db *gorm.DB 36 } 37 38 // TelegramChat ... 39 type TelegramChat struct { 40 EntityId common.EntityId 41 ChatId int64 42 Username string 43 CreatedAt time.Time `gorm:"<-:create"` 44 } 45 46 // TableName ... 47 func (d *TelegramChat) TableName() string { 48 return "telegram_chats" 49 } 50 51 // Add ... 52 func (n TelegramChats) Add(ctx context.Context, ch TelegramChat) (err error) { 53 if err = n.Db.WithContext(ctx).Create(&ch).Error; err != nil { 54 err = errors.Wrap(apperr.ErrChatAdd, err.Error()) 55 } 56 return 57 } 58 59 // Delete ... 60 func (n TelegramChats) Delete(ctx context.Context, entityId common.EntityId, chatId int64) (err error) { 61 err = n.Db.WithContext(ctx).Delete(&TelegramChat{}, "entity_id = ? and chat_id = ?", entityId, chatId).Error 62 if err != nil { 63 err = errors.Wrap(apperr.ErrChatDelete, err.Error()) 64 } 65 return 66 } 67 68 // List ... 69 func (n *TelegramChats) List(ctx context.Context, limit, offset int, orderBy, sort string, entityId common.EntityId) (list []TelegramChat, total int64, err error) { 70 71 q := n.Db.WithContext(ctx).Model(&TelegramChat{}). 72 Where("entity_id = ?", entityId) 73 74 if err = q.Count(&total).Error; err != nil { 75 err = errors.Wrap(apperr.ErrChatList, err.Error()) 76 return 77 } 78 79 q = q. 80 Limit(limit). 81 Offset(offset) 82 83 if sort != "" && orderBy != "" { 84 q = q. 85 Order(fmt.Sprintf("%s %s", sort, orderBy)) 86 } 87 88 list = make([]TelegramChat, 0) 89 if err = q.Find(&list).Error; err != nil { 90 err = errors.Wrap(apperr.ErrChatList, err.Error()) 91 } 92 return 93 }