2021-04-22 13:36:18 +00:00
|
|
|
package transport
|
2020-01-13 19:17:30 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2021-06-16 20:19:45 +00:00
|
|
|
"fmt"
|
2020-01-13 19:17:30 +00:00
|
|
|
)
|
|
|
|
|
2021-06-16 20:19:45 +00:00
|
|
|
type SqlitePersistence struct {
|
|
|
|
db *sql.DB
|
|
|
|
tableName string
|
2020-01-13 19:17:30 +00:00
|
|
|
}
|
|
|
|
|
2021-06-16 20:19:45 +00:00
|
|
|
func newSQLitePersistence(db *sql.DB, tableName string) *SqlitePersistence {
|
|
|
|
return &SqlitePersistence{db: db, tableName: tableName}
|
2020-01-13 19:17:30 +00:00
|
|
|
}
|
|
|
|
|
2021-06-16 20:19:45 +00:00
|
|
|
func (s *SqlitePersistence) Add(chatID string, key []byte) error {
|
2022-03-28 10:10:40 +00:00
|
|
|
// tableName controlled by us
|
|
|
|
statement := fmt.Sprintf("INSERT INTO %s(chat_id, key) VALUES(?, ?)", s.tableName) // nolint:gosec
|
2020-01-13 19:17:30 +00:00
|
|
|
stmt, err := s.db.Prepare(statement)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer stmt.Close()
|
|
|
|
|
|
|
|
_, err = stmt.Exec(chatID, key)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-06-16 20:19:45 +00:00
|
|
|
func (s *SqlitePersistence) All() (map[string][]byte, error) {
|
2020-01-13 19:17:30 +00:00
|
|
|
keys := make(map[string][]byte)
|
|
|
|
|
2022-03-28 10:10:40 +00:00
|
|
|
// tableName controlled by us
|
|
|
|
statement := fmt.Sprintf("SELECT chat_id, key FROM %s", s.tableName) // nolint: gosec
|
2020-01-13 19:17:30 +00:00
|
|
|
|
|
|
|
stmt, err := s.db.Prepare(statement)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer stmt.Close()
|
|
|
|
|
|
|
|
rows, err := stmt.Query()
|
|
|
|
if err != nil && err != sql.ErrNoRows {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-05-14 10:51:32 +00:00
|
|
|
defer rows.Close()
|
2020-01-13 19:17:30 +00:00
|
|
|
|
|
|
|
for rows.Next() {
|
|
|
|
var (
|
|
|
|
chatID string
|
|
|
|
key []byte
|
|
|
|
)
|
|
|
|
|
|
|
|
err := rows.Scan(&chatID, &key)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
keys[chatID] = key
|
|
|
|
}
|
|
|
|
|
|
|
|
return keys, nil
|
|
|
|
}
|