File: resetdb.cpp

package info (click to toggle)
mysql%2B%2B 3.0.9-1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 11,228 kB
  • ctags: 9,647
  • sloc: cpp: 33,154; sh: 3,098; perl: 778; makefile: 700
file content (215 lines) | stat: -rw-r--r-- 7,252 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/***********************************************************************
 resetdb.cpp - (Re)initializes the example database, mysql_cpp_data.
	You must run this at least once before running most of the other
	examples, and it is helpful sometimes to run it again, as some of
	the examples modify the table in this database.

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by
 MySQL AB, and (c) 2004-2008 by Educational Technology Resources, Inc.
 Others may also hold copyrights on code in this file.  See the CREDITS
 file in the top directory of the distribution for details.

 This file is part of MySQL++.

 MySQL++ is free software; you can redistribute it and/or modify it
 under the terms of the GNU Lesser General Public License as published
 by the Free Software Foundation; either version 2.1 of the License, or
 (at your option) any later version.

 MySQL++ is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "cmdline.h"
#include "printdata.h"

#include <mysql++.h>

#include <iostream>
#include <cstdio>

using namespace std;


// Pull in the sample database name from the cmdline module.
extern const char* kpcSampleDatabase;


// Convert a packed version number in the format used within MySQL++
// to a printable string.
static string
version_str(int packed)
{
	char buf[9];
	snprintf(buf, sizeof(buf), "%d.%d.%d",
			(packed & 0xFF0000) >> 16,
			(packed & 0x00FF00) >> 8,
			(packed & 0x0000FF));
	return buf;
}


int
main(int argc, char *argv[])
{
	// Ensure that we're not mixing library and header file versions.
	// This is really easy to do if you have MySQL++ on your system and
	// are trying to build a new version, and run the examples directly
	// instead of through exrun.
	if (mysqlpp::get_library_version() != MYSQLPP_HEADER_VERSION) {
		cerr << "Version mismatch: library is v" <<
				version_str(mysqlpp::get_library_version()) <<
				", headers are v" <<
				version_str(MYSQLPP_HEADER_VERSION) <<
				".  Are you running this" << endl <<
				"with exrun?  See README.examples." << endl;
		return 1;
	}
	
	// Connect to database server
	const char *server = 0, *user = 0, *pass = "";
	mysqlpp::Connection con;
	try {
		if (parse_command_line(argc, argv, 0, &server, &user, &pass)) {
			extern bool dtest_mode;
			if (dtest_mode) {
				cout << "Connecting to database server..." << endl;
			}
			else {
				cout << "Connecting to '" << 
						(user ? user : "USERNAME") << "'@'" <<
						(server ? server : "localhost") << "', with" <<
						(pass[0] ? "" : "out") << " password..." << endl;
			}
			con.connect(0, server, user, pass);
		}
		else {
			return 1;		// command line parsing failed
		}
	}
	catch (exception& er) {
		cerr << "Connection failed: " << er.what() << endl;
		return 1;
	}
	
	// Create new sample database, or re-create it.  We suppress
	// exceptions, because it's not an error if DB doesn't yet exist.
	bool new_db = false;
	{
		mysqlpp::NoExceptions ne(con);
		mysqlpp::Query query = con.query();
		if (con.select_db(kpcSampleDatabase)) {
			// Toss old tables, ignoring errors because it would just
			// mean the table doesn't exist, which doesn't matter.
			cout << "Dropping existing sample data tables..." << endl;
			query.exec("drop table stock");
			query.exec("drop table images");
			query.exec("drop table deadlock_test1");
			query.exec("drop table deadlock_test2");
		}
		else {
			// Database doesn't exist yet, so create and select it.
			if (con.create_db(kpcSampleDatabase) &&
					con.select_db(kpcSampleDatabase)) {
				new_db = true;
			}
			else {
				cerr << "Error creating DB: " << con.error() << endl;
				return 1;
			}
		}
	}

	// Create sample data table within sample database.
	try {
		// Send the query to create the stock table and execute it.
		cout << "Creating stock table..." << endl;
		mysqlpp::Query query = con.query();
		query << 
				"CREATE TABLE stock (" <<
				"  item CHAR(30) NOT NULL, " <<
				"  num BIGINT NOT NULL, " <<
				"  weight DOUBLE NOT NULL, " <<
				"  price DECIMAL(6,2) NOT NULL, " <<
				"  sdate DATE NOT NULL, " <<
				"  description MEDIUMTEXT NULL) " <<
				"ENGINE = InnoDB " <<
				"CHARACTER SET utf8 COLLATE utf8_general_ci";
		query.execute();

		// Set up the template query to insert the data.  The parse()
		// call tells the query object that this is a template and
		// not a literal query string.
		query << "insert into %6:table values " <<
				"(%0q, %1q, %2, %3, %4q, %5q:desc)";
		query.parse();

		// Set a default for template query parameters "table" and "desc".
		query.template_defaults["table"] = "stock";
		query.template_defaults["desc"] = mysqlpp::null;

		// Notice that we don't give a sixth parameter in these calls,
		// so the default value of "stock" is used.  Also notice that
		// the first row is a UTF-8 encoded Unicode string!  All you
		// have to do to store Unicode data in recent versions of MySQL
		// is use UTF-8 encoding.
		cout << "Populating stock table..." << flush;
		query.execute("Nürnberger Brats", 97, 1.5, 8.79, "2005-03-10");
		query.execute("Pickle Relish", 87, 1.5, 1.75, "1998-09-04");
		query.execute("Hot Mustard", 73, .95, .97, "1998-05-25",
				"good American yellow mustard, not that European stuff");
		query.execute("Hotdog Buns", 65, 1.1, 1.1, "1998-04-23");

		// Test that above did what we wanted.
		cout << "inserted " << con.count_rows("stock") << " rows." << endl;

		// Now create empty images table, for testing BLOB and auto-
		// increment column features.
		cout << "Creating empty images table..." << endl;
		query.reset();		// forget template query info
		query << 
				"CREATE TABLE images (" <<
				"  id INT UNSIGNED AUTO_INCREMENT, " <<
				"  data BLOB, " <<
				"  PRIMARY KEY (id)" <<
				")";
		query.execute();

		// Create the tables used by examples/deadlock.cpp
		cout << "Creating deadlock testing tables..." << endl;
		query.execute("CREATE TABLE deadlock_test1 (x INT) ENGINE=innodb");
		query.execute("CREATE TABLE deadlock_test2 (x INT) ENGINE=innodb");
		query.execute("INSERT INTO deadlock_test1 VALUES (1);");
		query.execute("INSERT INTO deadlock_test2 VALUES (2);");

		// Report success
		cout << (new_db ? "Created" : "Reinitialized") <<
				" sample database successfully." << endl;
	}
	catch (const mysqlpp::BadQuery& er) {
		// Handle any query errors
		cerr << endl << "Query error: " << er.what() << endl;
		return 1;
	}
	catch (const mysqlpp::BadConversion& er) {
		// Handle bad conversions
		cerr << endl << "Conversion error: " << er.what() << endl <<
				"\tretrieved data size: " << er.retrieved <<
				", actual size: " << er.actual_size << endl;
		return 1;
	}
	catch (const mysqlpp::Exception& er) {
		// Catch-all for any other MySQL++ exceptions
		cerr << endl << "Error: " << er.what() << endl;
		return 1;
	}

	return 0;
}