harness-drone/store/shared/db/dbtest/dbtest.go

68 lines
1.9 KiB
Go
Raw Normal View History

2019-03-06 07:47:55 +00:00
// Copyright 2019 Drone IO, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2019-02-19 23:56:41 +00:00
package dbtest
import (
"os"
"strconv"
2019-02-19 23:56:41 +00:00
"github.com/drone/drone/store/shared/db"
// blank imports are used to load database drivers
// for unit tests. Only unit tests should be importing
// this package.
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
)
// Connect opens a new test database connection.
func Connect() (*db.DB, error) {
var (
driver = "sqlite3"
config = ":memory:?_foreign_keys=1"
maxConnections = 0
2019-02-19 23:56:41 +00:00
)
2019-04-22 23:14:17 +00:00
if os.Getenv("DRONE_DATABASE_DRIVER") != "" {
driver = os.Getenv("DRONE_DATABASE_DRIVER")
config = os.Getenv("DRONE_DATABASE_DATASOURCE")
maxConnectionsString := os.Getenv("DRONE_DATABASE_MAX_CONNECTIONS")
maxConnections, _ = strconv.Atoi(maxConnectionsString)
2019-02-19 23:56:41 +00:00
}
return db.Connect(driver, config, maxConnections)
2019-02-19 23:56:41 +00:00
}
// Reset resets the database state.
func Reset(d *db.DB) {
d.Lock(func(tx db.Execer, _ db.Binder) error {
tx.Exec("DELETE FROM cron")
tx.Exec("DELETE FROM logs")
tx.Exec("DELETE FROM steps")
tx.Exec("DELETE FROM stages")
2020-03-13 17:27:07 +00:00
tx.Exec("DELETE FROM latest")
2019-02-19 23:56:41 +00:00
tx.Exec("DELETE FROM builds")
tx.Exec("DELETE FROM perms")
tx.Exec("DELETE FROM repos")
tx.Exec("DELETE FROM users")
2019-04-22 23:14:17 +00:00
tx.Exec("DELETE FROM orgsecrets")
2019-02-19 23:56:41 +00:00
return nil
})
}
// Disconnect closes the database connection.
func Disconnect(d *db.DB) error {
return d.Close()
}