1 // Copyright (C) 2015-2021 Internet Systems Consortium, Inc. ("ISC")
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 #include <config.h>
8 #include <string>
9 #include <mysql.h>
10 #include <mysql/testutils/mysql_schema.h>
11 #include <mysql/mysql_connection.h>
12 #include <exceptions/exceptions.h>
13
14 #include <fstream>
15 #include <iostream>
16 #include <sstream>
17 #include <stdlib.h>
18
19 using namespace std;
20
21 namespace isc {
22 namespace db {
23 namespace test {
24
25 const char* MYSQL_VALID_TYPE = "type=mysql";
26
27 string
validMySQLConnectionString()28 validMySQLConnectionString() {
29 return (connectionString(MYSQL_VALID_TYPE, VALID_NAME, VALID_HOST,
30 VALID_USER, VALID_PASSWORD));
31 }
32
destroyMySQLSchema(bool show_err,bool force)33 void destroyMySQLSchema(bool show_err, bool force) {
34 // If force is true or wipeMySQLData() fails, destroy the schema.
35 if (force || (!softWipeEnabled()) || wipeMySQLData(show_err)) {
36 runMySQLScript(DATABASE_SCRIPTS_DIR, "mysql/dhcpdb_drop.mysql", show_err);
37 }
38 }
39
createMySQLSchema(bool show_err,bool force)40 void createMySQLSchema(bool show_err, bool force) {
41 // If force is true or wipeMySQLData() fails, recreate the schema.
42 if (force || (!softWipeEnabled()) || wipeMySQLData(show_err)) {
43 destroyMySQLSchema(show_err, true);
44 runMySQLScript(DATABASE_SCRIPTS_DIR, "mysql/dhcpdb_create.mysql", show_err);
45 }
46 }
47
wipeMySQLData(bool show_err)48 bool wipeMySQLData(bool show_err) {
49 std::ostringstream cmd;
50 cmd << "sh " << DATABASE_SCRIPTS_DIR << "/";
51
52 std::ostringstream version;
53 version << MYSQL_SCHEMA_VERSION_MAJOR << "." << MYSQL_SCHEMA_VERSION_MINOR;
54
55 cmd << "mysql/wipe_data.sh " << version.str()
56 << " -N -B --user=keatest --password=keatest keatest";
57 if (!show_err) {
58 cmd << " 2>/dev/null ";
59 }
60
61 int retval = ::system(cmd.str().c_str());
62 if (retval) {
63 std::cerr << "wipeMySQLData failed:[" << cmd.str() << "]" << std::endl;
64 }
65
66 return(retval);
67 }
68
runMySQLScript(const std::string & path,const std::string & script_name,bool show_err)69 void runMySQLScript(const std::string& path, const std::string& script_name,
70 bool show_err) {
71 std::ostringstream cmd;
72 cmd << "mysql -N -B --user=keatest --password=keatest keatest";
73 if (!show_err) {
74 cmd << " 2>/dev/null ";
75 }
76
77 if (!path.empty()) {
78 cmd << " < " << path << "/";
79 }
80
81 cmd << script_name;
82
83 int retval = ::system(cmd.str().c_str());
84 if (retval) {
85 std::cerr << "runMySQLSchema failed: " << cmd.str() << std::endl;
86 isc_throw(Unexpected, "runMySQLSchema failed: " << cmd.str());
87 }
88 }
89
90 } // namespace test
91 } // namespace db
92 } // namespace isc
93