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 } 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 } 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 } return nil } func (s *storagePostgres) Close() { s.db.Close() }