1 /*
2  * (C) Copyright 2001-2015 Diomidis Spinellis
3  *
4  * This file is part of CScout.
5  *
6  * CScout is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * CScout is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with CScout.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  *
20  * Portable SQL database abstraction
21  *
22  */
23 
24 #include <cstring>
25 #include <iostream>
26 
27 #include "cpp.h"
28 #include "sql.h"
29 
30 // An instance of the database interface
31 Sql *Sql::instance;
32 
33 // Return SQL equivalent of character c
34 const char *
escape(char c)35 Sql::escape(char c)
36 {
37 	static char str[2];
38 
39 	switch (c) {
40 	case '\'': return "''";
41 	default:
42 		str[0] = c;
43 		return str;
44 	}
45 }
46 
47 const char *
escape(char c)48 Hsqldb::escape(char c)
49 {
50 	static char str[2];
51 
52 	switch (c) {
53 	case '\'': return "''";
54 	case '\n': return "\\u0000a";
55 	case '\r': return "\\u0000d";
56 	default:
57 		str[0] = c;
58 		return str;
59 	}
60 }
61 
62 string
escape(string s)63 Sql::escape(string s)
64 {
65 	string r;
66 
67 	for (string::const_iterator i = s.begin(); i != s.end(); i++)
68 		r += escape(*i);
69 	return r;
70 }
71 
72 bool
setEngine(const char * dbengine)73 Sql::setEngine(const char *dbengine)
74 {
75 	if (strcmp(dbengine, "mysql") == 0)
76 		instance = new Mysql();
77 	else if (strcmp(dbengine, "hsqldb") == 0)
78 		instance = new Hsqldb();
79 	else if (strcmp(dbengine, "postgres") == 0)
80 		instance = new Postgres();
81 	else {
82 		cerr << "Unknown database engine " << dbengine << "\n";
83 		cerr << "Supported database engine types are: mysql postgres hsqldb\n";
84 		return false;
85 	}
86 	return true;
87 }
88