newTestDatabase creates a new temporary test database. When a test database connection is returned, it will have created a new database and initialized it with tables from a reference database.
(base *sql.DB, dbUser, dbPassword, dbName, dbHost string)
| 97 | // database connection is returned, it will have created a new database and |
| 98 | // initialized it with tables from a reference database. |
| 99 | func newTestDatabase(base *sql.DB, dbUser, dbPassword, dbName, dbHost string) (*sql.DB, func() error, error) { |
| 100 | var err error |
| 101 | var baseName = dbName |
| 102 | |
| 103 | if baseName == "" { |
| 104 | row := base.QueryRow("SELECT DATABASE()") |
| 105 | err := row.Scan(&baseName) |
| 106 | if err != nil { |
| 107 | return nil, nil, err |
| 108 | } |
| 109 | } |
| 110 | tUUID, _ := uuid.NewV4() |
| 111 | suffix := strings.Replace(tUUID.String(), "-", "_", -1) |
| 112 | newDBName := baseName + suffix |
| 113 | _, err = base.Exec("CREATE DATABASE " + newDBName) |
| 114 | if err != nil { |
| 115 | return nil, nil, err |
| 116 | } |
| 117 | newDB, err := initMySQL(dbUser, dbPassword, newDBName, dbHost) |
| 118 | if err != nil { |
| 119 | return nil, nil, err |
| 120 | } |
| 121 | |
| 122 | rows, err := base.Query("SHOW TABLES IN " + baseName) |
| 123 | if err != nil { |
| 124 | return nil, nil, err |
| 125 | } |
| 126 | for rows.Next() { |
| 127 | var tableName string |
| 128 | if err := rows.Scan(&tableName); err != nil { |
| 129 | return nil, nil, err |
| 130 | } |
| 131 | query := fmt.Sprintf("CREATE TABLE %s LIKE %s.%s", tableName, baseName, tableName) |
| 132 | if _, err := newDB.Exec(query); err != nil { |
| 133 | return nil, nil, err |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | cleanup := func() error { |
| 138 | if closeErr := newDB.Close(); closeErr != nil { |
| 139 | fmt.Println(closeErr) |
| 140 | } |
| 141 | |
| 142 | _, err = base.Exec("DROP DATABASE " + newDBName) |
| 143 | return err |
| 144 | } |
| 145 | return newDB, cleanup, nil |
| 146 | } |
| 147 | |
| 148 | func countRows(t *testing.T, ctx context.Context, db *sql.DB, count int, query string, args ...interface{}) { |
| 149 | var returned int |
no test coverage detected