package test_common

import (
	"database/sql"
	"github.com/stretchr/testify/require"
	"testing"
)

var dbType string
var testDB TestDB

func init() {
	dbType, testDB = ProcessDBTestFlags()
}

func TestMySQL(t *testing.T) {

	if dbType != "mysql" {
		return
	}

	mySQLTestDB := testDB.(*MySQLTestDB)

	db, _, err := mySQLTestDB.SetupDB(t)
	require.Nil(t, err)
	require.NotNil(t, db)

	_, err = db.Exec("create table steve (c1 int, c2 int)")
	require.Nil(t, err)

	exists, err := mySQLTestDB.TableExists("steve")
	require.True(t, exists)

	mySQLTestDB.CleanupDB()

	// Validate that the database is gone
	db, err = sql.Open("mysql", MysqlCreds+"@/")
	require.Nil(t, err)

	rows, err := db.Query("SHOW DATABASES LIKE '" + mySQLTestDB.dbName + "'")
	require.Nil(t, err)

	// We should have no rows
	require.False(t, rows.Next())
}

func TestSQLLite(t *testing.T) {

	if dbType != "sqlite" {
		return
	}

	sqliteTestDB := testDB.(*SqliteTestDB)

	db, _, err := sqliteTestDB.SetupDB(t)
	require.Nil(t, err)
	require.NotNil(t, db)

	// sqlite file does not get created until the first table
	_, err = db.Exec("create table steve (c1 int, c2 int)")
	require.Nil(t, err)

	exists, err := sqliteTestDB.TableExists("steve")
	require.True(t, exists)

	sqliteTestDB.CleanupDB()
}

func TestPostgres(t *testing.T) {

	if dbType != "postgres" {
		return
	}

	postgresTestDb := testDB.(*PostgresTestDB)

	db, _, err := postgresTestDb.SetupDB(t)
	require.Nil(t, err)
	require.NotNil(t, db)

	// Try creating a table
	_, err = db.Exec("create table steve (c1 int, c2 int)")
	require.Nil(t, err)

	exists, err := postgresTestDb.TableExists("steve")
	require.True(t, exists)

	//postgresTestDb.CleanupDB()
}
