butler/internal/modules/storage/postgres/postgres.go

60 lines
1.3 KiB
Go
Raw Normal View History

2023-08-13 14:06:28 +00:00
package postgres
import (
"context"
"database/sql"
_ "github.com/lib/pq"
"git.3crabs.ru/VLADIMIR/butler/internal/modules/storage"
)
type storagePostgres struct {
db *sql.DB
}
func NewStoragePostgres(urlConnect string) (storage.IStorage, error) {
db, err := sql.Open("postgres", urlConnect)
if err != nil {
return nil, err
}
return &storagePostgres{db: db}, nil
}
2023-08-13 17:17:42 +00:00
func (s *storagePostgres) GetAllUsersByChatID(ctx context.Context, chatID string) ([]*storage.User, error) {
rows, err := s.db.Query(`select chat_id, user_id from users where chat_id = $1`, chatID)
if err != nil {
return nil, err
}
defer rows.Close()
var users []*storage.User
for rows.Next() {
user := &storage.User{}
err := rows.Scan(&user.ChatID, &user.UserID)
if err != nil {
return nil, err
}
users = append(users, user)
}
err = rows.Err()
if err != nil {
return nil, err
}
return users, nil
2023-08-13 14:06:28 +00:00
}
2023-08-13 17:17:42 +00:00
func (s *storagePostgres) UpsertUser(ctx context.Context, user *storage.User) error {
stmt, err := s.db.Prepare(`insert into users (chat_id, user_id) select $1, $2 where not exists (select * FROM users WHERE chat_id = $1 and user_id = $2);`)
if err != nil {
return err
}
if _, err := stmt.Exec(user.ChatID, user.UserID); err != nil {
return err
}
2023-08-13 14:06:28 +00:00
return nil
}
func (s *storagePostgres) Close() {
s.db.Close()
}