2023-08-11 11:28:45 +00:00
|
|
|
package helpers
|
2022-03-23 18:47:00 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
|
2023-08-11 11:28:45 +00:00
|
|
|
"github.com/status-im/status-go/common/dbsetup"
|
2022-03-23 18:47:00 +00:00
|
|
|
"github.com/status-im/status-go/protocol/sqlite"
|
|
|
|
)
|
|
|
|
|
2023-08-11 11:28:45 +00:00
|
|
|
const kdfIterationsNumberForTests = 1
|
2022-09-27 20:27:20 +00:00
|
|
|
|
2022-03-23 18:47:00 +00:00
|
|
|
// SetupTestSQLDB creates a temporary sqlite database file, initialises and then returns with a teardown func
|
2023-08-11 11:28:45 +00:00
|
|
|
func SetupTestSQLDB(dbInit dbsetup.DatabaseInitializer, prefix string) (*sql.DB, func() error, error) {
|
2022-03-23 18:47:00 +00:00
|
|
|
tmpfile, err := ioutil.TempFile("", prefix)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
2023-08-11 11:28:45 +00:00
|
|
|
|
|
|
|
db, err := dbInit.Initialize(tmpfile.Name(), "password", kdfIterationsNumberForTests)
|
2022-03-23 18:47:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return db, func() error {
|
|
|
|
err := db.Close()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return os.Remove(tmpfile.Name())
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2023-08-11 11:28:45 +00:00
|
|
|
func SetupTestMemorySQLDB(dbInit dbsetup.DatabaseInitializer) (*sql.DB, error) {
|
|
|
|
db, err := dbInit.Initialize(sqlite.InMemoryPath, "password", kdfIterationsNumberForTests)
|
2022-03-23 18:47:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return db, nil
|
|
|
|
}
|
2023-05-19 15:31:45 +00:00
|
|
|
|
|
|
|
func ColumnExists(db *sql.DB, tableName string, columnName string) (bool, error) {
|
|
|
|
rows, err := db.Query("PRAGMA table_info(" + tableName + ")")
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
|
|
|
|
var cid int
|
|
|
|
var name string
|
|
|
|
var dataType string
|
|
|
|
var notNull bool
|
|
|
|
var dFLTValue sql.NullString
|
|
|
|
var pk int
|
|
|
|
|
|
|
|
for rows.Next() {
|
|
|
|
err := rows.Scan(&cid, &name, &dataType, ¬Null, &dFLTValue, &pk)
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
if name == columnName {
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if rows.Err() != nil {
|
|
|
|
return false, rows.Err()
|
|
|
|
}
|
|
|
|
|
|
|
|
return false, nil
|
|
|
|
}
|